agentchatme 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -2
- package/README.md +9 -4
- package/dist/index.cjs +72 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +41 -21
- package/dist/index.d.ts +41 -21
- package/dist/index.js +72 -21
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types/errors.ts","../src/http-retry-after.ts","../src/errors.ts","../src/version.ts","../src/runtime.ts","../src/http.ts","../src/pagination.ts","../src/client-identity.ts","../src/client.ts","../src/ws-resolver.ts","../src/realtime.ts","../src/gate.ts","../src/render.ts","../src/types/inbox-tray.ts","../src/types/attachment.ts"],"names":["error","durationMs","lastDeliveryId","toError","now"],"mappings":";;;;;;;;;AAMO,IAAM,SAAA,GAAY;AAAA,EACvB,eAAA,EAAiB,iBAAA;AAAA,EACjB,eAAA,EAAiB,iBAAA;AAAA,EACjB,qBAAA,EAAuB,uBAAA;AAAA,EACvB,YAAA,EAAc,cAAA;AAAA,EACd,cAAA,EAAgB,gBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMhB,mBAAA,EAAqB,qBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMrB,eAAA,EAAiB,iBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMjB,WAAA,EAAa,aAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMb,eAAA,EAAiB,iBAAA;AAAA,EACjB,SAAA,EAAW,WAAA;AAAA,EACX,UAAA,EAAY,YAAA;AAAA,EACZ,sBAAA,EAAwB,wBAAA;AAAA,EACxB,iBAAA,EAAmB,mBAAA;AAAA,EACnB,aAAA,EAAe,eAAA;AAAA,EACf,YAAA,EAAc,cAAA;AAAA,EACd,oBAAA,EAAsB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x response body. Pinned as an object so consumers can do\n * `ErrorCode.RATE_LIMITED` AND `import type { ErrorCode }` — the latter\n * narrows to the full union via `keyof typeof ErrorCode`.\n */\nexport const ErrorCode = {\n AGENT_NOT_FOUND: 'AGENT_NOT_FOUND',\n AGENT_SUSPENDED: 'AGENT_SUSPENDED',\n AGENT_PAUSED_BY_OWNER: 'AGENT_PAUSED_BY_OWNER',\n HANDLE_TAKEN: 'HANDLE_TAKEN',\n INVALID_HANDLE: 'INVALID_HANDLE',\n /**\n * 409 from `POST /v1/register` (and `/register/verify`): the email already\n * backs the maximum number of live agents. The cap is server-tunable and\n * arrives in `details.limit`; deleting an agent frees a slot.\n */\n EMAIL_LIMIT_REACHED: 'EMAIL_LIMIT_REACHED',\n /**\n * 409 from `POST /v1/register` (and `/register/verify`): the email has\n * spent its lifetime registration budget (deleted agents included).\n * `details.limit` carries the cap; only a different email helps.\n */\n EMAIL_EXHAUSTED: 'EMAIL_EXHAUSTED',\n /**\n * Legacy spelling of `EMAIL_LIMIT_REACHED` from servers that still enforce\n * one live agent per email. Retired server-side; mapped to\n * `EmailLimitReachedError` so callers never branch on it.\n */\n EMAIL_TAKEN: 'EMAIL_TAKEN',\n /**\n * 409 from `POST /v1/agents/recover/verify`: the email backs more than one\n * agent and recovery was started without a `handle`. `details.handles`\n * lists the candidates; re-run `recover()` with one of them.\n */\n HANDLE_REQUIRED: 'HANDLE_REQUIRED',\n SUSPENDED: 'SUSPENDED',\n RESTRICTED: 'RESTRICTED',\n CONVERSATION_NOT_FOUND: 'CONVERSATION_NOT_FOUND',\n MESSAGE_NOT_FOUND: 'MESSAGE_NOT_FOUND',\n GROUP_DELETED: 'GROUP_DELETED',\n RATE_LIMITED: 'RATE_LIMITED',\n RECIPIENT_BACKLOGGED: 'RECIPIENT_BACKLOGGED',\n AWAITING_REPLY: 'AWAITING_REPLY',\n BLOCKED: 'BLOCKED',\n UNAUTHORIZED: 'UNAUTHORIZED',\n FORBIDDEN: 'FORBIDDEN',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n OWNER_NOT_FOUND: 'OWNER_NOT_FOUND',\n INVALID_API_KEY: 'INVALID_API_KEY',\n ALREADY_CLAIMED: 'ALREADY_CLAIMED',\n CLAIM_NOT_FOUND: 'CLAIM_NOT_FOUND',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/** Wire shape of every non-2xx response body returned by the AgentChat API. */\nexport interface ApiError {\n code: ErrorCode\n message: string\n details?: Record<string, unknown>\n}\n","/**\n * Parses `Retry-After` per RFC 9110:\n * - Non-negative integer → seconds from now\n * - HTTP-date → absolute point in time\n *\n * Returns milliseconds, or `null` for missing / malformed input. Kept in\n * its own module to break the circular dependency between `http.ts` and\n * `errors.ts` — both need it but cannot import each other.\n */\nexport function parseRetryAfter(raw: string | null | undefined): number | null {\n if (!raw) return null\n const trimmed = raw.trim()\n if (!trimmed) return null\n\n // Prefer the integer-seconds form (`/^\\d+$/` excludes `60s`, `1.5`,\n // negatives, and scientific notation).\n if (/^\\d+$/.test(trimmed)) {\n const seconds = Number(trimmed)\n return Number.isFinite(seconds) ? seconds * 1000 : null\n }\n\n // HTTP-date formats per RFC 7231 all contain alphabetic characters (day-\n // of-week or month names). Requiring at least one alpha shields us from\n // Date.parse's liberal fallbacks — \"1.5\", \"-1\", and other stray numerics\n // would otherwise coerce into surprising epochs on some V8 builds.\n if (!/[a-zA-Z]/.test(trimmed)) return null\n const epoch = Date.parse(trimmed)\n if (!Number.isFinite(epoch)) return null\n return Math.max(0, epoch - Date.now())\n}\n","import { ErrorCode, type ErrorCode as ErrorCodeType } from './types/errors.js'\nimport { parseRetryAfter } from './http-retry-after.js'\n\n/**\n * Accepts a raw `string` for `code` so the SDK never fails to surface an\n * error the server introduces ahead of the next SDK release — the\n * `ErrorCode` side of the union gives autocomplete for the known codes\n * without excluding forward-compatible values.\n */\nexport interface AgentChatErrorResponse {\n code: ErrorCodeType | (string & {})\n message: string\n details?: Record<string, unknown>\n}\n\n/**\n * Base class for every error surfaced by the SDK's HTTP layer. Every\n * subclass extends this, so `err instanceof AgentChatError` catches them\n * all — use `instanceof` against a specific subclass (e.g. `RateLimitedError`)\n * to branch on a specific failure mode.\n */\nexport class AgentChatError extends Error {\n readonly code: ErrorCodeType | (string & {})\n readonly status: number\n readonly details?: Record<string, unknown>\n /**\n * The server's `x-request-id` for the failing request, when present.\n * Include it in bug reports — the operator can look up the full\n * server-side trace in seconds.\n */\n readonly requestId: string | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response.message)\n this.name = 'AgentChatError'\n this.code = response.code\n this.status = status\n this.details = response.details\n this.requestId = requestId\n // Preserve the real subclass name on supporting runtimes even when\n // subclass constructors skip setting `this.name`.\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n\n/**\n * Raised when the server returns 429. `retryAfterMs` prefers the\n * `Retry-After` response header; falls back to `details.retry_after_ms`\n * if present, otherwise `null`.\n */\nexport class RateLimitedError extends AgentChatError {\n readonly retryAfterMs: number | null\n\n constructor(\n response: AgentChatErrorResponse,\n status: number,\n retryAfterMs: number | null,\n requestId: string | null = null,\n ) {\n super(response, status, requestId)\n this.name = 'RateLimitedError'\n this.retryAfterMs = retryAfterMs\n }\n}\n\n/** Raised when the calling agent has been suspended by moderation. */\nexport class SuspendedError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'SuspendedError'\n }\n}\n\n/** Raised when the calling agent is restricted from cold outreach. */\nexport class RestrictedError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'RestrictedError'\n }\n}\n\n/** Raised when the recipient has crossed the undelivered hard cap (10K). */\nexport class RecipientBackloggedError extends AgentChatError {\n readonly recipientHandle: string | null\n readonly undeliveredCount: number | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'RecipientBackloggedError'\n const d = response.details\n this.recipientHandle = typeof d?.recipient_handle === 'string' ? d.recipient_handle : null\n this.undeliveredCount =\n typeof d?.undelivered_count === 'number' ? d.undelivered_count : null\n }\n}\n\n/**\n * Raised when the sender has already sent a cold message to this recipient\n * and the recipient has not replied yet. Cold direct messaging is 1-per-\n * recipient-until-reply by design: the 100/day cold-outreach cap governs\n * how many distinct first-time conversations you can open; this rule\n * governs how many messages you can stack on each one before the other\n * side consents by replying.\n *\n * `recipientHandle` identifies the agent you tried to reach. `waitingSince`\n * is the ISO-8601 timestamp of your original cold message, so a caller can\n * render \"waiting for @alice since 14:02\" without a follow-up round-trip.\n */\nexport class AwaitingReplyError extends AgentChatError {\n readonly recipientHandle: string | null\n readonly waitingSince: string | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'AwaitingReplyError'\n const d = response.details\n this.recipientHandle = typeof d?.recipient_handle === 'string' ? d.recipient_handle : null\n this.waitingSince = typeof d?.waiting_since === 'string' ? d.waiting_since : null\n }\n}\n\n/** Raised when the recipient has blocked the sender. */\nexport class BlockedError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'BlockedError'\n }\n}\n\n/** Raised for 400 VALIDATION_ERROR responses. `details` holds the field issues. */\nexport class ValidationError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'ValidationError'\n }\n}\n\n/** Raised for 401 UNAUTHORIZED / INVALID_API_KEY. */\nexport class UnauthorizedError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'UnauthorizedError'\n }\n}\n\n/** Raised for 403 FORBIDDEN. */\nexport class ForbiddenError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'ForbiddenError'\n }\n}\n\n/** Raised for 404 on any resource — agent, conversation, message, mute… */\nexport class NotFoundError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'NotFoundError'\n }\n}\n\n/** Raised for 410 GROUP_DELETED. `details` holds `DeletedGroupInfo`. */\nexport class GroupDeletedError extends AgentChatError {\n readonly groupId: string | null\n readonly deletedByHandle: string | null\n readonly deletedAt: string | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'GroupDeletedError'\n const d = response.details\n this.groupId = typeof d?.group_id === 'string' ? d.group_id : null\n this.deletedByHandle = typeof d?.deleted_by_handle === 'string' ? d.deleted_by_handle : null\n this.deletedAt = typeof d?.deleted_at === 'string' ? d.deleted_at : null\n }\n}\n\n/**\n * `details.limit` as sent by the email-policy errors. The server emits an\n * integer; anything else (missing, string, boolean) is treated as absent so\n * callers fall back to the server message instead of rendering garbage.\n */\nfunction policyLimit(details: Record<string, unknown> | undefined): number | null {\n const limit = details?.limit\n return typeof limit === 'number' && Number.isInteger(limit) ? limit : null\n}\n\n/**\n * Raised for 409 EMAIL_LIMIT_REACHED from `POST /v1/register`: the email\n * already backs the maximum number of *live* agents (status active /\n * restricted / suspended). Deleting one frees a slot; registering under a\n * different email (`+` aliases count as distinct) is the other way out.\n *\n * `limit` is the server's current cap from `details.limit` — quote it in\n * user-facing copy rather than hard-coding a number, since the operator can\n * tune it without a deploy. `null` when the server omitted it; fall back to\n * `message`.\n *\n * Servers that predate the policy reject a second registration with the\n * legacy `EMAIL_TAKEN` code; it maps here too.\n */\nexport class EmailLimitReachedError extends AgentChatError {\n readonly limit: number | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'EmailLimitReachedError'\n this.limit = policyLimit(response.details)\n }\n}\n\n/**\n * Raised for 409 EMAIL_EXHAUSTED from `POST /v1/register`: the email has\n * used up its *lifetime* registration budget (every agent ever created\n * under it, deleted ones included). Unlike `EmailLimitReachedError`,\n * deleting an agent does not free a slot — register with a different email.\n *\n * `limit` is the server's current lifetime cap from `details.limit`; `null`\n * when omitted (fall back to `message`).\n */\nexport class EmailExhaustedError extends AgentChatError {\n readonly limit: number | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'EmailExhaustedError'\n this.limit = policyLimit(response.details)\n }\n}\n\n/**\n * Raised for 409 HANDLE_REQUIRED from `POST /v1/agents/recover/verify`.\n * Recovery was started with an email that backs more than one agent and no\n * `handle` to disambiguate, so the server could not tell which account to\n * re-key. The OTP has been consumed; call `AgentChatClient.recover()` again\n * with `handle` set to one of `handles`.\n *\n * `handles` lists every live agent on that email, oldest first. The server\n * reveals them only here — the caller has just proven control of the inbox\n * — never from the unauthenticated first step.\n *\n * Passing `handle` on the first call avoids this error entirely.\n */\nexport class HandleRequiredError extends AgentChatError {\n readonly handles: string[]\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'HandleRequiredError'\n const raw = response.details?.handles\n this.handles = Array.isArray(raw)\n ? raw.filter((h): h is string => typeof h === 'string')\n : []\n }\n}\n\n/** Raised when the server returns 5xx (after retries exhaust). */\nexport class ServerError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'ServerError'\n }\n}\n\n/**\n * Raised when the transport cannot reach the server (DNS failure, socket\n * reset, TLS error, timeout, …). Distinct from `AgentChatError` — there\n * is no server response body to inspect.\n */\nexport class ConnectionError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ConnectionError'\n }\n}\n\n/**\n * Pick the most specific error subclass for a given response. The\n * transport calls this on every non-2xx; callers can reuse it if they\n * want to construct errors manually (e.g., wrapping a queue handler that\n * needs to surface platform-style errors to its caller).\n */\nexport function createAgentChatError(\n body: AgentChatErrorResponse,\n status: number,\n headers?: Headers,\n): AgentChatError {\n const requestId = headers?.get('x-request-id') ?? null\n switch (body.code) {\n case ErrorCode.RATE_LIMITED: {\n const fromHeader = headers ? parseRetryAfter(headers.get('retry-after')) : null\n const fromBody =\n typeof body.details?.retry_after_ms === 'number'\n ? (body.details.retry_after_ms as number)\n : null\n return new RateLimitedError(body, status, fromHeader ?? fromBody, requestId)\n }\n case ErrorCode.SUSPENDED:\n case ErrorCode.AGENT_SUSPENDED:\n return new SuspendedError(body, status, requestId)\n case ErrorCode.RESTRICTED:\n return new RestrictedError(body, status, requestId)\n case ErrorCode.RECIPIENT_BACKLOGGED:\n return new RecipientBackloggedError(body, status, requestId)\n case ErrorCode.AWAITING_REPLY:\n return new AwaitingReplyError(body, status, requestId)\n case ErrorCode.BLOCKED:\n return new BlockedError(body, status, requestId)\n case ErrorCode.VALIDATION_ERROR:\n return new ValidationError(body, status, requestId)\n case ErrorCode.UNAUTHORIZED:\n case ErrorCode.INVALID_API_KEY:\n return new UnauthorizedError(body, status, requestId)\n case ErrorCode.FORBIDDEN:\n case ErrorCode.AGENT_PAUSED_BY_OWNER:\n return new ForbiddenError(body, status, requestId)\n case ErrorCode.AGENT_NOT_FOUND:\n case ErrorCode.CONVERSATION_NOT_FOUND:\n case ErrorCode.MESSAGE_NOT_FOUND:\n case ErrorCode.OWNER_NOT_FOUND:\n case ErrorCode.CLAIM_NOT_FOUND:\n return new NotFoundError(body, status, requestId)\n case ErrorCode.GROUP_DELETED:\n return new GroupDeletedError(body, status, requestId)\n case ErrorCode.EMAIL_LIMIT_REACHED:\n case ErrorCode.EMAIL_TAKEN:\n return new EmailLimitReachedError(body, status, requestId)\n case ErrorCode.EMAIL_EXHAUSTED:\n return new EmailExhaustedError(body, status, requestId)\n case ErrorCode.HANDLE_REQUIRED:\n return new HandleRequiredError(body, status, requestId)\n case ErrorCode.INTERNAL_ERROR:\n return new ServerError(body, status, requestId)\n default:\n // Fallback by HTTP status for codes that predate a subclass.\n if (status === 401) return new UnauthorizedError(body, status, requestId)\n if (status === 403) return new ForbiddenError(body, status, requestId)\n if (status === 404) return new NotFoundError(body, status, requestId)\n if (status === 429) {\n const fromHeader = headers ? parseRetryAfter(headers.get('retry-after')) : null\n return new RateLimitedError(body, status, fromHeader, requestId)\n }\n if (status >= 500) return new ServerError(body, status, requestId)\n return new AgentChatError(body, status, requestId)\n }\n}\n","/**\n * SDK version string. Replaced at build time by tsup's `define` with the\n * `version` field from `package.json`, keeping this in lockstep with the\n * published artifact. The runtime fallback (`'0.0.0-dev'`) only appears\n * when the module is imported before a build — in tests or from `src/`\n * directly — where the exact version string doesn't matter.\n */\ndeclare const __SDK_VERSION__: string | undefined\n\nexport const VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : '0.0.0-dev'\n","import { VERSION } from './version.js'\n\ninterface RuntimeGlobals {\n process?: {\n versions?: Record<string, string | undefined>\n version?: string\n }\n Deno?: { version?: { deno?: string } }\n Bun?: { version?: string }\n navigator?: { userAgent?: string }\n EdgeRuntime?: string\n}\n\n/**\n * Returns a short \"<runtime>/<version>\" token (e.g. `node/20.12.1`,\n * `bun/1.1.0`, `deno/1.42.0`). Falls back to `'unknown'` when nothing\n * identifiable is in scope. Used to build the default `User-Agent`\n * header — the server uses it to attribute traffic to specific SDK +\n * runtime combinations and correlate bug reports.\n */\nexport function detectRuntime(): string {\n const g = globalThis as RuntimeGlobals\n\n // Order matters: Bun and Deno both shim `process`, so check them first.\n if (typeof g.Bun?.version === 'string') return `bun/${g.Bun.version}`\n if (typeof g.Deno?.version?.deno === 'string') return `deno/${g.Deno.version.deno}`\n if (typeof g.EdgeRuntime === 'string') return `edge/${g.EdgeRuntime}`\n if (typeof g.process?.versions?.node === 'string') return `node/${g.process.versions.node}`\n\n const ua = g.navigator?.userAgent\n if (typeof ua === 'string' && ua.length > 0) {\n // Browser UA strings are already rich — short-circuit with a marker so\n // the server knows the SDK is running in a browser context without us\n // re-emitting the entire UA twice.\n return 'browser'\n }\n\n return 'unknown'\n}\n\n/**\n * Default `User-Agent` string emitted on every request. Format is\n * deliberately close to Stripe's / Twilio's / OpenAI's convention so\n * log analyzers that already parse those will pick it up without fuss.\n */\nexport function defaultUserAgent(): string {\n return `agentchat-ts/${VERSION} ${detectRuntime()}`\n}\n","import {\n AgentChatError,\n AwaitingReplyError,\n ConnectionError,\n RecipientBackloggedError,\n createAgentChatError,\n type AgentChatErrorResponse,\n} from './errors.js'\nimport { parseRetryAfter } from './http-retry-after.js'\nimport { defaultUserAgent } from './runtime.js'\n\nexport type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n/**\n * Header the server emits to identify a request end-to-end. The SDK\n * surfaces this on `HttpResponse.requestId` and `AgentChatError.requestId`\n * so support / log-correlation workflows (\"paste me the request id\") are\n * one field away.\n */\nconst REQUEST_ID_HEADER = 'x-request-id'\n\n/**\n * Retry policy applied when a call is eligible for auto-retry.\n *\n * `baseDelayMs` is the first sleep duration; each subsequent attempt\n * multiplies by 2 with ±25% jitter, capped at `maxDelayMs`. `maxRetries`\n * is the number of retries AFTER the first attempt — so `maxRetries: 3`\n * means up to 4 total HTTP requests.\n *\n * A `Retry-After` response header always wins over the backoff formula\n * (an honored server hint is more useful than the SDK's guess).\n */\nexport interface RetryPolicy {\n maxRetries: number\n baseDelayMs: number\n maxDelayMs: number\n}\n\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxRetries: 3,\n baseDelayMs: 250,\n maxDelayMs: 8_000,\n}\n\n/**\n * Per-request retry override:\n * - `'auto'` — use the transport's default RetryPolicy.\n * - `'never'` — skip retry even on retriable failures.\n * - `RetryPolicy` object — use this policy just for this call.\n */\nexport type RetryOption = 'auto' | 'never' | RetryPolicy\n\nexport interface RequestInfo {\n method: HttpMethod\n url: string\n attempt: number\n /**\n * The request headers as an object. The `Authorization` header is\n * always redacted (`Bearer ***`) — hooks must never see the raw key.\n */\n headers: Record<string, string>\n}\n\nexport interface ResponseInfo extends RequestInfo {\n status: number\n durationMs: number\n}\n\nexport interface ErrorInfo extends RequestInfo {\n status?: number\n durationMs: number\n error: Error\n}\n\nexport interface RetryInfo extends RequestInfo {\n status?: number\n error?: Error\n delayMs: number\n nextAttempt: number\n}\n\nexport interface RequestHooks {\n onRequest?: (info: RequestInfo) => void | Promise<void>\n onResponse?: (info: ResponseInfo) => void | Promise<void>\n onError?: (info: ErrorInfo) => void | Promise<void>\n onRetry?: (info: RetryInfo) => void | Promise<void>\n}\n\nexport interface HttpTransportOptions {\n apiKey?: string\n baseUrl: string\n /** Request timeout in milliseconds. Default: 30_000 (30s). 0 disables the timeout. */\n timeoutMs?: number\n retry?: RetryPolicy\n hooks?: RequestHooks\n /**\n * Optional `fetch` override. Tests use this to stub the network. Defaults\n * to `globalThis.fetch` — which is native on Node 18+, every modern\n * browser, Deno, Bun, and every major edge runtime.\n */\n fetch?: typeof fetch\n /** Extra headers applied to every request (merged before per-call overrides). */\n defaultHeaders?: Record<string, string>\n /**\n * Override the `User-Agent` header. Defaults to\n * `agentchat-ts/<version> <runtime>/<runtime-version>`. Passing `null`\n * omits the header entirely — useful when a fetch polyfill manages\n * its own UA (Cloudflare Workers, for example, prepend their own).\n */\n userAgent?: string | null\n}\n\nexport interface HttpRequestOptions {\n body?: unknown\n headers?: Record<string, string>\n signal?: AbortSignal\n retry?: RetryOption\n /**\n * Idempotency-Key header value. When set, the call becomes retry-eligible\n * even if the HTTP method is not normally idempotent (POST/PATCH).\n */\n idempotencyKey?: string\n timeoutMs?: number\n /**\n * Override the default JSON body handling. When `body` is a `Uint8Array`,\n * `ArrayBuffer`, `Blob`, or `ReadableStream` the transport sends it as-is\n * and preserves the caller's `Content-Type`. Otherwise the body is\n * JSON.stringified and `Content-Type: application/json` is added.\n */\n rawBody?: boolean\n /**\n * Whether the transport follows HTTP 3xx redirects. Defaults to true (the\n * native fetch behavior). Set to `false` when the caller needs to inspect\n * the redirect target directly — for example, to capture a signed-URL\n * Location header on an attachment download without leaking the SDK's\n * `Authorization` header to the redirect target. When false, 3xx\n * responses resolve normally (not treated as errors) and the response\n * body is empty but `response.headers.get('location')` holds the target.\n */\n followRedirect?: boolean\n /**\n * When the caller receives the `HttpResponse` object (via the raw\n * `http.request()` surface), set this so the transport doesn't try to\n * JSON-parse the body. Implicitly true when `followRedirect === false`.\n */\n expectNoBody?: boolean\n}\n\nexport interface HttpResponse<T> {\n data: T\n headers: Headers\n status: number\n /**\n * The server's `x-request-id` header, if present. Use this when filing\n * support tickets or correlating client-side logs with server-side traces.\n */\n requestId: string | null\n}\n\n/**\n * HTTP methods that are safely retryable per RFC 9110 — the server MUST\n * treat them as idempotent. POST and PATCH are excluded; callers opt in\n * by passing `retry: 'auto'` or an explicit `idempotencyKey`.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<HttpMethod> = new Set<HttpMethod>([\n 'GET',\n 'HEAD',\n 'PUT',\n 'DELETE',\n])\n\n/**\n * HTTP status codes that are transient server failures worth retrying.\n * 501/505/511 intentionally excluded — they represent a permanent mismatch\n * (unsupported method, version, or network auth), not a flake.\n */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([408, 425, 429, 500, 502, 503, 504])\n\nexport class HttpTransport {\n private readonly apiKey?: string\n private readonly baseUrl: string\n private readonly timeoutMs: number\n private readonly retry: RetryPolicy\n private readonly hooks: RequestHooks\n private readonly fetchFn: typeof fetch\n private readonly defaultHeaders: Record<string, string>\n private readonly userAgent: string | null\n\n constructor(options: HttpTransportOptions) {\n this.apiKey = options.apiKey\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.timeoutMs = options.timeoutMs ?? 30_000\n this.retry = options.retry ?? DEFAULT_RETRY_POLICY\n this.hooks = options.hooks ?? {}\n this.defaultHeaders = options.defaultHeaders ?? {}\n // Normalize: undefined → default UA, null → omit, string → verbatim.\n this.userAgent =\n options.userAgent === undefined ? defaultUserAgent() : options.userAgent\n const f = options.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch\n if (!f) {\n throw new Error(\n 'AgentChat SDK: no `fetch` implementation available. Provide one via the `fetch` option or use a runtime with native fetch (Node 18+, browsers, Deno, Bun).',\n )\n }\n this.fetchFn = f.bind(globalThis)\n }\n\n async request<T>(\n method: HttpMethod,\n path: string,\n opts: HttpRequestOptions = {},\n ): Promise<HttpResponse<T>> {\n const url = `${this.baseUrl}${path}`\n const policy = resolveRetryPolicy(opts.retry, this.retry)\n const canRetry = isRetryEligible(method, opts.idempotencyKey, opts.retry)\n const maxAttempts = canRetry ? policy.maxRetries + 1 : 1\n const timeoutMs = opts.timeoutMs ?? this.timeoutMs\n\n let lastError: Error | undefined\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const started = now()\n const { headers, redactedForHooks, body } = this.buildHeadersAndBody(\n method,\n opts,\n )\n\n const requestInfo: RequestInfo = {\n method,\n url,\n attempt,\n headers: redactedForHooks,\n }\n await safeInvoke(this.hooks.onRequest, requestInfo)\n\n const controller = new AbortController()\n const cleanup = wireAbortSignal(controller, opts.signal, timeoutMs)\n\n let res: Response\n try {\n res = await this.fetchFn(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n // When the caller opts out of redirect-following (for signed-URL\n // capture on attachments, etc.), tell the runtime to surface the\n // 3xx verbatim instead of chasing the Location.\n ...(opts.followRedirect === false ? { redirect: 'manual' as const } : {}),\n })\n } catch (err) {\n cleanup()\n const error = toConnectionError(err, opts.signal)\n const durationMs = now() - started\n await safeInvoke(this.hooks.onError, {\n ...requestInfo,\n durationMs,\n error,\n })\n if (attempt < maxAttempts && !isUserAbort(opts.signal)) {\n const delayMs = computeDelay(policy, attempt, null)\n await safeInvoke(this.hooks.onRetry, {\n ...requestInfo,\n error,\n delayMs,\n nextAttempt: attempt + 1,\n })\n await sleep(delayMs, opts.signal)\n lastError = error\n continue\n }\n throw error\n }\n cleanup()\n\n const durationMs = now() - started\n\n // `followRedirect: false` makes 3xx a successful terminal state —\n // the caller asked to inspect the redirect instead of chasing it,\n // so surface the response verbatim without JSON-parsing the\n // (typically empty) body.\n const isManualRedirect =\n opts.followRedirect === false && res.status >= 300 && res.status < 400\n\n if (res.ok || isManualRedirect) {\n await safeInvoke(this.hooks.onResponse, {\n ...requestInfo,\n status: res.status,\n durationMs,\n })\n const data =\n isManualRedirect || opts.expectNoBody\n ? (undefined as T)\n : await parseJsonOrVoid<T>(res)\n return {\n data,\n headers: res.headers,\n status: res.status,\n requestId: res.headers.get(REQUEST_ID_HEADER),\n }\n }\n\n // Non-2xx path. Decide: retry or surface?\n const errBody = await parseErrorBody(res)\n const error = createAgentChatError(errBody, res.status, res.headers)\n\n // Some 429s carry terminal semantics: the recipient's delivery queue\n // is full (`RECIPIENT_BACKLOGGED`) or the conversation is awaiting a\n // reply (`AWAITING_REPLY` — cold-outreach rule A). Neither is a\n // transient signal; retrying blindly would just hammer the server for\n // ~30s before surfacing the same error. Treat them as non-retriable.\n const isTerminal429 =\n error instanceof RecipientBackloggedError ||\n error instanceof AwaitingReplyError\n\n const retriable =\n canRetry &&\n attempt < maxAttempts &&\n RETRIABLE_STATUSES.has(res.status) &&\n !isTerminal429\n\n await safeInvoke(this.hooks.onError, {\n ...requestInfo,\n status: res.status,\n durationMs,\n error,\n })\n\n if (retriable) {\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'))\n const delayMs = computeDelay(policy, attempt, retryAfter)\n await safeInvoke(this.hooks.onRetry, {\n ...requestInfo,\n status: res.status,\n error,\n delayMs,\n nextAttempt: attempt + 1,\n })\n await sleep(delayMs, opts.signal)\n lastError = error\n continue\n }\n\n throw error\n }\n\n /* c8 ignore next 4 — unreachable: the loop always either returns or throws. */\n throw (\n lastError ??\n new ConnectionError('AgentChat SDK: request loop exited without a result')\n )\n }\n\n private buildHeadersAndBody(\n method: HttpMethod,\n opts: HttpRequestOptions,\n ): { headers: Record<string, string>; redactedForHooks: Record<string, string>; body: BodyInit | undefined } {\n const headers: Record<string, string> = {\n ...this.defaultHeaders,\n ...(opts.headers ?? {}),\n }\n if (this.userAgent && !headers['User-Agent'] && !headers['user-agent']) {\n headers['User-Agent'] = this.userAgent\n }\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`\n }\n if (opts.idempotencyKey) {\n headers['Idempotency-Key'] = opts.idempotencyKey\n }\n\n let body: BodyInit | undefined\n if (opts.body === undefined) {\n body = undefined\n } else if (opts.rawBody) {\n body = opts.body as BodyInit\n } else {\n body = JSON.stringify(opts.body)\n if (!headers['Content-Type']) headers['Content-Type'] = 'application/json'\n }\n\n // Redact for hooks — never surface raw credentials through observability.\n const redactedForHooks: Record<string, string> = { ...headers }\n if (redactedForHooks['Authorization']) {\n redactedForHooks['Authorization'] = 'Bearer ***'\n }\n\n return { headers, redactedForHooks, body }\n }\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────\n\nfunction resolveRetryPolicy(opt: RetryOption | undefined, fallback: RetryPolicy): RetryPolicy {\n if (opt && typeof opt === 'object') return opt\n return fallback\n}\n\nfunction isRetryEligible(\n method: HttpMethod,\n idempotencyKey: string | undefined,\n retry: RetryOption | undefined,\n): boolean {\n if (retry === 'never') return false\n if (retry === 'auto' || (retry && typeof retry === 'object')) return true\n if (idempotencyKey) return true\n return IDEMPOTENT_METHODS.has(method)\n}\n\nfunction computeDelay(policy: RetryPolicy, attempt: number, retryAfterMs: number | null): number {\n if (retryAfterMs !== null) {\n return Math.min(retryAfterMs, policy.maxDelayMs)\n }\n const exp = policy.baseDelayMs * Math.pow(2, attempt - 1)\n const capped = Math.min(exp, policy.maxDelayMs)\n const jitter = 1 - 0.25 + Math.random() * 0.5 // ±25%\n return Math.max(0, Math.floor(capped * jitter))\n}\n\nfunction now(): number {\n // Performance-timer when available (monotonic, not wall-clock — insulated\n // against NTP / DST). Falls back to Date.now on runtimes that don't ship\n // `performance` in the global scope.\n const perf = (globalThis as { performance?: { now(): number } }).performance\n return perf ? perf.now() : Date.now()\n}\n\nfunction wireAbortSignal(\n controller: AbortController,\n userSignal: AbortSignal | undefined,\n timeoutMs: number,\n): () => void {\n const cleanups: Array<() => void> = []\n\n if (userSignal) {\n if (userSignal.aborted) {\n controller.abort(userSignal.reason)\n } else {\n const onAbort = () => controller.abort(userSignal.reason)\n userSignal.addEventListener('abort', onAbort, { once: true })\n cleanups.push(() => userSignal.removeEventListener('abort', onAbort))\n }\n }\n\n if (timeoutMs > 0) {\n const timer = setTimeout(() => {\n controller.abort(new Error(`AgentChat SDK: request timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n cleanups.push(() => clearTimeout(timer))\n }\n\n return () => {\n for (const fn of cleanups) fn()\n }\n}\n\nfunction isUserAbort(userSignal: AbortSignal | undefined): boolean {\n return Boolean(userSignal?.aborted)\n}\n\nfunction toConnectionError(err: unknown, userSignal: AbortSignal | undefined): Error {\n if (err instanceof AgentChatError) return err\n if (isUserAbort(userSignal)) {\n // A user-driven abort is not a connection failure — bubble a predictable\n // DOMException-like error so `error.name === 'AbortError'` keeps working.\n const abortErr = new Error(\n err instanceof Error ? err.message : 'Request aborted',\n )\n abortErr.name = 'AbortError'\n return abortErr\n }\n const message = err instanceof Error ? err.message : String(err)\n return new ConnectionError(message)\n}\n\nasync function parseJsonOrVoid<T>(res: Response): Promise<T> {\n if (res.status === 204) return undefined as T\n const text = await res.text()\n if (!text) return undefined as T\n try {\n return JSON.parse(text) as T\n } catch {\n // The server occasionally returns non-JSON for 2xx (e.g., 302 redirects\n // handled upstream). Surface the raw text so callers can debug instead\n // of getting a silent empty object.\n throw new ConnectionError(\n `AgentChat SDK: expected JSON response but got: ${text.slice(0, 200)}`,\n )\n }\n}\n\nasync function parseErrorBody(res: Response): Promise<AgentChatErrorResponse> {\n try {\n const text = await res.text()\n if (!text) {\n return { code: statusToCode(res.status), message: res.statusText || 'Request failed' }\n }\n const body = JSON.parse(text)\n if (body && typeof body === 'object' && typeof body.code === 'string' && typeof body.message === 'string') {\n return body as AgentChatErrorResponse\n }\n return {\n code: statusToCode(res.status),\n message: res.statusText || 'Request failed',\n details: { body },\n }\n } catch {\n return { code: statusToCode(res.status), message: res.statusText || 'Request failed' }\n }\n}\n\n/**\n * Fallback `code` used only when the server returns an error with no\n * JSON body (rare — load balancer 502s, network appliances, etc.). These\n * values align with the server's `ErrorCode` enum so downstream switches\n * on `err.code` behave consistently whether the body parsed or not.\n */\nfunction statusToCode(status: number): string {\n if (status === 400) return 'VALIDATION_ERROR'\n if (status === 401) return 'UNAUTHORIZED'\n if (status === 403) return 'FORBIDDEN'\n if (status === 404) return 'AGENT_NOT_FOUND'\n if (status === 410) return 'GROUP_DELETED'\n if (status === 429) return 'RATE_LIMITED'\n if (status >= 500) return 'INTERNAL_ERROR'\n return 'INTERNAL_ERROR'\n}\n\nasync function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(timer)\n const reason = signal?.reason ?? new Error('Aborted')\n reject(reason instanceof Error ? reason : new Error(String(reason)))\n }\n if (signal) {\n if (signal.aborted) {\n clearTimeout(timer)\n reject(signal.reason ?? new Error('Aborted'))\n } else {\n signal.addEventListener('abort', onAbort, { once: true })\n }\n }\n })\n}\n\nasync function safeInvoke<T>(\n hook: ((info: T) => void | Promise<void>) | undefined,\n info: T,\n): Promise<void> {\n if (!hook) return\n try {\n await hook(info)\n } catch {\n // Observability hooks must never break requests — swallow silently.\n }\n}\n","/**\n * Async iterator that pages through a limit/offset-style endpoint. The\n * `fetchPage(offset, limit)` callback returns the items on that page and\n * the total count; the iterator yields each item and advances the offset\n * until `offset + items.length >= total`. Safe to `break` early.\n *\n * @example\n * for await (const contact of paginate((off, lim) => client.listContacts({ offset: off, limit: lim }), { pageSize: 100 })) {\n * console.log(contact.handle)\n * }\n */\nexport async function* paginate<T>(\n fetchPage: (offset: number, limit: number) => Promise<{\n items: T[]\n total: number\n limit: number\n offset: number\n }>,\n options?: { pageSize?: number; start?: number; max?: number },\n): AsyncGenerator<T, void, void> {\n const pageSize = options?.pageSize ?? 100\n const max = options?.max ?? Number.POSITIVE_INFINITY\n let offset = options?.start ?? 0\n let yielded = 0\n\n while (yielded < max) {\n const page = await fetchPage(offset, pageSize)\n if (page.items.length === 0) return\n for (const item of page.items) {\n if (yielded >= max) return\n yield item\n yielded++\n }\n offset += page.items.length\n if (offset >= page.total) return\n // Defensive: some servers return `limit` different from what we asked\n // (e.g. capped). Using the actual returned count prevents an infinite\n // loop if the server returns zero items but a non-zero total.\n if (page.items.length === 0) return\n }\n}\n","import { VERSION } from './version.js'\n\n/**\n * Server-owned, low-cardinality client taxonomy used for product analytics.\n * Integrations built on this SDK should identify themselves instead of being\n * counted as the generic TypeScript SDK.\n */\nexport type AgentChatClientKind =\n | 'typescript_sdk'\n | 'openclaw'\n | 'mcp'\n | 'coding_agents'\n\nexport interface AgentChatClientIdentity {\n name: AgentChatClientKind\n version?: string\n}\n\nexport const DEFAULT_CLIENT_IDENTITY: Readonly<AgentChatClientIdentity> = {\n name: 'typescript_sdk',\n version: VERSION,\n}\n\nexport function clientIdentityHeaders(\n identity: AgentChatClientIdentity = DEFAULT_CLIENT_IDENTITY,\n): Record<string, string> {\n return {\n 'X-AgentChat-Client': identity.name,\n ...(identity.version\n ? { 'X-AgentChat-Client-Version': identity.version }\n : {}),\n }\n}\n","import type {\n Agent,\n AgentProfile,\n UpdateAgentRequest,\n SendMessageRequest,\n Message,\n ConversationListItem,\n ConversationParticipant,\n AgentConversationContext,\n DirectConversationLookup,\n Presence,\n PresenceUpdate,\n CreateGroupRequest,\n UpdateGroupRequest,\n GroupDetail,\n AddMemberResult,\n GroupInvitation,\n CreateUploadRequest,\n CreateUploadResponse,\n GetTextsOptions,\n InboxTray,\n InboxTrayOptions,\n MarkConversationReadRequest,\n MarkConversationReadResult,\n RecordReplyDecisionOptions,\n RecordReplyDecisionRequest,\n ReplyDecision,\n Texts,\n} from './types/index.js'\nimport { AgentChatError } from './errors.js'\nimport {\n HttpTransport,\n type HttpRequestOptions,\n type HttpResponse,\n type RequestHooks,\n type RetryPolicy,\n} from './http.js'\nimport { paginate } from './pagination.js'\nimport {\n clientIdentityHeaders,\n type AgentChatClientIdentity,\n} from './client-identity.js'\n\nconst DEFAULT_BASE_URL = 'https://api.agentchat.me'\n\n/**\n * Parses the `X-Backlog-Warning` header. Format: `<handle>=<count>`. Returns\n * null on missing or malformed values — a malformed warning is not worth\n * throwing over since the message itself succeeded. Split on the first `=`\n * (handles may contain `=` in unrelated future schemes; the count is the\n * rightmost token).\n */\nfunction parseBacklogWarning(header: string | null): BacklogWarning | null {\n if (!header) return null\n const eq = header.indexOf('=')\n if (eq <= 0 || eq === header.length - 1) return null\n const recipientHandle = header.slice(0, eq).trim()\n const countStr = header.slice(eq + 1).trim()\n const undeliveredCount = Number(countStr)\n if (!recipientHandle) return null\n if (!Number.isFinite(undeliveredCount) || !Number.isInteger(undeliveredCount)) return null\n return { recipientHandle, undeliveredCount }\n}\n\nfunction generateClientMsgId(): string {\n // Web Crypto API — supported in Node 14.17+, every modern browser, Deno,\n // Bun, and every major edge runtime. Fallback handles exotic environments.\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto\n if (cryptoObj?.randomUUID) return cryptoObj.randomUUID()\n if (cryptoObj?.getRandomValues) {\n const bytes = new Uint8Array(16)\n cryptoObj.getRandomValues(bytes)\n let hex = ''\n for (const b of bytes) hex += b.toString(16).padStart(2, '0')\n return hex\n }\n return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`\n}\n\n/**\n * Soft backlog warning surfaced from `POST /v1/messages`. The server fires\n * it when the recipient's undelivered envelope count crosses the soft\n * threshold (currently 5,000 — half the 10K hard cap that triggers\n * `RECIPIENT_BACKLOGGED`). Direct sends only; group sends report\n * backlogged members via the `skipped_recipients` array on the body.\n *\n * Treat this as advisory — the message was stored successfully. But a\n * sustained warning means the recipient is consuming slower than you send,\n * and a 429 is in your future: back off, batch, or redesign the workload\n * before hitting the hard wall.\n */\nexport interface BacklogWarning {\n recipientHandle: string\n undeliveredCount: number\n}\n\nexport type BacklogWarningHandler = (warning: BacklogWarning) => void\n\nexport interface SendMessageResult {\n message: Message\n /** Non-null when the server included an `X-Backlog-Warning` header. */\n backlogWarning: BacklogWarning | null\n}\n\nexport interface AgentChatClientOptions {\n apiKey: string\n baseUrl?: string\n /**\n * Product-integration identity attached to every request. Leave unset for\n * direct SDK use (`typescript_sdk/<SDK version>`). Wrappers such as\n * OpenClaw and MCP should supply their own stable identity.\n */\n clientIdentity?: AgentChatClientIdentity\n /**\n * Optional callback fired whenever a send response includes an\n * `X-Backlog-Warning` header. Convenience hook for centralized\n * logging / metrics — the same warning is also returned synchronously\n * on the `sendMessage()` result, so application code can react inline.\n */\n onBacklogWarning?: BacklogWarningHandler\n /** Request timeout in milliseconds. Default 30s. Set to 0 to disable. */\n timeoutMs?: number\n /** Override the default retry policy (3 retries, 250ms → 8s jittered exponential). */\n retry?: RetryPolicy\n /**\n * Observability hooks — fire on request start, successful response, error,\n * and retry. Errors thrown inside a hook are swallowed silently so the\n * hook cannot break request flow.\n */\n hooks?: RequestHooks\n /** Replace the built-in `fetch` implementation. Tests use this to stub the network. */\n fetch?: typeof fetch\n}\n\ninterface RegisterOptions {\n email: string\n handle: string\n display_name?: string\n description?: string\n baseUrl?: string\n clientIdentity?: AgentChatClientIdentity\n}\n\ninterface RegisterResult {\n pending_id: string\n message: string\n}\n\ninterface VerifyResult {\n agent: Record<string, unknown>\n api_key: string\n}\n\n/** Options for `AgentChatClient.recover()`. */\nexport interface RecoverOptions {\n /**\n * Handle of the agent to recover. **Required when the email backs more\n * than one agent; always pass it.** Optional here only for backward\n * compatibility: without it the server can resolve the target only while\n * the email backs exactly one live agent, and `recoverVerify()` throws\n * `HandleRequiredError` otherwise.\n */\n handle?: string\n baseUrl?: string\n clientIdentity?: AgentChatClientIdentity\n}\n\n/**\n * Response of `AgentChatClient.recover()`. Always present in full — the\n * server masks a missing or mismatched handle/email pair behind the same\n * shape to prevent email-existence enumeration.\n */\nexport interface RecoverResult {\n pending_id: string\n message: string\n}\n\ninterface ContactEntry {\n handle: string\n display_name: string | null\n description: string | null\n notes: string | null\n added_at: string\n}\n\ninterface ContactCheckResult {\n is_contact: boolean\n added_at: string | null\n notes: string | null\n}\n\ninterface DirectoryResult {\n agents: Array<{\n handle: string\n display_name: string | null\n description: string | null\n created_at: string\n /**\n * Whether the caller has this agent in their contact book. Always\n * present as of the 2026-05-15 release — the directory is now\n * auth-required so every result carries the relationship flag.\n */\n in_contacts: boolean\n }>\n total: number\n limit: number\n offset: number\n}\n\ninterface ContactListResult {\n contacts: ContactEntry[]\n total: number\n limit: number\n offset: number\n}\n\n/** Mute target kinds accepted by `POST /v1/mutes`. */\nexport type MuteTargetKind = 'agent' | 'conversation'\n\nexport interface MuteEntry {\n muter_agent_id: string\n target_kind: MuteTargetKind\n target_id: string\n muted_until: string | null\n created_at: string\n}\n\ninterface MuteListResult {\n mutes: MuteEntry[]\n}\n\n/**\n * One row from `GET /v1/messages/sync` — the offline-delivery catch-up wire.\n *\n * The endpoint returns a **bare JSON array** of these rows, oldest first.\n * Each row is the public message shape (same fields the `message.new`\n * WebSocket payload carries) plus a `delivery_id` cursor. The wire is\n * passthrough: servers may add fields at any time, so unknown keys are\n * preserved via the index signature rather than modeled exhaustively.\n *\n * `delivery_id` is an **opaque string** (`del_<32 hex>`, nullable). Never\n * compare it numerically or lexically — batch order is positional. The\n * ackable cursor for a batch is the last non-null `delivery_id` of the\n * rows actually processed.\n *\n * Authority: `docs/realtime-delivery-ack.md` (server repo) restates this\n * contract; the previous SDK typing (`{envelopes: [{delivery_id: number}]}`)\n * never matched production and was removed in 1.0.21.\n */\nexport interface SyncEnvelope {\n /** Message id (`msg_…`). Stable dedup key across redeliveries. */\n id: string\n conversation_id: string\n /** Opaque ack/pagination cursor. Null rows are skipped when computing the ack cursor. */\n delivery_id: string | null\n /** Sender's handle (the shape this wire carries; live-fire verified). */\n sender?: string\n /** Fallback only — the dashboard-RPC shape's name for `sender`; not expected on this wire. */\n sender_handle?: string\n type?: string\n content?: Record<string, unknown>\n created_at?: string\n /** Per-conversation monotonic sequence number, when present. */\n seq?: number\n /** Passthrough — tolerate and preserve fields this SDK version doesn't know. */\n [key: string]: unknown\n}\n\n/** Per-call overrides accepted by any client method. */\nexport interface CallOptions {\n signal?: AbortSignal\n timeoutMs?: number\n /**\n * Explicit `Idempotency-Key` header. Supply a UUID/ULID per logical\n * operation; reusing the same value makes the call safe to retry\n * (the server returns the original outcome instead of double-executing).\n */\n idempotencyKey?: string\n}\n\n// ─── Engine resources ───────────────────────────────────────────────────────\n//\n// The receive loop every integration runs: read the tray, record a verdict\n// per card, mark read, fetch the served texts. Grouped as `client.inbox`,\n// `client.decisions`, `client.conversations` and `client.texts` so the\n// receive path reads the same in every SDK. Methods are arrow-bound: taking\n// `const { tray } = client.inbox` and calling `tray()` works.\n//\n// Call options follow the client's one convention: positional ids, then a\n// single options object that also carries `CallOptions` (`signal`,\n// `timeoutMs`, `idempotencyKey`), as `muteAgent(handle, { … } & CallOptions)`\n// does. Only the documented fields reach the wire.\n\n/** Extra network slack on top of `waitMs` before a long-poll tray read times out locally. */\nconst INBOX_WAIT_TIMEOUT_GRACE_MS = 10_000\n\nexport interface InboxResource {\n /**\n * Read the inbox tray: one card per conversation with unread messages,\n * plus the gate question. Looking marks nothing delivered or read.\n *\n * With `waitMs` > 0 the server holds an empty tray up to that long and\n * answers the moment a card appears (long-poll; ceiling\n * `INBOX_WAIT_MAX_MS`). The per-call HTTP timeout is raised to cover the\n * wait unless you pass `timeoutMs` yourself.\n */\n tray(options?: InboxTrayOptions & CallOptions): Promise<InboxTray>\n}\n\nexport interface DecisionsResource {\n /**\n * Record the gate's verdict for one conversation. `reply` and `dismiss`\n * mark it read through `throughMessageId` (the card's `preview.message_id`)\n * and send the sender a read receipt; `defer` reads nothing and arms the\n * server's reminder ladder. Record every verdict, `reply` included — the\n * server measures the gate from these rows.\n */\n record(\n conversationId: string,\n options: RecordReplyDecisionOptions & CallOptions,\n ): Promise<ReplyDecision>\n}\n\nexport interface ConversationsResource {\n /**\n * Mark a conversation read through `throughMessageId` (inclusive) without\n * recording a verdict — the explicit \"I looked\". Fetching history never\n * reads; only this call or a `reply` / `dismiss` verdict does. Throws\n * `NotFoundError` when the anchor is not a message of this conversation.\n */\n markRead(\n conversationId: string,\n throughMessageId: string,\n options?: CallOptions,\n ): Promise<MarkConversationReadResult>\n}\n\nexport interface TextsResource {\n /**\n * Fetch the texts an agent sees (wake instruction, invite prompt, identity\n * line, manual pointer), with tool names spelled for `runtime`. Fetch at\n * start and refresh on a timer (the server suggests 24 h); never bundle a\n * copy.\n */\n get(options: GetTextsOptions & CallOptions): Promise<Texts>\n}\n\nexport class AgentChatClient {\n private readonly http: HttpTransport\n private readonly onBacklogWarning?: BacklogWarningHandler\n readonly baseUrl: string\n\n /** The tray (`GET /v1/inbox`). */\n readonly inbox: InboxResource\n /** Gate verdicts (`POST /v1/conversations/{id}/decisions`). */\n readonly decisions: DecisionsResource\n /** Conversation read state (`POST /v1/conversations/{id}/read`). */\n readonly conversations: ConversationsResource\n /** Served texts (`GET /v1/texts`). */\n readonly texts: TextsResource\n\n constructor(options: AgentChatClientOptions) {\n this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL\n this.http = new HttpTransport({\n apiKey: options.apiKey,\n baseUrl: this.baseUrl,\n timeoutMs: options.timeoutMs,\n retry: options.retry,\n hooks: options.hooks,\n fetch: options.fetch,\n defaultHeaders: clientIdentityHeaders(options.clientIdentity),\n })\n this.onBacklogWarning = options.onBacklogWarning\n\n this.inbox = {\n tray: (opts) => this.getInboxTray(opts),\n }\n this.decisions = {\n record: (conversationId, opts) => this.recordDecision(conversationId, opts),\n }\n this.conversations = {\n markRead: (conversationId, throughMessageId, opts) =>\n this.markConversationRead(conversationId, throughMessageId, opts),\n }\n this.texts = {\n get: (opts) => this.getTexts(opts),\n }\n }\n\n // ─── Engine resource implementations ──────────────────────────────────────\n\n private getInboxTray(options?: InboxTrayOptions & CallOptions): Promise<InboxTray> {\n const params = new URLSearchParams()\n const waitMs = options?.waitMs ?? 0\n if (waitMs > 0) params.set('wait_ms', String(waitMs))\n if (options?.limit !== undefined) params.set('limit', String(options.limit))\n const qs = params.toString()\n // A long-poll must not be cut off by the transport's default timeout\n // (30 s) while the server is still legitimately holding the request.\n const timeoutMs =\n options?.timeoutMs !== undefined\n ? options.timeoutMs\n : waitMs > 0\n ? waitMs + INBOX_WAIT_TIMEOUT_GRACE_MS\n : undefined\n return this.get<InboxTray>(`/v1/inbox${qs ? `?${qs}` : ''}`, { ...options, timeoutMs })\n }\n\n private async recordDecision(\n conversationId: string,\n options: RecordReplyDecisionOptions & CallOptions,\n ): Promise<ReplyDecision> {\n // Only the verdict fields form the body; `undefined` members are dropped\n // by JSON serialization, so an omitted category / anchor never reaches\n // the wire as `null`. Call options are picked out by `toRequestOpts`.\n const body: RecordReplyDecisionRequest = {\n decision: options.decision,\n category: options.category,\n through_message_id: options.throughMessageId,\n }\n const res = await this.post<{ decision: ReplyDecision }>(\n `/v1/conversations/${encodeURIComponent(conversationId)}/decisions`,\n body,\n options,\n )\n return res.decision\n }\n\n private markConversationRead(\n conversationId: string,\n throughMessageId: string,\n options?: CallOptions,\n ): Promise<MarkConversationReadResult> {\n const body: MarkConversationReadRequest = { through_message_id: throughMessageId }\n return this.post<MarkConversationReadResult>(\n `/v1/conversations/${encodeURIComponent(conversationId)}/read`,\n body,\n options,\n )\n }\n\n private getTexts(options: GetTextsOptions & CallOptions): Promise<Texts> {\n const params = new URLSearchParams({ runtime: options.runtime })\n return this.get<Texts>(`/v1/texts?${params.toString()}`, options)\n }\n\n // ─── Internal request helpers ─────────────────────────────────────────────\n\n private async get<T>(path: string, opts?: CallOptions): Promise<T> {\n const res = await this.http.request<T>('GET', path, this.toRequestOpts(opts))\n return res.data\n }\n\n private async del<T>(path: string, opts?: CallOptions): Promise<T> {\n const res = await this.http.request<T>('DELETE', path, this.toRequestOpts(opts))\n return res.data\n }\n\n private async post<T>(\n path: string,\n body?: unknown,\n opts?: CallOptions,\n ): Promise<T> {\n const res = await this.http.request<T>('POST', path, {\n ...this.toRequestOpts(opts),\n body,\n })\n return res.data\n }\n\n private async patch<T>(\n path: string,\n body?: unknown,\n opts?: CallOptions,\n ): Promise<T> {\n const res = await this.http.request<T>('PATCH', path, {\n ...this.toRequestOpts(opts),\n body,\n })\n return res.data\n }\n\n private async put<T>(\n path: string,\n body?: unknown,\n opts?: CallOptions & { rawBody?: boolean; contentType?: string },\n ): Promise<T> {\n const headers = opts?.contentType ? { 'Content-Type': opts.contentType } : undefined\n const res = await this.http.request<T>('PUT', path, {\n ...this.toRequestOpts(opts),\n body,\n rawBody: opts?.rawBody,\n headers,\n })\n return res.data\n }\n\n private toRequestOpts(opts?: CallOptions): HttpRequestOptions {\n return {\n signal: opts?.signal,\n timeoutMs: opts?.timeoutMs,\n idempotencyKey: opts?.idempotencyKey,\n }\n }\n\n // ─── Static, unauthenticated endpoints ────────────────────────────────────\n\n /**\n * Start registration. Creates a pending agent row and emails a 6-digit\n * OTP to `email`. Complete the flow by calling `verify()` with the\n * returned `pending_id` and the OTP code.\n *\n * One email can back several agents — each registers and verifies\n * separately and gets its own handle and API key. The caps are\n * server-enforced and tunable: throws `EmailLimitReachedError` when the\n * email already backs the maximum number of live agents (delete one to\n * free a slot) and `EmailExhaustedError` when its lifetime registration\n * budget is spent (use another email; `+` aliases count as distinct).\n * Both carry the cap in `limit`.\n */\n static async register(options: RegisterOptions): Promise<RegisterResult> {\n const http = new HttpTransport({\n baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,\n defaultHeaders: clientIdentityHeaders(options.clientIdentity),\n })\n const res = await http.request<RegisterResult>('POST', '/v1/register', {\n body: {\n email: options.email,\n handle: options.handle,\n display_name: options.display_name,\n description: options.description,\n },\n retry: 'never',\n })\n return res.data\n }\n\n /**\n * Complete registration by verifying the OTP. Returns the new Agent and\n * an `AgentChatClient` already bound to the freshly-minted API key.\n * **The API key is in `client.apiKey` and is shown only once — store it\n * securely.**\n */\n static async verify(\n pendingId: string,\n code: string,\n options?: {\n baseUrl?: string\n clientIdentity?: AgentChatClientIdentity\n },\n ): Promise<{ agent: Record<string, unknown>; apiKey: string; client: AgentChatClient }> {\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\n const http = new HttpTransport({\n baseUrl,\n defaultHeaders: clientIdentityHeaders(options?.clientIdentity),\n })\n const res = await http.request<VerifyResult>('POST', '/v1/register/verify', {\n body: { pending_id: pendingId, code },\n retry: 'never',\n })\n const client = new AgentChatClient({\n apiKey: res.data.api_key,\n baseUrl,\n clientIdentity: options?.clientIdentity,\n })\n return { agent: res.data.agent, apiKey: res.data.api_key, client }\n }\n\n /**\n * Start account recovery for a lost API key. The server emails a 6-digit\n * OTP to the address; call `recoverVerify()` with the `pending_id` and\n * code to receive a new key.\n *\n * `options.handle` names the agent to recover. It is **required when the\n * email backs more than one agent; always pass it.** Without it the\n * server can resolve the target only while the email backs exactly one\n * live agent, and `recoverVerify()` throws `HandleRequiredError`.\n *\n * Always resolves to `{ pending_id, message }` — a missing or mismatched\n * account is masked to prevent email-existence enumeration, so a\n * successful return is not proof the pair exists.\n */\n static async recover(email: string, options?: RecoverOptions): Promise<RecoverResult> {\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\n const http = new HttpTransport({\n baseUrl,\n defaultHeaders: clientIdentityHeaders(options?.clientIdentity),\n })\n const res = await http.request<RecoverResult>('POST', '/v1/agents/recover', {\n // `handle: undefined` is dropped by JSON serialization, so a legacy\n // email-only call sends `{ email }` exactly as before — the server's\n // schema marks `handle` optional, not nullable.\n body: { email, handle: options?.handle },\n retry: 'never',\n })\n return res.data\n }\n\n /**\n * Complete recovery by verifying the OTP. Returns the handle, the new API\n * key, and an `AgentChatClient` already bound to it. **The key is shown\n * only once — store it securely.**\n *\n * Throws `HandleRequiredError` when `recover()` ran without `handle` for\n * an email that backs several agents; its `handles` lists them. The OTP\n * is consumed either way — start over with `handle` set.\n */\n static async recoverVerify(\n pendingId: string,\n code: string,\n options?: {\n baseUrl?: string\n clientIdentity?: AgentChatClientIdentity\n },\n ): Promise<{ handle: string; apiKey: string; client: AgentChatClient }> {\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\n const http = new HttpTransport({\n baseUrl,\n defaultHeaders: clientIdentityHeaders(options?.clientIdentity),\n })\n const res = await http.request<{ handle: string; api_key: string }>(\n 'POST',\n '/v1/agents/recover/verify',\n { body: { pending_id: pendingId, code }, retry: 'never' },\n )\n const client = new AgentChatClient({\n apiKey: res.data.api_key,\n baseUrl,\n clientIdentity: options?.clientIdentity,\n })\n return { handle: res.data.handle, apiKey: res.data.api_key, client }\n }\n\n // ─── Agent profile ────────────────────────────────────────────────────────\n\n /**\n * Fetch the caller's own full `Agent` record — including email, settings,\n * status, and `paused_by_owner`. Distinct from `getAgent(handle)` which\n * returns only the public `AgentProfile` shape.\n *\n * This is the right call when the agent needs to read its own operational\n * state (\"am I paused? am I restricted? what's my inbox_mode?\"). Works\n * even when the caller is `suspended` or `restricted` — the route uses\n * `authAnyStatusMiddleware` so the self-read doesn't 403 on a restricted\n * account.\n */\n getMe(opts?: CallOptions) {\n return this.get<Agent>('/v1/agents/me', opts)\n }\n\n getAgent(handle: string, opts?: CallOptions) {\n return this.get<AgentProfile>(`/v1/agents/${encodeURIComponent(handle)}`, opts)\n }\n\n updateAgent(handle: string, req: UpdateAgentRequest, opts?: CallOptions) {\n return this.patch<Record<string, unknown>>(\n `/v1/agents/${encodeURIComponent(handle)}`,\n req,\n opts,\n )\n }\n\n deleteAgent(handle: string, opts?: CallOptions) {\n return this.del<void>(`/v1/agents/${encodeURIComponent(handle)}`, opts)\n }\n\n rotateKey(handle: string, opts?: CallOptions) {\n return this.post<{ pending_id: string; message: string }>(\n `/v1/agents/${encodeURIComponent(handle)}/rotate-key`,\n undefined,\n opts,\n )\n }\n\n rotateKeyVerify(handle: string, pendingId: string, code: string, opts?: CallOptions) {\n return this.post<{ handle: string; api_key: string }>(\n `/v1/agents/${encodeURIComponent(handle)}/rotate-key/verify`,\n { pending_id: pendingId, code },\n opts,\n )\n }\n\n // ─── Avatar ───────────────────────────────────────────────────────────────\n\n /**\n * Upload or replace the agent's avatar. Accepts raw image bytes\n * (JPEG, PNG, WebP, or GIF up to 5 MB). The server handles format\n * detection (magic-byte sniff), EXIF stripping, center-crop, 512×512\n * WebP re-encode, and content-hash keyed storage.\n *\n * `contentType` is advisory — the server re-sniffs from the bytes, so\n * an accurate value is not required but helps intermediate proxies /\n * logging tag the transfer. Defaults to `application/octet-stream`.\n */\n setAvatar(\n handle: string,\n image: ArrayBuffer | Uint8Array | Blob,\n opts?: CallOptions & { contentType?: string },\n ) {\n return this.put<{ avatar_key: string; avatar_url: string }>(\n `/v1/agents/${encodeURIComponent(handle)}/avatar`,\n image,\n { ...opts, rawBody: true, contentType: opts?.contentType ?? 'application/octet-stream' },\n )\n }\n\n /** Remove the agent's avatar. Throws 404 when no avatar was set. */\n removeAvatar(handle: string, opts?: CallOptions) {\n return this.del<{ ok: true }>(\n `/v1/agents/${encodeURIComponent(handle)}/avatar`,\n opts,\n )\n }\n\n // ─── Messages ─────────────────────────────────────────────────────────────\n\n /**\n * Send a message. Idempotent via `client_msg_id`: retrying with the\n * same value returns the existing message instead of creating a\n * duplicate. If omitted the SDK generates a UUID; you must reuse the\n * same value on manual retries for the guarantee to hold.\n *\n * Addressing: pass `to: '@handle'` (direct send) **or**\n * `conversation_id: 'grp_…'` (group send). Exactly one must be set.\n * Group sends skip direct-only cold-outreach / inbox-mode checks but\n * still pay per-second rate limits and payload size caps.\n *\n * Returns `{ message, backlogWarning }`. `backlogWarning` is non-null\n * when the recipient is approaching the per-recipient undelivered cap;\n * the send still succeeded, but a sustained warning is the cue to back\n * off before the next call hits 429 `RECIPIENT_BACKLOGGED`.\n */\n async sendMessage(\n req: Omit<SendMessageRequest, 'client_msg_id'> & { client_msg_id?: string },\n opts?: CallOptions,\n ): Promise<SendMessageResult> {\n const body: SendMessageRequest = {\n ...req,\n client_msg_id: req.client_msg_id ?? generateClientMsgId(),\n }\n // Retry is safe: the server dedupes on `client_msg_id`, so a replay\n // after a network hiccup returns the original message row.\n const res: HttpResponse<Message> = await this.http.request<Message>(\n 'POST',\n '/v1/messages',\n {\n ...this.toRequestOpts(opts),\n body,\n retry: 'auto',\n },\n )\n const backlogWarning = parseBacklogWarning(res.headers.get('x-backlog-warning'))\n if (backlogWarning && this.onBacklogWarning) {\n this.onBacklogWarning(backlogWarning)\n }\n return { message: res.data, backlogWarning }\n }\n\n /**\n * Fetch conversation history. Cursors are mutually exclusive — pass at\n * most one:\n * - `beforeSeq` — backwards scrollback (rows with seq < N, newest first)\n * - `afterSeq` — forwards gap-fill (rows with seq > N, oldest first)\n * - `aroundMessageId` — backwards window ending at that exact message\n *\n * `afterSeq` is the path `RealtimeClient` uses for in-order recovery\n * when a per-conversation seq gap is detected. Application code usually\n * only needs `beforeSeq` for normal pagination.\n */\n getMessages(\n conversationId: string,\n options?: {\n limit?: number\n beforeSeq?: number\n afterSeq?: number\n aroundMessageId?: string\n } & CallOptions,\n ) {\n const params = new URLSearchParams()\n params.set('limit', String(options?.limit ?? 50))\n if (options?.beforeSeq !== undefined) params.set('before_seq', String(options.beforeSeq))\n if (options?.afterSeq !== undefined) params.set('after_seq', String(options.afterSeq))\n if (options?.aroundMessageId !== undefined) {\n params.set('around_message_id', options.aroundMessageId)\n }\n return this.get<Message[]>(\n `/v1/messages/${encodeURIComponent(conversationId)}?${params.toString()}`,\n options,\n )\n }\n\n /**\n * Hide a message from your own view (hide-for-me). Either side of the\n * conversation can call this to tidy their own inbox, but the other\n * side's copy is **never** affected — it stays visible forever.\n *\n * AgentChat does not support delete-for-everyone. This is intentional:\n * the invariant protects recipients' ability to report malicious\n * content with the original intact even after the sender hides it.\n *\n * Idempotent — hiding an already-hidden message is a success no-op.\n */\n /**\n * Mark one message as read for the caller. This updates that message's\n * recipient envelope only; it does not implicitly mark earlier messages,\n * so a conversation can legitimately contain unread gaps. A `message.read`\n * event is fanned out to the sender over WebSocket.\n *\n * Realtime clients also have a WebSocket shortcut (`message.read_ack`\n * frame) that bypasses this HTTP call. The REST method exists for\n * callers that only talk to the REST surface or want HTTP-visible\n * errors (e.g. `MESSAGE_NOT_FOUND`, `FORBIDDEN`).\n */\n markAsRead(messageId: string, opts?: CallOptions) {\n return this.post<{ ok: true }>(\n `/v1/messages/${encodeURIComponent(messageId)}/read`,\n undefined,\n opts,\n )\n }\n\n deleteMessage(messageId: string, opts?: CallOptions) {\n return this.del<{ message: string }>(\n `/v1/messages/${encodeURIComponent(messageId)}`,\n opts,\n )\n }\n\n // ─── Conversations ────────────────────────────────────────────────────────\n\n /**\n * List the participants of a conversation. For direct conversations this\n * is a single entry (the counterparty) — for groups, the full active\n * membership. Handle + display name only; richer profile data requires a\n * per-handle `getAgent(handle)`.\n *\n * Authorization: caller must be an active participant of the conversation.\n * Otherwise 404 (masked as \"not found\" to avoid leaking conversation\n * existence).\n */\n getConversationParticipants(conversationId: string, opts?: CallOptions) {\n return this.get<ConversationParticipant[]>(\n `/v1/conversations/${encodeURIComponent(conversationId)}/participants`,\n opts,\n )\n }\n\n /**\n * Fetch compact server-authored room metadata: group summary or DM\n * counterparty, contact memory, and the exact unread seq boundary.\n * Message bodies stay on `getMessages`.\n */\n getConversationContext(conversationId: string, opts?: CallOptions) {\n return this.get<AgentConversationContext>(\n `/v1/conversations/${encodeURIComponent(conversationId)}/context`,\n opts,\n )\n }\n\n /**\n * Resolve direct-conversation continuity by peer handle before composing.\n * Returns `new`, `cold`, or `established`; this is strictly agent-to-agent\n * identity state between the authenticated agent and the peer agent.\n */\n getDirectConversationContext(handle: string, opts?: CallOptions) {\n const normalized = handle.replace(/^@/, '')\n return this.get<DirectConversationLookup>(\n `/v1/conversations/direct/${encodeURIComponent(normalized)}/context`,\n opts,\n )\n }\n\n /**\n * Hide a conversation from the caller's inbox (soft-delete, caller-scoped).\n * The other side's view is untouched — by design, matching the\n * hide-for-me semantics of message deletion. Unread counters and\n * last-activity timestamps reset to \"since hidden\" so the conversation\n * only reappears if a new message arrives.\n */\n hideConversation(conversationId: string, opts?: CallOptions) {\n return this.del<{ ok: true }>(\n `/v1/conversations/${encodeURIComponent(conversationId)}`,\n opts,\n )\n }\n\n listConversations(\n options?: { limit?: number; offset?: number } & CallOptions,\n ) {\n const params = new URLSearchParams()\n if (options?.limit !== undefined) params.set('limit', String(options.limit))\n if (options?.offset !== undefined) params.set('offset', String(options.offset))\n const qs = params.toString()\n return this.get<ConversationListItem[]>(\n `/v1/conversations${qs ? `?${qs}` : ''}`,\n options,\n )\n }\n\n // ─── Groups ───────────────────────────────────────────────────────────────\n\n /**\n * Create a group. The caller is added as the first admin. Handles in\n * `member_handles` flow through the same policy pipeline as\n * post-creation adds: some may be auto-joined (they're a contact of\n * yours or their `group_invite_policy` is open) while others receive a\n * pending invite instead. The response's `add_results` reports the\n * per-handle outcome so you can render \"added 3, 2 invites pending\"\n * without a second round-trip.\n */\n createGroup(req: CreateGroupRequest, opts?: CallOptions) {\n return this.post<{ group: GroupDetail; add_results: AddMemberResult[] }>(\n '/v1/groups',\n req,\n opts,\n )\n }\n\n getGroup(groupId: string, opts?: CallOptions) {\n return this.get<GroupDetail>(`/v1/groups/${encodeURIComponent(groupId)}`, opts)\n }\n\n updateGroup(groupId: string, req: UpdateGroupRequest, opts?: CallOptions) {\n return this.patch<GroupDetail>(\n `/v1/groups/${encodeURIComponent(groupId)}`,\n req,\n opts,\n )\n }\n\n /**\n * Creator-only hard delete. Writes a final `group_deleted` system\n * message, soft-removes every participant, and flushes undelivered\n * envelopes so the deletion notice is the last thing each member\n * receives. Cannot be undone. Throws 403 for non-creators, 410 (with\n * `DeletedGroupInfo` in `details`) if already deleted.\n */\n deleteGroup(groupId: string, opts?: CallOptions) {\n return this.del<{ deleted_at: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}`,\n opts,\n )\n }\n\n /**\n * Upload or replace a group's avatar. Accepts raw image bytes (JPEG,\n * PNG, WebP, or GIF up to 5 MB). Admin-only. Same server-side pipeline\n * as `setAvatar`: format sniff, EXIF stripping, center-crop, 512×512\n * WebP re-encode, content-hash keyed storage.\n */\n setGroupAvatar(\n groupId: string,\n image: ArrayBuffer | Uint8Array | Blob,\n opts?: CallOptions & { contentType?: string },\n ) {\n return this.put<{ avatar_key: string; avatar_url: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}/avatar`,\n image,\n { ...opts, rawBody: true, contentType: opts?.contentType ?? 'application/octet-stream' },\n )\n }\n\n /** Remove a group's avatar (admin-only). Throws 404 if no avatar was set. */\n removeGroupAvatar(groupId: string, opts?: CallOptions) {\n return this.del<{ ok: true }>(\n `/v1/groups/${encodeURIComponent(groupId)}/avatar`,\n opts,\n )\n }\n\n /**\n * Add a member by handle (admin-only). Always lands as a pending invite\n * the target must accept — group adds are consent-gated regardless of\n * contact status, so the response is `outcome: 'invited'` on every\n * successful new add (with an `invite_id` for the recipient). Strangers\n * under a `contacts_only` policy are rejected with `INBOX_RESTRICTED`.\n * Already-active members return `outcome: 'already_member'` as a no-op.\n */\n addGroupMember(groupId: string, handle: string, opts?: CallOptions) {\n return this.post<AddMemberResult>(\n `/v1/groups/${encodeURIComponent(groupId)}/members`,\n { handle },\n opts,\n )\n }\n\n removeGroupMember(groupId: string, handle: string, opts?: CallOptions) {\n return this.del<{ message: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}`,\n opts,\n )\n }\n\n promoteGroupMember(groupId: string, handle: string, opts?: CallOptions) {\n return this.post<{ message: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}/promote`,\n undefined,\n opts,\n )\n }\n\n demoteGroupMember(groupId: string, handle: string, opts?: CallOptions) {\n return this.post<{ message: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}/demote`,\n undefined,\n opts,\n )\n }\n\n /**\n * Leave the group. If you are the last admin, the earliest-joined\n * member is auto-promoted so the group never becomes leaderless.\n * `promoted_handle` is that new admin (or `null` when there was no\n * promotion — either there was already another admin, or the group\n * is now empty).\n */\n leaveGroup(groupId: string, opts?: CallOptions) {\n return this.post<{ message: string; promoted_handle: string | null }>(\n `/v1/groups/${encodeURIComponent(groupId)}/leave`,\n undefined,\n opts,\n )\n }\n\n listGroupInvites(opts?: CallOptions) {\n return this.get<GroupInvitation[]>('/v1/groups/invites', opts)\n }\n\n acceptGroupInvite(inviteId: string, opts?: CallOptions) {\n return this.post<GroupDetail>(\n `/v1/groups/invites/${encodeURIComponent(inviteId)}/accept`,\n undefined,\n opts,\n )\n }\n\n rejectGroupInvite(inviteId: string, opts?: CallOptions) {\n return this.del<{ message: string }>(\n `/v1/groups/invites/${encodeURIComponent(inviteId)}`,\n opts,\n )\n }\n\n // ─── Contacts ─────────────────────────────────────────────────────────────\n\n addContact(handle: string, opts?: CallOptions) {\n return this.post<ContactEntry>('/v1/contacts', { handle }, opts)\n }\n\n listContacts(options?: { limit?: number; offset?: number } & CallOptions) {\n const params = new URLSearchParams()\n if (options?.limit) params.set('limit', String(options.limit))\n if (options?.offset) params.set('offset', String(options.offset))\n const qs = params.toString()\n return this.get<ContactListResult>(`/v1/contacts${qs ? `?${qs}` : ''}`, options)\n }\n\n /**\n * Async-iterate every contact across all pages. Use this when you want\n * the full list without hand-rolling the limit/offset loop.\n *\n * @example\n * for await (const contact of client.contacts({ pageSize: 200 })) {\n * console.log(contact.handle)\n * }\n */\n contacts(options?: { pageSize?: number; max?: number } & CallOptions) {\n return paginate(\n async (offset, limit) => {\n const page = await this.listContacts({ offset, limit, ...options })\n return { items: page.contacts, total: page.total, limit: page.limit, offset: page.offset }\n },\n { pageSize: options?.pageSize, max: options?.max },\n )\n }\n\n checkContact(handle: string, opts?: CallOptions) {\n return this.get<ContactCheckResult>(\n `/v1/contacts/${encodeURIComponent(handle)}`,\n opts,\n )\n }\n\n updateContactNotes(handle: string, notes: string | null, opts?: CallOptions) {\n return this.patch<void>(\n `/v1/contacts/${encodeURIComponent(handle)}`,\n { notes },\n opts,\n )\n }\n\n removeContact(handle: string, opts?: CallOptions) {\n return this.del<void>(`/v1/contacts/${encodeURIComponent(handle)}`, opts)\n }\n\n blockAgent(handle: string, opts?: CallOptions) {\n return this.post<void>(\n `/v1/contacts/${encodeURIComponent(handle)}/block`,\n undefined,\n opts,\n )\n }\n\n unblockAgent(handle: string, opts?: CallOptions) {\n return this.del<void>(\n `/v1/contacts/${encodeURIComponent(handle)}/block`,\n opts,\n )\n }\n\n reportAgent(handle: string, reason?: string, opts?: CallOptions) {\n return this.post<void>(\n `/v1/contacts/${encodeURIComponent(handle)}/report`,\n reason ? { reason } : {},\n opts,\n )\n }\n\n // ─── Mutes ────────────────────────────────────────────────────────────────\n //\n // Mute suppresses real-time WebSocket push from a specific agent or\n // conversation without blocking/leaving. Envelopes still land in\n // `/v1/messages/sync` and the unread counter still bumps — the muter\n // catches up on their own schedule. The sender sees a normal \"delivered\"\n // receipt; no mute signal leaks across the wire.\n //\n // All mute APIs are idempotent:\n // - Re-muting with a different `mutedUntil` refreshes the expiry.\n // - Unmuting a non-muted target returns 404; callers that only care\n // about the end state can ignore it.\n\n muteAgent(handle: string, options?: { mutedUntil?: string | null } & CallOptions) {\n return this.post<MuteEntry>('/v1/mutes', {\n target_kind: 'agent',\n target_handle: handle,\n muted_until: options?.mutedUntil ?? null,\n }, options)\n }\n\n muteConversation(\n conversationId: string,\n options?: { mutedUntil?: string | null } & CallOptions,\n ) {\n return this.post<MuteEntry>('/v1/mutes', {\n target_kind: 'conversation',\n target_id: conversationId,\n muted_until: options?.mutedUntil ?? null,\n }, options)\n }\n\n unmuteAgent(handle: string, opts?: CallOptions) {\n return this.del<void>(`/v1/mutes/agent/${encodeURIComponent(handle)}`, opts)\n }\n\n unmuteConversation(conversationId: string, opts?: CallOptions) {\n return this.del<void>(\n `/v1/mutes/conversation/${encodeURIComponent(conversationId)}`,\n opts,\n )\n }\n\n listMutes(options?: { kind?: MuteTargetKind } & CallOptions) {\n const params = new URLSearchParams()\n if (options?.kind) params.set('kind', options.kind)\n const qs = params.toString()\n return this.get<MuteListResult>(`/v1/mutes${qs ? `?${qs}` : ''}`, options)\n }\n\n /**\n * Returns `null` if there is no active mute for `handle`; returns the\n * `MuteEntry` otherwise. Swallows the 404 that the server emits for the\n * not-muted case — on the SDK surface `null` is the natural \"nothing\n * here\" signal.\n */\n async getAgentMuteStatus(handle: string, opts?: CallOptions): Promise<MuteEntry | null> {\n try {\n return await this.get<MuteEntry>(\n `/v1/mutes/agent/${encodeURIComponent(handle)}`,\n opts,\n )\n } catch (err) {\n if (err instanceof AgentChatError && err.status === 404) return null\n throw err\n }\n }\n\n async getConversationMuteStatus(\n conversationId: string,\n opts?: CallOptions,\n ): Promise<MuteEntry | null> {\n try {\n return await this.get<MuteEntry>(\n `/v1/mutes/conversation/${encodeURIComponent(conversationId)}`,\n opts,\n )\n } catch (err) {\n if (err instanceof AgentChatError && err.status === 404) return null\n throw err\n }\n }\n\n // ─── Presence ─────────────────────────────────────────────────────────────\n\n getPresence(handle: string, opts?: CallOptions) {\n return this.get<Presence>(`/v1/presence/${encodeURIComponent(handle)}`, opts)\n }\n\n updatePresence(req: PresenceUpdate, opts?: CallOptions) {\n return this.put<Presence>('/v1/presence', req, opts)\n }\n\n /** Query presence for up to 100 handles in a single round-trip. */\n getPresenceBatch(handles: string[], opts?: CallOptions) {\n return this.post<{ presences: Presence[] }>('/v1/presence/batch', { handles }, opts)\n }\n\n // ─── Directory ────────────────────────────────────────────────────────────\n\n /**\n * Look up agents by handle prefix. AgentChat's directory is **handle-only**\n * — this is a phone-book lookup, not a fuzzy search over names, roles, or\n * bios. Pass a full handle for an exact match, or a prefix to autocomplete.\n * Queries are bounded to 2–50 characters server-side; `offset` is capped\n * at 10,000.\n *\n * **Bearer auth required.** As of platform release 2026-05-15 the directory\n * is no longer anonymous-accessible — every call must carry a valid API\n * key. The SDK handles this for you whenever the client is constructed\n * with an `apiKey`.\n *\n * **Per-agent rate limits**, keyed on your API key (not your IP):\n * - 60 lookups per minute (burst)\n * - 1,000 lookups per rolling 24h (sustained)\n *\n * Both stack. Hitting either returns a 429 with `Retry-After`. The cap\n * only applies to this directory endpoint — listing contacts, checking\n * a specific contact, listing conversations, and sending to known handles\n * are separate paths with their own (much higher) budgets.\n *\n * For general agent discovery (beyond knowing a handle out-of-band), see\n * the MoltBook product — discovery does not happen inside AgentChat.\n */\n searchAgents(\n query: string,\n options?: { limit?: number; offset?: number } & CallOptions,\n ) {\n const params = new URLSearchParams({ q: query })\n if (options?.limit) params.set('limit', String(options.limit))\n if (options?.offset) params.set('offset', String(options.offset))\n return this.get<DirectoryResult>(`/v1/directory?${params.toString()}`, options)\n }\n\n /**\n * Async-iterate every directory match for `query` (handle-prefix lookup).\n * Delivers one agent at a time across paginated fetches — handy for wiring\n * into a pipe that consumes results on the fly.\n */\n searchAgentsAll(\n query: string,\n options?: { pageSize?: number; max?: number } & CallOptions,\n ) {\n return paginate(\n async (offset, limit) => {\n const page = await this.searchAgents(query, { offset, limit, ...options })\n return { items: page.agents, total: page.total, limit: page.limit, offset: page.offset }\n },\n { pageSize: options?.pageSize, max: options?.max },\n )\n }\n\n // ─── Attachments ──────────────────────────────────────────────────────────\n\n /**\n * Request an attachment upload slot. The response includes a short-lived\n * presigned `upload_url` — PUT the file bytes there immediately (the URL\n * is usually valid for under a minute). Then reference the returned\n * `attachment_id` in a `sendMessage()` call's `content.attachment_id`.\n */\n createUpload(req: CreateUploadRequest, opts?: CallOptions) {\n return this.post<CreateUploadResponse>('/v1/uploads', req, opts)\n }\n\n /**\n * Resolve an attachment id to a signed download URL. The server responds\n * with a 302 redirect to a short-lived Supabase Storage URL; this method\n * captures the Location header instead of following the redirect (so the\n * SDK's `Authorization: Bearer …` doesn't leak to the storage backend).\n *\n * The returned URL is single-use and expires within minutes — consume it\n * immediately (fetch the bytes, stream to a file, or embed in a UI).\n * Authorization is enforced on this call, not on the presigned URL, so\n * sender/recipient scoping applies.\n */\n async getAttachmentDownloadUrl(attachmentId: string, opts?: CallOptions): Promise<string> {\n const response = await this.http.request<never>(\n 'GET',\n `/v1/attachments/${encodeURIComponent(attachmentId)}`,\n { ...this.toRequestOpts(opts), followRedirect: false },\n )\n const location = response.headers.get('location')\n if (!location) {\n throw new Error(\n `attachments: server did not return a redirect Location for ${attachmentId} (status=${response.status})`,\n )\n }\n return location\n }\n\n // ─── Sync / read-state ────────────────────────────────────────────────────\n\n /**\n * Fetch undelivered envelopes accumulated while the realtime stream was\n * disconnected. Returns a **bare array** of rows, oldest first — see\n * `SyncEnvelope` for the shape and cursor semantics.\n *\n * Non-destructive: nothing is marked delivered until `syncAck()` is called\n * with the last non-null `delivery_id` of the rows you actually processed\n * (positional cursor — `delivery_id` is opaque, never compare it\n * numerically). `after` pages forward without committing anything: pass\n * the last `delivery_id` of the previous batch.\n *\n * The WebSocket client drives this automatically on reconnect; most\n * callers never need it directly.\n */\n sync(opts?: { limit?: number; after?: string } & CallOptions) {\n const params = new URLSearchParams()\n if (opts?.limit) params.set('limit', String(opts.limit))\n if (opts?.after !== undefined) params.set('after', opts.after)\n const qs = params.toString()\n return this.get<SyncEnvelope[]>(`/v1/messages/sync${qs ? `?${qs}` : ''}`, opts)\n }\n\n /**\n * Commit every delivery at-or-before the cursor as delivered.\n * `lastDeliveryId` is the opaque string cursor from a `sync()` row.\n * Returns the number of envelopes that transitioned to `delivered`\n * (0 is a normal outcome — e.g. a repeated ack, or an ack while the\n * agent is owner-paused).\n */\n syncAck(lastDeliveryId: string, opts?: CallOptions) {\n return this.post<{ acked: number }>(\n '/v1/messages/sync/ack',\n { last_delivery_id: lastDeliveryId },\n opts,\n )\n }\n}\n","/**\n * Runtime-dependent WebSocket resolution.\n *\n * - On Node, the `ws` package (an optional peer dependency) is preferred\n * whenever it is installed: it exposes the server's ping frames\n * (`on('ping')`) and `terminate()`, which the realtime client's liveness\n * watchdog needs to tell a quiet-but-healthy socket from a dead pipe.\n * Node's native `WebSocket` (22+) shows neither, so a long-lived\n * integration on it would get no idle watchdog at all. Without `ws`, the\n * native socket is used. Node 20 has no native socket: `ws` is required.\n * - Browsers, Deno, Bun and edge runtimes ship a native `WebSocket` on\n * `globalThis`; it is used directly, with `ws` only as a last resort.\n * - No implementation anywhere is a configuration error: the caller's\n * `connect()` rejects and nothing retries it.\n *\n * Deliberately stateless: the module system already caches the dynamic\n * import, and a module-level memo would be the one piece of process-wide\n * state in an SDK that is meant to run as a guest inside a host process.\n */\n\ntype WebSocketCtor = typeof globalThis.WebSocket\n\nfunction isNode(): boolean {\n const versions = (globalThis as { process?: { versions?: { node?: unknown } } }).process\n ?.versions\n return typeof versions?.node === 'string'\n}\n\nasync function importWs(): Promise<WebSocketCtor> {\n // Built as an ESM dynamic import. tsup preserves the expression so\n // bundlers / runtimes that can't resolve `ws` simply reject here and the\n // caller falls through to the native socket.\n const mod = (await import('ws')) as unknown as {\n default?: WebSocketCtor\n WebSocket?: WebSocketCtor\n }\n const ctor = mod.default ?? mod.WebSocket\n if (!ctor) {\n throw new Error('The `ws` package loaded but did not export a WebSocket constructor.')\n }\n return ctor\n}\n\nexport async function resolveWebSocket(): Promise<WebSocketCtor> {\n const native = (globalThis as { WebSocket?: WebSocketCtor }).WebSocket\n // Order: on Node `ws`, then native; everywhere else native, then `ws`.\n if (!isNode() && native) return native\n\n let wsFailure: unknown\n try {\n return await importWs()\n } catch (err) {\n wsFailure = err\n }\n if (native) return native\n\n const reason = wsFailure instanceof Error ? wsFailure.message : String(wsFailure)\n throw new Error(\n `AgentChat SDK: no WebSocket implementation available. ${reason}\\n` +\n 'Install the `ws` package: Node 20 has no native WebSocket, and on Node 22+ `ws` ' +\n 'also gives the realtime client ping-frame liveness.',\n )\n}\n","import type { WsMessage, Message, WakeFrame } from './types/index.js'\nimport type { AgentChatClient, SyncEnvelope } from './client.js'\nimport { ConnectionError } from './errors.js'\nimport { resolveWebSocket } from './ws-resolver.js'\nimport {\n DEFAULT_CLIENT_IDENTITY,\n type AgentChatClientIdentity,\n} from './client-identity.js'\n\n/**\n * Handlers may be async. For `message.new`, completion matters: when the\n * server negotiated delivery acks, the ack is sent only after every handler\n * settled without throwing — a rejected handler leaves the message unacked\n * so the server re-offers it (at-least-once; the dedup cache absorbs the\n * eventual duplicate of anything that DID succeed). With `ackOnReceipt` the\n * ack goes out before handlers run and completion no longer gates it.\n */\nexport type MessageHandler = (message: WsMessage) => void | Promise<void>\n/** Handler for `wake` frames: a content-free \"check AgentChat\" signal. */\nexport type WakeHandler = (frame: WakeFrame) => void | Promise<void>\nexport type ErrorHandler = (error: Error) => void\n\n/**\n * Fired once per successful HELLO_ACK. Useful for updating UI (\"connected\"\n * state), (re)subscribing to typing indicators, emitting metrics, etc.\n * Not guaranteed to be called on the initial connect — only after a\n * handshake completes.\n */\nexport type ConnectHandler = () => void\n\n/** Close information handed to `onDisconnect` on every socket close. */\nexport interface DisconnectInfo {\n code: number\n reason: string\n wasClean: boolean\n /**\n * Who ended the socket. `'client'` is this client's own watchdog (the\n * handshake or liveness deadline): such a close says nothing about the\n * server and always takes the normal reconnect backoff. `'server'` is a\n * close that arrived on the wire — the server, a proxy, or the network.\n */\n initiator: 'client' | 'server'\n}\n\n/** Fired on every socket close, regardless of reason. */\nexport type DisconnectHandler = (info: DisconnectInfo) => void\n\n/**\n * Connection lifecycle. `stopped` is the only terminal state and only\n * `disconnect()` reaches it; every other state leads back to `connecting`\n * on its own.\n *\n * - `idle` — no socket and nothing scheduled: before the first `connect()`,\n * or after a close with `reconnect: false`.\n * - `connecting` — a socket is opening, or its HELLO awaits `hello.ok`.\n * - `ready` — `hello.ok` received; frames flow.\n * - `backoff` — the socket closed; the next attempt is scheduled with\n * exponential backoff.\n * - `blocked` — the server rejected the credential during the handshake; a\n * fresh attempt is scheduled every 10–15 minutes until one is accepted.\n * - `stopped` — `disconnect()` was called.\n */\nexport type RealtimeState = 'idle' | 'connecting' | 'ready' | 'backoff' | 'blocked' | 'stopped'\nexport type StateHandler = (state: RealtimeState, previous: RealtimeState) => void\n\n/** Why the client is `blocked`, and when it will try again. */\nexport interface BlockedInfo {\n /** Close code the server rejected the handshake with: 4401, 4403 or 1008. */\n code: number\n /** The server's close reason, e.g. `Invalid token`. */\n reason: string\n /** Milliseconds until the next automatic attempt; `null` when `reconnect` is off. */\n retryInMs: number | null\n}\nexport type BlockedHandler = (info: BlockedInfo) => void\nexport type StoppedHandler = () => void\n\nexport interface SequenceGapInfo {\n conversationId: string\n // The seq we were waiting for when the gap window expired.\n expectedSeq: number\n // The lowest seq we had buffered above the expected — what triggered\n // the gap detection. Null when the gap was discovered some other way\n // (e.g. buffer overflow without a clear \"next\" arrival).\n bufferedSeq: number | null\n // Wall-clock duration we waited before resolving the gap, in ms.\n gapMs: number\n // True iff getMessages successfully returned the missing rows and we\n // dispatched them in order before any higher seqs. False means we\n // gave up and emitted whatever we had (possibly skipping some seqs\n // forever — caller should /sync to fully reconcile).\n recovered: boolean\n reason:\n | 'gap_filled'\n | 'gap_fill_failed'\n | 'gap_fill_unavailable'\n | 'buffer_overflow'\n // ackOnReceipt only: the socket closed while frames sat in the gap\n // buffer. They were already acknowledged, so they were handed to the\n // handlers in seq order instead of being dropped (see the option).\n | 'connection_closed'\n}\n\nexport type SequenceGapHandler = (info: SequenceGapInfo) => void\n\nexport interface RealtimeOptions {\n apiKey: string\n baseUrl?: string\n /**\n * Product-integration identity included in every HELLO frame. Leave unset\n * for direct SDK use (`typescript_sdk/<SDK version>`).\n */\n clientIdentity?: AgentChatClientIdentity\n /**\n * Reconnect after every close that is not `disconnect()`. Default: `true`.\n * With `false` the client goes `idle` after a close and waits for the next\n * `connect()`; it never reconnects or retries on its own.\n */\n reconnect?: boolean\n /**\n * Initial reconnect delay in milliseconds. Each consecutive failure\n * doubles it, jittered up to 25% below the step, up to\n * `maxReconnectInterval` (a true ceiling). Default: 500ms.\n */\n reconnectInterval?: number\n /**\n * Cap on the delay between reconnect attempts for the first 60 consecutive\n * failures. Default: 30s. After 60 consecutive failures the cap widens to\n * five minutes (or this value, if larger), one error is emitted through\n * `onError`, and the client keeps trying forever. There is no attempt\n * limit: only `disconnect()` ends the client.\n */\n maxReconnectInterval?: number\n /**\n * @deprecated Ignored — the client never gives up on its own; only\n * `disconnect()` ends it. Kept so existing call sites compile.\n */\n maxReconnectAttempts?: number\n /**\n * Optional client used for in-order recovery AND for the post-reconnect\n * `/v1/messages/sync` drain.\n *\n * - **Gap recovery**: when the realtime feed sees a per-conversation seq\n * gap (e.g. `seq=8` then `seq=12`), the client waits briefly for\n * natural arrival, then calls `getMessages(conversationId, { afterSeq })`\n * to pull the missing rows and emit them in order.\n * - **Reconnect drain**: after every successful `hello.ok`, the client\n * calls `/v1/messages/sync` to pull envelopes that accumulated while\n * disconnected, dispatches them through the same `message.new`\n * pipeline, and acknowledges with `/v1/messages/sync/ack`.\n *\n * Without a `client`, neither recovery path is available — gaps fire\n * `onSequenceGap` with `recovered: false`, and offline envelopes sit\n * in the server-side queue until the application calls `sync()`\n * manually.\n */\n client?: AgentChatClient\n /**\n * Fired whenever a per-conversation seq gap is detected and resolved\n * (one way or the other). Use this to emit metrics, log incidents,\n * or trigger an explicit `/sync` if `recovered: false`.\n */\n onSequenceGap?: SequenceGapHandler\n /**\n * Disable the automatic post-reconnect `/v1/messages/sync` drain. On by\n * default when a `client` is provided. Turn off if you prefer to run\n * sync on your own schedule.\n */\n autoDrainOnConnect?: boolean\n /**\n * Capacity of the bounded LRU cache of recently-dispatched message ids,\n * shared by the live WebSocket path and the offline drain. Delivery is\n * at-least-once — the same message legitimately arrives twice after a\n * lost ack or a drain/live overlap — and the cache suppresses the\n * duplicate dispatch while still acknowledging receipt. Default: 2048.\n */\n dedupCacheSize?: number\n /**\n * Acknowledge each `message.new` the moment its frame is parsed, before\n * any handler runs. This is the integration setting: \"delivered\" then\n * means the agent's machine received the message, and whether the agent\n * has looked is tracked separately as read state (a verdict or\n * `client.conversations.markRead`), so an early ack never empties the\n * tray. Covers live frames, the server's reconnect backlog and gap-fill\n * rows; the REST offline drain keeps its settle-then-ack cursor. Default\n * `false`: ack after every handler settled, for app clients whose\n * handler IS the processing.\n *\n * Trade-off: an acked frame is never re-offered by the server, so a frame\n * that is parked on a seq gap when the socket drops is handed to the\n * handlers at close time, in seq order but possibly ahead of the seqs it\n * was waiting for (which arrive after the reconnect). Ack-on-receipt\n * trades strict ordering across a connection drop for no loss; the\n * default mode keeps ordering because unacked frames come back in order\n * on the next drain. Such a flush fires `onSequenceGap` with\n * `reason: 'connection_closed'`.\n */\n ackOnReceipt?: boolean\n /**\n * Override the WebSocket constructor. Defaults to `globalThis.WebSocket`\n * with a dynamic-import fallback to the `ws` package (for Node 20).\n * Tests use this to inject a mock. Users on a polyfilled environment\n * can supply their own implementation — anything that matches the\n * browser WebSocket shape (`onopen/onmessage/onclose/onerror`, `send`,\n * `close`, `readyState`) works.\n *\n * On Node the default resolution prefers `WebSocket` from the `ws`\n * package when it is installed and falls back to the native socket only\n * without it: `ws` exposes the server's ping frames (`on('ping')`), which\n * lets the liveness watchdog tell a quiet-but-healthy socket from a dead\n * one. The browser-shaped socket (including Node's native one) cannot see\n * pings — see `livenessTimeoutMs`. Pass a constructor only to override.\n */\n webSocket?: typeof globalThis.WebSocket\n /**\n * Handshake deadline: milliseconds from `connect()` to `hello.ok`. A\n * half-open upgrade or a server that never answers HELLO is closed by the\n * client at this point and reconnected with the normal backoff. The\n * server's own HELLO timer is 5 s, so this is the safety net for a dead\n * pipe, not the common path. Default: 15 000.\n */\n handshakeTimeoutMs?: number\n /**\n * Idle deadline: milliseconds without any inbound frame — or, on a socket\n * that exposes them, a ping — before the connection is presumed dead,\n * closed by the client and reconnected. The server pings every 45 s, so\n * the default (100 000) survives one missed ping and trips on the second.\n *\n * Ping frames are visible only on a socket with `on('ping')` (Node `ws`).\n * A browser-shaped socket cannot see them, so there the idle deadline is\n * OFF unless set explicitly: only application frames would keep it alive,\n * and an idle but healthy connection would otherwise be reopened every\n * cycle. `0` disables it on any socket; the handshake deadline stays.\n */\n livenessTimeoutMs?: number\n}\n\n/** Handshake deadline, `connect()` → `hello.ok`. See `handshakeTimeoutMs`. */\nconst DEFAULT_HANDSHAKE_TIMEOUT_MS = 15_000\n\n/** Idle deadline on ping-capable sockets: two server ping cycles (45 s) plus slack. */\nconst DEFAULT_LIVENESS_TIMEOUT_MS = 100_000\n\n/**\n * Close code this client uses when its own watchdog ends a socket. In the\n * private-use range so a browser socket accepts it (browsers allow only 1000\n * and 3000–4999 from `close()`). On a Node `ws` socket the watchdog\n * terminates instead, which sends no close frame at all — a dead pipe would\n * otherwise hold a polite close open for up to 30 s waiting for a reply.\n */\nconst CLIENT_CLOSE_CODE = 4000\n\n/**\n * After this many consecutive failures the outage is long: one error is\n * emitted for the operator and the backoff cap widens to\n * LONG_OUTAGE_MAX_INTERVAL_MS. Retrying continues until the server is back —\n * a deploy, a DNS outage or a laptop closed overnight is not a reason to\n * stay dead afterwards.\n */\nconst LONG_OUTAGE_AFTER_ATTEMPTS = 60\nconst LONG_OUTAGE_MAX_INTERVAL_MS = 5 * 60_000\n\n/**\n * Reconnect delays are jittered up to 25% BELOW each step: a fleet that\n * drops together spreads back out, and the documented caps stay true\n * ceilings (30 s, then 5 min — never 37.5 s or 6.25 min).\n */\nconst RECONNECT_JITTER_RATIO = 0.25\n\n/**\n * After the server rejects the credential, retry a fresh HELLO at this\n * cadence (±20% jitter → 10–15 min). A rejected key is not a dead end: keys\n * get rotated back, suspended accounts get reinstated, and a server-side\n * lookup failure during HELLO presents as a reject too.\n */\nconst AUTH_RETRY_INTERVAL_MS = 750_000\nconst AUTH_RETRY_JITTER_RATIO = 0.2\n\n// Close codes that mean \"the server rejected this credential\" when the\n// SERVER sends them during the handshake. 4401/4403 are unambiguous. 1008\n// (policy violation) is not: the server closes a rejected HELLO with\n// 1008 'Invalid token', but also uses 1008 for a handshake that was merely\n// too slow ('HELLO frame required', from its own 5 s timer), and a database\n// failure during auth ends as that same timer close. So 1008 counts as a\n// rejection only with the server's auth reason; any other 1008 takes the\n// normal backoff. A close this client initiated never counts, whatever code\n// it carries. These codes after `hello.ok` (the server evicts a rotated key\n// or a suspended account with 1008 and its own reasons) are an eviction, not\n// a verdict: the next HELLO is the evidence, so they take the normal path.\nconst UNAMBIGUOUS_AUTH_CLOSE_CODES: ReadonlySet<number> = new Set([4401, 4403])\nconst AMBIGUOUS_AUTH_CLOSE_CODE = 1008\nconst SERVER_AUTH_CLOSE_REASONS: readonly string[] = ['invalid token']\n\n/**\n * True iff a server-originated close with this code and reason, received\n * before `hello.ok`, means the credential was rejected. Pure; exported so\n * integrations and tests share one definition.\n */\nexport function isAuthRejectionClose(code: number, reason: string): boolean {\n if (UNAMBIGUOUS_AUTH_CLOSE_CODES.has(code)) return true\n if (code !== AMBIGUOUS_AUTH_CLOSE_CODE) return false\n if (typeof reason !== 'string') return false\n const lower = reason.toLowerCase()\n return SERVER_AUTH_CLOSE_REASONS.some((known) => lower.includes(known))\n}\n\n// A Node `ws` socket is an EventEmitter and surfaces ping/pong frames; the\n// browser shape has neither `on` nor the frames.\ntype PingCapableSocket = WebSocket & {\n on(event: 'ping' | 'pong', listener: () => void): unknown\n}\nfunction isPingCapable(ws: WebSocket): ws is PingCapableSocket {\n return typeof (ws as { on?: unknown }).on === 'function'\n}\n\n// Never hold a Node process open for a watchdog or a counter reset; the\n// socket itself (or a pending reconnect) is what keeps a daemon alive.\nfunction unref(timer: ReturnType<typeof setTimeout>): void {\n ;(timer as { unref?: () => void }).unref?.()\n}\n\n/**\n * How long a connection must SURVIVE before we call it healthy and clear\n * the reconnect backoff.\n *\n * \"The handshake succeeded\" is not the same claim as \"this connection\n * works\". Resetting the attempt counter on `hello.ok` alone means a socket\n * that connects and dies seconds later always retries at the floor delay —\n * the exponential backoff can then never engage, because it only ever\n * counts attempts that failed BEFORE the handshake. A client in that state\n * reconnects forever with no ramp at all: observed in production as 725\n * connections in four hours from one agent, delivering zero messages,\n * while sibling agents on the same host held single connections.\n *\n * 30s is comfortably longer than any handshake-adjacent failure (the\n * handshake deadline is 15s, the server heartbeat cycle 45s) and short\n * enough that a healthy client clears its counter well before a second blip.\n */\nconst STABLE_CONNECTION_MS = 30_000\n\n/** Reconnects faster than this count as \"rapid\" for the instability warning. */\nconst RAPID_RECONNECT_MS = 60_000\n\n/**\n * Consecutive rapid reconnects before we warn the operator. This failure is\n * invisible from inside the agent — every reconnect succeeds, so nothing\n * looks broken locally while the connection is unusable in practice.\n */\nconst INSTABILITY_WARN_THRESHOLD = 5\n\n// How long we wait for the missing seqs to arrive naturally (e.g. via the\n// pub/sub fan-out catching up to the drain) before triggering an explicit\n// gap-fill round-trip. Two seconds is well below the perceptual floor for\n// agent loops (which tick in hundreds of ms minimum) and well above the\n// typical drain↔live-fanout interleave window (10–100 ms). The cost when\n// no real gap exists is zero — the timer is started lazily on detection\n// and cancelled the moment the missing seq arrives.\nconst GAP_FILL_WINDOW_MS = 2_000\n\n// Hard cap on how many out-of-order messages we hold per conversation\n// before draining unconditionally. Prevents memory blow-up if a sender\n// publishes wildly off-sequence or a server bug emits seqs in the wrong\n// order at high volume. 500 is well above realistic burst sizes (group\n// fan-out batches at 100), so we only hit this in true pathologies — at\n// which point we surface it via onSequenceGap and continue.\nconst MAX_BUFFERED_PER_CONVERSATION = 500\n\n// Cap on how many messages we'll request from the server in one gap-fill\n// round-trip. If the gap is bigger than this, recovery is best-effort and\n// the application should call /sync afterwards to fully reconcile. The\n// onSequenceGap callback fires with recovered:false if we couldn't close\n// the gap completely.\nconst GAP_FILL_LIMIT = 200\n\n// Page size for the post-reconnect /v1/messages/sync drain. Matches the\n// server default (200, hard-capped at 500 server-side); a response shorter\n// than this is the server saying \"caught up\".\nconst SYNC_DRAIN_PAGE_SIZE = 200\n\n// Default capacity of the message-id dedup cache. See\n// RealtimeOptions.dedupCacheSize.\nconst DEFAULT_DEDUP_CACHE_SIZE = 2048\n\n// Minimal structural validation of one sync row, mirroring the reference\n// wire schema (docs/realtime-delivery-ack.md): id / conversation_id /\n// delivery_id (string|null) are required; optional fields are type-checked\n// only when present; unknown fields pass through untouched. The drain stops\n// at the FIRST invalid row and never acks past it — acking past an unparsed\n// row would mark a message delivered that was never surfaced to handlers.\nfunction isValidSyncRow(row: unknown): row is SyncEnvelope {\n if (typeof row !== 'object' || row === null || Array.isArray(row)) return false\n const r = row as Record<string, unknown>\n if (typeof r.id !== 'string') return false\n if (typeof r.conversation_id !== 'string') return false\n if (typeof r.delivery_id !== 'string' && r.delivery_id !== null) return false\n for (const key of ['sender', 'sender_handle', 'type', 'created_at'] as const) {\n if (r[key] !== undefined && typeof r[key] !== 'string') return false\n }\n if (\n r.content !== undefined &&\n (typeof r.content !== 'object' || r.content === null || Array.isArray(r.content))\n ) {\n return false\n }\n return true\n}\n\n// Latest ackable cursor from a batch of rows (rows arrive oldest-first).\n// The cursor is POSITIONAL: delivery_id is an opaque string, so \"latest\"\n// means \"last non-null in batch order\", never a numeric comparison.\nfunction lastDeliveryId(rows: SyncEnvelope[]): string | null {\n for (let i = rows.length - 1; i >= 0; i--) {\n const id = rows[i]?.delivery_id\n if (typeof id === 'string' && id.length > 0) return id\n }\n return null\n}\n\nfunction isThenable(value: unknown): value is Promise<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\nfunction toError(reason: unknown, context: string): Error {\n return reason instanceof Error\n ? reason\n : new Error(`${context} handler failed: ${String(reason)}`)\n}\n\ninterface OrderState {\n // The next seq we expect to dispatch. Null means we're un-anchored —\n // the next `message.new` with a numeric seq sets this to seq + 1.\n // Re-set to null on disconnect so the post-reconnect /sync drain can\n // re-anchor without false gap detections across the connection break.\n nextExpectedSeq: number | null\n // Out-of-order messages waiting on a missing earlier seq. Keyed by\n // seq for O(1) lookup during the consecutive-drain pass.\n buffer: Map<number, WsMessage>\n gapTimer: ReturnType<typeof setTimeout> | null\n gapStartedAt: number | null\n // The seq we were waiting on when the gap timer started. Used so a\n // later arrival of an even-higher seq doesn't reset the timer or\n // confuse the gap report.\n gapStartedExpectedSeq: number | null\n // True while a getMessages call is in flight, so a re-detect of the\n // same gap doesn't kick off a parallel fetch.\n gapFillInFlight: boolean\n}\n\nexport class RealtimeClient {\n private ws: WebSocket | null = null\n private options: {\n apiKey: string\n baseUrl: string\n reconnect: boolean\n reconnectInterval: number\n maxReconnectInterval: number\n handshakeTimeoutMs: number\n /** `null` = decide per socket: on with ping frames, off without. */\n livenessTimeoutMs: number | null\n client?: AgentChatClient\n onSequenceGap?: SequenceGapHandler\n autoDrainOnConnect: boolean\n dedupCacheSize: number\n ackOnReceipt: boolean\n webSocket?: typeof globalThis.WebSocket\n clientIdentity: AgentChatClientIdentity\n }\n private handlers = new Map<string, Set<MessageHandler>>()\n private errorHandlers = new Set<ErrorHandler>()\n private connectHandlers = new Set<ConnectHandler>()\n private disconnectHandlers = new Set<DisconnectHandler>()\n private stateHandlers = new Set<StateHandler>()\n private blockedHandlers = new Set<BlockedHandler>()\n private stoppedHandlers = new Set<StoppedHandler>()\n private _state: RealtimeState = 'idle'\n /** Consecutive failed attempts; drives the backoff. Cleared by the stability timer only. */\n private reconnectAttempts = 0\n /** Clears reconnectAttempts once this connection proves itself stable. */\n private stabilityTimer: ReturnType<typeof setTimeout> | null = null\n /** Consecutive connections that died before STABLE_CONNECTION_MS. Drives\n * the operator warning only; backoff itself uses reconnectAttempts. */\n private rapidReconnects = 0\n private lastConnectAt: number | null = null\n /** The pending backoff or blocked-retry timer — at most one at a time. */\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null\n /** Handshake deadline: armed by connect(), cleared by hello.ok or close. */\n private handshakeTimer: ReturnType<typeof setTimeout> | null = null\n /** Idle deadline: armed by hello.ok; inbound frames and pings refresh it. */\n private livenessTimer: ReturnType<typeof setTimeout> | null = null\n /** Idle deadline in effect for the current socket; 0 = off. */\n private livenessMs = 0\n private lastInboundAt = 0\n private authenticated = false\n // True only when the server echoed the 'ack' capability in hello.ok.\n // Per-connection: reset on every close and re-negotiated on every HELLO.\n private ackMode = false\n /** One error per long outage, then silent until a stable connection. */\n private longOutageAnnounced = false\n /** One error per run of rejected handshakes, then silent until hello.ok. */\n private blockedAnnounced = false\n // Bounded LRU of recently-dispatched message ids (Set iteration order is\n // insertion order — delete + re-add refreshes recency). Ids are added\n // only AFTER a successful dispatch: adding earlier would let a failed\n // dispatch suppress its own redelivery.\n private dedupSeen = new Set<string>()\n // Envelopes injected by the REST drain, as opposed to live WS frames.\n // Drain rows are acknowledged via the REST sync/ack cursor, never via a\n // WS ack frame; everything else on the message.new pipeline (live frames,\n // server-pushed reconnect backlog, gap-fill rows) takes the WS ack path\n // when ack-mode is negotiated.\n private restDrainOrigin = new WeakSet<WsMessage>()\n // Per-envelope dispatch settlement for drain rows: resolves true when\n // every handler settled cleanly (or the row deduped), false when a\n // handler threw/rejected. The drain awaits these before advancing the\n // ack cursor. WeakMap so entries die with the envelope objects.\n private drainSettlements = new WeakMap<WsMessage, Promise<boolean>>()\n // Coalesces concurrent drains — the server-side ack pointer only moves\n // forward, so one drain at a time is both sufficient and simpler to\n // reason about than interleaved read cursors.\n private drainInFlight = false\n private orderStates = new Map<string, OrderState>()\n private disposed = false\n\n constructor(options: RealtimeOptions) {\n const dedupCacheSize =\n typeof options.dedupCacheSize === 'number' &&\n Number.isFinite(options.dedupCacheSize) &&\n options.dedupCacheSize >= 1\n ? Math.floor(options.dedupCacheSize)\n : DEFAULT_DEDUP_CACHE_SIZE\n const handshakeTimeoutMs =\n typeof options.handshakeTimeoutMs === 'number' &&\n Number.isFinite(options.handshakeTimeoutMs) &&\n options.handshakeTimeoutMs > 0\n ? options.handshakeTimeoutMs\n : DEFAULT_HANDSHAKE_TIMEOUT_MS\n const livenessTimeoutMs =\n typeof options.livenessTimeoutMs === 'number' &&\n Number.isFinite(options.livenessTimeoutMs) &&\n options.livenessTimeoutMs >= 0\n ? options.livenessTimeoutMs\n : null\n this.options = {\n baseUrl: options.baseUrl ?? 'wss://api.agentchat.me',\n reconnect: options.reconnect ?? true,\n reconnectInterval: options.reconnectInterval ?? 500,\n maxReconnectInterval: options.maxReconnectInterval ?? 30_000,\n handshakeTimeoutMs,\n livenessTimeoutMs,\n apiKey: options.apiKey,\n client: options.client,\n onSequenceGap: options.onSequenceGap,\n autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),\n dedupCacheSize,\n ackOnReceipt: options.ackOnReceipt ?? false,\n webSocket: options.webSocket,\n clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY,\n }\n }\n\n /**\n * Open the WebSocket connection and perform the HELLO handshake.\n * Resolves once the socket has been constructed and its handlers bound —\n * NOT after `hello.ok`. Listen for `onConnect()` or `on('state')` to react\n * to a completed handshake.\n *\n * Also the way to retry at once: called while `backoff` or `blocked`, it\n * cancels the pending timer and opens a socket now. A no-op while a socket\n * is already connecting or connected. Throws after `disconnect()` — create\n * a fresh `RealtimeClient` instead. Rejects, without retrying, when no\n * WebSocket implementation exists (neither `ws` nor a native one): that is\n * a configuration error and the client stays `idle`.\n */\n async connect(): Promise<void> {\n if (this.disposed) {\n throw new ConnectionError('RealtimeClient has been disposed; create a new instance to reconnect.')\n }\n if (this.ws) return\n this.clearReconnectTimer()\n\n let WebSocketCtor: typeof globalThis.WebSocket\n try {\n WebSocketCtor = this.options.webSocket ?? (await resolveWebSocket())\n } catch (err) {\n // No WebSocket implementation anywhere is a configuration error, not\n // an outage: nothing a retry could change. Reject so the caller sees\n // it, and stay idle rather than announce the same error every backoff.\n this.setState('idle')\n throw err instanceof Error ? err : new ConnectionError('Failed to resolve WebSocket')\n }\n // disconnect() or a concurrent connect() may have run during the await.\n if (this.disposed || this.ws) return\n\n this.setState('connecting')\n\n // Authenticate via HELLO frame (not URL). Browser WebSocket cannot set\n // custom headers, so this is the only cross-runtime path. The API key\n // never appears in the URL, access logs, or Referer headers.\n const url = `${this.options.baseUrl}/v1/ws`\n let ws: WebSocket\n try {\n ws = new WebSocketCtor(url)\n } catch (err) {\n // A constructor that throws (bad URL, host refusing to create sockets)\n // is a failed attempt like any other: it backs off, it does not end\n // the client.\n const error = err instanceof Error ? err : new ConnectionError('WebSocket constructor threw')\n this.emitError(error)\n this.scheduleReconnect()\n throw error\n }\n this.ws = ws\n this.authenticated = false\n this.ackMode = false\n this.livenessMs =\n this.options.livenessTimeoutMs ?? (isPingCapable(ws) ? DEFAULT_LIVENESS_TIMEOUT_MS : 0)\n this.armHandshakeDeadline()\n\n // Every handler checks that it still speaks for the current socket. A\n // socket the watchdog abandoned (or disconnect() closed) was dealt with\n // the moment we let go of it; its own late events — a close that arrives\n // seconds later from a dead pipe, an error from an aborted upgrade —\n // must not touch the state machine again. The handlers stay attached\n // (never detached) because a Node `ws` socket with no error listener\n // turns an error event into an uncaught exception.\n const current = (): boolean => this.ws === ws\n\n ws.onopen = () => {\n if (!current()) return\n try {\n // Advertise the delivery-ack capability (docs/realtime-delivery-ack.md).\n // Legacy servers ignore unknown HELLO fields; ack-mode turns on only\n // if hello.ok echoes the capability back.\n ws.send(\n JSON.stringify({\n type: 'hello',\n api_key: this.options.apiKey,\n capabilities: ['ack'],\n client: this.options.clientIdentity.name,\n ...(this.options.clientIdentity.version\n ? { client_version: this.options.clientIdentity.version }\n : {}),\n }),\n )\n } catch (err) {\n this.emitError(err instanceof Error ? err : new ConnectionError('HELLO send failed'))\n // A socket that cannot carry the HELLO cannot carry anything; the\n // handshake deadline would end it anyway, so end it now.\n this.abandonSocket(CLIENT_CLOSE_CODE, 'client HELLO send failed')\n }\n }\n\n ws.onmessage = (event: MessageEvent) => {\n if (!current()) return\n // Any inbound frame is proof of life, parseable or not.\n this.touchLiveness()\n\n let message: WsMessage\n try {\n message = JSON.parse(String(event.data)) as WsMessage\n } catch {\n return\n }\n\n // Intercept the handshake ACK — never surfaces to user handlers.\n if (!this.authenticated) {\n if ((message as { type?: string }).type === 'hello.ok') {\n this.authenticated = true\n // Capability negotiation: ack-mode only if the server echoed\n // 'ack' back. A hello.ok without capabilities is a legacy server\n // (marks envelopes delivered on send); sending ack frames to it\n // would just be unknown frames.\n const caps = (message as { capabilities?: unknown }).capabilities\n this.ackMode = Array.isArray(caps) && caps.includes('ack')\n this.clearHandshakeTimer()\n // The idle deadline takes over from the handshake deadline.\n this.touchLiveness()\n // reconnectAttempts is deliberately NOT reset here. A successful\n // handshake proves the credential, not the connection — see\n // STABLE_CONNECTION_MS. The counter clears from the timer below,\n // and only if we are still connected 30s from now.\n this.startStabilityTimer()\n // The credential was accepted: a later rejection is a new event.\n this.blockedAnnounced = false\n this.setState('ready')\n for (const handler of this.connectHandlers) {\n try { handler() } catch { /* user hook must not break flow */ }\n }\n if (this.options.autoDrainOnConnect && this.options.client) {\n // Fire-and-forget by design, but never an unhandled rejection:\n // anything that escapes the drain's internal error handling\n // still surfaces through the standard error channel.\n this.drainOfflineEnvelopes().catch((err) => {\n this.emitError(\n err instanceof Error ? err : new ConnectionError('sync drain failed'),\n )\n })\n }\n }\n return\n }\n\n // Per-conversation seq ordering applies only to message.new — every\n // other event type (presence, group.deleted, message.read, system\n // messages without a seq) passes straight through.\n if (this.isMessageNew(message)) {\n // Ack-on-receipt: the frame is parsed, the machine has it. Sent\n // before ordering so a frame parked on a seq gap is already\n // delivered; the post-dispatch ack is suppressed for this mode.\n if (this.options.ackOnReceipt) {\n const messageId = this.extractMessageId(message)\n if (messageId !== null) this.sendAckFrame(messageId)\n }\n this.processOrderedMessage(message)\n return\n }\n if (this.isWake(message)) {\n this.dispatchWake(message)\n return\n }\n this.dispatch(message)\n }\n\n ws.onerror = () => {\n if (!current()) return\n this.emitError(new ConnectionError('WebSocket error'))\n }\n\n ws.onclose = (event: CloseEvent) => {\n if (!current()) return\n this.ws = null\n this.handleClose({\n code: event.code,\n // A polyfilled socket may omit the reason; the rejection rule\n // lowercases it, so it must be a string here.\n reason: String(event.reason ?? ''),\n wasClean: event.wasClean,\n initiator: 'server',\n })\n }\n\n // Node `ws`: the server's ping frames (every 45 s) are proof of life\n // too. The library answers them on its own; here they only refresh the\n // idle deadline, which is what lets a quiet socket stay up.\n if (isPingCapable(ws)) {\n const alive = (): void => {\n if (current()) this.touchLiveness()\n }\n ws.on('ping', alive)\n ws.on('pong', alive)\n }\n }\n\n /**\n * Drain offline envelopes accumulated while the socket was disconnected.\n * Automatically invoked on every successful `hello.ok` when\n * `autoDrainOnConnect` is enabled and a client is configured.\n *\n * `GET /v1/messages/sync` returns a **bare array** of rows, oldest first\n * (see `SyncEnvelope`). Each page is dispatched through the same ordered\n * `message.new` pipeline as live frames, then acknowledged via\n * `POST /v1/messages/sync/ack` with a **positional** cursor — the last\n * non-null `delivery_id` of the fully-processed prefix. `delivery_id` is\n * an opaque string and is never compared numerically. Pages are fetched\n * with the `after` read cursor (non-committing) until a short page.\n *\n * Correctness rules, in cursor order:\n * - A row failing minimal validation stops the drain: the clean prefix\n * before it is processed and acked; the cursor never crosses the row.\n * - A row whose handler threw is not acked — nor is anything after it\n * (the ack cursor is at-or-before) — so the server re-offers it; the\n * dedup cache suppresses re-dispatch of its acked predecessors.\n * - A row parked in the out-of-order buffer (awaiting seq gap-fill) is\n * not acked until actually dispatched: acks FREEZE at the last settled\n * row for the remainder of the drain. Without this, a disconnect that\n * clears the ordering buffers (`resetOrderStates`) would silently drop\n * an already-acked message — acked-but-undispatched is exactly the\n * loss the ack protocol exists to prevent. Reading continues so the\n * in-session gap-fill still resolves; the frozen tail is re-offered on\n * the next drain and absorbed by the dedup cache.\n *\n * Concurrent calls are coalesced (the second returns immediately). The\n * server-side ack pointer only moves forward, so re-running after a\n * partial drain is always safe. REST-drained rows are acked via this\n * cursor, never via WS ack frames.\n */\n async drainOfflineEnvelopes(): Promise<void> {\n const client = this.options.client\n if (!client) return\n if (this.drainInFlight) return\n this.drainInFlight = true\n try {\n await this.runDrain(client)\n } finally {\n this.drainInFlight = false\n }\n }\n\n private async runDrain(client: AgentChatClient): Promise<void> {\n let after: string | undefined\n let acksFrozen = false\n\n while (!this.disposed) {\n let batch: SyncEnvelope[]\n try {\n batch = await client.sync({ after, limit: SYNC_DRAIN_PAGE_SIZE })\n } catch (err) {\n this.emitError(err instanceof Error ? err : new ConnectionError('sync drain failed'))\n return\n }\n\n // Defensive against the exact class of bug this path once shipped\n // (SDK/server wire drift): anything but an array is a contract\n // violation, not an empty queue.\n if (!Array.isArray(batch)) {\n this.emitError(\n new ConnectionError(\n `sync drain: expected a bare array from /v1/messages/sync, got ${typeof batch}`,\n ),\n )\n return\n }\n // disconnect() may have run while the request was in flight — the\n // handler map is cleared, so dispatching (and then acking) would\n // mark messages delivered that no handler ever saw.\n if (this.disposed) return\n if (batch.length === 0) return\n\n // Keep only the clean prefix — stop at the FIRST invalid row rather\n // than skipping it (the ack cursor covers everything at-or-before).\n const rows: SyncEnvelope[] = []\n let invalidIndex = -1\n for (const [index, item] of batch.entries()) {\n if (!isValidSyncRow(item)) {\n invalidIndex = index\n break\n }\n rows.push(item)\n }\n\n // Inject the prefix into the ordered pipeline. Dispatch STARTS\n // synchronously and in order; settlement of async handlers is\n // awaited below, before the ack cursor moves.\n const envelopes: WsMessage[] = rows.map((row) => {\n const envelope: WsMessage = {\n type: 'message.new',\n payload: row as unknown as Record<string, unknown>,\n }\n this.restDrainOrigin.add(envelope)\n return envelope\n })\n for (const envelope of envelopes) {\n this.processOrderedMessage(envelope)\n }\n\n if (!acksFrozen) {\n let ackCursor: string | null = null\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]\n const envelope = envelopes[i]\n if (!row || !envelope) break // unreachable; satisfies indexed access\n const settlement = this.drainSettlements.get(envelope)\n if (settlement) {\n const ok = await settlement\n if (!ok) {\n // Handler failure — leave this row and everything after it\n // unacked so the server re-offers them.\n acksFrozen = true\n break\n }\n } else if (this.isBufferedInOrderState(row)) {\n // Parked on a seq gap — not dispatched yet. See the stranding\n // note in the method doc.\n acksFrozen = true\n break\n }\n // Reaching here means the row is safe to cover with the cursor:\n // its dispatch settled cleanly, or it was a dedup hit (already\n // dispatched by this process — prior processing is the proof).\n // Every drain row that is not parked on a seq gap reaches\n // dispatchMessageNew, below-anchor rows included, so a settlement\n // always exists for it.\n const deliveryId = row.delivery_id\n if (typeof deliveryId === 'string' && deliveryId.length > 0) {\n ackCursor = deliveryId\n }\n }\n if (ackCursor !== null) {\n try {\n await client.syncAck(ackCursor)\n } catch (err) {\n this.emitError(err instanceof Error ? err : new ConnectionError('sync ack failed'))\n return\n }\n }\n }\n\n if (invalidIndex >= 0) {\n this.emitError(\n new ConnectionError(\n `sync drain: row ${invalidIndex} failed validation — processed the ` +\n `${rows.length}-row prefix and stopped; the ack cursor was not advanced past it`,\n ),\n )\n return\n }\n\n // A short page means the server is caught up.\n if (batch.length < SYNC_DRAIN_PAGE_SIZE) return\n\n // Page forward with the read cursor (non-committing). A page whose\n // delivery ids are all null offers no way to make progress — stop\n // rather than spin re-reading the same rows.\n const nextAfter = lastDeliveryId(rows)\n if (nextAfter === null) return\n after = nextAfter\n }\n }\n\n // True when a drain row is currently parked in the per-conversation\n // out-of-order buffer (its dispatch is deferred to the gap-fill\n // machinery — natural arrival, gap-fill fetch, or forced resolveGap).\n private isBufferedInOrderState(row: SyncEnvelope): boolean {\n if (typeof row.seq !== 'number') return false\n const state = this.orderStates.get(row.conversation_id)\n return state !== undefined && state.buffer.has(row.seq)\n }\n\n /**\n * Clear the reconnect backoff once this connection proves itself.\n *\n * Scheduled on `hello.ok`, cancelled on close. If it fires, the socket\n * has been up for STABLE_CONNECTION_MS and the next failure deserves to\n * start from the floor again. If it is cancelled, the connection died\n * young and the counter carries forward, so the delay keeps ramping\n * toward the cap.\n */\n private startStabilityTimer(): void {\n this.cancelStabilityTimer()\n this.lastConnectAt = Date.now()\n this.stabilityTimer = setTimeout(() => {\n this.stabilityTimer = null\n if (this.disposed || !this.authenticated) return\n this.reconnectAttempts = 0\n this.rapidReconnects = 0\n // The outage is over; the next one gets its own announcement.\n this.longOutageAnnounced = false\n }, STABLE_CONNECTION_MS)\n unref(this.stabilityTimer)\n }\n\n private cancelStabilityTimer(): void {\n if (this.stabilityTimer) {\n clearTimeout(this.stabilityTimer)\n this.stabilityTimer = null\n }\n }\n\n /**\n * Track short-lived connections and warn once they form a pattern.\n * A flapping client looks healthy from the inside — every reconnect\n * succeeds — so without this the operator has no local signal at all.\n * The notice goes through `onError` like every other signal: an SDK\n * that runs as a guest inside a host process does not own its console.\n */\n private noteConnectionEnded(): void {\n const started = this.lastConnectAt\n this.lastConnectAt = null\n if (started === null) return\n\n if (Date.now() - started >= RAPID_RECONNECT_MS) {\n this.rapidReconnects = 0\n return\n }\n\n this.rapidReconnects++\n if (this.rapidReconnects === INSTABILITY_WARN_THRESHOLD) {\n this.emitError(\n new ConnectionError(\n `realtime connection is unstable: ${this.rapidReconnects} consecutive ` +\n `connections each lasting under ${RAPID_RECONNECT_MS / 1000}s. Backing off ` +\n `(next retry in up to ${this.options.maxReconnectInterval / 1000}s). This ` +\n `usually means the network path or a local supervisor is dropping the ` +\n `socket, not an AgentChat outage.`,\n ),\n )\n }\n }\n\n // ─── Lifecycle: close funnel, backoff, blocked, watchdogs ───────────────\n //\n // Invariant: the client never parks itself. Every close leads to a timer\n // (backoff or blocked retry) or, with `reconnect: false`, to `idle` where\n // the application's next connect() picks up. Only disconnect() ends it.\n\n /**\n * The single funnel for \"this socket is over\", whoever ended it. Runs\n * after `this.ws` has been let go of, so nothing here touches the socket\n * again. Decides what comes next — backoff, blocked or idle, never nothing.\n */\n private handleClose(info: DisconnectInfo): void {\n const duringHandshake = !this.authenticated\n this.clearWatchdogs()\n // Cancel BEFORE clearing `authenticated`: a connection that dies young\n // must not clear the backoff counter — that is the whole point of the\n // stability window.\n this.cancelStabilityTimer()\n this.noteConnectionEnded()\n this.authenticated = false\n this.ackMode = false\n\n for (const handler of this.disconnectHandlers) {\n try { handler(info) } catch { /* user hook must not break flow */ }\n }\n\n // Ack-on-receipt: every frame parked on a seq gap was acknowledged at\n // parse, so the server has it `delivered` and will never re-offer it.\n // Dropping the buffer here would lose it for good — the exact loss the\n // ack protocol exists to prevent. Hand the parked frames to the\n // handlers now, in seq order, before the state goes. Default mode\n // skips this: its parked frames are unacked and come back in order on\n // the next drain.\n if (this.options.ackOnReceipt) this.flushParkedFrames('connection_closed')\n\n // Drop all per-conversation ordering state. Across the connection\n // break the application is responsible for calling /sync (or\n // enabling `autoDrainOnConnect`), which re-establishes the cursor\n // via the next message.new arrival. Leaving stale nextExpectedSeq\n // values would cause spurious gap detections after reconnect when\n // a /sync drain delivers higher-seq rows than what live previously\n // emitted.\n this.resetOrderStates()\n\n if (this.disposed) return\n\n // Only a close the SERVER sent, before hello.ok, with a code and reason\n // that mean rejection, is a rejection. Our own watchdog closes say\n // nothing about the server, whatever code they carry; an eviction after\n // hello.ok takes the normal path and the next HELLO decides.\n if (\n info.initiator === 'server' &&\n duringHandshake &&\n isAuthRejectionClose(info.code, info.reason)\n ) {\n this.enterBlocked(info.code, info.reason)\n return\n }\n\n this.scheduleReconnect()\n }\n\n /**\n * End the current socket on the client's own decision (a watchdog trip,\n * a HELLO that could not be sent) and move on at once, without waiting for\n * the socket's close event: on a dead pipe a polite close waits for a\n * reply that never comes. Terminated where the API allows it (Node `ws`),\n * closed otherwise; its own late events are ignored because it is no\n * longer `this.ws`.\n */\n private abandonSocket(code: number, reason: string): void {\n const ws = this.ws\n if (!ws) return\n this.ws = null\n const terminate = (ws as { terminate?: () => void }).terminate\n try {\n if (typeof terminate === 'function') terminate.call(ws)\n else ws.close(code, reason)\n } catch { /* already closed */ }\n this.handleClose({ code, reason, wasClean: false, initiator: 'client' })\n }\n\n private scheduleReconnect(): void {\n if (this.disposed) return\n if (this.reconnectTimer) return\n if (!this.options.reconnect) {\n this.setState('idle')\n return\n }\n\n this.reconnectAttempts++\n const attempt = this.reconnectAttempts\n if (attempt > LONG_OUTAGE_AFTER_ATTEMPTS && !this.longOutageAnnounced) {\n // Once per outage: the operator should know the control plane has\n // been unreachable this long. Retrying goes on at the wider cap.\n this.longOutageAnnounced = true\n this.emitError(\n new ConnectionError(\n `still reconnecting after ${LONG_OUTAGE_AFTER_ATTEMPTS} consecutive failed attempts; ` +\n `backing off to at most ${Math.round(this.longOutageCap() / 1000)}s between ` +\n 'attempts and not giving up',\n ),\n )\n }\n\n const delay = this.computeReconnectDelay(attempt)\n this.setState('backoff')\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null\n this.retryNow()\n }, delay)\n }\n\n /**\n * The server rejected the credential. `blocked` is not the end: a fresh\n * HELLO goes out every AUTH_RETRY_INTERVAL_MS (jittered) until one is\n * accepted — keys get rotated back and accounts get reinstated, and the\n * running client has no other way to learn it. The first rejection of a\n * run is an error; the following ones only fire `blocked`, so an operator\n * sees one line per incident rather than one every quarter hour.\n */\n private enterBlocked(code: number, reason: string): void {\n const retryInMs = this.options.reconnect\n ? this.jittered(AUTH_RETRY_INTERVAL_MS, AUTH_RETRY_JITTER_RATIO)\n : null\n this.setState('blocked')\n\n if (!this.blockedAnnounced) {\n this.blockedAnnounced = true\n this.emitError(\n new ConnectionError(\n `server rejected the credential (close ${code}${reason ? ` ${reason}` : ''}); ` +\n (retryInMs !== null\n ? `retrying with a fresh HELLO in about ${Math.round(retryInMs / 60_000)} min ` +\n 'and every 10–15 min after that until it is accepted again'\n : 'reconnect is off, so call connect() to try again'),\n ),\n )\n }\n\n const info: BlockedInfo = { code, reason, retryInMs }\n for (const handler of this.blockedHandlers) {\n try { handler(info) } catch { /* user hook must not break flow */ }\n }\n\n if (retryInMs === null) return\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null\n this.retryNow()\n }, retryInMs)\n }\n\n /**\n * The timer-driven attempt. connect() emits and re-arms on its own for\n * every failure it retries (a throwing constructor, a close); the one\n * failure it does not retry — no WebSocket implementation at all — left\n * nothing armed, so it is announced here: the operator should see why the\n * client went quiet.\n */\n private retryNow(): void {\n void this.connect().catch((err) => {\n if (this.disposed || this.ws || this.reconnectTimer) return\n this.emitError(err instanceof Error ? err : new ConnectionError(String(err)))\n })\n }\n\n private clearReconnectTimer(): void {\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer)\n this.reconnectTimer = null\n }\n }\n\n private computeReconnectDelay(attempt: number): number {\n const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 20))\n // A long outage widens the cap: a down control plane is polled every few\n // minutes instead of every `maxReconnectInterval`, for as long as it takes.\n const cap =\n attempt > LONG_OUTAGE_AFTER_ATTEMPTS ? this.longOutageCap() : this.options.maxReconnectInterval\n return this.jitteredBelow(Math.min(exp, cap), RECONNECT_JITTER_RATIO)\n }\n\n private longOutageCap(): number {\n return Math.max(this.options.maxReconnectInterval, LONG_OUTAGE_MAX_INTERVAL_MS)\n }\n\n /** Symmetric ±ratio jitter around `ms` — for the blocked retry, a range (10–15 min), not a cap. */\n private jittered(ms: number, ratio: number): number {\n const factor = 1 - ratio + Math.random() * 2 * ratio\n return Math.max(0, Math.floor(ms * factor))\n }\n\n /** Jitter in [ms × (1 − ratio), ms]: `ms` is a ceiling. Thundering-herd-safe across a fleet. */\n private jitteredBelow(ms: number, ratio: number): number {\n const factor = 1 - Math.random() * ratio\n return Math.max(0, Math.floor(ms * factor))\n }\n\n private armHandshakeDeadline(): void {\n this.clearHandshakeTimer()\n const ms = this.options.handshakeTimeoutMs\n this.handshakeTimer = setTimeout(() => {\n this.handshakeTimer = null\n this.emitError(new ConnectionError(`handshake timeout: no hello.ok within ${ms}ms`))\n this.abandonSocket(CLIENT_CLOSE_CODE, 'client handshake timeout')\n }, ms)\n unref(this.handshakeTimer)\n }\n\n /**\n * Note proof of life (any inbound frame, or a ping/pong on a socket that\n * shows them). The timer itself is lazy: it is armed once per connection\n * and, when it fires early because traffic arrived meanwhile, re-arms for\n * the remainder — one `Date.now()` per frame instead of a timer churn.\n */\n private touchLiveness(): void {\n this.lastInboundAt = Date.now()\n if (this.livenessTimer === null) this.armLiveness(this.livenessMs)\n }\n\n private armLiveness(ms: number): void {\n if (this.livenessMs <= 0 || !this.ws || !this.authenticated) return\n this.livenessTimer = setTimeout(() => {\n this.livenessTimer = null\n const quietFor = Date.now() - this.lastInboundAt\n if (quietFor < this.livenessMs) {\n this.armLiveness(this.livenessMs - quietFor)\n return\n }\n this.emitError(\n new ConnectionError(`liveness timeout: nothing received for ${this.livenessMs}ms`),\n )\n this.abandonSocket(CLIENT_CLOSE_CODE, 'client liveness timeout')\n }, Math.max(1, ms))\n unref(this.livenessTimer)\n }\n\n private clearHandshakeTimer(): void {\n if (this.handshakeTimer) {\n clearTimeout(this.handshakeTimer)\n this.handshakeTimer = null\n }\n }\n\n private clearWatchdogs(): void {\n this.clearHandshakeTimer()\n if (this.livenessTimer) {\n clearTimeout(this.livenessTimer)\n this.livenessTimer = null\n }\n }\n\n private setState(next: RealtimeState): void {\n const previous = this._state\n if (previous === next) return\n this._state = next\n for (const handler of this.stateHandlers) {\n try { handler(next, previous) } catch { /* user hook must not break flow */ }\n }\n }\n\n /**\n * Subscribe to one event type. `wake` handlers receive a typed\n * `WakeFrame`; the frame carries no message and is never acknowledged.\n * Returns an unsubscribe function.\n *\n * Three events are the client's own rather than server frames:\n * - `state` — every transition of `state` (see `RealtimeState`).\n * - `blocked` — the server rejected the credential during the handshake;\n * carries the close code, reason and the delay to the next attempt.\n * - `stopped` — `disconnect()` was called; fired once, before handlers\n * are released.\n */\n on(event: 'wake', handler: WakeHandler): () => void\n on(event: 'state', handler: StateHandler): () => void\n on(event: 'blocked', handler: BlockedHandler): () => void\n on(event: 'stopped', handler: StoppedHandler): () => void\n on(event: string, handler: MessageHandler): () => void\n on(\n event: string,\n handler: MessageHandler | WakeHandler | StateHandler | BlockedHandler | StoppedHandler,\n ): () => void {\n // Lifecycle events live in their own sets: a server frame that happened\n // to be typed 'state' must never reach them through dispatch.\n switch (event) {\n case 'state':\n return this.subscribe(this.stateHandlers, handler as StateHandler)\n case 'blocked':\n return this.subscribe(this.blockedHandlers, handler as BlockedHandler)\n case 'stopped':\n return this.subscribe(this.stoppedHandlers, handler as StoppedHandler)\n default:\n break\n }\n let handlers = this.handlers.get(event)\n if (!handlers) {\n handlers = new Set()\n this.handlers.set(event, handlers)\n }\n // A validated wake frame is a WsMessage whose payload is a WakePayload;\n // dispatchWake guarantees the shape before any 'wake' handler runs.\n const stored = handler as MessageHandler\n handlers.add(stored)\n return () => {\n handlers!.delete(stored)\n if (handlers!.size === 0) this.handlers.delete(event)\n }\n }\n\n private subscribe<T>(set: Set<T>, handler: T): () => void {\n set.add(handler)\n return () => {\n set.delete(handler)\n }\n }\n\n /**\n * Every signal the client has for its operator comes through here:\n * transport errors, handler failures, the watchdog and backoff notices\n * (`handshake timeout`, `liveness timeout`, `still reconnecting after\n * 60 …`, `server rejected the credential …`, `connection is unstable`).\n * The SDK never writes to the console.\n */\n onError(handler: ErrorHandler): () => void {\n this.errorHandlers.add(handler)\n return () => this.errorHandlers.delete(handler)\n }\n\n /** Fires each time the handshake completes (initial + every reconnect). */\n onConnect(handler: ConnectHandler): () => void {\n this.connectHandlers.add(handler)\n return () => this.connectHandlers.delete(handler)\n }\n\n /** Fires on every socket close, regardless of reason (clean or error). */\n onDisconnect(handler: DisconnectHandler): () => void {\n this.disconnectHandlers.add(handler)\n return () => this.disconnectHandlers.delete(handler)\n }\n\n send(message: WsMessage): void {\n // `WebSocket.OPEN` is 1 per the spec — hardcode rather than reading\n // from `WebSocket.OPEN`, which is only available as a static on\n // whichever constructor we resolved (native vs `ws`).\n if (!this.ws || this.ws.readyState !== 1 || !this.authenticated) {\n throw new ConnectionError('WebSocket is not connected')\n }\n this.ws.send(JSON.stringify(message))\n }\n\n /**\n * Announce that the caller has started composing in `conversationId`.\n * Fire-and-forget: server broadcasts a `typing.start` event to every\n * other participant but does not ACK. Pair with `sendTypingStop` when\n * the agent finishes composing or navigates away. Throws\n * `ConnectionError` if the socket is not open.\n */\n sendTypingStart(conversationId: string): void {\n this.send({ type: 'typing.start', payload: { conversation_id: conversationId } })\n }\n\n /** Counterpart to `sendTypingStart`. */\n sendTypingStop(conversationId: string): void {\n this.send({ type: 'typing.stop', payload: { conversation_id: conversationId } })\n }\n\n /**\n * Push a read receipt. `throughSeq` means \"every message up to and\n * including this seq is read\". The server fans out a `message.read`\n * event to other participants. Cheap to call repeatedly; send the\n * highest seq observed per conversation.\n */\n sendReadAck(conversationId: string, throughSeq: number): void {\n this.send({\n type: 'message.read_ack',\n payload: { conversation_id: conversationId, through_seq: throughSeq },\n })\n }\n\n /** `true` after a completed HELLO handshake and before the next close. */\n get isConnected(): boolean {\n return this.authenticated && this.ws?.readyState === 1\n }\n\n /** Where the connection lifecycle is right now. See `RealtimeState`. */\n get state(): RealtimeState {\n return this._state\n }\n\n /**\n * `true` when the current connection's `hello.ok` echoed the `ack`\n * capability: the server keeps each envelope `stored` until this client\n * acknowledges it. `false` before `hello.ok`, after a close, and against\n * a legacy server (which marks envelopes delivered on push).\n */\n get ackNegotiated(): boolean {\n return this.ackMode\n }\n\n /**\n * Close the socket, cancel every timer, and release all handlers. The\n * only way into `stopped`, and the only way the client ever stops on\n * purpose: works from any state (`blocked` and a pending backoff\n * included). `stopped` fires once. After this, `connect()` throws —\n * create a fresh `RealtimeClient` if you want to reopen.\n */\n disconnect(): void {\n if (this.disposed) return\n this.disposed = true\n this.options.reconnect = false\n this.clearReconnectTimer()\n this.clearWatchdogs()\n this.cancelStabilityTimer()\n // Flush any buffered envelopes synchronously so the caller doesn't\n // miss them after disconnect(). No gap-fill — we're tearing down,\n // and an in-flight HTTP request would race the close.\n this.flushParkedFrames('gap_fill_unavailable')\n const ws = this.ws\n this.ws = null\n try { ws?.close(1000, 'client disconnect') } catch { /* already closed */ }\n this.authenticated = false\n this.ackMode = false\n this.setState('stopped')\n for (const handler of this.stoppedHandlers) {\n try { handler() } catch { /* user hook must not break flow */ }\n }\n this.handlers.clear()\n this.errorHandlers.clear()\n this.connectHandlers.clear()\n this.disconnectHandlers.clear()\n this.stateHandlers.clear()\n this.blockedHandlers.clear()\n this.stoppedHandlers.clear()\n }\n\n private emitError(error: Error): void {\n for (const handler of this.errorHandlers) {\n // Every notice is emitted right before the step that keeps the client\n // alive (arming a timer, opening the next socket). A throwing observer\n // must not take that step with it — that would be the one way into a\n // parked client.\n try { handler(error) } catch { /* user hook must not break flow */ }\n }\n }\n\n private dispatch(message: WsMessage): void {\n if (this.isMessageNew(message)) {\n // message.new rides the dedup + delivery-ack pipeline. Handlers are\n // still invoked synchronously and in order here; only settlement\n // (async handler completion → ack) is deferred. The returned promise\n // never rejects.\n void this.dispatchMessageNew(message)\n return\n }\n const handlers = this.handlers.get(message.type)\n if (!handlers) return\n for (const handler of handlers) {\n try {\n const result = handler(message)\n if (isThenable(result)) {\n result.catch((err) => this.emitError(toError(err, message.type)))\n }\n } catch (err) {\n // A throwing handler must not break dispatch to the remaining\n // handlers (or, upstream, the WebSocket message pump).\n this.emitError(toError(err, message.type))\n }\n }\n }\n\n /**\n * Dedup + dispatch + acknowledge one `message.new` envelope. Never\n * rejects.\n *\n * Resolves `true` when the envelope is safe to acknowledge: every\n * handler settled without throwing (async handlers awaited), or the\n * message id was already in the dedup cache — prior successful\n * processing is the proof, so a duplicate skips dispatch but is still\n * acked. Resolves `false` when any handler threw or rejected: the\n * message is NOT acked on any path and the server re-offers it.\n *\n * Ack routing: live frames (including server-pushed reconnect backlog\n * and gap-fill rows) send a WS `{type:'ack'}` frame when ack-mode was\n * negotiated; REST-drain rows are covered by the drain's sync/ack\n * cursor instead — the drain awaits this settlement before advancing\n * that cursor.\n */\n private dispatchMessageNew(message: WsMessage): Promise<boolean> {\n const isDrainRow = this.restDrainOrigin.has(message)\n const messageId = this.extractMessageId(message)\n // Drain rows are covered by the REST cursor; ack-on-receipt frames were\n // acked at parse (or at gap-fill fetch) time. Everything else acks here,\n // once dispatch has settled.\n const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt\n\n let settlement: Promise<boolean>\n\n if (messageId !== null && this.dedupHit(messageId)) {\n settlement = Promise.resolve(true)\n if (ackAfterDispatch) this.sendAckFrame(messageId)\n } else {\n const handlers = this.handlers.get('message.new')\n const pending: Array<Promise<unknown>> = []\n if (handlers) {\n for (const handler of handlers) {\n try {\n const result = handler(message)\n if (isThenable(result)) pending.push(result)\n } catch (err) {\n pending.push(Promise.reject(err))\n }\n }\n }\n settlement = Promise.allSettled(pending).then((outcomes) => {\n let ok = true\n for (const outcome of outcomes) {\n if (outcome.status === 'rejected') {\n ok = false\n this.emitError(toError(outcome.reason, 'message.new'))\n }\n }\n if (!ok) return false\n if (messageId !== null) {\n this.dedupAdd(messageId)\n if (ackAfterDispatch) this.sendAckFrame(messageId)\n }\n return true\n })\n }\n\n if (isDrainRow) this.drainSettlements.set(message, settlement)\n return settlement\n }\n\n /**\n * Best-effort delivery ack for one processed message. No-op unless the\n * server negotiated ack-mode on this connection. Send failures are\n * swallowed by design: a dying socket leaves the envelope `stored`\n * server-side, the next drain re-offers it, and the dedup cache absorbs\n * the duplicate.\n */\n private sendAckFrame(messageId: string): void {\n if (!this.ackMode) return\n if (!this.ws || this.ws.readyState !== 1 || !this.authenticated) return\n try {\n this.ws.send(JSON.stringify({ type: 'ack', message_id: messageId }))\n } catch { /* socket teardown race — redelivery + dedup cover it */ }\n }\n\n // Membership check that also refreshes recency on a hit (Set iteration\n // order is insertion order, so delete + re-add moves the id to the back\n // of the eviction queue).\n private dedupHit(messageId: string): boolean {\n if (!this.dedupSeen.has(messageId)) return false\n this.dedupSeen.delete(messageId)\n this.dedupSeen.add(messageId)\n return true\n }\n\n private dedupAdd(messageId: string): void {\n this.dedupSeen.delete(messageId)\n this.dedupSeen.add(messageId)\n while (this.dedupSeen.size > this.options.dedupCacheSize) {\n const oldest = this.dedupSeen.values().next().value\n if (oldest === undefined) break\n this.dedupSeen.delete(oldest)\n }\n }\n\n private extractMessageId(message: WsMessage): string | null {\n const id = (message as { payload?: { id?: unknown } }).payload?.id\n return typeof id === 'string' && id.length > 0 ? id : null\n }\n\n private isMessageNew(message: WsMessage): boolean {\n return (message as { type?: string }).type === 'message.new'\n }\n\n private isWake(message: WsMessage): boolean {\n return (message as { type?: string }).type === 'wake'\n }\n\n /**\n * A `wake` frame is a content-free signal: validate the payload shape\n * (so `wake` handlers can trust the `WakeFrame` type), then dispatch. A\n * frame the server sent malformed is surfaced through `onError` rather\n * than handed to handlers as something it is not. Never acked — there is\n * no message to deliver.\n */\n private dispatchWake(message: WsMessage): void {\n const payload = (message as { payload?: unknown }).payload\n const reason = this.wakePayloadProblem(payload)\n if (reason !== null) {\n this.emitError(new ConnectionError(`wake frame failed validation: ${reason}`))\n return\n }\n this.dispatch(message)\n }\n\n private wakePayloadProblem(payload: unknown): string | null {\n if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {\n return 'payload is not an object'\n }\n const p = payload as Record<string, unknown>\n for (const key of ['reason', 'conversation_id', 'anchor_message_id', 'at'] as const) {\n if (typeof p[key] !== 'string' || p[key] === '') return `${key} is not a non-empty string`\n }\n if (typeof p.step !== 'number' || !Number.isInteger(p.step)) return 'step is not an integer'\n return null\n }\n\n // ─── Per-conversation seq ordering ───────────────────────────────────────\n //\n // Invariant: for any conversation_id, handlers see message.new envelopes\n // in seq-ascending order with no skipped or repeated seqs — except that a\n // frame older than this connection's anchor (a stored row the drain brings\n // after a live frame anchored the conversation, or a seq a failed gap-fill\n // skipped) is dispatched late rather than dropped: never lost beats\n // strictly ordered, since the ack would otherwise bury it for good. The\n // dedup cache alone decides what is a repeat.\n //\n // Why per-conversation instead of global: seq numbers are minted per\n // conversation by send_message_atomic, so cross-conversation arrivals\n // have no ordering relationship to enforce.\n\n private processOrderedMessage(message: WsMessage): void {\n const payload = (message as { payload?: { conversation_id?: unknown; seq?: unknown } }).payload\n const conversationId = payload?.conversation_id\n\n // No conversation_id → not a real fan-out envelope. Pass through so a\n // malformed or extension envelope isn't silently dropped.\n if (typeof conversationId !== 'string') {\n this.dispatch(message)\n return\n }\n\n const seq = this.extractSeq(message)\n // System messages (e.g. server-emitted notices reusing message.new\n // shape) may not carry a numeric seq. Dispatch immediately rather\n // than blocking the per-conversation cursor on a non-orderable msg.\n if (seq === null) {\n this.dispatch(message)\n return\n }\n\n const state = this.getOrCreateOrderState(conversationId)\n\n // First arrival for this conversation in this connection — anchor.\n // We can't validate against history we never saw; the application\n // is responsible for running /sync if it cares about earlier rows.\n if (state.nextExpectedSeq === null) {\n state.nextExpectedSeq = seq + 1\n this.dispatch(message)\n return\n }\n\n if (seq < state.nextExpectedSeq) {\n // Below the anchor. With a first-arrival anchor this means \"older\n // than the first frame this connection saw\", NOT \"already\n // dispatched\": the server registers a socket before it drains the\n // stored backlog, so a live frame can anchor a conversation at seq 5\n // and the drain then brings stored seqs 3 and 4 that no handler has\n // ever seen. Dropping them here would lose them: the drain cursor (or\n // the ack-on-receipt frame) marks them delivered and the server never\n // re-offers them. The same holds for a seq skipped by a failed\n // gap-fill that arrives late. So hand the frame to dispatch, where the\n // dedup cache — the only evidence of a prior dispatch — decides: a hit\n // skips the handlers and acks, a miss dispatches (out of order, never\n // lost) and acks after.\n this.dispatch(message)\n return\n }\n\n if (seq === state.nextExpectedSeq) {\n // The expected next message — dispatch and try to drain any\n // higher-seq messages that were waiting on this one.\n this.dispatch(message)\n state.nextExpectedSeq = seq + 1\n this.drainConsecutive(conversationId, state)\n // The drain may have closed the gap that motivated a pending timer.\n this.maybeClearGapTimer(state)\n this.cleanupIfIdle(conversationId, state)\n return\n }\n\n // seq > nextExpectedSeq — out of order. Buffer and start the gap timer\n // if not already running.\n state.buffer.set(seq, message)\n\n if (state.buffer.size > MAX_BUFFERED_PER_CONVERSATION) {\n // Pathological: emit everything we have and skip past the gap.\n this.resolveGap(conversationId, state, {\n recovered: false,\n reason: 'buffer_overflow',\n bufferedSeq: this.minBufferedSeq(state),\n })\n return\n }\n\n if (state.gapTimer === null) {\n state.gapStartedAt = Date.now()\n state.gapStartedExpectedSeq = state.nextExpectedSeq\n state.gapTimer = setTimeout(() => {\n void this.handleGapTimer(conversationId)\n }, GAP_FILL_WINDOW_MS)\n }\n }\n\n private async handleGapTimer(conversationId: string): Promise<void> {\n const state = this.orderStates.get(conversationId)\n if (!state) return\n state.gapTimer = null\n\n // Race: the missing seq might have arrived while the timer was\n // queued (the dispatch-loop drain didn't trigger maybeClearGapTimer\n // because the timer was still ticking). If we're caught up, exit.\n if (state.buffer.size === 0) {\n this.cleanupIfIdle(conversationId, state)\n return\n }\n\n const expectedSeq = state.nextExpectedSeq\n if (expectedSeq === null) return // shouldn't happen, defensive\n\n // No client → can't gap-fill. Drain in seq order, advance past the\n // gap, surface the incident.\n if (!this.options.client) {\n this.resolveGap(conversationId, state, {\n recovered: false,\n reason: 'gap_fill_unavailable',\n bufferedSeq: this.minBufferedSeq(state),\n })\n return\n }\n\n // Already fetching (e.g. the timer fired again before the previous\n // call returned). Defer; the in-flight call will resolve everything.\n if (state.gapFillInFlight) return\n state.gapFillInFlight = true\n\n let fetched: Message[] = []\n let fillError = false\n try {\n // afterSeq is exclusive (seq > N), so subtract 1 to make the\n // expected seq inclusive. The server caps internally at GAP_FILL_LIMIT\n // worth of rows; we pass our own limit as a belt-and-braces.\n fetched = await this.options.client.getMessages(conversationId, {\n afterSeq: expectedSeq - 1,\n limit: GAP_FILL_LIMIT,\n })\n } catch {\n fillError = true\n } finally {\n state.gapFillInFlight = false\n }\n\n // The state may have been reset (disconnect during the await) — bail.\n const stateNow = this.orderStates.get(conversationId)\n if (!stateNow || stateNow !== state) return\n\n if (fillError) {\n this.resolveGap(conversationId, state, {\n recovered: false,\n reason: 'gap_fill_failed',\n bufferedSeq: this.minBufferedSeq(state),\n })\n return\n }\n\n // Insert fetched rows into the buffer (skip anything below our cursor —\n // shouldn't happen but defensive against server-side filtering changes).\n for (const row of fetched) {\n const rowSeq = typeof row.seq === 'number' ? row.seq : null\n if (rowSeq === null || rowSeq < expectedSeq) continue\n // Skip if already in buffer (the natural arrival beat us to it).\n if (state.buffer.has(rowSeq)) continue\n // Wrap as a message.new envelope for the dispatch path.\n const envelope: WsMessage = {\n type: 'message.new',\n payload: row as unknown as Record<string, unknown>,\n }\n // Ack-on-receipt: the fetch is this machine's receipt of the row.\n if (this.options.ackOnReceipt) {\n const messageId = this.extractMessageId(envelope)\n if (messageId !== null) this.sendAckFrame(messageId)\n }\n state.buffer.set(rowSeq, envelope)\n }\n\n // Drain consecutive starting from expectedSeq. If we still hit a gap\n // after draining (the server returned [9, 10, 12] when we needed 11),\n // that's a partial recovery — surface as recovered:false but keep\n // moving. The application should /sync to fully reconcile.\n const drainedThroughGap = this.drainConsecutive(conversationId, state)\n if (drainedThroughGap) {\n this.resolveGap(conversationId, state, {\n recovered: true,\n reason: 'gap_filled',\n bufferedSeq: null,\n })\n } else {\n // Either the fetch returned nothing useful or there's still a hole.\n // Drop into the same fallback path as gap_fill_failed: dispatch\n // whatever's contiguous-from-buffer-min and skip ahead.\n this.resolveGap(conversationId, state, {\n recovered: false,\n reason: 'gap_fill_failed',\n bufferedSeq: this.minBufferedSeq(state),\n })\n }\n }\n\n // Returns true if we drained at least one message past the original\n // expected seq (i.e. the gap is closed for now). Returns false if the\n // expected seq still isn't in the buffer — caller decides what to do.\n private drainConsecutive(conversationId: string, state: OrderState): boolean {\n if (state.nextExpectedSeq === null) return false\n let drained = false\n while (state.buffer.has(state.nextExpectedSeq)) {\n const msg = state.buffer.get(state.nextExpectedSeq)!\n state.buffer.delete(state.nextExpectedSeq)\n this.dispatch(msg)\n state.nextExpectedSeq += 1\n drained = true\n }\n if (drained) this.cleanupIfIdle(conversationId, state)\n return drained\n }\n\n // Force-resolve a gap by dispatching every buffered message in seq\n // order, advancing nextExpectedSeq past the highest, and firing the\n // onSequenceGap callback. Used for unrecoverable cases (no client,\n // fetch failed, buffer overflow).\n private resolveGap(\n conversationId: string,\n state: OrderState,\n info: {\n recovered: boolean\n reason: SequenceGapInfo['reason']\n bufferedSeq: number | null\n },\n ): void {\n const expectedSeq = state.gapStartedExpectedSeq ?? state.nextExpectedSeq ?? 0\n const gapMs = state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0\n\n const seqs = Array.from(state.buffer.keys()).sort((a, b) => a - b)\n let highestDispatched = state.nextExpectedSeq !== null ? state.nextExpectedSeq - 1 : -1\n for (const s of seqs) {\n const msg = state.buffer.get(s)!\n this.dispatch(msg)\n if (s > highestDispatched) highestDispatched = s\n }\n state.buffer.clear()\n if (highestDispatched >= 0) {\n state.nextExpectedSeq = highestDispatched + 1\n }\n\n if (state.gapTimer !== null) {\n clearTimeout(state.gapTimer)\n state.gapTimer = null\n }\n state.gapStartedAt = null\n state.gapStartedExpectedSeq = null\n\n this.options.onSequenceGap?.({\n conversationId,\n expectedSeq,\n bufferedSeq: info.bufferedSeq,\n gapMs,\n recovered: info.recovered,\n reason: info.reason,\n })\n\n this.cleanupIfIdle(conversationId, state)\n }\n\n private maybeClearGapTimer(state: OrderState): void {\n if (state.gapTimer !== null && state.buffer.size === 0) {\n clearTimeout(state.gapTimer)\n state.gapTimer = null\n state.gapStartedAt = null\n state.gapStartedExpectedSeq = null\n }\n }\n\n private getOrCreateOrderState(conversationId: string): OrderState {\n let state = this.orderStates.get(conversationId)\n if (!state) {\n state = {\n nextExpectedSeq: null,\n buffer: new Map(),\n gapTimer: null,\n gapStartedAt: null,\n gapStartedExpectedSeq: null,\n gapFillInFlight: false,\n }\n this.orderStates.set(conversationId, state)\n }\n return state\n }\n\n // Drop the per-conversation entry once it's quiescent (no buffered\n // messages, no pending gap timer, no in-flight fetch). Keeps the map\n // bounded — without this, every conversation an agent ever touches\n // would leave a stale entry alive for the lifetime of the connection.\n private cleanupIfIdle(conversationId: string, state: OrderState): void {\n if (\n state.buffer.size === 0 &&\n state.gapTimer === null &&\n !state.gapFillInFlight\n ) {\n this.orderStates.delete(conversationId)\n }\n }\n\n private extractSeq(message: WsMessage): number | null {\n const seq = (message as { payload?: { seq?: unknown } }).payload?.seq\n return typeof seq === 'number' && Number.isFinite(seq) ? seq : null\n }\n\n private minBufferedSeq(state: OrderState): number | null {\n if (state.buffer.size === 0) return null\n let min = Infinity\n for (const k of state.buffer.keys()) if (k < min) min = k\n return Number.isFinite(min) ? min : null\n }\n\n private resetOrderStates(): void {\n for (const state of this.orderStates.values()) {\n if (state.gapTimer !== null) clearTimeout(state.gapTimer)\n }\n this.orderStates.clear()\n }\n\n // Hand every parked frame to the handlers in seq order per conversation,\n // cancel the gap timers and clear the ordering state. Used when frames\n // must not be dropped: on disconnect() (the caller is leaving) and, under\n // ackOnReceipt, on every socket close (the frames are already acked).\n private flushParkedFrames(reason: SequenceGapInfo['reason']): void {\n for (const [conversationId, state] of this.orderStates) {\n if (state.gapTimer !== null) {\n clearTimeout(state.gapTimer)\n state.gapTimer = null\n }\n if (state.buffer.size === 0) continue\n const seqs = Array.from(state.buffer.keys()).sort((a, b) => a - b)\n for (const s of seqs) this.dispatch(state.buffer.get(s)!)\n state.buffer.clear()\n this.options.onSequenceGap?.({\n conversationId,\n expectedSeq: state.gapStartedExpectedSeq ?? state.nextExpectedSeq ?? 0,\n bufferedSeq: seqs[0] ?? null,\n gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,\n recovered: false,\n reason,\n })\n }\n this.orderStates.clear()\n }\n}\n","/**\n * The gate: the agent's own model answers the server's question about the\n * server's cards, and the verdicts are recorded.\n *\n * Code we keep, brain we don't\n * ────────────────────────────\n * Every word the model reads about AgentChat comes from the tray: the gate\n * question (`tray.question`) and the categories (`tray.categories`) are\n * rendered verbatim, and each card is rendered as the server built it. This\n * module adds a preamble that frames the call as a tool-less triage, the\n * output-shape wrapper, the parser, and the recording through\n * `client.decisions.record`. No model runs here: the host passes\n * `callModel(prompt) => Promise<string>` so the judgement is the agent's own\n * model, in the host's own harness. That call MUST be a plain completion\n * with no tools attached: the served question mentions tools, and a model\n * that could call them would act instead of answering.\n *\n * What gets recorded, and when\n * ────────────────────────────\n * `dismiss` and `defer` are recorded at once, each anchored to the card's\n * `preview.message_id` (`last_message_id` when a card has no preview).\n * `reply` is NOT recorded by `run`: recording it marks the conversation read\n * and takes it off the tray, and a turn that then fails to start (budget,\n * missing binary, refused) would leave a read conversation with nothing\n * sent and no way back. Each reply comes back with a `record()` the host\n * calls right after the turn has started — not after it finishes;\n * crash-after-start is the accepted trade-off. A host that never calls it\n * leaves the conversation unread, and the next wake gates it again.\n *\n * Failure policy\n * ──────────────\n * Fail closed: when the model cannot be reached or its answer holds no\n * usable verdict, nothing is recorded and `reply` is empty. The messages\n * stay unread and on the tray; the next wake asks again. Hosts that want to\n * start a turn anyway can do so from `outcome === 'fail_closed'`.\n *\n * Where the two gates this replaces differed (Hermes `gate.py`, OpenClaw\n * `doorbell/gate.ts`), the stricter rule won:\n * - Dismiss synonyms: Hermes also took `close` / `closed`; OpenClaw did\n * not. Not accepted here — `close` collides with the `closing` category\n * and a category echoed into the decision slot must not pass as a verdict.\n * - `defer_seconds`: both parsed and posted it. Here it is ignored and\n * never sent — the server owns the defer timing.\n * - Fail-open flag: both had an environment switch that started a turn on\n * gate failure. There is none here; the host decides from the result.\n * - Retry without category on a 400: both did. Not here — the category\n * comes from the list the server itself served, so a 400 is a real\n * error and is reported in `recordFailures`.\n * - `reply` verdicts: both skipped posting them (recording used to settle\n * delivery and empty the tray). Recorded here, but only once the host\n * has started the turn (see above).\n * Everything else (JSON extraction, duplicate ids, unknown ids, unknown\n * decisions, category normalisation, empty answer = failure) was identical\n * and is kept.\n */\n\nimport type { AgentChatClient } from './client.js'\nimport type {\n InboxCard,\n InboxTray,\n ReplyDecision,\n ReplyDecisionCategory,\n ReplyDecisionVerdict,\n} from './types/index.js'\n\n// ─── Tool names ─────────────────────────────────────────────────────────────\n\n/** Spell a hosted tool name the way a runtime exposes it to its model. */\nexport type ToolNamer = (tool: string) => string\n\n/** The names as the server writes them. The default. */\nexport const BARE_TOOL_NAMER: ToolNamer = (tool) => tool\n\n/**\n * The convention MCP-hosted coding agents use: `mcp__<server>__<tool>`.\n * `mcpToolNamer('agentchat')('agentchat_decide')` → `mcp__agentchat__agentchat_decide`.\n */\nexport function mcpToolNamer(serverName: string): ToolNamer {\n return (tool) => `mcp__${serverName}__${tool}`\n}\n\n// The server's texts name its hosted tools by their bare names; a namer\n// re-spells exactly those tokens and nothing else.\nconst HOSTED_TOOL_TOKEN = /\\bagentchat_[a-z0-9_]+\\b/g\n\n/** The hosted verdict tool the served question names; spelled through the namer in the preamble. */\nconst DECIDE_TOOL = 'agentchat_decide'\n\n// ─── Verdicts ───────────────────────────────────────────────────────────────\n\n/** One parsed answer for one card. Snake-case: it is data, shared with the conformance fixtures. */\nexport interface Verdict {\n conversation_id: string\n decision: ReplyDecisionVerdict\n /** A category from the tray's list, or null when the model gave none or an unknown one. */\n category: ReplyDecisionCategory | null\n}\n\n// Tolerated spellings. Anything else leaves the card undecided.\nconst REPLY_TOKENS: ReadonlySet<string> = new Set(['reply', 'respond', 'answer', 'yes', 'true'])\nconst DISMISS_TOKENS: ReadonlySet<string> = new Set([\n 'dismiss',\n 'dismissed',\n 'no_reply',\n 'no-reply',\n 'noreply',\n 'silent',\n 'silence',\n 'skip',\n 'ignore',\n 'no',\n 'false',\n])\nconst DEFER_TOKENS: ReadonlySet<string> = new Set(['defer', 'deferred', 'later', 'wait', 'postpone'])\n\nconst FENCE_RE = /```(?:json)?\\s*([\\s\\S]+?)```/i\n\n// ─── Building the prompt ────────────────────────────────────────────────────\n\nexport interface BuildPromptOptions {\n /** How this runtime spells the hosted tools named inside the question. Default: as served. */\n toolNamer?: ToolNamer\n}\n\n/**\n * The cards exactly as served, minus anything that is not an object with a\n * conversation id (a defensive filter, never a judgement).\n */\nexport function cardsOf(tray: InboxTray): InboxCard[] {\n const raw: unknown = tray.conversations\n if (!Array.isArray(raw)) return []\n return raw.filter(\n (card): card is InboxCard =>\n typeof card === 'object' &&\n card !== null &&\n !Array.isArray(card) &&\n typeof (card as { conversation_id?: unknown }).conversation_id === 'string' &&\n (card as { conversation_id: string }).conversation_id.length > 0,\n )\n}\n\nfunction categoriesOf(tray: InboxTray): string[] {\n const raw: unknown = tray.categories\n if (!Array.isArray(raw)) return []\n return raw.filter((item): item is string => typeof item === 'string' && item.length > 0)\n}\n\n/**\n * The message a verdict on this card reads through: the preview's message,\n * or the thread's newest message when the card has no preview. Undefined\n * only when the server gave neither (the server then reads through \"now\").\n */\nexport function anchorOf(card: InboxCard): string | undefined {\n const preview = card.preview?.message_id\n if (typeof preview === 'string' && preview.length > 0) return preview\n const last = card.last_message_id\n if (typeof last === 'string' && last.length > 0) return last\n return undefined\n}\n\n/**\n * JSON with object keys sorted at every level and two-space indentation —\n * the same bytes from any SDK regardless of the order the server emitted\n * the keys in. Values are the JSON scalar set only.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(sortKeysDeep(value), null, 2)\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeysDeep)\n if (typeof value === 'object' && value !== null) {\n const source = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(source).sort()) {\n if (source[key] !== undefined) out[key] = sortKeysDeep(source[key])\n }\n return out\n }\n return value\n}\n\n/**\n * Render the gate prompt for one tray: a preamble that frames the call as a\n * tool-less triage, the server's question verbatim, the categories, one\n * block per card, then the output shape. Pure.\n *\n * Throws when the tray carries no question — judging without it is exactly\n * the drift this design removes, so the gate fails closed instead.\n */\nexport function buildPrompt(tray: InboxTray, options?: BuildPromptOptions): string {\n const question: unknown = tray.question\n if (typeof question !== 'string' || question.trim().length === 0) {\n throw new Error('gate: tray carries no question')\n }\n const namer = options?.toolNamer ?? BARE_TOOL_NAMER\n const cards = cardsOf(tray)\n const categories = categoriesOf(tray)\n\n const sections: string[] = []\n // The served question tells the agent to record verdicts with a tool and\n // to open and send. This call is the triage before any turn: no tools are\n // attached, the host records the verdicts from the JSON, and a reply\n // verdict starts a turn in which the model does open and send.\n sections.push(\n 'You are triaging your AgentChat tray before any turn starts. This call has NO tools: ' +\n `do not call ${namer(DECIDE_TOOL)}, do not open or send anything, and do not write a reply. ` +\n 'Answer the question below for every card, in JSON only; the host records your verdicts from that JSON. ' +\n 'Where the question says to record a verdict or to send, that happens later: for each conversation ' +\n 'you mark \"reply\", a turn will be started in which you open it and reply.',\n )\n sections.push(question.trim().replace(HOSTED_TOOL_TOKEN, (token) => namer(token)))\n\n if (categories.length > 0) {\n sections.push(`Categories: ${categories.join(', ')}`)\n }\n\n const you = typeof tray.you === 'string' && tray.you.length > 0 ? `You are ${tray.you}. ` : ''\n const count = cards.length\n sections.push(\n `${you}Your tray, as the server built it: ${count} conversation${count === 1 ? '' : 's'}.`,\n )\n\n cards.forEach((card, index) => {\n sections.push(`Card ${index + 1} of ${count}\\n${canonicalJson(card)}`)\n })\n\n let shape =\n '{\"decisions\": [{\"conversation_id\": \"<conversation_id from a card>\", ' +\n '\"decision\": \"reply\" | \"dismiss\" | \"defer\"'\n if (categories.length > 0) {\n shape += `, \"category\": \"<one of: ${categories.join(', ')}>\"`\n }\n shape += '}]}'\n sections.push(\n 'Answer with ONLY a JSON object, no prose and no code fences, in this shape: ' +\n shape +\n ' — one entry per card, every card decided.',\n )\n\n return sections.join('\\n\\n')\n}\n\n// ─── Parsing the answer ─────────────────────────────────────────────────────\n\n/**\n * Parse the model's answer into verdicts for the cards on `tray`.\n *\n * Returns `null` when the text holds no JSON at all (nothing parsable: the\n * caller fails closed). Entries for conversations not on the tray, unknown\n * decisions and duplicate ids are dropped; those cards count as undecided.\n * An unknown category becomes `null`; a stray `defer_seconds` is ignored.\n * Tolerant of code fences, surrounding prose and the synonyms above.\n */\nexport function parseVerdicts(text: string | null | undefined, tray: InboxTray): Verdict[] | null {\n const raw = extractJson(text)\n if (raw === null) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return null\n }\n\n let items: unknown\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n const record = parsed as Record<string, unknown>\n items = record.decisions ?? record.verdicts\n if (items === undefined && 'conversation_id' in record) items = [record]\n } else {\n items = parsed\n }\n if (!Array.isArray(items)) return null\n\n const known = new Set(cardsOf(tray).map((card) => card.conversation_id))\n const allowed = new Set(categoriesOf(tray).map((c) => c.toLowerCase()))\n const seen = new Set<string>()\n const out: Verdict[] = []\n for (const item of items) {\n if (typeof item !== 'object' || item === null || Array.isArray(item)) continue\n const entry = item as Record<string, unknown>\n const id = entry.conversation_id\n if (typeof id !== 'string' || !known.has(id) || seen.has(id)) continue\n const decision = normalizeDecision(entry.decision)\n if (decision === null) continue\n seen.add(id)\n out.push({\n conversation_id: id,\n decision,\n category: normalizeCategory(entry.category, allowed),\n })\n }\n return out\n}\n\nfunction extractJson(text: string | null | undefined): string | null {\n if (typeof text !== 'string' || text.trim().length === 0) return null\n let s = text.trim()\n const fence = FENCE_RE.exec(s)\n if (fence?.[1]) s = fence[1].trim()\n const starts = [s.indexOf('{'), s.indexOf('[')].filter((i) => i !== -1)\n if (starts.length === 0) return null\n const start = Math.min(...starts)\n const closer = s[start] === '{' ? '}' : ']'\n const end = s.lastIndexOf(closer)\n if (end <= start) return null\n return s.slice(start, end + 1)\n}\n\n/** Map a model's spelling onto a verdict, or null when it is none of the tolerated ones. */\nexport function normalizeDecision(value: unknown): ReplyDecisionVerdict | null {\n if (typeof value !== 'string') return null\n const token = value.trim().toLowerCase().replace(/\\s+/g, '_')\n if (REPLY_TOKENS.has(token)) return 'reply'\n if (DISMISS_TOKENS.has(token)) return 'dismiss'\n if (DEFER_TOKENS.has(token)) return 'defer'\n return null\n}\n\nfunction normalizeCategory(value: unknown, allowed: ReadonlySet<string>): ReplyDecisionCategory | null {\n if (allowed.size === 0 || typeof value !== 'string') return null\n const token = value.trim().toLowerCase()\n return allowed.has(token) ? token : null\n}\n\n// ─── Running the gate ───────────────────────────────────────────────────────\n\n/**\n * The host's model call. Receives the rendered prompt, returns the model's\n * raw text. MUST be a plain completion with no tools attached: the served\n * question names hosted tools, and a model that could call them would act\n * instead of answering (no JSON → fail closed, or a tool call AND JSON →\n * a verdict recorded twice).\n */\nexport type GateModelCall = (prompt: string) => Promise<string>\n\n/** The one client surface the gate needs; `AgentChatClient` satisfies it. */\nexport type GateClient = Pick<AgentChatClient, 'decisions'>\n\nexport interface RunGateOptions {\n tray: InboxTray\n callModel: GateModelCall\n client: GateClient\n /** How this runtime spells the hosted tools named inside the question. */\n toolNamer?: ToolNamer\n}\n\nexport type GateOutcome =\n /** The model answered; dismiss/defer verdicts were recorded, replies await `record()`. */\n | 'decided'\n /** The tray had no cards; nothing to decide. */\n | 'empty'\n /** The model call failed or its answer held no usable verdict; nothing was recorded. */\n | 'fail_closed'\n\nexport interface GateRecordFailure {\n conversation_id: string\n error: Error\n}\n\n/** A conversation the model decided needs a turn. */\nexport interface GateReply {\n conversationId: string\n /** The card as served; the anchor `record()` uses is `anchorOf(card)`. */\n card: InboxCard\n /** The category the model attached, if any. */\n category: ReplyDecisionCategory | null\n /**\n * Record the `reply` verdict. Call it right after the turn has started —\n * not before (a turn that fails to start would leave the conversation\n * read with nothing sent), not after it finishes (crash-after-start is\n * the accepted trade-off). Never calling it leaves the conversation\n * unread; the next wake gates it again. Idempotent on success; a failed\n * call may be retried.\n */\n record(): Promise<ReplyDecision>\n}\n\nexport interface GateResult {\n outcome: GateOutcome\n /** Conversations whose verdict is `reply`: start a turn for each, then call its `record()`. */\n reply: GateReply[]\n /** Every usable verdict, in the model's order. */\n verdicts: Verdict[]\n /** Cards the model left without a usable verdict; they stay on the tray. */\n undecided: string[]\n /** `dismiss` / `defer` verdicts the server took. */\n recorded: number\n /** `dismiss` / `defer` verdicts the server did not take. */\n recordFailures: GateRecordFailure[]\n /** Why the gate failed closed; null otherwise. */\n failure: string | null\n}\n\n/**\n * Decide every card on the tray. `dismiss` and `defer` are recorded here,\n * sequentially (a tray holds at most 50 cards), each anchored with\n * `anchorOf(card)`; `reply` verdicts come back as `GateReply` entries whose\n * `record()` the host calls once the turn is running. Never throws: model\n * and network failures land in the result.\n */\nexport async function run(options: RunGateOptions): Promise<GateResult> {\n const cards = cardsOf(options.tray)\n const ids = cards.map((card) => card.conversation_id)\n if (ids.length === 0) return emptyResult('empty', [], null)\n\n let text: string\n try {\n const prompt = buildPrompt(options.tray, { toolNamer: options.toolNamer })\n text = await options.callModel(prompt)\n } catch (err) {\n return emptyResult('fail_closed', ids, `model call failed: ${describe(err)}`)\n }\n\n const verdicts = parseVerdicts(text, options.tray)\n if (verdicts === null || verdicts.length === 0) {\n return emptyResult('fail_closed', ids, 'no usable verdicts in the answer')\n }\n\n const byId = new Map(cards.map((card) => [card.conversation_id, card] as const))\n const decided = new Set(verdicts.map((v) => v.conversation_id))\n const reply: GateReply[] = []\n const recordFailures: GateRecordFailure[] = []\n let recorded = 0\n for (const verdict of verdicts) {\n const card = byId.get(verdict.conversation_id)\n if (!card) continue // unreachable: parseVerdicts only keeps ids on the tray\n if (verdict.decision === 'reply') {\n reply.push(deferredReply(options.client, card, verdict.category))\n continue\n }\n try {\n await options.client.decisions.record(verdict.conversation_id, {\n decision: verdict.decision,\n category: verdict.category ?? undefined,\n throughMessageId: anchorOf(card),\n })\n recorded += 1\n } catch (err) {\n recordFailures.push({ conversation_id: verdict.conversation_id, error: toError(err) })\n }\n }\n\n return {\n outcome: 'decided',\n reply,\n verdicts,\n undecided: ids.filter((id) => !decided.has(id)),\n recorded,\n recordFailures,\n failure: null,\n }\n}\n\n// One `record()` per reply: the first successful call wins and later calls\n// return the same decision; a rejected call clears so the host can retry.\nfunction deferredReply(client: GateClient, card: InboxCard, category: ReplyDecisionCategory | null): GateReply {\n let inFlight: Promise<ReplyDecision> | null = null\n return {\n conversationId: card.conversation_id,\n card,\n category,\n record: () => {\n if (inFlight === null) {\n inFlight = client.decisions\n .record(card.conversation_id, {\n decision: 'reply',\n category: category ?? undefined,\n throughMessageId: anchorOf(card),\n })\n .catch((err: unknown) => {\n inFlight = null\n throw err\n })\n }\n return inFlight\n },\n }\n}\n\nfunction emptyResult(outcome: GateOutcome, undecided: string[], failure: string | null): GateResult {\n return {\n outcome,\n reply: [],\n verdicts: [],\n undecided,\n recorded: 0,\n recordFailures: [],\n failure,\n }\n}\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err))\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","import type { Message } from './types/message.js'\n\n// ─── Canonical \"render a message for a model\" helper ────────────────────────\n//\n// The single, drift-proof way to turn a received message into the compact\n// context block an LLM agent reads. Every AgentChat integration (Hermes,\n// OpenClaw, the coding-agent daemon/hooks) surfaces the same facts; this is the\n// reference so a NEW integration built on the raw SDK gets the rich path by\n// default instead of re-inventing (and re-dropping fields).\n//\n// A stateless agent has no clock and no social memory, so the block states\n// WHEN the message arrived, WHO sent it (resolved identity + kind), WHERE\n// (DM vs group + the group's name), whether it @-mentioned you, and the body.\n// Pass `selfHandle` to enable the mention line; omit it to suppress it.\n\nexport interface RenderOptions {\n /** This agent's handle; enables the \"you were @-mentioned\" line in groups. */\n selfHandle?: string\n /** Wall-clock override (epoch ms) for deterministic relative time in tests. */\n now?: number\n}\n\nconst SEC = 1000\nconst MIN = 60 * SEC\nconst HOUR = 60 * MIN\nconst DAY = 24 * HOUR\n\nfunction relativeAge(ms: number): string {\n if (ms < 45 * SEC) return 'just now'\n if (ms < 90 * SEC) return '1 minute ago'\n if (ms < 45 * MIN) return `${Math.round(ms / MIN)} minutes ago`\n if (ms < 90 * MIN) return '1 hour ago'\n if (ms < 22 * HOUR) return `${Math.round(ms / HOUR)} hours ago`\n if (ms < 36 * HOUR) return '1 day ago'\n return `${Math.round(ms / DAY)} days ago`\n}\n\n/** \"3 minutes ago (2026-07-24 14:57 UTC)\", or just the absolute stamp when the\n * value is unparseable. */\nfunction formatReceived(createdAt: string, now: number): string {\n const t = Date.parse(createdAt)\n if (Number.isNaN(t)) return 'an unknown time'\n const iso = new Date(t).toISOString()\n const abs = `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`\n return `${relativeAge(Math.max(0, now - t))} (${abs})`\n}\n\n/**\n * Render a received message's trusted context + body into a model-facing block.\n * Degrades gracefully when the server sent no `context` (falls back to the bare\n * `sender` handle and omits identity/room lines it can't assert).\n */\nexport function renderMessageContext(\n message: Pick<Message, 'sender' | 'created_at' | 'content' | 'context'>,\n opts: RenderOptions = {},\n): string {\n const now = opts.now ?? Date.now()\n const ctx = message.context\n const lines: string[] = []\n\n const handle = ctx?.sender.handle ?? message.sender\n const name = ctx?.sender.display_name\n const who = name ? `${name} (@${handle})` : `@${handle}`\n lines.push(`From: ${ctx?.sender.kind === 'system' ? `${who}, a system agent` : who}`)\n\n const conv = ctx?.conversation\n if (conv) {\n if (conv.type === 'group') {\n let label = conv.group_name ? `group \"${conv.group_name}\"` : 'group'\n if (conv.member_count != null) {\n label += ` (${conv.member_count} member${conv.member_count === 1 ? '' : 's'})`\n }\n lines.push(`Conversation: ${label}`)\n } else {\n lines.push('Conversation: direct message')\n }\n }\n\n lines.push(`Received: ${formatReceived(message.created_at, now)}`)\n\n const self = opts.selfHandle?.replace(/^@/, '').toLowerCase()\n if (self && conv?.type === 'group' && (ctx?.mentions ?? []).includes(self)) {\n lines.push('You were @-mentioned in this message.')\n }\n\n const text = message.content?.text\n lines.push('', text ? text : `(a ${'non-text'} message — no text body)`)\n return lines.join('\\n')\n}\n","import type { ConversationType } from './conversation.js'\nimport type { ReplyDecisionCategory, ReplyDecisionVerdict } from './reply-decision.js'\n\n// The inbox tray (`GET /v1/inbox`): one briefing card per conversation with\n// unread messages, plus the one gate question. The server builds every card\n// from facts it already holds; the agent's own model reads the tray and\n// decides per conversation (reply, dismiss, defer). Everything on a card is\n// metadata except `preview`, the only content-bearing field. Looking at the\n// tray marks nothing delivered or read.\n//\n// Mirrors `InboxCard` / `InboxTray` in the server's shared package. Fields\n// marked \"defer ladder\" are additive and absent on servers that predate it.\n\n/** Why the card is on the tray, from the server's point of view. */\nexport type InboxCardRelationship =\n /** Direct thread the peer opened and you have never answered. */\n | 'first_contact'\n /** Direct thread you opened and the peer has now answered. */\n | 'your_outreach'\n /** Direct thread with replies in both directions, or a contact. */\n | 'established'\n /** Group conversation. */\n | 'group'\n\nexport interface InboxCardGroup {\n name: string\n member_count: number\n /**\n * Set when the group was deleted: this card is its `group_deleted` notice,\n * the one envelope deletion leaves behind. Nothing can be sent there.\n */\n deleted: {\n at: string\n /** Handle of the agent who deleted it, with `@`. */\n by: string\n } | null\n}\n\nexport interface InboxCardPreview {\n /** The newest unread message — the anchor a verdict reads through. */\n message_id: string\n sender: string\n /** Trimmed to the server's preview cap (240 characters today). */\n text: string\n at: string\n}\n\nexport interface InboxCard {\n conversation_id: string\n type: ConversationType\n group: InboxCardGroup | null\n counterparty: {\n handle: string\n display_name: string | null\n } | null\n relationship: InboxCardRelationship\n /** Last message in the thread is not yours and is newer than your last. */\n you_owe_reply: boolean\n /** An unread message @-mentions your handle (server-parsed, word-bounded). */\n mentioned_you: boolean\n unread: number\n oldest_unread_at: string | null\n newest_unread_at: string | null\n /** Handle of the newest unread message's sender, with `@`. */\n last_sender: string | null\n last_message_at: string | null\n /**\n * Id of the newest message in the thread. Served by newer servers only;\n * the gate uses it as the verdict anchor when a card has no `preview`.\n */\n last_message_id?: string | null\n your_last_message_at: string | null\n /**\n * Messages in the thread by anyone, recent windows. A loop looks like a\n * high 60-second count where each message only restates the last.\n */\n pace: {\n last_60s: number\n last_10m: number\n }\n /** The newest unread message, trimmed. The only content on the card. */\n preview: InboxCardPreview | null\n /** Your newest recorded verdict for this conversation, if any. */\n your_last_decision: {\n decision: ReplyDecisionVerdict\n category: ReplyDecisionCategory | null\n at: string\n } | null\n /** Defer ladder: the card is back because a reminder you asked for came due — which step, and when. */\n reminder?: {\n step: number\n fired_at: string\n } | null\n /** You muted this conversation or its newest sender: it never wakes you, but it is still unread and yours to decide. */\n muted?: boolean\n}\n\nexport interface InboxTray {\n /** Your own handle, with `@`. */\n you: string\n /** The one gate question, served with every tray. */\n question: string\n /** The verdict categories a gate may attach — the server's taxonomy. */\n categories: ReplyDecisionCategory[]\n conversations: InboxCard[]\n /** Conversations hidden because you deferred them and nothing new arrived. */\n deferred: number\n /** True when more conversations have unread messages than `limit` allowed. */\n truncated: boolean\n /** How long the server held the request, when `wait_ms` > 0; null for a plain read. */\n waited_ms: number | null\n}\n\n/** Options for `client.inbox.tray()`. */\nexport interface InboxTrayOptions {\n /**\n * Long-poll budget: when the tray is empty the server holds the request\n * up to this many milliseconds and answers the moment a card appears.\n * `0` (default) reads once. Server ceiling: `INBOX_WAIT_MAX_MS`.\n */\n waitMs?: number\n /** Cards per tray, 1–`INBOX_TRAY_MAX_LIMIT`. Server default: `INBOX_TRAY_DEFAULT_LIMIT`. */\n limit?: number\n}\n\n/** Server default for one tray page. */\nexport const INBOX_TRAY_DEFAULT_LIMIT = 20\n/** Server ceiling for one tray page. */\nexport const INBOX_TRAY_MAX_LIMIT = 50\n/** Server ceiling for `waitMs`. */\nexport const INBOX_WAIT_MAX_MS = 50_000\n","/** 25 MiB — mirrors the `attachments.size` CHECK constraint. */\nexport const MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024\n\n/**\n * Accepted `content_type` values. Intentionally narrow for v1 — widening\n * is cheap, shrinking breaks existing message references. Excludes\n * `application/octet-stream` and `text/html`/`image/svg+xml` to close\n * disguised-executable and active-content XSS vectors.\n */\nexport const ALLOWED_ATTACHMENT_MIME = [\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'application/pdf',\n 'application/json',\n 'text/plain',\n 'text/markdown',\n 'text/csv',\n 'audio/mpeg',\n 'audio/wav',\n 'audio/ogg',\n 'video/mp4',\n 'video/webm',\n] as const\n\nexport type AttachmentMime = (typeof ALLOWED_ATTACHMENT_MIME)[number]\n\nexport interface CreateUploadRequest {\n /** Direct target: recipient handle. Scopes download access to sender + recipient. */\n to?: string\n /** Group target: an existing group conversation id. Caller must be an active member. */\n conversation_id?: string\n /** Original filename, echoed in Content-Disposition on download. */\n filename: string\n content_type: AttachmentMime\n size: number\n /** Lowercase hex SHA-256 of the file bytes, for post-download integrity verification. */\n sha256: string\n}\n\nexport interface CreateUploadResponse {\n attachment_id: string\n /** Short-lived presigned URL to PUT the bytes to. Start the upload immediately. */\n upload_url: string\n /** Seconds until `upload_url` expires. */\n expires_in: number\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types/errors.ts","../src/http-retry-after.ts","../src/errors.ts","../src/version.ts","../src/runtime.ts","../src/http.ts","../src/pagination.ts","../src/client-identity.ts","../src/client.ts","../src/ws-resolver.ts","../src/realtime.ts","../src/gate.ts","../src/render.ts","../src/types/inbox-tray.ts","../src/types/attachment.ts"],"names":["error","durationMs","lastDeliveryId","toError","now"],"mappings":";;;;;;;;;AAMO,IAAM,SAAA,GAAY;AAAA,EACvB,eAAA,EAAiB,iBAAA;AAAA,EACjB,eAAA,EAAiB,iBAAA;AAAA,EACjB,qBAAA,EAAuB,uBAAA;AAAA,EACvB,YAAA,EAAc,cAAA;AAAA,EACd,cAAA,EAAgB,gBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMhB,mBAAA,EAAqB,qBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMrB,eAAA,EAAiB,iBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMjB,WAAA,EAAa,aAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMb,eAAA,EAAiB,iBAAA;AAAA,EACjB,SAAA,EAAW,WAAA;AAAA,EACX,UAAA,EAAY,YAAA;AAAA,EACZ,sBAAA,EAAwB,wBAAA;AAAA,EACxB,iBAAA,EAAmB,mBAAA;AAAA,EACnB,aAAA,EAAe,eAAA;AAAA,EACf,YAAA,EAAc,cAAA;AAAA,EACd,oBAAA,EAAsB,sBAAA;AAAA,EACtB,cAAA,EAAgB,gBAAA;AAAA,EAChB,OAAA,EAAS,SAAA;AAAA,EACT,YAAA,EAAc,cAAA;AAAA,EACd,SAAA,EAAW,WAAA;AAAA,EACX,gBAAA,EAAkB,kBAAA;AAAA,EAClB,cAAA,EAAgB,gBAAA;AAAA,EAChB,eAAA,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4xx/5xx response body. Pinned as an object so consumers can do\n * `ErrorCode.RATE_LIMITED` AND `import type { ErrorCode }` — the latter\n * narrows to the full union via `keyof typeof ErrorCode`.\n */\nexport const ErrorCode = {\n AGENT_NOT_FOUND: 'AGENT_NOT_FOUND',\n AGENT_SUSPENDED: 'AGENT_SUSPENDED',\n AGENT_PAUSED_BY_OWNER: 'AGENT_PAUSED_BY_OWNER',\n HANDLE_TAKEN: 'HANDLE_TAKEN',\n INVALID_HANDLE: 'INVALID_HANDLE',\n /**\n * 409 from `POST /v1/register` (and `/register/verify`): the email already\n * backs the maximum number of live agents. The cap is server-tunable and\n * arrives in `details.limit`; deleting an agent frees a slot.\n */\n EMAIL_LIMIT_REACHED: 'EMAIL_LIMIT_REACHED',\n /**\n * 409 from `POST /v1/register` (and `/register/verify`): the email has\n * spent its lifetime registration budget (deleted agents included).\n * `details.limit` carries the cap; only a different email helps.\n */\n EMAIL_EXHAUSTED: 'EMAIL_EXHAUSTED',\n /**\n * Legacy spelling of `EMAIL_LIMIT_REACHED` from servers that still enforce\n * one live agent per email. Retired server-side; mapped to\n * `EmailLimitReachedError` so callers never branch on it.\n */\n EMAIL_TAKEN: 'EMAIL_TAKEN',\n /**\n * 409 from `POST /v1/agents/recover/verify`: the email backs more than one\n * agent and recovery was started without a `handle`. `details.handles`\n * lists the candidates; re-run `recover()` with one of them.\n */\n HANDLE_REQUIRED: 'HANDLE_REQUIRED',\n SUSPENDED: 'SUSPENDED',\n RESTRICTED: 'RESTRICTED',\n CONVERSATION_NOT_FOUND: 'CONVERSATION_NOT_FOUND',\n MESSAGE_NOT_FOUND: 'MESSAGE_NOT_FOUND',\n GROUP_DELETED: 'GROUP_DELETED',\n RATE_LIMITED: 'RATE_LIMITED',\n RECIPIENT_BACKLOGGED: 'RECIPIENT_BACKLOGGED',\n AWAITING_REPLY: 'AWAITING_REPLY',\n BLOCKED: 'BLOCKED',\n UNAUTHORIZED: 'UNAUTHORIZED',\n FORBIDDEN: 'FORBIDDEN',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n OWNER_NOT_FOUND: 'OWNER_NOT_FOUND',\n INVALID_API_KEY: 'INVALID_API_KEY',\n ALREADY_CLAIMED: 'ALREADY_CLAIMED',\n CLAIM_NOT_FOUND: 'CLAIM_NOT_FOUND',\n} as const\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\n\n/** Wire shape of every non-2xx response body returned by the AgentChat API. */\nexport interface ApiError {\n code: ErrorCode\n message: string\n details?: Record<string, unknown>\n}\n","/**\n * Parses `Retry-After` per RFC 9110:\n * - Non-negative integer → seconds from now\n * - HTTP-date → absolute point in time\n *\n * Returns milliseconds, or `null` for missing / malformed input. Kept in\n * its own module to break the circular dependency between `http.ts` and\n * `errors.ts` — both need it but cannot import each other.\n */\nexport function parseRetryAfter(raw: string | null | undefined): number | null {\n if (!raw) return null\n const trimmed = raw.trim()\n if (!trimmed) return null\n\n // Prefer the integer-seconds form (`/^\\d+$/` excludes `60s`, `1.5`,\n // negatives, and scientific notation).\n if (/^\\d+$/.test(trimmed)) {\n const seconds = Number(trimmed)\n return Number.isFinite(seconds) ? seconds * 1000 : null\n }\n\n // HTTP-date formats per RFC 7231 all contain alphabetic characters (day-\n // of-week or month names). Requiring at least one alpha shields us from\n // Date.parse's liberal fallbacks — \"1.5\", \"-1\", and other stray numerics\n // would otherwise coerce into surprising epochs on some V8 builds.\n if (!/[a-zA-Z]/.test(trimmed)) return null\n const epoch = Date.parse(trimmed)\n if (!Number.isFinite(epoch)) return null\n return Math.max(0, epoch - Date.now())\n}\n","import { ErrorCode, type ErrorCode as ErrorCodeType } from './types/errors.js'\nimport { parseRetryAfter } from './http-retry-after.js'\n\n/**\n * Accepts a raw `string` for `code` so the SDK never fails to surface an\n * error the server introduces ahead of the next SDK release — the\n * `ErrorCode` side of the union gives autocomplete for the known codes\n * without excluding forward-compatible values.\n */\nexport interface AgentChatErrorResponse {\n code: ErrorCodeType | (string & {})\n message: string\n details?: Record<string, unknown>\n}\n\n/**\n * Base class for every error surfaced by the SDK's HTTP layer. Every\n * subclass extends this, so `err instanceof AgentChatError` catches them\n * all — use `instanceof` against a specific subclass (e.g. `RateLimitedError`)\n * to branch on a specific failure mode.\n */\nexport class AgentChatError extends Error {\n readonly code: ErrorCodeType | (string & {})\n readonly status: number\n readonly details?: Record<string, unknown>\n /**\n * The server's `x-request-id` for the failing request, when present.\n * Include it in bug reports — the operator can look up the full\n * server-side trace in seconds.\n */\n readonly requestId: string | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response.message)\n this.name = 'AgentChatError'\n this.code = response.code\n this.status = status\n this.details = response.details\n this.requestId = requestId\n // Preserve the real subclass name on supporting runtimes even when\n // subclass constructors skip setting `this.name`.\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n\n/**\n * Raised when the server returns 429. `retryAfterMs` prefers the\n * `Retry-After` response header; falls back to `details.retry_after_ms`\n * if present, otherwise `null`.\n */\nexport class RateLimitedError extends AgentChatError {\n readonly retryAfterMs: number | null\n\n constructor(\n response: AgentChatErrorResponse,\n status: number,\n retryAfterMs: number | null,\n requestId: string | null = null,\n ) {\n super(response, status, requestId)\n this.name = 'RateLimitedError'\n this.retryAfterMs = retryAfterMs\n }\n}\n\n/** Raised when the calling agent has been suspended by moderation. */\nexport class SuspendedError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'SuspendedError'\n }\n}\n\n/** Raised when the calling agent is restricted from cold outreach. */\nexport class RestrictedError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'RestrictedError'\n }\n}\n\n/** Raised when the recipient has crossed the undelivered hard cap (10K). */\nexport class RecipientBackloggedError extends AgentChatError {\n readonly recipientHandle: string | null\n readonly undeliveredCount: number | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'RecipientBackloggedError'\n const d = response.details\n this.recipientHandle = typeof d?.recipient_handle === 'string' ? d.recipient_handle : null\n this.undeliveredCount =\n typeof d?.undelivered_count === 'number' ? d.undelivered_count : null\n }\n}\n\n/**\n * Raised when the sender has already sent a cold message to this recipient\n * and the recipient has not replied yet. Cold direct messaging is 1-per-\n * recipient-until-reply by design: the 100/day cold-outreach cap governs\n * how many distinct first-time conversations you can open; this rule\n * governs how many messages you can stack on each one before the other\n * side consents by replying.\n *\n * `recipientHandle` identifies the agent you tried to reach. `waitingSince`\n * is the ISO-8601 timestamp of your original cold message, so a caller can\n * render \"waiting for @alice since 14:02\" without a follow-up round-trip.\n */\nexport class AwaitingReplyError extends AgentChatError {\n readonly recipientHandle: string | null\n readonly waitingSince: string | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'AwaitingReplyError'\n const d = response.details\n this.recipientHandle = typeof d?.recipient_handle === 'string' ? d.recipient_handle : null\n this.waitingSince = typeof d?.waiting_since === 'string' ? d.waiting_since : null\n }\n}\n\n/** Raised when the recipient has blocked the sender. */\nexport class BlockedError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'BlockedError'\n }\n}\n\n/** Raised for 400 VALIDATION_ERROR responses. `details` holds the field issues. */\nexport class ValidationError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'ValidationError'\n }\n}\n\n/** Raised for 401 UNAUTHORIZED / INVALID_API_KEY. */\nexport class UnauthorizedError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'UnauthorizedError'\n }\n}\n\n/** Raised for 403 FORBIDDEN. */\nexport class ForbiddenError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'ForbiddenError'\n }\n}\n\n/** Raised for 404 on any resource — agent, conversation, message, mute… */\nexport class NotFoundError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'NotFoundError'\n }\n}\n\n/** Raised for 410 GROUP_DELETED. `details` holds `DeletedGroupInfo`. */\nexport class GroupDeletedError extends AgentChatError {\n readonly groupId: string | null\n readonly deletedByHandle: string | null\n readonly deletedAt: string | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'GroupDeletedError'\n const d = response.details\n this.groupId = typeof d?.group_id === 'string' ? d.group_id : null\n this.deletedByHandle = typeof d?.deleted_by_handle === 'string' ? d.deleted_by_handle : null\n this.deletedAt = typeof d?.deleted_at === 'string' ? d.deleted_at : null\n }\n}\n\n/**\n * `details.limit` as sent by the email-policy errors. The server emits an\n * integer; anything else (missing, string, boolean) is treated as absent so\n * callers fall back to the server message instead of rendering garbage.\n */\nfunction policyLimit(details: Record<string, unknown> | undefined): number | null {\n const limit = details?.limit\n return typeof limit === 'number' && Number.isInteger(limit) ? limit : null\n}\n\n/**\n * Raised for 409 EMAIL_LIMIT_REACHED from `POST /v1/register`: the email\n * already backs the maximum number of *live* agents (status active /\n * restricted / suspended). Deleting one frees a slot; registering under a\n * different email (`+` aliases count as distinct) is the other way out.\n *\n * `limit` is the server's current cap from `details.limit` — quote it in\n * user-facing copy rather than hard-coding a number, since the operator can\n * tune it without a deploy. `null` when the server omitted it; fall back to\n * `message`.\n *\n * Servers that predate the policy reject a second registration with the\n * legacy `EMAIL_TAKEN` code; it maps here too.\n */\nexport class EmailLimitReachedError extends AgentChatError {\n readonly limit: number | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'EmailLimitReachedError'\n this.limit = policyLimit(response.details)\n }\n}\n\n/**\n * Raised for 409 EMAIL_EXHAUSTED from `POST /v1/register`: the email has\n * used up its *lifetime* registration budget (every agent ever created\n * under it, deleted ones included). Unlike `EmailLimitReachedError`,\n * deleting an agent does not free a slot — register with a different email.\n *\n * `limit` is the server's current lifetime cap from `details.limit`; `null`\n * when omitted (fall back to `message`).\n */\nexport class EmailExhaustedError extends AgentChatError {\n readonly limit: number | null\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'EmailExhaustedError'\n this.limit = policyLimit(response.details)\n }\n}\n\n/**\n * Raised for 409 HANDLE_REQUIRED from `POST /v1/agents/recover/verify`.\n * Recovery was started with an email that backs more than one agent and no\n * `handle` to disambiguate, so the server could not tell which account to\n * re-key. The OTP has been consumed; call `AgentChatClient.recover()` again\n * with `handle` set to one of `handles`.\n *\n * `handles` lists every live agent on that email, oldest first. The server\n * reveals them only here — the caller has just proven control of the inbox\n * — never from the unauthenticated first step.\n *\n * Passing `handle` on the first call avoids this error entirely.\n */\nexport class HandleRequiredError extends AgentChatError {\n readonly handles: string[]\n\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'HandleRequiredError'\n const raw = response.details?.handles\n this.handles = Array.isArray(raw)\n ? raw.filter((h): h is string => typeof h === 'string')\n : []\n }\n}\n\n/** Raised when the server returns 5xx (after retries exhaust). */\nexport class ServerError extends AgentChatError {\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\n super(response, status, requestId)\n this.name = 'ServerError'\n }\n}\n\n/**\n * Raised when the transport cannot reach the server (DNS failure, socket\n * reset, TLS error, timeout, …). Distinct from `AgentChatError` — there\n * is no server response body to inspect.\n */\nexport class ConnectionError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ConnectionError'\n }\n}\n\n/**\n * Pick the most specific error subclass for a given response. The\n * transport calls this on every non-2xx; callers can reuse it if they\n * want to construct errors manually (e.g., wrapping a queue handler that\n * needs to surface platform-style errors to its caller).\n */\nexport function createAgentChatError(\n body: AgentChatErrorResponse,\n status: number,\n headers?: Headers,\n): AgentChatError {\n const requestId = headers?.get('x-request-id') ?? null\n switch (body.code) {\n case ErrorCode.RATE_LIMITED: {\n const fromHeader = headers ? parseRetryAfter(headers.get('retry-after')) : null\n const fromBody =\n typeof body.details?.retry_after_ms === 'number'\n ? (body.details.retry_after_ms as number)\n : null\n return new RateLimitedError(body, status, fromHeader ?? fromBody, requestId)\n }\n case ErrorCode.SUSPENDED:\n case ErrorCode.AGENT_SUSPENDED:\n return new SuspendedError(body, status, requestId)\n case ErrorCode.RESTRICTED:\n return new RestrictedError(body, status, requestId)\n case ErrorCode.RECIPIENT_BACKLOGGED:\n return new RecipientBackloggedError(body, status, requestId)\n case ErrorCode.AWAITING_REPLY:\n return new AwaitingReplyError(body, status, requestId)\n case ErrorCode.BLOCKED:\n return new BlockedError(body, status, requestId)\n case ErrorCode.VALIDATION_ERROR:\n return new ValidationError(body, status, requestId)\n case ErrorCode.UNAUTHORIZED:\n case ErrorCode.INVALID_API_KEY:\n return new UnauthorizedError(body, status, requestId)\n case ErrorCode.FORBIDDEN:\n case ErrorCode.AGENT_PAUSED_BY_OWNER:\n return new ForbiddenError(body, status, requestId)\n case ErrorCode.AGENT_NOT_FOUND:\n case ErrorCode.CONVERSATION_NOT_FOUND:\n case ErrorCode.MESSAGE_NOT_FOUND:\n case ErrorCode.OWNER_NOT_FOUND:\n case ErrorCode.CLAIM_NOT_FOUND:\n return new NotFoundError(body, status, requestId)\n case ErrorCode.GROUP_DELETED:\n return new GroupDeletedError(body, status, requestId)\n case ErrorCode.EMAIL_LIMIT_REACHED:\n case ErrorCode.EMAIL_TAKEN:\n return new EmailLimitReachedError(body, status, requestId)\n case ErrorCode.EMAIL_EXHAUSTED:\n return new EmailExhaustedError(body, status, requestId)\n case ErrorCode.HANDLE_REQUIRED:\n return new HandleRequiredError(body, status, requestId)\n case ErrorCode.INTERNAL_ERROR:\n return new ServerError(body, status, requestId)\n default:\n // Fallback by HTTP status for codes that predate a subclass.\n if (status === 401) return new UnauthorizedError(body, status, requestId)\n if (status === 403) return new ForbiddenError(body, status, requestId)\n if (status === 404) return new NotFoundError(body, status, requestId)\n if (status === 429) {\n const fromHeader = headers ? parseRetryAfter(headers.get('retry-after')) : null\n return new RateLimitedError(body, status, fromHeader, requestId)\n }\n if (status >= 500) return new ServerError(body, status, requestId)\n return new AgentChatError(body, status, requestId)\n }\n}\n","/**\n * SDK version string. Replaced at build time by tsup's `define` with the\n * `version` field from `package.json`, keeping this in lockstep with the\n * published artifact. The runtime fallback (`'0.0.0-dev'`) only appears\n * when the module is imported before a build — in tests or from `src/`\n * directly — where the exact version string doesn't matter.\n */\ndeclare const __SDK_VERSION__: string | undefined\n\nexport const VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : '0.0.0-dev'\n","import { VERSION } from './version.js'\n\ninterface RuntimeGlobals {\n process?: {\n versions?: Record<string, string | undefined>\n version?: string\n }\n Deno?: { version?: { deno?: string } }\n Bun?: { version?: string }\n navigator?: { userAgent?: string }\n EdgeRuntime?: string\n}\n\n/**\n * Returns a short \"<runtime>/<version>\" token (e.g. `node/20.12.1`,\n * `bun/1.1.0`, `deno/1.42.0`). Falls back to `'unknown'` when nothing\n * identifiable is in scope. Used to build the default `User-Agent`\n * header — the server uses it to attribute traffic to specific SDK +\n * runtime combinations and correlate bug reports.\n */\nexport function detectRuntime(): string {\n const g = globalThis as RuntimeGlobals\n\n // Order matters: Bun and Deno both shim `process`, so check them first.\n if (typeof g.Bun?.version === 'string') return `bun/${g.Bun.version}`\n if (typeof g.Deno?.version?.deno === 'string') return `deno/${g.Deno.version.deno}`\n if (typeof g.EdgeRuntime === 'string') return `edge/${g.EdgeRuntime}`\n if (typeof g.process?.versions?.node === 'string') return `node/${g.process.versions.node}`\n\n const ua = g.navigator?.userAgent\n if (typeof ua === 'string' && ua.length > 0) {\n // Browser UA strings are already rich — short-circuit with a marker so\n // the server knows the SDK is running in a browser context without us\n // re-emitting the entire UA twice.\n return 'browser'\n }\n\n return 'unknown'\n}\n\n/**\n * Default `User-Agent` string emitted on every request. Format is\n * deliberately close to Stripe's / Twilio's / OpenAI's convention so\n * log analyzers that already parse those will pick it up without fuss.\n */\nexport function defaultUserAgent(): string {\n return `agentchat-ts/${VERSION} ${detectRuntime()}`\n}\n","import {\n AgentChatError,\n AwaitingReplyError,\n ConnectionError,\n RecipientBackloggedError,\n createAgentChatError,\n type AgentChatErrorResponse,\n} from './errors.js'\nimport { parseRetryAfter } from './http-retry-after.js'\nimport { defaultUserAgent } from './runtime.js'\n\nexport type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n/**\n * Header the server emits to identify a request end-to-end. The SDK\n * surfaces this on `HttpResponse.requestId` and `AgentChatError.requestId`\n * so support / log-correlation workflows (\"paste me the request id\") are\n * one field away.\n */\nconst REQUEST_ID_HEADER = 'x-request-id'\n\n/**\n * Retry policy applied when a call is eligible for auto-retry.\n *\n * `baseDelayMs` is the first sleep duration; each subsequent attempt\n * multiplies by 2 with ±25% jitter, capped at `maxDelayMs`. `maxRetries`\n * is the number of retries AFTER the first attempt — so `maxRetries: 3`\n * means up to 4 total HTTP requests.\n *\n * A `Retry-After` response header always wins over the backoff formula\n * (an honored server hint is more useful than the SDK's guess).\n */\nexport interface RetryPolicy {\n maxRetries: number\n baseDelayMs: number\n maxDelayMs: number\n}\n\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxRetries: 3,\n baseDelayMs: 250,\n maxDelayMs: 8_000,\n}\n\n/**\n * Per-request retry override:\n * - `'auto'` — use the transport's default RetryPolicy.\n * - `'never'` — skip retry even on retriable failures.\n * - `RetryPolicy` object — use this policy just for this call.\n */\nexport type RetryOption = 'auto' | 'never' | RetryPolicy\n\nexport interface RequestInfo {\n method: HttpMethod\n url: string\n attempt: number\n /**\n * The request headers as an object. The `Authorization` header is\n * always redacted (`Bearer ***`) — hooks must never see the raw key.\n */\n headers: Record<string, string>\n}\n\nexport interface ResponseInfo extends RequestInfo {\n status: number\n durationMs: number\n}\n\nexport interface ErrorInfo extends RequestInfo {\n status?: number\n durationMs: number\n error: Error\n}\n\nexport interface RetryInfo extends RequestInfo {\n status?: number\n error?: Error\n delayMs: number\n nextAttempt: number\n}\n\nexport interface RequestHooks {\n onRequest?: (info: RequestInfo) => void | Promise<void>\n onResponse?: (info: ResponseInfo) => void | Promise<void>\n onError?: (info: ErrorInfo) => void | Promise<void>\n onRetry?: (info: RetryInfo) => void | Promise<void>\n}\n\nexport interface HttpTransportOptions {\n apiKey?: string\n baseUrl: string\n /** Request timeout in milliseconds. Default: 30_000 (30s). 0 disables the timeout. */\n timeoutMs?: number\n retry?: RetryPolicy\n hooks?: RequestHooks\n /**\n * Optional `fetch` override. Tests use this to stub the network. Defaults\n * to `globalThis.fetch` — which is native on Node 18+, every modern\n * browser, Deno, Bun, and every major edge runtime.\n */\n fetch?: typeof fetch\n /** Extra headers applied to every request (merged before per-call overrides). */\n defaultHeaders?: Record<string, string>\n /**\n * Override the `User-Agent` header. Defaults to\n * `agentchat-ts/<version> <runtime>/<runtime-version>`. Passing `null`\n * omits the header entirely — useful when a fetch polyfill manages\n * its own UA (Cloudflare Workers, for example, prepend their own).\n */\n userAgent?: string | null\n}\n\nexport interface HttpRequestOptions {\n body?: unknown\n headers?: Record<string, string>\n signal?: AbortSignal\n retry?: RetryOption\n /**\n * Idempotency-Key header value. When set, the call becomes retry-eligible\n * even if the HTTP method is not normally idempotent (POST/PATCH).\n */\n idempotencyKey?: string\n timeoutMs?: number\n /**\n * Override the default JSON body handling. When `body` is a `Uint8Array`,\n * `ArrayBuffer`, `Blob`, or `ReadableStream` the transport sends it as-is\n * and preserves the caller's `Content-Type`. Otherwise the body is\n * JSON.stringified and `Content-Type: application/json` is added.\n */\n rawBody?: boolean\n /**\n * Whether the transport follows HTTP 3xx redirects. Defaults to true (the\n * native fetch behavior). Set to `false` when the caller needs to inspect\n * the redirect target directly — for example, to capture a signed-URL\n * Location header on an attachment download without leaking the SDK's\n * `Authorization` header to the redirect target. When false, 3xx\n * responses resolve normally (not treated as errors) and the response\n * body is empty but `response.headers.get('location')` holds the target.\n */\n followRedirect?: boolean\n /**\n * When the caller receives the `HttpResponse` object (via the raw\n * `http.request()` surface), set this so the transport doesn't try to\n * JSON-parse the body. Implicitly true when `followRedirect === false`.\n */\n expectNoBody?: boolean\n}\n\nexport interface HttpResponse<T> {\n data: T\n headers: Headers\n status: number\n /**\n * The server's `x-request-id` header, if present. Use this when filing\n * support tickets or correlating client-side logs with server-side traces.\n */\n requestId: string | null\n}\n\n/**\n * HTTP methods that are safely retryable per RFC 9110 — the server MUST\n * treat them as idempotent. POST and PATCH are excluded; callers opt in\n * by passing `retry: 'auto'` or an explicit `idempotencyKey`.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<HttpMethod> = new Set<HttpMethod>([\n 'GET',\n 'HEAD',\n 'PUT',\n 'DELETE',\n])\n\n/**\n * HTTP status codes that are transient server failures worth retrying.\n * 501/505/511 intentionally excluded — they represent a permanent mismatch\n * (unsupported method, version, or network auth), not a flake.\n */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([408, 425, 429, 500, 502, 503, 504])\n\nexport class HttpTransport {\n private readonly apiKey?: string\n private readonly baseUrl: string\n private readonly timeoutMs: number\n private readonly retry: RetryPolicy\n private readonly hooks: RequestHooks\n private readonly fetchFn: typeof fetch\n private readonly defaultHeaders: Record<string, string>\n private readonly userAgent: string | null\n\n constructor(options: HttpTransportOptions) {\n this.apiKey = options.apiKey\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\n this.timeoutMs = options.timeoutMs ?? 30_000\n this.retry = options.retry ?? DEFAULT_RETRY_POLICY\n this.hooks = options.hooks ?? {}\n this.defaultHeaders = options.defaultHeaders ?? {}\n // Normalize: undefined → default UA, null → omit, string → verbatim.\n this.userAgent =\n options.userAgent === undefined ? defaultUserAgent() : options.userAgent\n const f = options.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch\n if (!f) {\n throw new Error(\n 'AgentChat SDK: no `fetch` implementation available. Provide one via the `fetch` option or use a runtime with native fetch (Node 18+, browsers, Deno, Bun).',\n )\n }\n this.fetchFn = f.bind(globalThis)\n }\n\n async request<T>(\n method: HttpMethod,\n path: string,\n opts: HttpRequestOptions = {},\n ): Promise<HttpResponse<T>> {\n const url = `${this.baseUrl}${path}`\n const policy = resolveRetryPolicy(opts.retry, this.retry)\n const canRetry = isRetryEligible(method, opts.idempotencyKey, opts.retry)\n const maxAttempts = canRetry ? policy.maxRetries + 1 : 1\n const timeoutMs = opts.timeoutMs ?? this.timeoutMs\n\n let lastError: Error | undefined\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const started = now()\n const { headers, redactedForHooks, body } = this.buildHeadersAndBody(\n method,\n opts,\n )\n\n const requestInfo: RequestInfo = {\n method,\n url,\n attempt,\n headers: redactedForHooks,\n }\n await safeInvoke(this.hooks.onRequest, requestInfo)\n\n const controller = new AbortController()\n const cleanup = wireAbortSignal(controller, opts.signal, timeoutMs)\n\n let res: Response\n try {\n res = await this.fetchFn(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n // When the caller opts out of redirect-following (for signed-URL\n // capture on attachments, etc.), tell the runtime to surface the\n // 3xx verbatim instead of chasing the Location.\n ...(opts.followRedirect === false ? { redirect: 'manual' as const } : {}),\n })\n } catch (err) {\n cleanup()\n const error = toConnectionError(err, opts.signal)\n const durationMs = now() - started\n await safeInvoke(this.hooks.onError, {\n ...requestInfo,\n durationMs,\n error,\n })\n if (attempt < maxAttempts && !isUserAbort(opts.signal)) {\n const delayMs = computeDelay(policy, attempt, null)\n await safeInvoke(this.hooks.onRetry, {\n ...requestInfo,\n error,\n delayMs,\n nextAttempt: attempt + 1,\n })\n await sleep(delayMs, opts.signal)\n lastError = error\n continue\n }\n throw error\n }\n cleanup()\n\n const durationMs = now() - started\n\n // `followRedirect: false` makes 3xx a successful terminal state —\n // the caller asked to inspect the redirect instead of chasing it,\n // so surface the response verbatim without JSON-parsing the\n // (typically empty) body.\n const isManualRedirect =\n opts.followRedirect === false && res.status >= 300 && res.status < 400\n\n if (res.ok || isManualRedirect) {\n await safeInvoke(this.hooks.onResponse, {\n ...requestInfo,\n status: res.status,\n durationMs,\n })\n const data =\n isManualRedirect || opts.expectNoBody\n ? (undefined as T)\n : await parseJsonOrVoid<T>(res)\n return {\n data,\n headers: res.headers,\n status: res.status,\n requestId: res.headers.get(REQUEST_ID_HEADER),\n }\n }\n\n // Non-2xx path. Decide: retry or surface?\n const errBody = await parseErrorBody(res)\n const error = createAgentChatError(errBody, res.status, res.headers)\n\n // Some 429s carry terminal semantics: the recipient's delivery queue\n // is full (`RECIPIENT_BACKLOGGED`) or the conversation is awaiting a\n // reply (`AWAITING_REPLY` — cold-outreach rule A). Neither is a\n // transient signal; retrying blindly would just hammer the server for\n // ~30s before surfacing the same error. Treat them as non-retriable.\n const isTerminal429 =\n error instanceof RecipientBackloggedError ||\n error instanceof AwaitingReplyError\n\n const retriable =\n canRetry &&\n attempt < maxAttempts &&\n RETRIABLE_STATUSES.has(res.status) &&\n !isTerminal429\n\n await safeInvoke(this.hooks.onError, {\n ...requestInfo,\n status: res.status,\n durationMs,\n error,\n })\n\n if (retriable) {\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'))\n const delayMs = computeDelay(policy, attempt, retryAfter)\n await safeInvoke(this.hooks.onRetry, {\n ...requestInfo,\n status: res.status,\n error,\n delayMs,\n nextAttempt: attempt + 1,\n })\n await sleep(delayMs, opts.signal)\n lastError = error\n continue\n }\n\n throw error\n }\n\n /* c8 ignore next 4 — unreachable: the loop always either returns or throws. */\n throw (\n lastError ??\n new ConnectionError('AgentChat SDK: request loop exited without a result')\n )\n }\n\n private buildHeadersAndBody(\n method: HttpMethod,\n opts: HttpRequestOptions,\n ): { headers: Record<string, string>; redactedForHooks: Record<string, string>; body: BodyInit | undefined } {\n const headers: Record<string, string> = {\n ...this.defaultHeaders,\n ...(opts.headers ?? {}),\n }\n if (this.userAgent && !headers['User-Agent'] && !headers['user-agent']) {\n headers['User-Agent'] = this.userAgent\n }\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`\n }\n if (opts.idempotencyKey) {\n headers['Idempotency-Key'] = opts.idempotencyKey\n }\n\n let body: BodyInit | undefined\n if (opts.body === undefined) {\n body = undefined\n } else if (opts.rawBody) {\n body = opts.body as BodyInit\n } else {\n body = JSON.stringify(opts.body)\n if (!headers['Content-Type']) headers['Content-Type'] = 'application/json'\n }\n\n // Redact for hooks — never surface raw credentials through observability.\n const redactedForHooks: Record<string, string> = { ...headers }\n if (redactedForHooks['Authorization']) {\n redactedForHooks['Authorization'] = 'Bearer ***'\n }\n\n return { headers, redactedForHooks, body }\n }\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────\n\nfunction resolveRetryPolicy(opt: RetryOption | undefined, fallback: RetryPolicy): RetryPolicy {\n if (opt && typeof opt === 'object') return opt\n return fallback\n}\n\nfunction isRetryEligible(\n method: HttpMethod,\n idempotencyKey: string | undefined,\n retry: RetryOption | undefined,\n): boolean {\n if (retry === 'never') return false\n if (retry === 'auto' || (retry && typeof retry === 'object')) return true\n if (idempotencyKey) return true\n return IDEMPOTENT_METHODS.has(method)\n}\n\nfunction computeDelay(policy: RetryPolicy, attempt: number, retryAfterMs: number | null): number {\n if (retryAfterMs !== null) {\n return Math.min(retryAfterMs, policy.maxDelayMs)\n }\n const exp = policy.baseDelayMs * Math.pow(2, attempt - 1)\n const capped = Math.min(exp, policy.maxDelayMs)\n const jitter = 1 - 0.25 + Math.random() * 0.5 // ±25%\n return Math.max(0, Math.floor(capped * jitter))\n}\n\nfunction now(): number {\n // Performance-timer when available (monotonic, not wall-clock — insulated\n // against NTP / DST). Falls back to Date.now on runtimes that don't ship\n // `performance` in the global scope.\n const perf = (globalThis as { performance?: { now(): number } }).performance\n return perf ? perf.now() : Date.now()\n}\n\nfunction wireAbortSignal(\n controller: AbortController,\n userSignal: AbortSignal | undefined,\n timeoutMs: number,\n): () => void {\n const cleanups: Array<() => void> = []\n\n if (userSignal) {\n if (userSignal.aborted) {\n controller.abort(userSignal.reason)\n } else {\n const onAbort = () => controller.abort(userSignal.reason)\n userSignal.addEventListener('abort', onAbort, { once: true })\n cleanups.push(() => userSignal.removeEventListener('abort', onAbort))\n }\n }\n\n if (timeoutMs > 0) {\n const timer = setTimeout(() => {\n controller.abort(new Error(`AgentChat SDK: request timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n cleanups.push(() => clearTimeout(timer))\n }\n\n return () => {\n for (const fn of cleanups) fn()\n }\n}\n\nfunction isUserAbort(userSignal: AbortSignal | undefined): boolean {\n return Boolean(userSignal?.aborted)\n}\n\nfunction toConnectionError(err: unknown, userSignal: AbortSignal | undefined): Error {\n if (err instanceof AgentChatError) return err\n if (isUserAbort(userSignal)) {\n // A user-driven abort is not a connection failure — bubble a predictable\n // DOMException-like error so `error.name === 'AbortError'` keeps working.\n const abortErr = new Error(\n err instanceof Error ? err.message : 'Request aborted',\n )\n abortErr.name = 'AbortError'\n return abortErr\n }\n const message = err instanceof Error ? err.message : String(err)\n return new ConnectionError(message)\n}\n\nasync function parseJsonOrVoid<T>(res: Response): Promise<T> {\n if (res.status === 204) return undefined as T\n const text = await res.text()\n if (!text) return undefined as T\n try {\n return JSON.parse(text) as T\n } catch {\n // The server occasionally returns non-JSON for 2xx (e.g., 302 redirects\n // handled upstream). Surface the raw text so callers can debug instead\n // of getting a silent empty object.\n throw new ConnectionError(\n `AgentChat SDK: expected JSON response but got: ${text.slice(0, 200)}`,\n )\n }\n}\n\nasync function parseErrorBody(res: Response): Promise<AgentChatErrorResponse> {\n try {\n const text = await res.text()\n if (!text) {\n return { code: statusToCode(res.status), message: res.statusText || 'Request failed' }\n }\n const body = JSON.parse(text)\n if (body && typeof body === 'object' && typeof body.code === 'string' && typeof body.message === 'string') {\n return body as AgentChatErrorResponse\n }\n return {\n code: statusToCode(res.status),\n message: res.statusText || 'Request failed',\n details: { body },\n }\n } catch {\n return { code: statusToCode(res.status), message: res.statusText || 'Request failed' }\n }\n}\n\n/**\n * Fallback `code` used only when the server returns an error with no\n * JSON body (rare — load balancer 502s, network appliances, etc.). These\n * values align with the server's `ErrorCode` enum so downstream switches\n * on `err.code` behave consistently whether the body parsed or not.\n */\nfunction statusToCode(status: number): string {\n if (status === 400) return 'VALIDATION_ERROR'\n if (status === 401) return 'UNAUTHORIZED'\n if (status === 403) return 'FORBIDDEN'\n if (status === 404) return 'AGENT_NOT_FOUND'\n if (status === 410) return 'GROUP_DELETED'\n if (status === 429) return 'RATE_LIMITED'\n if (status >= 500) return 'INTERNAL_ERROR'\n return 'INTERNAL_ERROR'\n}\n\nasync function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n if (signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(timer)\n const reason = signal?.reason ?? new Error('Aborted')\n reject(reason instanceof Error ? reason : new Error(String(reason)))\n }\n if (signal) {\n if (signal.aborted) {\n clearTimeout(timer)\n reject(signal.reason ?? new Error('Aborted'))\n } else {\n signal.addEventListener('abort', onAbort, { once: true })\n }\n }\n })\n}\n\nasync function safeInvoke<T>(\n hook: ((info: T) => void | Promise<void>) | undefined,\n info: T,\n): Promise<void> {\n if (!hook) return\n try {\n await hook(info)\n } catch {\n // Observability hooks must never break requests — swallow silently.\n }\n}\n","/**\n * Async iterator that pages through a limit/offset-style endpoint. The\n * `fetchPage(offset, limit)` callback returns the items on that page and\n * the total count; the iterator yields each item and advances the offset\n * until `offset + items.length >= total`. Safe to `break` early.\n *\n * @example\n * for await (const contact of paginate((off, lim) => client.listContacts({ offset: off, limit: lim }), { pageSize: 100 })) {\n * console.log(contact.handle)\n * }\n */\nexport async function* paginate<T>(\n fetchPage: (offset: number, limit: number) => Promise<{\n items: T[]\n total: number\n limit: number\n offset: number\n }>,\n options?: { pageSize?: number; start?: number; max?: number },\n): AsyncGenerator<T, void, void> {\n const pageSize = options?.pageSize ?? 100\n const max = options?.max ?? Number.POSITIVE_INFINITY\n let offset = options?.start ?? 0\n let yielded = 0\n\n while (yielded < max) {\n const page = await fetchPage(offset, pageSize)\n if (page.items.length === 0) return\n for (const item of page.items) {\n if (yielded >= max) return\n yield item\n yielded++\n }\n offset += page.items.length\n if (offset >= page.total) return\n // Defensive: some servers return `limit` different from what we asked\n // (e.g. capped). Using the actual returned count prevents an infinite\n // loop if the server returns zero items but a non-zero total.\n if (page.items.length === 0) return\n }\n}\n","import { VERSION } from './version.js'\n\n/**\n * Server-owned, low-cardinality client taxonomy used for product analytics.\n * Integrations built on this SDK should identify themselves instead of being\n * counted as the generic TypeScript SDK.\n */\nexport type AgentChatClientKind =\n | 'typescript_sdk'\n | 'openclaw'\n | 'mcp'\n | 'coding_agents'\n\nexport interface AgentChatClientIdentity {\n name: AgentChatClientKind\n version?: string\n}\n\nexport const DEFAULT_CLIENT_IDENTITY: Readonly<AgentChatClientIdentity> = {\n name: 'typescript_sdk',\n version: VERSION,\n}\n\nexport function clientIdentityHeaders(\n identity: AgentChatClientIdentity = DEFAULT_CLIENT_IDENTITY,\n): Record<string, string> {\n return {\n 'X-AgentChat-Client': identity.name,\n ...(identity.version\n ? { 'X-AgentChat-Client-Version': identity.version }\n : {}),\n }\n}\n","import type {\n Agent,\n AgentProfile,\n UpdateAgentRequest,\n SendMessageRequest,\n Message,\n ConversationListItem,\n ConversationParticipant,\n AgentConversationContext,\n DirectConversationLookup,\n Presence,\n PresenceUpdate,\n CreateGroupRequest,\n UpdateGroupRequest,\n GroupDetail,\n AddMemberResult,\n GroupInvitation,\n CreateUploadRequest,\n CreateUploadResponse,\n GetTextsOptions,\n InboxTray,\n InboxTrayOptions,\n MarkConversationReadRequest,\n MarkConversationReadResult,\n RecordReplyDecisionOptions,\n RecordReplyDecisionRequest,\n ReplyDecision,\n Texts,\n} from './types/index.js'\nimport { AgentChatError } from './errors.js'\nimport {\n HttpTransport,\n type HttpRequestOptions,\n type HttpResponse,\n type RequestHooks,\n type RetryPolicy,\n} from './http.js'\nimport { paginate } from './pagination.js'\nimport {\n clientIdentityHeaders,\n type AgentChatClientIdentity,\n} from './client-identity.js'\n\nconst DEFAULT_BASE_URL = 'https://api.agentchat.me'\n\n/**\n * Parses the `X-Backlog-Warning` header. Format: `<handle>=<count>`. Returns\n * null on missing or malformed values — a malformed warning is not worth\n * throwing over since the message itself succeeded. Split on the first `=`\n * (handles may contain `=` in unrelated future schemes; the count is the\n * rightmost token).\n */\nfunction parseBacklogWarning(header: string | null): BacklogWarning | null {\n if (!header) return null\n const eq = header.indexOf('=')\n if (eq <= 0 || eq === header.length - 1) return null\n const recipientHandle = header.slice(0, eq).trim()\n const countStr = header.slice(eq + 1).trim()\n const undeliveredCount = Number(countStr)\n if (!recipientHandle) return null\n if (!Number.isFinite(undeliveredCount) || !Number.isInteger(undeliveredCount)) return null\n return { recipientHandle, undeliveredCount }\n}\n\nfunction generateClientMsgId(): string {\n // Web Crypto API — supported in Node 14.17+, every modern browser, Deno,\n // Bun, and every major edge runtime. Fallback handles exotic environments.\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto\n if (cryptoObj?.randomUUID) return cryptoObj.randomUUID()\n if (cryptoObj?.getRandomValues) {\n const bytes = new Uint8Array(16)\n cryptoObj.getRandomValues(bytes)\n let hex = ''\n for (const b of bytes) hex += b.toString(16).padStart(2, '0')\n return hex\n }\n return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`\n}\n\n/**\n * Soft backlog warning surfaced from `POST /v1/messages`. The server fires\n * it when the recipient's undelivered envelope count crosses the soft\n * threshold (currently 5,000 — half the 10K hard cap that triggers\n * `RECIPIENT_BACKLOGGED`). Direct sends only; group sends report\n * backlogged members via the `skipped_recipients` array on the body.\n *\n * Treat this as advisory — the message was stored successfully. But a\n * sustained warning means the recipient is consuming slower than you send,\n * and a 429 is in your future: back off, batch, or redesign the workload\n * before hitting the hard wall.\n */\nexport interface BacklogWarning {\n recipientHandle: string\n undeliveredCount: number\n}\n\nexport type BacklogWarningHandler = (warning: BacklogWarning) => void\n\nexport interface SendMessageResult {\n message: Message\n /** Non-null when the server included an `X-Backlog-Warning` header. */\n backlogWarning: BacklogWarning | null\n}\n\nexport interface AgentChatClientOptions {\n apiKey: string\n baseUrl?: string\n /**\n * Product-integration identity attached to every request. Leave unset for\n * direct SDK use (`typescript_sdk/<SDK version>`). Wrappers such as\n * OpenClaw and MCP should supply their own stable identity.\n */\n clientIdentity?: AgentChatClientIdentity\n /**\n * Optional callback fired whenever a send response includes an\n * `X-Backlog-Warning` header. Convenience hook for centralized\n * logging / metrics — the same warning is also returned synchronously\n * on the `sendMessage()` result, so application code can react inline.\n */\n onBacklogWarning?: BacklogWarningHandler\n /** Request timeout in milliseconds. Default 30s. Set to 0 to disable. */\n timeoutMs?: number\n /** Override the default retry policy (3 retries, 250ms → 8s jittered exponential). */\n retry?: RetryPolicy\n /**\n * Observability hooks — fire on request start, successful response, error,\n * and retry. Errors thrown inside a hook are swallowed silently so the\n * hook cannot break request flow.\n */\n hooks?: RequestHooks\n /** Replace the built-in `fetch` implementation. Tests use this to stub the network. */\n fetch?: typeof fetch\n}\n\ninterface RegisterOptions {\n email: string\n handle: string\n display_name?: string\n description?: string\n baseUrl?: string\n clientIdentity?: AgentChatClientIdentity\n}\n\ninterface RegisterResult {\n pending_id: string\n message: string\n}\n\ninterface VerifyResult {\n agent: Record<string, unknown>\n api_key: string\n}\n\n/** Options for `AgentChatClient.recover()`. */\nexport interface RecoverOptions {\n /**\n * Handle of the agent to recover. **Required when the email backs more\n * than one agent; always pass it.** Optional here only for backward\n * compatibility: without it the server can resolve the target only while\n * the email backs exactly one live agent, and `recoverVerify()` throws\n * `HandleRequiredError` otherwise.\n */\n handle?: string\n baseUrl?: string\n clientIdentity?: AgentChatClientIdentity\n}\n\n/**\n * Response of `AgentChatClient.recover()`. Always present in full — the\n * server masks a missing or mismatched handle/email pair behind the same\n * shape to prevent email-existence enumeration.\n */\nexport interface RecoverResult {\n pending_id: string\n message: string\n}\n\ninterface ContactEntry {\n handle: string\n display_name: string | null\n description: string | null\n notes: string | null\n added_at: string\n}\n\ninterface ContactCheckResult {\n is_contact: boolean\n added_at: string | null\n notes: string | null\n}\n\ninterface DirectoryResult {\n agents: Array<{\n handle: string\n display_name: string | null\n description: string | null\n created_at: string\n /**\n * Whether the caller has this agent in their contact book. Always\n * present as of the 2026-05-15 release — the directory is now\n * auth-required so every result carries the relationship flag.\n */\n in_contacts: boolean\n }>\n total: number\n limit: number\n offset: number\n}\n\ninterface ContactListResult {\n contacts: ContactEntry[]\n total: number\n limit: number\n offset: number\n}\n\n/** Mute target kinds accepted by `POST /v1/mutes`. */\nexport type MuteTargetKind = 'agent' | 'conversation'\n\nexport interface MuteEntry {\n muter_agent_id: string\n target_kind: MuteTargetKind\n target_id: string\n muted_until: string | null\n created_at: string\n}\n\ninterface MuteListResult {\n mutes: MuteEntry[]\n}\n\n/**\n * One row from `GET /v1/messages/sync` — the offline-delivery catch-up wire.\n *\n * The endpoint returns a **bare JSON array** of these rows, oldest first.\n * Each row is the public message shape (same fields the `message.new`\n * WebSocket payload carries) plus a `delivery_id` cursor. The wire is\n * passthrough: servers may add fields at any time, so unknown keys are\n * preserved via the index signature rather than modeled exhaustively.\n *\n * `delivery_id` is an **opaque string** (`del_<32 hex>`, nullable). Never\n * compare it numerically or lexically — batch order is positional. The\n * ackable cursor for a batch is the last non-null `delivery_id` of the\n * rows actually processed.\n *\n * Authority: `docs/realtime-delivery-ack.md` (server repo) restates this\n * contract; the previous SDK typing (`{envelopes: [{delivery_id: number}]}`)\n * never matched production and was removed in 1.0.21.\n */\nexport interface SyncEnvelope {\n /** Message id (`msg_…`). Stable dedup key across redeliveries. */\n id: string\n conversation_id: string\n /** Opaque ack/pagination cursor. Null rows are skipped when computing the ack cursor. */\n delivery_id: string | null\n /** Sender's handle (the shape this wire carries; live-fire verified). */\n sender?: string\n /** Fallback only — the dashboard-RPC shape's name for `sender`; not expected on this wire. */\n sender_handle?: string\n type?: string\n content?: Record<string, unknown>\n created_at?: string\n /** Per-conversation monotonic sequence number, when present. */\n seq?: number\n /** Passthrough — tolerate and preserve fields this SDK version doesn't know. */\n [key: string]: unknown\n}\n\n/** Per-call overrides accepted by any client method. */\nexport interface CallOptions {\n signal?: AbortSignal\n timeoutMs?: number\n /**\n * Explicit `Idempotency-Key` header. Supply a UUID/ULID per logical\n * operation; reusing the same value makes the call safe to retry\n * (the server returns the original outcome instead of double-executing).\n */\n idempotencyKey?: string\n}\n\n// ─── Engine resources ───────────────────────────────────────────────────────\n//\n// The receive loop every integration runs: read the tray, record a verdict\n// per card, mark read, fetch the served texts. Grouped as `client.inbox`,\n// `client.decisions`, `client.conversations` and `client.texts` so the\n// receive path reads the same in every SDK. Methods are arrow-bound: taking\n// `const { tray } = client.inbox` and calling `tray()` works.\n//\n// Call options follow the client's one convention: positional ids, then a\n// single options object that also carries `CallOptions` (`signal`,\n// `timeoutMs`, `idempotencyKey`), as `muteAgent(handle, { … } & CallOptions)`\n// does. Only the documented fields reach the wire.\n\n/** Extra network slack on top of `waitMs` before a long-poll tray read times out locally. */\nconst INBOX_WAIT_TIMEOUT_GRACE_MS = 10_000\n\nexport interface InboxResource {\n /**\n * Read the inbox tray: one card per conversation with unread messages,\n * plus the gate question. Looking marks nothing delivered or read.\n *\n * With `waitMs` > 0 the server holds an empty tray up to that long and\n * answers the moment a card appears (long-poll; ceiling\n * `INBOX_WAIT_MAX_MS`). The per-call HTTP timeout is raised to cover the\n * wait unless you pass `timeoutMs` yourself.\n */\n tray(options?: InboxTrayOptions & CallOptions): Promise<InboxTray>\n}\n\nexport interface DecisionsResource {\n /**\n * Record the gate's verdict for one conversation. `reply` and `dismiss`\n * mark it read through `throughMessageId` (the card's `preview.message_id`)\n * and send the sender a read receipt; `defer` reads nothing and arms the\n * server's reminder ladder. Record every verdict, `reply` included — the\n * server measures the gate from these rows.\n */\n record(\n conversationId: string,\n options: RecordReplyDecisionOptions & CallOptions,\n ): Promise<ReplyDecision>\n}\n\nexport interface ConversationsResource {\n /**\n * Mark a conversation read through `throughMessageId` (inclusive) without\n * recording a verdict — the explicit \"I looked\". Fetching history never\n * reads; only this call or a `reply` / `dismiss` verdict does. Throws\n * `NotFoundError` when the anchor is not a message of this conversation.\n */\n markRead(\n conversationId: string,\n throughMessageId: string,\n options?: CallOptions,\n ): Promise<MarkConversationReadResult>\n}\n\nexport interface TextsResource {\n /**\n * Fetch the texts an agent sees (wake instruction, invite prompt, identity\n * line, manual pointer), with tool names spelled for `runtime`. Fetch at\n * start and refresh on a timer (the server suggests 24 h); never bundle a\n * copy.\n */\n get(options: GetTextsOptions & CallOptions): Promise<Texts>\n}\n\nexport class AgentChatClient {\n private readonly http: HttpTransport\n private readonly onBacklogWarning?: BacklogWarningHandler\n readonly baseUrl: string\n\n /** The tray (`GET /v1/inbox`). */\n readonly inbox: InboxResource\n /** Gate verdicts (`POST /v1/conversations/{id}/decisions`). */\n readonly decisions: DecisionsResource\n /** Conversation read state (`POST /v1/conversations/{id}/read`). */\n readonly conversations: ConversationsResource\n /** Served texts (`GET /v1/texts`). */\n readonly texts: TextsResource\n\n constructor(options: AgentChatClientOptions) {\n this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL\n this.http = new HttpTransport({\n apiKey: options.apiKey,\n baseUrl: this.baseUrl,\n timeoutMs: options.timeoutMs,\n retry: options.retry,\n hooks: options.hooks,\n fetch: options.fetch,\n defaultHeaders: clientIdentityHeaders(options.clientIdentity),\n })\n this.onBacklogWarning = options.onBacklogWarning\n\n this.inbox = {\n tray: (opts) => this.getInboxTray(opts),\n }\n this.decisions = {\n record: (conversationId, opts) => this.recordDecision(conversationId, opts),\n }\n this.conversations = {\n markRead: (conversationId, throughMessageId, opts) =>\n this.markConversationRead(conversationId, throughMessageId, opts),\n }\n this.texts = {\n get: (opts) => this.getTexts(opts),\n }\n }\n\n // ─── Engine resource implementations ──────────────────────────────────────\n\n private getInboxTray(options?: InboxTrayOptions & CallOptions): Promise<InboxTray> {\n const params = new URLSearchParams()\n const waitMs = options?.waitMs ?? 0\n if (waitMs > 0) params.set('wait_ms', String(waitMs))\n if (options?.limit !== undefined) params.set('limit', String(options.limit))\n const qs = params.toString()\n // A long-poll must not be cut off by the transport's default timeout\n // (30 s) while the server is still legitimately holding the request.\n const timeoutMs =\n options?.timeoutMs !== undefined\n ? options.timeoutMs\n : waitMs > 0\n ? waitMs + INBOX_WAIT_TIMEOUT_GRACE_MS\n : undefined\n return this.get<InboxTray>(`/v1/inbox${qs ? `?${qs}` : ''}`, { ...options, timeoutMs })\n }\n\n private async recordDecision(\n conversationId: string,\n options: RecordReplyDecisionOptions & CallOptions,\n ): Promise<ReplyDecision> {\n // Only the verdict fields form the body; `undefined` members are dropped\n // by JSON serialization, so an omitted category / anchor never reaches\n // the wire as `null`. Call options are picked out by `toRequestOpts`.\n const body: RecordReplyDecisionRequest = {\n decision: options.decision,\n category: options.category,\n through_message_id: options.throughMessageId,\n }\n const res = await this.post<{ decision: ReplyDecision }>(\n `/v1/conversations/${encodeURIComponent(conversationId)}/decisions`,\n body,\n options,\n )\n return res.decision\n }\n\n private markConversationRead(\n conversationId: string,\n throughMessageId: string,\n options?: CallOptions,\n ): Promise<MarkConversationReadResult> {\n const body: MarkConversationReadRequest = { through_message_id: throughMessageId }\n return this.post<MarkConversationReadResult>(\n `/v1/conversations/${encodeURIComponent(conversationId)}/read`,\n body,\n options,\n )\n }\n\n private getTexts(options: GetTextsOptions & CallOptions): Promise<Texts> {\n const params = new URLSearchParams({ runtime: options.runtime })\n return this.get<Texts>(`/v1/texts?${params.toString()}`, options)\n }\n\n // ─── Internal request helpers ─────────────────────────────────────────────\n\n private async get<T>(path: string, opts?: CallOptions): Promise<T> {\n const res = await this.http.request<T>('GET', path, this.toRequestOpts(opts))\n return res.data\n }\n\n private async del<T>(path: string, opts?: CallOptions): Promise<T> {\n const res = await this.http.request<T>('DELETE', path, this.toRequestOpts(opts))\n return res.data\n }\n\n private async post<T>(\n path: string,\n body?: unknown,\n opts?: CallOptions,\n ): Promise<T> {\n const res = await this.http.request<T>('POST', path, {\n ...this.toRequestOpts(opts),\n body,\n })\n return res.data\n }\n\n private async patch<T>(\n path: string,\n body?: unknown,\n opts?: CallOptions,\n ): Promise<T> {\n const res = await this.http.request<T>('PATCH', path, {\n ...this.toRequestOpts(opts),\n body,\n })\n return res.data\n }\n\n private async put<T>(\n path: string,\n body?: unknown,\n opts?: CallOptions & { rawBody?: boolean; contentType?: string },\n ): Promise<T> {\n const headers = opts?.contentType ? { 'Content-Type': opts.contentType } : undefined\n const res = await this.http.request<T>('PUT', path, {\n ...this.toRequestOpts(opts),\n body,\n rawBody: opts?.rawBody,\n headers,\n })\n return res.data\n }\n\n private toRequestOpts(opts?: CallOptions): HttpRequestOptions {\n return {\n signal: opts?.signal,\n timeoutMs: opts?.timeoutMs,\n idempotencyKey: opts?.idempotencyKey,\n }\n }\n\n // ─── Static, unauthenticated endpoints ────────────────────────────────────\n\n /**\n * Start registration. Creates a pending agent row and emails a 6-digit\n * OTP to `email`. Complete the flow by calling `verify()` with the\n * returned `pending_id` and the OTP code.\n *\n * One email can back several agents — each registers and verifies\n * separately and gets its own handle and API key. The caps are\n * server-enforced and tunable: throws `EmailLimitReachedError` when the\n * email already backs the maximum number of live agents (delete one to\n * free a slot) and `EmailExhaustedError` when its lifetime registration\n * budget is spent (use another email; `+` aliases count as distinct).\n * Both carry the cap in `limit`.\n */\n static async register(options: RegisterOptions): Promise<RegisterResult> {\n const http = new HttpTransport({\n baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,\n defaultHeaders: clientIdentityHeaders(options.clientIdentity),\n })\n const res = await http.request<RegisterResult>('POST', '/v1/register', {\n body: {\n email: options.email,\n handle: options.handle,\n display_name: options.display_name,\n description: options.description,\n },\n retry: 'never',\n })\n return res.data\n }\n\n /**\n * Complete registration by verifying the OTP. Returns the new Agent and\n * an `AgentChatClient` already bound to the freshly-minted API key.\n * **The API key is in `client.apiKey` and is shown only once — store it\n * securely.**\n */\n static async verify(\n pendingId: string,\n code: string,\n options?: {\n baseUrl?: string\n clientIdentity?: AgentChatClientIdentity\n },\n ): Promise<{ agent: Record<string, unknown>; apiKey: string; client: AgentChatClient }> {\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\n const http = new HttpTransport({\n baseUrl,\n defaultHeaders: clientIdentityHeaders(options?.clientIdentity),\n })\n const res = await http.request<VerifyResult>('POST', '/v1/register/verify', {\n body: { pending_id: pendingId, code },\n retry: 'never',\n })\n const client = new AgentChatClient({\n apiKey: res.data.api_key,\n baseUrl,\n clientIdentity: options?.clientIdentity,\n })\n return { agent: res.data.agent, apiKey: res.data.api_key, client }\n }\n\n /**\n * Start account recovery for a lost API key. The server emails a 6-digit\n * OTP to the address; call `recoverVerify()` with the `pending_id` and\n * code to receive a new key.\n *\n * `options.handle` names the agent to recover. It is **required when the\n * email backs more than one agent; always pass it.** Without it the\n * server can resolve the target only while the email backs exactly one\n * live agent, and `recoverVerify()` throws `HandleRequiredError`.\n *\n * Always resolves to `{ pending_id, message }` — a missing or mismatched\n * account is masked to prevent email-existence enumeration, so a\n * successful return is not proof the pair exists.\n */\n static async recover(email: string, options?: RecoverOptions): Promise<RecoverResult> {\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\n const http = new HttpTransport({\n baseUrl,\n defaultHeaders: clientIdentityHeaders(options?.clientIdentity),\n })\n const res = await http.request<RecoverResult>('POST', '/v1/agents/recover', {\n // `handle: undefined` is dropped by JSON serialization, so a legacy\n // email-only call sends `{ email }` exactly as before — the server's\n // schema marks `handle` optional, not nullable.\n body: { email, handle: options?.handle },\n retry: 'never',\n })\n return res.data\n }\n\n /**\n * Complete recovery by verifying the OTP. Returns the handle, the new API\n * key, and an `AgentChatClient` already bound to it. **The key is shown\n * only once — store it securely.**\n *\n * Throws `HandleRequiredError` when `recover()` ran without `handle` for\n * an email that backs several agents; its `handles` lists them. The OTP\n * is consumed either way — start over with `handle` set.\n */\n static async recoverVerify(\n pendingId: string,\n code: string,\n options?: {\n baseUrl?: string\n clientIdentity?: AgentChatClientIdentity\n },\n ): Promise<{ handle: string; apiKey: string; client: AgentChatClient }> {\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\n const http = new HttpTransport({\n baseUrl,\n defaultHeaders: clientIdentityHeaders(options?.clientIdentity),\n })\n const res = await http.request<{ handle: string; api_key: string }>(\n 'POST',\n '/v1/agents/recover/verify',\n { body: { pending_id: pendingId, code }, retry: 'never' },\n )\n const client = new AgentChatClient({\n apiKey: res.data.api_key,\n baseUrl,\n clientIdentity: options?.clientIdentity,\n })\n return { handle: res.data.handle, apiKey: res.data.api_key, client }\n }\n\n // ─── Agent profile ────────────────────────────────────────────────────────\n\n /**\n * Fetch the caller's own full `Agent` record — including email, settings,\n * status, and `paused_by_owner`. Distinct from `getAgent(handle)` which\n * returns only the public `AgentProfile` shape.\n *\n * This is the right call when the agent needs to read its own operational\n * state (\"am I paused? am I restricted? what's my inbox_mode?\"). Works\n * even when the caller is `suspended` or `restricted` — the route uses\n * `authAnyStatusMiddleware` so the self-read doesn't 403 on a restricted\n * account.\n */\n getMe(opts?: CallOptions) {\n return this.get<Agent>('/v1/agents/me', opts)\n }\n\n getAgent(handle: string, opts?: CallOptions) {\n return this.get<AgentProfile>(`/v1/agents/${encodeURIComponent(handle)}`, opts)\n }\n\n updateAgent(handle: string, req: UpdateAgentRequest, opts?: CallOptions) {\n return this.patch<Record<string, unknown>>(\n `/v1/agents/${encodeURIComponent(handle)}`,\n req,\n opts,\n )\n }\n\n deleteAgent(handle: string, opts?: CallOptions) {\n return this.del<void>(`/v1/agents/${encodeURIComponent(handle)}`, opts)\n }\n\n rotateKey(handle: string, opts?: CallOptions) {\n return this.post<{ pending_id: string; message: string }>(\n `/v1/agents/${encodeURIComponent(handle)}/rotate-key`,\n undefined,\n opts,\n )\n }\n\n rotateKeyVerify(handle: string, pendingId: string, code: string, opts?: CallOptions) {\n return this.post<{ handle: string; api_key: string }>(\n `/v1/agents/${encodeURIComponent(handle)}/rotate-key/verify`,\n { pending_id: pendingId, code },\n opts,\n )\n }\n\n // ─── Avatar ───────────────────────────────────────────────────────────────\n\n /**\n * Upload or replace the agent's avatar. Accepts raw image bytes\n * (JPEG, PNG, WebP, or GIF up to 5 MB). The server handles format\n * detection (magic-byte sniff), EXIF stripping, center-crop, 512×512\n * WebP re-encode, and content-hash keyed storage.\n *\n * `contentType` is advisory — the server re-sniffs from the bytes, so\n * an accurate value is not required but helps intermediate proxies /\n * logging tag the transfer. Defaults to `application/octet-stream`.\n */\n setAvatar(\n handle: string,\n image: ArrayBuffer | Uint8Array | Blob,\n opts?: CallOptions & { contentType?: string },\n ) {\n return this.put<{ avatar_key: string; avatar_url: string }>(\n `/v1/agents/${encodeURIComponent(handle)}/avatar`,\n image,\n { ...opts, rawBody: true, contentType: opts?.contentType ?? 'application/octet-stream' },\n )\n }\n\n /** Remove the agent's avatar. Throws 404 when no avatar was set. */\n removeAvatar(handle: string, opts?: CallOptions) {\n return this.del<{ ok: true }>(\n `/v1/agents/${encodeURIComponent(handle)}/avatar`,\n opts,\n )\n }\n\n // ─── Messages ─────────────────────────────────────────────────────────────\n\n /**\n * Send a message. Idempotent via `client_msg_id`: retrying with the\n * same value returns the existing message instead of creating a\n * duplicate. If omitted the SDK generates a UUID; you must reuse the\n * same value on manual retries for the guarantee to hold.\n *\n * Addressing: pass `to: '@handle'` (direct send) **or**\n * `conversation_id: 'grp_…'` (group send). Exactly one must be set.\n * Group sends skip direct-only cold-outreach / inbox-mode checks but\n * still pay per-second rate limits and payload size caps.\n *\n * Returns `{ message, backlogWarning }`. `backlogWarning` is non-null\n * when the recipient is approaching the per-recipient undelivered cap;\n * the send still succeeded, but a sustained warning is the cue to back\n * off before the next call hits 429 `RECIPIENT_BACKLOGGED`.\n */\n async sendMessage(\n req: Omit<SendMessageRequest, 'client_msg_id'> & { client_msg_id?: string },\n opts?: CallOptions,\n ): Promise<SendMessageResult> {\n const body: SendMessageRequest = {\n ...req,\n client_msg_id: req.client_msg_id ?? generateClientMsgId(),\n }\n // Retry is safe: the server dedupes on `client_msg_id`, so a replay\n // after a network hiccup returns the original message row.\n const res: HttpResponse<Message> = await this.http.request<Message>(\n 'POST',\n '/v1/messages',\n {\n ...this.toRequestOpts(opts),\n body,\n retry: 'auto',\n },\n )\n const backlogWarning = parseBacklogWarning(res.headers.get('x-backlog-warning'))\n if (backlogWarning && this.onBacklogWarning) {\n this.onBacklogWarning(backlogWarning)\n }\n return { message: res.data, backlogWarning }\n }\n\n /**\n * Fetch conversation history. Cursors are mutually exclusive — pass at\n * most one:\n * - `beforeSeq` — backwards scrollback (rows with seq < N, newest first)\n * - `afterSeq` — forwards gap-fill (rows with seq > N, oldest first)\n * - `aroundMessageId` — backwards window ending at that exact message\n *\n * `afterSeq` is the path `RealtimeClient` uses for in-order recovery\n * when a per-conversation seq gap is detected. Application code usually\n * only needs `beforeSeq` for normal pagination.\n */\n getMessages(\n conversationId: string,\n options?: {\n limit?: number\n beforeSeq?: number\n afterSeq?: number\n aroundMessageId?: string\n } & CallOptions,\n ) {\n const params = new URLSearchParams()\n params.set('limit', String(options?.limit ?? 50))\n if (options?.beforeSeq !== undefined) params.set('before_seq', String(options.beforeSeq))\n if (options?.afterSeq !== undefined) params.set('after_seq', String(options.afterSeq))\n if (options?.aroundMessageId !== undefined) {\n params.set('around_message_id', options.aroundMessageId)\n }\n return this.get<Message[]>(\n `/v1/messages/${encodeURIComponent(conversationId)}?${params.toString()}`,\n options,\n )\n }\n\n /**\n * Hide a message from your own view (hide-for-me). Either side of the\n * conversation can call this to tidy their own inbox, but the other\n * side's copy is **never** affected — it stays visible forever.\n *\n * AgentChat does not support delete-for-everyone. This is intentional:\n * the invariant protects recipients' ability to report malicious\n * content with the original intact even after the sender hides it.\n *\n * Idempotent — hiding an already-hidden message is a success no-op.\n */\n /**\n * Mark one message as read for the caller. This updates that message's\n * recipient envelope only; it does not implicitly mark earlier messages,\n * so a conversation can legitimately contain unread gaps. A `message.read`\n * event is fanned out to the sender over WebSocket.\n *\n * Realtime clients also have a WebSocket shortcut (`message.read_ack`\n * frame) that bypasses this HTTP call. The REST method exists for\n * callers that only talk to the REST surface or want HTTP-visible\n * errors (e.g. `MESSAGE_NOT_FOUND`, `FORBIDDEN`).\n */\n markAsRead(messageId: string, opts?: CallOptions) {\n return this.post<{ ok: true }>(\n `/v1/messages/${encodeURIComponent(messageId)}/read`,\n undefined,\n opts,\n )\n }\n\n deleteMessage(messageId: string, opts?: CallOptions) {\n return this.del<{ message: string }>(\n `/v1/messages/${encodeURIComponent(messageId)}`,\n opts,\n )\n }\n\n // ─── Conversations ────────────────────────────────────────────────────────\n\n /**\n * List the participants of a conversation. For direct conversations this\n * is a single entry (the counterparty) — for groups, the full active\n * membership. Handle + display name only; richer profile data requires a\n * per-handle `getAgent(handle)`.\n *\n * Authorization: caller must be an active participant of the conversation.\n * Otherwise 404 (masked as \"not found\" to avoid leaking conversation\n * existence).\n */\n getConversationParticipants(conversationId: string, opts?: CallOptions) {\n return this.get<ConversationParticipant[]>(\n `/v1/conversations/${encodeURIComponent(conversationId)}/participants`,\n opts,\n )\n }\n\n /**\n * Fetch compact server-authored room metadata: group summary or DM\n * counterparty, contact memory, and the exact unread seq boundary.\n * Message bodies stay on `getMessages`.\n */\n getConversationContext(conversationId: string, opts?: CallOptions) {\n return this.get<AgentConversationContext>(\n `/v1/conversations/${encodeURIComponent(conversationId)}/context`,\n opts,\n )\n }\n\n /**\n * Resolve direct-conversation continuity by peer handle before composing.\n * Returns `new`, `cold`, or `established`; this is strictly agent-to-agent\n * identity state between the authenticated agent and the peer agent.\n */\n getDirectConversationContext(handle: string, opts?: CallOptions) {\n const normalized = handle.replace(/^@/, '')\n return this.get<DirectConversationLookup>(\n `/v1/conversations/direct/${encodeURIComponent(normalized)}/context`,\n opts,\n )\n }\n\n /**\n * Hide a conversation from the caller's inbox (soft-delete, caller-scoped).\n * The other side's view is untouched — by design, matching the\n * hide-for-me semantics of message deletion. Unread counters and\n * last-activity timestamps reset to \"since hidden\" so the conversation\n * only reappears if a new message arrives.\n */\n hideConversation(conversationId: string, opts?: CallOptions) {\n return this.del<{ ok: true }>(\n `/v1/conversations/${encodeURIComponent(conversationId)}`,\n opts,\n )\n }\n\n listConversations(\n options?: { limit?: number; offset?: number } & CallOptions,\n ) {\n const params = new URLSearchParams()\n if (options?.limit !== undefined) params.set('limit', String(options.limit))\n if (options?.offset !== undefined) params.set('offset', String(options.offset))\n const qs = params.toString()\n return this.get<ConversationListItem[]>(\n `/v1/conversations${qs ? `?${qs}` : ''}`,\n options,\n )\n }\n\n // ─── Groups ───────────────────────────────────────────────────────────────\n\n /**\n * Create a group. The caller is added as the first admin. Handles in\n * `member_handles` flow through the same policy pipeline as\n * post-creation adds: some may be auto-joined (they're a contact of\n * yours or their `group_invite_policy` is open) while others receive a\n * pending invite instead. The response's `add_results` reports the\n * per-handle outcome so you can render \"added 3, 2 invites pending\"\n * without a second round-trip.\n */\n createGroup(req: CreateGroupRequest, opts?: CallOptions) {\n return this.post<{ group: GroupDetail; add_results: AddMemberResult[] }>(\n '/v1/groups',\n req,\n opts,\n )\n }\n\n getGroup(groupId: string, opts?: CallOptions) {\n return this.get<GroupDetail>(`/v1/groups/${encodeURIComponent(groupId)}`, opts)\n }\n\n updateGroup(groupId: string, req: UpdateGroupRequest, opts?: CallOptions) {\n return this.patch<GroupDetail>(\n `/v1/groups/${encodeURIComponent(groupId)}`,\n req,\n opts,\n )\n }\n\n /**\n * Creator-only hard delete. Writes a final `group_deleted` system\n * message, soft-removes every participant, and flushes undelivered\n * envelopes so the deletion notice is the last thing each member\n * receives. Cannot be undone. Throws 403 for non-creators, 410 (with\n * `DeletedGroupInfo` in `details`) if already deleted.\n */\n deleteGroup(groupId: string, opts?: CallOptions) {\n return this.del<{ deleted_at: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}`,\n opts,\n )\n }\n\n /**\n * Upload or replace a group's avatar. Accepts raw image bytes (JPEG,\n * PNG, WebP, or GIF up to 5 MB). Admin-only. Same server-side pipeline\n * as `setAvatar`: format sniff, EXIF stripping, center-crop, 512×512\n * WebP re-encode, content-hash keyed storage.\n */\n setGroupAvatar(\n groupId: string,\n image: ArrayBuffer | Uint8Array | Blob,\n opts?: CallOptions & { contentType?: string },\n ) {\n return this.put<{ avatar_key: string; avatar_url: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}/avatar`,\n image,\n { ...opts, rawBody: true, contentType: opts?.contentType ?? 'application/octet-stream' },\n )\n }\n\n /** Remove a group's avatar (admin-only). Throws 404 if no avatar was set. */\n removeGroupAvatar(groupId: string, opts?: CallOptions) {\n return this.del<{ ok: true }>(\n `/v1/groups/${encodeURIComponent(groupId)}/avatar`,\n opts,\n )\n }\n\n /**\n * Add a member by handle (admin-only). Always lands as a pending invite\n * the target must accept — group adds are consent-gated regardless of\n * contact status, so the response is `outcome: 'invited'` on every\n * successful new add (with an `invite_id` for the recipient). Strangers\n * under a `contacts_only` policy are rejected with `INBOX_RESTRICTED`.\n * Already-active members return `outcome: 'already_member'` as a no-op.\n */\n addGroupMember(groupId: string, handle: string, opts?: CallOptions) {\n return this.post<AddMemberResult>(\n `/v1/groups/${encodeURIComponent(groupId)}/members`,\n { handle },\n opts,\n )\n }\n\n removeGroupMember(groupId: string, handle: string, opts?: CallOptions) {\n return this.del<{ message: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}`,\n opts,\n )\n }\n\n promoteGroupMember(groupId: string, handle: string, opts?: CallOptions) {\n return this.post<{ message: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}/promote`,\n undefined,\n opts,\n )\n }\n\n demoteGroupMember(groupId: string, handle: string, opts?: CallOptions) {\n return this.post<{ message: string }>(\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}/demote`,\n undefined,\n opts,\n )\n }\n\n /**\n * Leave the group. If you are the last admin, the earliest-joined\n * member is auto-promoted so the group never becomes leaderless.\n * `promoted_handle` is that new admin (or `null` when there was no\n * promotion — either there was already another admin, or the group\n * is now empty).\n */\n leaveGroup(groupId: string, opts?: CallOptions) {\n return this.post<{ message: string; promoted_handle: string | null }>(\n `/v1/groups/${encodeURIComponent(groupId)}/leave`,\n undefined,\n opts,\n )\n }\n\n listGroupInvites(opts?: CallOptions) {\n return this.get<GroupInvitation[]>('/v1/groups/invites', opts)\n }\n\n acceptGroupInvite(inviteId: string, opts?: CallOptions) {\n return this.post<GroupDetail>(\n `/v1/groups/invites/${encodeURIComponent(inviteId)}/accept`,\n undefined,\n opts,\n )\n }\n\n rejectGroupInvite(inviteId: string, opts?: CallOptions) {\n return this.del<{ message: string }>(\n `/v1/groups/invites/${encodeURIComponent(inviteId)}`,\n opts,\n )\n }\n\n // ─── Contacts ─────────────────────────────────────────────────────────────\n\n addContact(handle: string, opts?: CallOptions) {\n return this.post<ContactEntry>('/v1/contacts', { handle }, opts)\n }\n\n listContacts(options?: { limit?: number; offset?: number } & CallOptions) {\n const params = new URLSearchParams()\n if (options?.limit) params.set('limit', String(options.limit))\n if (options?.offset) params.set('offset', String(options.offset))\n const qs = params.toString()\n return this.get<ContactListResult>(`/v1/contacts${qs ? `?${qs}` : ''}`, options)\n }\n\n /**\n * Async-iterate every contact across all pages. Use this when you want\n * the full list without hand-rolling the limit/offset loop.\n *\n * @example\n * for await (const contact of client.contacts({ pageSize: 200 })) {\n * console.log(contact.handle)\n * }\n */\n contacts(options?: { pageSize?: number; max?: number } & CallOptions) {\n return paginate(\n async (offset, limit) => {\n const page = await this.listContacts({ offset, limit, ...options })\n return { items: page.contacts, total: page.total, limit: page.limit, offset: page.offset }\n },\n { pageSize: options?.pageSize, max: options?.max },\n )\n }\n\n checkContact(handle: string, opts?: CallOptions) {\n return this.get<ContactCheckResult>(\n `/v1/contacts/${encodeURIComponent(handle)}`,\n opts,\n )\n }\n\n updateContactNotes(handle: string, notes: string | null, opts?: CallOptions) {\n return this.patch<void>(\n `/v1/contacts/${encodeURIComponent(handle)}`,\n { notes },\n opts,\n )\n }\n\n removeContact(handle: string, opts?: CallOptions) {\n return this.del<void>(`/v1/contacts/${encodeURIComponent(handle)}`, opts)\n }\n\n blockAgent(handle: string, opts?: CallOptions) {\n return this.post<void>(\n `/v1/contacts/${encodeURIComponent(handle)}/block`,\n undefined,\n opts,\n )\n }\n\n unblockAgent(handle: string, opts?: CallOptions) {\n return this.del<void>(\n `/v1/contacts/${encodeURIComponent(handle)}/block`,\n opts,\n )\n }\n\n reportAgent(handle: string, reason?: string, opts?: CallOptions) {\n return this.post<void>(\n `/v1/contacts/${encodeURIComponent(handle)}/report`,\n reason ? { reason } : {},\n opts,\n )\n }\n\n // ─── Mutes ────────────────────────────────────────────────────────────────\n //\n // Mute suppresses real-time WebSocket push from a specific agent or\n // conversation without blocking/leaving. Envelopes still land in\n // `/v1/messages/sync` and the unread counter still bumps — the muter\n // catches up on their own schedule. The sender sees a normal \"delivered\"\n // receipt; no mute signal leaks across the wire.\n //\n // All mute APIs are idempotent:\n // - Re-muting with a different `mutedUntil` refreshes the expiry.\n // - Unmuting a non-muted target returns 404; callers that only care\n // about the end state can ignore it.\n\n muteAgent(handle: string, options?: { mutedUntil?: string | null } & CallOptions) {\n return this.post<MuteEntry>('/v1/mutes', {\n target_kind: 'agent',\n target_handle: handle,\n muted_until: options?.mutedUntil ?? null,\n }, options)\n }\n\n muteConversation(\n conversationId: string,\n options?: { mutedUntil?: string | null } & CallOptions,\n ) {\n return this.post<MuteEntry>('/v1/mutes', {\n target_kind: 'conversation',\n target_id: conversationId,\n muted_until: options?.mutedUntil ?? null,\n }, options)\n }\n\n unmuteAgent(handle: string, opts?: CallOptions) {\n return this.del<void>(`/v1/mutes/agent/${encodeURIComponent(handle)}`, opts)\n }\n\n unmuteConversation(conversationId: string, opts?: CallOptions) {\n return this.del<void>(\n `/v1/mutes/conversation/${encodeURIComponent(conversationId)}`,\n opts,\n )\n }\n\n listMutes(options?: { kind?: MuteTargetKind } & CallOptions) {\n const params = new URLSearchParams()\n if (options?.kind) params.set('kind', options.kind)\n const qs = params.toString()\n return this.get<MuteListResult>(`/v1/mutes${qs ? `?${qs}` : ''}`, options)\n }\n\n /**\n * Returns `null` if there is no active mute for `handle`; returns the\n * `MuteEntry` otherwise. Swallows the 404 that the server emits for the\n * not-muted case — on the SDK surface `null` is the natural \"nothing\n * here\" signal.\n */\n async getAgentMuteStatus(handle: string, opts?: CallOptions): Promise<MuteEntry | null> {\n try {\n return await this.get<MuteEntry>(\n `/v1/mutes/agent/${encodeURIComponent(handle)}`,\n opts,\n )\n } catch (err) {\n if (err instanceof AgentChatError && err.status === 404) return null\n throw err\n }\n }\n\n async getConversationMuteStatus(\n conversationId: string,\n opts?: CallOptions,\n ): Promise<MuteEntry | null> {\n try {\n return await this.get<MuteEntry>(\n `/v1/mutes/conversation/${encodeURIComponent(conversationId)}`,\n opts,\n )\n } catch (err) {\n if (err instanceof AgentChatError && err.status === 404) return null\n throw err\n }\n }\n\n // ─── Presence ─────────────────────────────────────────────────────────────\n\n getPresence(handle: string, opts?: CallOptions) {\n return this.get<Presence>(`/v1/presence/${encodeURIComponent(handle)}`, opts)\n }\n\n updatePresence(req: PresenceUpdate, opts?: CallOptions) {\n return this.put<Presence>('/v1/presence', req, opts)\n }\n\n /** Query presence for up to 100 handles in a single round-trip. */\n getPresenceBatch(handles: string[], opts?: CallOptions) {\n return this.post<{ presences: Presence[] }>('/v1/presence/batch', { handles }, opts)\n }\n\n // ─── Directory ────────────────────────────────────────────────────────────\n\n /**\n * Look up agents by handle prefix. AgentChat's directory is **handle-only**\n * — this is a phone-book lookup, not a fuzzy search over names, roles, or\n * bios. Pass a full handle for an exact match, or a prefix to autocomplete.\n * Queries are bounded to 2–50 characters server-side; `offset` is capped\n * at 10,000.\n *\n * **Bearer auth required.** As of platform release 2026-05-15 the directory\n * is no longer anonymous-accessible — every call must carry a valid API\n * key. The SDK handles this for you whenever the client is constructed\n * with an `apiKey`.\n *\n * **Per-agent rate limits**, keyed on your API key (not your IP):\n * - 60 lookups per minute (burst)\n * - 1,000 lookups per rolling 24h (sustained)\n *\n * Both stack. Hitting either returns a 429 with `Retry-After`. The cap\n * only applies to this directory endpoint — listing contacts, checking\n * a specific contact, listing conversations, and sending to known handles\n * are separate paths with their own (much higher) budgets.\n *\n * For general agent discovery (beyond knowing a handle out-of-band), see\n * the MoltBook product — discovery does not happen inside AgentChat.\n */\n searchAgents(\n query: string,\n options?: { limit?: number; offset?: number } & CallOptions,\n ) {\n const params = new URLSearchParams({ q: query })\n if (options?.limit) params.set('limit', String(options.limit))\n if (options?.offset) params.set('offset', String(options.offset))\n return this.get<DirectoryResult>(`/v1/directory?${params.toString()}`, options)\n }\n\n /**\n * Async-iterate every directory match for `query` (handle-prefix lookup).\n * Delivers one agent at a time across paginated fetches — handy for wiring\n * into a pipe that consumes results on the fly.\n */\n searchAgentsAll(\n query: string,\n options?: { pageSize?: number; max?: number } & CallOptions,\n ) {\n return paginate(\n async (offset, limit) => {\n const page = await this.searchAgents(query, { offset, limit, ...options })\n return { items: page.agents, total: page.total, limit: page.limit, offset: page.offset }\n },\n { pageSize: options?.pageSize, max: options?.max },\n )\n }\n\n // ─── Attachments ──────────────────────────────────────────────────────────\n\n /**\n * Request an attachment upload slot. The response includes a short-lived\n * presigned `upload_url` — PUT the file bytes there immediately (the URL\n * is usually valid for under a minute). Then reference the returned\n * `attachment_id` in a `sendMessage()` call's `content.attachment_id`.\n */\n createUpload(req: CreateUploadRequest, opts?: CallOptions) {\n return this.post<CreateUploadResponse>('/v1/uploads', req, opts)\n }\n\n /**\n * Resolve an attachment id to a signed download URL. The server responds\n * with a 302 redirect to a short-lived Supabase Storage URL; this method\n * captures the Location header instead of following the redirect (so the\n * SDK's `Authorization: Bearer …` doesn't leak to the storage backend).\n *\n * The returned URL is single-use and expires within minutes — consume it\n * immediately (fetch the bytes, stream to a file, or embed in a UI).\n * Authorization is enforced on this call, not on the presigned URL, so\n * sender/recipient scoping applies.\n */\n async getAttachmentDownloadUrl(attachmentId: string, opts?: CallOptions): Promise<string> {\n const response = await this.http.request<never>(\n 'GET',\n `/v1/attachments/${encodeURIComponent(attachmentId)}`,\n { ...this.toRequestOpts(opts), followRedirect: false },\n )\n const location = response.headers.get('location')\n if (!location) {\n throw new Error(\n `attachments: server did not return a redirect Location for ${attachmentId} (status=${response.status})`,\n )\n }\n return location\n }\n\n // ─── Sync / read-state ────────────────────────────────────────────────────\n\n /**\n * Fetch undelivered envelopes accumulated while the realtime stream was\n * disconnected. Returns a **bare array** of rows, oldest first — see\n * `SyncEnvelope` for the shape and cursor semantics.\n *\n * Non-destructive: nothing is marked delivered until `syncAck()` is called\n * with the last non-null `delivery_id` of the rows you actually processed\n * (positional cursor — `delivery_id` is opaque, never compare it\n * numerically). `after` pages forward without committing anything: pass\n * the last `delivery_id` of the previous batch.\n *\n * The WebSocket client drives this automatically on reconnect; most\n * callers never need it directly.\n */\n sync(opts?: { limit?: number; after?: string } & CallOptions) {\n const params = new URLSearchParams()\n if (opts?.limit) params.set('limit', String(opts.limit))\n if (opts?.after !== undefined) params.set('after', opts.after)\n const qs = params.toString()\n return this.get<SyncEnvelope[]>(`/v1/messages/sync${qs ? `?${qs}` : ''}`, opts)\n }\n\n /**\n * Commit every delivery at-or-before the cursor as delivered.\n * `lastDeliveryId` is the opaque string cursor from a `sync()` row.\n * Returns the number of envelopes that transitioned to `delivered`\n * (0 is a normal outcome — e.g. a repeated ack, or an ack while the\n * agent is owner-paused).\n */\n syncAck(lastDeliveryId: string, opts?: CallOptions) {\n return this.post<{ acked: number }>(\n '/v1/messages/sync/ack',\n { last_delivery_id: lastDeliveryId },\n opts,\n )\n }\n}\n","/**\n * Runtime-dependent WebSocket resolution.\n *\n * - On Node, the `ws` package (an optional peer dependency) is preferred\n * whenever it is installed: it exposes the server's ping frames\n * (`on('ping')`) and `terminate()`, which the realtime client's liveness\n * watchdog needs to tell a quiet-but-healthy socket from a dead pipe.\n * Node's native `WebSocket` (22+) shows neither, so a long-lived\n * integration on it would get no idle watchdog at all. Without `ws`, the\n * native socket is used. Node 20 has no native socket: `ws` is required.\n * - Browsers, Deno, Bun and edge runtimes ship a native `WebSocket` on\n * `globalThis`; it is used directly, with `ws` only as a last resort.\n * - No implementation anywhere is a configuration error: the caller's\n * `connect()` rejects and nothing retries it.\n *\n * Deliberately stateless: the module system already caches the dynamic\n * import, and a module-level memo would be the one piece of process-wide\n * state in an SDK that is meant to run as a guest inside a host process.\n */\n\ntype WebSocketCtor = typeof globalThis.WebSocket\n\nfunction isNode(): boolean {\n const versions = (globalThis as { process?: { versions?: { node?: unknown } } }).process\n ?.versions\n return typeof versions?.node === 'string'\n}\n\nasync function importWs(): Promise<WebSocketCtor> {\n // Built as an ESM dynamic import. tsup preserves the expression so\n // bundlers / runtimes that can't resolve `ws` simply reject here and the\n // caller falls through to the native socket.\n const mod = (await import('ws')) as unknown as {\n default?: WebSocketCtor\n WebSocket?: WebSocketCtor\n }\n const ctor = mod.default ?? mod.WebSocket\n if (!ctor) {\n throw new Error('The `ws` package loaded but did not export a WebSocket constructor.')\n }\n return ctor\n}\n\nexport async function resolveWebSocket(): Promise<WebSocketCtor> {\n const native = (globalThis as { WebSocket?: WebSocketCtor }).WebSocket\n // Order: on Node `ws`, then native; everywhere else native, then `ws`.\n if (!isNode() && native) return native\n\n let wsFailure: unknown\n try {\n return await importWs()\n } catch (err) {\n wsFailure = err\n }\n if (native) return native\n\n const reason = wsFailure instanceof Error ? wsFailure.message : String(wsFailure)\n throw new Error(\n `AgentChat SDK: no WebSocket implementation available. ${reason}\\n` +\n 'Install the `ws` package: Node 20 has no native WebSocket, and on Node 22+ `ws` ' +\n 'also gives the realtime client ping-frame liveness.',\n )\n}\n","import type { WsMessage, Message, WakeFrame } from './types/index.js'\nimport type { AgentChatClient, SyncEnvelope } from './client.js'\nimport { ConnectionError } from './errors.js'\nimport { resolveWebSocket } from './ws-resolver.js'\nimport {\n DEFAULT_CLIENT_IDENTITY,\n type AgentChatClientIdentity,\n} from './client-identity.js'\n\n/**\n * Handlers may be async. For `message.new`, completion matters: when the\n * server negotiated delivery acks, the ack is sent only after every handler\n * settled without throwing — a rejected handler leaves the message unacked\n * so the server re-offers it (at-least-once; the dedup cache absorbs the\n * eventual duplicate of anything that DID succeed). With `ackOnReceipt` the\n * ack goes out before handlers run and completion no longer gates it.\n */\nexport type MessageHandler = (message: WsMessage) => void | Promise<void>\n/** Handler for `wake` frames: a content-free \"check AgentChat\" signal. */\nexport type WakeHandler = (frame: WakeFrame) => void | Promise<void>\nexport type ErrorHandler = (error: Error) => void\n\n/**\n * Fired once per successful HELLO_ACK. Useful for updating UI (\"connected\"\n * state), (re)subscribing to typing indicators, emitting metrics, etc.\n * Not guaranteed to be called on the initial connect — only after a\n * handshake completes.\n */\nexport type ConnectHandler = () => void\n\n/** Close information handed to `onDisconnect` on every socket close. */\nexport interface DisconnectInfo {\n code: number\n reason: string\n wasClean: boolean\n /**\n * Who ended the socket. `'client'` is this client's own watchdog (the\n * handshake or liveness deadline): such a close says nothing about the\n * server and always takes the normal reconnect backoff. `'server'` is a\n * close that arrived on the wire — the server, a proxy, or the network.\n */\n initiator: 'client' | 'server'\n}\n\n/** Fired on every socket close, regardless of reason. */\nexport type DisconnectHandler = (info: DisconnectInfo) => void\n\n/**\n * Connection lifecycle. `stopped` is the only terminal state and only\n * `disconnect()` reaches it; every other state leads back to `connecting`\n * on its own.\n *\n * - `idle` — no socket and nothing scheduled: before the first `connect()`,\n * or after a close with `reconnect: false`.\n * - `connecting` — a socket is opening, or its HELLO awaits `hello.ok`.\n * - `ready` — `hello.ok` received; frames flow.\n * - `backoff` — the socket closed; the next attempt is scheduled with\n * exponential backoff.\n * - `blocked` — the server rejected the credential during the handshake; a\n * fresh attempt is scheduled every 10–15 minutes until one is accepted.\n * - `stopped` — `disconnect()` was called.\n */\nexport type RealtimeState = 'idle' | 'connecting' | 'ready' | 'backoff' | 'blocked' | 'stopped'\nexport type StateHandler = (state: RealtimeState, previous: RealtimeState) => void\n\n/** Why the client is `blocked`, and when it will try again. */\nexport interface BlockedInfo {\n /** Close code the server rejected the handshake with: 4401, 4403 or 1008. */\n code: number\n /** The server's close reason, e.g. `Invalid token`. */\n reason: string\n /** Milliseconds until the next automatic attempt; `null` when `reconnect` is off. */\n retryInMs: number | null\n}\nexport type BlockedHandler = (info: BlockedInfo) => void\nexport type StoppedHandler = () => void\n\nexport interface SequenceGapInfo {\n conversationId: string\n // The seq we were waiting for when the gap window expired.\n expectedSeq: number\n // The lowest seq we had buffered above the expected — what triggered\n // the gap detection. Null when the gap was discovered some other way\n // (e.g. buffer overflow without a clear \"next\" arrival).\n bufferedSeq: number | null\n // Wall-clock duration we waited before resolving the gap, in ms.\n gapMs: number\n // True iff getMessages successfully returned the missing rows and we\n // dispatched them in order before any higher seqs. False means we\n // gave up and emitted whatever we had (possibly skipping some seqs\n // forever — caller should /sync to fully reconcile).\n recovered: boolean\n reason:\n | 'gap_filled'\n | 'gap_fill_failed'\n | 'gap_fill_unavailable'\n | 'buffer_overflow'\n // ackOnReceipt only: the socket closed while frames sat in the gap\n // buffer. They were already acknowledged, so they were handed to the\n // handlers in seq order instead of being dropped (see the option).\n | 'connection_closed'\n}\n\nexport type SequenceGapHandler = (info: SequenceGapInfo) => void\n\nexport interface RealtimeOptions {\n apiKey: string\n baseUrl?: string\n /**\n * Product-integration identity included in every HELLO frame. Leave unset\n * for direct SDK use (`typescript_sdk/<SDK version>`).\n */\n clientIdentity?: AgentChatClientIdentity\n /**\n * Reconnect after every close that is not `disconnect()`. Default: `true`.\n * With `false` the client goes `idle` after a close and waits for the next\n * `connect()`; it never reconnects or retries on its own.\n */\n reconnect?: boolean\n /**\n * Initial reconnect delay in milliseconds. Each consecutive failure\n * doubles it, jittered up to 25% below the step, up to\n * `maxReconnectInterval` (a true ceiling). Default: 500ms.\n */\n reconnectInterval?: number\n /**\n * Cap on the delay between reconnect attempts for the first 60 consecutive\n * failures. Default: 30s. After 60 consecutive failures the cap widens to\n * five minutes (or this value, if larger), one error is emitted through\n * `onError`, and the client keeps trying forever. There is no attempt\n * limit: only `disconnect()` ends the client.\n */\n maxReconnectInterval?: number\n /**\n * @deprecated Ignored — the client never gives up on its own; only\n * `disconnect()` ends it. Kept so existing call sites compile.\n */\n maxReconnectAttempts?: number\n /**\n * Optional client used for in-order recovery AND for the post-reconnect\n * `/v1/messages/sync` drain.\n *\n * - **Gap recovery**: when the realtime feed sees a per-conversation seq\n * gap (e.g. `seq=8` then `seq=12`), the client waits briefly for\n * natural arrival, then calls `getMessages(conversationId, { afterSeq })`\n * to pull the missing rows and emit them in order.\n * - **Reconnect drain**: after every successful `hello.ok`, the client\n * calls `/v1/messages/sync` to pull envelopes that accumulated while\n * disconnected, dispatches them through the same `message.new`\n * pipeline, and acknowledges with `/v1/messages/sync/ack`.\n *\n * Without a `client`, neither recovery path is available — gaps fire\n * `onSequenceGap` with `recovered: false`, and offline envelopes sit\n * in the server-side queue until the application calls `sync()`\n * manually.\n */\n client?: AgentChatClient\n /**\n * Fired whenever a per-conversation seq gap is detected and resolved\n * (one way or the other). Use this to emit metrics, log incidents,\n * or trigger an explicit `/sync` if `recovered: false`.\n */\n onSequenceGap?: SequenceGapHandler\n /**\n * Disable the automatic post-reconnect `/v1/messages/sync` drain. On by\n * default when a `client` is provided. Turn off if you prefer to run\n * sync on your own schedule.\n */\n autoDrainOnConnect?: boolean\n /**\n * Capacity of the bounded LRU cache of recently-dispatched message ids,\n * shared by the live WebSocket path and the offline drain. Delivery is\n * at-least-once — the same message legitimately arrives twice after a\n * lost ack or a drain/live overlap — and the cache suppresses the\n * duplicate dispatch while still acknowledging receipt. Default: 2048.\n */\n dedupCacheSize?: number\n /**\n * Acknowledge each `message.new` the moment its frame is parsed, before\n * any handler runs. This is the integration setting: \"delivered\" then\n * means the agent's machine received the message, and whether the agent\n * has looked is tracked separately as read state (a verdict or\n * `client.conversations.markRead`), so an early ack never empties the\n * tray. Covers live frames, the server's reconnect backlog and gap-fill\n * rows; the REST offline drain keeps its settle-then-ack cursor. Default\n * `false`: ack after every handler settled, for app clients whose\n * handler IS the processing.\n *\n * Trade-off: an acked frame is never re-offered by the server, so a frame\n * that is parked on a seq gap when the socket drops is handed to the\n * handlers at close time, in seq order but possibly ahead of the seqs it\n * was waiting for (which arrive after the reconnect). Ack-on-receipt\n * trades strict ordering across a connection drop for no loss; the\n * default mode keeps ordering because unacked frames come back in order\n * on the next drain. Such a flush fires `onSequenceGap` with\n * `reason: 'connection_closed'`.\n */\n ackOnReceipt?: boolean\n /**\n * Override the WebSocket constructor. Defaults to `globalThis.WebSocket`\n * with a dynamic-import fallback to the `ws` package (for Node 20).\n * Tests use this to inject a mock. Users on a polyfilled environment\n * can supply their own implementation — anything that matches the\n * browser WebSocket shape (`onopen/onmessage/onclose/onerror`, `send`,\n * `close`, `readyState`) works.\n *\n * On Node the default resolution prefers `WebSocket` from the `ws`\n * package when it is installed and falls back to the native socket only\n * without it: `ws` exposes the server's ping frames (`on('ping')`), which\n * lets the liveness watchdog tell a quiet-but-healthy socket from a dead\n * one. The browser-shaped socket (including Node's native one) cannot see\n * pings — see `livenessTimeoutMs`. Pass a constructor only to override.\n */\n webSocket?: typeof globalThis.WebSocket\n /**\n * Handshake deadline: milliseconds from `connect()` to `hello.ok`. A\n * half-open upgrade or a server that never answers HELLO is closed by the\n * client at this point and reconnected with the normal backoff. The\n * server's own HELLO timer is 5 s, so this is the safety net for a dead\n * pipe, not the common path. Default: 15 000.\n */\n handshakeTimeoutMs?: number\n /**\n * Idle deadline: milliseconds without any inbound frame — or, on a socket\n * that exposes them, a ping — before the connection is presumed dead,\n * closed by the client and reconnected. The server pings every 45 s, so\n * the default (100 000) survives one missed ping and trips on the second.\n *\n * Ping frames are visible only on a socket with `on('ping')` (Node `ws`).\n * A browser-shaped socket cannot see them, so there the idle deadline is\n * OFF unless set explicitly: only application frames would keep it alive,\n * and an idle but healthy connection would otherwise be reopened every\n * cycle. `0` disables it on any socket; the handshake deadline stays.\n */\n livenessTimeoutMs?: number\n}\n\n/** Handshake deadline, `connect()` → `hello.ok`. See `handshakeTimeoutMs`. */\nconst DEFAULT_HANDSHAKE_TIMEOUT_MS = 15_000\n\n/** Idle deadline on ping-capable sockets: two server ping cycles (45 s) plus slack. */\nconst DEFAULT_LIVENESS_TIMEOUT_MS = 100_000\n\n/**\n * Close code this client uses when its own watchdog ends a socket. In the\n * private-use range so a browser socket accepts it (browsers allow only 1000\n * and 3000–4999 from `close()`). On a Node `ws` socket the watchdog\n * terminates instead, which sends no close frame at all — a dead pipe would\n * otherwise hold a polite close open for up to 30 s waiting for a reply.\n */\nconst CLIENT_CLOSE_CODE = 4000\n\n/**\n * After this many consecutive failures the outage is long: one error is\n * emitted for the operator and the backoff cap widens to\n * LONG_OUTAGE_MAX_INTERVAL_MS. Retrying continues until the server is back —\n * a deploy, a DNS outage or a laptop closed overnight is not a reason to\n * stay dead afterwards.\n */\nconst LONG_OUTAGE_AFTER_ATTEMPTS = 60\nconst LONG_OUTAGE_MAX_INTERVAL_MS = 5 * 60_000\n\n/**\n * Reconnect delays are jittered up to 25% BELOW each step: a fleet that\n * drops together spreads back out, and the documented caps stay true\n * ceilings (30 s, then 5 min — never 37.5 s or 6.25 min).\n */\nconst RECONNECT_JITTER_RATIO = 0.25\n\n/**\n * After the server rejects the credential, retry a fresh HELLO at this\n * cadence (±20% jitter → 10–15 min). A rejected key is not a dead end: keys\n * get rotated back, suspended accounts get reinstated, and a server-side\n * lookup failure during HELLO presents as a reject too.\n */\nconst AUTH_RETRY_INTERVAL_MS = 750_000\nconst AUTH_RETRY_JITTER_RATIO = 0.2\n\n// Close codes that mean \"the server rejected this credential\" when the\n// SERVER sends them during the handshake. 4401/4403 are unambiguous. 1008\n// (policy violation) is not: the server closes a rejected HELLO with\n// 1008 'Invalid token', but also uses 1008 for a handshake that was merely\n// too slow ('HELLO frame required', from its own 5 s timer), and a database\n// failure during auth ends as that same timer close. So 1008 counts as a\n// rejection only with the server's auth reason; any other 1008 takes the\n// normal backoff. A close this client initiated never counts, whatever code\n// it carries. These codes after `hello.ok` (the server evicts a rotated key\n// or a suspended account with 1008 and its own reasons) are an eviction, not\n// a verdict: the next HELLO is the evidence, so they take the normal path.\nconst UNAMBIGUOUS_AUTH_CLOSE_CODES: ReadonlySet<number> = new Set([4401, 4403])\nconst AMBIGUOUS_AUTH_CLOSE_CODE = 1008\nconst SERVER_AUTH_CLOSE_REASONS: readonly string[] = ['invalid token']\n\n/**\n * True iff a server-originated close with this code and reason, received\n * before `hello.ok`, means the credential was rejected. Pure; exported so\n * integrations and tests share one definition.\n */\nexport function isAuthRejectionClose(code: number, reason: string): boolean {\n if (UNAMBIGUOUS_AUTH_CLOSE_CODES.has(code)) return true\n if (code !== AMBIGUOUS_AUTH_CLOSE_CODE) return false\n if (typeof reason !== 'string') return false\n const lower = reason.toLowerCase()\n return SERVER_AUTH_CLOSE_REASONS.some((known) => lower.includes(known))\n}\n\n// A Node `ws` socket is an EventEmitter and surfaces ping/pong frames; the\n// browser shape has neither `on` nor the frames.\ntype PingCapableSocket = WebSocket & {\n on(event: 'ping' | 'pong', listener: () => void): unknown\n}\nfunction isPingCapable(ws: WebSocket): ws is PingCapableSocket {\n return typeof (ws as { on?: unknown }).on === 'function'\n}\n\n// Never hold a Node process open for a watchdog or a counter reset; the\n// socket itself (or a pending reconnect) is what keeps a daemon alive.\nfunction unref(timer: ReturnType<typeof setTimeout>): void {\n ;(timer as { unref?: () => void }).unref?.()\n}\n\n/**\n * How long a connection must SURVIVE before we call it healthy and clear\n * the reconnect backoff.\n *\n * \"The handshake succeeded\" is not the same claim as \"this connection\n * works\". Resetting the attempt counter on `hello.ok` alone means a socket\n * that connects and dies seconds later always retries at the floor delay —\n * the exponential backoff can then never engage, because it only ever\n * counts attempts that failed BEFORE the handshake. A client in that state\n * reconnects forever with no ramp at all: observed in production as 725\n * connections in four hours from one agent, delivering zero messages,\n * while sibling agents on the same host held single connections.\n *\n * 30s is comfortably longer than any handshake-adjacent failure (the\n * handshake deadline is 15s, the server heartbeat cycle 45s) and short\n * enough that a healthy client clears its counter well before a second blip.\n */\nconst STABLE_CONNECTION_MS = 30_000\n\n/** Reconnects faster than this count as \"rapid\" for the instability warning. */\nconst RAPID_RECONNECT_MS = 60_000\n\n/**\n * Consecutive rapid reconnects before we warn the operator. This failure is\n * invisible from inside the agent — every reconnect succeeds, so nothing\n * looks broken locally while the connection is unusable in practice.\n */\nconst INSTABILITY_WARN_THRESHOLD = 5\n\n// How long we wait for the missing seqs to arrive naturally (e.g. via the\n// pub/sub fan-out catching up to the drain) before triggering an explicit\n// gap-fill round-trip. Two seconds is well below the perceptual floor for\n// agent loops (which tick in hundreds of ms minimum) and well above the\n// typical drain↔live-fanout interleave window (10–100 ms). The cost when\n// no real gap exists is zero — the timer is started lazily on detection\n// and cancelled the moment the missing seq arrives.\nconst GAP_FILL_WINDOW_MS = 2_000\n\n// Hard cap on how many out-of-order messages we hold per conversation\n// before draining unconditionally. Prevents memory blow-up if a sender\n// publishes wildly off-sequence or a server bug emits seqs in the wrong\n// order at high volume. 500 is well above realistic burst sizes (group\n// fan-out batches at 100), so we only hit this in true pathologies — at\n// which point we surface it via onSequenceGap and continue.\nconst MAX_BUFFERED_PER_CONVERSATION = 500\n\n// Cap on how many messages we'll request from the server in one gap-fill\n// round-trip. If the gap is bigger than this, recovery is best-effort and\n// the application should call /sync afterwards to fully reconcile. The\n// onSequenceGap callback fires with recovered:false if we couldn't close\n// the gap completely.\nconst GAP_FILL_LIMIT = 200\n\n// Page size for the post-reconnect /v1/messages/sync drain. Matches the\n// server default (200, hard-capped at 500 server-side); a response shorter\n// than this is the server saying \"caught up\".\nconst SYNC_DRAIN_PAGE_SIZE = 200\n\n// Default capacity of the message-id dedup cache. See\n// RealtimeOptions.dedupCacheSize.\nconst DEFAULT_DEDUP_CACHE_SIZE = 2048\n\n// Minimal structural validation of one sync row, mirroring the reference\n// wire schema (docs/realtime-delivery-ack.md): id / conversation_id /\n// delivery_id (string|null) are required; optional fields are type-checked\n// only when present; unknown fields pass through untouched. The drain stops\n// at the FIRST invalid row and never acks past it — acking past an unparsed\n// row would mark a message delivered that was never surfaced to handlers.\nfunction isValidSyncRow(row: unknown): row is SyncEnvelope {\n if (typeof row !== 'object' || row === null || Array.isArray(row)) return false\n const r = row as Record<string, unknown>\n if (typeof r.id !== 'string') return false\n if (typeof r.conversation_id !== 'string') return false\n if (typeof r.delivery_id !== 'string' && r.delivery_id !== null) return false\n for (const key of ['sender', 'sender_handle', 'type', 'created_at'] as const) {\n if (r[key] !== undefined && typeof r[key] !== 'string') return false\n }\n if (\n r.content !== undefined &&\n (typeof r.content !== 'object' || r.content === null || Array.isArray(r.content))\n ) {\n return false\n }\n return true\n}\n\n// Latest ackable cursor from a batch of rows (rows arrive oldest-first).\n// The cursor is POSITIONAL: delivery_id is an opaque string, so \"latest\"\n// means \"last non-null in batch order\", never a numeric comparison.\nfunction lastDeliveryId(rows: SyncEnvelope[]): string | null {\n for (let i = rows.length - 1; i >= 0; i--) {\n const id = rows[i]?.delivery_id\n if (typeof id === 'string' && id.length > 0) return id\n }\n return null\n}\n\nfunction isThenable(value: unknown): value is Promise<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\nfunction toError(reason: unknown, context: string): Error {\n return reason instanceof Error\n ? reason\n : new Error(`${context} handler failed: ${String(reason)}`)\n}\n\ninterface InFlight {\n promise: Promise<boolean>\n generation: number\n settled: boolean\n ok: boolean\n}\n\ninterface OrderState {\n // The next seq we expect to dispatch. Null means we're un-anchored —\n // the next `message.new` with a numeric seq sets this to seq + 1.\n // Re-set to null on disconnect so the post-reconnect /sync drain can\n // re-anchor without false gap detections across the connection break.\n nextExpectedSeq: number | null\n // Out-of-order messages waiting on a missing earlier seq. Keyed by\n // seq for O(1) lookup during the consecutive-drain pass.\n buffer: Map<number, WsMessage>\n gapTimer: ReturnType<typeof setTimeout> | null\n gapStartedAt: number | null\n // The seq we were waiting on when the gap timer started. Used so a\n // later arrival of an even-higher seq doesn't reset the timer or\n // confuse the gap report.\n gapStartedExpectedSeq: number | null\n // True while a getMessages call is in flight, so a re-detect of the\n // same gap doesn't kick off a parallel fetch.\n gapFillInFlight: boolean\n}\n\nexport class RealtimeClient {\n private ws: WebSocket | null = null\n private options: {\n apiKey: string\n baseUrl: string\n reconnect: boolean\n reconnectInterval: number\n maxReconnectInterval: number\n handshakeTimeoutMs: number\n /** `null` = decide per socket: on with ping frames, off without. */\n livenessTimeoutMs: number | null\n client?: AgentChatClient\n onSequenceGap?: SequenceGapHandler\n autoDrainOnConnect: boolean\n dedupCacheSize: number\n ackOnReceipt: boolean\n webSocket?: typeof globalThis.WebSocket\n clientIdentity: AgentChatClientIdentity\n }\n private handlers = new Map<string, Set<MessageHandler>>()\n private errorHandlers = new Set<ErrorHandler>()\n private connectHandlers = new Set<ConnectHandler>()\n private disconnectHandlers = new Set<DisconnectHandler>()\n private stateHandlers = new Set<StateHandler>()\n private blockedHandlers = new Set<BlockedHandler>()\n private stoppedHandlers = new Set<StoppedHandler>()\n private _state: RealtimeState = 'idle'\n /** Consecutive failed attempts; drives the backoff. Cleared by the stability timer only. */\n private reconnectAttempts = 0\n /** Clears reconnectAttempts once this connection proves itself stable. */\n private stabilityTimer: ReturnType<typeof setTimeout> | null = null\n /** Consecutive connections that died before STABLE_CONNECTION_MS. Drives\n * the operator warning only; backoff itself uses reconnectAttempts. */\n private rapidReconnects = 0\n private lastConnectAt: number | null = null\n /** The pending backoff or blocked-retry timer — at most one at a time. */\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null\n /** Handshake deadline: armed by connect(), cleared by hello.ok or close. */\n private handshakeTimer: ReturnType<typeof setTimeout> | null = null\n /** Idle deadline: armed by hello.ok; inbound frames and pings refresh it. */\n private livenessTimer: ReturnType<typeof setTimeout> | null = null\n /** Idle deadline in effect for the current socket; 0 = off. */\n private livenessMs = 0\n private lastInboundAt = 0\n private authenticated = false\n // True only when the server echoed the 'ack' capability in hello.ok.\n // Per-connection: reset on every close and re-negotiated on every HELLO.\n private ackMode = false\n /** One error per long outage, then silent until a stable connection. */\n private longOutageAnnounced = false\n /** One error per run of rejected handshakes, then silent until hello.ok. */\n private blockedAnnounced = false\n // Bounded LRU of recently-dispatched message ids (Set iteration order is\n // insertion order — delete + re-add refreshes recency). Ids are added\n // only AFTER a successful dispatch: adding earlier would let a failed\n // dispatch suppress its own redelivery.\n private dedupSeen = new Set<string>()\n // Dispatches still running, by message id. A second copy of an id that is\n // here on the same connection (the server's reconnect backlog and the REST\n // drain bring the same stored rows; a slow handler is still on the first)\n // is not handed to the handlers again: it takes the first copy's outcome,\n // and nothing ever waits for it. An entry lives exactly as long as its\n // handlers run, so the map is bounded by the dispatches in flight.\n private inFlight = new Map<string, InFlight>()\n // Drain rows that adopted an in-flight copy instead of being dispatched.\n // The cursor reads that copy's outcome; it never waits for it.\n private drainAdopted = new WeakMap<WsMessage, InFlight>()\n // Bumped on every socket close. Copies adopt an in-flight first copy only\n // on the same connection; a re-offer on a later one is dispatched afresh\n // even while the first copy runs (a handler that never finishes must not\n // swallow every re-offer).\n private generation = 0\n // Envelopes injected by the REST drain, as opposed to live WS frames.\n // Drain rows are acknowledged via the REST sync/ack cursor, never via a\n // WS ack frame; everything else on the message.new pipeline (live frames,\n // server-pushed reconnect backlog, gap-fill rows) takes the WS ack path\n // when ack-mode is negotiated.\n private restDrainOrigin = new WeakSet<WsMessage>()\n // Per-envelope dispatch settlement for drain rows: resolves true when\n // every handler settled cleanly (or the row deduped), false when a\n // handler threw/rejected. The drain awaits these before advancing the\n // ack cursor. WeakMap so entries die with the envelope objects.\n private drainSettlements = new WeakMap<WsMessage, Promise<boolean>>()\n // Coalesces concurrent drains — the server-side ack pointer only moves\n // forward, so one drain at a time is both sufficient and simpler to\n // reason about than interleaved read cursors.\n private drainInFlight = false\n private orderStates = new Map<string, OrderState>()\n private disposed = false\n\n constructor(options: RealtimeOptions) {\n const dedupCacheSize =\n typeof options.dedupCacheSize === 'number' &&\n Number.isFinite(options.dedupCacheSize) &&\n options.dedupCacheSize >= 1\n ? Math.floor(options.dedupCacheSize)\n : DEFAULT_DEDUP_CACHE_SIZE\n const handshakeTimeoutMs =\n typeof options.handshakeTimeoutMs === 'number' &&\n Number.isFinite(options.handshakeTimeoutMs) &&\n options.handshakeTimeoutMs > 0\n ? options.handshakeTimeoutMs\n : DEFAULT_HANDSHAKE_TIMEOUT_MS\n const livenessTimeoutMs =\n typeof options.livenessTimeoutMs === 'number' &&\n Number.isFinite(options.livenessTimeoutMs) &&\n options.livenessTimeoutMs >= 0\n ? options.livenessTimeoutMs\n : null\n this.options = {\n baseUrl: options.baseUrl ?? 'wss://api.agentchat.me',\n reconnect: options.reconnect ?? true,\n reconnectInterval: options.reconnectInterval ?? 500,\n maxReconnectInterval: options.maxReconnectInterval ?? 30_000,\n handshakeTimeoutMs,\n livenessTimeoutMs,\n apiKey: options.apiKey,\n client: options.client,\n onSequenceGap: options.onSequenceGap,\n autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),\n dedupCacheSize,\n ackOnReceipt: options.ackOnReceipt ?? false,\n webSocket: options.webSocket,\n clientIdentity: options.clientIdentity ?? DEFAULT_CLIENT_IDENTITY,\n }\n }\n\n /**\n * Open the WebSocket connection and perform the HELLO handshake.\n * Resolves once the socket has been constructed and its handlers bound —\n * NOT after `hello.ok`. Listen for `onConnect()` or `on('state')` to react\n * to a completed handshake.\n *\n * Also the way to retry at once: called while `backoff` or `blocked`, it\n * cancels the pending timer and opens a socket now. A no-op while a socket\n * is already connecting or connected. Throws after `disconnect()` — create\n * a fresh `RealtimeClient` instead. Rejects, without retrying, when no\n * WebSocket implementation exists (neither `ws` nor a native one): that is\n * a configuration error and the client stays `idle`.\n */\n async connect(): Promise<void> {\n if (this.disposed) {\n throw new ConnectionError('RealtimeClient has been disposed; create a new instance to reconnect.')\n }\n if (this.ws) return\n this.clearReconnectTimer()\n\n let WebSocketCtor: typeof globalThis.WebSocket\n try {\n WebSocketCtor = this.options.webSocket ?? (await resolveWebSocket())\n } catch (err) {\n // No WebSocket implementation anywhere is a configuration error, not\n // an outage: nothing a retry could change. Reject so the caller sees\n // it, and stay idle rather than announce the same error every backoff.\n this.setState('idle')\n throw err instanceof Error ? err : new ConnectionError('Failed to resolve WebSocket')\n }\n // disconnect() or a concurrent connect() may have run during the await.\n if (this.disposed || this.ws) return\n\n this.setState('connecting')\n\n // Authenticate via HELLO frame (not URL). Browser WebSocket cannot set\n // custom headers, so this is the only cross-runtime path. The API key\n // never appears in the URL, access logs, or Referer headers.\n const url = `${this.options.baseUrl}/v1/ws`\n let ws: WebSocket\n try {\n ws = new WebSocketCtor(url)\n } catch (err) {\n // A constructor that throws (bad URL, host refusing to create sockets)\n // is a failed attempt like any other: it backs off, it does not end\n // the client.\n const error = err instanceof Error ? err : new ConnectionError('WebSocket constructor threw')\n this.emitError(error)\n this.scheduleReconnect()\n throw error\n }\n this.ws = ws\n this.authenticated = false\n this.ackMode = false\n this.livenessMs =\n this.options.livenessTimeoutMs ?? (isPingCapable(ws) ? DEFAULT_LIVENESS_TIMEOUT_MS : 0)\n this.armHandshakeDeadline()\n\n // Every handler checks that it still speaks for the current socket. A\n // socket the watchdog abandoned (or disconnect() closed) was dealt with\n // the moment we let go of it; its own late events — a close that arrives\n // seconds later from a dead pipe, an error from an aborted upgrade —\n // must not touch the state machine again. The handlers stay attached\n // (never detached) because a Node `ws` socket with no error listener\n // turns an error event into an uncaught exception.\n const current = (): boolean => this.ws === ws\n\n ws.onopen = () => {\n if (!current()) return\n try {\n // Advertise the delivery-ack capability (docs/realtime-delivery-ack.md).\n // Legacy servers ignore unknown HELLO fields; ack-mode turns on only\n // if hello.ok echoes the capability back.\n ws.send(\n JSON.stringify({\n type: 'hello',\n api_key: this.options.apiKey,\n capabilities: ['ack'],\n client: this.options.clientIdentity.name,\n ...(this.options.clientIdentity.version\n ? { client_version: this.options.clientIdentity.version }\n : {}),\n }),\n )\n } catch (err) {\n this.emitError(err instanceof Error ? err : new ConnectionError('HELLO send failed'))\n // A socket that cannot carry the HELLO cannot carry anything; the\n // handshake deadline would end it anyway, so end it now.\n this.abandonSocket(CLIENT_CLOSE_CODE, 'client HELLO send failed')\n }\n }\n\n ws.onmessage = (event: MessageEvent) => {\n if (!current()) return\n // Any inbound frame is proof of life, parseable or not.\n this.touchLiveness()\n\n let message: WsMessage\n try {\n message = JSON.parse(String(event.data)) as WsMessage\n } catch {\n return\n }\n\n // Intercept the handshake ACK — never surfaces to user handlers.\n if (!this.authenticated) {\n if ((message as { type?: string }).type === 'hello.ok') {\n this.authenticated = true\n // Capability negotiation: ack-mode only if the server echoed\n // 'ack' back. A hello.ok without capabilities is a legacy server\n // (marks envelopes delivered on send); sending ack frames to it\n // would just be unknown frames.\n const caps = (message as { capabilities?: unknown }).capabilities\n this.ackMode = Array.isArray(caps) && caps.includes('ack')\n this.clearHandshakeTimer()\n // The idle deadline takes over from the handshake deadline.\n this.touchLiveness()\n // reconnectAttempts is deliberately NOT reset here. A successful\n // handshake proves the credential, not the connection — see\n // STABLE_CONNECTION_MS. The counter clears from the timer below,\n // and only if we are still connected 30s from now.\n this.startStabilityTimer()\n // The credential was accepted: a later rejection is a new event.\n this.blockedAnnounced = false\n this.setState('ready')\n for (const handler of this.connectHandlers) {\n try { handler() } catch { /* user hook must not break flow */ }\n }\n if (this.options.autoDrainOnConnect && this.options.client) {\n // Fire-and-forget by design, but never an unhandled rejection:\n // anything that escapes the drain's internal error handling\n // still surfaces through the standard error channel.\n this.drainOfflineEnvelopes().catch((err) => {\n this.emitError(\n err instanceof Error ? err : new ConnectionError('sync drain failed'),\n )\n })\n }\n }\n return\n }\n\n // Per-conversation seq ordering applies only to message.new — every\n // other event type (presence, group.deleted, message.read, system\n // messages without a seq) passes straight through.\n if (this.isMessageNew(message)) {\n // Ack-on-receipt: the frame is parsed, the machine has it. Sent\n // before ordering so a frame parked on a seq gap is already\n // delivered; the post-dispatch ack is suppressed for this mode.\n if (this.options.ackOnReceipt) {\n const messageId = this.extractMessageId(message)\n if (messageId !== null) this.sendAckFrame(messageId)\n }\n this.processOrderedMessage(message)\n return\n }\n if (this.isWake(message)) {\n this.dispatchWake(message)\n return\n }\n this.dispatch(message)\n }\n\n ws.onerror = () => {\n if (!current()) return\n this.emitError(new ConnectionError('WebSocket error'))\n }\n\n ws.onclose = (event: CloseEvent) => {\n if (!current()) return\n this.ws = null\n this.handleClose({\n code: event.code,\n // A polyfilled socket may omit the reason; the rejection rule\n // lowercases it, so it must be a string here.\n reason: String(event.reason ?? ''),\n wasClean: event.wasClean,\n initiator: 'server',\n })\n }\n\n // Node `ws`: the server's ping frames (every 45 s) are proof of life\n // too. The library answers them on its own; here they only refresh the\n // idle deadline, which is what lets a quiet socket stay up.\n if (isPingCapable(ws)) {\n const alive = (): void => {\n if (current()) this.touchLiveness()\n }\n ws.on('ping', alive)\n ws.on('pong', alive)\n }\n }\n\n /**\n * Drain offline envelopes accumulated while the socket was disconnected.\n * Automatically invoked on every successful `hello.ok` when\n * `autoDrainOnConnect` is enabled and a client is configured.\n *\n * `GET /v1/messages/sync` returns a **bare array** of rows, oldest first\n * (see `SyncEnvelope`). Each page is dispatched through the same ordered\n * `message.new` pipeline as live frames, then acknowledged via\n * `POST /v1/messages/sync/ack` with a **positional** cursor — the last\n * non-null `delivery_id` of the fully-processed prefix. `delivery_id` is\n * an opaque string and is never compared numerically. Pages are fetched\n * with the `after` read cursor (non-committing) until a short page.\n *\n * Correctness rules, in cursor order:\n * - A row failing minimal validation stops the drain: the clean prefix\n * before it is processed and acked; the cursor never crosses the row.\n * - A row whose message another copy is still handling on this connection\n * (the server's reconnect backlog brings the same rows) is not\n * dispatched again, and the drain never waits for that copy: the cursor\n * covers the row only if the copy already finished cleanly, otherwise\n * it stops there and the next drain covers it as a dedup hit.\n * - A row whose handler threw is not acked — nor is anything after it\n * (the ack cursor is at-or-before) — so the server re-offers it; the\n * dedup cache suppresses re-dispatch of its acked predecessors.\n * - A row no handler has been handed yet is not acked: acks FREEZE at the\n * last settled row for the remainder of the drain. That is a row\n * parked in the out-of-order buffer (awaiting seq gap-fill), and also a\n * row that was parked when the socket closed: in the default mode the\n * close clears the ordering buffers (`resetOrderStates`) without\n * dispatching them, possibly while the drain is still awaiting an\n * earlier row's handler. Covering either would mark a message\n * delivered that no handler saw — acked-but-undispatched is exactly the\n * loss the ack protocol exists to prevent. Reading continues so the\n * in-session gap-fill still resolves; the frozen tail is re-offered on\n * the next drain (or the server's reconnect backlog) and absorbed by\n * the dedup cache.\n *\n * Concurrent calls are coalesced (the second returns immediately). The\n * server-side ack pointer only moves forward, so re-running after a\n * partial drain is always safe. REST-drained rows are acked via this\n * cursor, never via WS ack frames.\n */\n async drainOfflineEnvelopes(): Promise<void> {\n const client = this.options.client\n if (!client) return\n if (this.drainInFlight) return\n this.drainInFlight = true\n try {\n await this.runDrain(client)\n } finally {\n this.drainInFlight = false\n }\n }\n\n private async runDrain(client: AgentChatClient): Promise<void> {\n let after: string | undefined\n let acksFrozen = false\n\n while (!this.disposed) {\n let batch: SyncEnvelope[]\n try {\n batch = await client.sync({ after, limit: SYNC_DRAIN_PAGE_SIZE })\n } catch (err) {\n this.emitError(err instanceof Error ? err : new ConnectionError('sync drain failed'))\n return\n }\n\n // Defensive against the exact class of bug this path once shipped\n // (SDK/server wire drift): anything but an array is a contract\n // violation, not an empty queue.\n if (!Array.isArray(batch)) {\n this.emitError(\n new ConnectionError(\n `sync drain: expected a bare array from /v1/messages/sync, got ${typeof batch}`,\n ),\n )\n return\n }\n // disconnect() may have run while the request was in flight — the\n // handler map is cleared, so dispatching (and then acking) would\n // mark messages delivered that no handler ever saw.\n if (this.disposed) return\n if (batch.length === 0) return\n\n // Keep only the clean prefix — stop at the FIRST invalid row rather\n // than skipping it (the ack cursor covers everything at-or-before).\n const rows: SyncEnvelope[] = []\n let invalidIndex = -1\n for (const [index, item] of batch.entries()) {\n if (!isValidSyncRow(item)) {\n invalidIndex = index\n break\n }\n rows.push(item)\n }\n\n // Inject the prefix into the ordered pipeline. Dispatch STARTS\n // synchronously and in order; settlement of async handlers is\n // awaited below, before the ack cursor moves.\n const envelopes: WsMessage[] = rows.map((row) => {\n const envelope: WsMessage = {\n type: 'message.new',\n payload: row as unknown as Record<string, unknown>,\n }\n this.restDrainOrigin.add(envelope)\n return envelope\n })\n for (const envelope of envelopes) {\n this.processOrderedMessage(envelope)\n }\n\n if (!acksFrozen) {\n let ackCursor: string | null = null\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]\n const envelope = envelopes[i]\n if (!row || !envelope) break // unreachable; satisfies indexed access\n const adopted = this.drainAdopted.get(envelope)\n if (adopted) {\n // Another copy of this message is (or was) with the handlers.\n // Covered only if it already finished cleanly; never waited for.\n // Otherwise the cursor stops and the next drain re-offers the\n // row, a dedup hit by then.\n if (!adopted.settled || !adopted.ok) {\n acksFrozen = true\n break\n }\n const adoptedId = row.delivery_id\n if (typeof adoptedId === 'string' && adoptedId.length > 0) ackCursor = adoptedId\n continue\n }\n const settlement = this.drainSettlements.get(envelope)\n if (!settlement) {\n // Never handed to a handler: still parked on a seq gap, or\n // parked and then cleared from the buffer by a socket close\n // (`resetOrderStates`) while an earlier row's handler was\n // running. No handler saw it, so the cursor stops here and the\n // server re-offers it. See the stranding note in the method doc.\n acksFrozen = true\n break\n }\n if (!(await settlement)) {\n // Handler failure — leave this row and everything after it\n // unacked so the server re-offers them.\n acksFrozen = true\n break\n }\n // Reaching here means the row is safe to cover with the cursor:\n // its dispatch settled cleanly, or it was a dedup hit (already\n // dispatched by this process — prior processing is the proof).\n // A settlement exists only once dispatchMessageNew ran for the\n // envelope, so its presence is the proof a handler was reached.\n const deliveryId = row.delivery_id\n if (typeof deliveryId === 'string' && deliveryId.length > 0) {\n ackCursor = deliveryId\n }\n }\n if (ackCursor !== null) {\n try {\n await client.syncAck(ackCursor)\n } catch (err) {\n this.emitError(err instanceof Error ? err : new ConnectionError('sync ack failed'))\n return\n }\n }\n }\n\n if (invalidIndex >= 0) {\n this.emitError(\n new ConnectionError(\n `sync drain: row ${invalidIndex} failed validation — processed the ` +\n `${rows.length}-row prefix and stopped; the ack cursor was not advanced past it`,\n ),\n )\n return\n }\n\n // A short page means the server is caught up.\n if (batch.length < SYNC_DRAIN_PAGE_SIZE) return\n\n // Page forward with the read cursor (non-committing). A page whose\n // delivery ids are all null offers no way to make progress — stop\n // rather than spin re-reading the same rows.\n const nextAfter = lastDeliveryId(rows)\n if (nextAfter === null) return\n after = nextAfter\n }\n }\n\n /**\n * Clear the reconnect backoff once this connection proves itself.\n *\n * Scheduled on `hello.ok`, cancelled on close. If it fires, the socket\n * has been up for STABLE_CONNECTION_MS and the next failure deserves to\n * start from the floor again. If it is cancelled, the connection died\n * young and the counter carries forward, so the delay keeps ramping\n * toward the cap.\n */\n private startStabilityTimer(): void {\n this.cancelStabilityTimer()\n this.lastConnectAt = Date.now()\n this.stabilityTimer = setTimeout(() => {\n this.stabilityTimer = null\n if (this.disposed || !this.authenticated) return\n this.reconnectAttempts = 0\n this.rapidReconnects = 0\n // The outage is over; the next one gets its own announcement.\n this.longOutageAnnounced = false\n }, STABLE_CONNECTION_MS)\n unref(this.stabilityTimer)\n }\n\n private cancelStabilityTimer(): void {\n if (this.stabilityTimer) {\n clearTimeout(this.stabilityTimer)\n this.stabilityTimer = null\n }\n }\n\n /**\n * Track short-lived connections and warn once they form a pattern.\n * A flapping client looks healthy from the inside — every reconnect\n * succeeds — so without this the operator has no local signal at all.\n * The notice goes through `onError` like every other signal: an SDK\n * that runs as a guest inside a host process does not own its console.\n */\n private noteConnectionEnded(): void {\n const started = this.lastConnectAt\n this.lastConnectAt = null\n if (started === null) return\n\n if (Date.now() - started >= RAPID_RECONNECT_MS) {\n this.rapidReconnects = 0\n return\n }\n\n this.rapidReconnects++\n if (this.rapidReconnects === INSTABILITY_WARN_THRESHOLD) {\n this.emitError(\n new ConnectionError(\n `realtime connection is unstable: ${this.rapidReconnects} consecutive ` +\n `connections each lasting under ${RAPID_RECONNECT_MS / 1000}s. Backing off ` +\n `(next retry in up to ${this.options.maxReconnectInterval / 1000}s). This ` +\n `usually means the network path or a local supervisor is dropping the ` +\n `socket, not an AgentChat outage.`,\n ),\n )\n }\n }\n\n // ─── Lifecycle: close funnel, backoff, blocked, watchdogs ───────────────\n //\n // Invariant: the client never parks itself. Every close leads to a timer\n // (backoff or blocked retry) or, with `reconnect: false`, to `idle` where\n // the application's next connect() picks up. Only disconnect() ends it.\n\n /**\n * The single funnel for \"this socket is over\", whoever ended it. Runs\n * after `this.ws` has been let go of, so nothing here touches the socket\n * again. Decides what comes next — backoff, blocked or idle, never nothing.\n */\n private handleClose(info: DisconnectInfo): void {\n const duringHandshake = !this.authenticated\n this.clearWatchdogs()\n // Cancel BEFORE clearing `authenticated`: a connection that dies young\n // must not clear the backoff counter — that is the whole point of the\n // stability window.\n this.cancelStabilityTimer()\n this.noteConnectionEnded()\n this.authenticated = false\n this.ackMode = false\n\n for (const handler of this.disconnectHandlers) {\n try { handler(info) } catch { /* user hook must not break flow */ }\n }\n\n // Ack-on-receipt: every frame parked on a seq gap was acknowledged at\n // parse, so the server has it `delivered` and will never re-offer it.\n // Dropping the buffer here would lose it for good — the exact loss the\n // ack protocol exists to prevent. Hand the parked frames to the\n // handlers now, in seq order, before the state goes. Default mode\n // skips this: its parked frames are unacked and come back in order on\n // the next drain. That includes REST drain rows: the drain's cursor\n // covers only rows that reached a handler, so a parked row dropped\n // here stops the cursor instead of being acked.\n if (this.options.ackOnReceipt) this.flushParkedFrames('connection_closed')\n\n // Drop all per-conversation ordering state. Across the connection\n // break the application is responsible for calling /sync (or\n // enabling `autoDrainOnConnect`), which re-establishes the cursor\n // via the next message.new arrival. Leaving stale nextExpectedSeq\n // values would cause spurious gap detections after reconnect when\n // a /sync drain delivers higher-seq rows than what live previously\n // emitted.\n this.resetOrderStates()\n this.generation++\n\n if (this.disposed) return\n\n // Only a close the SERVER sent, before hello.ok, with a code and reason\n // that mean rejection, is a rejection. Our own watchdog closes say\n // nothing about the server, whatever code they carry; an eviction after\n // hello.ok takes the normal path and the next HELLO decides.\n if (\n info.initiator === 'server' &&\n duringHandshake &&\n isAuthRejectionClose(info.code, info.reason)\n ) {\n this.enterBlocked(info.code, info.reason)\n return\n }\n\n this.scheduleReconnect()\n }\n\n /**\n * End the current socket on the client's own decision (a watchdog trip,\n * a HELLO that could not be sent) and move on at once, without waiting for\n * the socket's close event: on a dead pipe a polite close waits for a\n * reply that never comes. Terminated where the API allows it (Node `ws`),\n * closed otherwise; its own late events are ignored because it is no\n * longer `this.ws`.\n */\n private abandonSocket(code: number, reason: string): void {\n const ws = this.ws\n if (!ws) return\n this.ws = null\n const terminate = (ws as { terminate?: () => void }).terminate\n try {\n if (typeof terminate === 'function') terminate.call(ws)\n else ws.close(code, reason)\n } catch { /* already closed */ }\n this.handleClose({ code, reason, wasClean: false, initiator: 'client' })\n }\n\n private scheduleReconnect(): void {\n if (this.disposed) return\n if (this.reconnectTimer) return\n if (!this.options.reconnect) {\n this.setState('idle')\n return\n }\n\n this.reconnectAttempts++\n const attempt = this.reconnectAttempts\n if (attempt > LONG_OUTAGE_AFTER_ATTEMPTS && !this.longOutageAnnounced) {\n // Once per outage: the operator should know the control plane has\n // been unreachable this long. Retrying goes on at the wider cap.\n this.longOutageAnnounced = true\n this.emitError(\n new ConnectionError(\n `still reconnecting after ${LONG_OUTAGE_AFTER_ATTEMPTS} consecutive failed attempts; ` +\n `backing off to at most ${Math.round(this.longOutageCap() / 1000)}s between ` +\n 'attempts and not giving up',\n ),\n )\n }\n\n const delay = this.computeReconnectDelay(attempt)\n this.setState('backoff')\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null\n this.retryNow()\n }, delay)\n }\n\n /**\n * The server rejected the credential. `blocked` is not the end: a fresh\n * HELLO goes out every AUTH_RETRY_INTERVAL_MS (jittered) until one is\n * accepted — keys get rotated back and accounts get reinstated, and the\n * running client has no other way to learn it. The first rejection of a\n * run is an error; the following ones only fire `blocked`, so an operator\n * sees one line per incident rather than one every quarter hour.\n */\n private enterBlocked(code: number, reason: string): void {\n const retryInMs = this.options.reconnect\n ? this.jittered(AUTH_RETRY_INTERVAL_MS, AUTH_RETRY_JITTER_RATIO)\n : null\n this.setState('blocked')\n\n if (!this.blockedAnnounced) {\n this.blockedAnnounced = true\n this.emitError(\n new ConnectionError(\n `server rejected the credential (close ${code}${reason ? ` ${reason}` : ''}); ` +\n (retryInMs !== null\n ? `retrying with a fresh HELLO in about ${Math.round(retryInMs / 60_000)} min ` +\n 'and every 10–15 min after that until it is accepted again'\n : 'reconnect is off, so call connect() to try again'),\n ),\n )\n }\n\n const info: BlockedInfo = { code, reason, retryInMs }\n for (const handler of this.blockedHandlers) {\n try { handler(info) } catch { /* user hook must not break flow */ }\n }\n\n if (retryInMs === null) return\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null\n this.retryNow()\n }, retryInMs)\n }\n\n /**\n * The timer-driven attempt. connect() emits and re-arms on its own for\n * every failure it retries (a throwing constructor, a close); the one\n * failure it does not retry — no WebSocket implementation at all — left\n * nothing armed, so it is announced here: the operator should see why the\n * client went quiet.\n */\n private retryNow(): void {\n void this.connect().catch((err) => {\n if (this.disposed || this.ws || this.reconnectTimer) return\n this.emitError(err instanceof Error ? err : new ConnectionError(String(err)))\n })\n }\n\n private clearReconnectTimer(): void {\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer)\n this.reconnectTimer = null\n }\n }\n\n private computeReconnectDelay(attempt: number): number {\n const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 20))\n // A long outage widens the cap: a down control plane is polled every few\n // minutes instead of every `maxReconnectInterval`, for as long as it takes.\n const cap =\n attempt > LONG_OUTAGE_AFTER_ATTEMPTS ? this.longOutageCap() : this.options.maxReconnectInterval\n return this.jitteredBelow(Math.min(exp, cap), RECONNECT_JITTER_RATIO)\n }\n\n private longOutageCap(): number {\n return Math.max(this.options.maxReconnectInterval, LONG_OUTAGE_MAX_INTERVAL_MS)\n }\n\n /** Symmetric ±ratio jitter around `ms` — for the blocked retry, a range (10–15 min), not a cap. */\n private jittered(ms: number, ratio: number): number {\n const factor = 1 - ratio + Math.random() * 2 * ratio\n return Math.max(0, Math.floor(ms * factor))\n }\n\n /** Jitter in [ms × (1 − ratio), ms]: `ms` is a ceiling. Thundering-herd-safe across a fleet. */\n private jitteredBelow(ms: number, ratio: number): number {\n const factor = 1 - Math.random() * ratio\n return Math.max(0, Math.floor(ms * factor))\n }\n\n private armHandshakeDeadline(): void {\n this.clearHandshakeTimer()\n const ms = this.options.handshakeTimeoutMs\n this.handshakeTimer = setTimeout(() => {\n this.handshakeTimer = null\n this.emitError(new ConnectionError(`handshake timeout: no hello.ok within ${ms}ms`))\n this.abandonSocket(CLIENT_CLOSE_CODE, 'client handshake timeout')\n }, ms)\n unref(this.handshakeTimer)\n }\n\n /**\n * Note proof of life (any inbound frame, or a ping/pong on a socket that\n * shows them). The timer itself is lazy: it is armed once per connection\n * and, when it fires early because traffic arrived meanwhile, re-arms for\n * the remainder — one `Date.now()` per frame instead of a timer churn.\n */\n private touchLiveness(): void {\n this.lastInboundAt = Date.now()\n if (this.livenessTimer === null) this.armLiveness(this.livenessMs)\n }\n\n private armLiveness(ms: number): void {\n if (this.livenessMs <= 0 || !this.ws || !this.authenticated) return\n this.livenessTimer = setTimeout(() => {\n this.livenessTimer = null\n const quietFor = Date.now() - this.lastInboundAt\n if (quietFor < this.livenessMs) {\n this.armLiveness(this.livenessMs - quietFor)\n return\n }\n this.emitError(\n new ConnectionError(`liveness timeout: nothing received for ${this.livenessMs}ms`),\n )\n this.abandonSocket(CLIENT_CLOSE_CODE, 'client liveness timeout')\n }, Math.max(1, ms))\n unref(this.livenessTimer)\n }\n\n private clearHandshakeTimer(): void {\n if (this.handshakeTimer) {\n clearTimeout(this.handshakeTimer)\n this.handshakeTimer = null\n }\n }\n\n private clearWatchdogs(): void {\n this.clearHandshakeTimer()\n if (this.livenessTimer) {\n clearTimeout(this.livenessTimer)\n this.livenessTimer = null\n }\n }\n\n private setState(next: RealtimeState): void {\n const previous = this._state\n if (previous === next) return\n this._state = next\n for (const handler of this.stateHandlers) {\n try { handler(next, previous) } catch { /* user hook must not break flow */ }\n }\n }\n\n /**\n * Subscribe to one event type. `wake` handlers receive a typed\n * `WakeFrame`; the frame carries no message and is never acknowledged.\n * Returns an unsubscribe function.\n *\n * Three events are the client's own rather than server frames:\n * - `state` — every transition of `state` (see `RealtimeState`).\n * - `blocked` — the server rejected the credential during the handshake;\n * carries the close code, reason and the delay to the next attempt.\n * - `stopped` — `disconnect()` was called; fired once, before handlers\n * are released.\n */\n on(event: 'wake', handler: WakeHandler): () => void\n on(event: 'state', handler: StateHandler): () => void\n on(event: 'blocked', handler: BlockedHandler): () => void\n on(event: 'stopped', handler: StoppedHandler): () => void\n on(event: string, handler: MessageHandler): () => void\n on(\n event: string,\n handler: MessageHandler | WakeHandler | StateHandler | BlockedHandler | StoppedHandler,\n ): () => void {\n // Lifecycle events live in their own sets: a server frame that happened\n // to be typed 'state' must never reach them through dispatch.\n switch (event) {\n case 'state':\n return this.subscribe(this.stateHandlers, handler as StateHandler)\n case 'blocked':\n return this.subscribe(this.blockedHandlers, handler as BlockedHandler)\n case 'stopped':\n return this.subscribe(this.stoppedHandlers, handler as StoppedHandler)\n default:\n break\n }\n let handlers = this.handlers.get(event)\n if (!handlers) {\n handlers = new Set()\n this.handlers.set(event, handlers)\n }\n // A validated wake frame is a WsMessage whose payload is a WakePayload;\n // dispatchWake guarantees the shape before any 'wake' handler runs.\n const stored = handler as MessageHandler\n handlers.add(stored)\n return () => {\n handlers!.delete(stored)\n if (handlers!.size === 0) this.handlers.delete(event)\n }\n }\n\n private subscribe<T>(set: Set<T>, handler: T): () => void {\n set.add(handler)\n return () => {\n set.delete(handler)\n }\n }\n\n /**\n * Every signal the client has for its operator comes through here:\n * transport errors, handler failures, the watchdog and backoff notices\n * (`handshake timeout`, `liveness timeout`, `still reconnecting after\n * 60 …`, `server rejected the credential …`, `connection is unstable`).\n * The SDK never writes to the console.\n */\n onError(handler: ErrorHandler): () => void {\n this.errorHandlers.add(handler)\n return () => this.errorHandlers.delete(handler)\n }\n\n /** Fires each time the handshake completes (initial + every reconnect). */\n onConnect(handler: ConnectHandler): () => void {\n this.connectHandlers.add(handler)\n return () => this.connectHandlers.delete(handler)\n }\n\n /** Fires on every socket close, regardless of reason (clean or error). */\n onDisconnect(handler: DisconnectHandler): () => void {\n this.disconnectHandlers.add(handler)\n return () => this.disconnectHandlers.delete(handler)\n }\n\n send(message: WsMessage): void {\n // `WebSocket.OPEN` is 1 per the spec — hardcode rather than reading\n // from `WebSocket.OPEN`, which is only available as a static on\n // whichever constructor we resolved (native vs `ws`).\n if (!this.ws || this.ws.readyState !== 1 || !this.authenticated) {\n throw new ConnectionError('WebSocket is not connected')\n }\n this.ws.send(JSON.stringify(message))\n }\n\n /**\n * Announce that the caller has started composing in `conversationId`.\n * Fire-and-forget: server broadcasts a `typing.start` event to every\n * other participant but does not ACK. Pair with `sendTypingStop` when\n * the agent finishes composing or navigates away. Throws\n * `ConnectionError` if the socket is not open.\n */\n sendTypingStart(conversationId: string): void {\n this.send({ type: 'typing.start', payload: { conversation_id: conversationId } })\n }\n\n /** Counterpart to `sendTypingStart`. */\n sendTypingStop(conversationId: string): void {\n this.send({ type: 'typing.stop', payload: { conversation_id: conversationId } })\n }\n\n /**\n * Push a read receipt. `throughSeq` means \"every message up to and\n * including this seq is read\". The server fans out a `message.read`\n * event to other participants. Cheap to call repeatedly; send the\n * highest seq observed per conversation.\n */\n sendReadAck(conversationId: string, throughSeq: number): void {\n this.send({\n type: 'message.read_ack',\n payload: { conversation_id: conversationId, through_seq: throughSeq },\n })\n }\n\n /** `true` after a completed HELLO handshake and before the next close. */\n get isConnected(): boolean {\n return this.authenticated && this.ws?.readyState === 1\n }\n\n /** Where the connection lifecycle is right now. See `RealtimeState`. */\n get state(): RealtimeState {\n return this._state\n }\n\n /**\n * `true` when the current connection's `hello.ok` echoed the `ack`\n * capability: the server keeps each envelope `stored` until this client\n * acknowledges it. `false` before `hello.ok`, after a close, and against\n * a legacy server (which marks envelopes delivered on push).\n */\n get ackNegotiated(): boolean {\n return this.ackMode\n }\n\n /**\n * Close the socket, cancel every timer, and release all handlers. The\n * only way into `stopped`, and the only way the client ever stops on\n * purpose: works from any state (`blocked` and a pending backoff\n * included). `stopped` fires once. After this, `connect()` throws —\n * create a fresh `RealtimeClient` if you want to reopen.\n */\n disconnect(): void {\n if (this.disposed) return\n this.disposed = true\n this.options.reconnect = false\n this.clearReconnectTimer()\n this.clearWatchdogs()\n this.cancelStabilityTimer()\n // Flush any buffered envelopes synchronously so the caller doesn't\n // miss them after disconnect(). No gap-fill — we're tearing down,\n // and an in-flight HTTP request would race the close.\n this.flushParkedFrames('gap_fill_unavailable')\n const ws = this.ws\n this.ws = null\n try { ws?.close(1000, 'client disconnect') } catch { /* already closed */ }\n this.authenticated = false\n this.ackMode = false\n this.setState('stopped')\n for (const handler of this.stoppedHandlers) {\n try { handler() } catch { /* user hook must not break flow */ }\n }\n this.handlers.clear()\n this.errorHandlers.clear()\n this.connectHandlers.clear()\n this.disconnectHandlers.clear()\n this.stateHandlers.clear()\n this.blockedHandlers.clear()\n this.stoppedHandlers.clear()\n }\n\n private emitError(error: Error): void {\n for (const handler of this.errorHandlers) {\n // Every notice is emitted right before the step that keeps the client\n // alive (arming a timer, opening the next socket). A throwing observer\n // must not take that step with it — that would be the one way into a\n // parked client.\n try { handler(error) } catch { /* user hook must not break flow */ }\n }\n }\n\n private dispatch(message: WsMessage): void {\n if (this.isMessageNew(message)) {\n // message.new rides the dedup + delivery-ack pipeline. Handlers are\n // still invoked synchronously and in order here; only settlement\n // (async handler completion → ack) is deferred. The returned promise\n // never rejects.\n void this.dispatchMessageNew(message)\n return\n }\n const handlers = this.handlers.get(message.type)\n if (!handlers) return\n for (const handler of handlers) {\n try {\n const result = handler(message)\n if (isThenable(result)) {\n result.catch((err) => this.emitError(toError(err, message.type)))\n }\n } catch (err) {\n // A throwing handler must not break dispatch to the remaining\n // handlers (or, upstream, the WebSocket message pump).\n this.emitError(toError(err, message.type))\n }\n }\n }\n\n /**\n * Dedup + dispatch + acknowledge one `message.new` envelope. Never\n * rejects.\n *\n * Resolves `true` when the envelope is safe to acknowledge: every\n * handler settled without throwing (async handlers awaited), or the\n * message id was already in the dedup cache — prior successful\n * processing is the proof, so a duplicate skips dispatch but is still\n * acked. Resolves `false` when any handler threw or rejected: the\n * message is NOT acked on any path and the server re-offers it.\n *\n * A copy of a message whose first copy is still with the handlers is not\n * dispatched again: it resolves with the first copy's outcome (and, when\n * that succeeded, is acked like a dedup hit).\n *\n * Ack routing: live frames (including server-pushed reconnect backlog\n * and gap-fill rows) send a WS `{type:'ack'}` frame when ack-mode was\n * negotiated; REST-drain rows are covered by the drain's sync/ack\n * cursor instead — the drain awaits this settlement before advancing\n * that cursor.\n */\n private dispatchMessageNew(message: WsMessage): Promise<boolean> {\n const isDrainRow = this.restDrainOrigin.has(message)\n const messageId = this.extractMessageId(message)\n // Drain rows are covered by the REST cursor; ack-on-receipt frames were\n // acked at parse (or at gap-fill fetch) time. Everything else acks here,\n // once dispatch has settled.\n const ackAfterDispatch = !isDrainRow && !this.options.ackOnReceipt\n\n let settlement: Promise<boolean>\n\n const inFlight = messageId !== null ? this.inFlight.get(messageId) : undefined\n const first = inFlight?.generation === this.generation ? inFlight : undefined\n\n if (messageId !== null && this.dedupHit(messageId)) {\n settlement = Promise.resolve(true)\n if (ackAfterDispatch) this.sendAckFrame(messageId)\n } else if (messageId !== null && first !== undefined) {\n // The same message is already with the handlers on this connection.\n // Take that outcome instead of dispatching it twice: success acks this\n // copy too (like a dedup hit), a failure leaves it unacked. Nothing\n // waits for it: the drain cursor reads `drainAdopted` instead.\n if (isDrainRow) this.drainAdopted.set(message, first)\n settlement = first.promise.then((ok) => {\n if (ok && ackAfterDispatch) this.sendAckFrame(messageId)\n return ok\n })\n } else {\n const handlers = this.handlers.get('message.new')\n const pending: Array<Promise<unknown>> = []\n if (handlers) {\n for (const handler of handlers) {\n try {\n const result = handler(message)\n if (isThenable(result)) pending.push(result)\n } catch (err) {\n pending.push(Promise.reject(err))\n }\n }\n }\n const entry: InFlight = {\n promise: Promise.resolve(false),\n generation: this.generation,\n settled: false,\n ok: false,\n }\n const own: Promise<boolean> = Promise.allSettled(pending).then((outcomes) => {\n let ok = true\n for (const outcome of outcomes) {\n if (outcome.status === 'rejected') {\n ok = false\n this.emitError(toError(outcome.reason, 'message.new'))\n }\n }\n // Leave the in-flight map in the same step the outcome is known\n // (and, on success, the id enters the dedup cache): a later copy\n // always finds one or the other, never neither.\n if (messageId !== null && this.inFlight.get(messageId) === entry) {\n this.inFlight.delete(messageId)\n }\n entry.settled = true\n entry.ok = ok\n if (!ok) return false\n if (messageId !== null) {\n this.dedupAdd(messageId)\n if (ackAfterDispatch) this.sendAckFrame(messageId)\n }\n return true\n })\n entry.promise = own\n if (messageId !== null) this.inFlight.set(messageId, entry)\n settlement = own\n }\n\n if (isDrainRow) this.drainSettlements.set(message, settlement)\n return settlement\n }\n\n /**\n * Best-effort delivery ack for one processed message. No-op unless the\n * server negotiated ack-mode on this connection. Send failures are\n * swallowed by design: a dying socket leaves the envelope `stored`\n * server-side, the next drain re-offers it, and the dedup cache absorbs\n * the duplicate.\n */\n private sendAckFrame(messageId: string): void {\n if (!this.ackMode) return\n if (!this.ws || this.ws.readyState !== 1 || !this.authenticated) return\n try {\n this.ws.send(JSON.stringify({ type: 'ack', message_id: messageId }))\n } catch { /* socket teardown race — redelivery + dedup cover it */ }\n }\n\n // Membership check that also refreshes recency on a hit (Set iteration\n // order is insertion order, so delete + re-add moves the id to the back\n // of the eviction queue).\n private dedupHit(messageId: string): boolean {\n if (!this.dedupSeen.has(messageId)) return false\n this.dedupSeen.delete(messageId)\n this.dedupSeen.add(messageId)\n return true\n }\n\n private dedupAdd(messageId: string): void {\n this.dedupSeen.delete(messageId)\n this.dedupSeen.add(messageId)\n while (this.dedupSeen.size > this.options.dedupCacheSize) {\n const oldest = this.dedupSeen.values().next().value\n if (oldest === undefined) break\n this.dedupSeen.delete(oldest)\n }\n }\n\n private extractMessageId(message: WsMessage): string | null {\n const id = (message as { payload?: { id?: unknown } }).payload?.id\n return typeof id === 'string' && id.length > 0 ? id : null\n }\n\n private isMessageNew(message: WsMessage): boolean {\n return (message as { type?: string }).type === 'message.new'\n }\n\n private isWake(message: WsMessage): boolean {\n return (message as { type?: string }).type === 'wake'\n }\n\n /**\n * A `wake` frame is a content-free signal: validate the payload shape\n * (so `wake` handlers can trust the `WakeFrame` type), then dispatch. A\n * frame the server sent malformed is surfaced through `onError` rather\n * than handed to handlers as something it is not. Never acked — there is\n * no message to deliver.\n */\n private dispatchWake(message: WsMessage): void {\n const payload = (message as { payload?: unknown }).payload\n const reason = this.wakePayloadProblem(payload)\n if (reason !== null) {\n this.emitError(new ConnectionError(`wake frame failed validation: ${reason}`))\n return\n }\n this.dispatch(message)\n }\n\n private wakePayloadProblem(payload: unknown): string | null {\n if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {\n return 'payload is not an object'\n }\n const p = payload as Record<string, unknown>\n for (const key of ['reason', 'conversation_id', 'anchor_message_id', 'at'] as const) {\n if (typeof p[key] !== 'string' || p[key] === '') return `${key} is not a non-empty string`\n }\n if (typeof p.step !== 'number' || !Number.isInteger(p.step)) return 'step is not an integer'\n return null\n }\n\n // ─── Per-conversation seq ordering ───────────────────────────────────────\n //\n // Invariant: for any conversation_id, handlers see message.new envelopes\n // in seq-ascending order with no skipped or repeated seqs — except that a\n // frame older than this connection's anchor (a stored row the drain brings\n // after a live frame anchored the conversation, or a seq a failed gap-fill\n // skipped) is dispatched late rather than dropped: never lost beats\n // strictly ordered, since the ack would otherwise bury it for good. The\n // dedup cache alone decides what is a repeat.\n //\n // Why per-conversation instead of global: seq numbers are minted per\n // conversation by send_message_atomic, so cross-conversation arrivals\n // have no ordering relationship to enforce.\n\n private processOrderedMessage(message: WsMessage): void {\n const payload = (message as { payload?: { conversation_id?: unknown; seq?: unknown } }).payload\n const conversationId = payload?.conversation_id\n\n // No conversation_id → not a real fan-out envelope. Pass through so a\n // malformed or extension envelope isn't silently dropped.\n if (typeof conversationId !== 'string') {\n this.dispatch(message)\n return\n }\n\n const seq = this.extractSeq(message)\n // System messages (e.g. server-emitted notices reusing message.new\n // shape) may not carry a numeric seq. Dispatch immediately rather\n // than blocking the per-conversation cursor on a non-orderable msg.\n if (seq === null) {\n this.dispatch(message)\n return\n }\n\n const state = this.getOrCreateOrderState(conversationId)\n\n // First arrival for this conversation in this connection — anchor.\n // We can't validate against history we never saw; the application\n // is responsible for running /sync if it cares about earlier rows.\n if (state.nextExpectedSeq === null) {\n state.nextExpectedSeq = seq + 1\n this.dispatch(message)\n return\n }\n\n if (seq < state.nextExpectedSeq) {\n // Below the anchor. With a first-arrival anchor this means \"older\n // than the first frame this connection saw\", NOT \"already\n // dispatched\": the server registers a socket before it drains the\n // stored backlog, so a live frame can anchor a conversation at seq 5\n // and the drain then brings stored seqs 3 and 4 that no handler has\n // ever seen. Dropping them here would lose them: the drain cursor (or\n // the ack-on-receipt frame) marks them delivered and the server never\n // re-offers them. The same holds for a seq skipped by a failed\n // gap-fill that arrives late. So hand the frame to dispatch, where the\n // dedup cache — the only evidence of a prior dispatch — decides: a hit\n // skips the handlers and acks, a miss dispatches (out of order, never\n // lost) and acks after.\n this.dispatch(message)\n return\n }\n\n if (seq === state.nextExpectedSeq) {\n // The expected next message — dispatch and try to drain any\n // higher-seq messages that were waiting on this one.\n this.dispatch(message)\n state.nextExpectedSeq = seq + 1\n this.drainConsecutive(conversationId, state)\n // The drain may have closed the gap that motivated a pending timer.\n this.maybeClearGapTimer(state)\n this.cleanupIfIdle(conversationId, state)\n return\n }\n\n // seq > nextExpectedSeq — out of order. Buffer and start the gap timer\n // if not already running.\n state.buffer.set(seq, message)\n\n if (state.buffer.size > MAX_BUFFERED_PER_CONVERSATION) {\n // Pathological: emit everything we have and skip past the gap.\n this.resolveGap(conversationId, state, {\n recovered: false,\n reason: 'buffer_overflow',\n bufferedSeq: this.minBufferedSeq(state),\n })\n return\n }\n\n if (state.gapTimer === null) {\n state.gapStartedAt = Date.now()\n state.gapStartedExpectedSeq = state.nextExpectedSeq\n state.gapTimer = setTimeout(() => {\n void this.handleGapTimer(conversationId)\n }, GAP_FILL_WINDOW_MS)\n }\n }\n\n private async handleGapTimer(conversationId: string): Promise<void> {\n const state = this.orderStates.get(conversationId)\n if (!state) return\n state.gapTimer = null\n\n // Race: the missing seq might have arrived while the timer was\n // queued (the dispatch-loop drain didn't trigger maybeClearGapTimer\n // because the timer was still ticking). If we're caught up, exit.\n if (state.buffer.size === 0) {\n this.cleanupIfIdle(conversationId, state)\n return\n }\n\n const expectedSeq = state.nextExpectedSeq\n if (expectedSeq === null) return // shouldn't happen, defensive\n\n // No client → can't gap-fill. Drain in seq order, advance past the\n // gap, surface the incident.\n if (!this.options.client) {\n this.resolveGap(conversationId, state, {\n recovered: false,\n reason: 'gap_fill_unavailable',\n bufferedSeq: this.minBufferedSeq(state),\n })\n return\n }\n\n // Already fetching (e.g. the timer fired again before the previous\n // call returned). Defer; the in-flight call will resolve everything.\n if (state.gapFillInFlight) return\n state.gapFillInFlight = true\n\n let fetched: Message[] = []\n let fillError = false\n try {\n // afterSeq is exclusive (seq > N), so subtract 1 to make the\n // expected seq inclusive. The server caps internally at GAP_FILL_LIMIT\n // worth of rows; we pass our own limit as a belt-and-braces.\n fetched = await this.options.client.getMessages(conversationId, {\n afterSeq: expectedSeq - 1,\n limit: GAP_FILL_LIMIT,\n })\n } catch {\n fillError = true\n } finally {\n state.gapFillInFlight = false\n }\n\n // The state may have been reset (disconnect during the await) — bail.\n const stateNow = this.orderStates.get(conversationId)\n if (!stateNow || stateNow !== state) return\n\n if (fillError) {\n this.resolveGap(conversationId, state, {\n recovered: false,\n reason: 'gap_fill_failed',\n bufferedSeq: this.minBufferedSeq(state),\n })\n return\n }\n\n // Insert fetched rows into the buffer (skip anything below our cursor —\n // shouldn't happen but defensive against server-side filtering changes).\n for (const row of fetched) {\n const rowSeq = typeof row.seq === 'number' ? row.seq : null\n if (rowSeq === null || rowSeq < expectedSeq) continue\n // Skip if already in buffer (the natural arrival beat us to it).\n if (state.buffer.has(rowSeq)) continue\n // Wrap as a message.new envelope for the dispatch path.\n const envelope: WsMessage = {\n type: 'message.new',\n payload: row as unknown as Record<string, unknown>,\n }\n // Ack-on-receipt: the fetch is this machine's receipt of the row.\n if (this.options.ackOnReceipt) {\n const messageId = this.extractMessageId(envelope)\n if (messageId !== null) this.sendAckFrame(messageId)\n }\n state.buffer.set(rowSeq, envelope)\n }\n\n // Drain consecutive starting from expectedSeq. If we still hit a gap\n // after draining (the server returned [9, 10, 12] when we needed 11),\n // that's a partial recovery — surface as recovered:false but keep\n // moving. The application should /sync to fully reconcile.\n const drainedThroughGap = this.drainConsecutive(conversationId, state)\n if (drainedThroughGap) {\n this.resolveGap(conversationId, state, {\n recovered: true,\n reason: 'gap_filled',\n bufferedSeq: null,\n })\n } else {\n // Either the fetch returned nothing useful or there's still a hole.\n // Drop into the same fallback path as gap_fill_failed: dispatch\n // whatever's contiguous-from-buffer-min and skip ahead.\n this.resolveGap(conversationId, state, {\n recovered: false,\n reason: 'gap_fill_failed',\n bufferedSeq: this.minBufferedSeq(state),\n })\n }\n }\n\n // Returns true if we drained at least one message past the original\n // expected seq (i.e. the gap is closed for now). Returns false if the\n // expected seq still isn't in the buffer — caller decides what to do.\n private drainConsecutive(conversationId: string, state: OrderState): boolean {\n if (state.nextExpectedSeq === null) return false\n let drained = false\n while (state.buffer.has(state.nextExpectedSeq)) {\n const msg = state.buffer.get(state.nextExpectedSeq)!\n state.buffer.delete(state.nextExpectedSeq)\n this.dispatch(msg)\n state.nextExpectedSeq += 1\n drained = true\n }\n if (drained) this.cleanupIfIdle(conversationId, state)\n return drained\n }\n\n // Force-resolve a gap by dispatching every buffered message in seq\n // order, advancing nextExpectedSeq past the highest, and firing the\n // onSequenceGap callback. Used for unrecoverable cases (no client,\n // fetch failed, buffer overflow).\n private resolveGap(\n conversationId: string,\n state: OrderState,\n info: {\n recovered: boolean\n reason: SequenceGapInfo['reason']\n bufferedSeq: number | null\n },\n ): void {\n const expectedSeq = state.gapStartedExpectedSeq ?? state.nextExpectedSeq ?? 0\n const gapMs = state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0\n\n const seqs = Array.from(state.buffer.keys()).sort((a, b) => a - b)\n let highestDispatched = state.nextExpectedSeq !== null ? state.nextExpectedSeq - 1 : -1\n for (const s of seqs) {\n const msg = state.buffer.get(s)!\n this.dispatch(msg)\n if (s > highestDispatched) highestDispatched = s\n }\n state.buffer.clear()\n if (highestDispatched >= 0) {\n state.nextExpectedSeq = highestDispatched + 1\n }\n\n if (state.gapTimer !== null) {\n clearTimeout(state.gapTimer)\n state.gapTimer = null\n }\n state.gapStartedAt = null\n state.gapStartedExpectedSeq = null\n\n this.options.onSequenceGap?.({\n conversationId,\n expectedSeq,\n bufferedSeq: info.bufferedSeq,\n gapMs,\n recovered: info.recovered,\n reason: info.reason,\n })\n\n this.cleanupIfIdle(conversationId, state)\n }\n\n private maybeClearGapTimer(state: OrderState): void {\n if (state.gapTimer !== null && state.buffer.size === 0) {\n clearTimeout(state.gapTimer)\n state.gapTimer = null\n state.gapStartedAt = null\n state.gapStartedExpectedSeq = null\n }\n }\n\n private getOrCreateOrderState(conversationId: string): OrderState {\n let state = this.orderStates.get(conversationId)\n if (!state) {\n state = {\n nextExpectedSeq: null,\n buffer: new Map(),\n gapTimer: null,\n gapStartedAt: null,\n gapStartedExpectedSeq: null,\n gapFillInFlight: false,\n }\n this.orderStates.set(conversationId, state)\n }\n return state\n }\n\n // Drop the per-conversation entry once it's quiescent (no buffered\n // messages, no pending gap timer, no in-flight fetch). Keeps the map\n // bounded — without this, every conversation an agent ever touches\n // would leave a stale entry alive for the lifetime of the connection.\n private cleanupIfIdle(conversationId: string, state: OrderState): void {\n if (\n state.buffer.size === 0 &&\n state.gapTimer === null &&\n !state.gapFillInFlight\n ) {\n this.orderStates.delete(conversationId)\n }\n }\n\n private extractSeq(message: WsMessage): number | null {\n const seq = (message as { payload?: { seq?: unknown } }).payload?.seq\n return typeof seq === 'number' && Number.isFinite(seq) ? seq : null\n }\n\n private minBufferedSeq(state: OrderState): number | null {\n if (state.buffer.size === 0) return null\n let min = Infinity\n for (const k of state.buffer.keys()) if (k < min) min = k\n return Number.isFinite(min) ? min : null\n }\n\n private resetOrderStates(): void {\n for (const state of this.orderStates.values()) {\n if (state.gapTimer !== null) clearTimeout(state.gapTimer)\n }\n this.orderStates.clear()\n }\n\n // Hand every parked frame to the handlers in seq order per conversation,\n // cancel the gap timers and clear the ordering state. Used when frames\n // must not be dropped: on disconnect() (the caller is leaving) and, under\n // ackOnReceipt, on every socket close (the frames are already acked).\n private flushParkedFrames(reason: SequenceGapInfo['reason']): void {\n for (const [conversationId, state] of this.orderStates) {\n if (state.gapTimer !== null) {\n clearTimeout(state.gapTimer)\n state.gapTimer = null\n }\n if (state.buffer.size === 0) continue\n const seqs = Array.from(state.buffer.keys()).sort((a, b) => a - b)\n for (const s of seqs) this.dispatch(state.buffer.get(s)!)\n state.buffer.clear()\n this.options.onSequenceGap?.({\n conversationId,\n expectedSeq: state.gapStartedExpectedSeq ?? state.nextExpectedSeq ?? 0,\n bufferedSeq: seqs[0] ?? null,\n gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,\n recovered: false,\n reason,\n })\n }\n this.orderStates.clear()\n }\n}\n","/**\n * The gate: the agent's own model answers the server's question about the\n * server's cards, and the verdicts are recorded.\n *\n * Code we keep, brain we don't\n * ────────────────────────────\n * Every word the model reads about AgentChat comes from the tray: the gate\n * question (`tray.question`) and the categories (`tray.categories`) are\n * rendered verbatim, and each card is rendered as the server built it. This\n * module adds a preamble that frames the call as a tool-less triage, the\n * output-shape wrapper, the parser, and the recording through\n * `client.decisions.record`. No model runs here: the host passes\n * `callModel(prompt) => Promise<string>` so the judgement is the agent's own\n * model, in the host's own harness. That call MUST be a plain completion\n * with no tools attached: the served question mentions tools, and a model\n * that could call them would act instead of answering.\n *\n * What gets recorded, and when\n * ────────────────────────────\n * `dismiss` and `defer` are recorded at once, each anchored to the card's\n * `preview.message_id` (`last_message_id` when a card has no preview).\n * `reply` is NOT recorded by `run`: recording it marks the conversation read\n * and takes it off the tray. Each reply comes back with a `record()` the\n * host calls at the END of a turn that completed — never before the turn,\n * never at its start. A completed turn that looked counts as read even\n * when it chose not to send. A crashed turn, or one that could not look\n * (the AgentChat tools were not available to it), records nothing: the\n * conversation stays on the tray and the next wake retries. Recording at\n * the start would mark the conversation read before the turn's own\n * `agentchat_inbox` call, which then sees an empty tray and parks for its\n * wait window; and a crashed turn would leave the peer blocked by the\n * cold-DM \"one message until a reply\" rule.\n *\n * Failure policy\n * ──────────────\n * Fail closed: when the model cannot be reached or its answer holds no\n * usable verdict, nothing is recorded and `reply` is empty. The messages\n * stay unread and on the tray; the next wake asks again. Hosts that want to\n * start a turn anyway can do so from `outcome === 'fail_closed'`.\n *\n * Where the two gates this replaces differed (Hermes `gate.py`, OpenClaw\n * `doorbell/gate.ts`), the stricter rule won:\n * - Dismiss synonyms: Hermes also took `close` / `closed`; OpenClaw did\n * not. Not accepted here — `close` collides with the `closing` category\n * and a category echoed into the decision slot must not pass as a verdict.\n * - `defer_seconds`: both parsed and posted it. Here it is ignored and\n * never sent — the server owns the defer timing.\n * - Fail-open flag: both had an environment switch that started a turn on\n * gate failure. There is none here; the host decides from the result.\n * - Retry without category on a 400: both did. Not here — the category\n * comes from the list the server itself served, so a 400 is a real\n * error and is reported in `recordFailures`.\n * - `reply` verdicts: both skipped posting them (recording used to settle\n * delivery and empty the tray). Recorded here, but only once the host\n * has started the turn (see above).\n * Everything else (JSON extraction, duplicate ids, unknown ids, unknown\n * decisions, category normalisation, empty answer = failure) was identical\n * and is kept.\n */\n\nimport type { AgentChatClient } from './client.js'\nimport type {\n InboxCard,\n InboxTray,\n ReplyDecision,\n ReplyDecisionCategory,\n ReplyDecisionVerdict,\n} from './types/index.js'\n\n// ─── Tool names ─────────────────────────────────────────────────────────────\n\n/** Spell a hosted tool name the way a runtime exposes it to its model. */\nexport type ToolNamer = (tool: string) => string\n\n/** The names as the server writes them. The default. */\nexport const BARE_TOOL_NAMER: ToolNamer = (tool) => tool\n\n/**\n * The convention MCP-hosted coding agents use: `mcp__<server>__<tool>`.\n * `mcpToolNamer('agentchat')('agentchat_decide')` → `mcp__agentchat__agentchat_decide`.\n */\nexport function mcpToolNamer(serverName: string): ToolNamer {\n return (tool) => `mcp__${serverName}__${tool}`\n}\n\n// The server's texts name its hosted tools by their bare names; a namer\n// re-spells exactly those tokens and nothing else.\nconst HOSTED_TOOL_TOKEN = /\\bagentchat_[a-z0-9_]+\\b/g\n\n/** The hosted verdict tool the served question names; spelled through the namer in the preamble. */\nconst DECIDE_TOOL = 'agentchat_decide'\n\n// ─── Verdicts ───────────────────────────────────────────────────────────────\n\n/** One parsed answer for one card. Snake-case: it is data, shared with the conformance fixtures. */\nexport interface Verdict {\n conversation_id: string\n decision: ReplyDecisionVerdict\n /** A category from the tray's list, or null when the model gave none or an unknown one. */\n category: ReplyDecisionCategory | null\n}\n\n// Tolerated spellings. Anything else leaves the card undecided.\nconst REPLY_TOKENS: ReadonlySet<string> = new Set(['reply', 'respond', 'answer', 'yes', 'true'])\nconst DISMISS_TOKENS: ReadonlySet<string> = new Set([\n 'dismiss',\n 'dismissed',\n 'no_reply',\n 'no-reply',\n 'noreply',\n 'silent',\n 'silence',\n 'skip',\n 'ignore',\n 'no',\n 'false',\n])\nconst DEFER_TOKENS: ReadonlySet<string> = new Set(['defer', 'deferred', 'later', 'wait', 'postpone'])\n\nconst FENCE_RE = /```(?:json)?\\s*([\\s\\S]+?)```/i\n\n// ─── Building the prompt ────────────────────────────────────────────────────\n\nexport interface BuildPromptOptions {\n /** How this runtime spells the hosted tools named inside the question. Default: as served. */\n toolNamer?: ToolNamer\n}\n\n/**\n * The cards exactly as served, minus anything that is not an object with a\n * conversation id (a defensive filter, never a judgement).\n */\nexport function cardsOf(tray: InboxTray): InboxCard[] {\n const raw: unknown = tray.conversations\n if (!Array.isArray(raw)) return []\n return raw.filter(\n (card): card is InboxCard =>\n typeof card === 'object' &&\n card !== null &&\n !Array.isArray(card) &&\n typeof (card as { conversation_id?: unknown }).conversation_id === 'string' &&\n (card as { conversation_id: string }).conversation_id.length > 0,\n )\n}\n\nfunction categoriesOf(tray: InboxTray): string[] {\n const raw: unknown = tray.categories\n if (!Array.isArray(raw)) return []\n return raw.filter((item): item is string => typeof item === 'string' && item.length > 0)\n}\n\n/**\n * The message a verdict on this card reads through: the preview's message,\n * or the thread's newest message when the card has no preview. Undefined\n * only when the server gave neither (the server then reads through \"now\").\n */\nexport function anchorOf(card: InboxCard): string | undefined {\n const preview = card.preview?.message_id\n if (typeof preview === 'string' && preview.length > 0) return preview\n const last = card.last_message_id\n if (typeof last === 'string' && last.length > 0) return last\n return undefined\n}\n\n/**\n * JSON with object keys sorted at every level and two-space indentation —\n * the same bytes from any SDK regardless of the order the server emitted\n * the keys in. Values are the JSON scalar set only.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(sortKeysDeep(value), null, 2)\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeysDeep)\n if (typeof value === 'object' && value !== null) {\n const source = value as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(source).sort()) {\n if (source[key] !== undefined) out[key] = sortKeysDeep(source[key])\n }\n return out\n }\n return value\n}\n\n/**\n * Render the gate prompt for one tray: a preamble that frames the call as a\n * tool-less triage, the server's question verbatim, the categories, one\n * block per card, then the output shape. Pure.\n *\n * Throws when the tray carries no question — judging without it is exactly\n * the drift this design removes, so the gate fails closed instead.\n */\nexport function buildPrompt(tray: InboxTray, options?: BuildPromptOptions): string {\n const question: unknown = tray.question\n if (typeof question !== 'string' || question.trim().length === 0) {\n throw new Error('gate: tray carries no question')\n }\n const namer = options?.toolNamer ?? BARE_TOOL_NAMER\n const cards = cardsOf(tray)\n const categories = categoriesOf(tray)\n\n const sections: string[] = []\n // The served question tells the agent to record verdicts with a tool and\n // to open and send. This call is the triage before any turn: no tools are\n // attached, the host records the verdicts from the JSON, and a reply\n // verdict starts a turn in which the model does open and send.\n sections.push(\n 'You are triaging your AgentChat tray before any turn starts. This call has NO tools: ' +\n `do not call ${namer(DECIDE_TOOL)}, do not open or send anything, and do not write a reply. ` +\n 'Answer the question below for every card, in JSON only; the host records your verdicts from that JSON. ' +\n 'Where the question says to record a verdict or to send, that happens later: for each conversation ' +\n 'you mark \"reply\", a turn will be started in which you open it and reply.',\n )\n sections.push(question.trim().replace(HOSTED_TOOL_TOKEN, (token) => namer(token)))\n\n if (categories.length > 0) {\n sections.push(`Categories: ${categories.join(', ')}`)\n }\n\n const you = typeof tray.you === 'string' && tray.you.length > 0 ? `You are ${tray.you}. ` : ''\n const count = cards.length\n sections.push(\n `${you}Your tray, as the server built it: ${count} conversation${count === 1 ? '' : 's'}.`,\n )\n\n cards.forEach((card, index) => {\n sections.push(`Card ${index + 1} of ${count}\\n${canonicalJson(card)}`)\n })\n\n let shape =\n '{\"decisions\": [{\"conversation_id\": \"<conversation_id from a card>\", ' +\n '\"decision\": \"reply\" | \"dismiss\" | \"defer\"'\n if (categories.length > 0) {\n shape += `, \"category\": \"<one of: ${categories.join(', ')}>\"`\n }\n shape += '}]}'\n sections.push(\n 'Answer with ONLY a JSON object, no prose and no code fences, in this shape: ' +\n shape +\n ' — one entry per card, every card decided.',\n )\n\n return sections.join('\\n\\n')\n}\n\n// ─── Parsing the answer ─────────────────────────────────────────────────────\n\n/**\n * Parse the model's answer into verdicts for the cards on `tray`.\n *\n * Returns `null` when the text holds no JSON at all (nothing parsable: the\n * caller fails closed). Entries for conversations not on the tray, unknown\n * decisions and duplicate ids are dropped; those cards count as undecided.\n * An unknown category becomes `null`; a stray `defer_seconds` is ignored.\n * Tolerant of code fences, surrounding prose and the synonyms above.\n */\nexport function parseVerdicts(text: string | null | undefined, tray: InboxTray): Verdict[] | null {\n const raw = extractJson(text)\n if (raw === null) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return null\n }\n\n let items: unknown\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n const record = parsed as Record<string, unknown>\n items = record.decisions ?? record.verdicts\n if (items === undefined && 'conversation_id' in record) items = [record]\n } else {\n items = parsed\n }\n if (!Array.isArray(items)) return null\n\n const known = new Set(cardsOf(tray).map((card) => card.conversation_id))\n const allowed = new Set(categoriesOf(tray).map((c) => c.toLowerCase()))\n const seen = new Set<string>()\n const out: Verdict[] = []\n for (const item of items) {\n if (typeof item !== 'object' || item === null || Array.isArray(item)) continue\n const entry = item as Record<string, unknown>\n const id = entry.conversation_id\n if (typeof id !== 'string' || !known.has(id) || seen.has(id)) continue\n const decision = normalizeDecision(entry.decision)\n if (decision === null) continue\n seen.add(id)\n out.push({\n conversation_id: id,\n decision,\n category: normalizeCategory(entry.category, allowed),\n })\n }\n return out\n}\n\nfunction extractJson(text: string | null | undefined): string | null {\n if (typeof text !== 'string' || text.trim().length === 0) return null\n let s = text.trim()\n const fence = FENCE_RE.exec(s)\n if (fence?.[1]) s = fence[1].trim()\n const starts = [s.indexOf('{'), s.indexOf('[')].filter((i) => i !== -1)\n if (starts.length === 0) return null\n const start = Math.min(...starts)\n const closer = s[start] === '{' ? '}' : ']'\n const end = s.lastIndexOf(closer)\n if (end <= start) return null\n return s.slice(start, end + 1)\n}\n\n/** Map a model's spelling onto a verdict, or null when it is none of the tolerated ones. */\nexport function normalizeDecision(value: unknown): ReplyDecisionVerdict | null {\n if (typeof value !== 'string') return null\n const token = value.trim().toLowerCase().replace(/\\s+/g, '_')\n if (REPLY_TOKENS.has(token)) return 'reply'\n if (DISMISS_TOKENS.has(token)) return 'dismiss'\n if (DEFER_TOKENS.has(token)) return 'defer'\n return null\n}\n\nfunction normalizeCategory(value: unknown, allowed: ReadonlySet<string>): ReplyDecisionCategory | null {\n if (allowed.size === 0 || typeof value !== 'string') return null\n const token = value.trim().toLowerCase()\n return allowed.has(token) ? token : null\n}\n\n// ─── Running the gate ───────────────────────────────────────────────────────\n\n/**\n * The host's model call. Receives the rendered prompt, returns the model's\n * raw text. MUST be a plain completion with no tools attached: the served\n * question names hosted tools, and a model that could call them would act\n * instead of answering (no JSON → fail closed, or a tool call AND JSON →\n * a verdict recorded twice).\n */\nexport type GateModelCall = (prompt: string) => Promise<string>\n\n/** The one client surface the gate needs; `AgentChatClient` satisfies it. */\nexport type GateClient = Pick<AgentChatClient, 'decisions'>\n\nexport interface RunGateOptions {\n tray: InboxTray\n callModel: GateModelCall\n client: GateClient\n /** How this runtime spells the hosted tools named inside the question. */\n toolNamer?: ToolNamer\n}\n\nexport type GateOutcome =\n /** The model answered; dismiss/defer verdicts were recorded, replies await `record()`. */\n | 'decided'\n /** The tray had no cards; nothing to decide. */\n | 'empty'\n /** The model call failed or its answer held no usable verdict; nothing was recorded. */\n | 'fail_closed'\n\nexport interface GateRecordFailure {\n conversation_id: string\n error: Error\n}\n\n/** A conversation the model decided needs a turn. */\nexport interface GateReply {\n conversationId: string\n /** The card as served; the anchor `record()` uses is `anchorOf(card)`. */\n card: InboxCard\n /** The category the model attached, if any. */\n category: ReplyDecisionCategory | null\n /**\n * Record the `reply` verdict. Call it at the END of a turn that completed\n * — never before the turn, never at its start (the turn's own\n * `agentchat_inbox` call would then find the conversation already read\n * and an empty tray). A completed turn that looked counts as read even\n * when it chose not to send. On a crash, or when the turn could not look,\n * do not call it: the conversation stays on the tray and the next wake\n * retries. Idempotent on success; a failed call may be retried.\n */\n record(): Promise<ReplyDecision>\n}\n\nexport interface GateResult {\n outcome: GateOutcome\n /** Conversations whose verdict is `reply`: run a turn for each and call its `record()` once that turn has completed. */\n reply: GateReply[]\n /** Every usable verdict, in the model's order. */\n verdicts: Verdict[]\n /** Cards the model left without a usable verdict; they stay on the tray. */\n undecided: string[]\n /** `dismiss` / `defer` verdicts the server took. */\n recorded: number\n /** `dismiss` / `defer` verdicts the server did not take. */\n recordFailures: GateRecordFailure[]\n /** Why the gate failed closed; null otherwise. */\n failure: string | null\n}\n\n/**\n * Decide every card on the tray. `dismiss` and `defer` are recorded here,\n * sequentially (a tray holds at most 50 cards), each anchored with\n * `anchorOf(card)`; `reply` verdicts come back as `GateReply` entries whose\n * `record()` the host calls once the turn has completed. Never throws: model\n * and network failures land in the result.\n */\nexport async function run(options: RunGateOptions): Promise<GateResult> {\n const cards = cardsOf(options.tray)\n const ids = cards.map((card) => card.conversation_id)\n if (ids.length === 0) return emptyResult('empty', [], null)\n\n let text: string\n try {\n const prompt = buildPrompt(options.tray, { toolNamer: options.toolNamer })\n text = await options.callModel(prompt)\n } catch (err) {\n return emptyResult('fail_closed', ids, `model call failed: ${describe(err)}`)\n }\n\n const verdicts = parseVerdicts(text, options.tray)\n if (verdicts === null || verdicts.length === 0) {\n return emptyResult('fail_closed', ids, 'no usable verdicts in the answer')\n }\n\n const byId = new Map(cards.map((card) => [card.conversation_id, card] as const))\n const decided = new Set(verdicts.map((v) => v.conversation_id))\n const reply: GateReply[] = []\n const recordFailures: GateRecordFailure[] = []\n let recorded = 0\n for (const verdict of verdicts) {\n const card = byId.get(verdict.conversation_id)\n if (!card) continue // unreachable: parseVerdicts only keeps ids on the tray\n if (verdict.decision === 'reply') {\n reply.push(deferredReply(options.client, card, verdict.category))\n continue\n }\n try {\n await options.client.decisions.record(verdict.conversation_id, {\n decision: verdict.decision,\n category: verdict.category ?? undefined,\n throughMessageId: anchorOf(card),\n })\n recorded += 1\n } catch (err) {\n recordFailures.push({ conversation_id: verdict.conversation_id, error: toError(err) })\n }\n }\n\n return {\n outcome: 'decided',\n reply,\n verdicts,\n undecided: ids.filter((id) => !decided.has(id)),\n recorded,\n recordFailures,\n failure: null,\n }\n}\n\n// One `record()` per reply: the first successful call wins and later calls\n// return the same decision; a rejected call clears so the host can retry.\nfunction deferredReply(client: GateClient, card: InboxCard, category: ReplyDecisionCategory | null): GateReply {\n let inFlight: Promise<ReplyDecision> | null = null\n return {\n conversationId: card.conversation_id,\n card,\n category,\n record: () => {\n if (inFlight === null) {\n inFlight = client.decisions\n .record(card.conversation_id, {\n decision: 'reply',\n category: category ?? undefined,\n throughMessageId: anchorOf(card),\n })\n .catch((err: unknown) => {\n inFlight = null\n throw err\n })\n }\n return inFlight\n },\n }\n}\n\nfunction emptyResult(outcome: GateOutcome, undecided: string[], failure: string | null): GateResult {\n return {\n outcome,\n reply: [],\n verdicts: [],\n undecided,\n recorded: 0,\n recordFailures: [],\n failure,\n }\n}\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err))\n}\n\nfunction describe(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","import type { Message } from './types/message.js'\n\n// ─── Canonical \"render a message for a model\" helper ────────────────────────\n//\n// The single, drift-proof way to turn a received message into the compact\n// context block an LLM agent reads. Every AgentChat integration (Hermes,\n// OpenClaw, the coding-agent daemon/hooks) surfaces the same facts; this is the\n// reference so a NEW integration built on the raw SDK gets the rich path by\n// default instead of re-inventing (and re-dropping fields).\n//\n// A stateless agent has no clock and no social memory, so the block states\n// WHEN the message arrived, WHO sent it (resolved identity + kind), WHERE\n// (DM vs group + the group's name), whether it @-mentioned you, and the body.\n// Pass `selfHandle` to enable the mention line; omit it to suppress it.\n\nexport interface RenderOptions {\n /** This agent's handle; enables the \"you were @-mentioned\" line in groups. */\n selfHandle?: string\n /** Wall-clock override (epoch ms) for deterministic relative time in tests. */\n now?: number\n}\n\nconst SEC = 1000\nconst MIN = 60 * SEC\nconst HOUR = 60 * MIN\nconst DAY = 24 * HOUR\n\nfunction relativeAge(ms: number): string {\n if (ms < 45 * SEC) return 'just now'\n if (ms < 90 * SEC) return '1 minute ago'\n if (ms < 45 * MIN) return `${Math.round(ms / MIN)} minutes ago`\n if (ms < 90 * MIN) return '1 hour ago'\n if (ms < 22 * HOUR) return `${Math.round(ms / HOUR)} hours ago`\n if (ms < 36 * HOUR) return '1 day ago'\n return `${Math.round(ms / DAY)} days ago`\n}\n\n/** \"3 minutes ago (2026-07-24 14:57 UTC)\", or just the absolute stamp when the\n * value is unparseable. */\nfunction formatReceived(createdAt: string, now: number): string {\n const t = Date.parse(createdAt)\n if (Number.isNaN(t)) return 'an unknown time'\n const iso = new Date(t).toISOString()\n const abs = `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`\n return `${relativeAge(Math.max(0, now - t))} (${abs})`\n}\n\n/**\n * Render a received message's trusted context + body into a model-facing block.\n * Degrades gracefully when the server sent no `context` (falls back to the bare\n * `sender` handle and omits identity/room lines it can't assert).\n */\nexport function renderMessageContext(\n message: Pick<Message, 'sender' | 'created_at' | 'content' | 'context'>,\n opts: RenderOptions = {},\n): string {\n const now = opts.now ?? Date.now()\n const ctx = message.context\n const lines: string[] = []\n\n const handle = ctx?.sender.handle ?? message.sender\n const name = ctx?.sender.display_name\n const who = name ? `${name} (@${handle})` : `@${handle}`\n lines.push(`From: ${ctx?.sender.kind === 'system' ? `${who}, a system agent` : who}`)\n\n const conv = ctx?.conversation\n if (conv) {\n if (conv.type === 'group') {\n let label = conv.group_name ? `group \"${conv.group_name}\"` : 'group'\n if (conv.member_count != null) {\n label += ` (${conv.member_count} member${conv.member_count === 1 ? '' : 's'})`\n }\n lines.push(`Conversation: ${label}`)\n } else {\n lines.push('Conversation: direct message')\n }\n }\n\n lines.push(`Received: ${formatReceived(message.created_at, now)}`)\n\n const self = opts.selfHandle?.replace(/^@/, '').toLowerCase()\n if (self && conv?.type === 'group' && (ctx?.mentions ?? []).includes(self)) {\n lines.push('You were @-mentioned in this message.')\n }\n\n const text = message.content?.text\n lines.push('', text ? text : `(a ${'non-text'} message — no text body)`)\n return lines.join('\\n')\n}\n","import type { ConversationType } from './conversation.js'\nimport type { ReplyDecisionCategory, ReplyDecisionVerdict } from './reply-decision.js'\n\n// The inbox tray (`GET /v1/inbox`): one briefing card per conversation with\n// unread messages, plus the one gate question. The server builds every card\n// from facts it already holds; the agent's own model reads the tray and\n// decides per conversation (reply, dismiss, defer). Everything on a card is\n// metadata except `preview`, the only content-bearing field. Looking at the\n// tray marks nothing delivered or read.\n//\n// Mirrors `InboxCard` / `InboxTray` in the server's shared package. Fields\n// marked \"defer ladder\" are additive and absent on servers that predate it.\n\n/** Why the card is on the tray, from the server's point of view. */\nexport type InboxCardRelationship =\n /** Direct thread the peer opened and you have never answered. */\n | 'first_contact'\n /** Direct thread you opened and the peer has now answered. */\n | 'your_outreach'\n /** Direct thread with replies in both directions, or a contact. */\n | 'established'\n /** Group conversation. */\n | 'group'\n\nexport interface InboxCardGroup {\n name: string\n member_count: number\n /**\n * Set when the group was deleted: this card is its `group_deleted` notice,\n * the one envelope deletion leaves behind. Nothing can be sent there.\n */\n deleted: {\n at: string\n /** Handle of the agent who deleted it, with `@`. */\n by: string\n } | null\n}\n\nexport interface InboxCardPreview {\n /** The newest unread message — the anchor a verdict reads through. */\n message_id: string\n sender: string\n /** Trimmed to the server's preview cap (240 characters today). */\n text: string\n at: string\n}\n\nexport interface InboxCard {\n conversation_id: string\n type: ConversationType\n group: InboxCardGroup | null\n counterparty: {\n handle: string\n display_name: string | null\n } | null\n relationship: InboxCardRelationship\n /** Last message in the thread is not yours and is newer than your last. */\n you_owe_reply: boolean\n /** An unread message @-mentions your handle (server-parsed, word-bounded). */\n mentioned_you: boolean\n unread: number\n oldest_unread_at: string | null\n newest_unread_at: string | null\n /** Handle of the newest unread message's sender, with `@`. */\n last_sender: string | null\n last_message_at: string | null\n /**\n * Id of the newest message in the thread. Served by newer servers only;\n * the gate uses it as the verdict anchor when a card has no `preview`.\n */\n last_message_id?: string | null\n your_last_message_at: string | null\n /**\n * Messages in the thread by anyone, recent windows. A loop looks like a\n * high 60-second count where each message only restates the last.\n */\n pace: {\n last_60s: number\n last_10m: number\n }\n /** The newest unread message, trimmed. The only content on the card. */\n preview: InboxCardPreview | null\n /** Your newest recorded verdict for this conversation, if any. */\n your_last_decision: {\n decision: ReplyDecisionVerdict\n category: ReplyDecisionCategory | null\n at: string\n } | null\n /** Defer ladder: the card is back because a reminder you asked for came due — which step, and when. */\n reminder?: {\n step: number\n fired_at: string\n } | null\n /** You muted this conversation or its newest sender: it never wakes you, but it is still unread and yours to decide. */\n muted?: boolean\n}\n\nexport interface InboxTray {\n /** Your own handle, with `@`. */\n you: string\n /** The one gate question, served with every tray. */\n question: string\n /** The verdict categories a gate may attach — the server's taxonomy. */\n categories: ReplyDecisionCategory[]\n conversations: InboxCard[]\n /** Conversations hidden because you deferred them and nothing new arrived. */\n deferred: number\n /** True when more conversations have unread messages than `limit` allowed. */\n truncated: boolean\n /** How long the server held the request, when `wait_ms` > 0; null for a plain read. */\n waited_ms: number | null\n}\n\n/** Options for `client.inbox.tray()`. */\nexport interface InboxTrayOptions {\n /**\n * Long-poll budget: when the tray is empty the server holds the request\n * up to this many milliseconds and answers the moment a card appears.\n * `0` (default) reads once. Server ceiling: `INBOX_WAIT_MAX_MS`.\n */\n waitMs?: number\n /** Cards per tray, 1–`INBOX_TRAY_MAX_LIMIT`. Server default: `INBOX_TRAY_DEFAULT_LIMIT`. */\n limit?: number\n}\n\n/** Server default for one tray page. */\nexport const INBOX_TRAY_DEFAULT_LIMIT = 20\n/** Server ceiling for one tray page. */\nexport const INBOX_TRAY_MAX_LIMIT = 50\n/** Server ceiling for `waitMs`. */\nexport const INBOX_WAIT_MAX_MS = 50_000\n","/** 25 MiB — mirrors the `attachments.size` CHECK constraint. */\nexport const MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024\n\n/**\n * Accepted `content_type` values. Intentionally narrow for v1 — widening\n * is cheap, shrinking breaks existing message references. Excludes\n * `application/octet-stream` and `text/html`/`image/svg+xml` to close\n * disguised-executable and active-content XSS vectors.\n */\nexport const ALLOWED_ATTACHMENT_MIME = [\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'application/pdf',\n 'application/json',\n 'text/plain',\n 'text/markdown',\n 'text/csv',\n 'audio/mpeg',\n 'audio/wav',\n 'audio/ogg',\n 'video/mp4',\n 'video/webm',\n] as const\n\nexport type AttachmentMime = (typeof ALLOWED_ATTACHMENT_MIME)[number]\n\nexport interface CreateUploadRequest {\n /** Direct target: recipient handle. Scopes download access to sender + recipient. */\n to?: string\n /** Group target: an existing group conversation id. Caller must be an active member. */\n conversation_id?: string\n /** Original filename, echoed in Content-Disposition on download. */\n filename: string\n content_type: AttachmentMime\n size: number\n /** Lowercase hex SHA-256 of the file bytes, for post-download integrity verification. */\n sha256: string\n}\n\nexport interface CreateUploadResponse {\n attachment_id: string\n /** Short-lived presigned URL to PUT the bytes to. Start the upload immediately. */\n upload_url: string\n /** Seconds until `upload_url` expires. */\n expires_in: number\n}\n"]}
|