/** * BasePlatformAdapter: the inheritable base class for gateway channel adapters. * * Python parity: praisonaiagents/bots/base.py (plus the markdown-dialect * helpers from praisonaiagents/bots/format.py, inlined here because the base * adapter's `formatMessage` consumes them). * * A new messaging channel subclasses {@link BasePlatformAdapter}, implements * the four abstract primitives (`connect`, `disconnect`, `send`, * `getChatInfo`) and declares its {@link PlatformCapabilities}; it then * inherits chunking, retry/backoff with error classification, typing * heartbeat, formatting and graceful edit/delete fallbacks. * * @example * ```typescript * class AcmeBot extends BasePlatformAdapter { * capabilities = new PlatformCapabilities({ supportsEdit: true, maxMessageLength: 4096 }); * async connect() { return true; } * async disconnect() {} * async send(chatId, content) { * const messageId = await acmeApi.send(chatId, content); * return new SendResult({ ok: true, messageId, chatId }); * } * async getChatInfo(chatId) { return { id: chatId }; } * } * ``` */ import { PlatformCapabilities } from './protocols'; /** * Structured, machine-readable classification of why a send failed. * Python parity: `SendErrorKind(str, Enum)`. */ export declare enum SendErrorKind { /** Throttled by the platform (HTTP 429); retry after wait. */ RATE_LIMITED = "rate_limited", /** Chat/channel no longer exists (HTTP 404/410); do not retry, mark dead. */ TARGET_NOT_FOUND = "target_not_found", /** Bot was kicked/blocked or lacks rights (HTTP 403); do not retry, mark dead. */ FORBIDDEN = "forbidden", /** Bad/expired/revoked credential (HTTP 401); retrying the same token is pointless. */ AUTH_FATAL = "auth_fatal", /** Malformed payload the platform rejects (HTTP 400). */ INVALID_REQUEST = "invalid_request", /** Network blip / 5xx / timeout; safe to retry with backoff. */ TRANSIENT = "transient", /** Could not classify; treated as retryable to preserve the historical default. */ UNKNOWN = "unknown" } /** Kinds that must NOT be retried by the default delivery loop. Python parity: `_NON_RETRYABLE_KINDS`. */ export declare const NON_RETRYABLE_KINDS: ReadonlySet; /** * Derive whether a failure of `kind` should be retried. * Python parity: `_retryable_for_kind`. `null` (no classification) is retryable. */ export declare function retryableForKind(kind: SendErrorKind | null): boolean; /** * Best-effort extract an HTTP/platform status code from an error. * Python parity: `_error_status_code` (reads `status`, `status_code`, * `error_code`; the camelCase twins `statusCode`/`errorCode` are read too). */ export declare function errorStatusCode(exc: unknown): number | null; /** Classify a send error from its message when no status code is present. Python parity: `_classify_by_text`. */ export declare function classifyByText(error: string): SendErrorKind; /** * Pure, dependency-free fallback classifier for a send exception. * * Python parity: `classify_send_error(exc) -> SendResult`. Keys primarily off * the HTTP/platform status code and falls back to a small set of generic, * cross-platform substrings; anything it cannot confidently classify becomes * `UNKNOWN` (retryable). */ export declare function classifySendError(exc: unknown): SendResult; /** A chat/channel identifier as handed to an adapter (Python `Any`). */ export type ChatId = string | number; /** Message content: plain text or a structured platform payload. */ export type MessageContent = string | Record; /** Constructor options for {@link SendResult}; every field mirrors the Python dataclass default. */ export interface SendResultOptions { ok?: boolean; messageId?: string | null; chatId?: ChatId | null; messageIds?: string[]; error?: string | null; errorKind?: SendErrorKind | null; retryable?: boolean; retryAfter?: number | null; metadata?: Record; } /** * Result of a single outbound send/edit through an adapter. * Python parity: `SendResult` (dataclass) in praisonaiagents/bots/base.py. */ export declare class SendResult { /** Whether the send succeeded. */ ok: boolean; /** Platform message id of the last message sent (final chunk for chunked delivery). */ messageId: string | null; /** The chat/channel the message was delivered to. */ chatId: ChatId | null; /** All platform message ids produced (one per chunk). */ messageIds: string[]; /** Human-readable error string when `ok` is false. */ error: string | null; /** Structured classification of why the send failed. */ errorKind: SendErrorKind | null; /** Whether the failure is worth retrying (defaults true so unclassified failures still retry). */ retryable: boolean; /** Suggested seconds to wait before retrying (from a rate-limit response). */ retryAfter: number | null; /** Additional platform-specific result details. */ metadata: Record; constructor(options?: SendResultOptions); /** Convert to a plain dictionary with Python's snake_case keys. */ toDict(): Record; } /** * Split `text` into chunks of at most `maxLength` characters (UTF-16 units). * * Python parity: `_chunk_text`. Prefers paragraph, then line, then hard-split * boundaries. `maxLength <= 0` means unlimited. */ export declare function chunkText(text: string, maxLength: number): string[]; /** * Escape every Telegram MarkdownV2 special character in `text`. * Python parity: `escape_markdown_v2`. */ export declare function escapeMarkdownV2(text: string): string; /** * Convert common markdown to Slack `mrkdwn`. * Python parity: `markdown_to_slack`. */ export declare function markdownToSlack(text: string): string; /** * Reduce markdown to readable plain text (safe fallback). * Python parity: `strip_markdown`. Only paired delimiters are unwrapped so * identifiers like `svc_1` or `*.py` are never corrupted. */ export declare function stripMarkdown(text: string): string; /** * Render `text` for a platform's declared `markdownDialect`. * * Python parity: `format_for_dialect(text, dialect) -> (rendered, parse_mode)`. * Returns `[renderedText, parseMode]` where `parseMode` is the value the * transport expects (e.g. "MarkdownV2" for Telegram) or null. */ export declare function formatForDialect(text: string | null | undefined, dialect: string): [string, string | null]; /** Keyword arguments of {@link BasePlatformAdapter.connect}. */ export interface ConnectOptions { /** True when re-establishing after a drop. */ isReconnect?: boolean; } /** Keyword arguments of {@link BasePlatformAdapter.send}. */ export interface SendOptions { replyTo?: string | null; metadata?: Record | null; } /** Keyword arguments of {@link BasePlatformAdapter.deliver}. */ export interface DeliverOptions { replyTo?: string | null; metadata?: Record | null; /** Send a typing heartbeat before the first chunk (capability-gated). */ typing?: boolean; } /** * Inheritable base class for gateway platform/channel adapters. * * Python parity: `BasePlatformAdapter` in praisonaiagents/bots/base.py. * Subclasses implement the four abstract primitives and inherit the * capability-driven defaults. `retryBaseDelay` and `SendResult.retryAfter` * are in seconds, as in Python. */ export declare abstract class BasePlatformAdapter { /** Platform capabilities descriptor. Subclasses override with their own. */ capabilities: PlatformCapabilities; /** Max retry attempts for the default resilient delivery loop. */ maxRetries: number; /** Base backoff (seconds) for exponential retry when no `retryAfter`. */ retryBaseDelay: number; /** * Whether inbound supervision (auto-reconnect + health restart) should wrap * this adapter's run loop by default. */ supervisedInbound: boolean; /** Establish the platform connection; resolves true on success. */ abstract connect(options?: ConnectOptions): Promise; /** Tear down the platform connection and release resources. */ abstract disconnect(): Promise; /** * Send a single message to `chatId` (one API call, no chunking). * Chunking/retry/typing are handled by {@link deliver}. */ abstract send(chatId: ChatId, content: MessageContent, options?: SendOptions): Promise; /** Return metadata about a chat/channel (at least an `id` key). */ abstract getChatInfo(chatId: ChatId): Promise>; /** * Establish the connection and run the inbound loop until stopped. * Concrete adapters override this with their platform run loop. */ start(): Promise; /** Signal the inbound loop to stop and tear down the connection. */ stop(): Promise; /** * Map a raw, potentially-volatile platform id to a stable canonical id. * Default is the identity function. Implementations must be deterministic * and total: return the raw id unchanged when no canonical form is known. */ canonicalize(platform: string, rawUserId: string): string; /** Read a capability flag with a fallback default. Python parity: `_cap`. */ protected cap(name: string, defaultValue: T): T; /** Platform max message length (0 = unlimited). */ get maxMessageLength(): number; /** Whether the platform supports in-place message edits. */ get supportsEdit(): boolean; /** Whether the platform supports typing indicators. */ get supportsTyping(): boolean; /** Render `text` for the platform's declared `markdownDialect`. */ formatMessage(text: string): string; /** Split `text` to respect the platform max length. */ chunk(text: string): string[]; /** Send a typing indicator. Default no-op. */ sendTyping(chatId: ChatId): Promise; /** * Edit an existing message. When the platform does not support edits the * default reports `ok=false` with an `edit_not_supported` error; when it * declares `supportsEdit` but does not override this, it throws. */ editMessage(chatId: ChatId, messageId: string, content: MessageContent): Promise; /** Delete a message. Default: not supported, resolves false. */ deleteMessage(chatId: ChatId, messageId: string): Promise; /** * Map a native send exception into a classified {@link SendResult}. * Adapters override this to translate their SDK's error types; the default * delegates to {@link classifySendError}. */ classifyError(exc: unknown): SendResult; /** * Robustly deliver `content`, inheriting all shared machinery: formatting, * chunking, typing heartbeat and retry with backoff honouring `retryAfter`. * Non-text (object) content is passed straight through to `send`. */ deliver(chatId: ChatId, content: MessageContent, options?: DeliverOptions): Promise; /** * Send one chunk with retry/backoff, honouring the error taxonomy. * Python parity: `_send_with_retry`. Only `retryable` failures are retried; * a provably-permanent failure short-circuits immediately. */ protected sendWithRetry(chatId: ChatId, content: MessageContent, options?: SendOptions): Promise; /** Wait `seconds` (Python `asyncio.sleep`). Overridable for tests. */ protected sleep(seconds: number): Promise; }