@theokit/agents 6.4.2 → 7.1.0

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.
Files changed (41) hide show
  1. package/LICENSE +201 -0
  2. package/dist/{agent-handle-C6q7iA4u.d.ts → agent-handle-tgyu8J7q.d.ts} +9 -9
  3. package/dist/auth.js +1 -1
  4. package/dist/auth.js.map +1 -1
  5. package/dist/{bridge-entry-B-DQXIgk.d.ts → bridge-entry-ofFpOe-j.d.ts} +73 -13
  6. package/dist/bridge.d.ts +2 -2
  7. package/dist/bridge.js +2 -2
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/{chunk-NTDOKNSU.js → chunk-CVDPGEJF.js} +8 -28
  10. package/dist/chunk-CVDPGEJF.js.map +1 -0
  11. package/dist/{chunk-UJPG3K26.js → chunk-LJLNFCLS.js} +540 -926
  12. package/dist/chunk-LJLNFCLS.js.map +1 -0
  13. package/dist/{chunk-7QVYU63E.js → chunk-Z4QWC7IK.js} +1 -1
  14. package/dist/chunk-Z4QWC7IK.js.map +1 -0
  15. package/dist/client-react.d.ts +4 -4
  16. package/dist/client-react.js +2 -2
  17. package/dist/client-react.js.map +1 -1
  18. package/dist/client.d.ts +39 -24
  19. package/dist/client.js +2 -2
  20. package/dist/client.js.map +1 -1
  21. package/dist/index.d.ts +4 -4
  22. package/dist/index.js +2 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/interactive.js +1 -1
  25. package/dist/interactive.js.map +1 -1
  26. package/dist/persistence.d.ts +1 -1
  27. package/dist/persistence.js +3 -3
  28. package/dist/persistence.js.map +1 -1
  29. package/dist/pty.js +1 -1
  30. package/dist/pty.js.map +1 -1
  31. package/dist/sandbox.d.ts +1 -1
  32. package/dist/sandbox.js +3 -3
  33. package/dist/sandbox.js.map +1 -1
  34. package/dist/testing.js +1 -1
  35. package/dist/testing.js.map +1 -1
  36. package/dist/tools.js +1 -1
  37. package/dist/tools.js.map +1 -1
  38. package/package.json +14 -18
  39. package/dist/chunk-7QVYU63E.js.map +0 -1
  40. package/dist/chunk-NTDOKNSU.js.map +0 -1
  41. package/dist/chunk-UJPG3K26.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/client/consume-ui-message-stream.ts","../src/client/http-transport.ts","../src/client/last-user-text.ts","../src/client/in-process-transport.ts","../src/client/channel-transport.ts","../src/client/agent-client.ts","../src/client/agent-handle.ts"],"sourcesContent":["import type { UIMessage, UIMessageChunk } from 'ai'\n\n/**\n * M2 (theokit-ai-first) — read a TheoKit agent endpoint's `UIMessageStream` SSE `Response`\n * into reconstructed assistant `UIMessage`s, reusing the `ai` package's own consumer\n * primitives (`parseJsonEventStream` + `readUIMessageStream`) — the exact path\n * `@ai-sdk/react`'s `useChat` runs internally. No reinvented wire parser (Rule 9).\n *\n * `ai` is an OPTIONAL peer dependency, so it is imported dynamically: an app that never\n * calls an agent never pays for it, and importing `theokit/client` does not hard-require\n * `ai` (mirrors how the agent runtime dynamically imports `@theokit/sdk`). An agent app\n * always has `ai` installed (it is the UIMessageStream consumer).\n *\n * `onMessage` is invoked on every reconstruction step with the latest snapshot of the\n * assistant message, so a caller (the `useAgent` hook) can render streaming updates.\n */\nexport async function consumeUIMessageStream(\n response: Response,\n onMessage: (message: UIMessage) => void,\n): Promise<void> {\n const chunkStream = await responseToChunkStream(response)\n await consumeChunkStream(chunkStream, onMessage)\n}\n\n/**\n * M41 (ADR-0050 D3) — the reusable middle piece: a UIMessageStream SSE `Response` →\n * `ReadableStream<UIMessageChunk>`, reusing `ai`'s own `parseJsonEventStream` (the exact primitive\n * `useChat` runs). This is precisely what a `ChatTransport.sendMessages` returns, so `HttpTransport`\n * builds on it directly (no reinvented wire parser — Rule 9). A body-less response yields an empty stream.\n */\nexport async function responseToChunkStream(\n response: Response,\n): Promise<ReadableStream<UIMessageChunk>> {\n if (response.body === null) {\n return new ReadableStream<UIMessageChunk>({\n start(controller) {\n controller.close()\n },\n })\n }\n\n const { parseJsonEventStream, uiMessageChunkSchema } = await import('ai')\n\n // ai validates each SSE JSON frame against its own strict chunk schema (the exact gate `useChat`\n // runs), then yields `{ success, value }`; forward the valid chunks.\n const parsed = parseJsonEventStream({ stream: response.body, schema: uiMessageChunkSchema })\n return new ReadableStream<UIMessageChunk>({\n async start(controller) {\n for await (const result of parsed) {\n if (result.success) controller.enqueue(result.value)\n }\n controller.close()\n },\n })\n}\n\n/**\n * M41 (ADR-0050 D6) — read a `ReadableStream<UIMessageChunk>` into reconstructed assistant\n * `UIMessage`s via `ai`'s `readUIMessageStream`. Shared by `consumeUIMessageStream` (Response path)\n * and the framework-agnostic `AgentClient` store (transport path). `onMessage` fires on every\n * reconstruction step so a caller can render streaming updates.\n */\nexport async function consumeChunkStream(\n stream: ReadableStream<UIMessageChunk>,\n onMessage: (message: UIMessage) => void,\n): Promise<void> {\n const { readUIMessageStream } = await import('ai')\n // #136 — a provider failure (401/429/5xx) arrives as a `{ type: 'error', errorText }` chunk, NOT a\n // thrown rejection (the in-process runner and the SSE path both emit it as data). With the default\n // `readUIMessageStream({ stream })` (no `onError`, `terminateOnError` off) that chunk is silently\n // swallowed — the stream ends \"clean\" and the store settles to 'done' instead of 'error'.\n // `onError` captures the error; `terminateOnError` stops reconstructing partial messages after it AND\n // (under ai@7.0.14) errors the underlying iterator — so the `for await` below rejects and\n // `AgentClient.#drive`'s existing catch surfaces it (status='error', error set). The post-loop\n // `throw` is a defensive fallback that still surfaces the captured error if a future `ai` version\n // stops rejecting under `terminateOnError`; it is dead code under ai@7.0.14 but cheap version-robustness.\n let streamError: Error | undefined\n for await (const message of readUIMessageStream({\n stream,\n onError: (err) => {\n streamError = err instanceof Error ? err : new Error(String(err))\n },\n terminateOnError: true,\n })) {\n onMessage(message)\n }\n if (streamError !== undefined) throw streamError\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { responseToChunkStream } from './consume-ui-message-stream.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** Extra request headers — a static record OR a resolver called per request (for dynamic auth). */\nexport type HeadersResolver = Record<string, string> | (() => Record<string, string> | undefined)\n\nexport interface HttpTransportOptions {\n /** Agent endpoint path or URL, e.g. `/api/agents/support`. */\n api: string\n /**\n * Extra request headers (e.g. auth). Static record OR a resolver evaluated on EVERY request — pass a\n * resolver when the value is dynamic (a rotating JWT), so a stale header is never sent. Merged UNDER\n * per-request headers.\n */\n headers?: HeadersResolver\n /** Override fetch (primarily for tests / non-browser hosts) — static; resolved once at construction. */\n fetch?: typeof fetch\n}\n\n/** Normalize `ai`'s `Record | Headers | undefined` header option into a plain record. */\nfunction toRecord(headers: Record<string, string> | Headers | undefined): Record<string, string> {\n if (headers === undefined) return {}\n if (headers instanceof Headers) return Object.fromEntries(headers.entries())\n return headers\n}\n\n/**\n * M41 (ADR-0050 D3) — `ChatTransport` over the web agent path.\n *\n * - `sendMessages`: `POST <api>` with the UIMessageStream `accept` + the `X-Theo-Action` CSRF header\n * (HTTP method + headers are identical to the pre-M41 `useAgent` fetch; the body shape is a superset —\n * `{ ...input, messages: [UIMessage] }` — which the server's dual-path parser accepts, so no\n * regression), captures the server-minted `x-theokit-run-id`, and returns `ReadableStream<UIMessageChunk>`\n * via `ai`'s own SSE parser (`responseToChunkStream`).\n * - `reconnectToStream`: `GET <api>/runs/<runId>/stream` (M37 durable transport); 404 → `null` (the run\n * completed / was evicted). A caller may pass a `Last-Event-ID` header to resume only the tail; by\n * default the server replays the run from the start and the client upserts by message id (idempotent).\n * - `approve`: `POST <api>/approve/<id>` (out-of-band HITL settle).\n *\n * Implemented directly (not by subclassing `DefaultChatTransport`) because reconnect keys on our\n * server-minted `runId` captured from a response header, which the base class does not expose — see\n * ADR-0050 D3.\n */\nexport class HttpTransport implements AgentTransport {\n readonly #api: string\n readonly #headers: HeadersResolver\n readonly #fetch: typeof fetch\n /** Server-minted id of the last run (from `x-theokit-run-id`) — the reconnect key. */\n #lastRunId: string | undefined\n\n constructor(options: HttpTransportOptions) {\n this.#api = options.api\n this.#headers = options.headers ?? {}\n // BIND the default fetch to globalThis — the native `fetch` throws `TypeError: Illegal invocation` when\n // invoked as a method (`this.#fetch(...)` would set `this` to this transport instance, not the window).\n // An injected fetch (tests / non-browser hosts) is a plain function and is used as-is.\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis)\n }\n\n /** Resolve the configured headers per request (a resolver evaluates now — dynamic auth is never stale). */\n #resolveHeaders(): Record<string, string> {\n return (typeof this.#headers === 'function' ? this.#headers() : this.#headers) ?? {}\n }\n\n async sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, headers, body, chatId } = options\n // Only spread an object body (never a primitive — that would emit char-indexed keys). `body` is typed\n // `object | undefined` (ai's `ChatRequestOptions`), so no cast is needed — the guard narrows to\n // `object`. (A runtime-`null` body, which the type forbids, spreads to `{}` — harmless.) The server\n // accepts `{ messages }` (ai shape) AND `{ ...input }` (typed input), preferring the turn text.\n const extra = typeof body === 'object' ? body : undefined\n const response = await this.#fetch(this.#api, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n accept: 'text/event-stream',\n 'X-Theo-Action': '1',\n ...this.#resolveHeaders(),\n ...toRecord(headers),\n },\n // Send the stable `chatId` as the top-level `id` — the server reads it as the sessionId, so ONE\n // conversation (SDK history + session-scoped tools like `todolist`) persists across turns instead of\n // resetting on a fresh random session each request. Placed last so a session is never shadowed by an\n // `id` field inside the typed input. Undefined chatId ⇒ key omitted ⇒ server falls back (unchanged).\n body: JSON.stringify({ ...extra, messages, id: chatId }),\n signal: abortSignal,\n })\n if (!response.ok) {\n throw new Error(\n `Agent request to ${this.#api} failed: ${response.status} ${response.statusText}`,\n )\n }\n this.#lastRunId = response.headers.get('x-theokit-run-id') ?? undefined\n return responseToChunkStream(response)\n }\n\n async reconnectToStream(\n options: Parameters<ChatTransport<UIMessage>['reconnectToStream']>[0],\n ): Promise<ReadableStream<UIMessageChunk> | null> {\n if (this.#lastRunId === undefined) return null\n const response = await this.#fetch(`${this.#api}/runs/${this.#lastRunId}/stream`, {\n method: 'GET',\n headers: { ...this.#resolveHeaders(), ...toRecord(options.headers) },\n })\n if (response.status === 404) return null\n if (!response.ok) {\n throw new Error(\n `Agent reconnect to run ${this.#lastRunId} failed: ${response.status} ${response.statusText}`,\n )\n }\n return responseToChunkStream(response)\n }\n\n async approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n const response = await this.#fetch(`${this.#api}/approve/${approvalId}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'X-Theo-Action': '1',\n ...this.#resolveHeaders(),\n },\n body: JSON.stringify(decision),\n })\n if (!response.ok) {\n throw new Error(`Approve ${approvalId} failed: ${response.status} ${response.statusText}`)\n }\n }\n}\n","import type { UIMessage } from 'ai'\n\n/**\n * M41/M42 — extract the turn text from the last user message's text parts. Shared by the transports\n * that hand a plain `message` string to an in-process/push runner (`InProcessTransport`,\n * `ChannelTransport`) rather than POSTing the `messages[]` array (`HttpTransport`). One definition (G12).\n */\nexport function extractLastUserText(messages: readonly UIMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]\n if (message.role !== 'user') continue\n const text = message.parts\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map((part) => part.text)\n .join('')\n if (text.length > 0) return text\n }\n return ''\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { extractLastUserText } from './last-user-text.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** An inline approval request handed to the transport's resolver (structural — no server import). */\nexport interface InProcessApprovalRequestLike {\n approvalId: string\n toolName: string\n opts: unknown\n}\n\n/** Resolve one gated-tool approval inline (mirrors the SDK's `boolean | HitlDecision` return). */\nexport type InProcessAwaitApproval = (\n req: InProcessApprovalRequestLike,\n) => Promise<boolean | ApprovalDecision>\n\n/** The input the injected runner receives (structurally compatible with `StreamAgentTurnInProcessInput`). */\nexport interface InProcessRunInput {\n message: string\n sessionId?: string\n signal?: AbortSignal\n awaitApproval?: InProcessAwaitApproval\n /** M43 — per-request context (from `sendMessages`'s `metadata`) — tenant / provider / auth for the runner. */\n context?: unknown\n}\n\n/**\n * The in-process turn runner. The consumer binds `streamAgentTurnInProcess(mod, apiKey, …)`:\n * `new InProcessTransport({ run: (input) => streamAgentTurnInProcess(mod, apiKey, input) })`.\n * Injecting it keeps this client module decoupled from `server/` and makes the transport testable.\n */\nexport type InProcessRunner = (input: InProcessRunInput) => AsyncGenerator<UIMessageChunk>\n\nexport interface InProcessTransportOptions {\n run: InProcessRunner\n}\n\n/** Bridge an `AsyncGenerator<UIMessageChunk>` into a pull-based `ReadableStream<UIMessageChunk>`. */\nfunction generatorToStream(gen: AsyncGenerator<UIMessageChunk>): ReadableStream<UIMessageChunk> {\n return new ReadableStream<UIMessageChunk>({\n async pull(controller) {\n try {\n const result = await gen.next()\n if (result.done === true) {\n controller.close()\n return\n }\n // After the done-guard, `result` is an IteratorYieldResult<UIMessageChunk> — value is typed.\n controller.enqueue(result.value)\n } catch (err) {\n controller.error(err)\n }\n },\n async cancel() {\n await gen.return(undefined)\n },\n })\n}\n\n/**\n * M41 (ADR-0050 D4) — `ChatTransport` over the in-process seam (`streamAgentTurnInProcess`), for the\n * terminal/desktop surfaces that run client + server in ONE process (no HTTP loopback).\n *\n * - `sendMessages`: bridge the injected runner's `AsyncGenerator<UIMessageChunk>` into a\n * `ReadableStream<UIMessageChunk>` (honoring `abortSignal`, which the runner forwards to the SDK).\n * - `reconnectToStream`: always `null` — a single process has no dropped server-side stream to resume\n * (mirrors `ai`'s `DirectChatTransport`).\n * - `approve`: resolve the pending inline approval by id (the run parks on `awaitApproval`). An unknown\n * id rejects (fail-fast, Rule 8 — never a silent resolve).\n *\n * Error asymmetry vs `HttpTransport` (by design, matching the `ChatTransport` contract): a runner that\n * throws SYNCHRONOUSLY surfaces the error when the stream is READ (via `controller.error`), not from the\n * `sendMessages` promise — whereas `HttpTransport` throws from `sendMessages` on a non-2xx response.\n */\n/**\n * Uma aprovação estacionada foi descartada porque o turno terminou sem decisão.\n *\n * M92 — tipado de propósito. Antes a promessa simplesmente **nunca** resolvia, e a chamada de tool do\n * SDK pendurava; `resolve(false)` seria pior ainda, porque é indistinguível de \"o usuário negou\".\n */\nexport class ApprovalAbortedError extends Error {\n constructor(\n readonly approvalId: string,\n motivo: string,\n ) {\n super(`Aprovação '${approvalId}' descartada: ${motivo}.`)\n this.name = 'ApprovalAbortedError'\n }\n}\n\nexport class InProcessTransport implements AgentTransport {\n readonly #run: InProcessRunner\n /**\n * Aprovações inline estacionadas: `approvalId` → como resolver **ou rejeitar** a promessa parada.\n *\n * M92 — o `reject` entrou junto com a eviction. Antes havia só o `resolve`, e nada apagava a entrada\n * quando o turno abortava: a promessa ficava pendente **para sempre**, e a chamada de tool do SDK\n * pendurava com ela. Uma promessa que nunca resolve **nem** rejeita é a forma mais silenciosa de\n * engolir um erro — nem stack trace existe (`error-handling.md § 2`).\n */\n readonly #pending = new Map<\n string,\n {\n resolve: (decision: boolean | ApprovalDecision) => void\n reject: (err: Error) => void\n turno: number\n }\n >()\n\n /** O turno corrente. Um `send()` novo incrementa e varre o anterior. */\n #turno = 0\n\n constructor(options: InProcessTransportOptions) {\n this.#run = options.run\n }\n\n /**\n * Cria o `awaitApproval` DESTE turno, com o número e o sinal fechados no closure.\n *\n * Campo compartilhado não serve, e a revisão do M92 mediu por quê: um runner do turno 1 que\n * estaciona **depois** do `send` do turno 2 lê o campo já sobrescrito e nasce etiquetado turno 2 —\n * o abort do turno 1 não o varre, e a promessa pendura. A primeira correção do M92 trocou \"ler no\n * momento da aprovação\" por \"ler no `send`\", e continuou errada pela mesma razão: um campo só.\n *\n * O closure é o único lugar onde o turno de um runner pode viver sem ser sobrescrito por outro.\n */\n #criarAwaitApproval(turno: number, sinal: AbortSignal | undefined): InProcessAwaitApproval {\n return (req) =>\n new Promise<boolean | ApprovalDecision>((resolve, reject) => {\n // Abortado ANTES de a aprovação estacionar: varrer no `sendMessages` não alcança este caso,\n // porque naquele momento não havia nada a varrer.\n if (sinal?.aborted === true) {\n reject(new ApprovalAbortedError(req.approvalId, 'o turno já estava abortado'))\n return\n }\n // Ids de aprovação são UUIDs do servidor — colisão é bug real (dois turnos reusando um id).\n // Falha rápido em vez de sobrescrever em silêncio o resolver estacionado do turno anterior.\n if (this.#pending.has(req.approvalId)) {\n reject(new Error(`Duplicate pending approval id '${req.approvalId}' — ids must be unique.`))\n return\n }\n this.#pending.set(req.approvalId, { resolve, reject, turno })\n })\n }\n\n /**\n * Varre as aprovações de um turno, rejeitando cada uma com erro TIPADO.\n *\n * Rejeitar e não `resolve(false)`: um `false` é indistinguível de *\"o usuário negou\"*, e a diferença\n * importa — negar é decisão, abortar é interrupção. O SDK precisa das duas para desenrolar a chamada\n * de tool corretamente.\n */\n #varrerTurno(turno: number, motivo: string): void {\n for (const [id, entrada] of [...this.#pending]) {\n if (entrada.turno !== turno) continue\n this.#pending.delete(id)\n entrada.reject(new ApprovalAbortedError(id, motivo))\n }\n }\n\n /** Quantas aprovações estão estacionadas. Existe para o teste poder provar a eviction. */\n get pendentes(): number {\n return this.#pending.size\n }\n\n sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, metadata } = options\n // M92 — um `send()` novo varre o turno anterior: aprovações daquele turno nunca mais serão\n // decididas, e deixá-las no `Map` é vazamento com uma promessa pendurada em cada uma.\n this.#varrerTurno(this.#turno, 'um turno novo começou')\n this.#turno += 1\n const turnoAtual = this.#turno\n\n // O sinal de abort do turno é a costura que já chegava aqui e não era usada. `once` porque um\n // `AbortSignal` dispara no máximo uma vez, e reter o listener manteria o transporte vivo.\n // Sinal JÁ abortado não dispara `addEventListener` — a revisão do M92 mediu: `pendentes=1` e a\n // promessa PENDENTE, ou seja, exatamente o travamento que este milestone existe para fechar,\n // ainda alcançável. A varredura roda na hora e o listener cobre o abort que vier depois.\n if (abortSignal?.aborted === true) {\n this.#varrerTurno(turnoAtual, 'o turno já estava abortado')\n } else {\n abortSignal?.addEventListener(\n 'abort',\n () => {\n this.#varrerTurno(turnoAtual, 'o turno foi abortado')\n },\n { once: true },\n )\n }\n const generator = this.#run({\n message: extractLastUserText(messages),\n signal: abortSignal ?? undefined,\n awaitApproval: this.#criarAwaitApproval(turnoAtual, abortSignal ?? undefined),\n // M43 — forward per-request context (the seam's `metadata`) to the runner.\n context: metadata,\n })\n return Promise.resolve(generatorToStream(generator))\n }\n\n reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {\n return Promise.resolve(null)\n }\n\n approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n const entrada = this.#pending.get(approvalId)\n if (entrada === undefined) {\n return Promise.reject(\n new Error(`No pending approval '${approvalId}' (unknown or already settled).`),\n )\n }\n this.#pending.delete(approvalId)\n entrada.resolve(decision)\n return Promise.resolve()\n }\n}\n","import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'\n\nimport { extractLastUserText } from './last-user-text.js'\nimport type { AgentTransport, ApprovalDecision } from './transport.js'\n\n/** Handlers the transport hands to the injected push source for one turn. */\nexport interface ChannelTurnHandlers {\n /** One pushed JSONL line (a serialized `UIMessageChunk`). */\n onLine: (line: string) => void\n /** The turn ended — no more lines. */\n onClose: () => void\n /** The push source failed. */\n onError?: (err: unknown) => void\n}\n\n/**\n * The injected push source — a Tauri `Channel`/`invoke` bridge, kept STRUCTURAL so core adds no\n * `@tauri-apps/*` dependency and the transport is testable with a fake (ADR-0051 D2). The Tauri app\n * wires it: `new Channel()`, `channel.onmessage = onLine`, `invoke('run_agent', { message, channel })`,\n * returning a teardown that aborts the sidecar turn.\n */\nexport interface ChannelPushSource {\n /**\n * Start a turn; deliver each JSONL `UIMessageChunk` line to `onLine`, then `onClose`. Return a teardown.\n * `turn.context` (M43) is the per-request context (from the seam's `metadata`) — the Tauri `invoke`\n * forwards it to the sidecar. When no context is set it is present as `context: undefined` (the key is\n * NOT absent) — a sidecar that checks `'context' in turn` should treat `undefined` as \"no context\".\n */\n start(turn: { message: string; context?: unknown }, handlers: ChannelTurnHandlers): () => void\n /** Optional HITL settle (another Tauri `invoke`). */\n settle?(approvalId: string, decision: ApprovalDecision): Promise<void>\n}\n\nexport interface ChannelTransportOptions {\n source: ChannelPushSource\n}\n\n/**\n * M42 (ADR-0051) — `ChatTransport` over a Tauri-`Channel`-shaped push source, for the desktop webview.\n *\n * - `sendMessages`: start the turn via the injected source and bridge its pushed JSONL frames into a\n * `ReadableStream<UIMessageChunk>` (built in `start` — a Channel is push, so the stream's queue buffers\n * frames; ADR-0051 D3). A malformed JSONL line is SKIPPED, never fatal (ADR-0051 D4, Rule 8). `abortSignal`\n * tears down the source and closes the stream.\n * - `reconnectToStream`: always `null` — the M36 sidecar runs the turn directly (no durable server stream);\n * this is the honest parity for a single-process push surface (ADR-0051 D5; mirrors `InProcessTransport`).\n * - `approve`: routes to the injected `settle` (another Tauri `invoke`); absent `settle` → a typed error.\n *\n * The push source is INJECTED — core stays Tauri-agnostic and this transport is unit-tested with a fake.\n */\nexport class ChannelTransport implements AgentTransport {\n readonly #source: ChannelPushSource\n\n constructor(options: ChannelTransportOptions) {\n this.#source = options.source\n }\n\n sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, metadata } = options\n const message = extractLastUserText(messages)\n const source = this.#source\n\n // Per-stream teardown/abort-detach, hoisted so `cancel` (consumer stops reading) can also tear the\n // source down. `closed` makes every terminal transition idempotent (no enqueue/close after close).\n let closed = false\n let teardown: () => void = () => undefined\n let detachAbort: () => void = () => undefined\n\n const stream = new ReadableStream<UIMessageChunk>({\n start(controller) {\n const finish = (settle: () => void): void => {\n if (closed) return\n closed = true\n detachAbort()\n settle()\n }\n teardown = source.start(\n { message, context: metadata },\n {\n onLine: (line) => {\n if (closed) return\n // Skip a malformed pushed line — one bad frame must never crash the webview (ADR-0051 D4).\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch {\n return\n }\n // Discriminant guard: a `UIMessageChunk` is an object with a string `type`. The trust\n // boundary here is the LOCAL sidecar (not the network), so a discriminant check — not the\n // full `ai` schema (which isn't exposed standalone) — is proportionate: it rejects\n // structureless / wrong-shape payloads before they reach `readUIMessageStream`. Same\n // skip-not-crash policy as a parse error.\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as { type?: unknown }).type !== 'string'\n ) {\n return\n }\n controller.enqueue(parsed as UIMessageChunk)\n },\n onClose: () => {\n finish(() => {\n controller.close()\n })\n },\n onError: (err) => {\n finish(() => {\n controller.error(err)\n })\n },\n },\n )\n if (abortSignal !== undefined) {\n const onAbort = (): void => {\n finish(() => {\n teardown()\n controller.close()\n })\n }\n if (abortSignal.aborted) onAbort()\n else {\n abortSignal.addEventListener('abort', onAbort)\n detachAbort = () => {\n abortSignal.removeEventListener('abort', onAbort)\n }\n }\n }\n },\n cancel() {\n // The consumer stopped reading (reader.cancel) — abort the source turn + drop the abort listener.\n if (closed) return\n closed = true\n detachAbort()\n teardown()\n },\n })\n return Promise.resolve(stream)\n }\n\n reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {\n return Promise.resolve(null)\n }\n\n async approve(approvalId: string, decision: ApprovalDecision): Promise<void> {\n if (this.#source.settle === undefined) {\n throw new Error(`This channel source has no HITL settle — cannot approve '${approvalId}'.`)\n }\n await this.#source.settle(approvalId, decision)\n }\n}\n","import type { UIMessage, UIMessageChunk } from 'ai'\n\nimport { consumeChunkStream } from './consume-ui-message-stream.js'\nimport type { AgentTransport, ApprovalDecision, RequestContext } from './transport.js'\n\nexport type UseAgentStatus = 'idle' | 'streaming' | 'done' | 'error'\n\n/** The observable state the store exposes (stable reference between emits — `useSyncExternalStore` contract). */\nexport interface AgentClientState {\n /** The CURRENT turn's assistant messages (per-turn; reset each `send`). Back-compat — unchanged since M41. */\n messages: UIMessage[]\n /**\n * M46 — the full conversation: committed turns + the current turn's user message + in-flight assistant.\n * Accumulated across sends (never reset except by `reset()`), with stable ids committed exactly once.\n * Render this instead of hand-rolling a transcript from `messages`.\n */\n thread: UIMessage[]\n status: UseAgentStatus\n error: Error | undefined\n}\n\n/** Derive the turn text from a typed input: `input.message` when present, else the serialized input. */\nfunction inputToText(input: unknown): string {\n if (\n typeof input === 'object' &&\n input !== null &&\n typeof (input as { message?: unknown }).message === 'string'\n ) {\n return (input as { message: string }).message\n }\n if (typeof input === 'string') return input\n return JSON.stringify(input)\n}\n\n/** Build a user `UIMessage` from a typed input (text from `{ message }`, else the serialized input). */\nfunction buildUserMessage(input: unknown): UIMessage {\n return {\n id: crypto.randomUUID(),\n role: 'user',\n parts: [{ type: 'text', text: inputToText(input) }],\n }\n}\n\n/**\n * M41 (ADR-0050 D6) — the framework-agnostic agent client store.\n *\n * Holds `messages`/`status`/`error`, drives an {@link AgentTransport}, and notifies subscribers on\n * change. It is the SINGLE consolidation point: web (`HttpTransport`) and terminal/desktop\n * (`InProcessTransport`) run the SAME store. `useAgent` is a thin React binding over it via\n * `useSyncExternalStore`; a standalone (no-React) client (M44) can subscribe directly. Being\n * framework-agnostic, it is unit-tested without a DOM.\n */\n/**\n * M92 — opções do cliente. Aditivo: sem elas, o comportamento é o de sempre.\n */\nexport interface AgentClientOptions {\n /**\n * Janela de coalescing em ms. `0` ou ausente = emite por delta de token (comportamento pré-M92).\n *\n * Opt-in de propósito: este é um pacote publicado, e mudar a frequência de emit por padrão mudaria o\n * comportamento observável de quem conta emits ou depende da latência do primeiro token.\n */\n readonly emitIntervalMs?: number\n}\n\nexport class AgentClient<TInput = unknown> {\n readonly #transport: AgentTransport\n readonly #chatId = crypto.randomUUID()\n readonly #listeners = new Set<() => void>()\n /** M43 — resolves per-request context (evaluated on every send/reconnect — dynamic, never stale). */\n readonly #contextResolver: (() => RequestContext | undefined) | undefined\n\n #messages: UIMessage[] = []\n #status: UseAgentStatus = 'idle'\n #error: Error | undefined\n #controller: AbortController | null = null\n // M46 — conversation accumulation (React-free; all surfaces inherit it via the snapshot).\n /** Committed (finished) turns — user + assistant, with stable fabricated ids. */\n #committed: UIMessage[] = []\n /** The current turn's user message (in `thread` but never in `messages` — back-compat). */\n #currentUser: UIMessage | undefined\n /** A stable id for the current turn's assistant (the SDK leaves it empty — we fabricate one). */\n #currentAssistantId = ''\n #snapshot: AgentClientState = { messages: [], thread: [], status: 'idle', error: undefined }\n\n /**\n * M92 — o prefixo commitado, materializado UMA vez por escrita em vez de por delta de token.\n *\n * `#committed` só muda em dois lugares (medido): no `done` de `send()` e em `reset()`. Entre deltas\n * ele é constante, então reconstruí-lo a cada `#emit` é trabalho que a estrutura já garante inútil.\n *\n * Invalidação é **na escrita**, não por comparação: comparar custaria o mesmo O(C) que isto evita, e\n * memoizar por comprimento erraria em `reset()` — comprimento igual com conteúdo diferente é\n * possível, e o bug seria invisível.\n *\n * Honestidade sobre o tamanho do ganho: medido, o spread custa **0,0062 ms por delta @400 mensagens**\n * — 3,1 ms num turno de 500 deltas. É real e é micro. A ordem de grandeza deste milestone está no\n * coalescing abaixo, porque o que pende de cada emit (a derivação da timeline) custa **3,274 ms por\n * chamada** no mesmo tamanho de thread (M86).\n */\n #prefixo: UIMessage[] = []\n\n /** Coalescing opt-in: `0` (default) emite por delta, como sempre. */\n readonly #emitIntervalMs: number\n #timerDeEmit: ReturnType<typeof setTimeout> | undefined\n\n constructor(\n transport: AgentTransport,\n contextResolver?: () => RequestContext | undefined,\n options?: AgentClientOptions,\n ) {\n this.#transport = transport\n this.#contextResolver = contextResolver\n this.#emitIntervalMs = options?.emitIntervalMs ?? 0\n }\n\n /** Subscribe to state changes; returns an unsubscribe fn. */\n subscribe = (listener: () => void): (() => void) => {\n this.#listeners.add(listener)\n return () => {\n this.#listeners.delete(listener)\n }\n }\n\n /** The current immutable snapshot (stable reference until the next emit). */\n getSnapshot = (): AgentClientState => this.#snapshot\n\n /**\n * Emite AGORA. Usado diretamente nas transições de status — ver `#agendarEmit`.\n */\n #emit(): void {\n if (this.#timerDeEmit !== undefined) {\n clearTimeout(this.#timerDeEmit)\n this.#timerDeEmit = undefined\n }\n // thread = prefixo commitado + o user deste turno + o assistant em voo (`messages`). O prefixo vem\n // materializado (`#prefixo`); só a cauda é concatenada aqui. A referência do SNAPSHOT muda só neste\n // ponto, que é o contrato que `useSyncExternalStore` exige.\n // `concat` ÚNICO, não dois spreads.\n //\n // A primeira versão do M92 trocou `#committed` por `#prefixo` e manteve o spread — e `#prefixo` era\n // o **mesmo array**, um alias puro. A revisão mediu: 0,16 µs @C=20 → ~2 µs @C=400, ainda linear em\n // C, ou seja, byte-idêntico ao anterior. O DoD pedia getter preguiçoso ou concat único; eu tinha\n // entregue um rename.\n //\n // `concat` copia o prefixo uma vez por emit em vez de espalhá-lo elemento a elemento, e o motor\n // usa memcpy para arrays densos. Continua O(C) — não há como devolver um array novo sem copiar —\n // mas com constante menor, e é honesto dizer que o ganho aqui é de constante, não de ordem.\n const cauda = this.#currentUser ? [this.#currentUser, ...this.#messages] : this.#messages\n const thread = this.#prefixo.concat(cauda)\n this.#snapshot = { messages: this.#messages, thread, status: this.#status, error: this.#error }\n for (const listener of this.#listeners) listener()\n }\n\n /**\n * Emite por JANELA quando o coalescing está ligado; imediatamente quando não está.\n *\n * Borda de saída: o timer emite ao **fim** da janela, com o estado mais recente. O que isto compra\n * não é um emit mais barato — é **menos emits**, e o que pende de cada um é a derivação de 3,274 ms\n * medida no M86.\n *\n * As transições de status (`done`/`error`/`abort`) NÃO passam por aqui: elas chamam `#emit` direto,\n * porque um estado final preso num timer de 16 ms é um estado final perdido se o processo sair antes\n * — e `exec` sai logo após o turno.\n */\n #agendarEmit(): void {\n if (this.#emitIntervalMs <= 0) {\n this.#emit()\n return\n }\n if (this.#timerDeEmit !== undefined) return\n this.#timerDeEmit = setTimeout(() => {\n this.#timerDeEmit = undefined\n this.#emit()\n }, this.#emitIntervalMs)\n }\n\n #upsert(message: UIMessage): void {\n const next = [...this.#messages]\n const idx = next.findIndex((existing) => existing.id === message.id)\n if (idx >= 0) next[idx] = message\n else next.push(message)\n this.#messages = next\n }\n\n async #drive(\n open: () => Promise<ReadableStream<UIMessageChunk> | null>,\n controller: AbortController,\n ): Promise<void> {\n // Read via a function (not a narrowed local) — `aborted` flips ASYNC across the awaits below, so the\n // control-flow narrowing of a direct `signal.aborted` read would be wrong. A stale drive (its\n // controller aborted because a newer send/abort took over) MUST NOT clobber the newer status.\n const aborted = (): boolean => controller.signal.aborted\n try {\n const stream = await open()\n if (aborted()) return\n if (stream === null) {\n // Nothing to resume (e.g. reconnect after the run completed). Settle without error.\n this.#status = this.#messages.length > 0 ? 'done' : 'idle'\n this.#emit()\n return\n }\n await consumeChunkStream(stream, (message) => {\n if (aborted()) return\n // The SDK leaves the assistant message id empty — fabricate a stable per-turn id so every chunk\n // upserts into the SAME message and the committed copy has a collision-free key (M46).\n const stamped = message.id ? message : { ...message, id: this.#currentAssistantId }\n this.#upsert(stamped)\n // O ÚNICO ponto por delta de token — todos os outros `#emit` deste arquivo são transições de\n // status, e essas nunca esperam timer (ADR-2).\n this.#agendarEmit()\n })\n if (aborted()) return\n this.#status = 'done'\n this.#emit()\n } catch (err) {\n if (aborted()) return\n this.#error = err instanceof Error ? err : new Error(String(err))\n this.#status = 'error'\n this.#emit()\n }\n }\n\n /** Send a typed input; opens a fresh stream (replaces prior messages). */\n send = (input: TInput): void => {\n // M46 — commit the PRIOR turn into history exactly once, but ONLY if it finished cleanly (`done`).\n // An errored or aborted turn (status !== 'done') is dropped, keeping committed history uncorrupted.\n if (this.#status === 'done' && this.#currentUser) {\n this.#committed = [...this.#committed, this.#currentUser, ...this.#messages]\n // Invalidação NA ESCRITA (ADR-3): este é um dos dois únicos pontos que mexem em `#committed`.\n this.#prefixo = this.#committed\n }\n this.abort()\n const controller = new AbortController()\n this.#controller = controller\n const userMsg = buildUserMessage(input)\n this.#currentUser = userMsg\n this.#currentAssistantId = crypto.randomUUID()\n this.#messages = []\n this.#error = undefined\n this.#status = 'streaming'\n this.#emit()\n const context = this.#contextResolver?.()\n void this.#drive(\n () =>\n this.#transport.sendMessages({\n trigger: 'submit-message',\n chatId: this.#chatId,\n messageId: undefined,\n messages: [userMsg],\n abortSignal: controller.signal,\n // Only object inputs flow as the request `body` (the turn text is always in `messages`);\n // a primitive input is carried by the user message, never spread into the body.\n body: typeof input === 'object' && input !== null ? input : undefined,\n // M43 — per-request context reaches every transport (headers → HTTP, metadata → in-process/channel).\n headers: context?.headers,\n metadata: context?.metadata,\n }),\n controller,\n )\n }\n\n /** Resume an interrupted stream via the transport's `reconnectToStream` (no-op when unavailable). */\n reconnect = (): void => {\n const controller = new AbortController()\n this.#controller = controller\n // Reconnecting before any send() (or after reset()) leaves #currentAssistantId empty — fabricate one\n // so a replayed assistant never lands in `thread` with an empty, non-unique id (M46 invariant).\n if (!this.#currentAssistantId) this.#currentAssistantId = crypto.randomUUID()\n // Reconnect means \"resume/retry\" — a stale error must not linger next to a fresh 'streaming' status.\n this.#error = undefined\n this.#status = 'streaming'\n this.#emit()\n const context = this.#contextResolver?.()\n void this.#drive(\n () =>\n this.#transport.reconnectToStream({\n chatId: this.#chatId,\n headers: context?.headers,\n metadata: context?.metadata,\n }),\n controller,\n )\n }\n\n /** Abort an in-flight stream (not an error — leaves messages as-is). */\n abort = (): void => {\n this.#controller?.abort()\n this.#controller = null\n // Finalize the status when the USER aborts an in-flight turn: the aborted `#drive` early-returns\n // without touching status (so a stale drive can't clobber a newer turn), which would otherwise leave\n // `status` stuck on 'streaming' — a lingering spinner + an unusable surface. A caller that aborts to\n // start a NEW turn (`send`/`sendMessages`) sets 'streaming' again immediately after, so this is safe.\n if (this.#status === 'streaming') {\n this.#status = this.#committed.length > 0 || this.#messages.length > 0 ? 'done' : 'idle'\n this.#emit()\n }\n }\n\n /** Clear messages + error, back to idle. */\n reset = (): void => {\n this.abort()\n this.#messages = []\n // M46 — reset means a NEW conversation: clear committed history + the current turn's user too.\n this.#committed = []\n // O outro ponto de escrita. Sem isto o `reset()` serviria o prefixo velho — e comprimento igual\n // com conteúdo diferente é exatamente o caso que uma memoização por tamanho não pegaria.\n this.#prefixo = this.#committed\n this.#currentUser = undefined\n this.#error = undefined\n this.#status = 'idle'\n this.#emit()\n }\n\n /** Settle a paused HITL approval via the transport's HITL path (HTTP POST or inline callback). */\n approve = async (approvalId: string, decision: ApprovalDecision): Promise<void> => {\n await this.#transport.approve?.(approvalId, decision)\n }\n}\n","import { ChannelTransport, type ChannelPushSource } from './channel-transport.js'\nimport { InProcessTransport, type InProcessRunner } from './in-process-transport.js'\n\n/**\n * M47 (ADR-M47-2) — a typed, client-safe handle for an exposed agent.\n *\n * It carries ONLY the HTTP `path` at runtime plus phantom `input`/`toolNames` types (never populated) — so\n * `useAgent(chat)` / `createAgentClient(chat…)` bind with NO magic string (the path is generated from the\n * `@Expose` exposure, not hand-typed) and NO duplicated input type (the input type flows through the phantom\n * generic, inferred from the agent's `.input()`). This mirrors tRPC/Hono's type-only handle: the client\n * pulls the agent's TYPE via `import type`, never its server runtime. The generated `@theo/agents` module\n * emits one `export const <name> = agentHandle('/api/agents/<name>')` per agent, typed with the phantoms.\n */\nexport interface AgentHandle<TInput = unknown, TToolNames extends string = string> {\n /** The agent's HTTP endpoint path (e.g. `/api/agents/chat`). The only serializable/runtime-bearing field. */\n readonly path: string\n /**\n * M47 — bind this agent in-process (TUI / single-process): wraps the app's runner in an\n * {@link InProcessTransport}. `useAgent(chat.inProcess(run))` drives the SAME agent without HTTP.\n */\n inProcess(run: InProcessRunner): InProcessTransport\n /**\n * M47 — bind this agent over a push channel (Tauri desktop webview): wraps the source in a\n * {@link ChannelTransport}. `createAgentClient(chat.channel(source))` drives the SAME agent.\n */\n channel(source: ChannelPushSource): ChannelTransport\n /** Phantom — the agent's `input` type, carried for `useAgent(handle).send` inference. Never populated. */\n readonly __input?: TInput\n /** Phantom — the agent's tool-name union, carried end-to-end. Never populated. */\n readonly __toolNames?: TToolNames\n}\n\n/**\n * Build an {@link AgentHandle} from an agent's HTTP path. Types are supplied by the caller/codegen. The\n * `inProcess`/`channel` binders are methods (dropped by `JSON.stringify`, so the `{ path }` core stays\n * serializable + client-safe) that produce the M41 transports for the non-web surfaces.\n */\nexport function agentHandle<TInput = unknown, TToolNames extends string = string>(\n path: string,\n): AgentHandle<TInput, TToolNames> {\n return {\n path,\n inProcess: (run) => new InProcessTransport({ run }),\n channel: (source) => new ChannelTransport({ source }),\n }\n}\n\n/** Narrow an unknown binding to an {@link AgentHandle} (has a string `path`, is not a transport). */\nexport function isAgentHandle(value: unknown): value is AgentHandle {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { path?: unknown }).path === 'string' &&\n typeof (value as { sendMessages?: unknown }).sendMessages !== 'function'\n )\n}\n"],"mappings":";;;;;AAgBA,eAAsBA,uBACpBC,UACAC,WAAuC;AAEvC,QAAMC,cAAc,MAAMC,sBAAsBH,QAAAA;AAChD,QAAMI,mBAAmBF,aAAaD,SAAAA;AACxC;AANsBF;AActB,eAAsBI,sBACpBH,UAAkB;AAElB,MAAIA,SAASK,SAAS,MAAM;AAC1B,WAAO,IAAIC,eAA+B;MACxCC,MAAMC,YAAU;AACdA,mBAAWC,MAAK;MAClB;IACF,CAAA;EACF;AAEA,QAAM,EAAEC,sBAAsBC,qBAAoB,IAAK,MAAM,OAAO,IAAA;AAIpE,QAAMC,SAASF,qBAAqB;IAAEG,QAAQb,SAASK;IAAMS,QAAQH;EAAqB,CAAA;AAC1F,SAAO,IAAIL,eAA+B;IACxC,MAAMC,MAAMC,YAAU;AACpB,uBAAiBO,UAAUH,QAAQ;AACjC,YAAIG,OAAOC,QAASR,YAAWS,QAAQF,OAAOG,KAAK;MACrD;AACAV,iBAAWC,MAAK;IAClB;EACF,CAAA;AACF;AAxBsBN;AAgCtB,eAAsBC,mBACpBS,QACAZ,WAAuC;AAEvC,QAAM,EAAEkB,oBAAmB,IAAK,MAAM,OAAO,IAAA;A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IMessageStream","response","onMessage","chunkStream","responseToChunkStream","consumeChunkStream","body","ReadableStream","start","controller","close","parseJsonEventStream","uiMessageChunkSchema","parsed","stream","schema","result","success","enqueue","value","readUIMessageStream","streamError","message","onError","err","Error","String","terminateOnError","undefined","toRecord","headers","undefined","Headers","Object","fromEntries","entries","HttpTransport","options","api","fetch","globalThis","bind","sendMessages","messages","abortSignal","body","chatId","extra","response","method","accept","JSON","stringify","id","signal","ok","Error","status","statusText","get","responseToChunkStream","reconnectToStream","approve","approvalId","decision","extractLastUserText","messages","i","length","message","role","text","parts","filter","part","type","map","join","generatorToStream","gen","ReadableStream","pull","controller","result","next","done","close","enqueue","value","err","error","cancel","return","undefined","ApprovalAbortedError","Error","approvalId","motivo","name","InProcessTransport","Map","options","run","turno","sinal","req","Promise","resolve","reject","aborted","has","set","id","entrada","delete","pendentes","size","sendMessages","messages","abortSignal","metadata","turnoAtual","addEventListener","once","generator","message","extractLastUserText","signal","awaitApproval","context","reconnectToStream","approve","decision","get","ChannelTransport","options","source","sendMessages","messages","abortSignal","metadata","message","extractLastUserText","closed","teardown","undefined","detachAbort","stream","ReadableStream","start","controller","finish","settle","context","onLine","line","parsed","JSON","parse","type","enqueue","onClose","close","onError","err","error","onAbort","aborted","addEventListener","removeEventListener","cancel","Promise","resolve","reconnectToStream","approve","approvalId","decision","Error","inputToText","input","message","JSON","stringify","buildUserMessage","id","crypto","randomUUID","role","parts","type","text","AgentClient","Set","messages","thread","status","error","undefined","transport","contextResolver","options","emitIntervalMs","subscribe","listener","add","delete","getSnapshot","clearTimeout","cauda","concat","setTimeout","next","idx","findIndex","existing","push","open","controller","aborted","signal","stream","length","consumeChunkStream","stamped","err","Error","String","send","abort","AbortController","userMsg","context","sendMessages","trigger","chatId","messageId","abortSignal","body","headers","metadata","reconnect","reconnectToStream","reset","approve","approvalId","decision","agentHandle","path","inProcess","run","InProcessTransport","channel","source","ChannelTransport","isAgentHandle","value","sendMessages"]}