theokit 0.43.1 → 0.43.2

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.
@@ -24,9 +24,17 @@ async function responseToChunkStream(response) {
24
24
  }
25
25
  async function consumeChunkStream(stream, onMessage) {
26
26
  const { readUIMessageStream } = await import("ai");
27
- for await (const message of readUIMessageStream({ stream })) {
27
+ let streamError;
28
+ for await (const message of readUIMessageStream({
29
+ stream,
30
+ onError: (err) => {
31
+ streamError = err instanceof Error ? err : new Error(String(err));
32
+ },
33
+ terminateOnError: true
34
+ })) {
28
35
  onMessage(message);
29
36
  }
37
+ if (streamError !== void 0) throw streamError;
30
38
  }
31
39
 
32
40
  // src/client/agent-client.ts
@@ -490,4 +498,4 @@ export {
490
498
  HttpTransport,
491
499
  createAgentClient
492
500
  };
493
- //# sourceMappingURL=chunk-XZ4QD5IN.js.map
501
+ //# sourceMappingURL=chunk-ALMCG4EL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/consume-ui-message-stream.ts","../src/client/agent-client.ts","../src/client/last-user-text.ts","../src/client/channel-transport.ts","../src/client/in-process-transport.ts","../src/client/http-transport.ts","../src/client/create-agent-client.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 { 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 */\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 constructor(transport: AgentTransport, contextResolver?: () => RequestContext | undefined) {\n this.#transport = transport\n this.#contextResolver = contextResolver\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 #emit(): void {\n // thread = committed turns + this turn's user + the in-flight assistant (`messages`). New array per\n // emit is fine — the SNAPSHOT reference only changes here, satisfying useSyncExternalStore.\n const thread = this.#currentUser\n ? [...this.#committed, this.#currentUser, ...this.#messages]\n : [...this.#committed, ...this.#messages]\n this.#snapshot = { messages: this.#messages, thread, status: this.#status, error: this.#error }\n for (const listener of this.#listeners) listener()\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 this.#emit()\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 }\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 }\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 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 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/** 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 { 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 */\nexport class InProcessTransport implements AgentTransport {\n readonly #run: InProcessRunner\n /** Pending inline approvals: approvalId → resolver of the parked `awaitApproval` promise. */\n readonly #pending = new Map<string, (decision: boolean | ApprovalDecision) => void>()\n\n constructor(options: InProcessTransportOptions) {\n this.#run = options.run\n }\n\n #awaitApproval: InProcessAwaitApproval = (req) =>\n new Promise<boolean | ApprovalDecision>((resolve, reject) => {\n // Approval ids are server-minted UUIDs — a collision means a real bug (two turns reusing an id).\n // Fail fast rather than silently overwrite the earlier turn's parked resolver (Rule 8).\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)\n })\n\n sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, metadata } = options\n const generator = this.#run({\n message: extractLastUserText(messages),\n signal: abortSignal ?? undefined,\n awaitApproval: this.#awaitApproval,\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 resolve = this.#pending.get(approvalId)\n if (resolve === undefined) {\n return Promise.reject(\n new Error(`No pending approval '${approvalId}' (unknown or already settled).`),\n )\n }\n this.#pending.delete(approvalId)\n resolve(decision)\n return Promise.resolve()\n }\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\nimport { AgentClient, type AgentClientState } from './agent-client.js'\nimport type { AgentTransport, ApprovalDecision, RequestContext } from './transport.js'\n\nexport interface CreateAgentClientOptions {\n /**\n * M43 — per-request context attached to every turn (`headers` → HTTP; `metadata` → in-process/channel).\n * A value OR a resolver. **To keep context live across sends, pass a RESOLVER** (`() => ({...})`) — a\n * plain value is captured at construction and not re-read, so mutating `options.context` afterwards has\n * no effect (unlike `useAgent`, which reads a live ref). A resolver is re-evaluated every send/reconnect.\n */\n context?: RequestContext | (() => RequestContext | undefined)\n}\n\n/**\n * M44 (ADR-0053) — the standalone (no-React) agent client. A plain handle over the framework-agnostic\n * {@link AgentClient} store: drive a turn, observe state, settle HITL — from a node script, a CLI, a\n * test, or a non-React UI, over ANY {@link AgentTransport}.\n */\nexport interface AgentClientHandle<TInput = unknown> {\n /** Send a typed input; opens a fresh stream (replaces prior messages). */\n send(input: TInput): void\n /** Abort an in-flight stream. */\n abort(): void\n /** Clear messages + error, back to idle. */\n reset(): void\n /** Settle a paused HITL approval via the transport's HITL path. */\n approve(approvalId: string, decision: ApprovalDecision): Promise<void>\n /** Resume an interrupted stream (no-op when the transport can't). */\n reconnect(): void\n /** Subscribe to state changes; returns an unsubscribe fn. */\n subscribe(listener: () => void): () => void\n /**\n * The current immutable snapshot: per-turn `messages` (back-compat) + the full conversation `thread`\n * (M46 — committed history + in-flight, accumulated across sends) + `status` / `error`. A TUI / vanilla\n * consumer renders `thread` directly without hand-rolling a transcript.\n */\n getState(): AgentClientState\n /**\n * Drive one turn and yield the assistant `UIMessage` as it streams (progressive snapshots); iteration\n * ends when the turn settles. A `for await` script takes the last yielded value as the final result;\n * a failed turn rejects the iterator with the run error.\n */\n stream(input: TInput): AsyncIterable<UIMessage>\n}\n\n/** Drive a turn on the store and yield the latest assistant message on each streaming update. */\nfunction streamTurn<TInput>(client: AgentClient<TInput>, input: TInput): AsyncIterable<UIMessage> {\n return {\n async *[Symbol.asyncIterator]() {\n const pending: UIMessage[] = []\n let finished = false\n let streamError: Error | undefined\n let notify: (() => void) | null = null\n // Read via functions — `finished`/`streamError` flip ASYNC in the subscribe callback, so a direct\n // read would be wrongly narrowed to its initial literal by control-flow analysis (M41 pattern).\n const isFinished = (): boolean => finished\n const takeError = (): Error | undefined => streamError\n\n const unsubscribe = client.subscribe(() => {\n const snapshot = client.getSnapshot()\n if (snapshot.status === 'streaming') {\n // Push the growing assistant message ONLY on streaming updates. The terminal ('done'/'error')\n // emit carries the SAME final message already yielded on the last streaming update — pushing it\n // again would yield a duplicate. So the terminal emit only flips `finished` (+ captures error).\n const last = snapshot.messages.at(-1)\n if (last !== undefined) pending.push(last)\n } else {\n if (snapshot.status === 'error') streamError = snapshot.error\n finished = true\n }\n notify?.()\n })\n\n client.send(input)\n try {\n for (;;) {\n while (pending.length > 0) {\n const message = pending.shift()\n if (message !== undefined) yield message\n }\n if (isFinished()) break\n await new Promise<void>((resolve) => {\n notify = resolve\n // Close the lost-wakeup window: an emit may have fired during the drain, BEFORE `notify` was\n // set (its `notify?.()` was then a no-op). If work already arrived, resolve now, don't sleep.\n if (pending.length > 0 || isFinished()) resolve()\n })\n notify = null\n }\n const err = takeError()\n if (err !== undefined) throw err\n } finally {\n // Runs on normal completion AND on early `break` (the for-await calls the generator's return()):\n // stop observing, and abort the turn so an early-exiting consumer doesn't leave it running (abort\n // is a no-op once the turn has settled).\n unsubscribe()\n client.abort()\n }\n },\n }\n}\n\n/**\n * Create a standalone (no-React) agent client over a transport. `useAgent` is the React binding over the\n * same store; this is the equivalent for any JS runtime — one agent, consumable everywhere on the seam.\n */\nexport function createAgentClient<TInput = unknown>(\n transport: AgentTransport,\n options: CreateAgentClientOptions = {},\n): AgentClientHandle<TInput> {\n const { context } = options\n const contextResolver =\n context === undefined\n ? undefined\n : (): RequestContext | undefined => (typeof context === 'function' ? context() : context)\n const client = new AgentClient<TInput>(transport, contextResolver)\n\n return {\n send: client.send,\n abort: client.abort,\n reset: client.reset,\n approve: client.approve,\n reconnect: client.reconnect,\n subscribe: client.subscribe,\n getState: client.getSnapshot,\n stream: (input: TInput) => streamTurn(client, input),\n }\n}\n"],"mappings":";AAgBA,eAAsB,uBACpB,UACA,WACe;AACf,QAAM,cAAc,MAAM,sBAAsB,QAAQ;AACxD,QAAM,mBAAmB,aAAa,SAAS;AACjD;AAQA,eAAsB,sBACpB,UACyC;AACzC,MAAI,SAAS,SAAS,MAAM;AAC1B,WAAO,IAAI,eAA+B;AAAA,MACxC,MAAM,YAAY;AAChB,mBAAW,MAAM;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,EAAE,sBAAsB,qBAAqB,IAAI,MAAM,OAAO,IAAI;AAIxE,QAAM,SAAS,qBAAqB,EAAE,QAAQ,SAAS,MAAM,QAAQ,qBAAqB,CAAC;AAC3F,SAAO,IAAI,eAA+B;AAAA,IACxC,MAAM,MAAM,YAAY;AACtB,uBAAiB,UAAU,QAAQ;AACjC,YAAI,OAAO,QAAS,YAAW,QAAQ,OAAO,KAAK;AAAA,MACrD;AACA,iBAAW,MAAM;AAAA,IACnB;AAAA,EACF,CAAC;AACH;AAQA,eAAsB,mBACpB,QACA,WACe;AACf,QAAM,EAAE,oBAAoB,IAAI,MAAM,OAAO,IAAI;AAUjD,MAAI;AACJ,mBAAiB,WAAW,oBAAoB;AAAA,IAC9C;AAAA,IACA,SAAS,CAAC,QAAQ;AAChB,oBAAc,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAAA,IAClE;AAAA,IACA,kBAAkB;AAAA,EACpB,CAAC,GAAG;AACF,cAAU,OAAO;AAAA,EACnB;AACA,MAAI,gBAAgB,OAAW,OAAM;AACvC;;;ACjEA,SAAS,YAAY,OAAwB;AAC3C,MACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAgC,YAAY,UACpD;AACA,WAAQ,MAA8B;AAAA,EACxC;AACA,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,SAAO,KAAK,UAAU,KAAK;AAC7B;AA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BAAS;AAGT,gBAAI,QAAQ,SAAS,KAAK,WAAW,EAAG,SAAQ;AAAA,UAClD,CAAC;AACD,mBAAS;AAAA,QACX;AACA,cAAM,MAAM,UAAU;AACtB,YAAI,QAAQ,OAAW,OAAM;AAAA,MAC/B,UAAE;AAIA,oBAAY;AACZ,eAAO,MAAM;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACF;AAMO,SAAS,kBACd,WACA,UAAoC,CAAC,GACV;AAC3B,QAAM,EAAE,QAAQ,IAAI;AACpB,QAAM,kBACJ,YAAY,SACR,SACA,MAAmC,OAAO,YAAY,aAAa,QAAQ,IAAI;AACrF,QAAM,SAAS,IAAI,YAAoB,WAAW,eAAe;AAEjE,SAAO;AAAA,IACL,MAAM,OAAO;AAAA,IACb,OAAO,OAAO;AAAA,IACd,OAAO,OAAO;AAAA,IACd,SAAS,OAAO;AAAA,IAChB,WAAW,OAAO;AAAA,IAClB,WAAW,OAAO;AAAA,IAClB,UAAU,OAAO;AAAA,IACjB,QAAQ,CAAC,UAAkB,WAAW,QAAQ,KAAK;AAAA,EACrD;AACF;","names":[]}
@@ -7,7 +7,7 @@ import {
7
7
  consumeUIMessageStream,
8
8
  createAgentClient,
9
9
  responseToChunkStream
10
- } from "../chunk-XZ4QD5IN.js";
10
+ } from "../chunk-ALMCG4EL.js";
11
11
  import "../chunk-DGUM43GV.js";
