@tangle-network/agent-app 0.49.1 → 0.49.3

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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/chat-routes/draft-persistence.ts","../src/chat-routes/turn-routes.ts","../src/chat-routes/gateway-adapter.ts"],"sourcesContent":["/**\n * Incremental (\"draft\") persistence of the assistant row WHILE a turn streams.\n *\n * Why this exists — the scale argument, not a convenience:\n *\n * A live turn is readable from two places. The hot path is the session\n * gateway's in-memory/Redis event buffer, which exists so a viewer survives a\n * network blip: it is keyed one sorted set per session, refreshed on every\n * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x\n * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to\n * cover \"a viewer who opens the tab later\" is a category error: it buys memory\n * proportional to the increase and still serves nothing to a viewer who\n * arrives past the new horizon.\n *\n * So the hot buffer must stay SHORT (live delivery + reconnect only), and\n * durable storage must serve history. That only works if durable storage\n * actually HAS the in-flight turn — which, before this module, it did not: the\n * assistant row was written once, after the stream drained. A viewer arriving\n * mid-turn past the hot window read an empty transcript.\n *\n * This module closes that gap: the assistant row is inserted early and patched\n * on a coalesced cadence, so the durable transcript is at most one interval\n * (default 2 s) behind the live stream and the hot buffer never has to be the\n * history tier.\n *\n * Mechanism only. It owns no vocabulary: the caller supplies the snapshot\n * function, the store, and the deterministic row id.\n *\n * Four properties the cadence guarantees:\n * - **Time-floored.** At most one write per `intervalMs`, never one per token.\n * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,\n * status pings, and lifecycle envelopes never do.\n * - **Single-flight.** A write already in flight suppresses the next trigger\n * instead of queueing; the final write is authoritative regardless of how\n * many drafts landed.\n * - **Best-effort.** A store failure is logged and swallowed — a durability\n * optimization must never kill a healthy stream (the same rule\n * `withDurableChatProjection` already states).\n */\n\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Message row shape the writer reads back when re-entering a turn. */\nexport interface DraftStoredMessage extends Pick<AssistantRowValues, keyof ChatTurnUsage> {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n}\n\n/** Values written to the assistant row — the intersection of the append and\n * patch shapes, so one snapshot serves both. */\nexport interface AssistantRowValues {\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n}\n\n/** The store capability incremental persistence needs on top of\n * `appendMessage`. A store without `updateMessage` cannot patch a row, so it\n * cannot draft at all — the caller keeps today's single-write behavior. */\nexport interface AssistantDraftStore {\n listMessages(threadId: string): Promise<DraftStoredMessage[]>\n appendMessage(input: AssistantRowValues & {\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n }): Promise<unknown>\n updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** Live snapshot of the assistant body, taken from the producer's own\n * accumulators. `parts` is the DRAFT projection (`draftParts()`), never the\n * finalized one — see `draftAssistantParts`. */\nexport interface AssistantDraftSnapshot {\n content: string\n parts?: Array<Record<string, unknown>>\n usage?: ChatTurnUsage\n model?: string\n}\n\n/** Product-tunable cadence. Defaults are stated on each field; a product with\n * a chattier or heavier workload moves them without forking the writer. */\nexport interface DraftPersistenceTuning {\n /** Minimum wall-clock gap between draft writes, in ms. Default 2000.\n *\n * Justification for 2 s, from a measured tool-heavy production run (517\n * stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the\n * dirty gate turns 517 candidate writes into <= 45, while leaving the\n * durable row at most 2 s stale — an order of magnitude below the time it\n * takes a viewer to open a tab and render, so a late viewer never perceives\n * the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per\n * run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant\n * shards. Lower it and write amplification grows with no perceptible\n * freshness gain; raise it past ~5 s and a late viewer starts seeing a\n * visibly truncated answer. */\n intervalMs?: number\n /** Serialized-parts size (bytes) past which the interval backs off, so a\n * turn accumulating a megabyte-scale `parts` blob does not rewrite it every\n * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->\n * interval x 5. The final write is never throttled. */\n backoffBytes?: number\n /** Per-tool-part output cap applied to DRAFTS ONLY (bytes). A tool returning\n * a large blob would otherwise be rewritten in full on every draft. The\n * final write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. */\n maxDraftToolOutputBytes?: number\n}\n\n/** Define the inputs required to construct an assistant draft writer */\nexport interface AssistantDraftWriterOptions extends DraftPersistenceTuning {\n store: AssistantDraftStore\n threadId: string\n /** DETERMINISTIC row id for this turn's assistant message — the whole\n * idempotency mechanism. Derived from the turn's existing identity\n * (`deriveExecutionId` in the interactive lane, the turn id in the detached\n * lane), so a re-entered turn addresses the SAME row: the writer looks the\n * id up before its first insert and patches what it finds. */\n messageId: string\n /** Read the producer's live accumulators. Returns null before the producer\n * is resolved (the assembly defers box resolution into the first pull). */\n snapshot(): AssistantDraftSnapshot | null\n /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the\n * draft's scalar content AND every draft text part — parity with the final\n * write, or incremental persistence would re-open the at-rest PII leak that\n * transform closed, just seconds earlier and on every turn. */\n transformText?(text: string): string | Promise<string>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Coalescing writer that keeps one durable assistant row in step with a\n * streaming turn. Created per turn; not reusable. */\nexport interface AssistantDraftWriter {\n /** Arm/trigger a draft write from one engine event. Synchronous by design —\n * the write itself is fire-and-forget so the stream is never blocked on\n * store latency. */\n notify(event: { type?: unknown }): void\n /** Stop drafting and settle any in-flight write. Called before the final\n * write so a late draft can never clobber the authoritative row. */\n close(): Promise<void>\n /** Write the AUTHORITATIVE completion values onto this turn's row —\n * insert-or-patch under the same deterministic id, un-throttled and\n * un-truncated. Errors propagate: the final write is the one that must not\n * fail silently. Implies {@link close}. */\n finalize(values: AssistantRowValues): Promise<void>\n /** The durable row this turn is writing, once one exists. */\n rowId(): string | undefined\n /** Retract the row for a turn that produced nothing (mirrors the final\n * write's empty-turn skip, which leaves no row at all today). Also retracts\n * a row a PREVIOUS attempt left behind, so a re-entered turn that ends\n * empty converges on \"no row\" rather than a stale partial. */\n discard(): Promise<void>\n /** Diagnostics: how many draft writes actually reached the store. */\n writeCount(): number\n}\n\n/** Event types that carry assistant content and therefore arm a draft write.\n * An allowlist on purpose: an unknown type (a product heartbeat, a bespoke\n * passthrough) must NEVER arm a write, or a silent producer would rewrite the\n * same row forever. */\nconst CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'text',\n 'reasoning',\n 'tool_call',\n 'tool_result',\n 'usage',\n 'notice',\n 'error',\n 'file',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n 'message.part.updated',\n])\n\nconst DEFAULT_INTERVAL_MS = 2000\nconst DEFAULT_BACKOFF_BYTES = 262144\nconst DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768\n\n/** True when this event should arm a draft write. */\nexport function isDraftContentEvent(event: { type?: unknown }): boolean {\n return typeof event?.type === 'string' && CONTENT_EVENT_TYPES.has(event.type)\n}\n\n/** Caps one tool part's `output` for a DRAFT write. The value is replaced by a\n * truncated string plus a marker, so a reader can tell a clipped draft from a\n * real short output; the final write restores the untruncated value. */\nfunction capDraftToolOutput(part: Record<string, unknown>, maxBytes: number): Record<string, unknown> {\n if (maxBytes <= 0) return part\n if (String(part.type ?? '') !== 'tool') return part\n const state = part.state\n if (!state || typeof state !== 'object') return part\n const record = state as Record<string, unknown>\n const output = record.output\n if (output === undefined || output === null) return part\n const serialized = typeof output === 'string' ? output : safeStringify(output)\n if (serialized.length <= maxBytes) return part\n const metadata = (record.metadata && typeof record.metadata === 'object' ? record.metadata : {}) as Record<string, unknown>\n return {\n ...part,\n state: {\n ...record,\n output: `${serialized.slice(0, maxBytes)}…[draft-truncated ${serialized.length - maxBytes} chars]`,\n metadata: { ...metadata, draftTruncated: true },\n },\n }\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return String(value)\n }\n}\n\n/** Build the coalescing draft writer for one turn. */\nexport function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter {\n const log = options.log ?? (() => {})\n const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS\n const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES\n const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES\n\n let dirty = false\n let closed = false\n let inFlight: Promise<void> | undefined\n let lastWriteAt = 0\n let lastBlobBytes = 0\n let rowId: string | undefined\n let writes = 0\n\n /** Interval for the NEXT write, backed off by the size of the last blob\n * written — a turn accumulating a huge parts array rewrites it less often. */\n function currentIntervalMs(): number {\n if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5\n if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5)\n return baseIntervalMs\n }\n\n async function projectValues(snapshot: AssistantDraftSnapshot): Promise<AssistantRowValues> {\n const transform = options.transformText\n const content = transform ? await transform(snapshot.content) : snapshot.content\n let parts: ChatMessagePart[] | undefined\n if (snapshot.parts) {\n const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput))\n const redacted = transform\n ? await Promise.all(\n capped.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : capped\n parts = toChatMessageParts(redacted)\n }\n const usage = snapshot.usage ?? {}\n return {\n content,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(snapshot.model ? { model: snapshot.model } : {}),\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\n }\n }\n\n /** Adopt the row a PREVIOUS attempt at this turn already inserted, if any.\n * This lookup — by the deterministic id, through the store's ordinary read\n * — is the whole crash-safety mechanism: no new state, no extra column, no\n * second index. */\n async function adoptRow(): Promise<string | undefined> {\n if (rowId) return rowId\n const existing = (await options.store.listMessages(options.threadId)).find(\n (message) => message.id === options.messageId,\n )\n if (existing) rowId = existing.id\n return rowId\n }\n\n /** Insert-or-patch one set of values onto this turn's single row. */\n async function writeOnce(values: AssistantRowValues): Promise<void> {\n if (await adoptRow()) {\n await options.store.updateMessage!(rowId!, values)\n writes += 1\n return\n }\n const inserted = await options.store.appendMessage({\n id: options.messageId,\n threadId: options.threadId,\n role: 'assistant',\n ...values,\n })\n // The `?? options.messageId` tail is valid HERE and only here: this writer\n // supplied the id, so a store that returns nothing still wrote that row.\n // A caller that did not assign an id has no such fallback — which is why\n // `rowIdOf` deliberately stops at the honest read.\n rowId = rowIdOf(inserted) ?? options.messageId\n writes += 1\n }\n\n function trigger(): void {\n if (closed) return\n if (!dirty) return\n // Single-flight: a write already in flight SUPPRESSES this trigger rather\n // than queueing behind it. `dirty` stays armed, so the next event after it\n // lands writes the newer snapshot — one write is never spent on state a\n // later one supersedes.\n if (inFlight) return\n const now = Date.now()\n // The first content event writes immediately (a late viewer sees a row at\n // once); the time floor governs every write after it.\n if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return\n const snapshot = options.snapshot()\n if (!snapshot) return\n // Nothing to persist yet: an armed-but-empty snapshot (first event is a\n // tool call with no text and no parts) would insert a blank row.\n if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return\n dirty = false\n lastWriteAt = now\n inFlight = (async () => {\n try {\n const values = await projectValues(snapshot)\n lastBlobBytes = values.parts ? safeStringify(values.parts).length : 0\n await writeOnce(values)\n } catch (err) {\n // Best-effort by contract: a store outage degrades freshness for late\n // viewers, it does not fail a healthy turn.\n log('[chat-routes] incremental assistant persistence failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n } finally {\n inFlight = undefined\n // A trigger that arrived while this write was in flight left `dirty`\n // armed with a NEWER snapshot. Re-run it here or that state would sit\n // unwritten until the next content event — and if this was the last\n // event of a quiet stretch, until the final write.\n if (dirty && !closed) trigger()\n }\n })()\n }\n\n return {\n notify(event) {\n if (closed) return\n if (isDraftContentEvent(event)) dirty = true\n trigger()\n },\n async close() {\n closed = true\n if (inFlight) await inFlight\n },\n async finalize(values) {\n closed = true\n if (inFlight) await inFlight\n await writeOnce(values)\n },\n rowId: () => rowId,\n async discard() {\n closed = true\n if (inFlight) await inFlight\n if (!options.store.deleteMessage) return\n try {\n if (!(await adoptRow())) return\n await options.store.deleteMessage(rowId!)\n rowId = undefined\n } catch (err) {\n log('[chat-routes] draft assistant row discard failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n writeCount: () => writes,\n }\n}\n\n/** True when a store can support incremental persistence at all. Without\n * `updateMessage` a draft row could never be patched, so the caller keeps\n * today's exact single-write behavior. */\nexport function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean {\n return typeof store.updateMessage === 'function'\n}\n\n/** The row id an `appendMessage` actually returned, or `null` when the store\n * returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed\n * `Promise<unknown>` so a product adapter is free to resolve `void`; every\n * caller that wants to NAME the row it just wrote has to read defensively.\n *\n * Deliberately no fallback to a caller-assigned id — see `writeOnce`, which\n * adds its own. A caller that let the store mint the id has nothing to fall\n * back TO, and guessing one would report a row that may not exist. */\nexport function rowIdOf(inserted: unknown): string | null {\n const id = (inserted as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\n/** The default deterministic assistant-row id for a turn. Readable on purpose\n * (an operator grepping a transcript row id finds the run), and stable across\n * re-entries because every input already is. */\nexport function assistantRowIdForTurn(turnKey: string): string {\n return `assistant:${turnKey}`\n}\n","/**\n * `createChatTurnRoutes` — the assembled server chat vertical (issue #188\n * Phase 1). One factory composing the pieces every product re-wired by hand:\n *\n * body parse/validate → `/web` `parseJsonObjectBody` + `./wire`\n * turn identity → `/stream` `resolveChatTurn` + agent-runtime `/durable`\n * `deriveExecutionId`\n * producer → injected seam (sandbox lane via\n * `createSandboxChatProducer`; router lane is the\n * product's own `ChatTurnProducer`)\n * turn engine → agent-runtime `/durable` `handleChatTurn` (verbatim)\n * durability → `/stream` turn-buffer tap, wired BY DEFAULT\n * (tee + drain keeps the turn running after a\n * client drop; replay serves the buffered tail)\n * persistence → injected `/chat-store`-shaped store\n * (user row on send, assistant row on completion)\n * interactions answer → `/interactions` `createInteractionAnswerRoute`\n *\n * Handlers are web-standard `Request → Response` (Workers, Node 18+, Deno) —\n * no router import. Auth/access is one injected `authorize` seam, composable\n * with `/app-auth` guards but not coupled to them.\n *\n * Optional product seams let a complex turn-orchestrator compose the vertical\n * instead of hand-rolling a generator — each omittable to the exact behavior\n * above: `turnLock` (single-flight acquire/release around the turn),\n * `contextGate` (pre-producer domain-readiness short-circuit), `beforeTurn`\n * (observe + augment the producer input), `lifecycle` (deterministic\n * start/complete/error telemetry), `heartbeat` (keepalive during silent\n * producer waits), and `onRawEvent` (the raw producer events, for telemetry) —\n * plus the `authorize` result's `insertUserMessage` flag (suppress the user row\n * for a product-dispatched turn). `handleChatTurn` stays the engine — the seams\n * only wrap its input, its producer stream, and its settle.\n *\n * Seam stability: all of the above are STABLE and safe to depend on. They\n * graduated in #227 against the bar this package holds itself to — a seam is\n * provisional until two INDEPENDENT consumers exercise it, because one\n * consumer's shape is indistinguishable from that consumer's assumptions.\n * `turnLock` cleared it with `/turn-stream`'s shared DO adapter (#221);\n * `contextGate`, `beforeTurn`, `onRawEvent` and `insertUserMessage` each\n * cleared it with two product verticals reading them differently — and the\n * review found no leaked assumptions to fix, only `ChatRouteEvent` to export.\n *\n * They stay FLAT top-level options (not grouped under a `hooks` object): that\n * grouping would break every shipped consumer's call for no mechanism gain, and\n * this package's exports are additive-only. For the same reason `onRawEvent`\n * keeps its two-argument `(event, context)` signature rather than being\n * normalized to the single-args shape the other seams take.\n */\n\nimport {\n deriveExecutionId,\n handleChatTurn,\n type ChatTurnIdentity,\n type ChatTurnProducer,\n} from '@tangle-network/agent-runtime/durable'\nimport { mentionInputToPart, toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport {\n assistantRowIdForTurn,\n createAssistantDraftWriter,\n rowIdOf,\n storeSupportsDraftPersistence,\n type AssistantDraftStore,\n type AssistantDraftWriter,\n type DraftPersistenceTuning,\n} from './draft-persistence'\nimport {\n createInteractionAnswerRoute,\n type InteractionAnswerRoute,\n type InteractionAnswerRouteOptions,\n} from '../interactions/route'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n normalizeClientTurnId,\n replayTurnEvents,\n resolveChatTurn,\n stampReplaySeq,\n type PersistedChatMessageForTurn,\n type TurnEventStore,\n} from '../stream/index'\nimport type { ModelFailoverAttempt } from '../model-resolution/failover'\nimport { parseJsonObjectBody } from '../web/index'\nimport {\n assertPromptPartsWithinCap,\n ChatTurnInputError,\n parseChatTurnParts,\n parseFileMentions,\n type ChatTurnFilePartInput,\n type ChatTurnPartInput,\n type ChatTurnRequestPayload,\n type FileMention,\n} from './wire'\n\n// ── seams ───────────────────────────────────────────────────────────────────\n\n/** Usage receipt persisted onto the assistant message (the flattened\n * `step-finish` shape `/chat-store`'s columns mirror). */\nexport interface ChatTurnUsage {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n costUsd?: number\n}\n\n/** What the route persists — a structural subset of `/chat-store`'s\n * `ChatStore`, so `createChatStore(db, tables)` satisfies it directly and a\n * product with its own persistence adapts without importing drizzle. */\nexport interface ChatTurnMessageStore {\n listMessages(threadId: string): Promise<Array<{\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n }>>\n appendMessage(input: {\n /** Caller-assigned row id. Honored by `/chat-store`'s `createChatStore`;\n * a product store free to ignore it (the writer then adopts whatever id\n * the insert returns). Set only by incremental persistence. */\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n content: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n }): Promise<unknown>\n /** Patch an existing row. Its PRESENCE is what enables incremental assistant\n * persistence — a store without it keeps today's exact single-write-on-\n * completion behavior, which is what makes this additive. */\n updateMessage?(id: string, patch: {\n content?: string\n parts?: ChatMessagePart[]\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n }): Promise<unknown>\n /** Remove a row. Used to retract a draft assistant row for a turn that ended\n * producing nothing, so the empty-turn case still leaves no row at all. */\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** `ChatTurnProducer` plus the persisted projection the assembly reads after\n * drain. `createSandboxChatProducer` returns this; a router-lane producer\n * may omit the optional members (finalText persists as a single text part). */\nexport interface ChatTurnRouteProducer extends ChatTurnProducer {\n assistantParts?(): Array<Record<string, unknown>>\n /** MID-STREAM snapshot of the same projection, safe to call while the turn\n * is running: no dangling-tool terminalization, no pending-ask settlement\n * (see `/stream`'s `draftAssistantParts`). Read by incremental persistence.\n * A producer that omits it still drafts — the scalar text — but persists no\n * parts until the turn completes. */\n draftParts?(): Array<Record<string, unknown>>\n usage?(): ChatTurnUsage\n /** The model that SERVED the turn. With failover wired this is the model that\n * actually answered, which is not necessarily the one the caller preferred —\n * read it after the stream drains, never before. */\n model?: string\n /** Model-failover attribution, when the producer supports it. Reported onto\n * the usage/billing receipt so a downgrade is never silent. */\n modelFailover?(): ChatTurnModelFailover\n /** Requested-versus-served attribution reported by the sandbox sidecar.\n * `echoReceived` distinguishes a missing echo from a partial echo. */\n modelAttribution?(): ChatTurnModelAttribution\n}\n\n/** Which model served, and what it took to get there. */\nexport interface ChatTurnModelFailover {\n /** The model that served the turn. */\n model?: string\n /** Every model tried, in order, with the reason each was abandoned. */\n attempts: ModelFailoverAttempt[]\n /** True when the preferred model did not serve. */\n usedFallback: boolean\n}\n\n/** Requested and effective model attribution for one sandbox turn. */\nexport interface ChatTurnModelAttribution {\n /** The model explicitly requested by the caller, before shell failover. */\n requestedModel?: string\n /** The model the downstream sandbox reports actually served the turn. */\n servedModel?: string\n /** The provider that served the turn, when echoed by the sandbox. */\n servedProvider?: string\n /** How the sandbox selected the served model. */\n servedSource?: 'request' | 'environment' | 'profile'\n /** True when a structurally valid effective-backend echo was observed. */\n echoReceived: boolean\n}\n\n/** Resolve authorization status and context for a chat turn including tenant and user identification */\nexport type ChatTurnAuthorization<TContext> =\n | {\n ok: true\n tenantId: string\n userId: string\n context: TContext\n /** When `false`, skip the `role:'user'` message insert for this turn — for\n * a product-dispatched / synthetic turn (e.g. a follow-up the product\n * raised itself) that must not surface a new user row. Composes with —\n * never overrides — the engine's retry-dedup: `authorize` runs before\n * turn identity is resolved, so it cannot tell a retry from a fresh turn;\n * a turn already deduped stays deduped. Omit / `true` → today's behavior.\n *\n * Settled shape (#227). The validated case in both consumers is the same:\n * a durable plan-approval follow-up re-entering an execution the decision\n * route already enqueued — a decision, not a typed message, so it must\n * not surface a user bubble. Suppressing the insert also propagates:\n * `ChatTurnProduceArgs.userMessageId` is `null` for the rest of the turn\n * when there is no row to reuse, so a seam anchoring to the user row must\n * handle that arm rather than assume a string. */\n insertUserMessage?: boolean\n }\n | { ok: false; response: Response }\n\n/** Define arguments required to authorize a chat turn based on intent and request details */\nexport interface ChatTurnAuthorizeArgs {\n request: Request\n intent: 'turn' | 'replay' | 'running'\n /** Parsed, validated POST body (turn intent only). */\n body?: ChatTurnRequestPayload\n /** The buffered turn id being replayed (replay intent only). */\n turnId?: string\n /** The thread whose running turns are being discovered (running intent only). */\n threadId?: string\n}\n\n/** Trusted per-turn limits supplied by a server adapter, never by the body. */\nexport interface ChatTurnExecutionLimits {\n maxInputTokens?: number\n maxOutputTokens?: number\n maxReasoningTokens?: number\n maxToolTokens?: number\n maxToolCalls?: number\n maxProviderCostUsd?: number\n}\n\n/** Server-only context for one turn request. */\nexport interface ChatTurnRequestContext {\n waitUntil?(p: Promise<unknown>): void\n /** Abort this turn when its HTTP client disconnects. Browser callers omit it. */\n cancelOnDisconnect?: boolean\n /** Limits already authenticated by the server adapter. */\n executionLimits?: ChatTurnExecutionLimits\n}\n\n/** Define the arguments required to produce a chat turn with context and messaging details */\nexport interface ChatTurnProduceArgs<TContext> {\n request: Request\n body: ChatTurnRequestPayload\n identity: ChatTurnIdentity\n context: TContext\n /** The message to send: plain text, or parts when the client attached\n * files (a text part is prepended from `content` when present). */\n prompt: string | ChatTurnPartInput[]\n /** Stable id for cross-process reconnect (`deriveExecutionId`). */\n executionId: string\n /** The turn-buffer id announced to the client for replay. */\n turnStreamId: string\n priorMessages: PersistedChatMessageForTurn[]\n /** Server-authenticated limits for this turn. Never copied from the body. */\n executionLimits?: ChatTurnExecutionLimits\n /** The durable `role:'user'` row this turn is anchored to — the row the\n * factory just inserted, or the one retry-dedup REUSED. Products anchor\n * optimistic-bubble swaps, retry targeting, and stop-polling to it, and it\n * is the only way to name a REUSED row (which `priorMessages` excludes).\n *\n * Three states, all meaningful:\n * - `undefined` — not resolved yet. `turnLock.acquire` is the one seam that\n * sees this: it runs before any side effect by contract, so the row does\n * not exist when it reads the args.\n * - `null` — resolved, no row: `authorize` returned `insertUserMessage:\n * false` on a turn with nothing to reuse, or the store's `appendMessage`\n * resolved without a usable id.\n * - a string — the row id, for `contextGate`, `beforeTurn`, and `produce`. */\n userMessageId?: string | null\n}\n\n/** One event as it crosses the route: the producer's own vocabulary, or an\n * injected keepalive. Same shape the engine forwards verbatim.\n *\n * Public because it IS the vocabulary of two seams — `onRawEvent`'s parameter\n * and `heartbeat.event`'s return. Exported so a product can declare a\n * standalone handler (`function onRawEvent(e: ChatRouteEvent, ctx: T)`) rather\n * than depending on contextual typing from an inline object literal. */\nexport type ChatRouteEvent = { type: string; data?: Record<string, unknown> }\n\n/** Best-effort human-readable cause from a terminal `error` /\n * `session.run.failed` event's `data`. */\nfunction failureReasonOf(data: Record<string, unknown> | undefined): string | undefined {\n if (!data) return undefined\n const message = data.message ?? data.error ?? data.reason\n if (typeof message === 'string' && message.length > 0) return message\n return undefined\n}\n\n/** Keepalive emitted while the producer is quiet (long tool calls, first-token\n * wait) so client watchdogs stay re-armed. One is emitted each time\n * `intervalMs` elapses with no producer event; the window resets on every real\n * event, so a chatty producer never triggers one. The product owns the event\n * shape (`type` + `data`). Omit → no keepalives (today's behavior). */\nexport interface ChatTurnHeartbeat {\n intervalMs: number\n event(info: { elapsedMs: number; tick: number }): ChatRouteEvent\n}\n\n/** Patch a `beforeTurn` hook returns to augment the producer's input. Omitted\n * fields keep the route-assembled value; the product's `produce` still owns\n * the system prompt. */\nexport interface ChatTurnInputPatch {\n prompt?: string | ChatTurnPartInput[]\n priorMessages?: PersistedChatMessageForTurn[]\n}\n\n/** Pre-turn readiness verdict — proceed, short-circuit, or hand off to a\n * product-owned durable turn. Distinct from `authorize`: this gates domain\n * readiness, not access. */\nexport type ChatTurnGateResult =\n | { proceed: true }\n | { proceed: false; response: Response }\n /** The product has accepted the turn and owns execution and lifecycle after\n * the route releases its lock. */\n | { proceed: 'handoff'; response: Response }\n\n/** Single-flight lock verdict — acquired (with an opaque handle passed back to\n * `release`), or already held (short-circuit with the product's 409-style\n * `Response`). */\nexport type ChatTurnLockResult =\n | { acquired: true; handle?: unknown }\n | { acquired: false; response: Response }\n\n/** Async acquire/release wrapped around the turn. `acquire` runs before any\n * side effect; `release` runs once when the turn settles — including on a\n * short-circuit or a throw. */\nexport interface ChatTurnLock<TContext> {\n acquire(args: ChatTurnProduceArgs<TContext>): ChatTurnLockResult | Promise<ChatTurnLockResult>\n release(handle: unknown): void | Promise<void>\n}\n\ninterface ChatTurnLifecycleBase<TContext> {\n identity: ChatTurnIdentity\n executionId: string\n turnStreamId: string\n context: TContext\n}\n/** Define lifecycle start event with context and timestamp for a chat turn */\nexport interface ChatTurnLifecycleStart<TContext> extends ChatTurnLifecycleBase<TContext> {\n startedAt: number\n}\n/** Define the structure representing the completion state of a chat turn lifecycle with usage data */\nexport interface ChatTurnLifecycleComplete<TContext> extends ChatTurnLifecycleBase<TContext> {\n finalText: string\n usage: ChatTurnUsage\n durationMs: number\n /** The model that SERVED the turn — the fallback's id when failover moved it.\n * `usage` is that model's, so telemetry that splits cost or quality by model\n * must key on this and not on the requested one. */\n model?: string\n /** Requested-versus-served attribution. A difference is detectable from\n * this receipt and from the persisted assistant row independently. */\n requestedModel?: string\n servedModel?: string\n servedProvider?: string\n servedSource?: 'request' | 'environment' | 'profile'\n /** Attribution for a downgrade: which models were tried and why each failed.\n * `undefined` when the producer reports no failover support. */\n modelFailover?: ChatTurnModelFailover\n /** The durable `role:'assistant'` row this turn wrote, or `null` when it\n * wrote none (an empty turn leaves no row — a draft started mid-stream is\n * retracted). The detached lane surfaces the same id as\n * `DetachedTurnResult.messageId`; one contract, two lanes. */\n assistantMessageId: string | null\n /** Set when `contextGate` answered this turn and the producer never ran.\n *\n * Present so telemetry can tell \"the model produced nothing\" apart from \"the\n * model was never asked\" — they look identical here (`finalText: ''`,\n * empty `usage`) and mean opposite things. A gated turn writes no assistant\n * row, so `assistantMessageId` is `null`, and the billing/persistence\n * `onTurnComplete` is deliberately NOT fired for it. */\n gated?: true\n}\n/** Represent an error occurring during a chat turn lifecycle with context and duration information */\nexport interface ChatTurnLifecycleError<TContext> extends ChatTurnLifecycleBase<TContext> {\n error: unknown\n durationMs: number\n}\n\n/** Deterministic run telemetry: `onTurnStart` fires before the producer runs;\n * exactly one of `onTurnComplete` / `onTurnError` fires after the turn\n * settles, always after `onTurnStart`. Failure is derived from the turn's own\n * `error` / `session.run.failed` events (or a drain throw), not the engine's\n * lifecycle envelope. Hook errors are swallowed — telemetry never fails a\n * turn. */\nexport interface ChatTurnLifecycle<TContext> {\n onTurnStart?(info: ChatTurnLifecycleStart<TContext>): void | Promise<void>\n onTurnComplete?(info: ChatTurnLifecycleComplete<TContext>): void | Promise<void>\n onTurnError?(info: ChatTurnLifecycleError<TContext>): void | Promise<void>\n}\n\n/** What a settled turn reports to `onTurnComplete` — the product's\n * post-processing seam (billing, titles, audit). */\nexport interface ChatTurnCompleteInput<TContext> {\n identity: ChatTurnIdentity\n finalText: string\n context: TContext\n failed: boolean\n failureReason?: string\n /** The model that SERVED this turn. With failover wired it may differ from\n * the requested one, so a product that bills or scores per model MUST read\n * it here rather than assuming the model it asked for. */\n model?: string\n /** Requested-versus-served attribution. A difference is detectable from\n * this receipt and from the persisted assistant row independently. */\n requestedModel?: string\n servedModel?: string\n servedProvider?: string\n servedSource?: 'request' | 'environment' | 'profile'\n /** Present when the producer supports failover: the full attempt trail, and\n * `usedFallback` — the flag that makes a silent downgrade impossible. */\n modelFailover?: ChatTurnModelFailover\n /** The durable `role:'assistant'` row this turn wrote, or `null` when it\n * wrote none (an empty turn leaves no row).\n *\n * Populated even when `failed` is true — a terminal error event still\n * persists whatever partial answer arrived, and that pairing is exactly\n * what lets a product render an error row against a REAL message instead of\n * hunting for the newest row in the thread. The detached lane surfaces the\n * same id as `DetachedTurnResult.messageId`. */\n assistantMessageId: string | null\n}\n\n/** Define options to configure chat turn routes including authorization, storage, and event buffering */\nexport interface CreateChatTurnRoutesOptions<TContext = void> {\n /** Names the product in `deriveExecutionId` so retries land on the same\n * substrate execution. */\n projectId: string\n /** Authenticate + authorize the caller for a turn or a replay. The only\n * product-supplied access step: session auth, thread/workspace access,\n * seat/balance gates, rate limits all live here. */\n authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>\n /** Thread/message persistence (`/chat-store`'s store or a product adapter). */\n store: ChatTurnMessageStore\n /** Turn-event buffer (`createD1TurnEventStore(env.DB)` or `/turn-stream`'s\n * `createDurableObjectTurnEventStore(env.TURN_STREAM_DO)` in production,\n * `createMemoryTurnEventStore()` in tests). Wired by default — every turn\n * is buffered and replayable. */\n turnStore: TurnEventStore\n /** Build the turn's event stream. Sandbox lane: `streamSandboxPrompt(...)`\n * wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the\n * product's own producer. May be async (box resolution). */\n produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>\n /** Single-flight lock acquired before any side effect and released once when\n * the turn settles (including short-circuit/throw). `/turn-stream`'s\n * `createDurableTurnLock` is the shared DO-backed implementation. Omit →\n * no lock. */\n turnLock?: ChatTurnLock<TContext>\n /** Pre-turn readiness gate that can short-circuit with a product `Response`\n * before the producer runs (the user row is already persisted). Runs after\n * `turnLock.acquire`, before `beforeTurn`. Omit → always proceed.\n *\n * Settled shape (#227). What a consumer may depend on:\n * - `args.userMessageId` is RESOLVED here — a string, or `null` when the\n * insert was suppressed with nothing to reuse. (`turnLock.acquire` is the\n * only seam that sees it `undefined`.)\n * - `{proceed:false}` releases the lock and returns the product's `Response`\n * verbatim: `beforeTurn` and `produce` never run, no assistant row is\n * written, and the user row already inserted is KEPT — a real user turn\n * whose assistant side is the gate's own response.\n * - `{proceed:'handoff'}` releases the route-acquired lock, returns the\n * product's accepted `Response`, and transfers execution and lifecycle\n * ownership to the product's durable owner. The route runs no producer\n * or lifecycle hook.\n * - Always returning `{proceed:true}` is supported, not a misuse: the seam\n * doubles as the one place that runs after the user row exists and before\n * the producer, which is where per-turn analytics and readiness\n * precomputation belong. A gate that never gates is a valid consumer. */\n contextGate?(args: ChatTurnProduceArgs<TContext>): ChatTurnGateResult | Promise<ChatTurnGateResult>\n /** Observe the assembled producer input and optionally augment it (rewrite\n * the prompt / prior messages) before the producer runs. Omit → no change.\n *\n * Settled shape (#227). BOTH return arms are contract:\n * - a `ChatTurnInputPatch` shallow-merges over the route-assembled args, so\n * an omitted field keeps the route's value;\n * - `void` means \"no patch\" — and mutating `args.context` in place is the\n * supported way to thread request-scoped state forward to `produce` /\n * `lifecycle` / `onTurnComplete`, which all receive the same object.\n *\n * A throw propagates (the turn fails with the lock released). It runs BEFORE\n * `lifecycle.onTurnStart`, so a throw here fires no terminal lifecycle hook —\n * the span never opened. Telemetry for a failure in this seam belongs in the\n * seam, not in `lifecycle`. */\n beforeTurn?(args: ChatTurnProduceArgs<TContext>): ChatTurnInputPatch | void | Promise<ChatTurnInputPatch | void>\n /** Deterministic run telemetry (start / complete / error) with identity and\n * timing. Omit → no telemetry. */\n lifecycle?: ChatTurnLifecycle<TContext>\n /** Keepalive injected while the producer is quiet. Omit → no keepalives. */\n heartbeat?: ChatTurnHeartbeat\n /** Observe each event the producer emits, before the engine frames it and\n * before any heartbeat injection (the raw sidecar-producer events, for\n * telemetry). Never alters the stream; errors are swallowed. Distinct from\n * `onEvent`, which sees the engine-framed stream incl. lifecycle envelopes.\n *\n * Settled shape (#227). What a consumer may depend on:\n * - it sees EXACTLY the producer's own events — no engine lifecycle\n * envelopes, and no injected keepalives (`heartbeat` wraps the stream\n * downstream of this tap, so a synthetic event never reaches a trace);\n * - a throw is caught and logged, never surfaced: a broken telemetry sink\n * cannot fail a turn or truncate the client's stream;\n * - it is an OBSERVER — the return value is ignored, and the event object\n * continues downstream. Mutating it mutates the stream; don't.\n *\n * Takes `(event, context)` rather than one args object, matching both\n * shipped consumers; see the module header on why it stays that way. */\n onRawEvent?(event: ChatRouteEvent, context: TContext): void | Promise<void>\n /** Pre-persist transform of the final text (e.g. `/redact`'s `redactPII`).\n * Live stream is never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Incremental persistence of the assistant row WHILE the turn streams\n * (`./draft-persistence`), so a viewer arriving mid-run is served from\n * durable storage instead of the streaming gateway's hot event buffer.\n *\n * This is what lets the gateway keep that hot buffer SHORT at scale: its\n * Redis footprint is one sorted set per session refreshed on every push, so\n * memory grows LINEARLY with `ttl x concurrent sessions`. Stretching the\n * TTL to cover late viewers buys memory proportional to the increase and\n * still serves nothing past the new horizon. The buffer stays a reconnect\n * window; durable storage — kept at most one cadence interval stale by this\n * option — is the history tier.\n *\n * Enabled by DEFAULT whenever `store.updateMessage` exists (every\n * `/chat-store` consumer); a store without it keeps today's exact\n * single-write behavior. Pass `false` to opt out, or an object to tune the\n * cadence. Wiring it against a store that cannot patch rows throws at route\n * construction rather than silently no-op'ing. */\n incrementalPersistence?: false | DraftPersistenceTuning\n /** Deterministic durable row id for this turn's assistant message. Default\n * `assistant:<executionId>` — already stable across retries because\n * `deriveExecutionId` is. Override only if the product's message ids have a\n * format constraint; it MUST stay deterministic per turn or a re-entered\n * turn will duplicate its row instead of converging. */\n draftMessageId?(args: { identity: ChatTurnIdentity; executionId: string; threadId: string }): string\n /** Post-processing after a turn settles (billing, titles, audit). Fires with\n * `failed:true` + `failureReason` when the turn carried a terminal error\n * event (model 402 / rate-limit / server error) instead of a clean\n * completion, so products skip the deduct and render an error row rather\n * than billing an empty turn and marking it done. A turn that THROWS never\n * reaches this hook (the engine skips it on a producer throw). Errors are\n * swallowed by the engine — they never fail a streamed turn. */\n onTurnComplete?(input: ChatTurnCompleteInput<TContext>): Promise<void>\n /** Per-event side channel (product broadcast). The turn-buffer tap is\n * already wired; this runs in addition. */\n onEvent?(event: { type: string; data?: Record<string, unknown> }, context: TContext): void | Promise<void>\n /** Trace flush handed to `waitUntil` (OTLP export). */\n traceFlush?(context: TContext): Promise<void>\n /** Compose the interaction-answer endpoints (`/interactions`). Omit when the\n * product has no sidecar ask channel. */\n interactions?: InteractionAnswerRouteOptions\n /** Byte budget for inline prompt parts. Default `INLINE_PARTS_MAX_BYTES`. */\n maxInlinePartBytes?: number\n /** Per-flush coalescer for the turn buffer. Default `coalesceDeltas` (this\n * assembly streams the client vocabulary's `{type:'text'|'reasoning',\n * text}` lines, which it merges). A producer streaming raw\n * `message.part.updated` events passes `coalesceChatStreamEvents`. */\n coalesceTurnEvents?: (events: unknown[]) => unknown[]\n replay?: { pollMs?: number; timeoutMs?: number }\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Define routes to run, replay, and list running chat turns with streaming and reconnect support */\nexport interface ChatTurnRoutes {\n /** POST — run one turn, streaming NDJSON. First line is\n * `{type:'turn', turnId}` (the replay handle); the rest is the engine's\n * event protocol. Pass the platform's `waitUntil` so the turn keeps\n * running (and buffering) after a client disconnect. */\n turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response>\n /** GET — replay a buffered turn from `?fromSeq=` (0 = everything), then\n * follow it live until it completes. */\n replay(request: Request, params: { turnId: string }): Promise<Response>\n /** GET `?threadId=` — the reconnect-discovery endpoint: the turn ids still\n * running on a thread, so a client that reloaded mid-turn can re-attach to\n * the live stream via {@link replay} instead of losing it. Returns `[]` when\n * the turn store cannot enumerate running turns (`listRunning` unimplemented). */\n running(request: Request): Promise<Response>\n /** list/answer endpoints from `/interactions`; null when not configured. */\n interactions: InteractionAnswerRoute | null\n}\n\n// ── body validation ────────────────────────────────────────────────────────\n\nfunction errorResponse(err: ChatTurnInputError): Response {\n return Response.json({ code: err.code, error: err.message }, { status: err.status })\n}\n\ninterface ParsedTurnBody {\n payload: ChatTurnRequestPayload\n content: string\n fileParts: ChatTurnFilePartInput[]\n mentions: FileMention[]\n turnId: string | undefined\n}\n\nfunction validateTurnBody(body: Record<string, unknown>, maxInlinePartBytes: number | undefined): ParsedTurnBody {\n const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : ''\n if (!threadId) throw new ChatTurnInputError('Missing threadId')\n const rawContent = body.content ?? body.message ?? ''\n if (typeof rawContent !== 'string') throw new ChatTurnInputError('content must be a string')\n const content = rawContent.trim()\n const fileParts = parseChatTurnParts(body.parts)\n // Path references, not bytes — validated for traversal/charset/count, never\n // counted against the inline-parts byte budget below.\n const mentions = parseFileMentions(body.mentions)\n // A mention is a turn's whole payload often enough to count: \"@chart.png\"\n // with no prose is a real ask, and the pointer block the mentions produce is\n // prompt content the model reads.\n const hasAttachments = Array.isArray(body.attachments) && body.attachments.length > 0\n if (!content && fileParts.length === 0 && mentions.length === 0 && !hasAttachments) {\n throw new ChatTurnInputError('Missing content (send text, parts, mentions, attachments, or any combination)')\n }\n assertPromptPartsWithinCap(fileParts, maxInlinePartBytes)\n let turnId: string | undefined\n try {\n turnId = normalizeClientTurnId(body.turnId)\n } catch (err) {\n throw new ChatTurnInputError(err instanceof Error ? err.message : 'Invalid turnId')\n }\n return {\n // The VALIDATED, deduped mention list replaces the raw one on the payload,\n // so every downstream seam (`authorize`, `contextGate`, `beforeTurn`,\n // `produce`) reads checked paths and never the request's own.\n payload: { ...body, threadId, content, mentions } as ChatTurnRequestPayload,\n content,\n fileParts,\n mentions,\n turnId,\n }\n}\n\n/** File parts persist onto the user message verbatim — the wire shape is the\n * persisted `ChatFilePart`/`ChatImagePart` vocabulary already. Mentions get\n * the one mapping step their own vocabulary needs. The typed projection is\n * `/chat-store`'s (same boundary as the assistant hop).\n *\n * Mentions persist as parts rather than being folded into the prompt because\n * the prompt is not readable back: a retry rebuilds the turn from the stored\n * row, and a transcript draws its pills from it. Turning them INTO prompt\n * text stays the product's job — only the product knows how to resolve a\n * workspace-relative path to an in-box one (`fileMentionsToParts`'\n * `resolvePath` seam), so the route never dispatches them itself. */\nfunction userPartsWithFiles(\n userParts: Array<Record<string, unknown>>,\n fileParts: ChatTurnFilePartInput[],\n mentions: FileMention[],\n): ChatMessagePart[] {\n return toChatMessageParts([\n ...userParts,\n ...fileParts.map((part) => ({ ...part })),\n ...mentions.map((mention) => ({ ...mentionInputToPart(mention) })),\n ])\n}\n\n// ── producer-stream wrappers (heartbeat + raw tap) ───────────────────────────\n\n/** Fire `onRawEvent` for each producer event, before the engine frames it.\n * Best-effort — a telemetry throw is logged, never propagated. */\nasync function* tapRawEvents(\n source: AsyncIterable<ChatRouteEvent>,\n onRawEvent: (event: ChatRouteEvent) => void | Promise<void>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n for await (const event of source) {\n try {\n await onRawEvent(event)\n } catch (err) {\n log('[chat-routes] onRawEvent failed', { error: err instanceof Error ? err.message : String(err) })\n }\n yield event\n }\n}\n\n/** Inject a keepalive whenever `intervalMs` elapses with no source event. The\n * silent window (elapsed + tick) resets on every real event, so a producer\n * that keeps emitting never triggers a heartbeat. Closes the source on early\n * return, matching a `for await` over it. */\nasync function* withStreamHeartbeat(\n source: AsyncIterable<ChatRouteEvent>,\n intervalMs: number,\n makeEvent: (info: { elapsedMs: number; tick: number }) => ChatRouteEvent,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n let pending = iterator.next()\n let windowStart = Date.now()\n let tick = 0\n for (;;) {\n let timer: ReturnType<typeof setTimeout> | undefined\n let winner: 'event' | 'heartbeat'\n try {\n const heartbeat = new Promise<'heartbeat'>((resolve) => {\n timer = setTimeout(() => resolve('heartbeat'), intervalMs)\n })\n winner = await Promise.race([pending.then(() => 'event' as const), heartbeat])\n } finally {\n // Clear the pending timer on EVERY exit — including a `pending`\n // rejection — so a rejected source never orphans a setTimeout that\n // keeps the runtime alive for up to `intervalMs`.\n if (timer !== undefined) clearTimeout(timer)\n }\n if (winner === 'heartbeat') {\n tick += 1\n yield makeEvent({ elapsedMs: Date.now() - windowStart, tick })\n continue\n }\n const result = await pending\n if (result.done) return\n yield result.value\n pending = iterator.next()\n windowStart = Date.now()\n tick = 0\n }\n } finally {\n await iterator.return?.()\n }\n}\n\n// ── the factory ────────────────────────────────────────────────────────────\n\n/** Build chat turn routes to handle and validate incoming chat requests with optional logging */\nexport function createChatTurnRoutes<TContext = void>(\n options: CreateChatTurnRoutesOptions<TContext>,\n): ChatTurnRoutes {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n\n // Incremental persistence is on whenever the store can patch a row. An\n // EXPLICIT opt-in against a store that cannot is a wiring bug, so it fails\n // here — at construction — instead of silently degrading every turn.\n const draftStore: AssistantDraftStore = options.store\n if (options.incrementalPersistence && !storeSupportsDraftPersistence(draftStore)) {\n throw new Error(\n 'incrementalPersistence requires a store with updateMessage() — `/chat-store`\\'s createChatStore has it; a product store must implement it or omit the option',\n )\n }\n const draftTuning: DraftPersistenceTuning | null =\n options.incrementalPersistence === false || !storeSupportsDraftPersistence(draftStore)\n ? null\n : (options.incrementalPersistence ?? {})\n\n async function turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response> {\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return badBody\n\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody, options.maxInlinePartBytes)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return errorResponse(err)\n throw err\n }\n const { payload, content, fileParts, mentions, turnId } = parsed\n\n const auth = await options.authorize({ request, intent: 'turn', body: payload })\n if (!auth.ok) return auth.response\n const { tenantId, userId, context } = auth\n\n // Turn identity: reuse the just-persisted user row on a retry (same\n // turnId or identical trailing content) instead of double-inserting.\n const existingMessages = (await options.store.listMessages(payload.threadId)).map((m) => ({\n id: m.id,\n role: m.role,\n content: m.content,\n parts: (m.parts ?? null) as PersistedChatMessageForTurn['parts'],\n }))\n // An assistant row already trailing the thread is either this turn's\n // in-flight draft (retry — walk past it) or a settled answer (a genuine\n // repeat — new turn). The turn buffer's running index is the discriminator;\n // it is only consulted in the one case that can be ambiguous, so the common\n // path costs nothing.\n let hasRunningTurn = false\n if (draftTuning && existingMessages.at(-1)?.role === 'assistant') {\n try {\n hasRunningTurn = ((await options.turnStore.listRunning?.(payload.threadId)) ?? []).length > 0\n } catch (err) {\n log('[chat-routes] listRunning probe failed; treating the thread as idle', {\n threadId: payload.threadId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n const chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId, hasRunningTurn })\n\n const identity: ChatTurnIdentity = {\n tenantId,\n sessionId: payload.threadId,\n userId,\n turnIndex: chatTurn.turnIndex,\n }\n const executionId = deriveExecutionId({\n projectId: options.projectId,\n sessionId: payload.threadId,\n turnIndex: chatTurn.turnIndex,\n })\n const turnStreamId = crypto.randomUUID()\n\n const prompt: string | ChatTurnPartInput[] =\n fileParts.length === 0\n ? content\n : content\n ? [{ type: 'text', text: content }, ...fileParts]\n : [...fileParts]\n\n // The producer input every pre-turn seam reads. Replaced — never mutated\n // in place — as later steps resolve more of it (`userMessageId` after the\n // insert, `beforeTurn`'s patch after that), so a seam that captured the\n // object never sees it change underneath. `produce` reads the last\n // version because the engine defers its first pull.\n let produceArgs: ChatTurnProduceArgs<TContext> = {\n request,\n body: payload,\n identity,\n context,\n prompt,\n executionId,\n turnStreamId,\n priorMessages: chatTurn.priorMessages,\n ...(ctx?.executionLimits ? { executionLimits: ctx.executionLimits } : {}),\n }\n\n // Single-flight lock: acquire before any side effect. `release` runs\n // exactly once — in the drain's `finally` on a normal turn, or right here\n // on a short-circuit / throw.\n let lockAcquired = false\n let lockHandle: unknown\n let lockReleased = false\n const releaseLock = async (): Promise<void> => {\n if (!lockAcquired || lockReleased) return\n lockReleased = true\n try {\n await options.turnLock!.release(lockHandle)\n } catch (err) {\n log('[chat-routes] turnLock.release failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n if (options.turnLock) {\n const acquired = await options.turnLock.acquire(produceArgs)\n if (!acquired.acquired) return acquired.response\n lockAcquired = true\n lockHandle = acquired.handle\n }\n\n // Turn state, hoisted so the pre-stream `catch` can settle the lifecycle\n // (fire `onTurnError`, close the span) even when a seam throws\n // synchronously before the drain — the drain would otherwise be the only\n // path that runs the terminal hook.\n let producer: ChatTurnRouteProducer | undefined\n let draft: AssistantDraftWriter | undefined\n // Set once persistence settles; `undefined` means it never ran.\n let assistantMessageId: string | null | undefined\n /** The assistant row this turn ended with. Falls back to the draft writer\n * so a turn whose producer THREW — skipping `persistAssistantMessage`\n * entirely — still names the partial row it left behind. */\n const assistantRowId = (): string | null => assistantMessageId ?? draft?.rowId() ?? null\n let runFailed = false\n // Data of the event that marked the run failed — handed to `onTurnError`\n // when no drain throw supplies a richer cause.\n let lastFailureData: Record<string, unknown> | undefined\n let turnStartedAtMs = 0\n let turnStarted = false\n let lifecycleSettled = false\n // Set when `contextGate` answered the turn without running the producer.\n let gatedTurn = false\n\n // Exactly one terminal lifecycle hook, after the turn settles (idempotent).\n // Failure is this route's own verdict (`runFailed` from error/failed\n // events, or a drain/sync throw), not the engine's envelope.\n const fireTerminalLifecycle = async (failed: boolean, terminalError: unknown): Promise<void> => {\n if (lifecycleSettled) return\n lifecycleSettled = true\n const lifecycle = options.lifecycle\n if (!lifecycle) return\n const durationMs = Date.now() - turnStartedAtMs\n try {\n if (failed) {\n await lifecycle.onTurnError?.({\n identity, executionId, turnStreamId, context, durationMs,\n error: terminalError ?? lastFailureData ?? new Error('chat turn failed'),\n })\n } else {\n const failoverInfo = producer?.modelFailover?.()\n const attribution = producer?.modelAttribution?.()\n await lifecycle.onTurnComplete?.({\n identity, executionId, turnStreamId, context, durationMs,\n finalText: producer?.finalText() ?? '',\n usage: producer?.usage?.() ?? {},\n assistantMessageId: assistantRowId(),\n ...(gatedTurn ? { gated: true } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(attribution?.requestedModel ? { requestedModel: attribution.requestedModel } : {}),\n ...(attribution?.servedModel ? { servedModel: attribution.servedModel } : {}),\n ...(attribution?.servedProvider ? { servedProvider: attribution.servedProvider } : {}),\n ...(attribution?.servedSource ? { servedSource: attribution.servedSource } : {}),\n ...(failoverInfo ? { modelFailover: failoverInfo } : {}),\n })\n }\n } catch (err) {\n log('[chat-routes] lifecycle terminal hook failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n try {\n // The product (via `authorize`) may suppress the user-row insert for a\n // dispatched/synthetic turn. AND-composition: it can only subtract, never\n // resurrect a turn the engine already deduped as a retry.\n const insertUserMessage = chatTurn.shouldInsertUserMessage && (auth.insertUserMessage ?? true)\n // Name the row this turn is anchored to. Insert and reuse are mutually\n // exclusive (`shouldInsertUserMessage` is false exactly when a reusable\n // row was found), so one source or the other — never both, never a\n // guess. Products used to re-derive this by decorating the store and\n // falling back to the newest row, which mis-resolves under sub-second\n // same-thread turns.\n let userMessageId: string | null = chatTurn.reusedUserMessageId ?? null\n if (insertUserMessage) {\n userMessageId = rowIdOf(\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts, mentions),\n }),\n )\n }\n produceArgs = { ...produceArgs, userMessageId }\n\n // Domain-readiness gate: may short-circuit with the product's own\n // response before the producer runs. The user row above is kept (a real\n // user turn); the gate's response is the assistant side of it.\n if (options.contextGate) {\n const gate = await options.contextGate(produceArgs)\n if (gate.proceed === 'handoff') {\n await releaseLock()\n return gate.response\n }\n if (!gate.proceed) {\n await releaseLock()\n // A gated turn is still a TURN, and until now it was the one answer\n // path that fired no lifecycle hook at all — `turnStarted` is set\n // further down, so an early return here left telemetry with no record\n // that anything happened. A product whose gate answers everything\n // therefore looks IDLE rather than broken, which is indistinguishable\n // from healthy on every dashboard.\n //\n // Only the LIFECYCLE hooks fire (telemetry, errors swallowed); the\n // billing/persistence `onTurnComplete` deliberately does not, because\n // no model ran and no assistant row was written. `gated` marks the\n // completion so a consumer counts it without mistaking it for a model\n // turn that produced nothing.\n gatedTurn = true\n turnStartedAtMs = Date.now()\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: turnStartedAtMs,\n })\n } catch (err) {\n log('[chat-routes] lifecycle.onTurnStart failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n await fireTerminalLifecycle(false, undefined)\n return gate.response\n }\n }\n\n // Observe + optionally augment the assembled producer input.\n if (options.beforeTurn) {\n const patch = await options.beforeTurn(produceArgs)\n if (patch) produceArgs = { ...produceArgs, ...patch }\n }\n\n // Durability tap: every engine event buffers (coalesced) so a dropped\n // client replays the tail. Live delivery rides the Response body, not the\n // tap, so `write` is intentionally absent.\n const tap = createBufferedTurnTap({\n store: options.turnStore,\n turnId: turnStreamId,\n scopeId: payload.threadId,\n coalesce: options.coalesceTurnEvents ?? coalesceDeltas,\n })\n const turnMarker = { type: 'turn', turnId: turnStreamId }\n await tap.onEvent(turnMarker)\n\n // Durable projection: the turn buffer above serves LIVE reconnect; this\n // keeps the persisted transcript at most one cadence interval behind, so\n // a viewer arriving after the buffer's (deliberately short) hot window\n // reads the in-flight answer from storage instead of an empty thread.\n // Row identity is the turn's own `executionId`, so a re-entered turn\n // patches the row a previous attempt started instead of duplicating it.\n if (draftTuning) {\n draft = createAssistantDraftWriter({\n ...draftTuning,\n store: draftStore,\n threadId: payload.threadId,\n messageId: options.draftMessageId\n ? options.draftMessageId({ identity, executionId, threadId: payload.threadId })\n : assistantRowIdForTurn(executionId),\n snapshot: () => {\n if (!producer) return null\n return {\n content: producer.finalText(),\n ...(producer.draftParts ? { parts: producer.draftParts() } : {}),\n ...(producer.usage ? { usage: producer.usage() } : {}),\n ...(producer.model ? { model: producer.model } : {}),\n }\n },\n ...(options.transformFinalText ? { transformText: options.transformFinalText } : {}),\n log,\n })\n }\n\n turnStartedAtMs = Date.now()\n turnStarted = true\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: turnStartedAtMs,\n })\n } catch (err) {\n log('[chat-routes] lifecycle.onTurnStart failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n const result = handleChatTurn({\n identity,\n waitUntil: ctx?.waitUntil,\n log,\n hooks: {\n // The engine wants a synchronous producer; box resolution is async —\n // defer it into the generator's first pull.\n produce: () => ({\n stream: (async function* () {\n producer = await options.produce(produceArgs)\n let source: AsyncIterable<ChatRouteEvent> = producer.stream\n if (ctx?.cancelOnDisconnect) {\n source = abortOnSignal(source, request.signal)\n }\n if (options.onRawEvent) {\n source = tapRawEvents(source, (event) => options.onRawEvent!(event, context), log)\n }\n if (options.heartbeat) {\n source = withStreamHeartbeat(source, options.heartbeat.intervalMs, options.heartbeat.event)\n }\n for await (const event of source) yield event\n })(),\n finalText: () => producer?.finalText() ?? '',\n }),\n onEvent: async (event) => {\n if (event.type === 'session.run.failed' || event.type === 'error') {\n runFailed = true\n lastFailureData = event.data\n }\n await tap.onEvent(event)\n // Synchronous bookkeeping; the write it may start is fire-and-\n // forget, so store latency never back-pressures the live stream.\n draft?.notify(event)\n if (options.onEvent) await options.onEvent(event, context)\n },\n ...(options.transformFinalText ? { transformFinalText: options.transformFinalText } : {}),\n persistAssistantMessage: async ({ finalText }) => {\n if (ctx?.cancelOnDisconnect && request.signal.aborted) {\n await draft?.discard()\n assistantMessageId = null\n return\n }\n // The typed boundary: stream-normalizer records → stored vocabulary\n // (validating projection owned by /chat-store — no cast here). The\n // scalar `finalText` arrives already transformed by the engine; the\n // producer's text PARTS are raw, so the same transform must run over\n // each text segment before persistence or a redaction (legal PII)\n // leaks at rest through message.parts.\n const rawParts = producer?.assistantParts ? producer.assistantParts() : undefined\n const projected =\n rawParts && options.transformFinalText\n ? await Promise.all(\n rawParts.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await options.transformFinalText!(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : rawParts\n const parts = projected ? toChatMessageParts(projected) : undefined\n if (!finalText.trim() && (!parts || parts.length === 0)) {\n // Empty turn: today this leaves no assistant row at all, so a\n // draft row started earlier is retracted, not left behind.\n await draft?.discard()\n // Read the writer rather than assuming `null`: `discard` is a\n // no-op on a store without `deleteMessage` (drafting needs only\n // `updateMessage`), and there the draft row genuinely survives.\n assistantMessageId = draft?.rowId() ?? null\n return\n }\n const usage = producer?.usage?.() ?? {}\n const attribution = producer?.modelAttribution?.()\n const values = {\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(attribution?.requestedModel ? { requestedModel: attribution.requestedModel } : {}),\n ...(attribution?.servedModel ? { servedModel: attribution.servedModel } : {}),\n ...(attribution?.servedProvider ? { servedProvider: attribution.servedProvider } : {}),\n ...(attribution?.servedSource ? { servedSource: attribution.servedSource } : {}),\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\n }\n // ONE row per turn either way. With drafting, `finalize` settles\n // any in-flight draft and then insert-or-patches the same\n // deterministic id — so the row this turn ends with is identical to\n // the one the single-write path produces. Without it, today's\n // append is untouched.\n if (draft) {\n await draft.finalize(values)\n assistantMessageId = draft.rowId() ?? null\n return\n }\n assistantMessageId = rowIdOf(\n await options.store.appendMessage({\n threadId: payload.threadId,\n role: 'assistant',\n ...values,\n }),\n )\n },\n ...(options.onTurnComplete\n ? {\n // Wired into the engine's completion hook, which fires only when\n // the stream ended without throwing. A terminal error EVENT\n // (not a throw) still lands here — so surface `runFailed` so the\n // product skips billing an errored turn instead of marking it\n // complete with empty text.\n onTurnComplete: ({ identity: turnIdentity, finalText }: { identity: ChatTurnIdentity; finalText: string }) => {\n // Read AFTER the drain, so the model reported to billing is\n // the one that actually served — a fallback included.\n const failoverInfo = producer?.modelFailover?.()\n const attribution = producer?.modelAttribution?.()\n return options.onTurnComplete!({\n identity: turnIdentity,\n finalText,\n context,\n failed: runFailed,\n assistantMessageId: assistantRowId(),\n ...(runFailed ? { failureReason: failureReasonOf(lastFailureData) } : {}),\n ...(producer?.model ? { model: producer.model } : {}),\n ...(attribution?.requestedModel ? { requestedModel: attribution.requestedModel } : {}),\n ...(attribution?.servedModel ? { servedModel: attribution.servedModel } : {}),\n ...(attribution?.servedProvider ? { servedProvider: attribution.servedProvider } : {}),\n ...(attribution?.servedSource ? { servedSource: attribution.servedSource } : {}),\n ...(failoverInfo ? { modelFailover: failoverInfo } : {}),\n })\n },\n }\n : {}),\n ...(options.traceFlush ? { traceFlush: () => options.traceFlush!(context) } : {}),\n },\n })\n\n // Tee: one branch to the live client, one drained under waitUntil so the\n // turn (and its buffering via onEvent) runs to completion after a client\n // drop — the engine body executes as it is pulled.\n const [clientBody, drainBody] = result.body.tee()\n const drained = (async () => {\n const reader = drainBody.getReader()\n let drainError: unknown\n try {\n for (;;) {\n const { done } = await reader.read()\n if (done) break\n }\n } catch (err) {\n drainError = err\n log('[chat-routes] turn drain failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n const failed = runFailed || drainError !== undefined\n // Settle any in-flight draft INSIDE the waitUntil-tracked drain. On the\n // path where the producer throws, `persistAssistantMessage` never runs\n // to close the writer, and an unawaited write would race the isolate's\n // teardown — leaving a torn row instead of a clean partial one for a\n // re-entered turn to adopt.\n if (ctx?.cancelOnDisconnect && request.signal.aborted) {\n await draft?.discard()\n } else {\n await draft?.close()\n }\n try {\n await tap.done(failed ? 'error' : 'complete')\n } catch (err) {\n log('[chat-routes] turn buffer finalize failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n await fireTerminalLifecycle(failed, drainError)\n await releaseLock()\n })()\n if (ctx?.waitUntil) ctx.waitUntil(drained)\n else void drained.catch(() => {})\n\n // Announce the replay handle in headers and body before the engine's first event.\n const encoder = new TextEncoder()\n const marker = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(encoder.encode(`${JSON.stringify(turnMarker)}\\n`))\n controller.close()\n },\n })\n const body = concatStreams([marker, clientBody])\n\n return new Response(body, {\n headers: {\n 'Content-Type': result.contentType,\n 'Cache-Control': 'no-cache',\n 'X-Turn-Id': turnStreamId,\n },\n })\n } catch (err) {\n // A throw before the turn began streaming (user-insert, gate, beforeTurn,\n // lifecycle-start, tap setup, engine construction, tee). If the turn had\n // already started, settle the lifecycle with `onTurnError` (close the\n // span) — the drain never ran to do it. Then release the lock, propagate.\n if (turnStarted) await fireTerminalLifecycle(true, err)\n await releaseLock()\n throw err\n }\n }\n\n async function replay(request: Request, params: { turnId: string }): Promise<Response> {\n const turnId = params.turnId?.trim()\n if (!turnId) return Response.json({ error: 'Missing turnId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'replay', turnId })\n if (!auth.ok) return auth.response\n\n const fromSeqRaw = new URL(request.url).searchParams.get('fromSeq')\n const fromSeq = fromSeqRaw ? Math.max(0, Math.trunc(Number(fromSeqRaw)) || 0) : 0\n\n const encoder = new TextEncoder()\n const events = replayTurnEvents({\n store: options.turnStore,\n turnId,\n fromSeq,\n ...(options.replay?.pollMs !== undefined ? { pollMs: options.replay.pollMs } : {}),\n ...(options.replay?.timeoutMs !== undefined ? { timeoutMs: options.replay.timeoutMs } : {}),\n })\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n const { done, value } = await events.next()\n if (done) {\n controller.close()\n return\n }\n // Stamp the buffer ordinal so a reconnecting client resumes from\n // `?fromSeq=<lastSeq>` instead of refetching the turn from 0 and\n // re-applying every delta onto already-rendered state.\n controller.enqueue(encoder.encode(`${stampReplaySeq(value)}\\n`))\n },\n cancel() {\n void events.return(undefined)\n },\n })\n return new Response(body, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n },\n })\n }\n\n async function running(request: Request): Promise<Response> {\n const threadId = new URL(request.url).searchParams.get('threadId')?.trim()\n if (!threadId) return Response.json({ error: 'Missing threadId' }, { status: 400 })\n const auth = await options.authorize({ request, intent: 'running', threadId })\n if (!auth.ok) return auth.response\n // `listRunning` is optional on the store; a store that cannot enumerate\n // running turns simply reports none — the client falls back to the persisted\n // transcript, never to a hang.\n const ids = (await options.turnStore.listRunning?.(threadId)) ?? []\n return Response.json({ running: ids })\n }\n\n return {\n turn,\n replay,\n running,\n interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null,\n }\n}\n\n/** Sequential concat of byte streams (marker line, then the engine body). */\nfunction concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const next = streams[index++]\n if (!next) {\n controller.close()\n return\n }\n reader = next.getReader()\n }\n const { done, value } = await reader.read()\n if (done) {\n reader = null\n continue\n }\n controller.enqueue(value)\n return\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n for (const stream of streams.slice(index)) await stream.cancel(reason)\n },\n })\n}\n\n/**\n * Stop a producer pull as soon as an opted-in caller disconnects.\n * `AsyncIterator.return()` alone cannot interrupt a pending `next()` call, so\n * race each pull with the request signal and close the source in `finally`.\n */\nasync function* abortOnSignal<T>(\n source: AsyncIterable<T>,\n signal: AbortSignal,\n): AsyncGenerator<T, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n for (;;) {\n const next = await nextWithAbort(iterator, signal)\n if (next.done) return\n yield next.value\n }\n } finally {\n await closeIteratorAfterAbort(iterator)\n }\n}\n\nfunction nextWithAbort<T>(\n iterator: AsyncIterator<T>,\n signal: AbortSignal,\n): Promise<IteratorResult<T>> {\n if (signal.aborted) return Promise.reject(new Error('chat turn cancelled'))\n return new Promise((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n if (settled) return\n settled = true\n cleanup()\n reject(new Error('chat turn cancelled'))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n if (signal.aborted) {\n onAbort()\n return\n }\n Promise.resolve()\n .then(() => iterator.next())\n .then(\n (result) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(result)\n },\n (error: unknown) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n\nconst ABORT_CLEANUP_TIMEOUT_MS = 50\n\nasync function closeIteratorAfterAbort<T>(iterator: AsyncIterator<T>): Promise<void> {\n let closing: PromiseLike<unknown> | undefined\n try {\n const result = iterator.return?.()\n if (result) closing = Promise.resolve(result)\n } catch {\n return\n }\n if (!closing) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.resolve(closing).catch(() => undefined),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, ABORT_CLEANUP_TIMEOUT_MS)\n }),\n ])\n } finally {\n if (timeout !== undefined) clearTimeout(timeout)\n }\n}\n","import type { SandboxStreamEvent } from '../sandbox/index'\nimport type { ChatTurnExecutionLimits, ChatTurnRoutes } from './turn-routes'\nimport { chatTurnRequestInit, type ChatTurnRequestPayload } from './wire'\n\nexport interface StreamChatRouteAsSandboxOptions {\n routes: ChatTurnRoutes\n request: Request\n payload: ChatTurnRequestPayload\n waitUntil?: (promise: Promise<unknown>) => void\n /** Stop forwarding when the API client disconnects. The persisted turn continues. */\n signal?: AbortSignal\n /** Limits authenticated by the gateway and forwarded to the producer. */\n executionLimits?: ChatTurnExecutionLimits\n}\n\ninterface ParsedChatRouteEvent {\n type?: string\n data?: Record<string, unknown>\n text?: string\n usage?: Record<string, unknown>\n toolName?: string\n}\n\ntype GatewayUsageUpdate = NonNullable<NonNullable<SandboxStreamEvent['data']>['usage']>\n\n/**\n * Drive the normal persisted chat route and expose its events to an\n * agent-gateway sandbox adapter. The route remains the only turn owner: auth,\n * locking, live delivery, transcript writes, and completion hooks run once.\n */\nexport async function* streamChatRouteAsSandboxEvents(\n options: StreamChatRouteAsSandboxOptions,\n): AsyncGenerator<SandboxStreamEvent> {\n const parentSignal = options.signal ?? options.request.signal\n if (parentSignal.aborted) return\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined\n const stopForwarding = () => void reader?.cancel()\n parentSignal.addEventListener('abort', stopForwarding, { once: true })\n\n const request = new Request(options.request.url, {\n ...chatTurnRequestInit(options.payload),\n headers: options.request.headers,\n })\n request.headers.set('Content-Type', 'application/json')\n\n let complete = false\n try {\n const response = await options.routes.turn(\n request,\n {\n ...(options.waitUntil ? { waitUntil: options.waitUntil } : {}),\n ...(options.executionLimits ? { executionLimits: options.executionLimits } : {}),\n },\n )\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined)\n throw new Error(`chat route rejected the gateway turn (${response.status})`)\n }\n if (!response.body) throw new Error('chat route returned no stream')\n\n reader = response.body.getReader()\n if (parentSignal.aborted) {\n await reader.cancel().catch(() => undefined)\n return\n }\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) {\n complete = true\n buffer += decoder.decode()\n const event = toSandboxEvent(parseEvent(buffer))\n if (event) yield event\n break\n }\n buffer += decoder.decode(chunk.value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const event = toSandboxEvent(parseEvent(line))\n if (event) yield event\n }\n }\n } finally {\n if (!complete) await reader?.cancel().catch(() => undefined)\n reader?.releaseLock()\n parentSignal.removeEventListener('abort', stopForwarding)\n }\n}\n\nfunction parseEvent(line: string): ParsedChatRouteEvent | null {\n if (!line.trim()) return null\n let value: unknown\n try {\n value = JSON.parse(line)\n } catch {\n throw new Error('chat route returned invalid NDJSON')\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('chat route returned a non-object event')\n }\n const event = value as Record<string, unknown>\n if (event.type !== undefined && typeof event.type !== 'string') {\n throw new Error('chat route returned an invalid event type')\n }\n const data = event.data\n if (data !== undefined && (!data || typeof data !== 'object' || Array.isArray(data))) {\n throw new Error('chat route returned invalid event data')\n }\n const dataUsage = data && (data as Record<string, unknown>).usage\n if (dataUsage !== undefined && (!dataUsage || typeof dataUsage !== 'object' || Array.isArray(dataUsage))) {\n throw new Error('chat route returned invalid data.usage')\n }\n if (event.text !== undefined && typeof event.text !== 'string') {\n throw new Error('chat route returned an invalid text event')\n }\n const usage = event.usage\n if (usage !== undefined && (!usage || typeof usage !== 'object' || Array.isArray(usage))) {\n throw new Error('chat route returned invalid usage')\n }\n if (event.toolName !== undefined && typeof event.toolName !== 'string') {\n throw new Error('chat route returned an invalid tool name')\n }\n return {\n ...(typeof event.type === 'string' ? { type: event.type } : {}),\n ...(data ? { data: data as SandboxStreamEvent['data'] } : {}),\n ...(typeof event.text === 'string' ? { text: event.text } : {}),\n ...(usage ? { usage: usage as Record<string, unknown> } : {}),\n ...(typeof event.toolName === 'string' ? { toolName: event.toolName } : {}),\n }\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction aliasedSafeInteger(\n usage: Record<string, unknown>,\n field: string,\n alias?: string,\n): number | undefined {\n const value = usage[field]\n const aliasValue = alias ? usage[alias] : undefined\n for (const candidate of [value, aliasValue]) {\n if (candidate !== undefined && !isNonNegativeSafeInteger(candidate)) {\n throw new Error(`chat route returned invalid usage.${field}`)\n }\n }\n if (value !== undefined && aliasValue !== undefined && value !== aliasValue) {\n throw new Error(`chat route returned conflicting usage.${field}`)\n }\n return (value ?? aliasValue) as number | undefined\n}\n\nfunction aliasedNonNegativeNumber(\n usage: Record<string, unknown>,\n field: string,\n alias?: string,\n): number | undefined {\n const value = usage[field]\n const aliasValue = alias ? usage[alias] : undefined\n for (const candidate of [value, aliasValue]) {\n if (\n candidate !== undefined &&\n (typeof candidate !== 'number' || !Number.isFinite(candidate) || candidate < 0)\n ) {\n throw new Error(`chat route returned invalid usage.${field}`)\n }\n }\n if (value !== undefined && aliasValue !== undefined && value !== aliasValue) {\n throw new Error(`chat route returned conflicting usage.${field}`)\n }\n return (value ?? aliasValue) as number | undefined\n}\n\n/** Preserve each measured field without inventing the fields the route lacks. */\nfunction providerUsageUpdate(value: unknown): GatewayUsageUpdate | null {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null\n const source = value as Record<string, unknown>\n const usage: GatewayUsageUpdate = {}\n const inputTokens = aliasedSafeInteger(source, 'inputTokens', 'promptTokens')\n const outputTokens = aliasedSafeInteger(source, 'outputTokens', 'completionTokens')\n const reasoningTokens = aliasedSafeInteger(source, 'reasoningTokens')\n const toolTokens = aliasedSafeInteger(source, 'toolTokens')\n const toolCallCount = aliasedSafeInteger(source, 'toolCallCount')\n const providerCostUsd = aliasedNonNegativeNumber(source, 'providerCostUsd', 'costUsd')\n if (inputTokens !== undefined) usage.inputTokens = inputTokens\n if (outputTokens !== undefined) usage.outputTokens = outputTokens\n if (reasoningTokens !== undefined) usage.reasoningTokens = reasoningTokens\n if (toolTokens !== undefined) usage.toolTokens = toolTokens\n if (toolCallCount !== undefined) usage.toolCallCount = toolCallCount\n if (providerCostUsd !== undefined) usage.providerCostUsd = providerCostUsd\n if (source.budgetEnforced !== undefined) {\n if (typeof source.budgetEnforced !== 'boolean') {\n throw new Error('chat route returned invalid usage.budgetEnforced')\n }\n usage.budgetEnforced = source.budgetEnforced\n }\n return Object.keys(usage).length > 0 ? usage : null\n}\n\n/** Translate the app route's producer vocabulary to the gateway stream shape. */\nfunction toSandboxEvent(event: ParsedChatRouteEvent | null): SandboxStreamEvent | null {\n if (!event) return null\n\n // `createChatTurnRoutes` emits flattened text events. The gateway's adapter\n // contract uses the sandbox's canonical part-update shape instead.\n if (event.type === 'text') {\n if (event.text === undefined) throw new Error('chat route text event had no text')\n return {\n type: 'message.part.updated',\n data: { part: { type: 'text' }, delta: event.text },\n }\n }\n\n // Reasoning is persisted by the app route but is not public API output.\n // Dropping it also prevents internal thought text from crossing the paid\n // gateway boundary.\n if (event.type === 'reasoning') return null\n\n // Preserve measured fields even when the app route cannot prove a complete\n // provider-enforced receipt. The gateway fills only absent legacy fields and\n // marks that completed receipt as not provider-enforced.\n if (event.type === 'usage' || event.usage || event.data?.usage) {\n const usage = providerUsageUpdate(event.usage ?? event.data?.usage)\n if (!usage) return null\n return { type: 'usage', data: { usage } }\n }\n\n // A producer can announce the same tool call twice while its arguments fill\n // in. The terminal tool result occurs once, so count that event instead.\n if (event.type === 'tool_result') {\n if (!event.toolName) throw new Error('chat route tool result had no tool name')\n return { type: 'tool_result', data: { tool: { name: event.toolName } } }\n }\n\n if (event.type === 'input-required' && !event.data?.inputRequired) {\n const prompt = typeof event.data?.prompt === 'string' ? event.data.prompt : undefined\n return {\n type: 'input-required',\n data: { inputRequired: prompt ? { prompt } : {} },\n }\n }\n\n return {\n ...(event.type ? { type: event.type } : {}),\n ...(event.data ? { data: event.data as SandboxStreamEvent['data'] } : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiLA,IAAM,sBAA2C,oBAAI,IAAI;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,sBAAsB;AAC5B,IAAM,wBAAwB;AAC9B,IAAM,sCAAsC;AAGrC,SAAS,oBAAoB,OAAoC;AACtE,SAAO,OAAO,OAAO,SAAS,YAAY,oBAAoB,IAAI,MAAM,IAAI;AAC9E;AAKA,SAAS,mBAAmB,MAA+B,UAA2C;AACpG,MAAI,YAAY,EAAG,QAAO;AAC1B,M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,EACF;AAEA,SAAO;AAAA,IACL,GAAI,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI,CAAC;AAAA,IACzC,GAAI,MAAM,OAAO,EAAE,MAAM,MAAM,KAAmC,IAAI,CAAC;AAAA,EACzE;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/stream/turn-buffer.ts"],"sourcesContent":["/**\n * Resumable chat turns — the router-path answer to \"streams resume on\n * disconnect\" (issue #27). A turn's loop events are teed into a store as they\n * stream; the turn keeps running under `ctx.waitUntil` when the client drops;\n * a reconnecting client replays the buffered tail by sequence number and\n * keeps following until the turn completes.\n *\n * POST /chat/stream → pumpBufferedTurn(...) + live NDJSON\n * GET /chat/stream/:turnId → replayTurnEvents({ fromSeq }) → NDJSON\n *\n * Storage is a structural seam ({@link TurnEventStore}); a D1 implementation\n * ships here because that's what Cloudflare products have (KV is unsuitable:\n * eventually consistent cross-isolate). Per-token deltas would mean hundreds\n * of rows per turn, so consecutive text/reasoning deltas are coalesced within\n * a flush window before they are persisted — replay yields slightly chunkier\n * deltas with identical concatenation.\n */\n\nexport type TurnStatus = 'running' | 'complete' | 'error'\n\n/** A running row is a renewable lease, not permanent truth. If the process\n * driving a turn dies before writing a terminal status, reconnect discovery\n * must eventually stop returning that abandoned row. */\nexport const DEFAULT_RUNNING_TURN_LEASE_MS = 5 * 60_000\n\n/** Keep a healthy turn's lease comfortably ahead of expiry without turning\n * per-token streaming into status-write traffic. */\nexport const DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS = 30_000\n\n/** Represent a buffered turn event with a sequence number and serialized event data */\nexport interface BufferedTurnEvent {\n seq: number\n /** The serialized event line (JSON string, no trailing newline). */\n event: string\n}\n\n/** Manage and query turn events and their lifecycle statuses within a scoped event store */\nexport interface TurnEventStore {\n append(turnId: string, events: BufferedTurnEvent[]): Promise<void>\n read(turnId: string, fromSeq: number): Promise<BufferedTurnEvent[]>\n /** Record turn lifecycle. `scopeId` (a thread/session id) is optional and lets\n * {@link TurnEventStore.listRunning} rediscover this turn after a client reload\n * loses the turnId; stores that don't track scope ignore it. */\n setStatus(turnId: string, status: TurnStatus, scopeId?: string): Promise<void>\n getStatus(turnId: string): Promise<TurnStatus | null>\n /** Unexpired running turnIds for a scope, newest first — so a reloaded client\n * (clientRunId lost) can find and resume the in-flight turn without reviving\n * a row abandoned by a dead process. Optional: a store records it only if\n * `setStatus` was given a `scopeId`. */\n listRunning?(scopeId: string): Promise<string[]>\n /** Explicitly remove one turn's events and status. Optional so existing\n * custom stores remain source-compatible; the built-in D1 and memory stores\n * provide it. */\n deleteTurn?(turnId: string): Promise<void>\n /** Remove terminal turns whose status was updated before `before` (Unix\n * milliseconds or a Date). Running turns are never eligible. */\n pruneTerminalTurns?(before: number | Date): Promise<number>\n}\n\n/** Configure running-turn lease evaluation. The clock is injectable so store\n * contract tests do not sleep. Keep the default in production unless a\n * deployment also tunes the buffer's renewal interval. */\nexport interface TurnEventStoreOptions {\n runningTurnLeaseMs?: number\n now?: () => number\n}\n\n// ── coalescing ────────────────────────────────────────────────────────────\n\ntype AnyRecord = Record<string, unknown>\n\nfunction deltaTypeOf(ev: unknown): 'text' | 'reasoning' | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? (e.event as AnyRecord | undefined) : e) as AnyRecord | undefined\n if (!inner || typeof inner !== 'object') return null\n if ((inner.type === 'text' || inner.type === 'reasoning') && typeof inner.text === 'string') {\n return inner.type\n }\n return null\n}\n\n/** Merge consecutive text/reasoning deltas of the same type into one event.\n * Concatenation-preserving: replaying the coalesced stream produces the same\n * accumulated text as the original. */\nexport function coalesceDeltas(events: unknown[]): unknown[] {\n const out: unknown[] = []\n for (const ev of events) {\n const type = deltaTypeOf(ev)\n const prev = out[out.length - 1]\n if (type && prev && deltaTypeOf(prev) === type) {\n const read = (x: unknown): AnyRecord =>\n ((x as AnyRecord).kind === 'event' ? (x as AnyRecord).event : x) as AnyRecord\n const merged = JSON.parse(JSON.stringify(prev)) as AnyRecord\n read(merged).text = String(read(prev).text) + String(read(ev).text)\n out[out.length - 1] = merged\n continue\n }\n out.push(ev)\n }\n return out\n}\n\nfunction asPartUpdate(ev: unknown): { partId: unknown; delta: unknown } | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object' || e.type !== 'message.part.updated') return null\n const data = e.data as AnyRecord | undefined\n if (!data || typeof data !== 'object') return null\n const part = data.part as AnyRecord | undefined\n const partId = part?.id ?? data.partId ?? part?.partId ?? null\n return { partId, delta: data.delta }\n}\n\n/**\n * Coalesce consecutive `message.part.updated` deltas for the SAME part into one\n * event. agent-runtime products stream `ChatStreamEvent` NDJSON\n * (`{type:'message.part.updated', data:{part, delta}}`); pumped through the\n * buffer with the default tool-loop coalescer, every per-token delta persists as\n * its own row because that coalescer never recognizes the shape. Pass this as\n * {@link PumpBufferedTurnOptions.coalesce} instead.\n *\n * Concatenation-preserving for BOTH consumer styles: the merged event keeps the\n * LATEST event's `data.part` (already the cumulative accumulation) and sets\n * `data.delta` to the concatenation of the merged deltas, so a client that\n * appends `delta` and one that reads the cumulative `part` both reconstruct the\n * identical final text.\n */\nexport function coalesceChatStreamEvents(events: unknown[]): unknown[] {\n const out: unknown[] = []\n for (const ev of events) {\n const cur = asPartUpdate(ev)\n const prevEv = out[out.length - 1]\n const prev = prevEv ? asPartUpdate(prevEv) : null\n if (cur && prev && cur.partId != null && cur.partId === prev.partId) {\n // Base the merged row on the latest event (its `part` is the most complete\n // accumulation); carry forward the summed delta.\n const merged = JSON.parse(JSON.stringify(ev)) as AnyRecord\n ;(merged.data as AnyRecord).delta = String(prev.delta ?? '') + String(cur.delta ?? '')\n out[out.length - 1] = merged\n continue\n }\n out.push(ev)\n }\n return out\n}\n\n// ── buffering core (the tap) ────────────────────────────────────────────────\n\n/** Define options for buffering and flushing turn events with optional live client delivery and event coalescing */\nexport interface BufferedTurnOptions {\n store: TurnEventStore\n turnId: string\n /** Deliver one serialized line to the live client. Throwing here (client\n * disconnected) does NOT stop buffering — events keep persisting. */\n write?: (line: string) => Promise<void> | void\n /** Flush buffered events to the store at most this often. Default 400ms. */\n flushIntervalMs?: number\n /** Per-flush coalescer. Default {@link coalesceDeltas} (tool-loop text/reasoning\n * deltas). agent-runtime products streaming `ChatStreamEvent` pass\n * {@link coalesceChatStreamEvents} so per-token deltas don't each persist as a\n * row. Must be concatenation-preserving. */\n coalesce?: (events: unknown[]) => unknown[]\n /** Optional scope (thread/session id) recorded with the turn status, so\n * {@link TurnEventStore.listRunning} can find this turn after a reload. */\n scopeId?: string\n /** How often to renew the running-turn lease while a producer is alive.\n * The timer is backed up by event-driven renewal when a runtime freezes\n * unreferenced timers during remote I/O. Default\n * {@link DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS}. */\n runningTurnRenewIntervalMs?: number\n}\n\n/** A push-driven buffer for a turn whose producer the caller does NOT own. */\nexport interface BufferedTurnTap {\n /** Buffer one event: persist (coalesced, on the flush window) + best-effort\n * live-deliver. Wire to a push source's per-event hook (e.g. agent-runtime\n * `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call. */\n onEvent(raw: unknown): Promise<void>\n /** Settle the turn: final flush + set status. Call after the producer resolves\n * ('complete') or rejects ('error'). 'error' flushes what was produced first. */\n done(status?: Extract<TurnStatus, 'complete' | 'error'>): Promise<void>\n}\n\n/**\n * The buffering core. Sequence-numbers every event, delivers it to `write`\n * (best-effort — a disconnected client never stops buffering), and flushes to\n * the store in coalesced batches. Drives both transports:\n *\n * • {@link pumpBufferedTurn} — when you OWN an `AsyncIterable` producer.\n * • this tap (`onEvent`/`done`) — when the producer owns iteration and only\n * hands you a push callback (agent-runtime `handleChatTurn`'s `hooks.onEvent`\n * + the finished body). Durability stays here in the shell; the engine needs\n * no `TurnEventStore` seam.\n */\nexport function createBufferedTurnTap(opts: BufferedTurnOptions): BufferedTurnTap {\n const flushIntervalMs = opts.flushIntervalMs ?? 400\n const coalesce = opts.coalesce ?? coalesceDeltas\n const startedAt = Date.now()\n let seq = 0\n let clientGone = false\n let pending: unknown[] = []\n let lastFlush = Date.now()\n let started = false\n let settled = false\n let renewalTimer: ReturnType<typeof setTimeout> | undefined\n let renewal: Promise<void> = Promise.resolve()\n let lastRenewedAt = 0\n const runningTurnRenewIntervalMs = Math.max(\n 1,\n opts.runningTurnRenewIntervalMs ?? DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,\n )\n\n function clearRenewalTimer(): void {\n if (renewalTimer !== undefined) clearTimeout(renewalTimer)\n renewalTimer = undefined\n }\n\n function scheduleRenewal(): void {\n if (settled || !opts.scopeId) return\n clearRenewalTimer()\n const elapsedMs = Math.max(0, Date.now() - lastRenewedAt)\n const delayMs = Math.max(1, runningTurnRenewIntervalMs - elapsedMs)\n renewalTimer = setTimeout(() => {\n renewalTimer = undefined\n void renewLease()\n }, delayMs)\n // A deliberately abandoned tap in a Node test must not keep the process\n // alive until the production renewal interval elapses.\n if (typeof renewalTimer === 'object' && 'unref' in renewalTimer) {\n renewalTimer.unref()\n }\n }\n\n async function renewLease(): Promise<void> {\n if (settled || !opts.scopeId) return\n clearRenewalTimer()\n lastRenewedAt = Date.now()\n renewal = renewal\n .then(() => opts.store.setStatus(opts.turnId, 'running', opts.scopeId))\n .catch(() => {})\n await renewal\n scheduleRenewal()\n }\n\n async function flush(): Promise<void> {\n if (pending.length === 0) return\n const batch = coalesce(pending)\n pending = []\n const rows = batch.map((ev) => ({ seq: ++seq, event: JSON.stringify(ev) }))\n await opts.store.append(opts.turnId, rows)\n lastFlush = Date.now()\n }\n\n async function ensureStarted(): Promise<void> {\n if (started) return\n started = true\n await opts.store.setStatus(opts.turnId, 'running', opts.scopeId)\n lastRenewedAt = Date.now()\n scheduleRenewal()\n }\n\n return {\n async onEvent(raw) {\n await ensureStarted()\n // Cloudflare may freeze an unreferenced timer while a producer is\n // awaiting remote I/O. A real event (including the route heartbeat)\n // therefore also renews any lease whose interval has elapsed.\n if (\n opts.scopeId &&\n Date.now() - lastRenewedAt >= runningTurnRenewIntervalMs\n ) {\n await renewLease()\n }\n // Stamp ms-since-turn-start so any stored turn is replayable AND traceable\n // (see ../trace) from the same buffered rows.\n const ev = raw && typeof raw === 'object' ? { ...(raw as Record<string, unknown>), _t: Date.now() - startedAt } : raw\n pending.push(ev)\n if (!clientGone && opts.write) {\n try {\n // Live delivery carries a provisional ordering hint, not the persisted\n // seq (coalescing changes seq assignment); clients resume with the\n // seqs from replay, or 0 for \"everything\".\n await opts.write(JSON.stringify(ev))\n } catch {\n clientGone = true\n }\n }\n if (Date.now() - lastFlush >= flushIntervalMs) await flush()\n },\n async done(status = 'complete') {\n await ensureStarted()\n settled = true\n clearRenewalTimer()\n await renewal\n if (status === 'error') {\n await flush().catch(() => {})\n await opts.store.setStatus(opts.turnId, 'error', opts.scopeId).catch(() => {})\n return\n }\n await flush()\n await opts.store.setStatus(opts.turnId, 'complete', opts.scopeId)\n },\n }\n}\n\n// ── pump (producer side) ──────────────────────────────────────────────────\n\n/** Define options to pump data from an asynchronous iterable source with buffered turn control */\nexport interface PumpBufferedTurnOptions extends BufferedTurnOptions {\n source: AsyncIterable<unknown>\n}\n\n/**\n * Drive a turn to completion regardless of the live client, when you OWN the\n * producer as an `AsyncIterable`. A thin driver over {@link createBufferedTurnTap}.\n * Returns a promise that resolves when the turn finishes — hand it to\n * `ctx.waitUntil` so a disconnect can't kill the turn. Never rejects on\n * client-write failure; a source error marks the turn 'error' (after flushing\n * what was produced) and rethrows.\n */\nexport async function pumpBufferedTurn(opts: PumpBufferedTurnOptions): Promise<void> {\n const tap = createBufferedTurnTap(opts)\n try {\n for await (const raw of opts.source) await tap.onEvent(raw)\n await tap.done('complete')\n } catch (err) {\n await tap.done('error')\n throw err\n }\n}\n\n// ── replay (consumer side) ────────────────────────────────────────────────\n\n/** Define options for replaying turn events with control over sequence, polling, and timeout */\nexport interface ReplayTurnEventsOptions {\n store: TurnEventStore\n turnId: string\n /** Replay strictly after this sequence number (0 = from the beginning). */\n fromSeq?: number\n /** Poll cadence while the turn is still running. Default 500ms. */\n pollMs?: number\n /** Give up following a 'running' turn after this long. Default 120s. */\n timeoutMs?: number\n}\n\n/**\n * Yield buffered events after `fromSeq`, then keep polling while the turn is\n * still 'running' until it completes, errors, or times out. Terminates with a\n * final `{seq: -1, event: '{\"type\":\"turn_status\",...}'}` marker so clients\n * know why the replay ended.\n */\nexport async function* replayTurnEvents(opts: ReplayTurnEventsOptions): AsyncGenerator<BufferedTurnEvent> {\n const pollMs = opts.pollMs ?? 500\n const timeoutMs = opts.timeoutMs ?? 120_000\n let cursor = opts.fromSeq ?? 0\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n const batch = await opts.store.read(opts.turnId, cursor)\n for (const row of batch) {\n cursor = Math.max(cursor, row.seq)\n yield row\n }\n const status = await opts.store.getStatus(opts.turnId)\n if (status !== 'running') {\n // Writers flush before publishing terminal status; include rows committed after the first read.\n yield* await opts.store.read(opts.turnId, cursor)\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: status ?? 'unknown' }) }\n return\n }\n if (Date.now() >= deadline) {\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: 'timeout' }) }\n return\n }\n await new Promise((r) => setTimeout(r, pollMs))\n }\n}\n\n/**\n * Serialize a replayed row for the wire, stamping the buffer ordinal ONTO the\n * line so a reconnecting client can continue from `?fromSeq=<lastSeq>`.\n *\n * The seq lives on the {@link BufferedTurnEvent} row wrapper, not inside the\n * serialized event — `flush()` builds `{seq: ++seq, event: JSON.stringify(ev)}`.\n * A route that enqueues `row.event` alone therefore emits lines with no seq at\n * all, and every client cursor silently pins to 0: each reconnect refetches the\n * whole turn and re-applies every delta onto already-rendered state. This\n * restores the contract `web-react/chat-stream` already documents (\"replayed\n * lines carry an extra `seq` — transparently ignored\").\n *\n * The `{seq: -1}` `turn_status` sentinel is passed through unstamped: it is a\n * terminator, not a cursor position, and stamping it would move a client's\n * cursor to -1.\n *\n * Fail-soft by construction — a line that is not a JSON object passes through\n * verbatim. A stamping bug must degrade to today's behaviour, never break a\n * replay.\n */\nexport function stampReplaySeq(row: BufferedTurnEvent): string {\n if (row.seq <= 0) return row.event\n const line = row.event\n // Cheap splice instead of parse+stringify: these rows are already canonical\n // JSON objects from `JSON.stringify`, and replay is a hot per-event path.\n if (line.charCodeAt(0) !== 0x7b /* { */) return line\n const rest = line.slice(1)\n return rest.trimStart().startsWith('}')\n ? `{\"seq\":${row.seq}${rest}`\n : `{\"seq\":${row.seq},${rest}`\n}\n\n// ── D1 store ──────────────────────────────────────────────────────────────\n\n/** A bound D1 statement used by the turn store. */\nexport interface D1BoundForTurns {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n first<T = Record<string, unknown>>(): Promise<T | null>\n}\n\n/** Minimal structural D1 contract (Cloudflare `D1Database` satisfies it). */\nexport interface D1LikeForTurns {\n prepare(sql: string): {\n bind(...values: unknown[]): D1BoundForTurns\n }\n /** D1's only atomic primitive. Retention refuses a driver without it rather\n * than deleting events and status in separate, reorderable requests. */\n batch?(statements: D1BoundForTurns[]): Promise<unknown[]>\n}\n\nfunction normalizeTurnCutoff(before: number | Date): { milliseconds: number; iso: string } {\n const milliseconds = before instanceof Date ? before.getTime() : before\n if (!Number.isFinite(milliseconds)) {\n throw new RangeError('turn retention cutoff must be a finite Unix-millisecond timestamp or a valid Date')\n }\n const date = new Date(milliseconds)\n if (!Number.isFinite(date.getTime())) {\n throw new RangeError('turn retention cutoff is outside the supported Date range')\n }\n return { milliseconds, iso: date.toISOString() }\n}\n\nasync function runAtomicTurnBatch(\n db: D1LikeForTurns,\n statements: D1BoundForTurns[],\n): Promise<unknown[]> {\n if (typeof db.batch !== 'function') {\n throw new Error('turn retention requires D1 batch() for atomic deletion')\n }\n return db.batch(statements)\n}\n\nfunction changesFromD1Result(result: unknown): number {\n if (!result || typeof result !== 'object') return 0\n const meta = (result as { meta?: unknown }).meta\n if (meta && typeof meta === 'object') {\n const changes = (meta as { changes?: unknown }).changes\n if (typeof changes === 'number' && Number.isFinite(changes)) return changes\n }\n const changes = (result as { changes?: unknown }).changes\n return typeof changes === 'number' && Number.isFinite(changes) ? changes : 0\n}\n\n/** Schema for the D1 store — append to the product's migrations. */\nexport const TURN_EVENTS_MIGRATION_SQL = `\nCREATE TABLE IF NOT EXISTS turn_events (\n turnId TEXT NOT NULL,\n seq INTEGER NOT NULL,\n event TEXT NOT NULL,\n PRIMARY KEY (turnId, seq)\n);\nCREATE TABLE IF NOT EXISTS turn_status (\n turnId TEXT PRIMARY KEY,\n status TEXT NOT NULL,\n scopeId TEXT,\n updatedAt TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_turn_status_scope ON turn_status (scopeId, status);\nCREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);\n`\n\n/** For deployments whose `turn_status` table predates `scopeId`/`listRunning` —\n * run once to add the column (the CREATE above already includes it for new\n * deployments). SQLite ignores a duplicate-add error if already applied. */\nexport const TURN_STATUS_SCOPE_MIGRATION_SQL = `ALTER TABLE turn_status ADD COLUMN scopeId TEXT;`\n\n/** For deployments that already have the turn tables, add the index used by\n * terminal-turn retention without rerunning the table migration. */\nexport const TURN_STATUS_RETENTION_MIGRATION_SQL = 'CREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);'\n\n/** Resolve a TurnEventStore that appends and reads turn events using a D1-like database interface */\n/** 100 D1 variables per statement, three per row. */\nconst D1_APPEND_CHUNK = 33\n\nexport function createD1TurnEventStore(\n db: D1LikeForTurns,\n options: TurnEventStoreOptions = {},\n): TurnEventStore {\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, events) {\n if (!events.length) return\n // One multi-row insert per flush window keeps write volume bounded, but\n // D1 caps a statement at 100 bound variables, so a burst of more than 33\n // events (a subagent finishing, a long tool result) failed the whole\n // flush with `D1_ERROR: too many SQL variables` and killed the turn.\n // Rows are appended in order across chunks; a partial failure leaves a\n // prefix, which the ordered `seq` column already tolerates on replay.\n for (let start = 0; start < events.length; start += D1_APPEND_CHUNK) {\n const chunk = events.slice(start, start + D1_APPEND_CHUNK)\n const placeholders = chunk.map(() => '(?, ?, ?)').join(', ')\n const values = chunk.flatMap((e) => [turnId, e.seq, e.event])\n await db.prepare(`INSERT OR IGNORE INTO turn_events (turnId, seq, event) VALUES ${placeholders}`).bind(...values).run()\n }\n },\n async read(turnId, fromSeq) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? AND seq > ? ORDER BY seq ASC')\n .bind(turnId, fromSeq)\n .all<{ seq: number; event: string }>()\n return results\n },\n async setStatus(turnId, status, scopeId) {\n // COALESCE preserves a scopeId set on the initial 'running' write when a\n // later 'complete'/'error' write passes none.\n await db\n .prepare(\n 'INSERT INTO turn_status (turnId, status, scopeId, updatedAt) VALUES (?, ?, ?, ?) ON CONFLICT(turnId) DO UPDATE SET status = excluded.status, scopeId = COALESCE(excluded.scopeId, turn_status.scopeId), updatedAt = excluded.updatedAt',\n )\n .bind(turnId, status, scopeId ?? null, new Date(now()).toISOString())\n .run()\n },\n async getStatus(turnId) {\n const row = await db.prepare('SELECT status FROM turn_status WHERE turnId = ?').bind(turnId).first<{ status: TurnStatus }>()\n return row?.status ?? null\n },\n async listRunning(scopeId) {\n const { results } = await db\n .prepare(\n \"SELECT turnId FROM turn_status WHERE scopeId = ? AND status = 'running' AND updatedAt >= ? ORDER BY updatedAt DESC, rowid DESC\",\n )\n .bind(scopeId, new Date(now() - runningTurnLeaseMs).toISOString())\n .all<{ turnId: string }>()\n return results.map((r) => r.turnId)\n },\n async deleteTurn(turnId) {\n await runAtomicTurnBatch(db, [\n db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId),\n db.prepare('DELETE FROM turn_status WHERE turnId = ?').bind(turnId),\n ])\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before)\n const terminalBefore = \"status IN ('complete', 'error') AND updatedAt < ?\"\n const results = await runAtomicTurnBatch(db, [\n db\n .prepare(\n `DELETE FROM turn_events WHERE turnId IN (SELECT turnId FROM turn_status WHERE ${terminalBefore})`,\n )\n .bind(cutoff.iso),\n db.prepare(`DELETE FROM turn_status WHERE ${terminalBefore}`).bind(cutoff.iso),\n ])\n return changesFromD1Result(results[1])\n },\n }\n}\n\n/** In-memory store for tests and keyless local dev. */\nexport function createMemoryTurnEventStore(\n options: TurnEventStoreOptions = {},\n): TurnEventStore {\n const events = new Map<string, BufferedTurnEvent[]>()\n const status = new Map<string, TurnStatus>()\n const scopes = new Map<string, string>()\n const order: string[] = []\n const updatedAt = new Map<string, number>()\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, rows) {\n const list = events.get(turnId) ?? []\n list.push(...rows)\n events.set(turnId, list)\n },\n async read(turnId, fromSeq) {\n return (events.get(turnId) ?? []).filter((e) => e.seq > fromSeq)\n },\n async setStatus(turnId, s, scopeId) {\n status.set(turnId, s)\n if (scopeId) scopes.set(turnId, scopeId)\n if (!order.includes(turnId)) order.push(turnId)\n updatedAt.set(turnId, now())\n },\n async getStatus(turnId) {\n return status.get(turnId) ?? null\n },\n async listRunning(scopeId) {\n const cutoff = now() - runningTurnLeaseMs\n return order\n .filter(\n (turnId) =>\n status.get(turnId) === 'running' &&\n scopes.get(turnId) === scopeId &&\n (updatedAt.get(turnId) ?? Number.NEGATIVE_INFINITY) >= cutoff,\n )\n .sort((left, right) => {\n const updatedDelta = (updatedAt.get(right) ?? 0) - (updatedAt.get(left) ?? 0)\n return updatedDelta || order.indexOf(right) - order.indexOf(left)\n })\n },\n async deleteTurn(turnId) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n const index = order.indexOf(turnId)\n if (index >= 0) order.splice(index, 1)\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before).milliseconds\n const removable = order.filter((turnId) => {\n const s = status.get(turnId)\n return (s === 'complete' || s === 'error') && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < cutoff\n })\n for (const turnId of removable) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n }\n if (removable.length) {\n const removed = new Set(removable)\n for (let i = order.length - 1; i >= 0; i--) {\n if (removed.has(order[i]!)) order.splice(i, 1)\n }\n }\n return removable.length\n },\n }\n}\n"],"mappings":";AAuBO,IAAM,gCAAgC,IAAI;AAI1C,IAAM,yCAAyC;AA4CtD,SAAS,YAAY,IAA0C;AAC7D,QAAM,IAAI;AACV,MAAI,CAAC,KAAK,OAAO,MAAM,SAAU,QAAO;AACxC,QAAM,QAAS,EAAE,SAAS,UAAW,EAAE,QAAkC;AACzE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,OAAK,MAAM,SAAS,UAAU,MAAM,SAAS,gBAAgB,OAAO,MAAM,SAAS,UAAU;AAC3F,WAAO,MAAM;AAAA,EACf;AACA,SAAO;AACT;AAKO,SAAS,eAAe,QAA8B;AAC3D,QAAM,MAAiB,CAAC;AACxB,aAAW,MAAM,QAAQ;AACvB,UAAM,OAAO,YAAY,EAAE;AAC3B,UAAM,OAAO,IAAI,IAAI,SAAS,CAAC;AAC/B,QAAI,QAAQ,QAAQ,YAAY,IAAI,MAAM,MAAM;AAC9C,YAAM,OAAO,CAAC,MACV,EAAgB,SAAS,UAAW,EAAgB,QAAQ;AAChE,YAAM,SAAS,KAAK,MAAM,KAAK,UAAU,IAAI,CAAC;AAC9C,WAAK,MAAM,EAAE,OAAO,OAAO,KAAK,IAAI,EAAE,IAAI,IAAI,OAAO,KAAK,EAAE,EAAE,IAAI;AAClE,UAAI,IAAI,SAAS,CAAC,IAAI;AACtB;AAAA,IACF;AACA,QAAI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