/** * Bot platform protocols for the PraisonAI TypeScript SDK. * * Python parity: praisonaiagents/bots/protocols.py * * Defines the interfaces messaging-bot implementations satisfy so agents can * talk through Telegram, Discord, Slack, etc. Concrete adapters live outside * the core SDK; this module carries only the contracts, the capability * descriptors and the small pure helpers (health evaluation, callback payload * store) the Python core ships. * * Python dataclasses are ported as classes that take a single options object * whose defaults match the Python field defaults. `toDict()` keeps Python's * snake_case keys so the serialized form is wire-compatible with the Python * gateway; `fromDict()` accepts both snake_case and camelCase keys. * * NOTE: `BotUser`, `BotChannel`, `BotMessage` and `BotProtocol` are NOT * re-declared here because `src/gateway/index.ts` already exports interfaces * under those names. The Python-shaped structural contracts are exposed as * `BotUserProtocol`, `BotChannelProtocol` and `BotMessageProtocol` instead. */ /** * Declares what features a bot channel supports. * Python parity: `ChannelCapabilities` (TypedDict, total=False). */ export interface ChannelCapabilities { /** Whether the channel supports editing messages in place */ liveEdit?: boolean; /** Whether the channel supports adding reactions to messages */ reactions?: boolean; /** Whether the channel supports typing indicators */ typing?: boolean; /** Maximum message length (0 = unlimited) */ textLimit?: number; /** Minimum seconds between edits (for throttling) */ editRateLimit?: number; /** Minimum seconds between reactions */ reactionRateLimit?: number; } /** * Run status states for progress feedback. * Python parity: `RunStatus`. */ export declare enum RunStatus { QUEUED = "queued", THINKING = "thinking", TOOL = "tool", DONE = "done", ERROR = "error" } /** * Constructor options for {@link PlatformCapabilities}. Every field mirrors a * Python dataclass field and its default. */ export interface PlatformCapabilitiesOptions { maxMessageLength?: number; lengthUnit?: string; supportsEdit?: boolean; supportsTyping?: boolean; markdownDialect?: string; needsRateLimit?: boolean; editIntervalMs?: number; maxFilesPerMessage?: number; maxFileSizeMb?: number; supportedFileTypes?: string[]; acceptsWebhooks?: boolean; verifiesWebhookSignature?: boolean; reconcilesUnknownSend?: boolean; supportsIdempotencyToken?: boolean; supportsMedia?: boolean; supportsThreads?: boolean; } /** * Platform-specific capabilities descriptor for bot adapters. * * Python parity: `PlatformCapabilities` (frozen dataclass) in * praisonaiagents/bots/protocols.py. Instances are frozen after construction. * * @example * ```typescript * const caps = new PlatformCapabilities({ supportsEdit: true, maxMessageLength: 2000 }); * caps.toDict().max_message_length; // 2000 * ``` */ export declare class PlatformCapabilities { /** Maximum message length in the platform's unit */ readonly maxMessageLength: number; /** Unit for message length ("codepoints" or "utf16") */ readonly lengthUnit: string; /** Whether the platform supports in-place message edits (for streaming) */ readonly supportsEdit: boolean; /** Whether the platform supports typing indicators */ readonly supportsTyping: boolean; /** Markdown flavor the platform uses (e.g. "markdown", "telegram_markdown_v2") */ readonly markdownDialect: string; /** Whether the platform needs rate limiting */ readonly needsRateLimit: boolean; /** Minimum milliseconds between message edits (for streaming) */ readonly editIntervalMs: number; /** Maximum number of file attachments per message */ readonly maxFilesPerMessage: number; /** Maximum file size in megabytes */ readonly maxFileSizeMb: number; /** List of supported file extensions/mime types */ readonly supportedFileTypes: string[]; /** Whether the platform delivers inbound messages via webhook */ readonly acceptsWebhooks: boolean; /** Whether the adapter verifies inbound webhook authenticity */ readonly verifiesWebhookSignature: boolean; /** Whether the adapter can confirm whether a prior send attempt landed */ readonly reconcilesUnknownSend: boolean; /** Whether the transport accepts a provider-level idempotency token */ readonly supportsIdempotencyToken: boolean; /** Whether the adapter can attach/upload media files on outbound sends */ readonly supportsMedia: boolean; /** Whether the adapter can open a new thread/topic under a chat */ readonly supportsThreads: boolean; constructor(options?: PlatformCapabilitiesOptions); /** Convert to a dictionary with Python's snake_case keys. */ toDict(): Record; /** Create from a dictionary (snake_case or camelCase keys). */ static fromDict(data: Record): PlatformCapabilities; } /** Options for {@link ChannelField} (everything after the required `name`). */ export interface ChannelFieldOptions { required?: boolean; secret?: boolean; prompt?: string; env?: string | null; } /** * A single configuration field a channel plugin declares about itself. * Python parity: `ChannelField` (frozen dataclass). */ export declare class ChannelField { /** Config key name (as it appears under `channels.`) */ readonly name: string; /** Whether the field must be provided */ readonly required: boolean; /** Whether the value is sensitive (masked in prompts/logs) */ readonly secret: boolean; /** Human-friendly prompt shown by the onboarding wizard */ readonly prompt: string; /** Optional environment-variable name used as a fallback source */ readonly env: string | null; constructor(name: string, options?: ChannelFieldOptions); /** Convert to a dictionary with Python's snake_case keys. */ toDict(): Record; } /** * Optional self-description a channel adapter may expose. * Python parity: `ChannelDescriptor` (Protocol). `setup` is optional; consumers * probe for it rather than relying on structural typing. */ export interface ChannelDescriptor { configFields: ChannelField[]; systemPromptHint: string; /** Optional interactive setup returning collected config/env values. */ setup?(io: unknown): Record; } /** Keyword arguments of {@link WebhookVerifierProtocol.verify}. */ export interface WebhookVerifyOptions { /** Inbound request headers (case-insensitive mapping) */ headers: Record; /** The exact raw request body bytes (pre-parse) */ rawBody: Uint8Array | string; } /** * Protocol for verifying inbound webhook authenticity. * Python parity: `WebhookVerifierProtocol` (`verify(*, headers, raw_body)`). */ export interface WebhookVerifierProtocol { verify(options: WebhookVerifyOptions): boolean; } /** * Raised when a channel adapter cannot receive the gateway runtime seams. * Python parity: `GatewayAdapterContractError(TypeError)`. */ export declare class GatewayAdapterContractError extends TypeError { constructor(message?: string); } /** Constructor options for {@link GatewayRuntimeSeams}. */ export interface GatewayRuntimeSeamsOptions { identityResolver?: unknown; identityCanonicalizer?: unknown; deliveryRouter?: unknown; admissionGate?: unknown; turnLockMap?: unknown; } /** * The gateway reliability seams handed to a channel adapter at build time. * Python parity: `GatewayRuntimeSeams` (dataclass, every seam defaults to None). * A seam left `null` means the gateway has nothing to inject for it. */ export declare class GatewayRuntimeSeams { identityResolver: unknown; identityCanonicalizer: unknown; deliveryRouter: unknown; admissionGate: unknown; turnLockMap: unknown; constructor(options?: GatewayRuntimeSeamsOptions); } /** * Contract for channel adapters that accept the gateway runtime seams. * Python parity: `SupportsGatewayRuntime` (Protocol). */ export interface SupportsGatewayRuntime { /** Wire the gateway runtime seams into this adapter (only non-null seams apply). */ attachGatewayRuntime(runtime: GatewayRuntimeSeams): void; } /** * Types of bot messages. * Python parity: `MessageType(str, Enum)`. */ export declare enum MessageType { TEXT = "text", IMAGE = "image", AUDIO = "audio", VIDEO = "video", FILE = "file", LOCATION = "location", STICKER = "sticker", COMMAND = "command", CALLBACK = "callback", REACTION = "reaction", REPLY = "reply", EDIT = "edit", DELETE = "delete" } /** * Structural contract for a bot user. * Python parity: `BotUserProtocol` (fields of the `BotUser` dataclass). */ export interface BotUserProtocol { userId: string; username?: string | null; displayName?: string | null; isBot: boolean; metadata?: Record; } /** * Structural contract for a bot channel. * Python parity: `BotChannelProtocol` (fields of the `BotChannel` dataclass). */ export interface BotChannelProtocol { channelId: string; name?: string | null; /** dm, group, channel, thread */ channelType: string; metadata?: Record; } /** * Structural contract for a bot message. * Python parity: `BotMessageProtocol` (fields of the `BotMessage` dataclass). */ export interface BotMessageProtocol { messageId: string; content: string | Record; messageType?: MessageType | string; sender: BotUserProtocol | null; channel: BotChannelProtocol | null; timestamp?: number; replyTo?: string | null; threadId?: string | null; attachments?: Array>; metadata?: Record; } /** Constructor options for {@link ProbeResult}; `ok` is required. */ export interface ProbeResultOptions { ok: boolean; platform?: string; elapsedMs?: number; botUsername?: string | null; error?: string | null; details?: Record; } /** * Result of a channel connectivity probe. * Python parity: `ProbeResult` (dataclass). */ export declare class ProbeResult { ok: boolean; platform: string; elapsedMs: number; botUsername: string | null; error: string | null; details: Record; constructor(options: ProbeResultOptions); /** Convert to a dictionary with Python's snake_case keys. */ toDict(): Record; } /** * Reasons for channel health status. * Python parity: `HealthReason(Enum)`. */ export declare enum HealthReason { HEALTHY = "healthy", NOT_RUNNING = "not-running", DISCONNECTED = "disconnected", STALE_SOCKET = "stale-socket", STUCK = "stuck", BUSY = "busy", STARTUP_GRACE = "startup-grace", ERROR = "error" } /** The {@link HealthReason} values Python's `HealthReason.is_recoverable` reports True for. */ export declare const RECOVERABLE_HEALTH_REASONS: ReadonlySet; /** * Whether a health reason indicates a recoverable state. * Python parity: `HealthReason.is_recoverable` (TS enums cannot carry properties). */ export declare function isRecoverableHealthReason(reason: HealthReason): boolean; /** Constructor options for {@link HealthResult}; `ok` is required. */ export interface HealthResultOptions { ok: boolean; platform?: string; isRunning?: boolean; uptimeSeconds?: number | null; probe?: ProbeResult | null; sessions?: number; error?: string | null; details?: Record; reason?: HealthReason | null; lastActivity?: number | null; lastRunProgress?: number | null; activeRuns?: number; } /** * Detailed health status of a bot. * Python parity: `HealthResult` (dataclass). Timestamps are epoch seconds. */ export declare class HealthResult { ok: boolean; platform: string; isRunning: boolean; uptimeSeconds: number | null; probe: ProbeResult | null; sessions: number; error: string | null; details: Record; reason: HealthReason | null; /** Last INBOUND transport activity timestamp (epoch seconds) */ lastActivity: number | null; /** Last IN-RUN progress timestamp (epoch seconds) */ lastRunProgress: number | null; /** Number of in-flight agent turns (busy count) */ activeRuns: number; constructor(options: HealthResultOptions); /** Convert to a dictionary with Python's snake_case keys. */ toDict(): Record; } /** * Evaluate channel health and return a reason. * * Python parity: `evaluate_channel_health(health, startup_grace_seconds=60.0, * stale_after_seconds=120.0, stuck_after_seconds=900.0, current_time=None)`. * Pure function; all times are epoch seconds. * * - busy with recent inbound/in-run progress -> BUSY (never restarted); * - busy but no progress beyond `stuckAfterSeconds` -> STUCK; * - idle and inbound stale beyond `staleAfterSeconds` -> STALE_SOCKET. */ export declare function evaluateChannelHealth(health: HealthResult, startupGraceSeconds?: number, staleAfterSeconds?: number, stuckAfterSeconds?: number, currentTime?: number | null): HealthReason; /** Constructor options for {@link ChatCommandInfo}; `name` is required. */ export interface ChatCommandInfoOptions { name: string; description?: string; usage?: string | null; hidden?: boolean; } /** * Metadata for a registered chat command. * Python parity: `ChatCommandInfo` (dataclass). */ export declare class ChatCommandInfo { name: string; description: string; usage: string | null; hidden: boolean; constructor(options: ChatCommandInfoOptions); toDict(): Record; static fromDict(data: Record): ChatCommandInfo; } /** * Protocol for bots that support standardized chat commands. * Python parity: `ChatCommandProtocol`. */ export interface ChatCommandProtocol { /** Register a chat command handler (`name` without the leading slash). */ registerCommand(name: string, handler: (...args: unknown[]) => unknown, description?: string, usage?: string | null): void; /** List all registered chat commands. */ listCommands(): ChatCommandInfo[]; } /** * Protocol for channel adapters that support presentations. * Python parity: `SupportsPresentation`. The presentation and limits types are * generic because the portable presentation model is not ported yet. */ export interface SupportsPresentation { /** Channel-specific presentation limits */ readonly presentationLimits: TLimits; /** Render a presentation to a target; resolves to the message id or null. */ renderPresentation(target: string, presentation: TPresentation): Promise; /** Truncate a presentation to fit channel limits. */ truncatePresentation(presentation: TPresentation): TPresentation; } /** * Contract a channel presentation renderer implements. * Python parity: `PresentationRendererProtocol` (two static methods; in TS the * renderer is an object exposing them). */ export interface PresentationRendererProtocol { /** Return this channel's capability limits. */ getLimits(): TLimits; /** Render a presentation into a native, platform-specific payload. */ render(presentation: TPresentation): Record; } /** Constructor options for {@link EmailInbox}; `id` and `emailAddress` are required. */ export interface EmailInboxOptions { id: string; emailAddress: string; domain?: string; createdAt?: string | null; } /** * Information about an email inbox. * Python parity: `EmailInbox` (dataclass). */ export declare class EmailInbox { id: string; emailAddress: string; domain: string; createdAt: string | null; constructor(options: EmailInboxOptions); toDict(): Record; } /** * Protocol for email bots with inbox lifecycle management. * Python parity: `EmailProtocol`. */ export interface EmailProtocol { /** The bot's current email address */ readonly emailAddress: string | null; /** Create a new email inbox (`kwargs` are provider-specific extras). */ createInbox(domain?: string | null, kwargs?: Record): Promise>; /** List all inboxes accessible to this bot. */ listInboxes(): Promise>>; /** Delete an inbox; resolves true when deleted. */ deleteInbox(inboxId: string): Promise; } /** * Protocol for BotOS, the multi-platform bot orchestrator. * * Python parity: `BotOSProtocol` in praisonaiagents/bots/protocols.py. * * Hierarchy: * ``` * BotOS (multi-platform orchestrator) * └── Bot (single platform) * └── Agent / AgentTeam / AgentFlow (AI brain) * ``` */ export interface BotOSProtocol { /** Whether the orchestrator is currently running */ readonly isRunning: boolean; /** Start all registered bots concurrently. */ start(): Promise; /** Gracefully stop all running bots. */ stop(): Promise; /** Register a Bot instance for orchestration. */ addBot(bot: unknown): void; /** List platform names of all registered bots. */ listBots(): string[]; /** Remove a registered bot by platform name; true if removed. */ removeBot(platform: string): boolean; /** Get a registered bot by platform name, or null. */ getBot(platform: string): unknown | null; } /** Keyword arguments of {@link CallbackPayloadStoreProtocol.put}. */ export interface CallbackPayloadPutOptions { /** Expiry as epoch seconds */ expiresAt: number; } /** * Protocol for durable, reference-addressable interactive callback values. * Python parity: `CallbackPayloadStoreProtocol` (`put(ref, value, *, expires_at)`). */ export interface CallbackPayloadStoreProtocol { /** Persist `value` under `ref` until `expiresAt` (epoch seconds). */ put(ref: string, value: string, options: CallbackPayloadPutOptions): void; /** Return the value stored for `ref`, or null if unknown/expired. */ get(ref: string): string | null; } /** Constructor options for {@link InMemoryCallbackPayloadStore}. */ export interface InMemoryCallbackPayloadStoreOptions { maxEntries?: number; } /** * Bounded, zero-dependency in-memory {@link CallbackPayloadStoreProtocol}. * * Python parity: `InMemoryCallbackPayloadStore(*, max_entries=4096)`. Entries * are kept until `expiresAt` and the store is capped at `maxEntries` (oldest * inserted evicted first). */ export declare class InMemoryCallbackPayloadStore implements CallbackPayloadStoreProtocol { private readonly maxEntries; /** ref -> [value, expiresAt]; Map preserves insertion order for FIFO eviction. */ private readonly entries; constructor(options?: InMemoryCallbackPayloadStoreOptions); private purgeExpired; put(ref: string, value: string, options: CallbackPayloadPutOptions): void; get(ref: string): string | null; /** Number of live (not yet purged) entries. */ get size(): number; }