12
12
  export {
13
13
  AgentClient,
@@ -7,7 +7,7 @@ import {
7
7
  consumeUIMessageStream,
8
8
  createAgentClient,
9
9
  responseToChunkStream
10
- } from "../chunk-XZ4QD5IN.js";
10
+ } from "../chunk-ALMCG4EL.js";
11
11
  import {
12
12
  buildUseTheoQueryConfig,
13
13
  stableQueryKey
package/dist/index.d.ts CHANGED
@@ -53,8 +53,8 @@ declare const theoConfigSchema: z.ZodObject<{
53
53
  unhandledErrors: z.ZodOptional<z.ZodBoolean>;
54
54
  logLevels: z.ZodOptional<z.ZodArray<z.ZodEnum<{
55
55
  error: "error";
56
- info: "info";
57
56
  warn: "warn";
57
+ info: "info";
58
58
  debug: "debug";
59
59
  log: "log";
60
60
  }>>>;
@@ -92,24 +92,24 @@ declare const theoConfigSchema: z.ZodObject<{
92
92
  logging: z.ZodOptional<z.ZodObject<{
93
93
  level: z.ZodDefault<z.ZodEnum<{
94
94
  error: "error";
95
- info: "info";
96
95
  warn: "warn";
96
+ info: "info";
97
97
  debug: "debug";
98
98
  silent: "silent";
99
99
  }>>;
100
100
  }, z.core.$strip>>;
101
101
  security: z.ZodOptional<z.ZodObject<{
102
102
  csrf: z.ZodDefault<z.ZodEnum<{
103
- warn: "warn";
104
103
  off: "off";
104
+ warn: "warn";
105
105
  strict: "strict";
106
106
  }>>;
107
107
  headers: z.ZodOptional<z.ZodObject<{
108
108
  csp: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<false>]>>;
109
109
  cspMode: z.ZodDefault<z.ZodEnum<{
110
+ off: "off";
110
111
  enforce: "enforce";
111
112
  "report-only": "report-only";
112
- off: "off";
113
113
  }>>;
114
114
  hsts: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<false>]>>;
115
115
  frameOptions: z.ZodDefault<z.ZodEnum<{
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "theokit",
3
- "version": "0.43.1",
3
+ "version": "0.43.2",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "license": "Apache-2.0",
@@ -123,12 +123,12 @@
123
123
  "tsx": "^4.22.4",
124
124
  "typescript": "^5.9.3",
125
125
  "vite": "^6.4.3",
126
- "@theokit/http": "^0.7.0",
127
- "@theokit/agents": "^0.43.0"
126
+ "@theokit/agents": "^0.43.0",
127
+ "@theokit/http": "^0.7.0"
128
128
  },
129
129
  "peerDependencies": {
130
130
  "@theokit/sdk": "^4.0.1",
131
- "@theokit/ui": "^0.14.0 || ^0.18.0 || ^0.19.0 || ^1.0.0",
131
+ "@theokit/ui": "^1.1.0",
132
132
  "ai": ">=7.0.0",
133
133
  "db0": "^0.3.0",
134
134
  "react": "^19.0.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/client/consume-ui-message-stream.ts","../src/client/agent-client.ts","../src/client/last-user-text.ts","../src/client/channel-transport.ts","../src/client/in-process-transport.ts","../src/client/http-transport.ts","../src/client/create-agent-client.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 for await (const message of readUIMessageStream({ stream })) {\n onMessage(message)\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 */\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 constructor(transport: AgentTransport, contextResolver?: () => RequestContext | undefined) {\n this.#transport = transport\n this.#contextResolver = contextResolver\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 #emit(): void {\n // thread = committed turns + this turn's user + the in-flight assistant (`messages`). New array per\n // emit is fine — the SNAPSHOT reference only changes here, satisfying useSyncExternalStore.\n const thread = this.#currentUser\n ? [...this.#committed, this.#currentUser, ...this.#messages]\n : [...this.#committed, ...this.#messages]\n this.#snapshot = { messages: this.#messages, thread, status: this.#status, error: this.#error }\n for (const listener of this.#listeners) listener()\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 this.#emit()\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 }\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 }\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 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 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/** 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 { 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 */\nexport class InProcessTransport implements AgentTransport {\n readonly #run: InProcessRunner\n /** Pending inline approvals: approvalId → resolver of the parked `awaitApproval` promise. */\n readonly #pending = new Map<string, (decision: boolean | ApprovalDecision) => void>()\n\n constructor(options: InProcessTransportOptions) {\n this.#run = options.run\n }\n\n #awaitApproval: InProcessAwaitApproval = (req) =>\n new Promise<boolean | ApprovalDecision>((resolve, reject) => {\n // Approval ids are server-minted UUIDs — a collision means a real bug (two turns reusing an id).\n // Fail fast rather than silently overwrite the earlier turn's parked resolver (Rule 8).\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)\n })\n\n sendMessages(\n options: Parameters<ChatTransport<UIMessage>['sendMessages']>[0],\n ): Promise<ReadableStream<UIMessageChunk>> {\n const { messages, abortSignal, metadata } = options\n const generator = this.#run({\n message: extractLastUserText(messages),\n signal: abortSignal ?? undefined,\n awaitApproval: this.#awaitApproval,\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 resolve = this.#pending.get(approvalId)\n if (resolve === undefined) {\n return Promise.reject(\n new Error(`No pending approval '${approvalId}' (unknown or already settled).`),\n )\n }\n this.#pending.delete(approvalId)\n resolve(decision)\n return Promise.resolve()\n }\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\nimport { AgentClient, type AgentClientState } from './agent-client.js'\nimport type { AgentTransport, ApprovalDecision, RequestContext } from './transport.js'\n\nexport interface CreateAgentClientOptions {\n /**\n * M43 — per-request context attached to every turn (`headers` → HTTP; `metadata` → in-process/channel).\n * A value OR a resolver. **To keep context live across sends, pass a RESOLVER** (`() => ({...})`) — a\n * plain value is captured at construction and not re-read, so mutating `options.context` afterwards has\n * no effect (unlike `useAgent`, which reads a live ref). A resolver is re-evaluated every send/reconnect.\n */\n context?: RequestContext | (() => RequestContext | undefined)\n}\n\n/**\n * M44 (ADR-0053) — the standalone (no-React) agent client. A plain handle over the framework-agnostic\n * {@link AgentClient} store: drive a turn, observe state, settle HITL — from a node script, a CLI, a\n * test, or a non-React UI, over ANY {@link AgentTransport}.\n */\nexport interface AgentClientHandle<TInput = unknown> {\n /** Send a typed input; opens a fresh stream (replaces prior messages). */\n send(input: TInput): void\n /** Abort an in-flight stream. */\n abort(): void\n /** Clear messages + error, back to idle. */\n reset(): void\n /** Settle a paused HITL approval via the transport's HITL path. */\n approve(approvalId: string, decision: ApprovalDecision): Promise<void>\n /** Resume an interrupted stream (no-op when the transport can't). */\n reconnect(): void\n /** Subscribe to state changes; returns an unsubscribe fn. */\n subscribe(listener: () => void): () => void\n /**\n * The current immutable snapshot: per-turn `messages` (back-compat) + the full conversation `thread`\n * (M46 — committed history + in-flight, accumulated across sends) + `status` / `error`. A TUI / vanilla\n * consumer renders `thread` directly without hand-rolling a transcript.\n */\n getState(): AgentClientState\n /**\n * Drive one turn and yield the assistant `UIMessage` as it streams (progressive snapshots); iteration\n * ends when the turn settles. A `for await` script takes the last yielded value as the final result;\n * a failed turn rejects the iterator with the run error.\n */\n stream(input: TInput): AsyncIterable<UIMessage>\n}\n\n/** Drive a turn on the store and yield the latest assistant message on each streaming update. */\nfunction streamTurn<TInput>(client: AgentClient<TInput>, input: TInput): AsyncIterable<UIMessage> {\n return {\n async *[Symbol.asyncIterator]() {\n const pending: UIMessage[] = []\n let finished = false\n let streamError: Error | undefined\n let notify: (() => void) | null = null\n // Read via functions — `finished`/`streamError` flip ASYNC in the subscribe callback, so a direct\n // read would be wrongly narrowed to its initial literal by control-flow analysis (M41 pattern).\n const isFinished = (): boolean => finished\n const takeError = (): Error | undefined => streamError\n\n const unsubscribe = client.subscribe(() => {\n const snapshot = client.getSnapshot()\n if (snapshot.status === 'streaming') {\n // Push the growing assistant message ONLY on streaming updates. The terminal ('done'/'error')\n // emit carries the SAME final message already yielded on the last streaming update — pushing it\n // again would yield a duplicate. So the terminal emit only flips `finished` (+ captures error).\n const last = snapshot.messages.at(-1)\n if (last !== undefined) pending.push(last)\n } else {\n if (snapshot.status === 'error') streamError = snapshot.error\n finished = true\n }\n notify?.()\n })\n\n client.send(input)\n try {\n for (;;) {\n while (pending.length > 0) {\n const message = pending.shift()\n if (message !== undefined) yield message\n }\n if (isFinished()) break\n await new Promise<void>((resolve) => {\n notify = resolve\n // Close the lost-wakeup window: an emit may have fired during the drain, BEFORE `notify` was\n // set (its `notify?.()` was then a no-op). If work already arrived, resolve now, don't sleep.\n if (pending.length > 0 || isFinished()) resolve()\n })\n notify = null\n }\n const err = takeError()\n if (err !== undefined) throw err\n } finally {\n // Runs on normal completion AND on early `break` (the for-await calls the generator's return()):\n // stop observing, and abort the turn so an early-exiting consumer doesn't leave it running (abort\n // is a no-op once the turn has settled).\n unsubscribe()\n client.abort()\n }\n },\n }\n}\n\n/**\n * Create a standalone (no-React) agent client over a transport. `useAgent` is the React binding over the\n * same store; this is the equivalent for any JS runtime — one agent, consumable everywhere on the seam.\n */\nexport function createAgentClient<TInput = unknown>(\n transport: AgentTransport,\n options: CreateAgentClientOptions = {},\n): AgentClientHandle<TInput> {\n const { context } = options\n const contextResolver =\n context === undefined\n ? undefined\n : (): RequestContext | undefined => (typeof context === 'function' ? context() : context)\n const client = new AgentClient<TInput>(transport, contextResolver)\n\n return {\n send: client.send,\n abort: client.abort,\n reset: client.reset,\n approve: client.approve,\n reconnect: client.reconnect,\n subscribe: client.subscribe,\n getState: client.getSnapshot,\n stream: (input: TInput) => streamTurn(client, input),\n }\n}\n"],"mappings":";AAgBA,eAAsB,uBACpB,UACA,WACe;AACf,QAAM,cAAc,MAAM,sBAAsB,QAAQ;AACxD,QAAM,mBAAmB,aAAa,SAAS;AACjD;AAQA,eAAsB,sBACpB,UACyC;AACzC,MAAI,SAAS,SAAS,MAAM;AAC1B,WAAO,IAAI,eAA+B;AAAA,MACxC,MAAM,YAAY;AAChB,mBAAW,MAAM;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,EAAE,sBAAsB,qBAAqB,IAAI,MAAM,OAAO,IAAI;AAIxE,QAAM,SAAS,qBAAqB,EAAE,QAAQ,SAAS,MAAM,QAAQ,qBAAqB,CAAC;AAC3F,SAAO,IAAI,eAA+B;AAAA,IACxC,MAAM,MAAM,YAAY;AACtB,uBAAiB,UAAU,QAAQ;AACjC,YAAI,OAAO,QAAS,YAAW,QAAQ,OAAO,KAAK;AAAA,MACrD;AACA,iBAAW,MAAM;AAAA,IACnB;AAAA,EACF,CAAC;AACH;AAQA,eAAsB,mBACpB,QACA,WACe;AACf,QAAM,EAAE,oBAAoB,IAAI,MAAM,OAAO,IAAI;AACjD,mBAAiB,WAAW,oBAAoB,EAAE,OAAO,CAAC,GAAG;AAC3D,cAAU,OAAO;AAAA,EACnB;AACF;;;AChDA,SAAS,YAAY,OAAwB;AAC3C,MACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAgC,YAAY,UACpD;AACA,WAAQ,MAA8B;AAAA,EACxC;AACA,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,SAAO,KAAK,UAAU,KAAK;AAC7B;AAGA,SAAS,iBAA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