@tangle-network/agent-app 1.0.8 → 1.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-profiles/d1.js +3 -3
- package/dist/agent-profiles/index.js +3 -3
- package/dist/app-auth/index.js +1 -1
- package/dist/chat-routes/dispatch-parts.d.ts +1 -1
- package/dist/chat-routes/index.js +5 -5
- package/dist/{chunk-7JUQQEQY.js → chunk-532GILWC.js} +2 -2
- package/dist/{chunk-3KJAPMZB.js → chunk-C3JXGK3R.js} +2 -2
- package/dist/{chunk-UOZ4JCFJ.js → chunk-GJMKHY5U.js} +3 -25
- package/dist/chunk-GJMKHY5U.js.map +1 -0
- package/dist/{chunk-7MVMNCRP.js → chunk-IDRATMRZ.js} +5 -5
- package/dist/{chunk-7MVMNCRP.js.map → chunk-IDRATMRZ.js.map} +1 -1
- package/dist/{chunk-2CRRXINH.js → chunk-OJI2H3EZ.js} +13 -27
- package/dist/{chunk-2CRRXINH.js.map → chunk-OJI2H3EZ.js.map} +1 -1
- package/dist/{chunk-UCXB3ZZ3.js → chunk-TJA5ERCP.js} +3 -3
- package/dist/{chunk-VHDBKP3G.js → chunk-WQZCX4IJ.js} +2 -2
- package/dist/email/index.js +1 -1
- package/dist/email/palette.d.ts +23 -30
- package/dist/preset-cloudflare/index.js +2 -2
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +5 -5
- package/dist/sandbox/index.js +4 -4
- package/dist/theme/tokens.css +3 -3
- package/dist/tools/index.js +4 -4
- package/dist/work-product/index.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-UOZ4JCFJ.js.map +0 -1
- /package/dist/{chunk-7JUQQEQY.js.map → chunk-532GILWC.js.map} +0 -0
- /package/dist/{chunk-3KJAPMZB.js.map → chunk-C3JXGK3R.js.map} +0 -0
- /package/dist/{chunk-UCXB3ZZ3.js.map → chunk-TJA5ERCP.js.map} +0 -0
- /package/dist/{chunk-VHDBKP3G.js.map → chunk-WQZCX4IJ.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chat-routes/upload.ts","../src/chat-routes/dispatch-parts.ts","../src/chat-routes/reasoning-clock.ts","../src/chat-routes/router-producer.ts","../src/chat-routes/hybrid-producer.ts","../src/chat-routes/model-failover-stream.ts","../src/chat-routes/sandbox-model-source.ts","../src/chat-routes/sandbox-producer.ts","../src/chat-routes/cancellation.ts","../src/chat-routes/turn-admission.ts","../src/chat-routes/agent-producers.ts","../src/chat-routes/turn-route-contracts.ts","../src/chat-routes/turn-prefetch.ts","../src/chat-routes/turn-execution.ts","../src/chat-routes/native-turn-timing.ts","../src/chat-routes/turn-ownership.ts","../src/chat-routes/route-producer.ts","../src/chat-routes/producer-stream.ts","../src/chat-routes/dispatch-first.ts","../src/chat-routes/turn-event-stream.ts","../src/chat-routes/early-turn-work.ts","../src/chat-routes/default-backend.ts","../src/chat-routes/route-prewarm.ts","../src/chat-routes/turn-routes.ts","../src/chat-routes/gateway-adapter.ts"],"sourcesContent":["/**\n * `createUploadRoute` — the multimodal middle. Accepts multipart file uploads\n * and returns `PromptInputPart`-shaped descriptors the client echoes back on\n * send (`ChatTurnRequestPayload.parts`):\n *\n * ≤ inlineMaxBytes (700 KiB default) → inline `data:` URI part — rides the\n * turn body directly, no sandbox round trip.\n * > inlineMaxBytes → written into the sandbox workspace (base64 through the\n * structural `write` seam — `box.fs` satisfies it) and referenced by\n * `path`. Mandatory two-step: the gateway caps request bodies at ~1 MiB,\n * so a large file can never ride the prompt POST.\n *\n * The sink is structural (no sandbox-SDK import); products pass `box.fs`.\n *\n * @remarks Sole consumer today is the `--chat` scaffold (`create-agent-app\n * --chat` → `template-chat/src/chat.ts`), the reference multimodal path — its\n * inline-`data:`-or-ephemeral-sandbox-workspace split stays the scaffold's\n * proven upload pattern, not a fleet primitive; keep that distinction in mind\n * before widening its surface. Fleet apps with a durable store of their own\n * (KV, or AES-GCM-encrypted R2) no longer need to hand-roll a vault upload\n * route: `createAttachmentUploadRoute` (`./attachment-upload`, agent-app#234)\n * is the shared hardened path for that persistence model — a content-sniffed\n * type gate, two-phase atomic batch writes, and per-kind/aggregate size caps,\n * all seamed through an injected `WriteAttachmentFn`. Point readers there\n * instead of widening this route to cover both models.\n */\n\nimport type { ChatTurnFilePartInput } from './wire'\n\n/** 700 KiB: base64 inflates ~4/3, so an inline part stays comfortably under\n * the ~1 MiB gateway body cap alongside the JSON envelope. */\nexport const UPLOAD_INLINE_MAX_BYTES = 700 * 1024\n\n/** 8 MiB default ceiling per file — one base64 `write` call handles it. Raise\n * it only with a sink that can take the bigger single write. */\nexport const UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024\n\nconst DEFAULT_UPLOAD_DIRECTORY = '/workspace/uploads'\n\nfunction normalizeUploadDirectory(value: string): string | null {\n const withoutTrailingSlash = value.trim().replace(/\\/+$/, '')\n if (!withoutTrailingSlash.startsWith('/') || withoutTrailingSlash.length === 0) return null\n const segments = withoutTrailingSlash.slice(1).split('/')\n if (segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')) return null\n return `/${segments.join('/')}`\n}\n\n/** Structural match of the sandbox SDK's `box.fs` write surface (v0.10.5+:\n * `encoding: 'base64'` is the worker-safe binary path). */\nexport interface SandboxUploadSink {\n write(path: string, content: string, options?: { encoding?: 'utf8' | 'base64' }): Promise<unknown>\n}\n\n/** Resolve upload authorization status and provide upload destination or error response */\nexport type UploadAuthorization =\n | {\n ok: true\n /** Where large files land. Absent/null: only inline uploads are\n * accepted and an over-inline-cap file is rejected with 413. */\n sink?: SandboxUploadSink | null\n /** Per-request override of the workspace directory large files go to. */\n uploadDir?: string\n }\n | { ok: false; response: Response }\n\n/** Define options to authorize uploads and configure file size limits and upload directory */\nexport interface CreateUploadRouteOptions {\n /** Authenticate the caller and resolve the sandbox file sink (usually\n * `ensureWorkspaceSandbox(...)` → `box.fs`). */\n authorize(args: { request: Request }): Promise<UploadAuthorization>\n /** Inline-vs-sandbox threshold. Default {@link UPLOAD_INLINE_MAX_BYTES}. */\n inlineMaxBytes?: number\n /** Hard per-file cap. Default {@link UPLOAD_MAX_FILE_BYTES}. */\n maxFileBytes?: number\n /** Absolute workspace directory for path-ref files.\n * Default `'/workspace/uploads'`. */\n uploadDir?: string\n}\n\n/** One uploaded file, ready for the composer chip and the turn body. */\nexport interface UploadedChatFile {\n id: string\n name: string\n size: number\n mediaType: string\n /** True when the part carries the bytes inline (`data:` URI). */\n inline: boolean\n /** Echo this back verbatim in `ChatTurnRequestPayload.parts`. */\n part: ChatTurnFilePartInput\n}\n\n/** Path-safe file name: basename only, conservative charset, length-capped. */\nexport function sanitizeUploadFilename(name: string): string {\n const base = name.split(/[\\\\/]/).pop() ?? 'file'\n const safe = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '_')\n return (safe || 'file').slice(0, 120)\n}\n\nconst BASE64_CHUNK = 0x8000\n\n/** Convert a Uint8Array of bytes into a base64-encoded string */\nexport function bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK))\n }\n return btoa(binary)\n}\n\nfunction uploadError(status: number, code: string, error: string): Response {\n return Response.json({ code, error }, { status })\n}\n\n/** Create an upload route handler that authorizes requests and processes file uploads with size limits */\nexport function createUploadRoute(options: CreateUploadRouteOptions): (request: Request) => Promise<Response> {\n const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES\n const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES\n\n return async function upload(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (!auth.ok) return auth.response\n const sink = auth.sink ?? null\n const configuredUploadDir = auth.uploadDir ?? options.uploadDir ?? DEFAULT_UPLOAD_DIRECTORY\n\n let form: FormData\n try {\n form = await request.formData()\n } catch {\n return uploadError(400, 'INVALID_UPLOAD', 'Expected a multipart/form-data body with file fields')\n }\n const files: File[] = []\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\n })\n if (files.length === 0) {\n return uploadError(400, 'INVALID_UPLOAD', 'No files in the upload body')\n }\n\n const uploaded: UploadedChatFile[] = []\n for (const file of files) {\n const name = sanitizeUploadFilename(file.name)\n const mediaType = file.type || 'application/octet-stream'\n const partType: ChatTurnFilePartInput['type'] = mediaType.startsWith('image/') ? 'image' : 'file'\n\n if (file.size > maxFileBytes) {\n return uploadError(\n 413,\n 'FILE_TOO_LARGE',\n `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`,\n )\n }\n\n const id = crypto.randomUUID()\n if (file.size <= inlineMaxBytes) {\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: true,\n part: {\n type: partType,\n filename: name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n },\n })\n continue\n }\n\n if (!sink) {\n return uploadError(\n 413,\n 'SANDBOX_REQUIRED',\n `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`,\n )\n }\n const uploadDir = normalizeUploadDirectory(configuredUploadDir)\n if (!uploadDir) {\n return uploadError(\n 500,\n 'INVALID_UPLOAD_DIRECTORY',\n 'uploadDir must be an absolute path without empty, \".\" or \"..\" segments',\n )\n }\n const path = `${uploadDir}/${id}-${name}`\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n await sink.write(path, base64, { encoding: 'base64' })\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: false,\n part: { type: partType, filename: name, mediaType, path },\n })\n }\n\n return Response.json({ files: uploaded })\n }\n}\n","/**\n * `buildDispatchParts` — assemble the `PromptInputPart[]` a turn carrying\n * attachments and/or `@`-mentions dispatches to the sandbox. `parts[0]` is\n * always the full prompt text (typed text plus the attachment + mention pointer\n * blocks); each attachment or mention becomes one media part. An attachment\n * (read from the product store via the injected reader) draws the inline byte\n * budget first; a mention (read from the LIVE box) takes what is left. A file\n * inlines as a `data:` URI when it fits the remaining budget, otherwise uses\n * the in-box file reference supported by the current sandbox prompt contract.\n * Every media part is deduped by its resolved absolute path. This module only\n * produces the parts array; the caller decides when a turn dispatches parts\n * instead of a plain string.\n *\n * Storage-parameterized port of gtm-agent's `dispatch-parts.ts`: the vault\n * default reader is dropped (`readAttachment` is REQUIRED — the product supplies\n * its store adapter), the `GTM_SANDBOX_VAULT_DIR` prefixing becomes the required\n * `resolveAttachmentPath` seam, the `GTM_MULTIMODAL_FORCE_PATH` env fallback\n * becomes an explicit `forcePath` flag, and every budget cap reads an overridable\n * `./wire` constant. Kept behavior-identical for gtm-agent#618 adoption (the\n * demotion math and emitted part shapes reproduce its dispatched prompt bytes).\n */\n\nimport { isWorkspaceFileExportable } from '../web/file-export'\nimport { flattenHistory, type PromptInputPart } from '../sandbox'\nimport {\n statSandboxFileSize,\n readSandboxBinaryBytes,\n type SandboxExecChannel,\n} from '../sandbox/binary-read'\nimport {\n ChatTurnInputError,\n mediaTypeForMentionPath,\n base64WireLen,\n DISPATCH_REQUEST_MAX_BYTES,\n DISPATCH_STRUCTURAL_RESERVE_BYTES,\n DISPATCH_MAX_PARTS,\n type ChatTurnPartInput,\n} from './wire'\nimport { historyContentWithAttachments, type ChatAttachmentPart, type ChatMentionPart } from '../chat-store/parts'\nimport { bytesToBase64 } from './upload'\nimport type { ReadAttachmentFn } from './attachment-store'\nimport { pathToFileURL } from 'node:url'\n\nexport type { PromptInputPart }\n\n/** Resolve the outcome of dispatching parts with success status and corresponding value or error message */\nexport type DispatchPartsOutcome =\n | { succeeded: true; value: PromptInputPart[] }\n | { succeeded: false; error: string }\n\n/** One mention file's size (always) and inline bytes (only when the caller\n * asked for them — a path-only mention never reads its bytes). */\ntype SandboxMentionReadOutcome =\n | { succeeded: true; value: { size: number; base64?: string } }\n | { succeeded: false; error: string }\n\n/** Resolve sandbox mention details by reading from a specified path with optional byte reading */\nexport type ReadSandboxMentionFn = (\n box: SandboxExecChannel,\n absolutePath: string,\n options: { readBytes: boolean },\n) => Promise<SandboxMentionReadOutcome>\n\nfunction byteLen(value: string): number {\n return new TextEncoder().encode(value).length\n}\n\n/**\n * Default mention reader: stats the in-box file (which also proves it still\n * exists — a since-deleted mention fails loud here), then reads its bytes only\n * when the caller wants to inline it. Both hops cross the sandbox exec channel\n * via the substrate's binary-read helpers.\n */\nasync function readSandboxMention(\n box: SandboxExecChannel,\n absolutePath: string,\n options: { readBytes: boolean },\n): Promise<SandboxMentionReadOutcome> {\n const stat = await statSandboxFileSize(box, absolutePath)\n if (!stat.succeeded) {\n return { succeeded: false, error: `mentioned sandbox file missing or unreadable: ${absolutePath} — ${stat.error}` }\n }\n if (!options.readBytes) return { succeeded: true, value: { size: stat.value } }\n\n const read = await readSandboxBinaryBytes(box, absolutePath, stat.value)\n if (!read.succeeded) {\n return { succeeded: false, error: `mentioned sandbox file read failed: ${absolutePath} — ${read.error}` }\n }\n return { succeeded: true, value: { size: stat.value, base64: bytesToBase64(read.value.bytes) } }\n}\n\n/** HARD INVARIANT: an image carries exactly one URL or absolute path, while a\n * file carries the URL required by the current sandbox prompt contract. */\nfunction violatesUrlPathXor(part: PromptInputPart): boolean {\n if (part.type === 'text') return false\n const hasUrl = typeof part.url === 'string' && (\n part.url.startsWith('data:')\n || part.url.startsWith('file://')\n )\n const hasPath = 'path' in part && typeof part.path === 'string' && part.path.startsWith('/')\n if (part.type === 'file') return !hasUrl || hasPath\n return hasUrl === hasPath\n}\n\nfunction sandboxFileUrl(absolutePath: string): string | undefined {\n if (!absolutePath.startsWith('/')) return undefined\n try {\n return pathToFileURL(absolutePath).href\n } catch {\n return undefined\n }\n}\n\n/**\n * Convert the browser-safe chat attachment contract into the current sandbox\n * prompt contract. Images carry exactly one URL or path; generic files carry a\n * filename and URL.\n */\nexport function normalizeChatPromptForSandbox(\n prompt: string | readonly ChatTurnPartInput[],\n): string | PromptInputPart[] {\n if (typeof prompt === 'string') return prompt\n return prompt.map((part): PromptInputPart => {\n if (part.type === 'text') return part\n if ('content' in part) {\n throw new ChatTurnInputError('Sandbox prompt parts do not accept inline content; provide a URL or path')\n }\n\n const url = typeof part.url === 'string' && part.url.length > 0 ? part.url : undefined\n const path = typeof part.path === 'string' && part.path.length > 0 ? part.path : undefined\n if (Boolean(url) === Boolean(path)) {\n throw new ChatTurnInputError(`Sandbox ${part.type} parts require exactly one URL or path`)\n }\n if (path && !path.startsWith('/')) {\n throw new ChatTurnInputError(`Sandbox ${part.type} paths must be absolute: ${path}`)\n }\n\n if (part.type === 'image') {\n return {\n type: 'image',\n ...(part.filename ? { filename: part.filename } : {}),\n ...(part.mediaType ? { mediaType: part.mediaType } : {}),\n ...(url ? { url } : { path: path! }),\n }\n }\n\n const filename = part.filename?.trim()\n if (!filename) {\n throw new ChatTurnInputError('Sandbox file parts require a filename')\n }\n const fileUrl = url ?? sandboxFileUrl(path!)\n if (!fileUrl) {\n throw new ChatTurnInputError(`Sandbox file paths must be absolute: ${path}`)\n }\n return {\n type: 'file',\n filename,\n ...(part.mediaType ? { mediaType: part.mediaType } : {}),\n url: fileUrl,\n }\n })\n}\n\n/** A persisted message whose attachment pointers accompany its history text. */\nexport interface DispatchHistoryMessage {\n role: string\n content: string\n parts?: ReadonlyArray<Record<string, unknown>> | null\n}\n\n/** Whose eyes the history is read through. */\nexport interface DispatchHistoryPov {\n /** The agent being prompted (`args.agent?.id` on a mentioned turn). Its\n * own answers stay `assistant`; every other agent's answer becomes a\n * `user` message tagged `[Name] …`, the same tagging agent-runtime's\n * `runConversation` uses, so three or more parties stay unambiguous. */\n pov?: string\n /** The thread's own agent, so its untagged answers can be named when the\n * history is read by someone else. Omit → untagged rows stay `assistant`. */\n owner?: { id: string; name: string }\n /** Append each row's attachment pointers to its text, as dispatch does.\n * Default true; a Router turn with no box to read from passes false. */\n attachments?: boolean\n}\n\n/** Project persisted rows using the same role and attachment policy as dispatch.\n * A row written by several agents (a `speaker` part before each answer)\n * projects as one message per speaker, each tagged with its name; with a\n * point of view, the reader's own answers are untagged `assistant` turns and\n * everyone else's are tagged `user` turns. Reasoning and tool parts never\n * project: they are the writer's trace, not anyone's context. */\nexport function projectDispatchHistory(\n messages: ReadonlyArray<DispatchHistoryMessage>,\n view: DispatchHistoryPov = {},\n): Array<{ role: 'user' | 'assistant'; content: string }> {\n const out: Array<{ role: 'user' | 'assistant'; content: string }> = []\n const textOf = (message: DispatchHistoryMessage) =>\n view.attachments === false ? message.content : historyContentWithAttachments(message)\n for (const message of messages) {\n if (message.role !== 'assistant') {\n out.push({ role: 'user', content: textOf(message) })\n continue\n }\n const slices = speakerSlices(message)\n if (slices.length === 0) {\n const owner = view.owner\n const foreign = view.pov !== undefined && owner !== undefined && owner.id !== view.pov\n out.push({\n role: foreign ? 'user' : 'assistant',\n content: foreign ? tagged(owner!.name, textOf(message)) : textOf(message),\n })\n continue\n }\n for (const slice of slices) {\n const text = textOf({ role: 'assistant', content: slice.text, parts: slice.parts })\n if (view.pov === undefined) out.push({ role: 'assistant', content: tagged(slice.name, text) })\n else if (slice.id === view.pov) out.push({ role: 'assistant', content: text })\n else out.push({ role: 'user', content: tagged(slice.name, text) })\n }\n }\n return out\n}\n\nconst tagged = (name: string, text: string) => `[${name}] ${text}`\n\n/** One responder's slice of a multi-speaker row: its text and the parts that follow its speaker part. */\nfunction speakerSlices(message: DispatchHistoryMessage): Array<{ id: string; name: string; text: string; parts: Record<string, unknown>[] }> {\n const parts = message.parts ?? []\n const slices: Array<{ id: string; name: string; text: string; parts: Record<string, unknown>[] }> = []\n let current: (typeof slices)[number] | null = null\n for (const part of parts) {\n if (part.type === 'speaker' && typeof part.id === 'string' && typeof part.name === 'string') {\n current = { id: part.id, name: part.name, text: '', parts: [] }\n slices.push(current)\n } else if (current) {\n current.parts.push(part)\n if (part.type === 'text' && typeof part.text === 'string') current.text += part.text\n }\n }\n return slices\n}\n\n/** Build input parameters for dispatching chat message parts including text, attachments, mentions, and history */\nexport interface BuildDispatchPartsInput {\n text: string\n attachments: ChatAttachmentPart[]\n mentions?: ChatMentionPart[]\n history: Array<{ role: 'user' | 'assistant'; content: string }>\n systemPrompt: string\n /** Serialized size of the backend profile the SDK inlines into the same\n * prompt request body — a large, non-negotiable rider that must come out of\n * the inline budget or near-cap attachments 413 at the proxy instead of\n * demoting to path parts. */\n profileWireBytes: number\n /** The product's workspace/tenant key, passed to `readAttachment`. */\n scopeId: string\n /** Maps an attachment's store-relative path to the in-box absolute path a\n * local media reference uses (same style as `fileMentionsToParts`'s\n * `resolvePath`). */\n resolveAttachmentPath: (path: string) => string\n /** Maps a mention's workspace-relative path to its in-box absolute path.\n * Default: {@link BuildDispatchPartsInput.resolveAttachmentPath} — in gtm the\n * vault mount roots both; a product that mounts them apart overrides this. */\n resolveMentionPath?: (path: string) => string\n /** The turn's already-ensured box — required when `mentions` is non-empty\n * (mention bytes are read from the live box, not the store). */\n box?: SandboxExecChannel\n /** Force every media part to a local file reference, skipping all inlining. */\n forcePath?: boolean\n /** REQUIRED store reader for attachment content — no default (the product\n * owns its store; see {@link ReadAttachmentFn}). */\n readAttachment: ReadAttachmentFn\n readSandboxMention?: ReadSandboxMentionFn\n /** Whole-request proxy cap. Default {@link DISPATCH_REQUEST_MAX_BYTES}. */\n requestMaxBytes?: number\n /** JSON-envelope reserve off the top of the request cap. Default\n * {@link DISPATCH_STRUCTURAL_RESERVE_BYTES}. */\n structuralReserveBytes?: number\n /** Sidecar per-request parts-array cap. Default {@link DISPATCH_MAX_PARTS}. */\n maxParts?: number\n}\n\n/** Content of one attachment read, normalized to the base64 a `data:` URI\n * needs — `base64` reused verbatim, else `bytes` encoded once. */\nfunction readResultToBase64(read: { base64?: string; bytes?: Uint8Array }): string | undefined {\n if (typeof read.base64 === 'string') return read.base64\n if (read.bytes) return bytesToBase64(read.bytes)\n return undefined\n}\n\n/** Build dispatch parts from input by resolving mentions, paths, and applying size constraints asynchronously */\nexport async function buildDispatchParts(input: BuildDispatchPartsInput): Promise<DispatchPartsOutcome> {\n const readMention = input.readSandboxMention ?? readSandboxMention\n const resolveMentionPath = input.resolveMentionPath ?? input.resolveAttachmentPath\n const forcePath = input.forcePath ?? false\n // Agent mentions address a responder; only file mentions are read from the box.\n const mentions = (input.mentions ?? []).filter((mention) => mention.mentionKind !== 'agent')\n const requestMaxBytes = input.requestMaxBytes ?? DISPATCH_REQUEST_MAX_BYTES\n const structuralReserveBytes = input.structuralReserveBytes ?? DISPATCH_STRUCTURAL_RESERVE_BYTES\n const maxParts = input.maxParts ?? DISPATCH_MAX_PARTS\n\n const parts: PromptInputPart[] = [{ type: 'text', text: input.text }]\n // Absolute in-box paths already emitted — a file both attached and mentioned\n // (or mentioned twice) rides as a single media part.\n const emittedAbsPaths = new Set<string>()\n\n const flattenedForSizing = flattenHistory(input.text, input.history)\n // May go negative when history/systemPrompt alone are large — every\n // attachment then fails the `runningInline + cost <= inlineBudget` check\n // below and uses a local file reference, which does not draw on this inline\n // budget.\n const inlineBudget =\n requestMaxBytes\n - base64WireLen(byteLen(flattenedForSizing))\n - byteLen(JSON.stringify(input.systemPrompt))\n - input.profileWireBytes\n - structuralReserveBytes\n\n let runningInline = 0\n\n // Stable input order: attachments dispatch in the order the user attached\n // them, and the pointer block in `input.text` already names them in that\n // same order.\n for (const attachment of input.attachments) {\n if (!attachment.path) {\n return { succeeded: false, error: `attachment path must be non-empty: ${attachment.name}` }\n }\n\n // The reader crosses an external boundary (store/coordinator) — a rejection\n // there must land in the typed outcome, not escape as a thrown error the\n // caller would misattribute to stream init.\n let read: Awaited<ReturnType<ReadAttachmentFn>>\n try {\n read = await input.readAttachment(input.scopeId, attachment.path)\n } catch (err) {\n return {\n succeeded: false,\n error: `attachment store read failed: ${attachment.path} — ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (!read.ok) return { succeeded: false, error: read.reason }\n\n const base64 = readResultToBase64(read)\n if (base64 === undefined) {\n return { succeeded: false, error: `attachment store read produced no content: ${attachment.path}` }\n }\n\n const mediaType = attachment.mediaType ?? read.mediaType\n if (attachment.type === 'image' && !mediaType) {\n return { succeeded: false, error: `attachment is missing a mediaType required for an image data URI: ${attachment.path}` }\n }\n\n const absPath = input.resolveAttachmentPath(attachment.path)\n emittedAbsPaths.add(absPath)\n\n if (attachment.type === 'image') {\n const inlinePart: PromptInputPart = {\n type: 'image',\n filename: attachment.name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n if (!forcePath && runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n } else {\n parts.push({ type: 'image', filename: attachment.name, mediaType, path: absPath })\n }\n continue\n }\n\n // File parts use the current filename + URL contract. A file that is too\n // large to inline keeps its existing in-box file through a file:// URL.\n const fileMediaType = mediaType ?? 'application/octet-stream'\n const inlinePart: PromptInputPart = {\n type: 'file',\n filename: attachment.name,\n mediaType: fileMediaType,\n url: `data:${fileMediaType};base64,${base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n if (!forcePath && runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n } else {\n const url = sandboxFileUrl(absPath)\n if (!url) {\n return { succeeded: false, error: `resolved attachment path must be absolute: ${absPath}` }\n }\n parts.push({ type: 'file', filename: attachment.name, mediaType: fileMediaType, url })\n }\n }\n\n if (mentions.length > 0 && !input.box) {\n return { succeeded: false, error: 'internal error: sandbox mentions require a box to read from' }\n }\n for (const mention of mentions) {\n if (!mention.path) {\n return { succeeded: false, error: `mention path must be non-empty: ${mention.name}` }\n }\n if (!isWorkspaceFileExportable(mention.path)) {\n return { succeeded: false, error: `mention file is not exportable: ${mention.path}` }\n }\n const absPath = resolveMentionPath(mention.path)\n if (emittedAbsPaths.has(absPath)) continue\n emittedAbsPaths.add(absPath)\n\n const isImage = mention.mentionKind === 'image'\n const mediaType = isImage ? mediaTypeForMentionPath(mention.path) : undefined\n\n // Every mention is stat'd first: it proves the file still exists (a deleted\n // mention fails the turn loud) and gives the size for the inline budget\n // decision without pulling bytes across the exec channel.\n let stat: SandboxMentionReadOutcome\n try {\n stat = await readMention(input.box!, absPath, { readBytes: false })\n } catch (err) {\n return { succeeded: false, error: `mention read failed: ${absPath} — ${err instanceof Error ? err.message : String(err)}` }\n }\n if (!stat.succeeded) return { succeeded: false, error: stat.error }\n\n // Only an image that projects within the remaining budget reads its bytes\n // to inline; every other mention (and a budget-exceeding image) ships\n // by local reference, so a large file is never base64'd unnecessarily.\n const projectedInlineCost = base64WireLen(stat.value.size)\n + byteLen(JSON.stringify({ type: 'image', filename: mention.name, mediaType: mediaType ?? '', url: '' }))\n if (isImage && mediaType && !forcePath && runningInline + projectedInlineCost <= inlineBudget) {\n let read: SandboxMentionReadOutcome\n try {\n read = await readMention(input.box!, absPath, { readBytes: true })\n } catch (err) {\n return { succeeded: false, error: `mention read failed: ${absPath} — ${err instanceof Error ? err.message : String(err)}` }\n }\n if (!read.succeeded) return { succeeded: false, error: read.error }\n if (!read.value.base64) return { succeeded: false, error: `mentioned image produced no bytes: ${absPath}` }\n const inlinePart: PromptInputPart = {\n type: 'image',\n filename: mention.name,\n mediaType,\n url: `data:${mediaType};base64,${read.value.base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n // Re-check against the actual serialized cost — the projection can\n // undershoot; a real overshoot demotes to a path part rather than 413ing.\n if (runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n continue\n }\n }\n\n if (isImage && mediaType) {\n parts.push({ type: 'image', filename: mention.name, mediaType, path: absPath })\n } else {\n const url = sandboxFileUrl(absPath)\n if (!url) {\n return { succeeded: false, error: `resolved mention path must be absolute: ${absPath}` }\n }\n parts.push({ type: 'file', filename: mention.name, url })\n }\n }\n\n for (const part of parts) {\n if (violatesUrlPathXor(part)) {\n return { succeeded: false, error: 'internal error: emitted media part violates the url/path exclusivity invariant' }\n }\n }\n\n // Final whole-request check sized against what actually crosses the wire: the\n // history-merged text part (the substrate folds `history` into `parts[0]`\n // before dispatch), the media parts, the system prompt, and the inlined\n // backend profile riding the same body — the same terms `inlineBudget` was\n // derived from.\n const textPartSize = base64WireLen(byteLen(flattenedForSizing))\n const mediaPartsSize = parts.slice(1).reduce((total, part) => total + byteLen(JSON.stringify(part)), 0)\n const systemPromptSize = byteLen(JSON.stringify(input.systemPrompt))\n if (textPartSize + mediaPartsSize + systemPromptSize + input.profileWireBytes + structuralReserveBytes > requestMaxBytes) {\n return { succeeded: false, error: 'dispatch parts exceed the sandbox proxy request cap even after path demotion' }\n }\n\n // The sidecar rejects the whole request past its parts-array cap; the caller\n // selects which media ride natively, so overflow here is a caller bug\n // surfaced loudly rather than a truncation.\n if (parts.length > maxParts) {\n return { succeeded: false, error: `dispatch parts exceed the sidecar per-request cap of ${maxParts}` }\n }\n\n return { succeeded: true, value: parts }\n}\n","/**\n * When each reasoning run of a turn started and ended, so every chat producer\n * persists one reasoning part shape: `{ type: 'reasoning', text, time: { start, end } }`\n * (`ChatReasoningPart` in `/chat-store`).\n *\n * The engine (`./router-producer`) and the sandbox (`./sandbox-producer`) both\n * stream reasoning live as `{ type: 'reasoning', text }` deltas. This clock gives\n * their persisted parts the same timing: a run starts at its first delta and\n * ends when anything else streams (answer text, a tool) or the turn ends. A\n * harness that timed its own part keeps its times; the clock fills only what it\n * left out. `/web-react` reads the result back (`chatReasoningFromParts`), so a\n * reloaded turn shows how long the model thought.\n *\n * Import-free, so the browser-safe chat stream can share the part's type.\n */\n\n/** Start and end, in epoch milliseconds, of one reasoning run. */\nexport interface ReasoningRunTime {\n start?: number\n end?: number\n}\n\n/** The clock one producer keeps for one turn. `K` is how the producer names a run: a part key or the part itself. */\nexport interface ReasoningClock<K> {\n /** A reasoning delta for `run` streamed. Starts its clock on the first; ends any other open run. */\n reasoning(run: K): void\n /** Something other than reasoning streamed, or the turn ended: the open run is over, at `at` (default now). */\n settle(at?: number): void\n /** The run's time, the part's own `start` and `end` winning where it has them. */\n time(run: K, own?: ReasoningRunTime): ReasoningRunTime | undefined\n}\n\n/** A clock for one turn's reasoning runs. */\nexport function createReasoningClock<K>(now: () => number = Date.now): ReasoningClock<K> {\n const runs = new Map<K, ReasoningRunTime>()\n let open: { run: K } | null = null\n const settle = (at?: number) => {\n if (!open) return\n const time = runs.get(open.run)\n if (time && time.end === undefined) time.end = Math.max(time.start ?? 0, at ?? now())\n open = null\n }\n return {\n reasoning(run) {\n if (open && open.run === run) return\n settle()\n const time = runs.get(run)\n // The same run resumed after an interruption: it is open again.\n if (time) delete time.end\n else runs.set(run, { start: now() })\n open = { run }\n },\n settle,\n time(run, own) {\n const time = runs.get(run)\n if (!time) return own\n const start = own?.start ?? time.start\n const end = own?.end ?? time.end\n return { ...(start !== undefined ? { start } : {}), ...(end !== undefined ? { end } : {}) }\n },\n }\n}\n","/**\n * The chat-route producer for a Router turn: `runRouterTurn` behind the same\n * `produce` seam the sandbox lane uses (`createSandboxChatProducer`). The route\n * persists, buffers, replays and settles the turn exactly as it does for the\n * sandbox; only the producer differs.\n *\n * The engine is pushed, the route pulls: engine events land in a queue that the\n * `stream` generator drains in order, so a slow consumer never drops a frame\n * and the engine never waits on the consumer.\n */\nimport { composeRouterTurnPromptSections, runRouterTurn, type RouterTurnEvent, type RouterTurnFailure, type RouterTurnOptions, type RouterTurnOutcome, type RouterTurnPromptOptions, type RouterTurnTool } from '../runtime/router-turn'\nimport { createReasoningClock } from './reasoning-clock'\nimport { redactErrorMessage } from '../redact/index'\nimport { noticePart } from '../interactions/contract'\nimport type { ChatTurnRouteProducer, ChatTurnUsage } from './turn-routes'\nimport type { ProducerWireEvent } from './wire'\n\n/** The turn's model key: a plain key, or a per-turn lease whose fetch and revocation belong to the producer. */\nexport type RouterTurnKey = string | { key: string; fetchImpl?: typeof fetch; revoke(): Promise<void> }\ntype RouterTurnPrompt = string | (RouterTurnPromptOptions & { profile: Parameters<typeof composeRouterTurnPromptSections>[0] })\n\nexport type RouterTurnProducerOptions = Omit<RouterTurnOptions, 'onEvent' | 'systemPrompt' | 'apiKey'> & {\n /** The turn's key, including any claim still in flight. A lease's fetch and retirement belong to this producer. */\n apiKey: RouterTurnKey | Promise<RouterTurnKey>\n /** Domain-authored stable and per-turn bytes; composition and prefix validation are automatic. */\n systemPrompt: RouterTurnPrompt | Promise<RouterTurnPrompt>\n /** Final admission: model text may start earlier, but every tool waits for this request's committed domain state. */\n admitted?: Promise<unknown>\n /** Observe the finished turn or supply domain-authored final text/failure. An unfinished checkpoint is a turn_deadline failure here; durable continuation belongs to runRouterTurn callers. */\n onOutcome?: (outcome: RouterTurnOutcome) => void | { trailingText?: string; failure?: RouterTurnFailure } |\n Promise<void | { trailingText?: string; failure?: RouterTurnFailure }>\n /** Observe each engine event after the producer has projected it (a box speculator, metrics). A throw is ignored. */\n onEvent?: (event: RouterTurnEvent) => void\n /** Retire product resources once, including initialization failure and cancellation before the stream is read. */\n onSettled?(): Promise<void> | void\n}\n\nexport function createRouterTurnProducer(options: RouterTurnProducerOptions): Omit<ChatTurnRouteProducer, 'stream'> & {\n stream: AsyncGenerator<ProducerWireEvent, void, unknown>\n} {\n const abort = new AbortController()\n const signal = options.signal ? AbortSignal.any([abort.signal, options.signal]) : abort.signal\n void options.admitted?.catch(error => { abort.abort(error) })\n const credential = Promise.resolve(options.apiKey)\n let credentialSettled = false\n void credential.then(() => { credentialSettled = true }, () => { credentialSettled = true })\n let retired: Promise<void> | undefined\n const retire = () => retired ??= credential.then(async key => {\n if (typeof key !== 'string') await key.revoke()\n }, () => undefined).catch(error => {\n console.error(JSON.stringify({ event: 'router_turn_key_retire_failed', error: redactErrorMessage(error) }))\n })\n let stop: (reason: unknown) => void = () => {}\n const cancelled = new Promise<never>((_resolve, reject) => { stop = reject })\n const stopped = () => { stop(signal.reason); void retire() }\n signal.addEventListener('abort', stopped, { once: true })\n if (signal.aborted) stopped()\n const queue: ProducerWireEvent[] = []\n let wake: (() => void) | null = null\n let done = false\n let outcome: RouterTurnOutcome | null = null\n // The runtime starts usage at zero, so only a reported usage event makes the counts real.\n let usageReported = false\n const parts: Array<Record<string, unknown>> = []\n const toolParts = new Map<string, Record<string, unknown>>()\n let textPart: { type: 'text'; text: string } | null = null\n let textSegment = 0\n let reasoningPart: { type: 'reasoning'; text: string } | null = null\n // Each reasoning part's start and end, the same timing the sandbox producer persists.\n const reasoningClock = createReasoningClock<Record<string, unknown>>()\n\n const push = (event: ProducerWireEvent) => {\n queue.push(event)\n wake?.()\n }\n\n const run = Promise.race([Promise.all([credential, options.systemPrompt]), cancelled]).then(([key, prompt]) => {\n signal.throwIfAborted()\n return runRouterTurn({\n ...options,\n apiKey: typeof key === 'string' ? key : key.key,\n fetchImpl: typeof key === 'string' ? options.fetchImpl : key.fetchImpl ?? options.fetchImpl,\n signal,\n tools: options.tools?.map(tool => ({ ...tool, run: async (...args: Parameters<RouterTurnTool['run']>) => {\n await options.admitted; signal.throwIfAborted(); return tool.run(...args)\n } })),\n systemPrompt: typeof prompt === 'string' ? prompt : composeRouterTurnPromptSections(prompt.profile, prompt).text,\n showReasoning: options.showReasoning ?? true,\n onEvent: event => {\n if (event.type === 'text') {\n if (event.segment !== textSegment || !textPart) {\n textSegment = event.segment\n textPart = { type: 'text', text: '' }\n parts.push(textPart)\n }\n textPart.text += event.delta\n reasoningPart = null\n reasoningClock.settle()\n push({ type: 'text', text: event.delta })\n } else if (event.type === 'reasoning') {\n // A reasoning run is one part until a word or a tool interrupts it.\n if (!reasoningPart) {\n reasoningPart = { type: 'reasoning', text: '' }\n parts.push(reasoningPart)\n }\n reasoningPart.text += event.delta\n reasoningClock.reasoning(reasoningPart)\n push({ type: 'reasoning', text: event.delta })\n } else if (event.type === 'tool') {\n reasoningPart = null\n // The model stopped reasoning when it called the tool.\n reasoningClock.settle(event.startedAt)\n if (event.status === 'running') {\n const part = { type: 'tool', id: event.callId, callID: event.callId, tool: event.toolName,\n state: { status: 'running', input: event.input, time: { start: event.startedAt } } }\n toolParts.set(event.callId, part)\n parts.push(part)\n push({ type: 'tool_call', call: { toolCallId: event.callId, toolName: event.toolName, args: event.input } })\n } else {\n const part = toolParts.get(event.callId)\n const state = event.status === 'completed'\n ? { status: 'completed', output: event.output, time: { start: event.startedAt, end: event.endedAt } }\n : { status: 'error', error: event.error.message, time: { start: event.startedAt, end: event.endedAt } }\n if (part) part.state = { ...(part.state as Record<string, unknown>), ...state }\n push({ type: 'tool_result', toolCallId: event.callId, toolName: event.toolName,\n outcome: event.status === 'completed' ? { ok: true, result: event.output } : { ok: false, message: event.error.message, code: event.error.code } })\n }\n } else if (event.type === 'repeat') {\n // The repeat's reasoning is a new run: close the failed call's part so the two never merge.\n reasoningPart = null\n reasoningClock.settle()\n } else if (event.type === 'usage') {\n usageReported = true\n push({ type: 'usage', usage: { promptTokens: event.promptTokens, completionTokens: event.completionTokens,\n ...(event.cachedPromptTokens !== undefined ? { cachedPromptTokens: event.cachedPromptTokens } : {}) } })\n } else if (event.type === 'tool_event') {\n // Recorded on the tool's part, so a reload shows what the tool did, and streamed as it happens.\n const part = toolParts.get(event.callId)\n if (part) {\n const state = part.state as Record<string, unknown>\n part.state = { ...state, events: [...(state.events as unknown[] ?? []), { kind: event.kind, data: event.data, at: event.at }] }\n }\n push({ type: 'tool.event', data: { toolCallId: event.callId, toolName: event.toolName, kind: event.kind, data: event.data, at: event.at } })\n }\n if (options.onEvent) {\n try { options.onEvent(event) } catch { /* an observer never changes the turn */ }\n }\n },\n })\n }).then(async result => {\n // This producer settles chat; it has no durable owner to resume a checkpoint.\n // Classify unfinished work before domain settlement observes the outcome.\n if (result.continuation && !result.failure) {\n result.failure = { code: 'turn_deadline', message: 'The reply was stopped before it finished.' }\n }\n outcome = result\n const final = await options.onOutcome?.(result)\n if (final && final.trailingText) {\n result.text += final.trailingText\n parts.push({ type: 'text', text: final.trailingText })\n push({ type: 'text', text: final.trailingText })\n }\n if (final && final.failure) result.failure = final.failure\n if (result.failure) {\n parts.push(noticePart('error', 'router-error', result.failure.message, result.failure.code))\n push({ type: 'error', data: { message: result.failure.message, code: result.failure.code } })\n }\n }).finally(async () => {\n const retiring = retire()\n if (credentialSettled) await retiring\n try { await options.onSettled?.() } catch (error) {\n console.error(JSON.stringify({ event: 'router_turn_settle_failed', error: redactErrorMessage(error) }))\n }\n signal.removeEventListener('abort', stopped)\n reasoningClock.settle()\n done = true\n wake?.()\n })\n void run.catch(() => undefined)\n\n async function* stream(): AsyncGenerator<ProducerWireEvent, void, unknown> {\n for (;;) {\n while (queue.length) yield queue.shift()!\n if (done) break\n await new Promise<void>(resolve => { wake = resolve })\n wake = null\n }\n await run\n }\n\n // A reasoning part carries its run's time; a run still open in a mid-turn draft has a start and no end.\n const snapshot = () => parts.map(part => part.type === 'reasoning'\n ? { ...part, time: reasoningClock.time(part) }\n : { ...part })\n\n // A turn whose Router reported no usage stores no counts (null), never a made-up 0.\n const usage = (): ChatTurnUsage => !outcome || !usageReported ? {} : ({\n // The Router's prompt tokens include the cached ones; the sandbox lanes report input and cache reads apart, so\n // the stored row counts them apart here too and `inputTokens + cacheReadTokens` is the prompt on either lane.\n inputTokens: outcome.usage.promptTokens - (outcome.usage.cachedPromptTokens ?? 0),\n outputTokens: outcome.usage.completionTokens,\n ...(outcome.usage.cachedPromptTokens !== undefined ? { cacheReadTokens: outcome.usage.cachedPromptTokens } : {}),\n })\n\n const events = stream()\n const end = events.return.bind(events)\n const fail = events.throw.bind(events)\n events.return = async value => {\n abort.abort(new Error('The chat route stopped reading this turn'))\n try { return await end(value) } finally { const retiring = retire(); if (credentialSettled) await retiring }\n }\n events.throw = async error => {\n abort.abort(error)\n try { return await fail(error) } finally { const retiring = retire(); if (credentialSettled) await retiring }\n }\n\n return {\n stream: events,\n // The route tracks this continuation even when failure is visible before a pending key arrives.\n cleanup: run.then(retire, retire),\n finalText: () => outcome?.text ?? '',\n assistantParts: snapshot,\n draftParts: snapshot,\n usage,\n get model() { return outcome?.servedModel ?? undefined },\n modelAttribution: () => ({\n requestedModel: options.model,\n ...(outcome?.servedModel ? { servedModel: outcome.servedModel } : {}),\n echoReceived: Boolean(outcome?.servedModel),\n }),\n }\n}\n","/**\n * `createHybridTurnProducer`: the default chat turn. The model answers first\n * through the Tangle Router with the app's tools in process, and work that\n * needs a computer escalates to the workspace box through one `sandbox_run`\n * call whose answer comes back to the model.\n *\n * WHY THIS IS THE DEFAULT. Measured on production: the\n * Hospitality Router lane gave first text at 3.6 s with 0 of 39 failures; its\n * sandbox lane 31.0 s with 2 of 8. Legal's sandbox lane gave first text at\n * p50 137 s because the box agent writes nothing until its last tool call. The\n * box only wins after about 8 tool calls through the API path (3 to 6 when it\n * is warm), and those turns still reach it here, through `sandbox_run`.\n *\n * THE BOX. The producer starts it at most once per turn and every caller\n * shares that start: the speculator, the `sandbox_run` call, and a start that\n * admission already began (`box.started`, from {@link startHybridBox} in\n * `afterAuthorize`). A failed start is forgotten, so the tool's own call\n * retries it. Across isolates the product's `acquire` keeps its existing\n * single flight (`runForegroundSandboxSingleFlight` over the D1 claim, or the\n * warm lease).\n *\n * THE SPECULATOR is always on: words that ask for execution, a code fence or a\n * process-shaped attachment start the box before the model call, and the model\n * naming `sandbox_run` starts it while the call's arguments still stream.\n *\n * FIRST WORDS. Unless the product passes its own `guidance`, the prompt tells\n * the model to say in one sentence what it is about to do before its first\n * tool call, so a turn that writes a deliverable or escalates to the box shows\n * text at the model's first token, not after its last tool call.\n *\n * The trace passes through: model calls, tool calls, the box claim and the box\n * run are recorded under the turn's `trace` when the route gives one.\n * A typed computer failure also emits a persisted warning; the Router keeps\n * answering without relying on the model to explain that failure faithfully.\n * The warning's `detail` is the failure's redacted cause chain, so the cause is\n * in the transcript, not only in a log line a Worker does not keep.\n */\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { redactErrorMessage } from '../redact/index'\nimport { noticePart } from '../interactions/contract'\nimport type { RouterTurnTool } from '../runtime/router-turn'\nimport {\n createEscalationSpeculator,\n escalationHints,\n type EscalationHint,\n type EscalationInput,\n} from '../sandbox/escalation-speculator'\nimport { createSandboxRunTool, SandboxRunError, sandboxRunFailureDetail, type SandboxRunToolOptions } from '../sandbox/sandbox-run-tool'\nimport { createComputerStep, type ComputerStepOptions } from '../sandbox/computer-step'\nimport type { PersistedChatMessageForTurn } from '../stream/index'\nimport { projectDispatchHistory, type DispatchHistoryPov } from './dispatch-parts'\nimport { createRouterTurnProducer, type RouterTurnProducerOptions } from './router-producer'\nimport type { ChatTurnRouteProducer } from './turn-routes'\nimport type { ChatRouteEvent } from './turn-route-contracts'\nimport type { ChatTurnPartInput, ChatTurnRequestPayload } from './wire'\nimport type { ProducerNoticeEvent } from './wire'\n\n// The lead-in covers every tool, not only sandbox_run: on Legal's Router lane the model streamed a\n// submit_proposal payload for 45 s before its first word, so first text came at 54.9 s after a first token at 3.8 s.\n/** What the default prompt adds so the Router lane answers first and escalates out loud. */\nexport const HYBRID_TURN_GUIDANCE =\n 'Start your reply with text: before your first tool call, write one short sentence telling the member what you are ' +\n 'about to do, so they never wait in silence. Use sandbox_run only for work that needs code execution or files on ' +\n \"the workspace computer. Give the sandbox agent the member's requirements, paths and exact field names, \" +\n 'not model-written code; the sandbox agent writes and runs the code. Report what it returns.'\n\nconst DEFAULT_SANDBOX_RUN_TIMEOUT_MS = 4 * 60_000\n\nexport interface HybridTurnBox {\n /** Start or adopt the workspace box. The product provisions, binds and bills it, and keeps its own single flight\n * across isolates. A throw reaches the model as `sandbox_unavailable` (or the `SandboxRunError` it throws). */\n acquire(signal: AbortSignal): Promise<SandboxInstance>\n /** A start admission already began ({@link startHybridBox}); the producer takes it as the turn's start. */\n started?: Promise<SandboxInstance>\n /** Runs the task on the box and returns its answer. Omit it and pass `computer` for agent-app's computer step. */\n runTask?: SandboxRunToolOptions['runTask']\n /** agent-app's computer step ({@link createComputerStep}): the first of the turn's models the box key allows, one\n * session value, a turn id the runtime's admission makes idempotent, and the copy of the step's files into the product's Vault.\n * `parentExecutionId` defaults to the turn's execution id on the chat route, else the trace id. */\n computer?: ComputerStepOptions\n /** Wall-clock cap for one `sandbox_run` call, box start included. Default 4 minutes. */\n timeoutMs?: number\n warm?: SandboxRunToolOptions['warm']\n /** Every computer failure with its cause. The producer already persists the redacted cause chain on the turn's\n * warning notice (`detail`), and logs it when this is omitted. */\n onFailure?: SandboxRunToolOptions['onFailure']\n /** What the turn's warning notice keeps as `detail` for a failed call. Members read that notice in the transcript.\n * Default: the redacted cause chain ({@link sandboxRunFailureDetail}). Return undefined to keep a cause that holds\n * private platform diagnostics off the transcript; `onFailure` still receives the full error. */\n failureDetail?(error: SandboxRunError): string | undefined\n /** The tool's name and description. Default `sandbox_run` and its shared description. */\n name?: string\n description?: string\n /** Dispose this turn's opaque client credentials/resources after any started acquire settles. Never retire the box. */\n dispose?(): Promise<void> | void\n}\n\nexport interface HybridTurnProducerOptions extends RouterTurnProducerOptions {\n /** The app's in-process tools. `sandbox_run` is added after them. */\n tools?: RouterTurnTool[]\n box: HybridTurnBox\n /** The text the speculator reads. Default `userMessage`; pass what the member typed when `userMessage` carries\n * injected context that would trip the execution words. */\n speculateOn?: string\n /** The turn's attachments, for the speculator. */\n attachments?: EscalationInput['attachments']\n onSpeculate?(hint: EscalationHint): void\n /** Appended to `systemPrompt`. Default {@link HYBRID_TURN_GUIDANCE}; `false` when the prompt already says it. */\n guidance?: string | false\n}\n\n/**\n * Start the box at admission when the request asks for execution, so its resume overlaps the turn lock and the\n * profile pin instead of following them. Call it in `afterAuthorize` with the turn's body and hand the promise to\n * the producer as `box.started`. Returns undefined, and starts nothing, for a turn that does not look like it needs\n * the box.\n */\nexport function startHybridBox(\n body: Pick<ChatTurnRequestPayload, 'content' | 'parts'>,\n acquire: () => Promise<SandboxInstance>,\n): Promise<SandboxInstance> | undefined {\n const attachments = (body.parts ?? []).map(part => ({\n ...(part.mediaType ? { mediaType: part.mediaType } : {}),\n ...(part.filename ? { name: part.filename } : {}),\n }))\n if (escalationHints({ text: body.content ?? '', attachments }).length === 0) return undefined\n const started = acquire()\n // The producer or the caller's release awaits it; a start nobody awaits must not surface as an unhandled rejection.\n started.catch(() => undefined)\n return started\n}\n\n/** The turn's prompt as the text the model reads: text parts joined; file parts are not text. */\nexport function turnPromptText(prompt: string | readonly ChatTurnPartInput[]): string {\n return typeof prompt === 'string' ? prompt : prompt.map(part => part.type === 'text' ? part.text : '').join('\\n')\n}\n\n/** Whether the turn carries files. Files live in the box, so a turn with them runs on the sandbox lane. */\nexport function turnCarriesFiles(prompt: string | readonly ChatTurnPartInput[]): boolean {\n return typeof prompt !== 'string' && prompt.some(part => part.type !== 'text')\n}\n\n/** The conversation so far as the plain text history a Router turn replays: the last `limit` user and assistant\n * messages that have text, read through the responder's point of view when the turn was addressed to agents\n * (a row several agents wrote becomes one tagged message per speaker). Tool and reasoning parts are not replayed. */\nexport function routerTurnHistory(\n priorMessages: ReadonlyArray<Pick<PersistedChatMessageForTurn, 'role' | 'content'> & { parts?: ReadonlyArray<Record<string, unknown>> | null }>,\n limit = 40,\n view: Pick<DispatchHistoryPov, 'pov' | 'owner'> = {},\n): Array<{ role: 'user' | 'assistant'; content: string }> {\n const rows = priorMessages.filter((message) => message.role === 'user' || message.role === 'assistant')\n return projectDispatchHistory(rows, { ...view, attachments: false })\n .filter((message) => Boolean(message.content.trim()))\n .slice(-limit)\n}\n\nexport function createHybridTurnProducer(options: HybridTurnProducerOptions): ChatTurnRouteProducer {\n const { box, tools = [], speculateOn, attachments, onSpeculate, guidance, onSettled, admitted, signal, ...router } = options\n const abort = new AbortController()\n const stop = signal ? AbortSignal.any([abort.signal, signal]) : abort.signal\n void admitted?.catch(error => { abort.abort(error) })\n const timeoutMs = box.timeoutMs ?? DEFAULT_SANDBOX_RUN_TIMEOUT_MS\n let activeTasks = 0\n let unconfirmed = false\n\n let start: Promise<SandboxInstance> | undefined = box.started?.catch((error: unknown) => {\n start = undefined\n throw error\n })\n // A turn that never calls the box never awaits its admission start; that start's failure is not unhandled.\n start?.catch(() => undefined)\n const acquire = async (): Promise<SandboxInstance> => {\n await admitted\n stop.throwIfAborted()\n return start ??= box.acquire(stop).catch((error: unknown) => { start = undefined; throw error })\n }\n\n let settled: Promise<void> | undefined\n const settle = () => settled ??= (async () => {\n abort.abort(new Error('The hybrid turn settled'))\n await (box.started ?? start)?.catch(() => undefined)\n const results = await Promise.allSettled([Promise.resolve().then(() => box.dispose?.()), Promise.resolve().then(() => onSettled?.())])\n for (const result of results) if (result.status === 'rejected') {\n console.error(JSON.stringify({ event: 'hybrid_turn_settle_failed', error: redactErrorMessage(result.reason) }))\n }\n })()\n\n try {\n const step = box.computer\n ? createComputerStep({ ...box.computer, parentExecutionId: box.computer.parentExecutionId ?? router.traceId })\n : undefined\n const runBoxTask = box.runTask ?? step?.runTask\n if (!runBoxTask) throw new Error('A hybrid box needs runTask or computer')\n const warnings = new Map<string, ProducerNoticeEvent>()\n // Each failed call's redacted cause chain, by call id, recorded before the engine reports the call's error.\n const details = new Map<string, string>()\n const withWarnings = (parts: Array<Record<string, unknown>>) => parts.flatMap(part => {\n const warning = warnings.get(String(part.callID ?? part.id ?? ''))\n return warning ? [part, noticePart(warning.noticeKind, warning.id, warning.text, warning.code, warning.detail)] : [part]\n })\n const sandboxRun = createSandboxRunTool({\n box: () => acquire(),\n runTask: async (...args) => {\n await admitted\n stop.throwIfAborted()\n if (unconfirmed || activeTasks > 0) throw new SandboxRunError('sandbox_unconfirmed', 'An earlier computer step may still be running; no further task was dispatched.')\n activeTasks++\n try { return await runBoxTask(...args) }\n catch (error) {\n if (!(error instanceof SandboxRunError) || error.code === 'sandbox_unconfirmed') unconfirmed = true\n throw error\n } finally { activeTasks-- }\n },\n memberRequest: router.userMessage,\n timeoutMs,\n signal: stop,\n ...(box.warm ? { warm: box.warm } : {}),\n onFailure: (error, call) => {\n const detail = box.failureDetail ? box.failureDetail(error) : sandboxRunFailureDetail(error)\n if (call.callId && detail) details.set(call.callId, detail)\n if (box.onFailure) box.onFailure(error, call)\n else console.error(JSON.stringify({ event: 'agent_app_sandbox_run_failed', callId: call.callId ?? null, code: error.code,\n detail: sandboxRunFailureDetail(error) }))\n },\n ...(box.name ? { name: box.name } : {}),\n ...(box.description ? { description: box.description } : {}),\n })\n const speculator = createEscalationSpeculator({\n warm: acquire,\n escalationTools: [sandboxRun.name],\n ...(onSpeculate ? { onSpeculate } : {}),\n })\n speculator.onInput({ text: speculateOn ?? router.userMessage, ...(attachments ? { attachments } : {}) })\n\n const extra = guidance === false ? '' : [guidance ?? HYBRID_TURN_GUIDANCE, step?.guidance].filter(Boolean).join('\\n\\n')\n const producer = createRouterTurnProducer({\n ...router,\n systemPrompt: Promise.resolve(router.systemPrompt).then(prompt => !extra ? prompt : typeof prompt === 'string'\n ? `${prompt}\\n\\n${extra}` : { ...prompt, stable: [...(prompt.stable ?? []), extra] }),\n tools: [...tools, sandboxRun],\n admitted,\n // A turn that calls the box must outlive the call it waits on.\n budgetMs: router.budgetMs ?? timeoutMs + 60_000,\n signal: stop,\n onSettled: settle,\n onEvent: event => {\n speculator.onEvent(event as { type: string; toolName?: string })\n if (event.type === 'tool' && event.status === 'error' && event.toolName === sandboxRun.name && !stop.aborted) {\n const code = event.error.code\n if (code === 'sandbox_unconfirmed') unconfirmed = true\n if (code === 'sandbox_unavailable' || code === 'sandbox_failed' || code === 'sandbox_unconfirmed' || code === 'sandbox_empty') {\n const detail = details.get(event.callId)\n warnings.set(event.callId, {\n type: 'notice', noticeKind: 'warning', id: `sandbox-warning:${event.callId}`, code,\n text: code === 'sandbox_unavailable'\n ? 'The workspace computer is unavailable. I can continue with work that does not need it.'\n : 'The computer step did not return a confirmed answer. I can continue with work that does not need it.',\n ...(detail ? { detail } : {}),\n })\n }\n }\n router.onEvent?.(event)\n },\n })\n const events = (async function* () {\n for await (const event of producer.stream) {\n yield event\n // A box agent's question (`computer.questions`) reaches the member as the interaction it is; the answer\n // goes to the box through the app's interaction route.\n const side = event.type === 'tool.event' ? event.data as { kind?: unknown; data?: unknown } | undefined : undefined\n if (side?.kind === 'computer_interaction' && side.data && typeof side.data === 'object') yield side.data as ChatRouteEvent\n if (event.type === 'tool_result') {\n const warning = warnings.get(event.toolCallId)\n if (warning) yield warning\n }\n }\n })()\n // Closing before the wrapper's first pull must still abort the running Router.\n const end = events.return.bind(events)\n const fail = events.throw.bind(events)\n events.return = async value => {\n const closing = producer.stream.return(value)\n try { return await end(value) } finally { await closing }\n }\n events.throw = async error => {\n const closing = producer.stream.throw(error)\n try { return await fail(error) } finally { await closing }\n }\n return { ...producer, stream: events,\n terminalObserved: () => activeTasks === 0 && !unconfirmed,\n assistantParts: () => withWarnings(producer.assistantParts?.() ?? []),\n draftParts: () => withWarnings(producer.draftParts?.() ?? []),\n get model() { return producer.model },\n }\n } catch (error) {\n // Construction failures use the same tracked lifetime as stream failures, including a key still arriving.\n return createRouterTurnProducer({ ...router, systemPrompt: Promise.reject(error), signal: stop, onSettled: settle })\n }\n}\n","/**\n * Model failover for a STREAMING turn.\n *\n * `/model-resolution`'s `runWithModelFailover` already owns the policy: walk a\n * chain, classify a resolved-or-thrown signal, re-throw a non-outage failure\n * immediately, and carry the attempt trail. This module does NOT re-implement\n * any of that — it composes it. What it adds is the one thing a whole-call\n * primitive cannot express, because a stream fails PARTWAY:\n *\n * **A turn may only fail over before its first client-visible byte.**\n *\n * Once a text delta, tool call, or ask has reached the browser (and the\n * persisted transcript), restarting on another model would duplicate the\n * answer. So each attempt is probed: open the stream, pull events into a small\n * buffer, and decide at the first meaningful event whether this model is\n * serving. Committing replays the buffer and hands the live iterator through;\n * abandoning discards the buffer (those events describe the dead model's\n * session — including its `step-finish` usage, which must never be billed) and\n * lets `runWithModelFailover` walk to the next model.\n *\n * `liveLifecycleEvents` relaxes the buffer for progress only. `start`,\n * `status`, `model-processing`, and session lifecycle carry no answer and no\n * receipt, so a product may take them the moment they arrive and show what\n * the turn is waiting on.\n * OpenCode reports whole parts, so the buffer held every event for 16 s and\n * the product could show nothing through provisioning and agent startup. Off\n * by default: with it on, an abandoned model's progress stays in the stream.\n *\n * The classification itself is `isUpstreamUnavailable` verbatim, so this path\n * inherits the measured facts from the 2026-07-25 outage — above all that an\n * outage is NOT always a thrown error: the sandbox RESOLVES a terminal `error`\n * event carrying `{ errorCode: 'provider_inference_unavailable' }`, which a\n * classifier inspecting only `catch` misses entirely. That resolved shape is\n * the whole reason the breakage went unnoticed, so it is classified here first.\n *\n * Conservative by construction:\n * - A terminal failure that is NOT an outage (400, bad schema, content filter)\n * COMMITS rather than failing over — it surfaces to the user exactly as it\n * does today. Those fail identically on every model; walking the chain would\n * only multiply latency and spend to reach the same error.\n * - A clean stream that produced nothing NEVER walks the chain. An empty answer\n * is not evidence of a dead upstream, and a silent re-roll on another model is\n * precisely the unattributable downgrade this work exists to prevent. Opt-in\n * `emptyTurnRetries` re-runs the SAME model instead, which leaves attribution\n * untouched — measured on production 2026-07-27, an empty turn is a transient\n * platform flake that a same-model re-run recovers (8 hard cases: 7/8\n * delivered on the first pass, 8/8 with one re-run, at a cost of 1 extra turn\n * in 9). Default `0`, so the behavior is unchanged unless a product asks.\n * - A responsive chain of length 1 costs no extra call or latency and remains\n * byte-identical to no failover. A silent chain is now deliberately bounded.\n */\n\nimport {\n isUpstreamUnavailable,\n ModelFailoverExhaustedError,\n readUpstreamUnavailableCode,\n readHttpStatusHint,\n runWithModelFailover,\n type ModelFailoverAttempt,\n} from '../model-resolution/failover'\nimport type { ModelPolicy } from '../policy-filters/index'\nimport { asRecord, asString } from '../stream/index'\n\n/** Terminal event types that end an attempt with a failure verdict. */\nconst TERMINAL_FAILURE_TYPES = new Set(['error', 'session.run.failed'])\n\n/**\n * Part types that carry no transcript content. They are buffered like anything\n * else — replayed verbatim when the attempt commits — but their presence alone\n * never commits a model, so an outage arriving right after a `step-start` is\n * still recoverable. `step-finish` matters most: it carries the abandoned\n * attempt's token/cost receipt, which must be discarded rather than billed.\n */\nconst NON_COMMITTING_PART_TYPES = new Set(['step-start', 'step-finish'])\n\n/**\n * True when `event` puts content in front of the user (or in the persisted\n * transcript), making a restart on another model unsafe.\n *\n * Deliberately an allow-list of KNOWN-INERT types rather than a deny-list: an\n * unrecognized event commits. Getting this wrong in the safe direction costs a\n * missed failover; getting it wrong the other way duplicates a user's answer.\n */\nexport function isCommittingSandboxEvent(event: unknown): boolean {\n const record = asRecord(event)\n if (!record) return false\n const type = asString(record.type) ?? ''\n if (!type) return false\n\n if (type === 'message.part.updated') {\n const data = asRecord(record.data)\n const part = asRecord(data?.part)\n const partType = asString(part?.type) ?? ''\n if (NON_COMMITTING_PART_TYPES.has(partType)) return false\n // A text/reasoning part with NO content yet (the platform opens the part\n // with `text: \"\"` before the first token — verbatim in the 2026-07-26\n // capture) puts nothing in front of the user; discarding it cannot\n // duplicate an answer. The first real token commits.\n if (partType === 'text' || partType === 'reasoning') {\n return [data?.delta, part?.text, part?.content]\n .some(value => typeof value === 'string' && value.length > 0)\n }\n return true\n }\n\n // Session/turn lifecycle, progress status, and warnings belong to the\n // attempt, not the transcript — discardable with an abandoned model.\n // Captured examples: a dead model\n // emits `start`, `execution.started`, `status`×3, `session.updated`×2,\n // `warning`×2 BEFORE its terminal `error` — any one of them committing\n // would pin the turn to the dead model and kill the failover.\n if (\n type === 'start' ||\n type === 'execution.started' ||\n type === 'status' ||\n type === 'model-processing' ||\n type === 'model.processing' ||\n // Public Sandbox timing metadata: a request was attempted, not answered.\n type === 'model.first_request' ||\n type === 'session.created' ||\n type === 'session.updated' ||\n type === 'session.idle' ||\n type === 'step-start' ||\n type === 'step-finish' ||\n type === 'turn' ||\n type === 'warning'\n ) {\n return false\n }\n\n // Everything else — text/tool shapes the producer folds, asks, plans,\n // `result`/`done`, and any type this shell does not recognize — commits.\n return true\n}\n\n/**\n * Condense an abandoned attempt's raw failure text into something safe to show\n * a customer in the transcript.\n *\n * Measured on the live router 2026-07-27 19:40 UTC: an edge 5xx arrives as\n * Cloudflare's full HTML error PAGE, so the verbatim reason began\n * `<!DOCTYPE html>\\n<!--[if lt IE 7]> <html class=\"no-js ie6 oldie\"…` and the\n * fallback notice pasted 200 bytes of that markup into the answer the customer\n * reads. The cause is worth stating; the markup is not.\n *\n * Only the DISPLAY string is condensed. The full text stays on\n * `modelFailover.attempts[].reason` for the operator, so nothing is lost —\n * this narrows what the customer sees, never what telemetry records.\n */\nexport function summarizeFailoverReason(reason: string): string {\n const collapsed = reason.replace(/\\s+/g, ' ').trim()\n if (!collapsed) return 'upstream unavailable'\n\n // An HTML error page carries no message worth quoting — the status is the\n // whole content. Detected on the ORIGINAL text, before collapsing, because\n // that is the form the producer hands over.\n if (/<!doctype html|<html[\\s>]/i.test(collapsed)) {\n const status = readHttpStatusHint(collapsed)\n return status ? `HTTP ${status}` : 'upstream returned an error page'\n }\n\n // Anything else is a real message. Cap it so a verbose upstream cannot push\n // the answer off the screen, and cut on a word boundary when one is near.\n const LIMIT = 160\n if (collapsed.length <= LIMIT) return collapsed\n const clipped = collapsed.slice(0, LIMIT)\n const lastSpace = clipped.lastIndexOf(' ')\n return `${(lastSpace > LIMIT - 30 ? clipped.slice(0, lastSpace) : clipped).trimEnd()}…`\n}\n\n/** A terminal failure event, classified. `outage` decides failover vs surface. */\ninterface TerminalFailure {\n outage: boolean\n reason: string\n code?: string\n}\n\n/**\n * Classify a terminal failure event. Returns `null` for any non-terminal event.\n *\n * The RESOLVED shape is checked first and deliberately: the sandbox reports an\n * upstream outage by resolving `{ success: false, errorCode:\n * 'provider_inference_unavailable' }` inside a terminal `error` event's `data`,\n * never by throwing. Both `data` and the whole record are offered to\n * `isUpstreamUnavailable` so a payload nested either way is caught.\n */\n/**\n * Progress the consumer may see before the commit point: it names no model\n * output and carries no billing receipt, so streaming it live cannot duplicate\n * an answer or bill an abandoned attempt. `warning` and every\n * `message.part.updated` (including `step-start`/`step-finish`) stay buffered.\n */\nexport function isLiveLifecycleEvent(event: unknown): boolean {\n const type = asString(asRecord(event)?.type) ?? ''\n return (\n type === 'start' ||\n type === 'execution.started' ||\n type === 'status' ||\n type === 'model-processing' ||\n type === 'model.processing' ||\n // Public Sandbox timing metadata: a request was attempted, not answered.\n type === 'model.first_request' ||\n type === 'session.created' ||\n type === 'session.updated' ||\n type === 'session.idle'\n )\n}\n\nexport function classifyTerminalFailure(event: unknown): TerminalFailure | null {\n const record = asRecord(event)\n if (!record) return null\n const type = asString(record.type) ?? ''\n if (!TERMINAL_FAILURE_TYPES.has(type)) return null\n\n const data = asRecord(record.data)\n const outage = isUpstreamUnavailable(data) || isUpstreamUnavailable(record)\n const reason =\n asString(data?.message) ??\n asString(data?.error) ??\n asString(data?.reason) ??\n asString(record.message) ??\n `sandbox stream reported ${type}`\n const code =\n readUpstreamUnavailableCode(data) ??\n asString(data?.errorCode) ??\n asString(data?.code) ??\n readUpstreamUnavailableCode(record) ??\n asString(record.errorCode) ??\n asString(record.code)\n return { outage, reason, ...(code ? { code } : {}) }\n}\n\n/** A model that served: its buffered preamble plus the still-live iterator. */\ninterface AttemptCommit {\n committed: true\n buffered: unknown[]\n /** `null` when the stream already ended during the probe. */\n iterator: AsyncIterator<unknown> | null\n /** Cancel transport work when this attempt is drained or abandoned. */\n abort: () => void\n}\n\n/**\n * A model whose upstream is down. `error`/`errorCode` are read by\n * `runWithModelFailover`'s attempt-trail describe(), so the trail names the\n * real upstream cause rather than a wrapper's own words.\n */\ninterface AttemptOutage {\n committed: false\n error: string\n errorCode?: string\n timeoutCode?: ModelAttemptTimeoutCode\n}\n\ntype AttemptOutcome = AttemptCommit | AttemptOutage\n\n/** Open the raw turn stream for one specific model. */\nexport type OpenModelStream = (args: {\n model: string\n /** 1 for the preferred model, 2 for the first fallback, and so on. */\n attempt: number\n /** Aborted when this attempt times out, is abandoned, or finishes. Forward\n * this to `streamSandboxPrompt(..., { signal })` so a blocked transport is\n * cancelled immediately rather than only receiving iterator.return(). */\n signal: AbortSignal\n}) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>\n\n/** Fired when a model is abandoned and the next one is about to be tried. */\nexport interface ModelFallbackInfo {\n from: string\n to: string\n reason: string\n}\n\n/** Define inputs for streaming a turn across a model failover chain */\nexport interface ModelFailoverStreamOptions {\n /** Preferred model first, then fallbacks in descending preference. */\n models: readonly string[]\n open: OpenModelStream\n /**\n * Product admission policy applied to EVERY chain member before its stream\n * is opened — see `runWithModelFailover`'s `policy`. A member the policy\n * refuses is skipped (never opened, never sent the turn's data) and the walk\n * continues; an all-refused chain ends in `ModelFailoverExhaustedError`.\n */\n policy?: ModelPolicy\n /**\n * Maximum time to open/start one model's event source, including its first\n * iterator pull. Default 120 seconds, matching the sandbox provisioning\n * ceiling so cold infrastructure startup is bounded independently from\n * provider inference.\n */\n openTimeoutMs?: number\n /**\n * Hard deadline from the source's first lifecycle event to its first\n * answer-bearing event. Default 60 seconds. Processing/lifecycle events do\n * not commit the attempt and do not extend this deadline.\n */\n firstResponseTimeoutMs?: number\n /** Override the commit-point rule. Default {@link isCommittingSandboxEvent}. */\n isCommitting?: (event: unknown) => boolean\n /**\n * Stream {@link isLiveLifecycleEvent} progress to the consumer as it arrives\n * instead of holding it until the attempt commits. Default `false`, which\n * keeps an abandoned model's events entirely off the wire. With it on, such\n * an event is never replayed from the buffer, and one from an abandoned\n * attempt stays in the stream — it describes the sandbox, not the answer.\n */\n liveLifecycleEvents?: boolean\n onFallback?: (info: ModelFallbackInfo) => void\n /**\n * How many times to RE-RUN THE SAME MODEL when a turn completes having\n * produced no assistant text at all. Default `0` — byte-identical to no\n * retry.\n *\n * This is deliberately not a chain walk. Falling over to a different model\n * on an empty answer is the unattributable downgrade this module refuses to\n * do; re-running the SAME model changes nothing about attribution, because\n * the model that serves is the model that was asked for.\n *\n * Bounded by the same commit rule as failover: only a turn whose ONLY\n * committing event is a terminal receipt with no text is retried, so nothing\n * that reached the user can ever be produced twice.\n */\n emptyTurnRetries?: number\n /** Fired when an empty turn is discarded and the same model re-run. */\n onEmptyTurnRetry?: (info: EmptyTurnRetryInfo) => void\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** One same-model re-run of a turn that completed with no assistant text. */\nexport interface EmptyTurnRetryInfo {\n model: string\n /** 1 for the first re-run. */\n retry: number\n /** How many re-runs remain after this one. */\n remaining: number\n}\n\n/** The failover-wrapped stream plus the attribution every consumer needs. */\nexport interface ModelFailoverStreamHandle {\n events: AsyncGenerator<unknown, void, unknown>\n /** The model that actually served. `undefined` until the first pull resolves it. */\n servingModel(): string | undefined\n /** Every model tried, in order, with the reason each was abandoned. */\n attempts(): ModelFailoverAttempt[]\n /** True when the preferred model did not serve — the attributability signal. */\n usedFallback(): boolean\n}\n\n/** Default ceiling for opening/starting one source through its first event. */\nexport const DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS = 120_000\n\n/** Default ceiling for the first answer-bearing event after the source's first event. */\nexport const DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS = 60_000\n\n/** Structured timeout codes surfaced by the producer on final exhaustion. */\nexport type ModelAttemptTimeoutCode =\n | 'model_stream_open_timeout'\n | 'provider_first_response_timeout'\n\n/** Every configured model was exhausted and the final one timed out. */\nexport class ModelFailoverTimeoutError extends ModelFailoverExhaustedError {\n readonly code: ModelAttemptTimeoutCode\n readonly model: string\n readonly timeoutMs: number\n\n constructor(input: {\n attempts: ModelFailoverAttempt[]\n code: ModelAttemptTimeoutCode\n model: string\n timeoutMs: number\n }) {\n super(input.attempts)\n this.name = 'ModelFailoverTimeoutError'\n this.code = input.code\n this.model = input.model\n this.timeoutMs = input.timeoutMs\n this.message = input.code === 'model_stream_open_timeout'\n ? `Opening the model event source for ${input.model} exceeded ${input.timeoutMs}ms.`\n : `Model ${input.model} produced no first answer-bearing event within ${input.timeoutMs}ms.`\n }\n}\n\nfunction resolveTimeoutMs(value: number | undefined, fallback: number, label: string): number {\n if (value === undefined) return fallback\n if (!Number.isFinite(value) || value <= 0) {\n throw new RangeError(`${label} must be a finite number greater than 0`)\n }\n return Math.max(1, Math.trunc(value))\n}\n\nconst TIMED_OUT = Symbol('model-attempt-timed-out')\n\nfunction deadlineAfter(timeoutMs: number): {\n promise: Promise<typeof TIMED_OUT>\n clear: () => void\n} {\n let timer: ReturnType<typeof setTimeout> | undefined\n const promise = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs)\n })\n return {\n promise,\n clear: () => {\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n },\n }\n}\n\n/**\n * True when `event` is a terminal receipt (`result` / `done`) carrying no\n * assistant text.\n *\n * Measured on production `sandbox.tangle.tools` (28 turns through\n * the gtm-agent profile): a turn can end `{ outcome: { type: 'completed' } }`\n * with `finalText: ''` and zero token events — the platform reports success and\n * the customer's message is blank. It is not an outage, nothing throws, and\n * `isUpstreamUnavailable` correctly declines to classify it, so before this the\n * blank answer committed and shipped.\n */\nfunction isEmptyTerminalReceipt(event: unknown): boolean {\n const record = asRecord(event)\n if (!record) return false\n const type = asString(record.type) ?? ''\n if (type !== 'result' && type !== 'done') return false\n const data = asRecord(record.data)\n const text = asString(data?.finalText) ?? asString(data?.text) ?? ''\n return text.trim().length === 0\n}\n\n/**\n * Hard ceiling on same-model re-runs. A turn that comes back blank three times\n * running is not a flake this can retry away, and each pass costs a full\n * sandbox turn — so the budget is capped rather than trusted.\n */\nexport const MAX_EMPTY_TURN_RETRIES = 3\n\n/**\n * Coerce the caller's budget to a finite, bounded, non-negative integer.\n *\n * `Math.trunc(NaN)` is `NaN` and `retry >= NaN` is false for every `retry`, so\n * a naive clamp turns a bad config value into a loop that opens sandbox streams\n * until the worker dies. `Infinity` has the same shape. Both resolve to `0` —\n * an unusable budget disables the retry rather than running unbounded.\n */\nexport function resolveEmptyTurnRetries(value: number | undefined): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return 0\n const truncated = Math.trunc(value)\n if (truncated <= 0) return 0\n return Math.min(truncated, MAX_EMPTY_TURN_RETRIES)\n}\n\n/** Abandon a dead attempt's iterator. Never allowed to mask the outage. */\nasync function closeIterator(iterator: AsyncIterator<unknown>, log?: ModelFailoverStreamOptions['log']): Promise<void> {\n try {\n await iterator.return?.()\n } catch (err) {\n log?.('[chat-routes] abandoning a failed model stream threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n}\n\n/**\n * Wrap `open` in reactive model failover, streaming from the first model in\n * `models` that reaches its commit point.\n *\n * Zero added latency on the happy path: the preferred model is opened first and,\n * the moment it emits anything meaningful, its events flow straight through.\n *\n * @throws ModelFailoverTimeoutError when the final model times out,\n * ModelFailoverExhaustedError when every model's upstream is down, and\n * re-throws a non-outage error from the FIRST model without walking the\n * chain (the latter behaviors are inherited from\n * `runWithModelFailover`).\n */\nexport function streamWithModelFailover(\n options: ModelFailoverStreamOptions,\n): ModelFailoverStreamHandle {\n const committing = options.isCommitting ?? isCommittingSandboxEvent\n const emptyTurnRetries = resolveEmptyTurnRetries(options.emptyTurnRetries)\n const openTimeoutMs = resolveTimeoutMs(\n options.openTimeoutMs,\n DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS,\n 'openTimeoutMs',\n )\n const firstResponseTimeoutMs = resolveTimeoutMs(\n options.firstResponseTimeoutMs,\n DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS,\n 'firstResponseTimeoutMs',\n )\n const liveLifecycle = options.liveLifecycleEvents === true\n const progress = createProgressQueue()\n let serving: string | undefined\n let trail: ModelFailoverAttempt[] = []\n let fellBack = false\n const attemptState = { index: 0 }\n let finalTimeout: {\n code: ModelAttemptTimeoutCode\n model: string\n timeoutMs: number\n } | undefined\n\n /**\n * One open-and-drain pass. `empty` marks the pass as an EMPTY TURN — the\n * only committing event was a terminal receipt with no assistant text, so\n * nothing reached the user and the pass can be discarded without any risk of\n * producing an answer twice. It still carries the outcome it would otherwise\n * have returned, so exhausting the retry budget is byte-identical to no\n * retry at all.\n */\n const { drainOnce } = createModelAttemptDrainer(attemptState, options, openTimeoutMs, firstResponseTimeoutMs, committing, liveLifecycle, progress)\n\n const probe = async (model: string): Promise<AttemptOutcome> => {\n // Only the FINAL attempted model decides the exhaustion code. Clear a\n // prior model's timeout before this model can throw a different outage.\n finalTimeout = undefined\n for (let retry = 0; ; retry += 1) {\n const pass = await drainOnce(model)\n if (!pass.empty || retry >= emptyTurnRetries) {\n if (!pass.outcome.committed && pass.outcome.timeoutCode) {\n finalTimeout = {\n code: pass.outcome.timeoutCode,\n model,\n timeoutMs: pass.outcome.timeoutCode === 'model_stream_open_timeout'\n ? openTimeoutMs\n : firstResponseTimeoutMs,\n }\n } else {\n finalTimeout = undefined\n }\n return pass.outcome\n }\n // Discard the empty pass entirely — including its `step-finish` token\n // receipt, which must not be billed — and re-run the same model.\n const iterator = pass.outcome.committed ? pass.outcome.iterator : null\n if (pass.outcome.committed) pass.outcome.abort()\n if (iterator) void closeIterator(iterator, options.log)\n const info: EmptyTurnRetryInfo = { model, retry: retry + 1, remaining: emptyTurnRetries - retry - 1 }\n options.log?.('[chat-routes] turn completed with no assistant text; re-running the same model', {\n ...info,\n })\n options.onEmptyTurnRetry?.(info)\n }\n }\n\n const events = (async function* (): AsyncGenerator<unknown, void, unknown> {\n let handle: AttemptCommit\n // Progress arrives while the probe is still running. The queue closes only\n // after the verdict settles, so every event pushed before it is delivered\n // in order and ahead of the replayed buffer.\n const settled = runWithModelFailover<AttemptOutcome>({\n models: options.models,\n run: probe,\n ...(options.policy ? { policy: options.policy } : {}),\n // The probe has already classified the raw payload with\n // `isUpstreamUnavailable`; this reads its verdict rather than\n // re-classifying a wrapper object, so the two can never disagree.\n isUnavailableResult: (result) => result.committed === false,\n onFallback: (attempt, nextModel) => {\n const info: ModelFallbackInfo = {\n from: attempt.model,\n to: nextModel,\n reason: attempt.reason ?? 'upstream unavailable',\n }\n options.log?.('[chat-routes] model upstream unavailable; falling over', { ...info })\n options.onFallback?.(info)\n },\n }).finally(() => progress.close())\n // The verdict is read after the drain; mark the rejection handled until then.\n settled.catch(() => undefined)\n for (;;) {\n const item = await progress.pull()\n if (item === PROGRESS_CLOSED) break\n yield item\n }\n try {\n const outcome = await settled\n serving = outcome.model\n trail = outcome.attempts\n fellBack = outcome.usedFallback\n handle = outcome.value as AttemptCommit\n } catch (err) {\n // Exhaustion carries the full trail; keep it so the receipt still names\n // every model tried even though the turn produced nothing.\n const attempts = (err as { attempts?: ModelFailoverAttempt[] })?.attempts\n if (Array.isArray(attempts)) trail = attempts\n if (err instanceof ModelFailoverExhaustedError && finalTimeout) {\n throw new ModelFailoverTimeoutError({\n attempts: trail,\n ...finalTimeout,\n })\n }\n throw err\n }\n\n for (const event of handle.buffered) yield event\n\n const live = handle.iterator\n if (!live) {\n handle.abort()\n return\n }\n try {\n for (;;) {\n const next = await live.next()\n if (next.done) return\n yield next.value\n }\n } finally {\n // The consumer may abandon this generator mid-turn (client drop); close\n // the underlying stream rather than leaking it.\n handle.abort()\n await closeIterator(live, options.log)\n }\n })()\n\n return {\n events,\n servingModel: () => serving,\n attempts: () => trail,\n usedFallback: () => fellBack,\n }\n}\n\nconst PROGRESS_CLOSED: unique symbol = Symbol('progress-closed')\n\n/**\n * FIFO handoff from the probe (a plain promise chain) to the event generator.\n * `close` is idempotent and queues one sentinel behind everything pushed\n * before it, so a consumer never loses a progress event to the verdict.\n */\nfunction createProgressQueue(): {\n push(event: unknown): void\n close(): void\n pull(): Promise<unknown>\n} {\n const items: unknown[] = []\n const waiters: Array<(value: unknown) => void> = []\n let closed = false\n const deliver = (value: unknown): void => {\n const waiter = waiters.shift()\n if (waiter) waiter(value)\n else items.push(value)\n }\n return {\n push(event) {\n if (closed) return\n deliver(event)\n },\n close() {\n if (closed) return\n closed = true\n deliver(PROGRESS_CLOSED)\n },\n pull() {\n if (items.length > 0) return Promise.resolve(items.shift())\n if (closed) return Promise.resolve(PROGRESS_CLOSED)\n return new Promise((resolve) => waiters.push(resolve))\n },\n }\n}\n\nfunction createModelAttemptDrainer(\n attemptState: { index: number },\n options: ModelFailoverStreamOptions,\n openTimeoutMs: ReturnType<typeof resolveTimeoutMs>,\n firstResponseTimeoutMs: ReturnType<typeof resolveTimeoutMs>,\n committing: (event: unknown) => boolean,\n liveLifecycle: boolean,\n progress: ReturnType<typeof createProgressQueue>,\n) {\n const drainOnce = async (model: string): Promise<{ outcome: AttemptOutcome; empty: boolean }> => {\n attemptState.index += 1\n const controller = new AbortController()\n const abort = (): void => {\n if (!controller.signal.aborted) controller.abort()\n }\n const opening = Promise.resolve().then(() => options.open({\n model,\n attempt: attemptState.index,\n signal: controller.signal,\n }))\n const openDeadline = deadlineAfter(openTimeoutMs)\n let opened: AsyncIterable<unknown> | typeof TIMED_OUT\n try {\n opened = await Promise.race([opening, openDeadline.promise])\n } catch (err) {\n openDeadline.clear()\n abort()\n throw err\n }\n if (opened === TIMED_OUT) {\n openDeadline.clear()\n abort()\n // A Promise cannot be forcibly cancelled. If the abandoned open settles\n // later, close its iterator immediately so it cannot leak a connection.\n void opening.then(\n (lateSource) => {\n try {\n void closeIterator(lateSource[Symbol.asyncIterator](), options.log)\n } catch (err) {\n options.log?.('[chat-routes] closing a late model stream threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n (err) => {\n options.log?.('[chat-routes] abandoned model stream open rejected after timeout', {\n error: err instanceof Error ? err.message : String(err),\n })\n },\n )\n return {\n outcome: {\n committed: false,\n error: `Opening the model event source for ${model} exceeded ${openTimeoutMs}ms`,\n errorCode: 'model_stream_open_timeout',\n timeoutCode: 'model_stream_open_timeout',\n },\n empty: false,\n }\n }\n\n const source = opened\n let iterator: AsyncIterator<unknown>\n try {\n iterator = source[Symbol.asyncIterator]()\n } catch (err) {\n openDeadline.clear()\n abort()\n throw err\n }\n const buffered: unknown[] = []\n // Starting the source includes its first pull. `streamSandboxPrompt` is an\n // async generator, so its cold-start work does not execute until `next()`;\n // counting that time as provider inference would collapse the two phases.\n let next: IteratorResult<unknown> | typeof TIMED_OUT\n try {\n next = await Promise.race([\n Promise.resolve(iterator.next()),\n openDeadline.promise,\n ])\n } catch (err) {\n openDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n openDeadline.clear()\n if (next === TIMED_OUT) {\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: `Starting the model event source for ${model} exceeded ${openTimeoutMs}ms`,\n errorCode: 'model_stream_open_timeout',\n timeoutCode: 'model_stream_open_timeout',\n },\n empty: false,\n }\n }\n if (next.done) {\n abort()\n return { outcome: { committed: true, buffered, iterator: null, abort }, empty: true }\n }\n\n // One deadline for the WHOLE provider pre-response phase. Pulling a\n // lifecycle or processing event races the same promise; liveness cannot\n // reset the clock.\n const firstResponseDeadline = deadlineAfter(firstResponseTimeoutMs)\n\n for (;;) {\n const event = next.value\n let failure: TerminalFailure | null\n let commits = false\n try {\n failure = classifyTerminalFailure(event)\n commits = !failure && committing(event)\n } catch (err) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n if (failure?.outage) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: failure.reason,\n ...(failure.code ? { errorCode: failure.code } : {}),\n },\n empty: false,\n }\n }\n\n if (liveLifecycle && !failure && !commits && isLiveLifecycleEvent(event)) {\n progress.push(event)\n } else {\n buffered.push(event)\n }\n // A terminal NON-outage failure surfaces exactly as it does today.\n if (failure) {\n firstResponseDeadline.clear()\n return { outcome: { committed: true, buffered, iterator, abort }, empty: false }\n }\n if (commits) {\n firstResponseDeadline.clear()\n return { outcome: { committed: true, buffered, iterator, abort }, empty: isEmptyTerminalReceipt(event) }\n }\n\n // A THROWN failure propagates untouched: `runWithModelFailover` classifies\n // it (outage → next model, anything else → re-thrown to the caller).\n try {\n next = await Promise.race([\n Promise.resolve(iterator.next()),\n firstResponseDeadline.promise,\n ])\n } catch (err) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n if (next === TIMED_OUT) {\n firstResponseDeadline.clear()\n // Do not await `return()`: an async generator blocked inside `next()`\n // may not settle its return until that pull completes. Invoking it is\n // the cancellation signal; waiting for it would recreate the hang.\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: `Model ${model} produced no first answer-bearing event within ${firstResponseTimeoutMs}ms`,\n errorCode: 'provider_first_response_timeout',\n timeoutCode: 'provider_first_response_timeout',\n },\n empty: false,\n }\n }\n if (next.done) {\n firstResponseDeadline.clear()\n abort()\n // Clean end with nothing committing. Not an outage — but also not an\n // answer, so it is re-runnable on the same model.\n return { outcome: { committed: true, buffered, iterator: null, abort }, empty: true }\n }\n }\n }\n return { drainOnce }\n}\n","import type { SandboxChatProducerOptions } from './sandbox-producer'\nimport type { ChatTurnModelAttribution } from './turn-routes'\nimport { asRecord, asString, type JsonRecord } from '../stream/index'\nimport { buildModelChain } from '../model-resolution/failover'\nimport { streamWithModelFailover, resolveEmptyTurnRetries, summarizeFailoverReason, type ModelFailoverStreamHandle } from './model-failover-stream'\n\nfunction parseEffectiveBackend(data: JsonRecord): Omit<\n ChatTurnModelAttribution,\n 'requestedModel' | 'echoReceived'\n> | undefined {\n const backend = asRecord(data.effectiveBackend)\n if (!backend) return undefined\n const provider = asString(backend.provider)\n const model = asString(backend.model)\n const rawSource = asString(backend.source)\n const source =\n rawSource === 'request' || rawSource === 'environment' || rawSource === 'profile'\n ? rawSource\n : undefined\n if (!provider && !model && !source) return undefined\n return {\n ...(model ? { servedModel: model } : {}),\n ...(provider ? { servedProvider: provider } : {}),\n ...(source ? { servedSource: source } : {}),\n }\n}\n\nexport function createSandboxModelSource(options: SandboxChatProducerOptions, log: (message: string, meta?: Record<string, unknown>) => void) {\n if (options.openEvents && !options.model) {\n throw new Error(\n 'createSandboxChatProducer: `openEvents` requires `model` — failover must know which model it is running',\n )\n }\n if (!options.openEvents && !options.events) {\n throw new Error('createSandboxChatProducer: pass `openEvents` (failover-capable) or `events`')\n }\n // A fixed `events` stream cannot be re-opened, so the retry silently does\n // nothing. A config that asks for recovery and receives none is the exact\n // silent-no-op class this seam exists to remove — refuse it at construction\n // rather than let a product believe blank turns are being retried.\n if (!options.openEvents && resolveEmptyTurnRetries(options.emptyTurnRetries) > 0) {\n throw new Error(\n 'createSandboxChatProducer: `emptyTurnRetries` requires `openEvents` — a fixed `events` stream cannot be re-opened',\n )\n }\n const chain = options.model\n ? buildModelChain(options.model, options.modelFailover === false ? [] : (options.fallbackModels ?? []))\n : []\n\n /** Fallback notices waiting to be emitted. `onFallback` fires from inside the\n * first pull of the failover stream, where a generator cannot yield, so the\n * notice is queued and drained at the top of the next loop iteration —\n * landing immediately before the serving model's first event. */\n const pendingModelNotices: Array<{ id: string; text: string }> = []\n let modelNoticeCount = 0\n\n let openAttempts = 0\n let failover: ModelFailoverStreamHandle | undefined\n let source: AsyncIterable<unknown>\n if (options.openEvents) {\n const open = options.openEvents\n failover = streamWithModelFailover({\n models: chain,\n open: args => { openAttempts += 1; return open(args) },\n log,\n ...(options.modelPolicy ? { policy: options.modelPolicy } : {}),\n ...(options.openTimeoutMs !== undefined ? { openTimeoutMs: options.openTimeoutMs } : {}),\n ...(options.firstResponseTimeoutMs !== undefined\n ? { firstResponseTimeoutMs: options.firstResponseTimeoutMs }\n : {}),\n ...(options.emptyTurnRetries !== undefined ? { emptyTurnRetries: options.emptyTurnRetries } : {}),\n ...(options.onEmptyTurnRetry ? { onEmptyTurnRetry: options.onEmptyTurnRetry } : {}),\n ...(options.liveLifecycleEvents !== undefined ? { liveLifecycleEvents: options.liveLifecycleEvents } : {}),\n onFallback: (info) => {\n modelNoticeCount += 1\n pendingModelNotices.push({\n id: `model-fallback-${modelNoticeCount}`,\n // Named models on both sides: a quality regression after a downgrade\n // must be attributable to the model that actually answered. The\n // REASON is condensed — a real edge 5xx arrives as Cloudflare's HTML\n // error page, and the raw text put `<!DOCTYPE html><!--[if lt IE 7]>…`\n // into the customer's transcript. The verbatim text is still on\n // `modelFailover.attempts[].reason` for the operator.\n text: `${info.from} was unavailable (${summarizeFailoverReason(info.reason)}) — answered with ${info.to} instead.`,\n })\n options.onModelFallback?.(info)\n },\n })\n source = failover.events\n } else {\n source = options.events!\n }\n\n /** The model that ACTUALLY served this turn. Read lazily everywhere (the\n * `model` getter, the draft snapshot, the persisted row) so a fallback that\n * happens after the row was drafted still lands on the final write. */\n const servingModel = (): string | undefined => failover?.servingModel() ?? options.model\n const modelState = { effectiveBackend: undefined as ReturnType<typeof parseEffectiveBackend> }\n let substitutionNoticeQueued = false\n const servedModel = (): string | undefined => modelState.effectiveBackend?.servedModel ?? servingModel()\n\n const captureEffectiveBackend = (data: JsonRecord | undefined): void => {\n if (!data) return\n const parsed = parseEffectiveBackend(data)\n if (!parsed) return\n modelState.effectiveBackend = parsed\n const sentModel = servingModel()\n if (\n substitutionNoticeQueued ||\n !options.model ||\n !sentModel ||\n !parsed.servedModel ||\n sameModel(parsed.servedModel, sentModel)\n ) return\n substitutionNoticeQueued = true\n pendingModelNotices.push({\n id: 'model-substitution-1',\n text: `Requested ${sentModel} — the sandbox answered with ${parsed.servedModel} instead.`,\n })\n }\n return { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState, openAttempts: () => openAttempts }\n}\n\n/** The same model under a provider prefix (`zai-coding-plan/glm-5.3-flash` vs\n * `glm-5.3-flash`) is not a substitution; only a different model is. */\nfunction sameModel(a: string, b: string): boolean {\n const bare = (id: string) => id.slice(id.lastIndexOf('/') + 1).trim().toLowerCase()\n return bare(a) === bare(b)\n}\n","/**\n * Sandbox lane: bridge a raw sandbox event stream (`streamSandboxPrompt`) into\n * the `ChatTurnProducer` shape agent-runtime's `handleChatTurn` consumes AND\n * the client vocabulary `/web-react`'s `dispatchChatStreamLine` already parses\n * (`text` / `reasoning` / `tool_call` / `tool_result` / `usage` /\n * `notice` / structured `error` / `interaction`). Legal and tax each hand-rolled\n * this mapping differently;\n * this is that middle, composed from `/stream`'s normalizers — no new loop\n * logic, no SDK import (the event source is an injected `AsyncIterable`).\n *\n * Alongside the live mapping it accumulates the PERSISTED projection — the\n * `message.parts` rows `/chat-store` stores — via `normalizePersistedPart` /\n * `mergePersistedPart` / `finalizeAssistantParts`, plus the usage receipt from\n * `step-finish` parts. `createChatTurnRoutes` reads both after drain.\n */\n\nimport { createSandboxModelSource } from './sandbox-model-source'\n\nimport {\n cancelStatusFor,\n interactionPartKey,\n interactionToPersistedPart,\n isRenderableInteractionKind,\n noticePart,\n noticePartKey,\n parseInteractionCancel,\n parseInteractionRequest,\n type InteractionRequestWire,\n} from '../interactions/contract'\nimport {\n parsePlanSubmittedEvent,\n planToPersistedPart,\n} from '../plans/index'\nimport {\n asRecord,\n asString,\n draftAssistantParts,\n finalizeAssistantParts,\n finalizePendingInteractionParts,\n getPartKey,\n mergePersistedPart,\n normalizePersistedPart,\n normalizeToolEvent,\n terminalizeDanglingAssistantToolUpdates,\n type JsonRecord,\n type StreamEvent,\n} from '../stream/index'\nimport {\n ModelFailoverExhaustedError,\n type ModelFailoverAttempt,\n} from '../model-resolution/failover'\nimport type { ModelPolicy } from '../policy-filters/index'\nimport { isTerminalPromptEvent } from '../sandbox/prompt-events'\nimport { SandboxRunError } from '../sandbox/sandbox-run-error'\nimport {\n ModelFailoverTimeoutError,\n type EmptyTurnRetryInfo,\n type ModelFallbackInfo,\n type OpenModelStream,\n} from './model-failover-stream'\nimport { createReasoningClock, type ReasoningRunTime } from './reasoning-clock'\nimport type {\n ChatTurnRouteProducer,\n ChatTurnUsage,\n} from './turn-routes'\nimport { addStepFinishUsage } from './sandbox-turn-usage'\nimport type { ProducerWireEvent } from './wire'\n\n/** Outcome of a `promoteFilePart` attempt. `key`, when given, becomes the\n * persisted part's row key (e.g. `attachment:<path>`) so repeat promotions\n * of the same underlying file fold into one segment instead of appending;\n * omitted, the default `getPartKey` keying applies.\n *\n * On failure, `part` is an OPTIONAL substitute part to persist in place of\n * the raw url-bearing one — this is how a product swaps in a transcript\n * notice (gtm persists a `warning` notice part, never the transient url) for\n * a failed promotion instead of baking a `data:`/sandbox-path url into the\n * durable row. When `part` is present it is persisted (via the same\n * `recordPersistedPart` path as a success, honoring the optional `key`);\n * when absent, the existing raw-part fallback applies unchanged — so a\n * caller that only returns `{ succeeded: false, reason }` keeps today's\n * behavior verbatim. */\nexport type FilePartPromotionOutcome =\n | { succeeded: true; part: Record<string, unknown>; key?: string }\n | { succeeded: false; reason: string; part?: Record<string, unknown>; key?: string }\n\n/** Define options for producing sandbox chat events with rendering and interaction controls */\nexport interface SandboxChatProducerOptions {\n /** The raw sandbox event stream (e.g. `streamSandboxPrompt(...)`).\n *\n * An ALREADY-OPEN stream is bound to one model and cannot be reopened, so\n * this form can never fail over. Prefer {@link openEvents}; exactly one of\n * the two is required. */\n events?: AsyncIterable<unknown>\n /** Open the raw sandbox stream FOR A GIVEN MODEL — the failover-capable form\n * of {@link events}. The callback receives the model to run and returns the\n * same `AsyncIterable` `events` would have been (typically\n * `streamSandboxPrompt(shell, box, prompt, { ...opts, model })`).\n *\n * Wiring this turns failover ON with no further flag: whenever the resolved\n * chain (`model` + {@link fallbackModels}) holds more than one entry, a model\n * whose upstream is dead is abandoned BEFORE its first client-visible byte\n * and the next one is tried. A one-entry chain opens exactly once — no extra\n * call, no added latency, byte-identical to today.\n *\n * Requires {@link model}: failover has to know which model it is running. */\n openEvents?: OpenModelStream\n /** Recorded on the persisted assistant message. When failover moves the turn\n * to another model, the producer's `model` reports the model that ACTUALLY\n * served, not this preferred one — see {@link modelFailover}. */\n model?: string\n /** Models to try, in order, when `model`'s upstream is dead. Product config,\n * never a shell default: agent-app cannot know which ids are live, and a\n * baked list would rot into exactly the stale-liveness bug this guards\n * against. Empty/omitted → one attempt, today's behavior.\n *\n * Pick these deliberately. A same-family fallback is NOT automatically safe:\n * `gemini-2.5-flash` produced zero persisted deliverables in 2 of 3 measured\n * runs on a med-legal filing flow where `gemini-2.5-pro` succeeded. That is\n * why every fallback is surfaced (persisted `model`, a transcript notice, and\n * `modelFailover()`) instead of being applied silently. */\n fallbackModels?: readonly string[]\n /** Opt out of failover while still using {@link openEvents}. `false` collapses\n * the chain to `model` alone. */\n modelFailover?: false\n /**\n * Product admission policy applied to every chain member — the RESOLVED\n * preferred model AND every fallback — before its stream is opened. This is\n * the execution-time half of policy enforcement: it covers the model\n * whatever its source (request body, env, product default), and it is what\n * stops a compliant model's mid-turn 502 from re-running the turn's data\n * through a non-compliant fallback. A refused member is skipped with the\n * refusal recorded in `modelFailover().attempts`; an all-refused chain\n * exhausts. Omit → availability only (today's behavior).\n */\n modelPolicy?: ModelPolicy\n /** Maximum time to open/start one model event source through its first event.\n * Default 120 seconds. This is separate from provider first-output latency\n * so cold sandbox startup is not mislabeled as an inference failure. */\n openTimeoutMs?: number\n /** Hard deadline after the source's first lifecycle event for the first\n * answer-bearing event. Default 60 seconds. Processing/lifecycle events do\n * not extend it. */\n firstResponseTimeoutMs?: number\n /** Forward `start`/`status`/`model-processing`/session lifecycle to the\n * client as it arrives instead of after the commit point, so a product can\n * show what a turn is waiting on. Default `false`. An abandoned model's\n * progress then stays on the wire; its answer and receipt never do. */\n liveLifecycleEvents?: boolean\n /** Fired when a model is abandoned mid-chain (telemetry/alerting). The user\n * already sees a transcript notice; this is for the operator. */\n onModelFallback?: (info: ModelFallbackInfo) => void\n /** Re-run the SAME model this many times when a turn completes with no\n * assistant text at all. Default `0` (unchanged behavior). Requires\n * {@link openEvents} — there is nothing to re-open on a fixed stream.\n *\n * Distinct from {@link fallbackModels} on purpose: this never changes which\n * model answers, so it carries none of the attribution risk a downgrade\n * does. Measured on production 2026-07-27 through gtm-agent's profile, a\n * completed-but-blank turn is a transient platform flake — 8 hard cases went\n * 7/8 delivered to 8/8 with one re-run, costing 1 extra turn in 9. */\n emptyTurnRetries?: number\n /** Fired when a blank turn is discarded and the same model re-run. */\n onEmptyTurnRetry?: (info: EmptyTurnRetryInfo) => void\n /** Which ask kinds the product renders a card for. Anything else is\n * auto-declined (see `declineInteraction`) so the run never hangs in the\n * broker waiting on a card no client will show. Default: question/plan.\n * Products with per-turn plan mode can close over it without another option:\n * `(kind) => kind === 'question' || (kind === 'plan' && planEnabled)`.\n * The parsed request lets a product decline an ask by its content, such\n * as a question that duplicates a decision the product already shows. */\n isRenderableInteraction?: (kind: string, request: InteractionRequestWire) => boolean\n /** The transcript notice for an auto-declined ask; defaults to a policy line naming its kind. */\n declinedNotice?: (request: InteractionRequestWire, declineFailed: boolean) => string\n /** Resolve a non-renderable ask (wire `respondToSessionInteraction` with the\n * session's sidecar connection). Without it, a failure notice is emitted and\n * the run stays blocked until the broker times out. */\n declineInteraction?: (id: string) => Promise<void>\n /** Opt-in eager promotion of harness-emitted `file` parts. Unset, a `file`\n * part persists exactly as the harness sent it — a transient `url` (a\n * `data:` URI or in-sandbox path) baked into the transcript, which is\n * today's behavior and stays byte-identical if this is never wired. Set,\n * EVERY `file` part (never `image`, never any other kind) is routed\n * through this callback instead of `recordPersistedPart`'s default\n * fallback — including a part with NEITHER `id` NOR `url` (gtm always\n * attempts promotion; such a part simply fails \"carries no url\" and\n * resolves through the same failure path as any other rejection, rather\n * than being persisted raw and unpromoted) — so the product can durably\n * write the bytes and swap in a path-bearing part before the raw url ever\n * reaches the persisted transcript. Keyed per source-prefixed `id:<id>` /\n * `url:<url>` (an `id` and a `url` sharing the same text must never collide\n * onto one memo entry) and memoized by PROMISE (not result), so re-emitted\n * snapshot events for the same part —\n * the harness resends the whole part on every update, not just deltas —\n * fold onto the one in-flight or settled attempt rather than promoting\n * twice or racing two concurrent writes; a raw part with neither `id` nor\n * `url` cannot be keyed, so it is invoked UN-memoized (once per event) —\n * each occurrence is its own attempt. A rejecting promise is caught,\n * logged via `log`, and treated as `succeeded: false`. On `succeeded:\n * false` the outcome's optional `part` (a substitute — e.g. a warning\n * notice — see {@link FilePartPromotionOutcome}) persists in its place when\n * given; otherwise the raw part persists exactly as it does today — this\n * seam only decides whether to call the promoter and what to do with its\n * outcomes; the promotion mechanics (vault write, key derivation, notice\n * construction) live in the caller's callback, not here. */\n promoteFilePart?: (raw: JsonRecord) => Promise<FilePartPromotionOutcome>\n /** Append terminal error explanations to assistant text. Default true.\n * Set false when the application renders the structured error separately.\n * Error events, diagnostics, partial answers and tool settlement remain available. */\n includeErrorText?: boolean\n /** Record the terminal error explanation as an `error` notice part (persisted\n * on the assistant row and streamed as a `notice` event) instead of appending\n * it to the assistant text. A reloaded failed turn then carries a typed marker\n * a client renders in the danger tone, rather than prose indistinguishable\n * from the answer. Default false (today's text behavior). When true, the\n * error is never appended to the text, whatever `includeErrorText` says. */\n errorNotice?: boolean\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\ninterface TextTracker {\n /** Full accumulated text per part key, to derive suffix deltas from\n * snapshot-only harness events. */\n seen: Map<string, string>\n}\n\n/** Delta to emit for one text/reasoning part update: prefer the harness's\n * explicit delta; otherwise diff the snapshot against what was already\n * emitted for that part (snapshot-only harnesses re-send the whole text). */\nfunction textDelta(tracker: TextTracker, key: string, part: JsonRecord, rawDelta: unknown): string {\n const explicit = typeof rawDelta === 'string' ? rawDelta : undefined\n const previous = tracker.seen.get(key) ?? ''\n if (explicit !== undefined) {\n tracker.seen.set(key, previous + explicit)\n return explicit\n }\n const snapshot = asString(part.text) ?? asString(part.content) ?? ''\n if (!snapshot) return ''\n if (snapshot.startsWith(previous)) {\n tracker.seen.set(key, snapshot)\n return snapshot.slice(previous.length)\n }\n // The snapshot replaced the text outright — emit it whole; the persisted\n // projection stays correct because finalText is authoritative at finalize.\n tracker.seen.set(key, snapshot)\n return snapshot\n}\n\nfunction toFiniteNumber(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n return null\n}\n\n/** Parse authoritative usage from a terminal sandbox `result` or `done`. */\nfunction extractReportedTurnUsage(data: JsonRecord | null | undefined): ChatTurnUsage | null {\n const tokenUsage = asRecord(data?.tokenUsage)\n if (!tokenUsage) return null\n\n const inputTokens = toFiniteNumber(tokenUsage.inputTokens)\n const outputTokens = toFiniteNumber(tokenUsage.outputTokens)\n if (inputTokens === null || outputTokens === null) return null\n\n const reported: ChatTurnUsage = { inputTokens, outputTokens }\n const reasoningTokens = toFiniteNumber(tokenUsage.reasoningTokens)\n if (reasoningTokens !== null) reported.reasoningTokens = reasoningTokens\n const cacheReadTokens = toFiniteNumber(tokenUsage.cacheReadInputTokens)\n if (cacheReadTokens !== null) reported.cacheReadTokens = cacheReadTokens\n const cacheWriteTokens = toFiniteNumber(tokenUsage.cacheCreationInputTokens)\n if (cacheWriteTokens !== null) reported.cacheWriteTokens = cacheWriteTokens\n const costUsd = toFiniteNumber(data?.totalCostUsd) ?? toFiniteNumber(tokenUsage.cost)\n if (costUsd !== null) reported.costUsd = costUsd\n return reported\n}\n\n/** Native runtime usage events contain cumulative totals, including repeated terminal snapshots. */\nfunction extractUsageSnapshot(value: JsonRecord | null | undefined): ChatTurnUsage | null {\n const inputTokens = toFiniteNumber(value?.promptTokens)\n const outputTokens = toFiniteNumber(value?.completionTokens)\n if (inputTokens === null || outputTokens === null || inputTokens < 0 || outputTokens < 0) return null\n const reported: ChatTurnUsage = { inputTokens, outputTokens }\n const reasoningTokens = toFiniteNumber(value?.reasoningTokens)\n if (reasoningTokens !== null && reasoningTokens >= 0) reported.reasoningTokens = reasoningTokens\n const costUsd = toFiniteNumber(value?.providerCostUsd)\n if (costUsd !== null && costUsd >= 0) reported.costUsd = costUsd\n return reported\n}\n\nfunction applyTerminalUsage(reported: ChatTurnUsage, usage: ChatTurnUsage): void {\n usage.inputTokens = reported.inputTokens\n usage.outputTokens = reported.outputTokens\n if (reported.reasoningTokens !== undefined) usage.reasoningTokens = reported.reasoningTokens\n if (reported.cacheReadTokens !== undefined) usage.cacheReadTokens = reported.cacheReadTokens\n if (reported.cacheWriteTokens !== undefined) usage.cacheWriteTokens = reported.cacheWriteTokens\n if (reported.costUsd !== undefined) usage.costUsd = reported.costUsd\n}\n\nfunction sandboxStreamErrorMessage(data: unknown): string {\n const record = asRecord(data)\n const message = asString(record?.message) ?? asString(record?.error)\n if (message) return message\n try {\n return JSON.stringify(data) || 'Sandbox stream returned an error event without details.'\n } catch {\n return 'Sandbox stream returned an error event without details.'\n }\n}\n\n/** The typed reason a sandbox `error` event carries, or a generic stream-error code. */\nfunction sandboxStreamErrorCode(data: unknown): string {\n return asString(asRecord(data)?.code) ?? 'sandbox.stream_error'\n}\n\nfunction toProducerWireEvent(event: JsonRecord): ProducerWireEvent {\n return event as unknown as ProducerWireEvent\n}\n\nfunction sandboxStreamFailureDiagnostic(error: unknown): {\n userMessage: string\n failureNote: string\n code: string\n} {\n const streamMessage = (error as { streamMessage?: unknown })?.streamMessage\n const message = typeof streamMessage === 'string'\n ? streamMessage\n : error instanceof Error ? error.message : 'Sandbox stream failed'\n const diagnostics = asRecord((error as { diagnostics?: unknown })?.diagnostics)\n let diagnosticText: string | undefined\n if (diagnostics) {\n try {\n diagnosticText = JSON.stringify(diagnostics)\n } catch {\n diagnosticText = '[unserializable diagnostics]'\n }\n }\n const userMessage = [\n 'The sandbox model stream stopped before a clean completion.',\n `Error: ${message}`,\n 'Please retry. If it repeats, send these support details to the team.',\n ].join('\\n\\n')\n const failureNote = diagnosticText\n ? `sandbox-stream: ${message}; ${diagnosticText}`\n : `sandbox-stream: ${message}`\n let code = 'sandbox.stream_failed'\n if (error instanceof SandboxRunError) {\n code = error.code\n } else if (error instanceof ModelFailoverTimeoutError) {\n code = error.code\n } else if (error instanceof ModelFailoverExhaustedError) {\n code = error.upstreamCode ?? code\n }\n return { userMessage, failureNote, code }\n}\n\n/** Create a sandbox chat producer that manages chat turn routing with logging and interaction rendering options */\nexport function createSandboxChatProducer(options: SandboxChatProducerOptions): ChatTurnRouteProducer {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind\n\n // ── model failover ────────────────────────────────────────────────────────\n // ON by default whenever the caller can reopen the stream (`openEvents`) and\n // named more than one model. There is no `enabled` flag on purpose: the class\n // of failure this fixes was a capability that shipped switched off, and a\n // second opt-in on top of supplying the chain would reproduce it exactly.\n const { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState, openAttempts } = createSandboxModelSource(options, log)\n\n const projectionState: SandboxProjectionState = {\n fullText: '',\n terminalObserved: false,\n stepCounter: 0,\n danglingToolsTerminalized: false,\n interactionOutcome: 'answered',\n warningCount: 0,\n errorNoticeCount: 0,\n }\n\n const { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder } = createSandboxProjection(projectionState, pendingModelNotices)\n\n let observedSourceEvent = false\n let preflightRefused = false\n async function* stream(): AsyncGenerator<ProducerWireEvent, void, unknown> {\n try {\n for await (const raw of source) {\n observedSourceEvent = true\n const record = asRecord(raw)\n captureEffectiveBackend(asRecord(record?.data))\n yield* drainModelNotices()\n if (!record || typeof record.type !== 'string') continue\n // Fold bare tool_call/tool_result shapes into the canonical part event;\n // everything else keeps its original record (verbatim forwarding must\n // not strip fields outside `data`).\n const normalized = normalizeToolEvent({ type: record.type, data: asRecord(record.data) })\n const event: StreamEvent = normalized.type === 'message.part.updated'\n ? normalized\n : { type: record.type, data: asRecord(record.data) }\n\n if (event.type === 'message.part.updated') {\n yield* projectSandboxMessagePart(event, tracker, recordPersistedPart, reasoningClock, projectionState, partMap, announcedToolArgs, settledTools, usage, options, log, promotedFileParts)\n continue\n }\n\n if (event.type === 'interaction') {\n const parsed = parseInteractionRequest(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction event', { error: parsed.error })\n continue\n }\n if (renderable(parsed.value.kind, parsed.value)) {\n recordPersistedPart(\n interactionToPersistedPart(parsed.value, 'pending'),\n undefined,\n interactionPartKey(parsed.value.id),\n )\n yield toProducerWireEvent(record)\n continue\n }\n // Non-renderable ask: the run is blocked in the broker until someone\n // answers. Decline it so the turn proceeds instead of hanging.\n let declineFailed = false\n if (options.declineInteraction) {\n try {\n await options.declineInteraction(parsed.value.id)\n } catch (err) {\n declineFailed = true\n log('[chat-routes] failed to auto-decline interaction', {\n id: parsed.value.id,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n } else {\n declineFailed = true\n log('[chat-routes] non-renderable interaction with no declineInteraction wired', {\n id: parsed.value.id,\n kind: parsed.value.kind,\n })\n }\n const text = options.declinedNotice?.(parsed.value, declineFailed) ?? (declineFailed\n ? `The agent requested ${parsed.value.kind} approval; declining it failed — it will expire on its own.`\n : `The agent requested ${parsed.value.kind} approval — auto-declined by policy.`)\n const notice = noticePart('auto-declined', `auto-declined-${parsed.value.id}`, text)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'auto-declined', text }\n continue\n }\n\n if (event.type === 'interaction.cancel') {\n const parsed = parseInteractionCancel(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction.cancel event', { error: parsed.error })\n continue\n }\n const key = interactionPartKey(parsed.value.id)\n const existing = partMap.get(key)\n if (existing?.type === 'interaction' && existing.status === 'pending') {\n recordPersistedPart({\n ...existing,\n status: cancelStatusFor(parsed.value.reason),\n ...(parsed.value.reason ? { cancelReason: parsed.value.reason } : {}),\n }, undefined, key)\n }\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'plan.submitted') {\n const parsed = parsePlanSubmittedEvent(record)\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed plan.submitted event', { error: parsed.error })\n continue\n }\n recordPersistedPart(planToPersistedPart(parsed.value), undefined)\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'warning') {\n const message = asString(event.data?.message)\n if (message) {\n projectionState.warningCount += 1\n const code = asString(event.data?.code)\n const text = code ? `${code}: ${message}` : message\n const notice = noticePart('warning', `warning-${projectionState.warningCount}`, text)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'warning', text }\n }\n // The flattened notice is additive; existing raw-warning consumers keep\n // receiving the original event too.\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'usage') {\n const reported = extractUsageSnapshot(asRecord(record.usage))\n if (reported) applyTerminalUsage(reported, usage)\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'result') {\n projectionState.terminalObserved = true\n const finalText = asString(event.data?.finalText)\n if (finalText) projectionState.fullText = finalText\n const reported = extractReportedTurnUsage(asRecord(event.data))\n if (reported) {\n applyTerminalUsage(reported, usage)\n yield* emitFinalUsage()\n } else {\n // Legacy result shape kept as a secondary fallback.\n const resultUsage = asRecord(event.data?.usage)\n if (resultUsage) {\n const input = Number(resultUsage.inputTokens)\n const output = Number(resultUsage.outputTokens)\n if (Number.isFinite(input)) usage.inputTokens = input\n if (Number.isFinite(output)) usage.outputTokens = output\n }\n }\n yield* emitTerminalizedTools()\n continue\n }\n\n if (event.type === 'done') {\n // SDK transport-loss cleanup emits a failed done without a backend\n // terminal receipt. Preserve an earlier result, but never unlock on\n // that synthetic observation ending alone.\n if (isTerminalPromptEvent(record)) projectionState.terminalObserved = true\n const reported = extractReportedTurnUsage(asRecord(event.data))\n if (reported) {\n applyTerminalUsage(reported, usage)\n yield* emitFinalUsage()\n }\n yield* emitTerminalizedTools()\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'error') {\n const message = sandboxStreamErrorMessage(event.data)\n const errorContent = projectionState.fullText.trim()\n ? `The sandbox model stream stopped before a clean completion.\\n\\nError: ${message}`\n : `The sandbox agent returned an error before producing a visible answer.\\n\\nError: ${message}`\n if (options.errorNotice) {\n yield* emitErrorNotice(errorContent, sandboxStreamErrorCode(event.data))\n } else if (options.includeErrorText !== false) {\n const errorDelta = projectionState.fullText ? `\\n\\n---\\n${errorContent}` : errorContent\n projectionState.fullText += errorDelta\n yield { type: 'text', text: errorDelta }\n }\n projectionState.interactionOutcome = 'expired'\n yield* emitTerminalizedTools()\n yield toProducerWireEvent(record)\n continue\n }\n\n // Remaining lifecycle events forward verbatim; the client parser ignores\n // unknown types.\n yield toProducerWireEvent(record)\n }\n // A model that fell over and then produced nothing never entered the loop\n // body; the downgrade must still be recorded.\n yield* drainModelNotices()\n } catch (streamErr) {\n // A later fallback refusal cannot clear an earlier unobserved execution.\n // Count opens at their owner: failover may buffer the first native events.\n preflightRefused = !observedSourceEvent && openAttempts() === 1\n && streamErr instanceof SandboxRunError && streamErr.code === 'sandbox_unavailable'\n const diagnostic = sandboxStreamFailureDiagnostic(streamErr)\n log('[chat-routes] sandbox stream failed', {\n failureNote: diagnostic.failureNote,\n error: streamErr instanceof Error ? streamErr.message : String(streamErr),\n })\n if (options.errorNotice) {\n yield* emitErrorNotice(diagnostic.userMessage, diagnostic.code)\n } else if (options.includeErrorText !== false) {\n const errorDelta = projectionState.fullText\n ? `\\n\\n---\\n${diagnostic.userMessage}`\n : diagnostic.userMessage\n projectionState.fullText += errorDelta\n yield { type: 'text', text: errorDelta }\n }\n projectionState.interactionOutcome = 'expired'\n yield* emitTerminalizedTools()\n yield {\n type: 'error',\n data: {\n message: diagnostic.userMessage,\n code: diagnostic.code,\n details: { failureNote: diagnostic.failureNote },\n },\n }\n } finally {\n reasoningClock.settle()\n }\n }\n\n return {\n stream: stream(),\n finalText: () => projectionState.fullText,\n terminalObserved: () => projectionState.terminalObserved || preflightRefused,\n assistantParts: () => finalizePendingInteractionParts(\n finalizeAssistantParts(partOrder, timedParts(), projectionState.fullText),\n projectionState.interactionOutcome,\n ),\n // Mid-stream snapshot for incremental persistence: the same accumulators,\n // WITHOUT the two completion-time settlements (`terminalizeDanglingTool*`\n // and `finalizePendingInteractionParts`). A running tool and an unanswered\n // ask are the correct live state; settling them early would persist\n // phantom failures the final write then reverses.\n draftParts: () => draftAssistantParts(partOrder, timedParts(), projectionState.fullText),\n usage: () => usage,\n // A GETTER, not a captured value: `turn-routes` reads `producer.model` at\n // draft-snapshot and persist time, both of which happen after the stream\n // resolved which model serves. A plain property would freeze the PREFERRED\n // model into the row and make a downgrade unattributable — the exact\n // failure mode this work exists to prevent.\n get model(): string | undefined {\n return servedModel()\n },\n modelFailover: () => ({\n model: servingModel(),\n attempts: failover?.attempts() ?? [],\n usedFallback: failover?.usedFallback() ?? false,\n }),\n modelAttribution: () => ({\n ...(options.model ? { requestedModel: options.model } : {}),\n ...(modelState.effectiveBackend ?? {}),\n echoReceived: modelState.effectiveBackend !== undefined,\n }),\n }\n}\n\ninterface SandboxProjectionState {\n fullText: string\n terminalObserved: boolean\n stepCounter: number\n danglingToolsTerminalized: boolean\n interactionOutcome: 'answered' | 'expired'\n warningCount: number\n errorNoticeCount: number\n}\n\nfunction createSandboxProjection(projectionState: SandboxProjectionState, pendingModelNotices: { id: string; text: string }[]) {\n const partOrder: string[] = []\n const partMap = new Map<string, JsonRecord>()\n const tracker: TextTracker = { seen: new Map() }\n /** Each reasoning part's start and end where the harness sent none: the same timing the engine's producer persists. */\n const reasoningClock = createReasoningClock<string>()\n const usage: ChatTurnUsage = {}\n /** Whether each announced tool_call carried populated arguments. */\n const announcedToolArgs = new Map<string, boolean>()\n const settledTools = new Set<string>()\n /** Id-less step boundaries: one occurrence per key, never merged. */\n\n /** `promoteFilePart` memo, keyed by `id ?? url` of the raw part. Holds the\n * PROMISE (never the settled result) so concurrent duplicate events for\n * the same part await the one in-flight attempt instead of each starting\n * their own; the promise never rejects (see below), so a later duplicate\n * reading a settled entry reuses that first outcome — success or\n * failure — rather than retrying. */\n const promotedFileParts = new Map<string, Promise<FilePartPromotionOutcome>>()\n\n function recordPersistedPart(part: JsonRecord, delta: string | undefined, keyOverride?: string): void {\n const persisted = normalizePersistedPart(part)\n if (!persisted) return\n const key = keyOverride ?? getPartKey(persisted)\n if (!partMap.has(key)) partOrder.push(key)\n partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta))\n }\n\n function* emitTerminalizedTools(): Generator<ProducerWireEvent, void, unknown> {\n if (projectionState.danglingToolsTerminalized) return\n projectionState.danglingToolsTerminalized = true\n const updates = terminalizeDanglingAssistantToolUpdates(partOrder, partMap, projectionState.fullText)\n for (const part of updates) {\n const toolId = asString(part.id)\n if (!toolId || settledTools.has(toolId)) continue\n settledTools.add(toolId)\n const state = asRecord(part.state)\n yield {\n type: 'tool_result',\n toolCallId: toolId,\n toolName: asString(part.tool) ?? 'tool',\n outcome: {\n ok: false,\n ...(asString(state?.error) ? { message: asString(state?.error) } : {}),\n },\n }\n }\n }\n\n function* emitFinalUsage(): Generator<ProducerWireEvent, void, unknown> {\n const promptTokens = usage.inputTokens ?? 0\n const completionTokens = usage.outputTokens ?? 0\n if (promptTokens || completionTokens) {\n yield {\n type: 'usage',\n usage: {\n promptTokens,\n completionTokens,\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.costUsd !== undefined ? { providerCostUsd: usage.costUsd } : {}),\n },\n }\n }\n }\n\n /** Emit any queued fallback notices, persisting each so the downgrade is in\n * the durable transcript and not only in the live stream. Uses the existing\n * `warning` notice kind deliberately: every shipped client already renders\n * it, whereas a bespoke kind would be dropped by `dispatchChatStreamLine`'s\n * filter — an attribution nobody sees is not attribution. */\n function* drainModelNotices(): Generator<ProducerWireEvent, void, unknown> {\n while (pendingModelNotices.length > 0) {\n const queued = pendingModelNotices.shift()!\n const notice = noticePart('warning', queued.id, queued.text)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'warning', text: queued.text }\n }\n }\n\n /** `errorNotice` mode: the terminal error as a persisted `error` notice part,\n * so the durable row says \"this turn failed\" in a typed field. */\n function* emitErrorNotice(text: string, code: string): Generator<ProducerWireEvent, void, unknown> {\n projectionState.errorNoticeCount += 1\n const notice = noticePart('error', `error-${projectionState.errorNoticeCount}`, text, code)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'error', text, code }\n }\n\n\n /** The persisted parts with each reasoning part's time: the harness's own, else the clock's. */\n const timedParts = (): Map<string, JsonRecord> => {\n const timed = new Map(partMap)\n for (const [key, part] of partMap) {\n if (part.type !== 'reasoning') continue\n const time = reasoningClock.time(key, asRecord(part.time) as ReasoningRunTime | undefined)\n if (time) timed.set(key, { ...part, time })\n }\n return timed\n }\n\n return { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder }\n}\n\nasync function* projectSandboxMessagePart(\n event: StreamEvent,\n tracker: TextTracker,\n recordPersistedPart: (part: JsonRecord, delta: string | undefined, keyOverride?: string) => void,\n reasoningClock: ReturnType<typeof createSandboxProjection>['reasoningClock'],\n projectionState: SandboxProjectionState,\n partMap: Map<string, JsonRecord>,\n announcedToolArgs: Map<string, boolean>,\n settledTools: Set<string>,\n usage: ChatTurnUsage,\n options: SandboxChatProducerOptions,\n log: (message: string, meta?: Record<string, unknown>) => void,\n promotedFileParts: Map<string, Promise<FilePartPromotionOutcome>>,\n): AsyncGenerator<ProducerWireEvent, void, unknown> {\n if (event.type === 'message.part.updated') {\n const part = asRecord(event.data?.part)\n if (!part) return\n const rawDelta = event.data?.delta\n const partType = String(part.type ?? '')\n\n if (partType === 'text' || partType === 'reasoning') {\n const key = getPartKey(part)\n const delta = textDelta(tracker, key, part, rawDelta)\n recordPersistedPart(part, delta || undefined)\n if (delta) {\n if (partType === 'reasoning') reasoningClock.reasoning(key)\n else reasoningClock.settle()\n if (partType === 'text') projectionState.fullText += delta\n yield { type: partType, text: delta }\n }\n return\n }\n\n if (partType === 'tool') {\n reasoningClock.settle()\n recordPersistedPart(part, undefined)\n const persisted = partMap.get(getPartKey(part))\n const state = asRecord(persisted?.state)\n const toolId = String(persisted?.id ?? '')\n const toolName = String(persisted?.tool ?? 'tool')\n const args = asRecord(state?.input) ?? {}\n const hasPopulatedArgs = Object.keys(args).length > 0\n const announcedWithPopulatedArgs = announcedToolArgs.get(toolId)\n if (\n toolId &&\n (announcedWithPopulatedArgs === undefined ||\n (!announcedWithPopulatedArgs && hasPopulatedArgs && !settledTools.has(toolId)))\n ) {\n announcedToolArgs.set(toolId, hasPopulatedArgs)\n yield {\n type: 'tool_call',\n call: { toolCallId: toolId, toolName, args },\n }\n }\n const status = String(state?.status ?? '')\n if (toolId && (status === 'completed' || status === 'error') && !settledTools.has(toolId)) {\n settledTools.add(toolId)\n yield {\n type: 'tool_result',\n toolCallId: toolId,\n toolName,\n outcome: {\n ok: status === 'completed',\n ...(state?.output !== undefined ? { result: state.output } : {}),\n ...(asString(state?.error) ? { message: asString(state?.error) } : {}),\n },\n }\n }\n return\n }\n\n if (partType === 'step-finish') {\n addStepFinishUsage(part, usage)\n // Persist the per-step receipt too (unique key per occurrence: the\n // parts have no id and two receipts must never merge into one).\n recordPersistedPart(part, undefined, `step-finish:#${projectionState.stepCounter++}`)\n const promptTokens = usage.inputTokens ?? 0\n const completionTokens = usage.outputTokens ?? 0\n if (promptTokens || completionTokens) {\n yield {\n type: 'usage',\n usage: {\n promptTokens,\n completionTokens,\n ...(usage.reasoningTokens !== undefined\n ? { reasoningTokens: usage.reasoningTokens }\n : {}),\n ...(usage.costUsd !== undefined ? { providerCostUsd: usage.costUsd } : {}),\n },\n }\n }\n return\n }\n\n if (partType === 'step-start') {\n recordPersistedPart(part, undefined, `step-start:#${projectionState.stepCounter}`)\n return\n }\n\n if (partType === 'file' && options.promoteFilePart) {\n const promote = options.promoteFilePart\n // Prefixed by source (`id:`/`url:`) rather than the bare raw string —\n // an `id` and a `url` that happen to share the same text (e.g. both\n // `\"abc\"`) would otherwise collide onto one memo entry and fold two\n // unrelated parts' promotions together. Internal Map key only; never\n // observable outside this module.\n const rawId = asString(part.id)\n const rawUrl = asString(part.url)\n const memoKey = rawId ? `id:${rawId}` : rawUrl ? `url:${rawUrl}` : undefined\n // Always invoke the callback for a `file` part when one is wired —\n // gtm never skips promotion outright, even for a part with neither\n // `id` nor `url` (it simply fails \"carries no url\" and resolves\n // through the ordinary failure path). Memoization by PROMISE only\n // applies when there is something to key it on; keyless parts are\n // invoked un-memoized, once per occurrence.\n //\n // `Promise.resolve().then(...)` (rather than calling `promote(part)`\n // directly) so a SYNC throw from a non-async `promoteFilePart` is\n // captured into the promise chain instead of escaping this function\n // call outright — `.catch` below only ever sees a rejection, never a\n // thrown exception that unwinds past `attempt()`.\n const attempt = (): Promise<FilePartPromotionOutcome> =>\n Promise.resolve()\n .then(() => promote(part))\n .catch((err) => {\n const reason = err instanceof Error ? err.message : String(err)\n log('[chat-routes] file part promotion threw', { key: memoKey ?? '(keyless)', error: reason })\n return { succeeded: false as const, reason }\n })\n\n let pending: Promise<FilePartPromotionOutcome>\n if (memoKey) {\n pending = promotedFileParts.get(memoKey) ?? attempt()\n promotedFileParts.set(memoKey, pending)\n } else {\n pending = attempt()\n }\n\n const outcome = await pending\n if (outcome.succeeded) {\n recordPersistedPart(outcome.part, undefined, outcome.key)\n } else if (outcome.part) {\n // Substitute part (e.g. a warning notice) takes the raw part's\n // place in the transcript — the transient url never lands.\n recordPersistedPart(outcome.part, undefined, outcome.key)\n } else {\n recordPersistedPart(part, undefined)\n }\n return\n }\n\n // Remaining storable kinds (file/image/subtask) have no live\n // vocabulary line; they persist so the transcript keeps them.\n recordPersistedPart(part, undefined)\n return\n }\n}\n","import { parseJsonObjectBody } from '../web/index'\nimport { redactErrorMessage } from '../redact/index'\nimport { INLINE_PARTS_MAX_BYTES } from './wire'\nimport type { ChatRouteEvent, ChatTurnProduceArgs, CreateChatTurnRoutesOptions } from './turn-route-contracts'\n\nexport interface ChatTurnCancelRequest extends Record<string, unknown> {\n threadId: string\n turnId: string\n cancellationToken?: string\n}\n\n/** Product identity and editor access have already been checked before target is called. */\nexport interface ChatTurnCancelArgs<TContext> {\n request: Request\n body: ChatTurnCancelRequest\n tenantId: string\n userId: string\n context?: TContext\n /** Supplied only by the execution owner after admission; never copied from a request body. */\n messageId?: string\n}\n\n/** Structural public Sandbox API; addressing always comes from the captured receipt. */\nexport interface ChatTurnCancelSource {\n id: string\n session(id: string): {\n interrupt(input: { executionId: string }): Promise<{ cancelled: boolean }>\n status(): Promise<{ id: string; status?: string; activeExecutionId?: string | null } | null>\n }\n}\n\n/** Acknowledges durable intent only; the execution owner still reconciles actual completion and side effects. */\nexport interface ChatTurnCancelControlResult {\n requested: boolean\n}\n\n/** Application fields are projected once; the shared owner never infers OAuth or source-key authority. */\nexport interface ChatTurnCancelTarget {\n capturedMetadata: Record<string, unknown>\n status: string | undefined\n dispatchToken?: string\n requiresDispatchToken: boolean\n /** Server-captured exact owner, never coordinates supplied by the caller.\n * Called after authorization and dispatch-token checks. A positive request\n * acknowledges intent; it must not mark native work stopped. */\n control?: {\n request(capturedMetadata: Record<string, unknown>): Promise<ChatTurnCancelControlResult>\n }\n native?: {\n state: string | undefined\n sandboxId?: string\n sessionId?: string\n executionId?: string\n /** Resolve the original authorized box only after the dispatch token and receipt are validated. */\n source(): Promise<ChatTurnCancelSource | null>\n }\n /** Compare the WHOLE captured record atomically, then merge the stopped fields. False changes nothing.\n * A requested-only control target never calls this; the execution owner confirms its terminal outcome. */\n markStopped(capturedMetadata: Record<string, unknown>, stoppedAt: string): Promise<boolean>\n}\n\nexport interface ChatTurnCancelOptions<TContext> {\n target(args: ChatTurnCancelArgs<TContext>): Promise<ChatTurnCancelTarget | Response>\n}\n\nconst targetChanged = () => Response.json({\n error: 'This Stop no longer matches the current turn attempt. Refresh its current state.',\n code: 'CANCEL_TARGET_CHANGED',\n}, { status: 409 })\nconst stateChanged = () => Response.json({\n error: 'This turn changed while Stop was pending. Refresh before trying Stop again.',\n code: 'CANCEL_STATE_CHANGED',\n}, { status: 409 })\nconst success = (sandboxInterrupted: boolean) => Response.json({ succeeded: true, sandboxInterrupted })\n\n/** Existing product Stop, composed with the same authorization and storage owner as chat. */\nexport async function cancelChatTurn<TContext>(request: Request, options: {\n authorize: CreateChatTurnRoutesOptions<TContext>['authorize']\n cancel?: ChatTurnCancelOptions<TContext>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}): Promise<Response> {\n if (!options.cancel || request.method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const [raw, invalid] = await parseJsonObjectBody(request, { maxBytes: INLINE_PARTS_MAX_BYTES })\n if (invalid) return invalid\n const threadId = typeof raw.threadId === 'string' ? raw.threadId.trim() : ''\n const turnId = typeof raw.turnId === 'string' ? raw.turnId.trim() : ''\n if (!threadId || !turnId) {\n return Response.json({ error: 'Missing workspaceId, threadId, or turnId' }, { status: 400 })\n }\n const body: ChatTurnCancelRequest = { ...raw, threadId, turnId,\n cancellationToken: typeof raw.cancellationToken === 'string' ? raw.cancellationToken : undefined }\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? {}))\n try {\n const auth = await options.authorize({ request, intent: 'cancel', body, threadId })\n if (!auth.ok) return auth.response\n if (auth.intent !== undefined && auth.intent !== 'cancel') {\n return Response.json({ error: 'Authorization did not allow this turn cancellation.', code: 'chat_authorization_intent_mismatch' }, { status: 403 })\n }\n const target = await options.cancel.target({ request, body, tenantId: auth.tenantId, userId: auth.userId,\n ...('context' in auth ? { context: auth.context } : {}) })\n if (target instanceof Response) return target\n if (target.requiresDispatchToken && (!body.cancellationToken || body.cancellationToken !== target.dispatchToken)) {\n return targetChanged()\n }\n if (target.status === 'stopped' || target.status === 'answered') return success(false)\n if (target.control) {\n const intent = await target.control.request(target.capturedMetadata)\n return intent.requested ? Response.json({ succeeded: true, sandboxInterrupted: false, cancellationRequested: true }) : targetChanged()\n }\n const markStopped = async () => await target.markStopped(target.capturedMetadata, new Date().toISOString())\n ? null : stateChanged()\n if (!target.native) return await markStopped() ?? success(false)\n const native = target.native\n if (native.state !== 'running' || !native.executionId || !native.sessionId || !native.sandboxId) {\n return Response.json({\n error: 'This turn has no confirmed native execution to stop. Refresh and try again.',\n code: 'NATIVE_CANCEL_TARGET_UNAVAILABLE',\n }, { status: 409 })\n }\n const source = await native.source()\n if (!source || source.id !== native.sandboxId) {\n return Response.json({ error: 'The turn was not marked stopped because its original sandbox is unavailable.' }, { status: 503 })\n }\n try {\n const session = source.session(native.sessionId)\n const interrupted = await session.interrupt({ executionId: native.executionId })\n if (!interrupted.cancelled) {\n const current = await session.status()\n const anotherExecution = typeof current?.activeExecutionId === 'string'\n && current.activeExecutionId.length > 0 && current.activeExecutionId !== native.executionId\n const terminal = current && ['completed', 'failed', 'cancelled'].includes(current.status ?? '')\n if (!current || current.id !== native.sessionId || current.activeExecutionId === native.executionId\n || (!anotherExecution && !terminal)) {\n throw new Error('The targeted native execution has not been confirmed stopped')\n }\n }\n return await markStopped() ?? success(interrupted.cancelled)\n } catch (error) {\n log('[chat-routes] native cancellation failed', { error: redactErrorMessage(error) })\n return Response.json({ error: 'The turn was not marked stopped because its native execution could not be confirmed interrupted.' }, { status: 502 })\n }\n } catch (error) {\n if (error instanceof Response) return error\n log('[chat-routes] cancellation failed', { error: redactErrorMessage(error) })\n return Response.json({ error: 'Turn cancellation is temporarily unavailable.' }, { status: 503 })\n }\n}\n\n\n/** Internal route observation of the same product Stop target. This reads only;\n * native interruption and metadata writes remain exclusive to cancelChatTurn. */\nexport async function* observeTurnCancellation<TContext, TResource>(\n source: AsyncIterable<ChatRouteEvent>,\n args: ChatTurnProduceArgs<TContext, TResource>,\n cancel: ChatTurnCancelOptions<TContext>,\n abort: AbortController,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n if (!args.userMessageId) { yield* source; return }\n const iterator = source[Symbol.asyncIterator]()\n let closed = false, stopped = false, drained = false, warned = false\n let polling: Promise<boolean> | undefined\n let notifyStop!: () => void\n const stop = new Promise<IteratorResult<ChatRouteEvent>>(resolve => { notifyStop = () => { resolve({ done: true, value: undefined }) } })\n const body: ChatTurnCancelRequest = { ...args.body, threadId: args.identity.sessionId,\n turnId: typeof args.body.turnId === 'string' ? args.body.turnId : '',\n cancellationToken: typeof args.body.cancellationToken === 'string' ? args.body.cancellationToken : undefined }\n const readTarget = async (): Promise<boolean> => {\n if (closed) return true\n try {\n const target = await cancel.target({ request: args.request, body, tenantId: args.identity.tenantId,\n userId: args.identity.userId, context: args.context, messageId: args.userMessageId! })\n if (closed) return true\n if (target instanceof Response) return false\n if (target.status === 'stopped' || target.status === 'superseded') {\n stopped = true\n abort.abort(new Error('The captured turn was stopped or superseded.'))\n notifyStop()\n } else if (target.status === 'answered') clearInterval(timer)\n return true\n } catch (error) {\n // Unknown state is not evidence of Stop. Completion requires a fresh\n // successful read; background observation keeps checking in the meantime.\n if (!warned) {\n warned = true\n console.error('[chat-routes] stop observation unavailable', { error: redactErrorMessage(error) })\n }\n return false\n }\n }\n const poll = (): Promise<boolean> => polling ??= readTarget().finally(() => { polling = undefined })\n const timer = setInterval(() => { void poll() }, 1_000)\n try {\n // A lazy source can establish its domain row readiness during this first pull.\n let pending = iterator.next()\n void pending.catch(() => {})\n void poll()\n while (!stopped) {\n let next: IteratorResult<ChatRouteEvent>\n try { next = await Promise.race([pending, stop]) }\n catch (error) { if (stopped) return; throw error }\n if (stopped) return\n if (next.done) {\n // A stream can finish after Stop committed but before the next tick.\n // Join the earlier snapshot, then demand a new read at the drain boundary.\n await polling\n if (!await poll()) throw new Error('The captured turn state could not be confirmed at completion')\n if (stopped) return\n drained = true\n return\n }\n yield next.value\n pending = iterator.next()\n void pending.catch(() => {})\n }\n } finally {\n closed = true\n clearInterval(timer)\n if (!drained) {\n const cleanup = iterator.return?.().catch(() => {})\n if (cleanup) args.waitUntil?.(cleanup)\n }\n }\n}\n","/** Validated request and transcript projections at the chat-route boundary. */\nimport { mentionInputToPart, toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport { normalizeClientTurnId } from '../stream/index'\nimport type { TurnTrace } from '../turn-trace/recorder'\nimport { formatServerTiming } from '../turn-trace/server-timing'\nimport { checkModelPolicy } from '../policy-filters/index'\nimport type { ChatTurnAuthorization, CreateChatTurnRoutesOptions } from './turn-route-contracts'\nimport {\n assertPromptPartsWithinCap,\n ChatTurnInputError,\n parseChatTurnParts,\n parseMentions,\n type ChatTurnFilePartInput,\n type ChatTurnRequestPayload,\n type ChatMention,\n} from './wire'\n\n/** A turn whose body parsed and whose caller `authorize` admitted. */\nexport type AdmittedTurn<TContext> = {\n parsed: ParsedTurnBody\n auth: Extract<ChatTurnAuthorization<TContext>, { ok: true; context: TContext }>\n trace: TurnTrace\n /** The route's read-only prefetch for this admitted identity (`./turn-prefetch`). */\n prefetched?: Promise<unknown>\n}\n\n/** Emits one stage on a progress-first stream. */\nexport type TurnProgressCallback = (phase: string, message: string) => void\n\nexport function errorResponse(err: ChatTurnInputError): Response {\n return Response.json({ code: err.code, error: err.message }, { status: err.status })\n}\n\nexport interface ParsedTurnBody {\n payload: ChatTurnRequestPayload\n content: string\n fileParts: ChatTurnFilePartInput[]\n mentions: ChatMention[]\n turnId: string | undefined\n}\n\n/**\n * The turn's admission as a `Server-Timing` value: `admission` for the\n * request-to-stream wall time, then each `admission.*` span the trace holds in\n * start order. A timed request reads where admission went from the response\n * headers alone; the same spans reach the trace sink.\n */\nexport function admissionServerTiming(trace: TurnTrace): string {\n const now = Date.now()\n const steps = trace.spans(now)\n .filter((span) => span.kind === 'admission')\n .sort((a, b) => a.startMs - b.startMs)\n .map((span) => ({ name: span.name, dur: span.endMs - span.startMs }))\n return formatServerTiming([{ name: 'admission', dur: now - trace.startedAt }, ...steps])\n}\n\n/** The admission policy's refusal of the model the turn names, or null when it allows it or names none. */\nexport async function namedModelRefusal(\n policy: CreateChatTurnRoutesOptions<unknown>['modelPolicy'],\n payload: ChatTurnRequestPayload,\n trace: TurnTrace,\n): Promise<Response | null> {\n const namedModel = typeof payload.model === 'string' ? payload.model.trim() : ''\n if (!policy || !namedModel) return null\n const decision = await trace.measure('admission.model_policy', 'admission', () =>\n checkModelPolicy(namedModel, policy.catalog, policy.filter, policy.context))\n return decision.allowed ? null : Response.json({ code: 'model_policy_denied', error: decision.reason }, { status: 403 })\n}\n\nexport function validateTurnBody(body: Record<string, unknown>): 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 = parseMentions(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)\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 const retryAttemptId = body.retryAttemptId\n if (retryAttemptId !== undefined && (\n typeof retryAttemptId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(retryAttemptId) || !turnId\n )) throw new ChatTurnInputError('retryAttemptId requires turnId and 1–64 letters, digits, underscores, or hyphens')\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. */\nexport function userPartsWithFiles(\n userParts: Array<Record<string, unknown>>,\n fileParts: ChatTurnFilePartInput[],\n mentions: ChatMention[],\n): ChatMessagePart[] {\n return toChatMessageParts([\n ...userParts,\n ...fileParts.map((part) => ({ ...part })),\n ...mentions.map((mention) => ({ ...mentionInputToPart(mention) })),\n ])\n}\n","/**\n * A turn addressed to several agents runs them at the same time, each as its\n * own producer with the same thread history: the route sees one stream,\n * persists one assistant row, and the row's parts carry a `speaker` part\n * before each responder's parts, in the order the mentions were typed, so a\n * transcript draws each answer under its author.\n *\n * Live, every responder is announced up front with a `speaker` event, in\n * mention order, and then every event carries `speaker` (the responder's\n * agent id) as it arrives, so a viewer draws one live block per responder and\n * sees them answer at the same time. When a responder ends, its `speaker`\n * event is sent again with `state` (`done` or `failed`), and the stored row's\n * speaker parts carry the same state. The stored order stays the order typed,\n * so the transcript rereads the same way every time.\n *\n * Parallel and independent on purpose: the agents are addressed, not chained.\n * A responder that fails leaves a notice under its own name and the others\n * still answer; the turn fails only when every responder did.\n */\nimport type { ChatTurnIdentity } from '@tangle-network/agent-runtime/durable'\nimport type { TurnTrace } from '../turn-trace/recorder'\nimport { errorResponse } from './turn-admission'\nimport type { ChatRouteEvent, ChatTurnAgentsOptions, ChatTurnAgentTarget, ChatTurnProduceArgs, ChatTurnRouteProducer, ChatTurnUsage } from './turn-route-contracts'\nimport { agentMentionsOf, ChatTurnInputError, type ChatMention } from './wire'\n\n/**\n * Name a turn's responders from its agent mentions, before any lock, row or\n * model call: the product's resolver maps mentioned ids to the profiles they\n * run as, and a mention it does not return is refused. The thread's binding\n * does not move. Returns the response to send on refusal, otherwise the\n * produce args carrying `agents` in mention order (unchanged when none).\n */\nexport async function addressAgents<TContext, TResource>(input: {\n options: { agents?: ChatTurnAgentsOptions<TContext> }\n mentions: readonly ChatMention[]\n identity: ChatTurnIdentity\n context: TContext\n produceArgs: ChatTurnProduceArgs<TContext, TResource>\n trace: TurnTrace\n}): Promise<Response | ChatTurnProduceArgs<TContext, TResource>> {\n const addressed = agentMentionsOf(input.mentions)\n if (addressed.length === 0) return input.produceArgs\n const { agents } = input.options\n if (!agents) {\n return errorResponse(new ChatTurnInputError('This chat does not address agents by mention', 400, 'agents_unsupported'))\n }\n const targets = await input.trace.measure('admission.agents', 'admission', () =>\n agents.resolve({ identity: input.identity, context: input.context, mentions: addressed }))\n const byId = new Map(targets.map((target) => [target.id, target]))\n const unknown = addressed.find((mention) => !byId.has(mention.agentId))\n if (unknown) return errorResponse(new ChatTurnInputError(`Unknown agent @${unknown.handle}`, 400, 'unknown_agent'))\n return { ...input.produceArgs, agents: addressed.map((mention) => byId.get(mention.agentId)!) }\n}\n\n/** The event a viewer receives when the next responder starts. */\nexport const SPEAKER_EVENT = 'speaker'\n\n/** A responder's speaker part; `state` once it ended. */\nexport function speakerPart(agent: ChatTurnAgentTarget, state?: 'done' | 'failed'): Record<string, unknown> {\n return { type: 'speaker', id: agent.id, name: agent.name, handle: agent.handle, ...(state ? { state } : {}) }\n}\n\n/**\n * What a responder reads as the message: the addressed handles leave the text\n * (they are addressing, not content) and one line names who it answers as and\n * who else is answering, so each agent answers its own part instead of\n * playing every role (both did, GTM production 2026-10-27).\n */\nfunction addressedTurnText(content: string, agent: ChatTurnAgentTarget, agents: readonly ChatTurnAgentTarget[]): string {\n let text = content\n for (const target of agents) {\n text = text.replace(new RegExp(`(^|\\\\s)@${escapeRegExp(target.handle)}(?=\\\\s|$|[.,;:!?])`, 'g'), '$1')\n }\n text = text.replace(/[ \\t]{2,}/g, ' ').trim()\n const others = agents.filter((target) => target.id !== agent.id).map((target) => `${target.name} (@${target.handle})`)\n const line = others.length === 0\n ? `You answer this message as ${agent.name} (@${agent.handle}).`\n : `You answer this message as ${agent.name} (@${agent.handle}). ${others.join(', ')} ${others.length === 1 ? 'answers' : 'answer'} it separately at the same time; do your part and leave theirs to them.`\n return text ? `${line}\\n\\n${text}` : line\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/** The responder's copy of the produce args: its agent, its execution id and the message as it reads it. */\nfunction responderArgs<TContext, TResource>(\n args: ChatTurnProduceArgs<TContext, TResource>, agent: ChatTurnAgentTarget, index: number,\n): ChatTurnProduceArgs<TContext, TResource> {\n const agents = args.agents ?? []\n const address = (text: string) => addressedTurnText(text, agent, agents)\n const prompt = typeof args.prompt === 'string'\n ? address(args.prompt)\n : (() => {\n let done = false\n return args.prompt.map((part) => {\n if (done || part.type !== 'text' || typeof (part as { text?: unknown }).text !== 'string') return part\n done = true\n return { ...part, text: address((part as { text: string }).text) }\n })\n })()\n return {\n ...args, agent, executionId: `${args.executionId}-${index + 1}`, prompt,\n body: { ...args.body, ...(typeof args.body.content === 'string' ? { content: address(args.body.content) } : {}) },\n }\n}\n\nexport async function composeAgentProducers<TContext, TResource>(\n args: ChatTurnProduceArgs<TContext, TResource>,\n produce: (final: ChatTurnProduceArgs<TContext, TResource>) => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>,\n): Promise<ChatTurnRouteProducer> {\n const agents = args.agents ?? []\n if (agents.length === 0) throw new Error('composeAgentProducers needs at least one responder')\n const producers: Array<ChatTurnRouteProducer | undefined> = agents.map(() => undefined)\n const cleanups: Array<Promise<void>> = []\n // One slot per responder: its events as they arrive, drained eagerly so every\n // producer runs now; the composite stream reads whichever slot has events.\n const slots = agents.map(() => ({ queue: [] as ChatRouteEvent[], done: false, error: undefined as unknown, failure: undefined as ChatRouteEvent | undefined }))\n const failedNotice = (agent: ChatTurnAgentTarget, message: string): ChatRouteEvent =>\n ({ type: 'notice', id: `speaker-failed:${agent.id}`, noticeKind: 'error', text: `${agent.name} could not answer: ${message}`, speaker: agent.id } as ChatRouteEvent)\n let wake: (() => void) | undefined\n const notify = () => { const w = wake; wake = undefined; w?.() }\n agents.forEach((agent, index) => {\n const slot = slots[index]!\n void (async () => {\n try {\n // Each responder runs under its own execution id, so two native sessions\n // started for one turn never share a key; the route keeps the turn's.\n const producer = await produce(responderArgs(args, agent, index))\n producers[index] = producer\n if (producer.cleanup) cleanups.push(producer.cleanup)\n for await (const event of producer.stream) {\n // A responder's own failure stays its own: the route fails the turn on an\n // `error` event, so it becomes a notice under this speaker unless every\n // responder fails (then the last failure is forwarded at the end).\n if (event.type === 'error' || event.type === 'session.run.failed') {\n slot.failure = { ...event, speaker: agent.id } as ChatRouteEvent\n const message = typeof event.data?.message === 'string' ? event.data.message : 'the run failed'\n slot.queue.push(failedNotice(agent, message))\n } else {\n slot.queue.push({ ...event, speaker: agent.id } as ChatRouteEvent)\n }\n notify()\n }\n } catch (error) {\n slot.error = error\n } finally {\n slot.done = true\n notify()\n }\n })()\n })\n // A responder has ended once its producer settled; it failed if it threw or reported a failure.\n const endOf = (index: number): 'done' | 'failed' | undefined => {\n const slot = slots[index]!\n if (!slot.done) return undefined\n return slot.error !== undefined || slot.failure !== undefined ? 'failed' : 'done'\n }\n const stream = (async function* (): AsyncGenerator<ChatRouteEvent> {\n for (const agent of agents) {\n yield { type: SPEAKER_EVENT, ...speakerPart(agent) } as ChatRouteEvent\n }\n const reported = new Set<number>()\n const ended = new Set<number>()\n for (;;) {\n if (args.admissionSignal?.aborted) return\n let yielded = false\n for (const [index, slot] of slots.entries()) {\n while (slot.queue.length > 0) { yield slot.queue.shift()!; yielded = true }\n if (slot.done && slot.error !== undefined && !reported.has(index)) {\n reported.add(index)\n const agent = agents[index]!\n yield failedNotice(agent, slot.error instanceof Error ? slot.error.message : String(slot.error))\n yielded = true\n }\n const end = slot.queue.length === 0 ? endOf(index) : undefined\n if (end && !ended.has(index)) {\n ended.add(index)\n yield { type: SPEAKER_EVENT, ...speakerPart(agents[index]!, end) } as ChatRouteEvent\n yielded = true\n }\n }\n if (slots.every((slot) => slot.done && slot.queue.length === 0)) {\n // Every responder failed: the turn fails, as a thrown producer error or the last failure event.\n const failed = slots.every((slot) => slot.error !== undefined || slot.failure !== undefined)\n if (failed) {\n const thrown = slots.find((slot) => slot.error !== undefined)?.error\n if (thrown !== undefined) throw thrown\n const failure = slots.map((slot) => slot.failure).find((event) => event !== undefined)\n if (failure) yield failure\n }\n return\n }\n if (!yielded) await new Promise<void>((resolve) => {\n wake = resolve\n if (slots.some((slot) => slot.queue.length > 0 || slot.done)) {\n // Something landed between the scan and the wait; re-scan unless everything scanned is already settled.\n const pending = slots.some((slot, index) => slot.queue.length > 0 || (slot.done && !ended.has(index)))\n if (pending || slots.every((slot) => slot.done)) { wake = undefined; resolve() }\n }\n })\n }\n })()\n const entries = () => agents.flatMap((agent, index) => (producers[index] ? [{ agent, producer: producers[index]! }] : []))\n const failureOf = (index: number): string | undefined => {\n const slot = slots[index]!\n if (slot.error !== undefined) return slot.error instanceof Error ? slot.error.message : String(slot.error)\n const data = slot.failure?.data\n return slot.failure ? (typeof data?.message === 'string' ? data.message : 'the run failed') : undefined\n }\n // Every responder keeps its header in the stored row; a failed one carries its notice after whatever it said.\n const partsOf = (index: number, read: 'assistantParts' | 'draftParts') => {\n const agent = agents[index]!\n const producer = producers[index]\n const own = producer?.[read]?.()\n const text = producer?.finalText() ?? ''\n const parts = own ?? (text ? [{ type: 'text', text }] : [])\n const failure = failureOf(index)\n const notice = failure === undefined ? [] : [{ type: 'notice', noticeKind: 'error', id: `speaker-failed:${agent.id}`, text: `${agent.name} could not answer: ${failure}` }]\n return [speakerPart(agent, endOf(index)), ...parts, ...notice]\n }\n const last = () => entries().at(-1)?.producer\n return {\n stream,\n finalText: () => entries().map(({ producer }) => producer.finalText()).filter((text) => text.trim() !== '').join('\\n\\n'),\n assistantParts: () => agents.flatMap((_, index) => partsOf(index, 'assistantParts')),\n draftParts: () => agents.flatMap((_, index) => partsOf(index, 'draftParts')),\n usage: () => entries().reduce<ChatTurnUsage>((sum, { producer }) => {\n const usage = producer.usage?.() ?? {}\n for (const [key, value] of Object.entries(usage)) {\n if (typeof value === 'number') (sum as Record<string, number>)[key] = ((sum as Record<string, number>)[key] ?? 0) + value\n }\n return sum\n }, {}),\n terminalObserved: () => entries().every(({ producer }) => producer.terminalObserved?.() ?? true),\n get model() { return last()?.model },\n modelFailover: () => last()?.modelFailover?.() as ReturnType<NonNullable<ChatTurnRouteProducer['modelFailover']>>,\n modelAttribution: () => last()?.modelAttribution?.() as ReturnType<NonNullable<ChatTurnRouteProducer['modelAttribution']>>,\n cleanup: (async () => { await Promise.all(cleanups) })(),\n }\n}\n","/** Public contracts for admission, execution, persistence and chat-route hooks. */\nimport type { SandboxPromptExecutionLimits } from '../sandbox/prompt-options'\nimport type { ChatTurnStoreBindings } from './route-storage'\nimport type { NativeCompletionHandoffOptions, NativeTurnTimingFacts } from './native-turn-timing'\nimport type { ChatMessageValues } from '../chat-store/core'\nimport type { ChatTurnPrefetch, ChatTurnPrefetchIdentity } from './turn-prefetch'\nimport type { ChatTurnIdentity, ChatTurnProducer } from '@tangle-network/agent-runtime/durable'\nimport type { ChatMessagePart } from '../chat-store/parts'\nimport type { InteractionAnswerRoute, InteractionAnswerRouteOptions } from '../interactions/route'\nimport type { ModelFailoverAttempt } from '../model-resolution/failover'\nimport type { ModelPolicy } from '../policy-filters/index'\nimport type { PersistedChatMessageForTurn, TurnEventStore } from '../stream/index'\nimport type { D1LikeForTurns } from '../stream/turn-buffer'\nimport type { TurnStreamAuth } from '../turn-stream/adapters'\nimport type { TurnSpan, TurnSpanAttrs, TurnTrace, TurnTraceSink, TurnTraceSummary } from '../turn-trace/recorder'\nimport type { TurnRoutePhase } from './turn-progress'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { AgentMention, ChatTurnPartInput, ChatTurnRequestPayload } from './wire'\nimport type { RouterTurnProducerOptions } from './router-producer'\nimport type { HybridTurnProducerOptions } from './hybrid-producer'\nimport type { SandboxChatProducerOptions } from './sandbox-producer'\nimport type { ChatTurnCancelOptions, ChatTurnCancelRequest } from './cancellation'\n\n/** The route supplies request tracing, cancellation and the admission fence.\n * Domain callbacks supply model, credentials, policy, tools and prompt data. */\nexport type ChatTurnRouterConfiguration = Omit<RouterTurnProducerOptions, 'trace' | 'traceId' | 'signal' | 'userMessage' | 'history'> & {\n userMessage?: RouterTurnProducerOptions['userMessage']\n history?: RouterTurnProducerOptions['history']\n}\nexport type ChatTurnHybridConfiguration = Omit<HybridTurnProducerOptions, 'trace' | 'traceId' | 'signal' | 'userMessage' | 'history'> & {\n userMessage?: HybridTurnProducerOptions['userMessage']\n history?: HybridTurnProducerOptions['history']\n}\nexport type ChatTurnRouterBackend = ChatTurnRouteProducer | ChatTurnRouterConfiguration | ChatTurnHybridConfiguration\nexport type ChatTurnSandboxBackend = ChatTurnRouteProducer | SandboxChatProducerOptions\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: ChatMessageValues & {\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 }): 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: Partial<ChatMessageValues>): 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 /** Pending resource retirement after stream termination. The route tracks it\n * with the request's waitUntil, including when admission refuses an early\n * Router call. Cleanup must handle and report its own failures. */\n cleanup?: Promise<void>\n /** No unconfirmed native execution remains: a terminal was observed or local preflight prevented dispatch. */\n terminalObserved?(): boolean\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 /** Omit for existing callers; a full execution authorization may name its intent explicitly. */\n intent?: 'turn'\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 | {\n ok: true\n /** Identity/access for this operation only; it cannot start a turn. */\n intent: 'replay' | 'running' | 'cancel'\n tenantId: string\n userId: string\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 /** This request's bound host continuation, when supplied to turn(request, ctx). */\n waitUntil?: ChatTurnRequestContext['waitUntil']\n intent: 'turn' | 'replay' | 'running' | 'cancel'\n /** Parsed, validated POST body for a turn or cancellation. */\n body?: ChatTurnRequestPayload | ChatTurnCancelRequest\n /** The buffered turn id being replayed (replay intent only). */\n turnId?: string\n /** The thread whose running turns are being discovered. Prewarm also uses\n * running authorization, without a thread on page-open; the product may\n * authorize its verified workspace or refuse that operation. */\n threadId?: string\n /** The turn's trace (turn intent only). A product records its own child spans (a billing read, a workspace check) so the\n * admission wait is named by step; the route already records `admission.authorize` around the whole call. */\n trace?: TurnTrace\n /** The `admission.authorize` span (turn intent only): the parent for those child spans, so they nest under it. */\n span?: TurnSpan\n /** Turn intent with the route's `prefetch` option set: call it as soon as the caller's identity is verified, before\n * the rest of the checks, so the prefetch reads beside them (see `./turn-prefetch`). */\n identified?(identity: ChatTurnPrefetchIdentity): void\n}\n\n/** What `prepareTurn` receives: the admitted turn, before the conversation loads. */\nexport interface ChatTurnPrepareArgs<TContext> {\n request: Request\n /** This request's bound host continuation, when supplied to turn(request, ctx). */\n waitUntil?: ChatTurnRequestContext['waitUntil']\n /** Parsed, validated POST body. */\n body: ChatTurnRequestPayload\n tenantId: string\n userId: string\n threadId: string\n /** The context `authorize` returned; mutate it in place to finish it. */\n context: TContext\n /** Name the stage this work is in. On a progress-first stream it reaches the\n * client as a `session.run.phase` event; otherwise it is a no-op. */\n progress(phase: string, message: string): void\n}\n\n/** `prepareTurn`'s verdict: proceed, or answer with the product's response. */\nexport type ChatTurnPrepareResult = { ok: true } | { ok: false; response: Response }\n\n/** What `afterAuthorize` receives: the admitted turn, before the conversation loads and before any lock, read or write. */\nexport interface ChatTurnAfterAuthorizeArgs<TContext> {\n request: Request\n /** This request's bound host continuation, when supplied to turn(request, ctx). */\n waitUntil?: ChatTurnRequestContext['waitUntil']\n /** Parsed, validated POST body. */\n body: ChatTurnRequestPayload\n tenantId: string\n userId: string\n threadId: string\n /** The context `authorize` returned. Keep what the seam starts on it: `prepareTurn`, every later seam and `produce` receive the same object. */\n context: TContext\n /** The turn's trace, for the spans of the work the seam starts. */\n trace: TurnTrace\n}\n\n/** Frees what `afterAuthorize` started, for a turn that ends before `produce` takes it. */\nexport type ChatTurnAfterAuthorizeRelease<TResource = unknown> = (() => void | Promise<void>) | {\n /** Acquisition must clean up any partial resource when it rejects. */\n resource: Promise<TResource>\n /** Called once when this turn ends, including a refusal before acquisition resolves. */\n dispose(resource: TResource): void | Promise<void>\n}\n\n/** Trusted per-turn limits supplied by a server adapter, never by the body. */\nexport interface ChatTurnExecutionLimits extends SandboxPromptExecutionLimits {\n maxInputTokens?: 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/** A workspace agent a turn is addressed to, resolved by the product from an\n * `@` mention. `id` is the stable profile id the mention carried. */\nexport interface ChatTurnAgentTarget {\n id: string\n handle: string\n name: string\n /** The profile this responder runs as. A product's `produce` reads it from\n * `args.agent` and runs the turn as that agent instead of the thread's\n * bound one; the binding itself does not move. */\n profile?: AgentProfile\n}\n\n/** How a route turns `@agent` mentions into responders. */\nexport interface ChatTurnAgentsOptions<TContext> {\n /** Resolve the mentioned agents to the targets this caller may address.\n * Return only the ids you recognise for this workspace: a mention whose id\n * is missing from the result is refused as `unknown_agent` before anything\n * runs. Order is ignored; responders answer in mention order. */\n resolve(args: { identity: ChatTurnIdentity; context: TContext; mentions: AgentMention[] }): Promise<ChatTurnAgentTarget[]>\n}\n\n/** Define the arguments required to produce a chat turn with context and messaging details */\nexport interface ChatTurnProduceArgs<TContext, TResource = unknown> {\n /** The agent this producer answers as, when the turn was addressed to one\n * or more agents by mention. The route calls `produce` once per responder,\n * all at once, each with the same thread history and none seeing another's\n * answer, and persists their answers as one assistant row with a speaker\n * part before each, in mention order. Absent → the thread's own agent\n * answers, as before. */\n agent?: ChatTurnAgentTarget\n /** Every responder of this turn, in mention order. */\n agents?: ChatTurnAgentTarget[]\n request: Request\n /** The opaque resource afterAuthorize started; the route disposes it at this turn's end. */\n earlyResource?: Promise<TResource>\n /** This request's bound host continuation, when supplied to turn(request, ctx). */\n waitUntil?: ChatTurnRequestContext['waitUntil']\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 /** The turn's intent line (`intentLine`), or null when it was off, slow or\n * failed. Never rejects. A product puts it in the harness turn's context so\n * the agent knows what the founder was told it would do. */\n intentLine?: Promise<string | null>\n /** Server-authenticated limits for this turn. Never copied from the body. */\n executionLimits?: ChatTurnExecutionLimits\n /**\n * The turn's trace (`@tangle-network/agent-app/turn-trace`), bound to this turn's execution id. Pass it to the\n * Router engine (`trace`), `streamSandboxPrompt` and `ensureWorkspaceSandbox` so the turn's model calls, tool\n * calls and box claim are recorded under it; its `traceId` is what those calls send as `x-tangle-trace-id`.\n * The route records admission and persistence itself. Optional for source compatibility with synthetic\n * producers; every `createChatTurnRoutes` invocation supplies it.\n */\n trace?: TurnTrace\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` — a new row is not inserted yet. The dispatch-first policy\n * and `turnLock.acquire` see this for a fresh turn; a reused row's id is\n * already available from the history read, without another query.\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, including a reused row before dispatch policy;\n * also supplied to `contextGate`, `beforeTurn`, and `produce`. */\n userMessageId?: string | null\n /** True when this turn's own insert created `userMessageId`, so no earlier\n * attempt can have answered it; false when retry-dedup reused the row or no\n * row was written. A gate that refuses an already-answered retry can skip\n * its read when this is true. Already false for a reused row at backend\n * selection and lock acquisition; undefined for a fresh row until insertion. */\n userMessageInserted?: boolean\n /**\n * Transfer completion ownership to a product-owned durable runner. The\n * product MUST register that runner durably, then await this callback before\n * dispatching native execution. When timing transfer is used, persist the initial\n * timingFacts snapshot on the existing admission before registering that runner.\n * A callback rejection after registration retains durable ownership. Once it\n * resolves, this route remains a live event projector only: it no longer writes or settles the assistant\n * transcript, lifecycle hooks, lock, or replay-buffer status.\n *\n * Optional for source compatibility with synthetic producers. Every\n * `createChatTurnRoutes` invocation supplies it before `produce` runs.\n */\n handoffCompletion?: (options?: NativeCompletionHandoffOptions) => Promise<void>\n /** Serializable observations only; snapshots never predict events after handoff. */\n timingFacts?: () => NativeTurnTimingFacts\n /** What the route's `prefetch` read for this turn's admitted identity; set only when `prefetch` is configured. */\n prefetched?: Promise<unknown>\n /** Set for a fresh Router backend, which starts before the lock. Resolves to the final args (with\n * `userMessageId`, after `contextGate` and `beforeTurn`) once the admission chain commits, or rejects with\n * `TurnAdmissionRefusedError` when the turn is refused. Start the model call at once; write nothing durable,\n * and read nothing `beforeTurn` adds to `context`, until it resolves. */\n admitted?: Promise<ChatTurnProduceArgs<TContext, TResource>>\n /** Effective execution signal: product Stop/supersession, opted-in durable Stop/control loss,\n * and optional request-disconnect cancellation.\n * A fresh Router backend also aborts on admission refusal or when the route stops reading it.\n * Pass it to producer I/O; Router/Sandbox option data binds it automatically.\n * Early Router handoff waits for `admitted`. */\n admissionSignal?: AbortSignal\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/** 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/** This owner's cancellation observation: the signal aborts on Stop or control loss.\n * Closing observation does not release the lock or establish remote completion. */\nexport interface ChatTurnCancellation {\n signal: AbortSignal\n /** Close this owner's observation; never release the durable lock or claim remote work stopped. */\n close(): void | Promise<void>\n}\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; cancellation?: ChatTurnCancellation }\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, TResource = unknown> {\n acquire(args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnLockResult | Promise<ChatTurnLockResult>\n release(handle: unknown): void | Promise<void>\n /** Record a release for the durable owner to complete without freeing the lock; absent or false, the lock stays held. */\n park?(handle: unknown): Promise<boolean>\n /** Bring up whatever `acquire` will talk to, as soon as the turn is admitted\n * and while `prepareTurn` and the history read run. Never awaited; a failure\n * is logged and the turn goes on to `acquire` as usual. */\n warm?(target: { tenantId: string; userId: string; threadId: string; context: TContext }): void | Promise<void>\n}\n\ninterface ChatTurnLifecycleBase<TContext> {\n identity: ChatTurnIdentity\n executionId: string\n turnStreamId: string\n context: TContext\n /** Member row and backend observation facts, also reported on persistence failure. */\n userMessageId?: string | null\n backendTerminal?: boolean\n}\n/** When the turn's first visible word streamed, measured from `onTurnStart`. Absent when no word streamed. */\ninterface ChatTurnLifecycleTiming {\n /** Request receipt to onTurnStart; add to firstVisibleMs for request-origin latency. */\n admissionMs?: number\n /** First reasoning, tool activity or answer output, measured from onTurnStart. */\n firstVisibleMs?: number\n firstTextMs?: number\n /** Where the turn's wall time went: its share inside named spans and the time per kind of span. */\n trace?: TurnTraceSummary\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 /** Request receipt on the server clock. */\n requestReceivedAt: number\n admissionMs: 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>, ChatTurnLifecycleTiming {\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>, ChatTurnLifecycleTiming {\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 /** Follow-up work for a turn that ended cleanly: it runs with `onTurnComplete`'s own info once the assistant row is\n * persisted, the lifecycle hooks have fired and the thread's lock is released, under `waitUntil` where the host has\n * one. The member's next send never waits for it, so work that only decorates the answer (a model-written\n * checklist, a title, an index) belongs here and not in the producer's stream, where it holds the lock and the\n * stream open. It does not run for a failed, gated or handed-off turn. The turn's trace has ended; a product that\n * wants this work traced starts its own. A throw is logged and never reaches the member. */\n afterSettle?(info: ChatTurnLifecycleComplete<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 /** Persisted member row for this execution, when insertion was enabled. */\n userMessageId?: string | null\n /** False when a detached backend has not been observed to stop; its workspace stays fenced. */\n backendTerminal?: boolean\n identity: ChatTurnIdentity\n finalText: string\n context: TContext\n failed: boolean\n /** Final producer receipt, when it reports usage; absent counts remain unknown. */\n usage?: ChatTurnUsage\n failureReason?: string\n /** Typed reason of a failed turn, when its terminal error event names one. */\n failureCode?: 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/** Where a finished turn's trace goes, and the host's labels for its root span. Metadata only: never content. */\nexport interface ChatTurnTraceOptions<TContext> {\n /** Default: `createIntelligenceTurnTraceSink({ project: projectId })`, which reads the Sandbox product key from the environment. */\n sink?: TurnTraceSink\n /** Labels for the root span, e.g. the workspace id. Called once per exported turn. */\n labels?(info: { identity: ChatTurnIdentity; executionId: string; context: TContext }): TurnSpanAttrs\n}\n\n/** Define options to configure chat turn routes including authorization, storage, and event buffering */\nexport interface CreateChatTurnRoutesOptions<TContext = void, TResource = unknown> {\n /** Deployment bindings for the template defaults. Custom producers keep their own credentials and policy. */\n env?: import('./default-backend').ChatTurnEnvironment\n /** Disable the inherited prewarm endpoint explicitly. It warms only authenticated thread locks. */\n prewarm?: false\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 /** Let a turn address workspace agents by `@` mention: the composer's\n * `useFileMentions({ agents })` sends them, this resolves them to the\n * profiles they run as, and `produce` answers once per responder. Omit →\n * a turn carrying an agent mention is refused as `agents_unsupported`. */\n agents?: ChatTurnAgentsOptions<TContext>\n /** Resolve the exact authenticated stop target. Without this capability,\n * cancel returns 405 before parsing or authorization. */\n cancel?: ChatTurnCancelOptions<TContext>\n /** Read the turn's prompt inputs (profile, knowledge, catalogs) while `authorize` finishes: started when `authorize`\n * calls `args.identified`, or once it allows the turn. Read only: no writes, nothing paid or external beyond what\n * the verified identity allows. `produce` receives the result as `args.prefetched` only for an allowed turn of that\n * identity; a refusal aborts `args.signal` and drops it. Omit → nothing is prefetched. */\n prefetch?: ChatTurnPrefetch\n /** Finish the turn's context after `authorize` has admitted the caller and\n * before the conversation loads or the lock is taken: resolve the profile,\n * the model, anything that reads or writes product state. Keep `authorize`\n * to admission (identity, access, rate limits, input checks) so a refusal\n * stays fast and no write ever runs for a caller who is not admitted; on a\n * progress-first stream this work runs inside the stream and can name its\n * stages through `progress`. A refusal here is answered like a held lock:\n * a plain response without the progress header, a `turn.response` event\n * with it. Omit → nothing to prepare. */\n prepareTurn?(args: ChatTurnPrepareArgs<TContext>): ChatTurnPrepareResult | Promise<ChatTurnPrepareResult>\n /** Start the work this turn will need, the moment `authorize` and `modelPolicy` have admitted it, so that work overlaps\n * `prepareTurn`, the history read, the lock, the history recheck and the user-row insert instead of following them: the\n * workspace box, the keys a producer mints, a session ensure. Return `{resource, dispose}` to hand the route an\n * opaque acquisition promise: `produce` receives it as `args.earlyResource`, and the route disposes the value once\n * when the turn ends, including a refusal before acquisition resolves. Acquisition owns partial-failure cleanup.\n *\n * Admission has not finished, so the seam must start only work that the turn's refusal leaves harmless: a held lock\n * (409), a changed history, a gate's answer or a throw all end the turn without `produce`, and the work already\n * started runs on. Start nothing a second request for the same thread could not safely repeat, and nothing that\n * writes product state.\n *\n * Not awaited, and it must return synchronously: start the work and return, never wait for it. It may return a\n * legacy release function; the route calls it once, only if the turn ends without `produce` (the chain above, or a throw before the\n * engine took the turn), so a product frees credentials or leases the unused work holds. Once `produce` runs, the\n * work belongs to `produce` and the route never calls the release. A throw is logged and the turn goes on without\n * the early work. Omit → nothing starts early. */\n afterAuthorize?(args: ChatTurnAfterAuthorizeArgs<TContext>): void | ChatTurnAfterAuthorizeRelease<TResource>\n /** Product admission policy over the model a turn NAMES. When the request\n * body carries a `model`, it is checked here — after `authorize`, before\n * the conversation loads, the lock is taken, or any row is written — and a\n * refusal answers 403 with the policy's reason. Fail-closed: a named model\n * carrying no policy metadata is refused.\n *\n * This is half the enforcement. A body without `model` resolves to a\n * product default inside `produce`, which this seam never sees — enforce\n * that half at execution with `createSandboxChatProducer`'s `modelPolicy`\n * (or `runWithModelFailover`'s `policy` on a custom producer), which also\n * covers every fallback the turn could fail over to. Wire the SAME policy\n * object to both. Omit → no policy check (today's behavior). */\n modelPolicy?: ModelPolicy\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 | ChatTurnStoreBindings\n /** Build the turn stream after admission, or declare its execution backends.\n * Router calls start before the lock by default, after authorize has verified\n * identity/access. The model service enforces spend before paying a provider.\n * Output stays buffered until admission commits; a refusal cancels the call.\n * Return Router/Hybrid producer options to bind tracing, cancellation and\n * tool admission automatically. A custom Router producer must pass\n * admissionSignal and await admitted before tools or durable effects.\n * beforeTurn cannot patch a Router prompt already sent.\n *\n * when selects the Router backend (default true); false selects sandbox,\n * which always starts after admission. A function also starts after admission.\n * Reused user rows always finish admission before either backend starts. */\n produce?: import('./default-backend').ChatTurnDefaultBackend<TContext, TResource> | ((args: ChatTurnProduceArgs<TContext, TResource>) => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>) | {\n router(args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnRouterBackend | Promise<ChatTurnRouterBackend>\n when?(args: ChatTurnProduceArgs<TContext, TResource>): boolean\n sandbox?(args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnSandboxBackend | Promise<ChatTurnSandboxBackend>\n }\n /** Single-flight lock acquired before durable effects 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 * the binding-derived workspace lock. `false` explicitly disables it. Native\n * producers retain it until backend termination is observed. */\n turnLock?: ChatTurnLock<TContext, TResource> | false\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 an ordinary/Sandbox producer never run; an\n * early Router call is cancelled and discarded. 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, TResource>): 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?(\n args: ChatTurnProduceArgs<TContext, TResource>,\n /** `span` is the `admission.before_turn` span: the parent for a product's own child spans. */\n seam?: { span: TurnSpan },\n ): 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 /** 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 /**\n * Where each finished turn's trace goes. On by default: omit it and every turn goes to Tangle Intelligence under\n * `projectId` (`createIntelligenceTurnTraceSink`); pass `{ sink, labels }` to send it elsewhere or label it.\n * The route always records the turn's trace (`ChatTurnProduceArgs.trace`), reports its summary to `lifecycle`, and\n * writes one `agent_app_turn_trace` log line per turn (first text, coverage, time per kind); this sends the spans on.\n * The sink runs under `waitUntil` after the lifecycle hooks and after the turn lock is released, and its failure never\n * fails a turn. A turn handed to a durable owner (`handoffCompletion`) is exported when this request's live\n * projection ends, failed only when the projection saw an error. `false` is the only opt-out, and\n * `agent-app-signoff defaults` fails it until the app's `signoff.config.mjs` gives the reason.\n */\n turnTrace?: ChatTurnTraceOptions<TContext> | false\n /** Compose the interaction-answer endpoints (`/interactions`). Omit when the\n * product has no sidecar ask channel. */\n interactions?: InteractionAnswerRouteOptions\n /** Text for the route's own stages on a progress-first stream (`./turn-progress`).\n * Omitted stages keep `TURN_ROUTE_PHASE_MESSAGES`. */\n progressMessages?: Partial<Record<TurnRoutePhase, string>>\n /** Write and stream the turn's intent line ({@link ChatTurnIntentLine}). Omit → no line. */\n intentLine?: ChatTurnIntentLine<TContext>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** What `intentLine.generate` receives: the admitted turn's message and the thread's last few turns. */\nexport interface ChatTurnIntentLineArgs<TContext> {\n content: string\n /** The thread's last turns before this one, oldest first (at most {@link INTENT_LINE_HISTORY_MESSAGES}). */\n history: ReadonlyArray<{ role: 'user' | 'assistant' | 'system' | 'tool'; content: string }>\n tenantId: string\n userId: string\n threadId: string\n context: TContext\n /** Aborted when the line is no longer wanted (its deadline passed). */\n signal: AbortSignal\n}\n\n/**\n * The intent line: one plain sentence, written by a fast model call the moment\n * a turn is admitted, saying what the agent is about to do. It reaches a\n * progress-first client as a {@link TURN_INTENT_EVENT} while the harness boots,\n * and the turn's first answer text replaces it. It narrates intent and must\n * never answer or act. It fails open: a line later than `timeoutMs`, an error,\n * or an empty answer shows nothing.\n */\nexport interface ChatTurnIntentLine<TContext> {\n generate(args: ChatTurnIntentLineArgs<TContext>): Promise<string | null>\n /** Longest wait for the line. Default {@link INTENT_LINE_TIMEOUT_MS}. */\n timeoutMs?: number\n}\n\n/** A line slower than this shows nothing. */\nexport const INTENT_LINE_TIMEOUT_MS = 1_500\n/** Turns of the thread the line is written from. */\nexport const INTENT_LINE_HISTORY_MESSAGES = 6\n/** Longest line kept; anything longer is cut. */\nexport const INTENT_LINE_MAX_CHARS = 240\n\n/** Define routes to run, replay, and list running chat turns with streaming and reconnect support */\nexport interface ChatTurnRoutes {\n /** POST — warm the server-authorized workspace lock; verify a named thread before allowing it. Never provisions paid compute. */\n prewarm(request: Request): Promise<Response>\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. A request with\n * `TURN_PROGRESS_HEADER` gets a progress-first stream once it is\n * authorized (`./turn-progress`). */\n turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response>\n /** POST — stop the exact authorized execution; unavailable unless configured. */\n cancel(request: Request): 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 * The turn's read-only prefetch: the inputs its prompt needs (profile, knowledge, catalogs), read while `authorize`\n * finishes instead of after it.\n *\n * `authorize` calls `identified({ tenantId, userId })` once it has verified who is asking, and the route starts the\n * product's `prefetch` then, beside the rest of `authorize` (billing gates, rate limits). Nothing it read reaches the\n * producer unless `authorize` allows the turn for that same identity; on a refusal its signal aborts and its result\n * is dropped. An `authorize` that never calls `identified` still gets the prefetch, started once it allows the turn.\n *\n * Why: Legal's turns ran `authorize` (~716 ms) and then the prompt reads (~597 ms) in series before the model call\n * (dispatchMs median 1,567 ms); Creative overlaps the same reads by hand (creative-agent\n * chat-vertical.ts:289). The contract: the prefetch only reads. It writes nothing and calls nothing paid or external\n * as the member beyond what the verified identity already allows.\n */\nimport type { TurnTrace } from '../turn-trace/recorder'\nimport type { ChatTurnRequestPayload } from './wire'\n\n/** Who `authorize` verified the caller to be: the workspace (tenant) and the member. */\nexport interface ChatTurnPrefetchIdentity {\n tenantId: string\n userId: string\n}\n\nexport interface ChatTurnPrefetchArgs extends ChatTurnPrefetchIdentity {\n request: Request\n body: ChatTurnRequestPayload\n trace: TurnTrace\n /** Aborts when the turn is refused; stop reading. */\n signal: AbortSignal\n}\n\nexport type ChatTurnPrefetch = (args: ChatTurnPrefetchArgs) => unknown\n\nexport interface TurnPrefetchRun {\n /** For `authorize`: the caller's identity is verified; start the prefetch now. Later calls are ignored. */\n identified(identity: ChatTurnPrefetchIdentity): void\n /** `authorize` allowed the turn: the prefetch for this identity, started now if `identified` never ran or named\n * someone else. */\n admitted(identity: ChatTurnPrefetchIdentity): Promise<unknown>\n /** The turn was refused: abort the prefetch and drop what it read. */\n discard(): void\n}\n\nexport function startTurnPrefetch(\n prefetch: ChatTurnPrefetch,\n input: { request: Request; body: ChatTurnRequestPayload; trace: TurnTrace },\n): TurnPrefetchRun {\n let started: { identity: ChatTurnPrefetchIdentity; abort: AbortController; result: Promise<unknown> } | undefined\n const start = (identity: ChatTurnPrefetchIdentity) => {\n const abort = new AbortController()\n const result = input.trace.measure('admission.prefetch', 'admission', async () => prefetch({\n ...input, tenantId: identity.tenantId, userId: identity.userId, signal: abort.signal,\n }))\n // A refused turn never awaits it; its failure must not become an unhandled rejection.\n result.catch(() => {})\n started = { identity: { ...identity }, abort, result }\n }\n return {\n identified(identity) {\n if (!started) start(identity)\n },\n admitted(identity) {\n if (started && (started.identity.tenantId !== identity.tenantId || started.identity.userId !== identity.userId)) {\n // Read for a different identity than the one admitted: never hand it on.\n started.abort.abort()\n started = undefined\n }\n if (!started) start(identity)\n return started!.result\n },\n discard() {\n started?.abort.abort()\n started = undefined\n },\n }\n}\n","/** Admission-to-settlement execution for one authenticated chat turn. */\nimport { deriveExecutionId, handleChatTurn, type ChatTurnIdentity } from '@tangle-network/agent-runtime/durable'\nimport { toChatMessageParts } from '../chat-store/parts'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n resolveChatTurn,\n type BufferedTurnTap,\n type PersistedChatMessageForTurn,\n} from '../stream/index'\nimport type { TurnTraceSink, TurnTraceSnapshot, TurnTraceSummary } from '../turn-trace/recorder'\nimport { otlpTraceId } from '../turn-trace/otel'\nimport { noteMeasuredTurnFacts, readableTurnFailure } from '../turn-trace/turn-facts'\nimport { createNativeTimingTransfer, type NativeTimingTransfer } from './native-turn-timing'\nimport { createChatTurnOwnership } from './turn-ownership'\nimport {\n assistantRowIdForTurn,\n createAssistantDraftWriter,\n rowIdOf,\n type AssistantDraftStore,\n type AssistantDraftWriter,\n type DraftPersistenceTuning,\n} from './draft-persistence'\nimport { dispatchFirstFor, selectTurnProducer } from './dispatch-first'\nimport { observeTurnCancellation } from './cancellation'\nimport { admissionServerTiming, errorResponse, userPartsWithFiles, type AdmittedTurn, type TurnProgressCallback } from './turn-admission'\nimport { abortOnSignal, concatStreams, failureCodeOf, failureReasonOf, isVisibleOutput, isVisibleText, tapRawEvents, withStreamHeartbeat } from './turn-event-stream'\nimport type {\n ChatTurnLifecycleComplete,\n ChatTurnModelAttribution,\n ChatTurnProduceArgs,\n ChatTurnRequestContext,\n ChatTurnRouteProducer,\n ChatTurnTraceOptions,\n ChatRouteEvent,\n CreateChatTurnRoutesOptions,\n} from './turn-route-contracts'\nimport type { TurnRoutePhase } from './turn-progress'\nimport { ChatTurnInputError, type ChatTurnPartInput } from './wire'\nimport { addressAgents, composeAgentProducers } from './agent-producers'\nimport type { ResolvedChatTurnRoutesOptions } from './route-storage'\nimport type { AfterAuthorizeWork } from './early-turn-work'\n\n/** The thread's messages as the turn-identity resolver reads them. */\nasync function readTurnHistory(store: CreateChatTurnRoutesOptions<unknown>['store'], threadId: string): Promise<PersistedChatMessageForTurn[]> {\n return (await store.listMessages(threadId)).map((m) => ({\n id: m.id, role: m.role, content: m.content, parts: (m.parts ?? null) as PersistedChatMessageForTurn['parts'],\n }))\n}\n\ninterface TurnExecutionOptions<TContext, TResource> {\n options: ResolvedChatTurnRoutesOptions<TContext, TResource>\n draftStore: AssistantDraftStore\n draftTuning: DraftPersistenceTuning | null\n progressMessages: Record<TurnRoutePhase, string>\n traceOptions: ChatTurnTraceOptions<TContext> | undefined\n traceSink: TurnTraceSink | undefined\n startIntentLine(admitted: AdmittedTurn<TContext>): Promise<string | null> | undefined\n log(message: string, meta?: Record<string, unknown>): void\n}\n\n/** One requested-versus-served projection for persistence and both completion receipts. */\nfunction modelAttributionFields(attribution: ChatTurnModelAttribution | undefined) {\n return {\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 }\n}\n\n/** Bind the route's construction-time dependencies; each invocation retains its own turn state. */\n/** The lifecycle's timing for a settled turn, noted for the rollout timing store so it can fill a product row that\n * omits it (rollout/d1 `record`). */\nfunction settledTurnTiming(turnStreamId: string, at: {\n requestAt: number; startedAt: number; firstVisibleAt?: number\n firstTextAt?: number; model?: string\n failure?: { data?: Record<string, unknown>; error: unknown }\n}, trace: TurnTraceSummary) {\n const measured = {\n admissionMs: at.startedAt - at.requestAt,\n ...(at.firstVisibleAt === undefined ? {} : { firstVisibleMs: at.firstVisibleAt - at.startedAt }),\n ...(at.firstTextAt === undefined ? {} : { firstTextMs: at.firstTextAt - at.startedAt }),\n }\n const failureCode = at.failure ? readableTurnFailure(at.failure.error, at.failure.data) : undefined\n noteMeasuredTurnFacts(turnStreamId, { requestReceivedAt: at.requestAt, ...measured, ...(at.model ? { model: at.model } : {}),\n ...(failureCode ? { failureCode } : {}) })\n return { ...measured, trace }\n}\n\nexport function createAdmittedTurnRunner<TContext, TResource>(dependencies: TurnExecutionOptions<TContext, TResource>) {\n return (runAdmittedTurn<TContext, TResource>).bind(null, dependencies)\n}\n\nasync function runAdmittedTurn<TContext, TResource>({\n options, draftStore, draftTuning, progressMessages, traceOptions, traceSink, startIntentLine, log,\n}: TurnExecutionOptions<TContext, TResource>,\n request: Request,\n ctx: ChatTurnRequestContext | undefined,\n admitted: AdmittedTurn<TContext>,\n early: AfterAuthorizeWork<TResource>,\n progress?: TurnProgressCallback,\n startedIntent?: Promise<string | null>,\n): Promise<Response> {\n const { parsed, auth, trace } = admitted\n // A progress-first turn started its line at admission; any other starts it here.\n const intentLine = startedIntent ?? startIntentLine(admitted)\n const { payload, content, fileParts, mentions, turnId } = parsed\n const { tenantId, userId, context } = auth\n\n const preparedBatch = await prepareAdmittedTurn(options, trace, log, tenantId, userId, payload, context, request, progress, content, turnId, draftTuning, ctx?.waitUntil)\n if (preparedBatch instanceof Response) return preparedBatch\n const { turnStreamId, identity, executionId, chatTurn, readHistory, historyBeforeLock } = preparedBatch\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 // A product calls this only after it has durably registered the external\n // completion owner and before it dispatches native execution. Keeping the\n // public field optional preserves existing synthetic producers; this\n // assembled route always supplies it to the real `produce` invocation.\n const state = createAdmittedTurnState<TContext>()\n if (options.cancel) state.cancellationAbort = new AbortController()\n\n state.nativeTiming = createNativeTimingTransfer(() => ({\n turnStreamId, requestReceivedAt: trace.startedAt,\n ...(state.turnStarted ? { lifecycleStartedAt: state.turnStartedAtMs, admissionMs: state.turnStartedAtMs - trace.startedAt } : {}),\n ...(state.firstVisibleAtMs === undefined ? {} : { firstVisibleMs: state.firstVisibleAtMs - state.turnStartedAtMs }),\n ...(state.firstTextAtMs === undefined ? {} : { firstTextMs: state.firstTextAtMs - state.turnStartedAtMs }),\n }), error => log('[chat-routes] native timing persistence failed', { turnId: turnStreamId,\n error: error instanceof Error ? error.message : String(error) }))\n const { handoffCompletion, releaseLock } = createChatTurnOwnership(state, log, turnStreamId, options)\n\n let produceArgs: ChatTurnProduceArgs<TContext, TResource> = {\n request,\n waitUntil: ctx?.waitUntil,\n earlyResource: early.resource,\n admissionSignal: AbortSignal.any([\n state.executionAbort.signal,\n ...(state.cancellationAbort ? [state.cancellationAbort.signal] : []),\n ...(ctx?.cancelOnDisconnect ? [request.signal] : []),\n ]),\n body: payload,\n identity,\n context,\n prompt,\n executionId,\n turnStreamId,\n priorMessages: chatTurn.priorMessages, ...(chatTurn.reusedUserMessageId ? { userMessageId: chatTurn.reusedUserMessageId, userMessageInserted: false } : {}),\n handoffCompletion,\n timingFacts: state.nativeTiming.snapshot,\n trace,\n ...(intentLine ? { intentLine } : {}), ...(admitted.prefetched ? { prefetched: admitted.prefetched } : {}),\n ...(ctx?.executionLimits ? { executionLimits: ctx.executionLimits } : {}),\n }\n // Responders named from the product's own catalog, before any lock, row or model call.\n const addressed = await addressAgents({ options, mentions, identity, context, produceArgs, trace })\n if (addressed instanceof Response) return addressed\n produceArgs = addressed\n const selected = selectTurnProducer(options.produce, produceArgs)\n // Responders answer one after another, so nothing starts before the lock.\n const dispatched = produceArgs.agents ? undefined : dispatchFirstFor(selected, produceArgs, trace)\n if (dispatched) early.add(dispatched.refuse)\n const turnLock = options.turnLock\n if (turnLock) {\n const acquired = await trace.measure('admission.lock', 'admission', () => turnLock.acquire(produceArgs))\n if (!acquired.acquired) return acquired.response\n state.lockAcquired = true\n state.lockHandle = acquired.handle\n if (acquired.cancellation) {\n const cancellation = acquired.cancellation\n const abort = () => state.executionAbort.abort(cancellation.signal.reason)\n if (cancellation.signal.aborted) abort()\n else cancellation.signal.addEventListener('abort', abort, { once: true })\n state.closeCancellation = async () => {\n cancellation.signal.removeEventListener('abort', abort)\n await cancellation.close()\n }\n }\n }\n progress?.('preparing', progressMessages.preparing)\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\n // Set once persistence settles; `undefined` means it never ran.\n\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 { endTrace, exportTraceInBackground, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle } = createTurnSettlement(state, trace, options, executionId, traceSink, identity, traceOptions, context, turnStreamId, log, ctx, () => produceArgs.userMessageId)\n\n try {\n if (state.lockAcquired && JSON.stringify(await trace.measure('admission.history_recheck', 'admission', readHistory)) !== historyBeforeLock) {\n await releaseLock()\n return Response.json({\n code: 'chat_history_changed',\n error: 'The conversation changed while this turn was acquiring its lock. Refresh the conversation before starting new work.',\n }, { status: 409 })\n }\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 let userMessageInserted = false\n if (insertUserMessage) {\n userMessageId = rowIdOf(\n await trace.measure('admission.persist_user', 'admission', () => options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts, mentions),\n })),\n )\n userMessageInserted = userMessageId !== null\n }\n produceArgs = { ...produceArgs, userMessageId, userMessageInserted }\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 const contextGate = options.contextGate\n if (contextGate) {\n const gate = await trace.measure('admission.gate', 'admission', () => contextGate(produceArgs))\n if (gate.proceed === 'handoff') {\n await releaseLock()\n state.legacyHandoff = true\n endTrace(false, undefined)\n exportTraceInBackground()\n return gate.response\n }\n if (!gate.proceed) {\n await releaseLock()\n if (state.completionHandoff) {\n endTrace(false, undefined)\n exportTraceInBackground()\n return gate.response\n }\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 state.gatedTurn = true\n state.turnStartedAtMs = Date.now()\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: state.turnStartedAtMs,\n requestReceivedAt: trace.startedAt, admissionMs: state.turnStartedAtMs - trace.startedAt,\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 exportTraceInBackground()\n return gate.response\n }\n }\n\n // Observe + optionally augment the assembled producer input.\n const beforeTurn = options.beforeTurn\n if (beforeTurn) {\n const patch = await trace.measure('admission.before_turn', 'admission', (span) => beforeTurn(produceArgs, { span }))\n if (patch && Object.keys(patch).length && dispatched) throw new Error('beforeTurn cannot patch a Router turn already dispatched: its prompt is already sent')\n if (patch) produceArgs = { ...produceArgs, ...patch }\n }\n const streamSetup = trace.start('admission.stream_setup', 'admission')\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 state.tap = createBufferedTurnTap({\n store: options.turnStore,\n turnId: turnStreamId,\n scopeId: payload.threadId,\n coalesce: coalesceDeltas,\n })\n const turnMarker = { type: 'turn', turnId: turnStreamId }\n await state.tap.onEvent(turnMarker)\n if (state.completionHandoff) await state.tap!.detach()\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 state.draft = createAssistantDraftWriter({\n ...draftTuning,\n store: draftStore,\n threadId: payload.threadId,\n messageId: assistantRowIdForTurn(executionId),\n snapshot: () => {\n if (!state.producer || state.cancellationAbort?.signal.aborted) return null\n return {\n content: state.producer.finalText(),\n ...(state.producer.draftParts ? { parts: state.producer.draftParts() } : {}),\n ...(state.producer.usage ? { usage: state.producer.usage() } : {}),\n ...(state.producer.model ? { model: state.producer.model } : {}),\n }\n },\n ...(options.transformFinalText ? { transformText: options.transformFinalText } : {}),\n log,\n })\n // `contextGate` / `beforeTurn` may have handed ownership off before\n // the writer existed. Close this late-created writer immediately so it\n // cannot receive a later live event.\n if (state.completionHandoff) await state.draft.close()\n }\n\n state.turnStartedAtMs = Date.now()\n state.turnStarted = true\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: state.turnStartedAtMs,\n requestReceivedAt: trace.startedAt, admissionMs: state.turnStartedAtMs - trace.startedAt,\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 streamSetup.end()\n\n const { result } = createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, trace, options, selected.produce, request, context, payload, assistantRowId)\n\n // The engine has the turn, and its first pull runs `produce`, which owns whatever `afterAuthorize` started.\n const { clientBody } = startTurnDrain(result, log, turnStreamId, state, endTrace, exportTrace, trace, ctx, request, fireTerminalLifecycle, releaseLock, runAfterSettle, early.settle)\n early.handOff()\n\n return createTurnReplayResponse(result.contentType, clientBody, turnMarker, trace)\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 (!state.completionHandoff) {\n if (state.turnStarted) await fireTerminalLifecycle(true, err)\n await releaseLock()\n }\n // A turn that failed before it started, or after a durable owner took it, still ends its trace here.\n endTrace(true, err)\n exportTraceInBackground()\n throw err\n }\n}\ninterface AdmittedTurnState<TContext> {\n executionAbort: AbortController\n closeCancellation: (() => Promise<void>) | undefined\n draft: AssistantDraftWriter | undefined\n tap: BufferedTurnTap | undefined\n nativeTiming: NativeTimingTransfer | undefined\n completionHandoff: boolean\n completionHandoffPromise: Promise<void> | undefined\n lockAcquired: boolean\n lockHandle: unknown\n lockReleased: boolean\n cancellationAbort?: AbortController\n producer: ChatTurnRouteProducer | undefined\n assistantMessageId: string | null | undefined\n runFailed: boolean\n lastFailureData: Record<string, unknown> | undefined\n turnStartedAtMs: number\n firstVisibleAtMs: number | undefined\n firstTextAtMs: number | undefined\n turnStarted: boolean\n lifecycleSettled: boolean\n settledTurn: ChatTurnLifecycleComplete<TContext> | undefined\n gatedTurn: boolean\n legacyHandoff: boolean\n pendingTraceExport: (() => void | Promise<void>) | undefined\n traceEnded: boolean\n}\n\nfunction createAdmittedTurnState<TContext>(): AdmittedTurnState<TContext> {\n return {\n executionAbort: new AbortController(), closeCancellation: undefined,\n draft: undefined,\n tap: undefined,\n nativeTiming: undefined,\n completionHandoff: false,\n completionHandoffPromise: undefined,\n lockAcquired: false,\n lockHandle: undefined,\n lockReleased: false,\n producer: undefined,\n assistantMessageId: undefined,\n runFailed: false,\n lastFailureData: undefined,\n turnStartedAtMs: 0,\n firstVisibleAtMs: undefined,\n firstTextAtMs: undefined,\n turnStarted: false,\n lifecycleSettled: false,\n settledTurn: undefined,\n gatedTurn: false,\n legacyHandoff: false,\n pendingTraceExport: undefined,\n traceEnded: false,\n }\n}\n\nasync function prepareAdmittedTurn<TContext, TResource>(\n options: TurnExecutionOptions<TContext, TResource>['options'],\n trace: AdmittedTurn<TContext>['trace'],\n log: (message: string, meta?: Record<string, unknown>) => void,\n tenantId: string,\n userId: string,\n payload: AdmittedTurn<TContext>['parsed']['payload'],\n context: TContext,\n request: Request,\n progress: TurnProgressCallback | undefined,\n content: string,\n turnId: string | undefined,\n draftTuning: TurnExecutionOptions<TContext, TResource>['draftTuning'],\n waitUntil: ChatTurnRequestContext['waitUntil'],\n) {\n if (options.turnLock?.warm) {\n // Overlaps the lock's first-use cost with prepareTurn and the history read.\n // Its span shows that cost: waking the workspace channel that holds the lock.\n const warmSpan = trace.start('admission.lock_warm', 'admission')\n const warmFailed = (err: unknown) => {\n warmSpan.end(undefined, err)\n log('[chat-routes] turnLock.warm failed', { error: err instanceof Error ? err.message : String(err) })\n }\n try {\n void Promise.resolve(options.turnLock.warm({ tenantId, userId, threadId: payload.threadId, context })).then(() => warmSpan.end(), warmFailed)\n } catch (err) {\n warmFailed(err)\n }\n }\n\n const prepareTurn = options.prepareTurn\n if (prepareTurn) {\n const prepared = await trace.measure('admission.prepare', 'admission', () => prepareTurn({\n request,\n waitUntil,\n body: payload,\n tenantId,\n userId,\n threadId: payload.threadId,\n context,\n progress: (phase, message) => progress?.(phase, message),\n }))\n if (!prepared.ok) return prepared.response\n }\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 readHistory = () => readTurnHistory(options.store, payload.threadId)\n const historySpan = trace.start('admission.history', 'admission')\n const existingMessages = await readHistory()\n // Lock acquisition is async and follows identity derivation. A previous\n // owner can settle in that gap; the new owner must not dispatch an identity\n // or prompt derived from the old history. Capture values now, including\n // parts, rather than retaining mutable message references across the lock.\n const historyBeforeLock = options.turnLock ? JSON.stringify(existingMessages) : undefined\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 //\n // The probe can only change the answer when the running reading would\n // reuse a row (no client turnId, and the user row behind the trailing\n // assistant rows repeats this content); the settled reading never reuses\n // past a trailing assistant row. Every other turn, including each ordinary\n // follow-up, skips the round trip with an identical result.\n let chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId, hasRunningTurn: false })\n if (draftTuning && existingMessages.at(-1)?.role === 'assistant') {\n const ifRunning = resolveChatTurn({ existingMessages, userContent: content, turnId, hasRunningTurn: true })\n if (!ifRunning.shouldInsertUserMessage) {\n let hasRunningTurn = false\n try {\n hasRunningTurn = ((await trace.measure('admission.running_probe', 'admission', () => options.turnStore.listRunning?.(payload.threadId), undefined, historySpan)) ?? []).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 if (hasRunningTurn) chatTurn = ifRunning\n }\n }\n historySpan.end({ messages: existingMessages.length })\n\n const identity: ChatTurnIdentity = {\n tenantId,\n sessionId: payload.threadId,\n userId,\n turnIndex: chatTurn.turnIndex,\n }\n const turnExecutionId = deriveExecutionId({\n projectId: options.projectId,\n sessionId: payload.threadId,\n turnIndex: chatTurn.turnIndex,\n })\n // Message identity preserves the original inputs; an explicit retry starts\n // another native execution with its own immutable completion receipt.\n const executionId = payload.retryAttemptId\n ? `${turnExecutionId}:retry:${payload.retryAttemptId}`\n : turnExecutionId\n if (executionId.length > 256) return errorResponse(new ChatTurnInputError('Retry execution id exceeds 256 bytes'))\n // From here the trace's id is the turn's execution id, the id every Router and Sandbox call sends.\n trace.bind(executionId)\n const turnStreamId = crypto.randomUUID()\n return { turnStreamId, identity, executionId, chatTurn, readHistory, historyBeforeLock }\n}\n\nfunction createTurnSettlement<TContext, TResource>(\n state: AdmittedTurnState<TContext>,\n trace: AdmittedTurn<TContext>['trace'],\n options: TurnExecutionOptions<TContext, TResource>['options'],\n executionId: string,\n traceSink: TurnExecutionOptions<TContext, TResource>['traceSink'],\n identity: ChatTurnIdentity,\n traceOptions: TurnExecutionOptions<TContext, TResource>['traceOptions'],\n context: TContext,\n turnStreamId: `${string}-${string}-${string}-${string}-${string}`,\n log: (message: string, meta?: Record<string, unknown>) => void,\n ctx: ChatTurnRequestContext | undefined,\n userMessageId: () => string | null | undefined,\n) {\n const assistantRowId = (): string | null => state.assistantMessageId ?? state.draft?.rowId() ?? null\n\n // Data of the event that marked the run failed — handed to `onTurnError`\n // when no drain throw supplies a richer cause.\n\n // Answer text stays separate from reasoning and tools.\n\n // What `lifecycle.afterSettle` receives: set when the turn ended cleanly with a producer that ran.\n\n // Set when `contextGate` answered the turn without running the producer.\n\n // Set when `contextGate` handed the turn to the product's durable owner (`{ proceed: 'handoff' }`).\n\n /**\n * End the turn's trace once: write its summary line, and arm its export for `exportTrace`. A turn handed to a\n * durable owner ends here when this request's live projection ends; the owner settles everything else.\n */\n const endTrace = (failed: boolean, terminalError: unknown): TurnTraceSnapshot => {\n const failureCode = failed\n ? (failureCodeOf(state.lastFailureData) ?? (terminalError instanceof Error ? terminalError.name : 'turn_failed'))\n : undefined\n const snapshot = trace.finish(failureCode === undefined ? {} : { error: failureCode })\n if (state.traceEnded) return snapshot\n state.traceEnded = true\n const handedOff = state.completionHandoff || state.legacyHandoff\n // One line per turn in the host's logs (Workers Logs), so first text and coverage are readable without Intelligence.\n console.info(JSON.stringify({\n event: 'agent_app_turn_trace',\n project: options.projectId,\n executionId,\n otlpTraceId: otlpTraceId(snapshot.traceId),\n failed,\n ...(failureCode ? { failureCode } : {}),\n ...(handedOff ? { handedOff: true } : {}),\n ...(state.gatedTurn ? { gated: true } : {}),\n ...snapshot.summary,\n }))\n // Sent by `exportTrace`, after the turn lock is released: a slow collector must not hold the next send.\n const sink = traceSink\n if (sink) {\n state.pendingTraceExport = () => sink(snapshot, {\n 'tangle.sessionId': identity.sessionId,\n 'tangle.userId': identity.userId,\n 'tangle.tenantId': identity.tenantId,\n 'tangle.turn.failed': failed,\n ...(state.gatedTurn ? { 'tangle.turn.gated': true } : {}),\n ...(handedOff ? { 'tangle.turn.handed_off': true } : {}),\n ...(failureCode ? { 'tangle.turn.failure_code': failureCode } : {}),\n ...(traceOptions?.labels?.({ identity, executionId, context }) ?? {}),\n })\n }\n return snapshot\n }\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 (state.lifecycleSettled) return\n state.lifecycleSettled = true\n // The trace ends with the turn, before the product's own hooks run, so their work is not in its wall time.\n const snapshot = endTrace(failed, terminalError)\n const lifecycle = options.lifecycle\n const backend = { userMessageId: userMessageId(),\n backendTerminal: Boolean(state.producer) && (state.producer?.terminalObserved?.() ?? true) }\n const durationMs = Date.now() - state.turnStartedAtMs\n const timing = settledTurnTiming(turnStreamId, {\n requestAt: trace.startedAt, startedAt: state.turnStartedAtMs,\n firstVisibleAt: state.firstVisibleAtMs, firstTextAt: state.firstTextAtMs, model: state.producer?.model,\n failure: failed ? { data: state.lastFailureData, error: terminalError } : undefined,\n }, snapshot.summary)\n try {\n if (!lifecycle) {\n // No hooks to run; the trace still goes to its sink below.\n } else if (failed) {\n await lifecycle.onTurnError?.({\n identity, executionId, turnStreamId, context, durationMs, ...timing, ...backend,\n error: terminalError ?? state.lastFailureData ?? new Error('chat turn failed'),\n })\n } else {\n const failoverInfo = state.producer?.modelFailover?.()\n const attribution = state.producer?.modelAttribution?.()\n const completed: ChatTurnLifecycleComplete<TContext> = {\n identity, executionId, turnStreamId, context, durationMs, ...timing, ...backend,\n finalText: state.cancellationAbort?.signal.aborted ? '' : state.producer?.finalText() ?? '',\n usage: state.producer?.usage?.() ?? {},\n assistantMessageId: assistantRowId(),\n ...(state.gatedTurn ? { gated: true } : {}),\n ...(state.producer?.model ? { model: state.producer.model } : {}),\n ...modelAttributionFields(attribution),\n ...(failoverInfo ? { modelFailover: failoverInfo } : {}),\n }\n if (!state.gatedTurn) state.settledTurn = completed\n await lifecycle.onTurnComplete?.(completed)\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 /** Send the finished trace to its sink. Never throws. */\n const exportTrace = async (): Promise<void> => {\n const send = state.pendingTraceExport\n state.pendingTraceExport = undefined\n if (!send) return\n try {\n await send()\n } catch (err) {\n log('[chat-routes] turn trace sink failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n /** The product's follow-up work for a turn that ended cleanly, once its lock is released. Never throws. */\n const runAfterSettle = async (): Promise<void> => {\n const info = state.settledTurn\n state.settledTurn = undefined\n const afterSettle = options.lifecycle?.afterSettle\n if (!info || !afterSettle) return\n try {\n await afterSettle(info)\n } catch (err) {\n log('[chat-routes] lifecycle.afterSettle failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n /** Export after the response is on its way: under `waitUntil` where the host has one. */\n const exportTraceInBackground = (): void => {\n const sent = exportTrace()\n if (ctx?.waitUntil) ctx.waitUntil(sent)\n else void sent.catch(() => { })\n }\n return { endTrace, exportTraceInBackground, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle }\n}\n\nfunction createTurnEngine<TContext, TResource>(\n identity: ChatTurnIdentity,\n ctx: ChatTurnRequestContext | undefined,\n log: (message: string, meta?: Record<string, unknown>) => void,\n state: AdmittedTurnState<TContext>,\n dispatched: ReturnType<typeof dispatchFirstFor<TContext, TResource>>,\n produceArgs: ChatTurnProduceArgs<TContext, TResource>,\n trace: AdmittedTurn<TContext>['trace'],\n options: TurnExecutionOptions<TContext, TResource>['options'],\n produce: ReturnType<typeof selectTurnProducer<TContext, TResource>>['produce'],\n request: Request,\n context: TContext,\n payload: AdmittedTurn<TContext>['parsed']['payload'],\n assistantRowId: () => string | null,\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 // The product's own admission work: its profile pin, prompt and producer construction.\n const producerStream = async function* () {\n const started = dispatched\n ? dispatched.take(produceArgs)\n : produceArgs.agents\n ? trace.measure('admission.produce', 'admission', () => composeAgentProducers(produceArgs, produce))\n : trace.measure('admission.produce', 'admission', () => produce(produceArgs))\n if (!dispatched) {\n const cleanup = started.then(producer => producer.cleanup, () => undefined)\n ctx?.waitUntil?.(cleanup)\n void cleanup.catch(() => {})\n }\n state.producer = await started\n yield* state.producer.stream\n }\n let source: AsyncIterable<ChatRouteEvent> = producerStream()\n // A durable owner connection already carries exact authenticated Stop.\n // Keep metadata observation only for existing non-adopting targets.\n if (options.cancel && state.cancellationAbort && !state.closeCancellation) {\n source = observeTurnCancellation(source, produceArgs, options.cancel, state.cancellationAbort)\n }\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: () => state.cancellationAbort?.signal.aborted ? '' : state.producer?.finalText() ?? '',\n }),\n onEvent: async (event) => {\n let timingChanged = false\n if (state.firstVisibleAtMs === undefined && isVisibleOutput(event)) {\n state.firstVisibleAtMs = Date.now()\n trace.markFirstVisible(state.firstVisibleAtMs)\n timingChanged = true\n }\n if (state.firstTextAtMs === undefined && isVisibleText(event)) {\n state.firstTextAtMs = Date.now()\n trace.markFirstText(state.firstTextAtMs)\n timingChanged = true\n }\n if (timingChanged) {\n const written = state.nativeTiming?.note()\n if (written && ctx?.waitUntil) ctx.waitUntil(written)\n }\n if (event.type === 'session.run.failed' || event.type === 'error') {\n state.runFailed = true\n state.lastFailureData = event.data\n }\n await state.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 if (!state.completionHandoff) state.draft?.notify(event)\n if (options.onEvent) await options.onEvent(event, context)\n },\n ...(options.transformFinalText ? { transformFinalText: options.transformFinalText } : {}),\n persistAssistantMessage: ({ finalText }) => trace.measure('persist.assistant', 'persist', async () => {\n if (state.completionHandoff) return\n if (state.cancellationAbort?.signal.aborted || (ctx?.cancelOnDisconnect && request.signal.aborted)) {\n await state.draft?.discard()\n state.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 = state.producer?.assistantParts ? state.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 state.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 state.assistantMessageId = state.draft?.rowId() ?? null\n return\n }\n if (state.cancellationAbort?.signal.aborted) {\n await state.draft?.discard()\n state.assistantMessageId = null\n return\n }\n const usage = state.producer?.usage?.() ?? {}\n const attribution = state.producer?.modelAttribution?.()\n const values = {\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(state.producer?.model ? { model: state.producer.model } : {}),\n ...modelAttributionFields(attribution),\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 (state.draft) {\n await state.draft.finalize(values)\n state.assistantMessageId = state.draft.rowId() ?? null\n return\n }\n state.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: async ({ identity: turnIdentity, finalText }: { identity: ChatTurnIdentity; finalText: string }) => {\n if (state.completionHandoff) return\n // Read AFTER the drain, so the model reported to billing is\n // the one that actually served — a fallback included.\n const failoverInfo = state.producer?.modelFailover?.()\n const attribution = state.producer?.modelAttribution?.()\n // The engine awaits this before the stream ends, so the product's completion work is a span, not a gap.\n return trace.measure('persist.on_turn_complete', 'persist', () => options.onTurnComplete!({\n identity: turnIdentity,\n userMessageId: produceArgs.userMessageId,\n backendTerminal: state.producer?.terminalObserved?.() ?? true,\n finalText,\n context,\n failed: state.runFailed,\n usage: state.producer?.usage?.(),\n assistantMessageId: assistantRowId(),\n ...(state.runFailed ? { failureReason: failureReasonOf(state.lastFailureData) } : {}),\n ...(state.runFailed && failureCodeOf(state.lastFailureData) ? { failureCode: failureCodeOf(state.lastFailureData) } : {}),\n ...(state.producer?.model ? { model: state.producer.model } : {}),\n ...modelAttributionFields(attribution),\n ...(failoverInfo ? { modelFailover: failoverInfo } : {}),\n }))\n },\n }\n : {}),\n ...(options.traceFlush ? { traceFlush: () => options.traceFlush!(context) } : {}),\n },\n })\n return { result }\n}\n\nfunction startTurnDrain<TContext>(\n result: ReturnType<typeof handleChatTurn>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n turnStreamId: `${string}-${string}-${string}-${string}-${string}`,\n state: AdmittedTurnState<TContext>,\n endTrace: (failed: boolean, terminalError: unknown) => TurnTraceSnapshot,\n exportTrace: () => Promise<void>,\n trace: AdmittedTurn<TContext>['trace'],\n ctx: ChatTurnRequestContext | undefined,\n request: Request,\n fireTerminalLifecycle: (failed: boolean, terminalError: unknown) => Promise<void>,\n releaseLock: () => Promise<void>,\n runAfterSettle: () => Promise<void>,\n settleResource: () => Promise<void>,\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 = state.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 (state.completionHandoff) {\n // The external owner settles transcript, lifecycle, lock and replay\n // status. Flush only the post-handoff live projection; EOF is an\n // observation stop, never a terminal verdict for that owner. The\n // trace is this request's own record, so it ends here.\n endTrace(failed, drainError)\n await Promise.all([state.tap!.detach(), state.nativeTiming?.flush(), exportTrace()])\n return\n }\n const finalize = trace.start('persist.finalize', 'persist')\n if (state.cancellationAbort?.signal.aborted || (ctx?.cancelOnDisconnect && request.signal.aborted)) {\n await state.draft?.discard()\n } else {\n await state.draft?.close()\n }\n try {\n await state.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 finalize.end()\n await fireTerminalLifecycle(failed, drainError)\n await releaseLock()\n // Both run after the lock is released and inside this waitUntil-tracked drain, so neither holds the next send.\n await Promise.all([exportTrace(), runAfterSettle()])\n })().finally(settleResource)\n if (ctx?.waitUntil) ctx.waitUntil(drained)\n else void drained.catch(() => { })\n return { clientBody }\n}\n\n\nfunction createTurnReplayResponse(\n contentType: string,\n clientBody: ReadableStream<Uint8Array>,\n turnMarker: { type: string; turnId: string },\n trace: Parameters<typeof admissionServerTiming>[0],\n): Response {\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': contentType,\n 'Cache-Control': 'no-cache',\n 'X-Turn-Id': turnMarker.turnId,\n 'Server-Timing': admissionServerTiming(trace),\n },\n })\n}\n","/** Serializable route observations transferred to the existing native admission owner. */\nimport type { NativeTurnTimingFacts } from '../turn-trace/turn-facts'\nexport type { NativeTurnTimingFacts } from '../turn-trace/turn-facts'\n\nexport interface NativeCompletionHandoffOptions {\n /** Persist on the existing admission, keyed by turnStreamId. Initial origin must survive before handoff. */\n persistTimingFacts?(facts: NativeTurnTimingFacts): Promise<void>\n}\n\nexport interface NativeTimingTransfer {\n snapshot(): NativeTurnTimingFacts\n register(options?: NativeCompletionHandoffOptions): Promise<void>\n note(): Promise<void>\n flush(): Promise<void>\n}\n\n/** Initial registration is fail-closed. Later observations are serialized and waitUntil-tracked by the route. */\nexport function createNativeTimingTransfer(\n read: () => NativeTurnTimingFacts,\n onError: (error: unknown) => void,\n): NativeTimingTransfer {\n let persist: NativeCompletionHandoffOptions['persistTimingFacts']\n let pending = Promise.resolve()\n return {\n snapshot: () => ({ ...read() }),\n async register(options) {\n if (!options?.persistTimingFacts) return\n await options.persistTimingFacts({ ...read() })\n persist = options.persistTimingFacts\n },\n note() {\n if (!persist) return pending\n const snapshot = { ...read() }\n const write = persist\n pending = pending.then(() => write(snapshot)).catch(onError)\n return pending\n },\n flush: () => pending,\n }\n}\n","import type { AssistantDraftWriter } from './draft-persistence'\nimport type { NativeCompletionHandoffOptions, NativeTimingTransfer } from './native-turn-timing'\nimport type { BufferedTurnTap } from '../stream/index'\nimport type { ChatTurnLock, ChatTurnRouteProducer } from './turn-route-contracts'\n\ninterface OwnershipState {\n producer?: ChatTurnRouteProducer\n completionHandoff: boolean\n completionHandoffPromise: Promise<void> | undefined\n nativeTiming: NativeTimingTransfer | undefined\n tap: BufferedTurnTap | undefined\n draft: AssistantDraftWriter | undefined\n lockAcquired: boolean\n lockReleased: boolean\n lockHandle: unknown\n closeCancellation?: () => Promise<void>\n}\n\n/** One transfer of terminal authority, retaining the route only as a live projector. */\nexport function createChatTurnOwnership(state: OwnershipState,\n log: (message: string, meta?: Record<string, unknown>) => void, turnStreamId: string,\n options: { turnLock?: Pick<ChatTurnLock<unknown>, 'release' | 'park'> },\n) {\n // A cleanup step that fails is logged and never stops the steps after it.\n const attempt = async (step: string, run: () => unknown): Promise<void> => {\n try { await run() } catch (err) { log(`[chat-routes] ${step} failed`, { turnId: turnStreamId, error: err instanceof Error ? err.message : String(err) }) }\n }\n const handoffCompletion = (handoff?: NativeCompletionHandoffOptions): Promise<void> => {\n if (!state.completionHandoffPromise) {\n state.completionHandoffPromise = (async () => {\n // Product registration already owns this turn. A callback failure must never\n // restore the route's terminal authority or permit a second settlement.\n state.completionHandoff = true\n let registrationFailed = false\n try {\n await state.nativeTiming?.register(handoff)\n } catch (error) {\n registrationFailed = true\n throw error\n } finally {\n await attempt('turn buffer detach', () => state.tap?.detach())\n try {\n await state.draft?.close()\n } catch (err) {\n if (!registrationFailed) throw err\n log('[chat-routes] draft close failed after native timing refusal', { turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err) })\n } finally {\n await state.closeCancellation?.()\n }\n }\n })()\n }\n return state.completionHandoffPromise\n }\n const releaseLock = async (): Promise<void> => {\n if (state.completionHandoff || !state.lockAcquired || state.lockReleased) return\n // Losing the live observation is not evidence that a detached backend stopped.\n // The exact execution stays fenced; a parked intent lets its durable owner release it once proven.\n if (state.producer?.terminalObserved && !state.producer.terminalObserved()) {\n await attempt('turnLock.park', () => options.turnLock?.park?.(state.lockHandle))\n await state.closeCancellation?.()\n return\n }\n state.lockReleased = true\n // Expected cooperative completion must not interpret its own release as\n // external loss of execution authority. A close failure must not skip release.\n await attempt('turn cancellation close', () => state.closeCancellation?.())\n await attempt('turnLock.release', () => options.turnLock!.release(state.lockHandle))\n }\n return { handoffCompletion, releaseLock }\n}\n","/** Bind backend configuration to this route's identity, trace and admission. */\nimport { createHybridTurnProducer, routerTurnHistory, turnPromptText } from './hybrid-producer'\nimport { createRouterTurnProducer } from './router-producer'\nimport { createSandboxChatProducer } from './sandbox-producer'\nimport type { ChatTurnProduceArgs, ChatTurnRouteProducer, ChatTurnRouterBackend, ChatTurnSandboxBackend } from './turn-route-contracts'\n\nfunction isProducer(value: ChatTurnRouterBackend | ChatTurnSandboxBackend): value is ChatTurnRouteProducer {\n return 'stream' in value && typeof value.stream === 'object' && value.stream !== null && Symbol.asyncIterator in value.stream\n}\n\nexport function routerRouteProducer<TContext, TResource>(value: ChatTurnRouterBackend, args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnRouteProducer {\n if (isProducer(value)) return value\n const options = {\n ...value,\n userMessage: value.userMessage ?? turnPromptText(args.prompt),\n history: value.history ?? routerTurnHistory(args.priorMessages, undefined, { pov: args.agent?.id }),\n trace: args.trace,\n traceId: args.trace?.traceId,\n signal: args.admissionSignal,\n // Domain fences may wait for a certified profile or per-turn resource.\n // They can only add a requirement; they never replace route admission.\n admitted: Promise.all([args.admitted, value.admitted]),\n }\n if (!('box' in value)) return createRouterTurnProducer(options)\n // A repeated call of the same turn's tool call is the same computer step, whatever the trace.\n const computer = value.box.computer && { parentExecutionId: args.executionId, ...value.box.computer }\n return createHybridTurnProducer({ ...options, box: { ...value.box, ...(computer ? { computer } : {}) } })\n}\n\nexport function sandboxRouteProducer<TContext, TResource>(value: ChatTurnSandboxBackend, args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnRouteProducer {\n if (isProducer(value)) return value\n const openEvents = value.openEvents\n return createSandboxChatProducer({ ...value, ...(openEvents && args.admissionSignal ? {\n openEvents: input => openEvents({ ...input, signal: AbortSignal.any([input.signal, args.admissionSignal!]) }),\n } : {}) })\n}\n","import type { ChatTurnRouteProducer } from './turn-route-contracts'\n\n/** Replace transport while keeping every capability on its original receiver.\n * Object.create alone breaks class private state; spreading snapshots getters.\n * The separate target also permits wrapping an Object.freeze'd producer. */\nexport function withProducerStream(\n producer: ChatTurnRouteProducer,\n stream: ChatTurnRouteProducer['stream'],\n): ChatTurnRouteProducer {\n return new Proxy(Object.create(producer) as ChatTurnRouteProducer, {\n get(_target, property) {\n if (property === 'stream') return stream\n const value: unknown = Reflect.get(producer, property, producer)\n return typeof value === 'function' ? value.bind(producer) : value\n },\n })\n}\n","/** Router calls overlap the lock, history recheck, user insert and gates.\n * authorize already verified identity/access; the model service enforces spend.\n * Events remain buffered until admission commits. Refusal cancels the call and\n * drops its output; tools and durable effects must wait for args.admitted.\n * Ordinary functions and Sandbox backends never execute speculatively.\n */\nimport type { TurnTrace } from '../turn-trace/recorder'\nimport type { NativeCompletionHandoffOptions } from './native-turn-timing'\nimport type { ChatRouteEvent, ChatTurnProduceArgs, ChatTurnRouteProducer } from './turn-route-contracts'\nimport { routerRouteProducer, sandboxRouteProducer } from './route-producer'\nimport { withProducerStream } from './producer-stream'\nimport type { ResolvedChatTurnRoutesOptions } from './route-storage'\n\n/** Thrown into `args.admitted` when the turn was refused after its producer started. */\nclass TurnAdmissionRefusedError extends Error {\n constructor() {\n super('The turn was refused after its producer started; its output was discarded.')\n this.name = 'TurnAdmissionRefusedError'\n }\n}\n\nexport interface DispatchedProducer<TContext, TResource = unknown> {\n /** The admission chain committed: hand the producer its final args and return it, with what it already emitted first. */\n take(args: ChatTurnProduceArgs<TContext, TResource>): Promise<ChatTurnRouteProducer>\n /** The turn ended without the producer: abort it and discard its output. Idempotent; a no-op after `take`. */\n refuse(): void\n}\n\n/**\n * Start `produce` now with the args known before the lock. `args.admitted`\n * resolves to the final args at `take`, or rejects at `refuse`; the producer\n * writes nothing durable before it resolves. Its stream is drained into memory\n * from the start, so a producer that only works while pulled still dispatches.\n */\nfunction dispatchProducerFirst<TContext, TResource = unknown>(\n produce: (args: ChatTurnProduceArgs<TContext, TResource>) => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>,\n args: ChatTurnProduceArgs<TContext, TResource>,\n trace: TurnTrace,\n): DispatchedProducer<TContext, TResource> {\n const abort = new AbortController()\n let admit!: (final: ChatTurnProduceArgs<TContext, TResource>) => void\n let reject!: (error: Error) => void\n const admitted = new Promise<ChatTurnProduceArgs<TContext, TResource>>((resolve, fail) => { admit = resolve; reject = fail })\n // A producer that never awaits `admitted` must not raise an unhandled rejection when the turn is refused.\n admitted.catch(() => {})\n let settled: 'taken' | 'refused' | undefined\n // Set when nobody will read the producer again: a refusal, or the route's reader closing after `take`.\n let stopped = false\n\n const queue: ChatRouteEvent[] = []\n let ended = false\n let failure: { error: unknown } | undefined\n let wake: (() => void) | undefined\n const notify = () => { const resume = wake; wake = undefined; resume?.() }\n let source: AsyncIterator<ChatRouteEvent> | undefined\n\n // A registered durable owner settles the transcript and the lock, so a producer may hand off only a committed turn.\n const handoffCompletion = args.handoffCompletion\n const started = trace.measure('admission.produce', 'admission', () => produce({\n ...args,\n admitted,\n admissionSignal: args.admissionSignal ? AbortSignal.any([args.admissionSignal, abort.signal]) : abort.signal,\n ...(handoffCompletion ? { handoffCompletion: (options?: NativeCompletionHandoffOptions) => admitted.then(() => handoffCompletion(options)) } : {}),\n }))\n // Register before construction resolves: admission can refuse and return\n // while a producer is still awaiting an ephemeral credential or resource.\n const cleanup = started.then(producer => producer.cleanup, () => undefined)\n args.waitUntil?.(cleanup)\n void cleanup.catch(() => {})\n const draining = started.then(async (producer) => {\n try {\n source = producer.stream[Symbol.asyncIterator]()\n for (;;) {\n const next = await source.next()\n if (next.done || stopped) break\n queue.push(next.value)\n notify()\n }\n } catch (error) {\n if (!stopped) failure = { error }\n } finally {\n ended = true\n notify()\n }\n }, (error: unknown) => {\n failure = { error }\n ended = true\n notify()\n })\n\n /** Nobody reads this producer again: abort its model call, close its stream and drop what it queued. */\n const stop = (reason: Error) => {\n if (stopped) return\n stopped = true\n abort.abort(reason)\n queue.length = 0\n notify()\n // A producer that ignores the signal is closed too; one suspended at an await finishes that await first.\n void started.then(() => source?.return?.(), () => {}).catch(() => {})\n }\n\n async function* replay(): AsyncGenerator<ChatRouteEvent, void, unknown> {\n try {\n for (;;) {\n while (queue.length) yield queue.shift()!\n if (ended) break\n await new Promise<void>((resolve) => { wake = resolve })\n }\n await draining\n if (failure) throw failure.error\n } finally {\n // The route stopped reading early (a disconnect under `cancelOnDisconnect`, an engine stop): stop the producer\n // as closing its own stream would have.\n if (!ended) stop(new Error('The turn stopped reading its producer.'))\n }\n }\n\n return {\n async take(final) {\n if (settled) throw new Error(`dispatch-first producer already ${settled}`)\n settled = 'taken'\n admit(final)\n const producer = await started\n return withProducerStream(producer, replay())\n },\n refuse() {\n if (settled) return\n settled = 'refused'\n reject(new TurnAdmissionRefusedError())\n stop(new TurnAdmissionRefusedError())\n },\n }\n}\n\n/** Select once, so admission's context mutations cannot switch execution backends. */\nexport function selectTurnProducer<TContext, TResource = unknown>(\n produce: ResolvedChatTurnRoutesOptions<TContext, TResource>['produce'],\n args: ChatTurnProduceArgs<TContext, TResource>,\n) {\n if (typeof produce === 'function') return { produce, router: false }\n if (produce.when?.(args) ?? true) return {\n produce: async (final: ChatTurnProduceArgs<TContext, TResource>) => routerRouteProducer(await produce.router(final), final),\n router: true,\n }\n if (!produce.sandbox) throw new Error('The turn selected the Sandbox backend without a Sandbox producer')\n const sandbox = produce.sandbox\n return { produce: async (final: ChatTurnProduceArgs<TContext, TResource>) => sandboxRouteProducer(await sandbox(final), final), router: false }\n}\n\n/** A reused user row must pass duplicate/refusal checks before another model call. */\nexport function dispatchFirstFor<TContext, TResource = unknown>(\n selected: ReturnType<typeof selectTurnProducer<TContext, TResource>>,\n args: ChatTurnProduceArgs<TContext, TResource>,\n trace: TurnTrace,\n): DispatchedProducer<TContext, TResource> | undefined {\n return selected.router && !args.userMessageId ? dispatchProducerFirst(selected.produce, args, trace) : undefined\n}\n","/** Stream framing, event inspection and cancellation around a chat producer. */\nimport type { ChatRouteEvent } from './turn-route-contracts'\n\n/** Best-effort human-readable cause from a terminal `error` /\n * `session.run.failed` event's `data`. */\nexport function 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/** The typed reason a terminal `error` / `session.run.failed` event's `data`\n * names, e.g. `sandbox.stream_failed` or an upstream code. */\nexport function failureCodeOf(data: Record<string, unknown> | undefined): string | undefined {\n const code = data?.code\n return typeof code === 'string' && code.length > 0 ? code : undefined\n}\n\n/** A word the user sees: a producer `text` event, or a sandbox text part delta. */\nexport function isVisibleText(event: ChatRouteEvent): boolean {\n const value = event as ChatRouteEvent & { text?: unknown }\n if (event.type === 'text') return typeof value.text === 'string' ? value.text.trim().length > 0 : true\n if (event.type !== 'message.part.updated') return false\n const part = event.data?.part as { type?: unknown } | undefined\n const delta = event.data?.delta\n return part?.type === 'text' && typeof delta === 'string' && delta.trim().length > 0\n}\n\n/** Output rendered by either lane; admission/status/usage events are not model output. */\nexport function isVisibleOutput(event: ChatRouteEvent): boolean {\n if (isVisibleText(event)) return true\n const value = event as ChatRouteEvent & { text?: unknown }\n if (event.type === 'reasoning') return typeof value.text === 'string' && value.text.trim().length > 0\n if (event.type === 'tool_call' || event.type === 'tool.call' || event.type === 'tool_result' || event.type === 'tool.result' || event.type === 'tool.event') return true\n if (event.type !== 'message.part.updated') return false\n const part = event.data?.part as { type?: unknown; text?: unknown } | undefined\n if (part?.type === 'tool') return true\n if (part?.type !== 'reasoning' && part?.type !== 'text') return false\n const text = event.data?.delta ?? part.text\n return typeof text === 'string' && text.trim().length > 0\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. */\nexport async 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. */\nexport async 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/** Sequential concat of byte streams (marker line, then the engine body). */\nexport function 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 */\nexport async 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","/** Request-owned speculative work: legacy release callbacks and opaque resource lifetimes. */\nimport type { ChatTurnAfterAuthorizeRelease } from './turn-route-contracts'\nimport { redactErrorMessage } from '../redact/index'\n\nexport interface AfterAuthorizeWork<TResource = unknown> {\n resource?: Promise<TResource>\n handOff(): void\n release(): Promise<void>\n settle(): Promise<void>\n add(release: () => void): void\n}\n\nexport function earlyTurnWork<TResource>(\n started: ChatTurnAfterAuthorizeRelease<TResource> | undefined,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AfterAuthorizeWork<TResource> {\n let free = typeof started === 'function' ? started : undefined\n const owned = typeof started === 'object' ? started : undefined\n void owned?.resource.catch(() => {})\n let handedOff = false\n let stopped: Promise<void> | undefined\n let also: Array<() => void> = []\n const report = (error: unknown) => log('[chat-routes] afterAuthorize release failed', { error: redactErrorMessage(error) })\n const settle = (): Promise<void> => stopped ??= (async () => {\n if (owned) await owned.dispose(await owned.resource)\n })().catch(report)\n return {\n resource: owned?.resource,\n handOff: () => { handedOff = true; free = undefined; also = [] },\n add: release => { also.push(release) },\n settle,\n release: async () => {\n const product = free\n const route = also\n free = undefined\n also = []\n for (const stop of route) stop()\n if (product) await Promise.resolve().then(product).catch(report)\n if (!handedOff) await settle()\n },\n }\n}\n","/** The template's backend assembly. Products supply policy; routes own lane selection. */\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { Harness } from '../harness/index'\nimport { createD1PrewarmClaimStore } from '../sandbox/prewarm-claim-d1'\nimport { runForegroundSandboxSingleFlight } from '../sandbox/foreground-single-flight'\nimport { ensureWorkspaceSandbox, peekWorkspaceSandbox, streamSandboxPrompt } from '../sandbox/index'\nimport type { SandboxRuntimeConfig } from '../sandbox/configuration'\nimport { sandboxPromptExecutionOptions, type StreamSandboxPromptOptions } from '../sandbox/prompt-options'\nimport type { ChatTurnStoreBindings } from './route-storage'\nimport { turnCarriesFiles } from './hybrid-producer'\nimport { normalizeChatPromptForSandbox } from './dispatch-parts'\nimport { assertPolicy, type ModelPolicy } from '../policy-filters/index'\nimport type { ChatTurnProduceArgs, ChatTurnHybridConfiguration } from './turn-route-contracts'\nimport type { RouterTurnTool } from '../runtime/router-turn'\nimport type { RouterTurnKey } from './router-producer'\nimport type { ComputerVault } from '../sandbox/computer-files'\nimport type { Outcome } from '../sandbox/outcome'\n\n/** Worker bindings are explicit; no ambient deployment credentials replace product policy. */\nexport interface ChatTurnEnvironment {\n DB?: ChatTurnStoreBindings['db']\n TURN_STREAM?: ChatTurnStoreBindings['lock']['namespace']\n TURN_STREAM_DO?: ChatTurnStoreBindings['lock']['namespace']\n TURN_STREAM_AUTH_SECRET?: string\n D1_REGION?: ChatTurnStoreBindings['region']\n TANGLE_API_KEY?: string\n TANGLE_ROUTER_URL?: string\n MODEL_NAME?: string\n SANDBOX_API_KEY?: string\n SANDBOX_GATEWAY_URL?: string\n}\n\n/** Domain data for the default lane, instead of constructing producers or admission hooks. */\nexport interface ChatTurnDefaultBackend<TContext = unknown, TResource = unknown> {\n model?: string\n systemPrompt?: string\n harness?: Harness\n effort?: StreamSandboxPromptOptions['effort']\n interactions?: StreamSandboxPromptOptions['interactions']\n /** Existing product provisioning, credentials, profiles and egress policy remain authoritative. */\n shell?: SandboxRuntimeConfig\n /** Explicitly keep every turn on the sandbox lane. */\n router?: false\n /** Who pays for the Router model call: the turn's key, or a per-turn lease (`createDelegatedTurnKeys`) the\n * producer revokes when the turn settles. Default `TANGLE_API_KEY`. Started before the turn lock, like the call. */\n funding?(args: ChatTurnProduceArgs<TContext, TResource>): RouterTurnKey | Promise<RouterTurnKey>\n /** The product's in-process tools for the Router model; `sandbox_run` is added after them. */\n tools?(args: ChatTurnProduceArgs<TContext, TResource>): RouterTurnTool[] | Promise<RouterTurnTool[]>\n /** What the computer step does beyond running the task: copy its files into the product's Vault, and run a model\n * the box key allows (`readSandboxRouterModels` with the payer's key). */\n computer?: {\n files?(args: ChatTurnProduceArgs<TContext, TResource>): ComputerVault | undefined\n allowedModels?(args: ChatTurnProduceArgs<TContext, TResource>, signal: AbortSignal): Promise<Outcome<readonly string[] | null>>\n }\n}\n\nexport function defaultChatShell(projectId: string, env: ChatTurnEnvironment, config: ChatTurnDefaultBackend): SandboxRuntimeConfig {\n return config.shell ?? {\n credentials: () => env.SANDBOX_API_KEY?.trim() && env.SANDBOX_GATEWAY_URL?.trim()\n ? { apiKey: env.SANDBOX_API_KEY.trim(), baseUrl: env.SANDBOX_GATEWAY_URL.trim() } : null,\n name: workspaceId => `${projectId}-${workspaceId}`.slice(0, 63),\n metadata: harness => ({ app: projectId, harness }),\n connectedIntegrationIds: async () => [], env: async () => ({}), files: async () => [], secrets: async () => [],\n profile: ({ systemPrompt, extraMcp }) => ({ name: projectId,\n prompt: { systemPrompt: systemPrompt ?? config.systemPrompt ?? '' },\n ...(extraMcp && Object.keys(extraMcp).length ? { mcp: extraMcp } : {}),\n }),\n provider: { apiKey: env.TANGLE_API_KEY, routerBaseUrl: env.TANGLE_ROUTER_URL,\n modelName: env.MODEL_NAME, defaultModel: config.model },\n }\n}\n\nexport function createDefaultChatBackend<TContext, TResource>(projectId: string, env: ChatTurnEnvironment, config: ChatTurnDefaultBackend<TContext, TResource>, bindings?: ChatTurnStoreBindings, modelPolicy?: ModelPolicy) {\n const shell = defaultChatShell(projectId, env, config)\n const harness = config.harness ?? 'opencode'\n const acquire = (args: ChatTurnProduceArgs<TContext, TResource>): Promise<SandboxInstance> => {\n const scope = { workspaceId: args.identity.tenantId, userId: args.identity.userId }\n if (!bindings) throw new Error('Default sandbox execution requires durable D1 claim bindings')\n return runForegroundSandboxSingleFlight({ claim: createD1PrewarmClaimStore(bindings.db), workspaceId: scope.workspaceId,\n trace: args.trace, harness, provision: () => ensureWorkspaceSandbox(shell, { ...scope, harness, trace: args.trace }),\n peek: () => peekWorkspaceSandbox(shell, scope), adopt: ({ box }) => box })\n }\n const modelFor = (args: ChatTurnProduceArgs<TContext, TResource>) => {\n const model = args.body.model ?? env.MODEL_NAME ?? config.model\n if (!model?.trim()) throw new Error('Default chat requires MODEL_NAME or produce.model')\n return model\n }\n const runOptions = (args: ChatTurnProduceArgs<TContext, TResource>) => ({\n model: modelFor(args), harness, detach: true as const,\n systemPrompt: config.systemPrompt, interactions: config.interactions,\n ...sandboxPromptExecutionOptions(args.executionLimits, args.body.effort ?? config.effort),\n })\n const promptOptions = (args: ChatTurnProduceArgs<TContext, TResource>): StreamSandboxPromptOptions => ({\n ...runOptions(args), sessionId: args.identity.sessionId, executionId: args.executionId,\n turnId: args.executionId, trace: args.trace, signal: args.admissionSignal,\n })\n return {\n when: (args: ChatTurnProduceArgs<TContext, TResource>) => config.router !== false\n && (Boolean(config.funding) || Boolean(env.TANGLE_API_KEY?.trim())) && !turnCarriesFiles(args.prompt)\n // The Router can cap total output but not a separate reasoning subset.\n && !(args.executionLimits?.maxReasoningTokens),\n async router(args: ChatTurnProduceArgs<TContext, TResource>): Promise<ChatTurnHybridConfiguration> {\n const model = modelFor(args)\n if (modelPolicy) await assertPolicy({ kind: 'model', id: model, ...modelPolicy })\n const base = env.TANGLE_ROUTER_URL?.trim().replace(/\\/+$/, '')\n const funding = config.funding\n const tools = config.tools ? await config.tools(args) : undefined\n const files = config.computer?.files?.(args)\n const allowedModels = config.computer?.allowedModels\n return { apiKey: funding ? Promise.resolve().then(() => funding(args)) : env.TANGLE_API_KEY!.trim(), model,\n ...(tools?.length ? { tools } : {}),\n reasoningEffort: args.executionLimits?.maxReasoningTokens === 0 ? 'none' : args.body.effort ?? config.effort,\n ...(args.executionLimits?.maxOutputTokens !== undefined ? {\n maxTokens: args.executionLimits.maxOutputTokens, maxCompletionTokens: args.executionLimits.maxOutputTokens,\n } : {}),\n ...(base ? { baseUrl: base.endsWith('/v1') ? base : `${base}/v1` } : {}),\n systemPrompt: { profile: shell.profile({ systemPrompt: config.systemPrompt, harness }) },\n box: { acquire: () => acquire(args), computer: {\n shell, prompt: runOptions(args), parentExecutionId: args.executionId,\n session: { id: `sandbox-run-${args.identity.sessionId}` },\n ...(allowedModels ? { models: { preferred: [model], allowed: (signal: AbortSignal) => allowedModels(args, signal) } } : {}),\n ...(files ? { files } : {}),\n } },\n }\n },\n sandbox: async (args: ChatTurnProduceArgs<TContext, TResource>) => {\n const model = modelFor(args)\n if (modelPolicy) await assertPolicy({ kind: 'model', id: model, ...modelPolicy })\n // Resolve the box before the producer, but dispatch only when the route pulls\n // openEvents: producer construction failure can never leave native work running.\n const box = await acquire(args)\n return { model, modelPolicy, modelFailover: false as const, errorNotice: true,\n openEvents: ({ model, signal }: { model: string; signal: AbortSignal }) => streamSandboxPrompt(shell, box,\n normalizeChatPromptForSandbox(args.prompt), { ...promptOptions(args), model, signal }),\n }\n },\n }\n}\n","/** Prewarm inherits the existing thread-read authority; it never infers spend authority. */\nimport { createWorkspacePrewarmRoute } from '../sandbox/prewarm-route'\nimport { turnStorageBindings } from './route-storage'\nimport type { CreateChatTurnRoutesOptions } from './turn-route-contracts'\n\nexport function createChatPrewarm<TContext, TResource>(options: CreateChatTurnRoutesOptions<TContext, TResource>) {\n if (options.prewarm === false) return async () => new Response(null, { status: 405 })\n const bindings = options.turnLock === false ? undefined : turnStorageBindings(options)\n const route = createWorkspacePrewarmRoute({\n turnStore: bindings,\n authorize: async ({ request, threadId }) => {\n const auth = await options.authorize({ request, intent: 'running', threadId })\n if (!auth.ok) return { status: 'denied', response: auth.response }\n if (auth.intent !== undefined && auth.intent !== 'running') return { status: 'denied',\n response: Response.json({ error: 'Authorization did not allow this read.', code: 'chat_authorization_intent_mismatch' }, { status: 403 }) }\n if (!bindings) return { status: 'declined', reason: 'lock_not_configured' }\n return { status: 'allowed', workspaceId: auth.tenantId, steps: [] }\n },\n })\n return (request: Request) => route(request, undefined)\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 → function after admission, or declared Router\n * and Sandbox backends. Router model calls overlap\n * admission by default; tools wait for commit.\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), `afterAuthorize` (start the box, keys\n * and session the turn will need the moment the caller is admitted, so they\n * overlap the lock and the user-row insert), `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 * `prepareTurn` (post-admission context work, run inside a progress-first\n * stream) is provisional: one consumer so far.\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 { withD1QueryCount, currentD1QueryCounter } from '../launch-invariants/d1-query-count'\nimport { createInteractionAnswerRoute } from '../interactions/route'\nimport { replayTurnEvents, stampReplaySeq } from '../stream/index'\nimport { parseJsonObjectBody } from '../web/index'\nimport { createTurnTrace, type TurnTrace, type TurnTraceSink } from '../turn-trace/recorder'\nimport { createIntelligenceTurnTraceSink } from '../turn-trace/otel'\nimport { storeSupportsDraftPersistence, type AssistantDraftStore, type DraftPersistenceTuning } from './draft-persistence'\nimport { startTurnPrefetch } from './turn-prefetch'\nimport { errorResponse, namedModelRefusal, validateTurnBody, type AdmittedTurn, type ParsedTurnBody, type TurnProgressCallback } from './turn-admission'\nimport { createAdmittedTurnRunner } from './turn-execution'\nimport { earlyTurnWork, type AfterAuthorizeWork } from './early-turn-work'\nimport {\n INTENT_LINE_TIMEOUT_MS,\n INTENT_LINE_HISTORY_MESSAGES,\n INTENT_LINE_MAX_CHARS,\n type ChatRouteEvent,\n type ChatTurnAfterAuthorizeRelease,\n type ChatTurnRequestContext,\n type ChatTurnRoutes,\n type CreateChatTurnRoutesOptions,\n} from './turn-route-contracts'\nimport {\n buildTurnPhaseEvent,\n TURN_INTENT_EVENT,\n TURN_PROGRESS_FIRST,\n TURN_PROGRESS_HEADER,\n TURN_ROUTE_PHASE_MESSAGES,\n turnResponseEventFor,\n type TurnIntentEvent,\n type TurnRoutePhase,\n} from './turn-progress'\nimport { ChatTurnInputError } from './wire'\nimport { resolveTurnStorage, turnStorageBindings, type ResolvedChatTurnRoutesOptions } from './route-storage'\nimport { createDefaultChatBackend, type ChatTurnDefaultBackend } from './default-backend'\nimport { createChatPrewarm } from './route-prewarm'\nimport { cancelChatTurn } from './cancellation'\n\nexport * from './turn-route-contracts'\n\n/** Parse and validate the body, then authorize the caller. */\nasync function admitTurn<TContext, TResource>(\n request: Request, trace: TurnTrace, options: CreateChatTurnRoutesOptions<TContext, TResource>,\n waitUntil: ChatTurnRequestContext['waitUntil'],\n): Promise<({ ok: true } & AdmittedTurn<TContext>) | { ok: false; response: Response }> {\n const parse = trace.start('admission.parse', 'admission')\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return { ok: false, response: badBody }\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return { ok: false, response: errorResponse(err) }\n throw err\n }\n parse.end()\n const prefetch = options.prefetch && startTurnPrefetch(options.prefetch, { request, body: parsed.payload, trace })\n let handedOff = false\n try {\n const auth = await trace.measure('admission.authorize', 'admission', (span) => options.authorize({ request, waitUntil, intent: 'turn', body: parsed.payload, trace, span, ...(prefetch ? { identified: prefetch.identified } : {}) }))\n if (!auth.ok) return { ok: false, response: auth.response }\n if (!('context' in auth) || (auth.intent !== undefined && auth.intent !== 'turn')) {\n return { ok: false, response: Response.json({ error: 'Authorization did not allow this turn.', code: 'chat_authorization_intent_mismatch' }, { status: 403 }) }\n }\n // Check the named model before side effects; the producer checks the unnamed model.\n const refusal = await namedModelRefusal(options.modelPolicy, parsed.payload, trace)\n if (refusal) return { ok: false, response: refusal }\n const admitted = { ok: true as const, parsed, auth, trace, ...(prefetch ? { prefetched: prefetch.admitted(auth) } : {}) }\n handedOff = true\n return admitted\n } finally {\n // Refusals and thrown admission errors both abandon the read-only work.\n if (!handedOff) prefetch?.discard()\n }\n}\n\n\n/** Build chat turn routes to handle and validate incoming chat requests with optional logging */\nexport function createChatTurnRoutes<TContext = void, TResource = unknown>(\n input: CreateChatTurnRoutesOptions<TContext, TResource>,\n): ChatTurnRoutes {\n const produce = input.produce\n const options: ResolvedChatTurnRoutesOptions<TContext, TResource> = {\n ...input, ...resolveTurnStorage(input),\n produce: typeof produce === 'function' || (produce && 'router' in produce && typeof produce.router === 'function')\n ? produce as ResolvedChatTurnRoutesOptions<TContext, TResource>['produce']\n : createDefaultChatBackend<TContext, TResource>(input.projectId, input.env ?? {}, produce as ChatTurnDefaultBackend<TContext, TResource> | undefined ?? {}, turnStorageBindings(input), input.modelPolicy),\n }\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n\n // A patch-capable store always keeps durable in-flight history on the shared cadence.\n const draftStore: AssistantDraftStore = options.store\n const draftTuning: DraftPersistenceTuning | null = storeSupportsDraftPersistence(draftStore) ? {} : null\n\n const progressMessages: Record<TurnRoutePhase, string> = { ...TURN_ROUTE_PHASE_MESSAGES, ...options.progressMessages }\n\n // Every turn's trace goes to Intelligence unless the product turns it off (`turnTrace: false`).\n const traceOptions = options.turnTrace === false ? undefined : options.turnTrace\n const traceSink: TurnTraceSink | undefined = options.turnTrace === false\n ? undefined\n : (traceOptions?.sink ?? createIntelligenceTurnTraceSink({ project: options.projectId }))\n\n /** Start the admitted turn's intent line; resolves to the line, or null. Never rejects. */\n function startIntentLine(admitted: AdmittedTurn<TContext>): Promise<string | null> | undefined {\n const intentLine = options.intentLine\n if (!intentLine) return undefined\n const { parsed, auth } = admitted\n const threadId = parsed.payload.threadId\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const deadline = new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n controller.abort()\n resolve(null)\n }, intentLine.timeoutMs ?? INTENT_LINE_TIMEOUT_MS)\n })\n const generated = (async () => {\n const history = (await options.store.listMessages(threadId))\n .slice(-INTENT_LINE_HISTORY_MESSAGES)\n .map((message) => ({ role: message.role, content: message.content }))\n const text = await intentLine.generate({\n content: parsed.content,\n history,\n tenantId: auth.tenantId,\n userId: auth.userId,\n threadId,\n context: auth.context,\n signal: controller.signal,\n })\n const line = typeof text === 'string' ? text.trim().replace(/\\s+/g, ' ') : ''\n return line ? line.slice(0, INTENT_LINE_MAX_CHARS) : null\n })().catch((err) => {\n if (!controller.signal.aborted) {\n log('[chat-routes] intent line failed; showing none', { error: err instanceof Error ? err.message : String(err) })\n }\n return null\n })\n return Promise.race([generated, deadline]).finally(() => clearTimeout(timer))\n }\n const runAdmittedTurn = createAdmittedTurnRunner({\n options, draftStore, draftTuning, progressMessages, traceOptions, traceSink, startIntentLine, log,\n })\n\n async function turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response> {\n // Parsing and authorization finish before any response opens, for both\n // shapes: a refusal is always a plain HTTP response that reveals nothing\n // beyond what it says, and nothing runs for a caller who is not admitted.\n // The turn's clock starts at the request, so admission is inside its trace.\n const requestContext = ctx?.waitUntil ? { ...ctx, waitUntil: ctx.waitUntil.bind(ctx) } : ctx\n const admitted = await admitTurn(request, createTurnTrace({ d1QueryCounter: currentD1QueryCounter() }), options, requestContext?.waitUntil)\n if (!admitted.ok) return admitted.response\n if (request.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST) return runTurn(request, requestContext, admitted)\n return progressFirstTurn(request, requestContext, admitted)\n }\n\n\n /**\n * Open the response stream as soon as the caller is admitted, so the client\n * shows the turn's real stage while the conversation loads, the lock is\n * taken and the product's pre-turn work runs. The turn runs exactly as\n * {@link runTurn} does; its stream is piped through, and any other response\n * it returns after admission (a held lock, a gate's answer, a handoff, a\n * failure) becomes one `turn.response` event that `settleTurnResponse` turns\n * back into that response on the client.\n */\n function progressFirstTurn(request: Request, ctx: ChatTurnRequestContext | undefined, admitted: AdmittedTurn<TContext>): Response {\n const receivedAt = Date.now()\n const encoder = new TextEncoder()\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n const writer = writable.getWriter()\n let clientGone = false\n const write = async (chunk: Uint8Array): Promise<void> => {\n if (clientGone) return\n try {\n await writer.write(chunk)\n } catch {\n clientGone = true\n }\n }\n const writeEvent = (event: ChatRouteEvent): Promise<void> => write(encoder.encode(`${JSON.stringify(event)}\\n`))\n const progress: TurnProgressCallback = (phase, message) => {\n void writeEvent(buildTurnPhaseEvent(phase, message, { sinceRequestMs: Date.now() - receivedAt }))\n }\n progress('accepted', progressMessages.accepted)\n\n // The intent line reaches the client between whole NDJSON lines: before the\n // turn's own stream, or at a line boundary of it (its chunks can split lines).\n const intent = startIntentLine(admitted)\n let piping = false\n let atLineStart = true\n let pendingIntent: TurnIntentEvent | null = null\n if (intent) {\n void intent.then((text) => {\n if (!text || clientGone) return\n const event: TurnIntentEvent = { type: TURN_INTENT_EVENT, data: { text, sinceRequestMs: Date.now() - receivedAt } }\n if (!piping || atLineStart) void writeEvent(event)\n else pendingIntent = event\n })\n }\n\n const pump = (async () => {\n let inner: Response\n try {\n inner = await runTurn(request, ctx, admitted, progress, intent)\n } catch (err) {\n log('[chat-routes] turn failed before it streamed', { error: err instanceof Error ? err.message : String(err) })\n inner = err instanceof Response ? err\n : Response.json({ error: 'The turn failed before it started. Try again.' }, { status: 500 })\n }\n if (!inner.body || !inner.headers.get('x-turn-id')) {\n await writeEvent(await turnResponseEventFor(inner))\n } else {\n const reader = inner.body.getReader()\n piping = true\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n atLineStart = value.length > 0 && value[value.length - 1] === 0x0a\n await write(value)\n if (atLineStart && pendingIntent) {\n const event = pendingIntent\n pendingIntent = null\n await writeEvent(event)\n }\n if (clientGone) {\n // The turn keeps running under its own drain; only this view stops.\n await reader.cancel().catch(() => {})\n break\n }\n }\n } catch (err) {\n log('[chat-routes] progress-first pipe failed', { error: err instanceof Error ? err.message : String(err) })\n }\n }\n if (!clientGone) await writer.close().catch(() => {})\n })()\n if (ctx?.waitUntil) ctx.waitUntil(pump)\n else void pump.catch(() => {})\n\n return new Response(readable, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n [TURN_PROGRESS_HEADER]: TURN_PROGRESS_FIRST,\n },\n })\n }\n\n /** Start the product's `afterAuthorize` work for an admitted turn. Never throws. */\n function startAfterAuthorize(request: Request, admitted: AdmittedTurn<TContext>, waitUntil: ChatTurnRequestContext['waitUntil']): AfterAuthorizeWork<TResource> {\n let release: ChatTurnAfterAuthorizeRelease<TResource> | undefined\n const { parsed, auth, trace } = admitted\n if (options.afterAuthorize) {\n try {\n const started = options.afterAuthorize({\n request,\n waitUntil,\n body: parsed.payload,\n tenantId: auth.tenantId,\n userId: auth.userId,\n threadId: parsed.payload.threadId,\n context: auth.context,\n trace,\n })\n if (started) release = started\n } catch (err) {\n log('[chat-routes] afterAuthorize failed; the turn goes on without it', { error: err instanceof Error ? err.message : String(err) })\n }\n }\n return earlyTurnWork(release, log)\n }\n\n /** Run an admitted turn with the product's `afterAuthorize` work started first and freed if no producer takes it. */\n async function runTurn(\n request: Request,\n ctx: ChatTurnRequestContext | undefined,\n admitted: AdmittedTurn<TContext>,\n progress?: TurnProgressCallback,\n startedIntent?: Promise<string | null>,\n ): Promise<Response> {\n const early = startAfterAuthorize(request, admitted, ctx?.waitUntil)\n try {\n return await runAdmittedTurn(request, ctx, admitted, early, progress, startedIntent)\n } finally {\n // A held lock, a changed history, a gate's answer, a handoff or a throw ends the turn without `produce`. The response\n // does not wait for the product to free what it started.\n const freed = early.release()\n if (ctx?.waitUntil) ctx.waitUntil(freed)\n else void freed\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 if (auth.intent !== undefined && auth.intent !== 'replay') {\n return Response.json({ error: 'Authorization did not allow this replay.', code: 'chat_authorization_intent_mismatch' }, { status: 403 })\n }\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 })\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 if (auth.intent !== undefined && auth.intent !== 'running') {\n return Response.json({ error: 'Authorization did not allow this running-turn read.', code: 'chat_authorization_intent_mismatch' }, { status: 403 })\n }\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 prewarm: createChatPrewarm(input),\n turn: (request, ctx) => withD1QueryCount(() => turn(request, ctx)),\n cancel: request => cancelChatTurn(request, { authorize: options.authorize, cancel: options.cancel, log }),\n replay,\n running,\n interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BO,IAAM,0BAA0B,MAAM;AAItC,IAAM,wBAAwB,IAAI,OAAO;AAEhD,IAAM,2BAA2B;AAEjC,SAAS,yBAAyB,OAA8B;AAC9D,QAAM,uBAAuB,MAAM,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAC5D,MAAI,CAAC,qBAAqB,WAAW,GAAG,KAAK,qBAAqB,WAAW,EAAG,QAAO;AACvF,QAAM,WAAW,qBAAqB,MAAM,CAAC,EAAE,MAAM,GAAG;AACxD,MAAI,SAAS,KAAK,CAAC,YAAY,QAAQ,WAAW,KAAK,YAAY,OAAO,YAAY,IAAI,EAAG,QAAO;AACpG,SAAO,IAAI,SAAS,KAAK,GAAG,CAAC;AAC/B;AA+CO,SAAS,uBAAuB,MAAsB;AAC3D,QAAM,OAAO,KAAK,MAAM,OAAO,EAAE,IAAI,KAAK;AAC1C,QAAM,OAAO,KAAK,QAAQ,qBAAqB,GA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AW,MAAM,KAAK,SAAS;AAC5E,WAAO;AAAA,MACL,MAAM;AAAA,MACN,MAAM,EAAE,eAAe,SAAS,EAAE,OAAO,IAAI,CAAC,EAAE;AAAA,IAClD;AAAA,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":["base64","inlinePart","cost","model","runAdmittedTurn"]}
|
|
1
|
+
{"version":3,"sources":["../src/chat-routes/upload.ts","../src/chat-routes/dispatch-parts.ts","../src/chat-routes/reasoning-clock.ts","../src/chat-routes/router-producer.ts","../src/chat-routes/hybrid-producer.ts","../src/chat-routes/model-failover-stream.ts","../src/chat-routes/sandbox-model-source.ts","../src/chat-routes/sandbox-producer.ts","../src/chat-routes/cancellation.ts","../src/chat-routes/turn-admission.ts","../src/chat-routes/agent-producers.ts","../src/chat-routes/turn-route-contracts.ts","../src/chat-routes/turn-prefetch.ts","../src/chat-routes/turn-execution.ts","../src/chat-routes/native-turn-timing.ts","../src/chat-routes/turn-ownership.ts","../src/chat-routes/route-producer.ts","../src/chat-routes/producer-stream.ts","../src/chat-routes/dispatch-first.ts","../src/chat-routes/turn-event-stream.ts","../src/chat-routes/early-turn-work.ts","../src/chat-routes/default-backend.ts","../src/chat-routes/route-prewarm.ts","../src/chat-routes/turn-routes.ts","../src/chat-routes/gateway-adapter.ts"],"sourcesContent":["/**\n * `createUploadRoute` — the multimodal middle. Accepts multipart file uploads\n * and returns `PromptInputPart`-shaped descriptors the client echoes back on\n * send (`ChatTurnRequestPayload.parts`):\n *\n * ≤ inlineMaxBytes (700 KiB default) → inline `data:` URI part — rides the\n * turn body directly, no sandbox round trip.\n * > inlineMaxBytes → written into the sandbox workspace (base64 through the\n * structural `write` seam — `box.fs` satisfies it) and referenced by\n * `path`. Mandatory two-step: the gateway caps request bodies at ~1 MiB,\n * so a large file can never ride the prompt POST.\n *\n * The sink is structural (no sandbox-SDK import); products pass `box.fs`.\n *\n * @remarks Sole consumer today is the `--chat` scaffold (`create-agent-app\n * --chat` → `template-chat/src/chat.ts`), the reference multimodal path — its\n * inline-`data:`-or-ephemeral-sandbox-workspace split stays the scaffold's\n * proven upload pattern, not a fleet primitive; keep that distinction in mind\n * before widening its surface. Fleet apps with a durable store of their own\n * (KV, or AES-GCM-encrypted R2) no longer need to hand-roll a vault upload\n * route: `createAttachmentUploadRoute` (`./attachment-upload`, agent-app#234)\n * is the shared hardened path for that persistence model — a content-sniffed\n * type gate, two-phase atomic batch writes, and per-kind/aggregate size caps,\n * all seamed through an injected `WriteAttachmentFn`. Point readers there\n * instead of widening this route to cover both models.\n */\n\nimport type { ChatTurnFilePartInput } from './wire'\n\n/** 700 KiB: base64 inflates ~4/3, so an inline part stays comfortably under\n * the ~1 MiB gateway body cap alongside the JSON envelope. */\nexport const UPLOAD_INLINE_MAX_BYTES = 700 * 1024\n\n/** 8 MiB default ceiling per file — one base64 `write` call handles it. Raise\n * it only with a sink that can take the bigger single write. */\nexport const UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024\n\nconst DEFAULT_UPLOAD_DIRECTORY = '/workspace/uploads'\n\nfunction normalizeUploadDirectory(value: string): string | null {\n const withoutTrailingSlash = value.trim().replace(/\\/+$/, '')\n if (!withoutTrailingSlash.startsWith('/') || withoutTrailingSlash.length === 0) return null\n const segments = withoutTrailingSlash.slice(1).split('/')\n if (segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')) return null\n return `/${segments.join('/')}`\n}\n\n/** Structural match of the sandbox SDK's `box.fs` write surface (v0.10.5+:\n * `encoding: 'base64'` is the worker-safe binary path). */\nexport interface SandboxUploadSink {\n write(path: string, content: string, options?: { encoding?: 'utf8' | 'base64' }): Promise<unknown>\n}\n\n/** Resolve upload authorization status and provide upload destination or error response */\nexport type UploadAuthorization =\n | {\n ok: true\n /** Where large files land. Absent/null: only inline uploads are\n * accepted and an over-inline-cap file is rejected with 413. */\n sink?: SandboxUploadSink | null\n /** Per-request override of the workspace directory large files go to. */\n uploadDir?: string\n }\n | { ok: false; response: Response }\n\n/** Define options to authorize uploads and configure file size limits and upload directory */\nexport interface CreateUploadRouteOptions {\n /** Authenticate the caller and resolve the sandbox file sink (usually\n * `ensureWorkspaceSandbox(...)` → `box.fs`). */\n authorize(args: { request: Request }): Promise<UploadAuthorization>\n /** Inline-vs-sandbox threshold. Default {@link UPLOAD_INLINE_MAX_BYTES}. */\n inlineMaxBytes?: number\n /** Hard per-file cap. Default {@link UPLOAD_MAX_FILE_BYTES}. */\n maxFileBytes?: number\n /** Absolute workspace directory for path-ref files.\n * Default `'/workspace/uploads'`. */\n uploadDir?: string\n}\n\n/** One uploaded file, ready for the composer chip and the turn body. */\nexport interface UploadedChatFile {\n id: string\n name: string\n size: number\n mediaType: string\n /** True when the part carries the bytes inline (`data:` URI). */\n inline: boolean\n /** Echo this back verbatim in `ChatTurnRequestPayload.parts`. */\n part: ChatTurnFilePartInput\n}\n\n/** Path-safe file name: basename only, conservative charset, length-capped. */\nexport function sanitizeUploadFilename(name: string): string {\n const base = name.split(/[\\\\/]/).pop() ?? 'file'\n const safe = base.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^\\.+/, '_')\n return (safe || 'file').slice(0, 120)\n}\n\nconst BASE64_CHUNK = 0x8000\n\n/** Convert a Uint8Array of bytes into a base64-encoded string */\nexport function bytesToBase64(bytes: Uint8Array): string {\n let binary = ''\n for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK))\n }\n return btoa(binary)\n}\n\nfunction uploadError(status: number, code: string, error: string): Response {\n return Response.json({ code, error }, { status })\n}\n\n/** Create an upload route handler that authorizes requests and processes file uploads with size limits */\nexport function createUploadRoute(options: CreateUploadRouteOptions): (request: Request) => Promise<Response> {\n const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES\n const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES\n\n return async function upload(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (!auth.ok) return auth.response\n const sink = auth.sink ?? null\n const configuredUploadDir = auth.uploadDir ?? options.uploadDir ?? DEFAULT_UPLOAD_DIRECTORY\n\n let form: FormData\n try {\n form = await request.formData()\n } catch {\n return uploadError(400, 'INVALID_UPLOAD', 'Expected a multipart/form-data body with file fields')\n }\n const files: File[] = []\n form.forEach((value) => {\n if (value instanceof File) files.push(value)\n })\n if (files.length === 0) {\n return uploadError(400, 'INVALID_UPLOAD', 'No files in the upload body')\n }\n\n const uploaded: UploadedChatFile[] = []\n for (const file of files) {\n const name = sanitizeUploadFilename(file.name)\n const mediaType = file.type || 'application/octet-stream'\n const partType: ChatTurnFilePartInput['type'] = mediaType.startsWith('image/') ? 'image' : 'file'\n\n if (file.size > maxFileBytes) {\n return uploadError(\n 413,\n 'FILE_TOO_LARGE',\n `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`,\n )\n }\n\n const id = crypto.randomUUID()\n if (file.size <= inlineMaxBytes) {\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: true,\n part: {\n type: partType,\n filename: name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n },\n })\n continue\n }\n\n if (!sink) {\n return uploadError(\n 413,\n 'SANDBOX_REQUIRED',\n `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`,\n )\n }\n const uploadDir = normalizeUploadDirectory(configuredUploadDir)\n if (!uploadDir) {\n return uploadError(\n 500,\n 'INVALID_UPLOAD_DIRECTORY',\n 'uploadDir must be an absolute path without empty, \".\" or \"..\" segments',\n )\n }\n const path = `${uploadDir}/${id}-${name}`\n const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()))\n await sink.write(path, base64, { encoding: 'base64' })\n uploaded.push({\n id,\n name,\n size: file.size,\n mediaType,\n inline: false,\n part: { type: partType, filename: name, mediaType, path },\n })\n }\n\n return Response.json({ files: uploaded })\n }\n}\n","/**\n * `buildDispatchParts` — assemble the `PromptInputPart[]` a turn carrying\n * attachments and/or `@`-mentions dispatches to the sandbox. `parts[0]` is\n * always the full prompt text (typed text plus the attachment + mention pointer\n * blocks); each attachment or mention becomes one media part. An attachment\n * (read from the product store via the injected reader) draws the inline byte\n * budget first; a mention (read from the LIVE box) takes what is left. A file\n * inlines as a `data:` URI when it fits the remaining budget, otherwise uses\n * the in-box file reference supported by the current sandbox prompt contract.\n * Every media part is deduped by its resolved absolute path. This module only\n * produces the parts array; the caller decides when a turn dispatches parts\n * instead of a plain string.\n *\n * Storage-parameterized port of gtm-agent's `dispatch-parts.ts`: the vault\n * default reader is dropped (`readAttachment` is REQUIRED — the product supplies\n * its store adapter), the `GTM_SANDBOX_VAULT_DIR` prefixing becomes the required\n * `resolveAttachmentPath` seam, the `GTM_MULTIMODAL_FORCE_PATH` env fallback\n * becomes an explicit `forcePath` flag, and every budget cap reads an overridable\n * `./wire` constant. Kept behavior-identical for gtm-agent#618 adoption (the\n * demotion math and emitted part shapes reproduce its dispatched prompt bytes).\n */\n\nimport { partitionBySpeaker } from '@tangle-network/agent-interface/speaker'\nimport { isWorkspaceFileExportable } from '../web/file-export'\nimport { flattenHistory, type PromptInputPart } from '../sandbox'\nimport {\n statSandboxFileSize,\n readSandboxBinaryBytes,\n type SandboxExecChannel,\n} from '../sandbox/binary-read'\nimport {\n ChatTurnInputError,\n mediaTypeForMentionPath,\n base64WireLen,\n DISPATCH_REQUEST_MAX_BYTES,\n DISPATCH_STRUCTURAL_RESERVE_BYTES,\n DISPATCH_MAX_PARTS,\n type ChatTurnPartInput,\n} from './wire'\nimport { historyContentWithAttachments, type ChatAttachmentPart, type ChatMentionPart } from '../chat-store/parts'\nimport { bytesToBase64 } from './upload'\nimport type { ReadAttachmentFn } from './attachment-store'\nimport { pathToFileURL } from 'node:url'\n\nexport type { PromptInputPart }\n\n/** Resolve the outcome of dispatching parts with success status and corresponding value or error message */\nexport type DispatchPartsOutcome =\n | { succeeded: true; value: PromptInputPart[] }\n | { succeeded: false; error: string }\n\n/** One mention file's size (always) and inline bytes (only when the caller\n * asked for them — a path-only mention never reads its bytes). */\ntype SandboxMentionReadOutcome =\n | { succeeded: true; value: { size: number; base64?: string } }\n | { succeeded: false; error: string }\n\n/** Resolve sandbox mention details by reading from a specified path with optional byte reading */\nexport type ReadSandboxMentionFn = (\n box: SandboxExecChannel,\n absolutePath: string,\n options: { readBytes: boolean },\n) => Promise<SandboxMentionReadOutcome>\n\nfunction byteLen(value: string): number {\n return new TextEncoder().encode(value).length\n}\n\n/**\n * Default mention reader: stats the in-box file (which also proves it still\n * exists — a since-deleted mention fails loud here), then reads its bytes only\n * when the caller wants to inline it. Both hops cross the sandbox exec channel\n * via the substrate's binary-read helpers.\n */\nasync function readSandboxMention(\n box: SandboxExecChannel,\n absolutePath: string,\n options: { readBytes: boolean },\n): Promise<SandboxMentionReadOutcome> {\n const stat = await statSandboxFileSize(box, absolutePath)\n if (!stat.succeeded) {\n return { succeeded: false, error: `mentioned sandbox file missing or unreadable: ${absolutePath} — ${stat.error}` }\n }\n if (!options.readBytes) return { succeeded: true, value: { size: stat.value } }\n\n const read = await readSandboxBinaryBytes(box, absolutePath, stat.value)\n if (!read.succeeded) {\n return { succeeded: false, error: `mentioned sandbox file read failed: ${absolutePath} — ${read.error}` }\n }\n return { succeeded: true, value: { size: stat.value, base64: bytesToBase64(read.value.bytes) } }\n}\n\n/** HARD INVARIANT: an image carries exactly one URL or absolute path, while a\n * file carries the URL required by the current sandbox prompt contract. */\nfunction violatesUrlPathXor(part: PromptInputPart): boolean {\n if (part.type === 'text') return false\n const hasUrl = typeof part.url === 'string' && (\n part.url.startsWith('data:')\n || part.url.startsWith('file://')\n )\n const hasPath = 'path' in part && typeof part.path === 'string' && part.path.startsWith('/')\n if (part.type === 'file') return !hasUrl || hasPath\n return hasUrl === hasPath\n}\n\nfunction sandboxFileUrl(absolutePath: string): string | undefined {\n if (!absolutePath.startsWith('/')) return undefined\n try {\n return pathToFileURL(absolutePath).href\n } catch {\n return undefined\n }\n}\n\n/**\n * Convert the browser-safe chat attachment contract into the current sandbox\n * prompt contract. Images carry exactly one URL or path; generic files carry a\n * filename and URL.\n */\nexport function normalizeChatPromptForSandbox(\n prompt: string | readonly ChatTurnPartInput[],\n): string | PromptInputPart[] {\n if (typeof prompt === 'string') return prompt\n return prompt.map((part): PromptInputPart => {\n if (part.type === 'text') return part\n if ('content' in part) {\n throw new ChatTurnInputError('Sandbox prompt parts do not accept inline content; provide a URL or path')\n }\n\n const url = typeof part.url === 'string' && part.url.length > 0 ? part.url : undefined\n const path = typeof part.path === 'string' && part.path.length > 0 ? part.path : undefined\n if (Boolean(url) === Boolean(path)) {\n throw new ChatTurnInputError(`Sandbox ${part.type} parts require exactly one URL or path`)\n }\n if (path && !path.startsWith('/')) {\n throw new ChatTurnInputError(`Sandbox ${part.type} paths must be absolute: ${path}`)\n }\n\n if (part.type === 'image') {\n return {\n type: 'image',\n ...(part.filename ? { filename: part.filename } : {}),\n ...(part.mediaType ? { mediaType: part.mediaType } : {}),\n ...(url ? { url } : { path: path! }),\n }\n }\n\n const filename = part.filename?.trim()\n if (!filename) {\n throw new ChatTurnInputError('Sandbox file parts require a filename')\n }\n const fileUrl = url ?? sandboxFileUrl(path!)\n if (!fileUrl) {\n throw new ChatTurnInputError(`Sandbox file paths must be absolute: ${path}`)\n }\n return {\n type: 'file',\n filename,\n ...(part.mediaType ? { mediaType: part.mediaType } : {}),\n url: fileUrl,\n }\n })\n}\n\n/** A persisted message whose attachment pointers accompany its history text. */\nexport interface DispatchHistoryMessage {\n role: string\n content: string\n parts?: ReadonlyArray<Record<string, unknown>> | null\n}\n\n/** Whose eyes the history is read through. */\nexport interface DispatchHistoryPov {\n /** The agent being prompted (`args.agent?.id` on a mentioned turn). Its\n * own answers stay `assistant`; every other agent's answer becomes a\n * `user` message tagged `[Name] …`, the same tagging agent-runtime's\n * `runConversation` uses, so three or more parties stay unambiguous. */\n pov?: string\n /** The thread's own agent, so its untagged answers can be named when the\n * history is read by someone else. Omit → untagged rows stay `assistant`. */\n owner?: { id: string; name: string }\n /** Append each row's attachment pointers to its text, as dispatch does.\n * Default true; a Router turn with no box to read from passes false. */\n attachments?: boolean\n}\n\n/** Project persisted rows using the same role and attachment policy as dispatch.\n * A row written by several agents (stored speaker headers or live ownership tags)\n * projects as one message per speaker, each tagged with its name; with a\n * point of view, the reader's own answers are untagged `assistant` turns and\n * everyone else's are tagged `user` turns. Reasoning and tool parts never\n * project: they are the writer's trace, not anyone's context. */\nexport function projectDispatchHistory(\n messages: ReadonlyArray<DispatchHistoryMessage>,\n view: DispatchHistoryPov = {},\n): Array<{ role: 'user' | 'assistant'; content: string }> {\n const out: Array<{ role: 'user' | 'assistant'; content: string }> = []\n const textOf = (message: DispatchHistoryMessage) =>\n view.attachments === false ? message.content : historyContentWithAttachments(message)\n for (const message of messages) {\n if (message.role !== 'assistant') {\n out.push({ role: 'user', content: textOf(message) })\n continue\n }\n const sections = partitionBySpeaker(message.parts ?? [])\n const grouped = sections.some(section => section.speaker !== null)\n for (const { speaker, parts } of sections) {\n const text = textOf(grouped ? {\n role: 'assistant', parts,\n content: parts.filter(part => part.type === 'text' && typeof part.text === 'string').map(part => part.text).join(''),\n } : message)\n if (grouped && !speaker && !text) continue\n const owner = speaker ?? view.owner\n const foreign = view.pov !== undefined && owner !== undefined && owner.id !== view.pov\n out.push({\n role: foreign ? 'user' : 'assistant',\n content: owner && (foreign || (speaker && view.pov === undefined)) ? tagged(owner.name, text) : text,\n })\n }\n }\n return out\n}\n\nconst tagged = (name: string, text: string) => `[${name}] ${text}`\n\n/** Build input parameters for dispatching chat message parts including text, attachments, mentions, and history */\nexport interface BuildDispatchPartsInput {\n text: string\n attachments: ChatAttachmentPart[]\n mentions?: ChatMentionPart[]\n history: Array<{ role: 'user' | 'assistant'; content: string }>\n systemPrompt: string\n /** Serialized size of the backend profile the SDK inlines into the same\n * prompt request body — a large, non-negotiable rider that must come out of\n * the inline budget or near-cap attachments 413 at the proxy instead of\n * demoting to path parts. */\n profileWireBytes: number\n /** The product's workspace/tenant key, passed to `readAttachment`. */\n scopeId: string\n /** Maps an attachment's store-relative path to the in-box absolute path a\n * local media reference uses (same style as `fileMentionsToParts`'s\n * `resolvePath`). */\n resolveAttachmentPath: (path: string) => string\n /** Maps a mention's workspace-relative path to its in-box absolute path.\n * Default: {@link BuildDispatchPartsInput.resolveAttachmentPath} — in gtm the\n * vault mount roots both; a product that mounts them apart overrides this. */\n resolveMentionPath?: (path: string) => string\n /** The turn's already-ensured box — required when `mentions` is non-empty\n * (mention bytes are read from the live box, not the store). */\n box?: SandboxExecChannel\n /** Force every media part to a local file reference, skipping all inlining. */\n forcePath?: boolean\n /** REQUIRED store reader for attachment content — no default (the product\n * owns its store; see {@link ReadAttachmentFn}). */\n readAttachment: ReadAttachmentFn\n readSandboxMention?: ReadSandboxMentionFn\n /** Whole-request proxy cap. Default {@link DISPATCH_REQUEST_MAX_BYTES}. */\n requestMaxBytes?: number\n /** JSON-envelope reserve off the top of the request cap. Default\n * {@link DISPATCH_STRUCTURAL_RESERVE_BYTES}. */\n structuralReserveBytes?: number\n /** Sidecar per-request parts-array cap. Default {@link DISPATCH_MAX_PARTS}. */\n maxParts?: number\n}\n\n/** Content of one attachment read, normalized to the base64 a `data:` URI\n * needs — `base64` reused verbatim, else `bytes` encoded once. */\nfunction readResultToBase64(read: { base64?: string; bytes?: Uint8Array }): string | undefined {\n if (typeof read.base64 === 'string') return read.base64\n if (read.bytes) return bytesToBase64(read.bytes)\n return undefined\n}\n\n/** Build dispatch parts from input by resolving mentions, paths, and applying size constraints asynchronously */\nexport async function buildDispatchParts(input: BuildDispatchPartsInput): Promise<DispatchPartsOutcome> {\n const readMention = input.readSandboxMention ?? readSandboxMention\n const resolveMentionPath = input.resolveMentionPath ?? input.resolveAttachmentPath\n const forcePath = input.forcePath ?? false\n // Agent mentions address a responder; only file mentions are read from the box.\n const mentions = (input.mentions ?? []).filter((mention) => mention.mentionKind !== 'agent')\n const requestMaxBytes = input.requestMaxBytes ?? DISPATCH_REQUEST_MAX_BYTES\n const structuralReserveBytes = input.structuralReserveBytes ?? DISPATCH_STRUCTURAL_RESERVE_BYTES\n const maxParts = input.maxParts ?? DISPATCH_MAX_PARTS\n\n const parts: PromptInputPart[] = [{ type: 'text', text: input.text }]\n // Absolute in-box paths already emitted — a file both attached and mentioned\n // (or mentioned twice) rides as a single media part.\n const emittedAbsPaths = new Set<string>()\n\n const flattenedForSizing = flattenHistory(input.text, input.history)\n // May go negative when history/systemPrompt alone are large — every\n // attachment then fails the `runningInline + cost <= inlineBudget` check\n // below and uses a local file reference, which does not draw on this inline\n // budget.\n const inlineBudget =\n requestMaxBytes\n - base64WireLen(byteLen(flattenedForSizing))\n - byteLen(JSON.stringify(input.systemPrompt))\n - input.profileWireBytes\n - structuralReserveBytes\n\n let runningInline = 0\n\n // Stable input order: attachments dispatch in the order the user attached\n // them, and the pointer block in `input.text` already names them in that\n // same order.\n for (const attachment of input.attachments) {\n if (!attachment.path) {\n return { succeeded: false, error: `attachment path must be non-empty: ${attachment.name}` }\n }\n\n // The reader crosses an external boundary (store/coordinator) — a rejection\n // there must land in the typed outcome, not escape as a thrown error the\n // caller would misattribute to stream init.\n let read: Awaited<ReturnType<ReadAttachmentFn>>\n try {\n read = await input.readAttachment(input.scopeId, attachment.path)\n } catch (err) {\n return {\n succeeded: false,\n error: `attachment store read failed: ${attachment.path} — ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (!read.ok) return { succeeded: false, error: read.reason }\n\n const base64 = readResultToBase64(read)\n if (base64 === undefined) {\n return { succeeded: false, error: `attachment store read produced no content: ${attachment.path}` }\n }\n\n const mediaType = attachment.mediaType ?? read.mediaType\n if (attachment.type === 'image' && !mediaType) {\n return { succeeded: false, error: `attachment is missing a mediaType required for an image data URI: ${attachment.path}` }\n }\n\n const absPath = input.resolveAttachmentPath(attachment.path)\n emittedAbsPaths.add(absPath)\n\n if (attachment.type === 'image') {\n const inlinePart: PromptInputPart = {\n type: 'image',\n filename: attachment.name,\n mediaType,\n url: `data:${mediaType};base64,${base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n if (!forcePath && runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n } else {\n parts.push({ type: 'image', filename: attachment.name, mediaType, path: absPath })\n }\n continue\n }\n\n // File parts use the current filename + URL contract. A file that is too\n // large to inline keeps its existing in-box file through a file:// URL.\n const fileMediaType = mediaType ?? 'application/octet-stream'\n const inlinePart: PromptInputPart = {\n type: 'file',\n filename: attachment.name,\n mediaType: fileMediaType,\n url: `data:${fileMediaType};base64,${base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n if (!forcePath && runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n } else {\n const url = sandboxFileUrl(absPath)\n if (!url) {\n return { succeeded: false, error: `resolved attachment path must be absolute: ${absPath}` }\n }\n parts.push({ type: 'file', filename: attachment.name, mediaType: fileMediaType, url })\n }\n }\n\n if (mentions.length > 0 && !input.box) {\n return { succeeded: false, error: 'internal error: sandbox mentions require a box to read from' }\n }\n for (const mention of mentions) {\n if (!mention.path) {\n return { succeeded: false, error: `mention path must be non-empty: ${mention.name}` }\n }\n if (!isWorkspaceFileExportable(mention.path)) {\n return { succeeded: false, error: `mention file is not exportable: ${mention.path}` }\n }\n const absPath = resolveMentionPath(mention.path)\n if (emittedAbsPaths.has(absPath)) continue\n emittedAbsPaths.add(absPath)\n\n const isImage = mention.mentionKind === 'image'\n const mediaType = isImage ? mediaTypeForMentionPath(mention.path) : undefined\n\n // Every mention is stat'd first: it proves the file still exists (a deleted\n // mention fails the turn loud) and gives the size for the inline budget\n // decision without pulling bytes across the exec channel.\n let stat: SandboxMentionReadOutcome\n try {\n stat = await readMention(input.box!, absPath, { readBytes: false })\n } catch (err) {\n return { succeeded: false, error: `mention read failed: ${absPath} — ${err instanceof Error ? err.message : String(err)}` }\n }\n if (!stat.succeeded) return { succeeded: false, error: stat.error }\n\n // Only an image that projects within the remaining budget reads its bytes\n // to inline; every other mention (and a budget-exceeding image) ships\n // by local reference, so a large file is never base64'd unnecessarily.\n const projectedInlineCost = base64WireLen(stat.value.size)\n + byteLen(JSON.stringify({ type: 'image', filename: mention.name, mediaType: mediaType ?? '', url: '' }))\n if (isImage && mediaType && !forcePath && runningInline + projectedInlineCost <= inlineBudget) {\n let read: SandboxMentionReadOutcome\n try {\n read = await readMention(input.box!, absPath, { readBytes: true })\n } catch (err) {\n return { succeeded: false, error: `mention read failed: ${absPath} — ${err instanceof Error ? err.message : String(err)}` }\n }\n if (!read.succeeded) return { succeeded: false, error: read.error }\n if (!read.value.base64) return { succeeded: false, error: `mentioned image produced no bytes: ${absPath}` }\n const inlinePart: PromptInputPart = {\n type: 'image',\n filename: mention.name,\n mediaType,\n url: `data:${mediaType};base64,${read.value.base64}`,\n }\n const cost = byteLen(JSON.stringify(inlinePart))\n // Re-check against the actual serialized cost — the projection can\n // undershoot; a real overshoot demotes to a path part rather than 413ing.\n if (runningInline + cost <= inlineBudget) {\n parts.push(inlinePart)\n runningInline += cost\n continue\n }\n }\n\n if (isImage && mediaType) {\n parts.push({ type: 'image', filename: mention.name, mediaType, path: absPath })\n } else {\n const url = sandboxFileUrl(absPath)\n if (!url) {\n return { succeeded: false, error: `resolved mention path must be absolute: ${absPath}` }\n }\n parts.push({ type: 'file', filename: mention.name, url })\n }\n }\n\n for (const part of parts) {\n if (violatesUrlPathXor(part)) {\n return { succeeded: false, error: 'internal error: emitted media part violates the url/path exclusivity invariant' }\n }\n }\n\n // Final whole-request check sized against what actually crosses the wire: the\n // history-merged text part (the substrate folds `history` into `parts[0]`\n // before dispatch), the media parts, the system prompt, and the inlined\n // backend profile riding the same body — the same terms `inlineBudget` was\n // derived from.\n const textPartSize = base64WireLen(byteLen(flattenedForSizing))\n const mediaPartsSize = parts.slice(1).reduce((total, part) => total + byteLen(JSON.stringify(part)), 0)\n const systemPromptSize = byteLen(JSON.stringify(input.systemPrompt))\n if (textPartSize + mediaPartsSize + systemPromptSize + input.profileWireBytes + structuralReserveBytes > requestMaxBytes) {\n return { succeeded: false, error: 'dispatch parts exceed the sandbox proxy request cap even after path demotion' }\n }\n\n // The sidecar rejects the whole request past its parts-array cap; the caller\n // selects which media ride natively, so overflow here is a caller bug\n // surfaced loudly rather than a truncation.\n if (parts.length > maxParts) {\n return { succeeded: false, error: `dispatch parts exceed the sidecar per-request cap of ${maxParts}` }\n }\n\n return { succeeded: true, value: parts }\n}\n","/**\n * When each reasoning run of a turn started and ended, so every chat producer\n * persists one reasoning part shape: `{ type: 'reasoning', text, time: { start, end } }`\n * (`ChatReasoningPart` in `/chat-store`).\n *\n * The engine (`./router-producer`) and the sandbox (`./sandbox-producer`) both\n * stream reasoning live as `{ type: 'reasoning', text }` deltas. This clock gives\n * their persisted parts the same timing: a run starts at its first delta and\n * ends when anything else streams (answer text, a tool) or the turn ends. A\n * harness that timed its own part keeps its times; the clock fills only what it\n * left out. `/web-react` reads the result back (`chatReasoningFromParts`), so a\n * reloaded turn shows how long the model thought.\n *\n * Import-free, so the browser-safe chat stream can share the part's type.\n */\n\n/** Start and end, in epoch milliseconds, of one reasoning run. */\nexport interface ReasoningRunTime {\n start?: number\n end?: number\n}\n\n/** The clock one producer keeps for one turn. `K` is how the producer names a run: a part key or the part itself. */\nexport interface ReasoningClock<K> {\n /** A reasoning delta for `run` streamed. Starts its clock on the first; ends any other open run. */\n reasoning(run: K): void\n /** Something other than reasoning streamed, or the turn ended: the open run is over, at `at` (default now). */\n settle(at?: number): void\n /** The run's time, the part's own `start` and `end` winning where it has them. */\n time(run: K, own?: ReasoningRunTime): ReasoningRunTime | undefined\n}\n\n/** A clock for one turn's reasoning runs. */\nexport function createReasoningClock<K>(now: () => number = Date.now): ReasoningClock<K> {\n const runs = new Map<K, ReasoningRunTime>()\n let open: { run: K } | null = null\n const settle = (at?: number) => {\n if (!open) return\n const time = runs.get(open.run)\n if (time && time.end === undefined) time.end = Math.max(time.start ?? 0, at ?? now())\n open = null\n }\n return {\n reasoning(run) {\n if (open && open.run === run) return\n settle()\n const time = runs.get(run)\n // The same run resumed after an interruption: it is open again.\n if (time) delete time.end\n else runs.set(run, { start: now() })\n open = { run }\n },\n settle,\n time(run, own) {\n const time = runs.get(run)\n if (!time) return own\n const start = own?.start ?? time.start\n const end = own?.end ?? time.end\n return { ...(start !== undefined ? { start } : {}), ...(end !== undefined ? { end } : {}) }\n },\n }\n}\n","/**\n * The chat-route producer for a Router turn: `runRouterTurn` behind the same\n * `produce` seam the sandbox lane uses (`createSandboxChatProducer`). The route\n * persists, buffers, replays and settles the turn exactly as it does for the\n * sandbox; only the producer differs.\n *\n * The engine is pushed, the route pulls: engine events land in a queue that the\n * `stream` generator drains in order, so a slow consumer never drops a frame\n * and the engine never waits on the consumer.\n */\nimport { composeRouterTurnPromptSections, runRouterTurn, type RouterTurnEvent, type RouterTurnFailure, type RouterTurnOptions, type RouterTurnOutcome, type RouterTurnPromptOptions, type RouterTurnTool } from '../runtime/router-turn'\nimport { createReasoningClock } from './reasoning-clock'\nimport { redactErrorMessage } from '../redact/index'\nimport { noticePart } from '../interactions/contract'\nimport type { ChatTurnRouteProducer, ChatTurnUsage } from './turn-routes'\nimport type { ProducerWireEvent } from './wire'\n\n/** The turn's model key: a plain key, or a per-turn lease whose fetch and revocation belong to the producer. */\nexport type RouterTurnKey = string | { key: string; fetchImpl?: typeof fetch; revoke(): Promise<void> }\ntype RouterTurnPrompt = string | (RouterTurnPromptOptions & { profile: Parameters<typeof composeRouterTurnPromptSections>[0] })\n\nexport type RouterTurnProducerOptions = Omit<RouterTurnOptions, 'onEvent' | 'systemPrompt' | 'apiKey'> & {\n /** The turn's key, including any claim still in flight. A lease's fetch and retirement belong to this producer. */\n apiKey: RouterTurnKey | Promise<RouterTurnKey>\n /** Domain-authored stable and per-turn bytes; composition and prefix validation are automatic. */\n systemPrompt: RouterTurnPrompt | Promise<RouterTurnPrompt>\n /** Final admission: model text may start earlier, but every tool waits for this request's committed domain state. */\n admitted?: Promise<unknown>\n /** Observe the finished turn or supply domain-authored final text/failure. An unfinished checkpoint is a turn_deadline failure here; durable continuation belongs to runRouterTurn callers. */\n onOutcome?: (outcome: RouterTurnOutcome) => void | { trailingText?: string; failure?: RouterTurnFailure } |\n Promise<void | { trailingText?: string; failure?: RouterTurnFailure }>\n /** Observe each engine event after the producer has projected it (a box speculator, metrics). A throw is ignored. */\n onEvent?: (event: RouterTurnEvent) => void\n /** Retire product resources once, including initialization failure and cancellation before the stream is read. */\n onSettled?(): Promise<void> | void\n}\n\nexport function createRouterTurnProducer(options: RouterTurnProducerOptions): Omit<ChatTurnRouteProducer, 'stream'> & {\n stream: AsyncGenerator<ProducerWireEvent, void, unknown>\n} {\n const abort = new AbortController()\n const signal = options.signal ? AbortSignal.any([abort.signal, options.signal]) : abort.signal\n void options.admitted?.catch(error => { abort.abort(error) })\n const credential = Promise.resolve(options.apiKey)\n let credentialSettled = false\n void credential.then(() => { credentialSettled = true }, () => { credentialSettled = true })\n let retired: Promise<void> | undefined\n const retire = () => retired ??= credential.then(async key => {\n if (typeof key !== 'string') await key.revoke()\n }, () => undefined).catch(error => {\n console.error(JSON.stringify({ event: 'router_turn_key_retire_failed', error: redactErrorMessage(error) }))\n })\n let stop: (reason: unknown) => void = () => {}\n const cancelled = new Promise<never>((_resolve, reject) => { stop = reject })\n const stopped = () => { stop(signal.reason); void retire() }\n signal.addEventListener('abort', stopped, { once: true })\n if (signal.aborted) stopped()\n const queue: ProducerWireEvent[] = []\n let wake: (() => void) | null = null\n let done = false\n let outcome: RouterTurnOutcome | null = null\n // The runtime starts usage at zero, so only a reported usage event makes the counts real.\n let usageReported = false\n const parts: Array<Record<string, unknown>> = []\n const toolParts = new Map<string, Record<string, unknown>>()\n let textPart: { type: 'text'; text: string } | null = null\n let textSegment = 0\n let reasoningPart: { type: 'reasoning'; text: string } | null = null\n // Each reasoning part's start and end, the same timing the sandbox producer persists.\n const reasoningClock = createReasoningClock<Record<string, unknown>>()\n\n const push = (event: ProducerWireEvent) => {\n queue.push(event)\n wake?.()\n }\n\n const run = Promise.race([Promise.all([credential, options.systemPrompt]), cancelled]).then(([key, prompt]) => {\n signal.throwIfAborted()\n return runRouterTurn({\n ...options,\n apiKey: typeof key === 'string' ? key : key.key,\n fetchImpl: typeof key === 'string' ? options.fetchImpl : key.fetchImpl ?? options.fetchImpl,\n signal,\n tools: options.tools?.map(tool => ({ ...tool, run: async (...args: Parameters<RouterTurnTool['run']>) => {\n await options.admitted; signal.throwIfAborted(); return tool.run(...args)\n } })),\n systemPrompt: typeof prompt === 'string' ? prompt : composeRouterTurnPromptSections(prompt.profile, prompt).text,\n showReasoning: options.showReasoning ?? true,\n onEvent: event => {\n if (event.type === 'text') {\n if (event.segment !== textSegment || !textPart) {\n textSegment = event.segment\n textPart = { type: 'text', text: '' }\n parts.push(textPart)\n }\n textPart.text += event.delta\n reasoningPart = null\n reasoningClock.settle()\n push({ type: 'text', text: event.delta })\n } else if (event.type === 'reasoning') {\n // A reasoning run is one part until a word or a tool interrupts it.\n if (!reasoningPart) {\n reasoningPart = { type: 'reasoning', text: '' }\n parts.push(reasoningPart)\n }\n reasoningPart.text += event.delta\n reasoningClock.reasoning(reasoningPart)\n push({ type: 'reasoning', text: event.delta })\n } else if (event.type === 'tool') {\n reasoningPart = null\n // The model stopped reasoning when it called the tool.\n reasoningClock.settle(event.startedAt)\n if (event.status === 'running') {\n const part = { type: 'tool', id: event.callId, callID: event.callId, tool: event.toolName,\n state: { status: 'running', input: event.input, time: { start: event.startedAt } } }\n toolParts.set(event.callId, part)\n parts.push(part)\n push({ type: 'tool_call', call: { toolCallId: event.callId, toolName: event.toolName, args: event.input } })\n } else {\n const part = toolParts.get(event.callId)\n const state = event.status === 'completed'\n ? { status: 'completed', output: event.output, time: { start: event.startedAt, end: event.endedAt } }\n : { status: 'error', error: event.error.message, time: { start: event.startedAt, end: event.endedAt } }\n if (part) part.state = { ...(part.state as Record<string, unknown>), ...state }\n push({ type: 'tool_result', toolCallId: event.callId, toolName: event.toolName,\n outcome: event.status === 'completed' ? { ok: true, result: event.output } : { ok: false, message: event.error.message, code: event.error.code } })\n }\n } else if (event.type === 'repeat') {\n // The repeat's reasoning is a new run: close the failed call's part so the two never merge.\n reasoningPart = null\n reasoningClock.settle()\n } else if (event.type === 'usage') {\n usageReported = true\n push({ type: 'usage', usage: { promptTokens: event.promptTokens, completionTokens: event.completionTokens,\n ...(event.cachedPromptTokens !== undefined ? { cachedPromptTokens: event.cachedPromptTokens } : {}) } })\n } else if (event.type === 'tool_event') {\n // Recorded on the tool's part, so a reload shows what the tool did, and streamed as it happens.\n const part = toolParts.get(event.callId)\n if (part) {\n const state = part.state as Record<string, unknown>\n part.state = { ...state, events: [...(state.events as unknown[] ?? []), { kind: event.kind, data: event.data, at: event.at }] }\n }\n push({ type: 'tool.event', data: { toolCallId: event.callId, toolName: event.toolName, kind: event.kind, data: event.data, at: event.at } })\n }\n if (options.onEvent) {\n try { options.onEvent(event) } catch { /* an observer never changes the turn */ }\n }\n },\n })\n }).then(async result => {\n // This producer settles chat; it has no durable owner to resume a checkpoint.\n // Classify unfinished work before domain settlement observes the outcome.\n if (result.continuation && !result.failure) {\n result.failure = { code: 'turn_deadline', message: 'The reply was stopped before it finished.' }\n }\n outcome = result\n const final = await options.onOutcome?.(result)\n if (final && final.trailingText) {\n result.text += final.trailingText\n parts.push({ type: 'text', text: final.trailingText })\n push({ type: 'text', text: final.trailingText })\n }\n if (final && final.failure) result.failure = final.failure\n if (result.failure) {\n parts.push(noticePart('error', 'router-error', result.failure.message, result.failure.code))\n push({ type: 'error', data: { message: result.failure.message, code: result.failure.code } })\n }\n }).finally(async () => {\n const retiring = retire()\n if (credentialSettled) await retiring\n try { await options.onSettled?.() } catch (error) {\n console.error(JSON.stringify({ event: 'router_turn_settle_failed', error: redactErrorMessage(error) }))\n }\n signal.removeEventListener('abort', stopped)\n reasoningClock.settle()\n done = true\n wake?.()\n })\n void run.catch(() => undefined)\n\n async function* stream(): AsyncGenerator<ProducerWireEvent, void, unknown> {\n for (;;) {\n while (queue.length) yield queue.shift()!\n if (done) break\n await new Promise<void>(resolve => { wake = resolve })\n wake = null\n }\n await run\n }\n\n // A reasoning part carries its run's time; a run still open in a mid-turn draft has a start and no end.\n const snapshot = () => parts.map(part => part.type === 'reasoning'\n ? { ...part, time: reasoningClock.time(part) }\n : { ...part })\n\n // A turn whose Router reported no usage stores no counts (null), never a made-up 0.\n const usage = (): ChatTurnUsage => !outcome || !usageReported ? {} : ({\n // The Router's prompt tokens include the cached ones; the sandbox lanes report input and cache reads apart, so\n // the stored row counts them apart here too and `inputTokens + cacheReadTokens` is the prompt on either lane.\n inputTokens: outcome.usage.promptTokens - (outcome.usage.cachedPromptTokens ?? 0),\n outputTokens: outcome.usage.completionTokens,\n ...(outcome.usage.cachedPromptTokens !== undefined ? { cacheReadTokens: outcome.usage.cachedPromptTokens } : {}),\n })\n\n const events = stream()\n const end = events.return.bind(events)\n const fail = events.throw.bind(events)\n events.return = async value => {\n abort.abort(new Error('The chat route stopped reading this turn'))\n try { return await end(value) } finally { const retiring = retire(); if (credentialSettled) await retiring }\n }\n events.throw = async error => {\n abort.abort(error)\n try { return await fail(error) } finally { const retiring = retire(); if (credentialSettled) await retiring }\n }\n\n return {\n stream: events,\n // The route tracks this continuation even when failure is visible before a pending key arrives.\n cleanup: run.then(retire, retire),\n finalText: () => outcome?.text ?? '',\n assistantParts: snapshot,\n draftParts: snapshot,\n usage,\n get model() { return outcome?.servedModel ?? undefined },\n modelAttribution: () => ({\n requestedModel: options.model,\n ...(outcome?.servedModel ? { servedModel: outcome.servedModel } : {}),\n echoReceived: Boolean(outcome?.servedModel),\n }),\n }\n}\n","/**\n * `createHybridTurnProducer`: the default chat turn. The model answers first\n * through the Tangle Router with the app's tools in process, and work that\n * needs a computer escalates to the workspace box through one `sandbox_run`\n * call whose answer comes back to the model.\n *\n * WHY THIS IS THE DEFAULT. Measured on production: the\n * Hospitality Router lane gave first text at 3.6 s with 0 of 39 failures; its\n * sandbox lane 31.0 s with 2 of 8. Legal's sandbox lane gave first text at\n * p50 137 s because the box agent writes nothing until its last tool call. The\n * box only wins after about 8 tool calls through the API path (3 to 6 when it\n * is warm), and those turns still reach it here, through `sandbox_run`.\n *\n * THE BOX. The producer starts it at most once per turn and every caller\n * shares that start: the speculator, the `sandbox_run` call, and a start that\n * admission already began (`box.started`, from {@link startHybridBox} in\n * `afterAuthorize`). A failed start is forgotten, so the tool's own call\n * retries it. Across isolates the product's `acquire` keeps its existing\n * single flight (`runForegroundSandboxSingleFlight` over the D1 claim, or the\n * warm lease).\n *\n * THE SPECULATOR is always on: words that ask for execution, a code fence or a\n * process-shaped attachment start the box before the model call, and the model\n * naming `sandbox_run` starts it while the call's arguments still stream.\n *\n * FIRST WORDS. Unless the product passes its own `guidance`, the prompt tells\n * the model to say in one sentence what it is about to do before its first\n * tool call, so a turn that writes a deliverable or escalates to the box shows\n * text at the model's first token, not after its last tool call.\n *\n * The trace passes through: model calls, tool calls, the box claim and the box\n * run are recorded under the turn's `trace` when the route gives one.\n * A typed computer failure also emits a persisted warning; the Router keeps\n * answering without relying on the model to explain that failure faithfully.\n * The warning's `detail` is the failure's redacted cause chain, so the cause is\n * in the transcript, not only in a log line a Worker does not keep.\n */\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { redactErrorMessage } from '../redact/index'\nimport { noticePart } from '../interactions/contract'\nimport type { RouterTurnTool } from '../runtime/router-turn'\nimport {\n createEscalationSpeculator,\n escalationHints,\n type EscalationHint,\n type EscalationInput,\n} from '../sandbox/escalation-speculator'\nimport { createSandboxRunTool, SandboxRunError, sandboxRunFailureDetail, type SandboxRunToolOptions } from '../sandbox/sandbox-run-tool'\nimport { createComputerStep, type ComputerStepOptions } from '../sandbox/computer-step'\nimport type { PersistedChatMessageForTurn } from '../stream/index'\nimport { projectDispatchHistory, type DispatchHistoryPov } from './dispatch-parts'\nimport { createRouterTurnProducer, type RouterTurnProducerOptions } from './router-producer'\nimport type { ChatTurnRouteProducer } from './turn-routes'\nimport type { ChatRouteEvent } from './turn-route-contracts'\nimport type { ChatTurnPartInput, ChatTurnRequestPayload } from './wire'\nimport type { ProducerNoticeEvent } from './wire'\n\n// The lead-in covers every tool, not only sandbox_run: on Legal's Router lane the model streamed a\n// submit_proposal payload for 45 s before its first word, so first text came at 54.9 s after a first token at 3.8 s.\n/** What the default prompt adds so the Router lane answers first and escalates out loud. */\nexport const HYBRID_TURN_GUIDANCE =\n 'Start your reply with text: before your first tool call, write one short sentence telling the member what you are ' +\n 'about to do, so they never wait in silence. Use sandbox_run only for work that needs code execution or files on ' +\n \"the workspace computer. Give the sandbox agent the member's requirements, paths and exact field names, \" +\n 'not model-written code; the sandbox agent writes and runs the code. Report what it returns.'\n\nconst DEFAULT_SANDBOX_RUN_TIMEOUT_MS = 4 * 60_000\n\nexport interface HybridTurnBox {\n /** Start or adopt the workspace box. The product provisions, binds and bills it, and keeps its own single flight\n * across isolates. A throw reaches the model as `sandbox_unavailable` (or the `SandboxRunError` it throws). */\n acquire(signal: AbortSignal): Promise<SandboxInstance>\n /** A start admission already began ({@link startHybridBox}); the producer takes it as the turn's start. */\n started?: Promise<SandboxInstance>\n /** Runs the task on the box and returns its answer. Omit it and pass `computer` for agent-app's computer step. */\n runTask?: SandboxRunToolOptions['runTask']\n /** agent-app's computer step ({@link createComputerStep}): the first of the turn's models the box key allows, one\n * session value, a turn id the runtime's admission makes idempotent, and the copy of the step's files into the product's Vault.\n * `parentExecutionId` defaults to the turn's execution id on the chat route, else the trace id. */\n computer?: ComputerStepOptions\n /** Wall-clock cap for one `sandbox_run` call, box start included. Default 4 minutes. */\n timeoutMs?: number\n warm?: SandboxRunToolOptions['warm']\n /** Every computer failure with its cause. The producer already persists the redacted cause chain on the turn's\n * warning notice (`detail`), and logs it when this is omitted. */\n onFailure?: SandboxRunToolOptions['onFailure']\n /** What the turn's warning notice keeps as `detail` for a failed call. Members read that notice in the transcript.\n * Default: the redacted cause chain ({@link sandboxRunFailureDetail}). Return undefined to keep a cause that holds\n * private platform diagnostics off the transcript; `onFailure` still receives the full error. */\n failureDetail?(error: SandboxRunError): string | undefined\n /** The tool's name and description. Default `sandbox_run` and its shared description. */\n name?: string\n description?: string\n /** Dispose this turn's opaque client credentials/resources after any started acquire settles. Never retire the box. */\n dispose?(): Promise<void> | void\n}\n\nexport interface HybridTurnProducerOptions extends RouterTurnProducerOptions {\n /** The app's in-process tools. `sandbox_run` is added after them. */\n tools?: RouterTurnTool[]\n box: HybridTurnBox\n /** The text the speculator reads. Default `userMessage`; pass what the member typed when `userMessage` carries\n * injected context that would trip the execution words. */\n speculateOn?: string\n /** The turn's attachments, for the speculator. */\n attachments?: EscalationInput['attachments']\n onSpeculate?(hint: EscalationHint): void\n /** Appended to `systemPrompt`. Default {@link HYBRID_TURN_GUIDANCE}; `false` when the prompt already says it. */\n guidance?: string | false\n}\n\n/**\n * Start the box at admission when the request asks for execution, so its resume overlaps the turn lock and the\n * profile pin instead of following them. Call it in `afterAuthorize` with the turn's body and hand the promise to\n * the producer as `box.started`. Returns undefined, and starts nothing, for a turn that does not look like it needs\n * the box.\n */\nexport function startHybridBox(\n body: Pick<ChatTurnRequestPayload, 'content' | 'parts'>,\n acquire: () => Promise<SandboxInstance>,\n): Promise<SandboxInstance> | undefined {\n const attachments = (body.parts ?? []).map(part => ({\n ...(part.mediaType ? { mediaType: part.mediaType } : {}),\n ...(part.filename ? { name: part.filename } : {}),\n }))\n if (escalationHints({ text: body.content ?? '', attachments }).length === 0) return undefined\n const started = acquire()\n // The producer or the caller's release awaits it; a start nobody awaits must not surface as an unhandled rejection.\n started.catch(() => undefined)\n return started\n}\n\n/** The turn's prompt as the text the model reads: text parts joined; file parts are not text. */\nexport function turnPromptText(prompt: string | readonly ChatTurnPartInput[]): string {\n return typeof prompt === 'string' ? prompt : prompt.map(part => part.type === 'text' ? part.text : '').join('\\n')\n}\n\n/** Whether the turn carries files. Files live in the box, so a turn with them runs on the sandbox lane. */\nexport function turnCarriesFiles(prompt: string | readonly ChatTurnPartInput[]): boolean {\n return typeof prompt !== 'string' && prompt.some(part => part.type !== 'text')\n}\n\n/** The conversation so far as the plain text history a Router turn replays: the last `limit` user and assistant\n * messages that have text, read through the responder's point of view when the turn was addressed to agents\n * (a row several agents wrote becomes one tagged message per speaker). Tool and reasoning parts are not replayed. */\nexport function routerTurnHistory(\n priorMessages: ReadonlyArray<Pick<PersistedChatMessageForTurn, 'role' | 'content'> & { parts?: ReadonlyArray<Record<string, unknown>> | null }>,\n limit = 40,\n view: Pick<DispatchHistoryPov, 'pov' | 'owner'> = {},\n): Array<{ role: 'user' | 'assistant'; content: string }> {\n const rows = priorMessages.filter((message) => message.role === 'user' || message.role === 'assistant')\n return projectDispatchHistory(rows, { ...view, attachments: false })\n .filter((message) => Boolean(message.content.trim()))\n .slice(-limit)\n}\n\nexport function createHybridTurnProducer(options: HybridTurnProducerOptions): ChatTurnRouteProducer {\n const { box, tools = [], speculateOn, attachments, onSpeculate, guidance, onSettled, admitted, signal, ...router } = options\n const abort = new AbortController()\n const stop = signal ? AbortSignal.any([abort.signal, signal]) : abort.signal\n void admitted?.catch(error => { abort.abort(error) })\n const timeoutMs = box.timeoutMs ?? DEFAULT_SANDBOX_RUN_TIMEOUT_MS\n let activeTasks = 0\n let unconfirmed = false\n\n let start: Promise<SandboxInstance> | undefined = box.started?.catch((error: unknown) => {\n start = undefined\n throw error\n })\n // A turn that never calls the box never awaits its admission start; that start's failure is not unhandled.\n start?.catch(() => undefined)\n const acquire = async (): Promise<SandboxInstance> => {\n await admitted\n stop.throwIfAborted()\n return start ??= box.acquire(stop).catch((error: unknown) => { start = undefined; throw error })\n }\n\n let settled: Promise<void> | undefined\n const settle = () => settled ??= (async () => {\n abort.abort(new Error('The hybrid turn settled'))\n await (box.started ?? start)?.catch(() => undefined)\n const results = await Promise.allSettled([Promise.resolve().then(() => box.dispose?.()), Promise.resolve().then(() => onSettled?.())])\n for (const result of results) if (result.status === 'rejected') {\n console.error(JSON.stringify({ event: 'hybrid_turn_settle_failed', error: redactErrorMessage(result.reason) }))\n }\n })()\n\n try {\n const step = box.computer\n ? createComputerStep({ ...box.computer, parentExecutionId: box.computer.parentExecutionId ?? router.traceId })\n : undefined\n const runBoxTask = box.runTask ?? step?.runTask\n if (!runBoxTask) throw new Error('A hybrid box needs runTask or computer')\n const warnings = new Map<string, ProducerNoticeEvent>()\n // Each failed call's redacted cause chain, by call id, recorded before the engine reports the call's error.\n const details = new Map<string, string>()\n const withWarnings = (parts: Array<Record<string, unknown>>) => parts.flatMap(part => {\n const warning = warnings.get(String(part.callID ?? part.id ?? ''))\n return warning ? [part, noticePart(warning.noticeKind, warning.id, warning.text, warning.code, warning.detail)] : [part]\n })\n const sandboxRun = createSandboxRunTool({\n box: () => acquire(),\n runTask: async (...args) => {\n await admitted\n stop.throwIfAborted()\n if (unconfirmed || activeTasks > 0) throw new SandboxRunError('sandbox_unconfirmed', 'An earlier computer step may still be running; no further task was dispatched.')\n activeTasks++\n try { return await runBoxTask(...args) }\n catch (error) {\n if (!(error instanceof SandboxRunError) || error.code === 'sandbox_unconfirmed') unconfirmed = true\n throw error\n } finally { activeTasks-- }\n },\n memberRequest: router.userMessage,\n timeoutMs,\n signal: stop,\n ...(box.warm ? { warm: box.warm } : {}),\n onFailure: (error, call) => {\n const detail = box.failureDetail ? box.failureDetail(error) : sandboxRunFailureDetail(error)\n if (call.callId && detail) details.set(call.callId, detail)\n if (box.onFailure) box.onFailure(error, call)\n else console.error(JSON.stringify({ event: 'agent_app_sandbox_run_failed', callId: call.callId ?? null, code: error.code,\n detail: sandboxRunFailureDetail(error) }))\n },\n ...(box.name ? { name: box.name } : {}),\n ...(box.description ? { description: box.description } : {}),\n })\n const speculator = createEscalationSpeculator({\n warm: acquire,\n escalationTools: [sandboxRun.name],\n ...(onSpeculate ? { onSpeculate } : {}),\n })\n speculator.onInput({ text: speculateOn ?? router.userMessage, ...(attachments ? { attachments } : {}) })\n\n const extra = guidance === false ? '' : [guidance ?? HYBRID_TURN_GUIDANCE, step?.guidance].filter(Boolean).join('\\n\\n')\n const producer = createRouterTurnProducer({\n ...router,\n systemPrompt: Promise.resolve(router.systemPrompt).then(prompt => !extra ? prompt : typeof prompt === 'string'\n ? `${prompt}\\n\\n${extra}` : { ...prompt, stable: [...(prompt.stable ?? []), extra] }),\n tools: [...tools, sandboxRun],\n admitted,\n // A turn that calls the box must outlive the call it waits on.\n budgetMs: router.budgetMs ?? timeoutMs + 60_000,\n signal: stop,\n onSettled: settle,\n onEvent: event => {\n speculator.onEvent(event as { type: string; toolName?: string })\n if (event.type === 'tool' && event.status === 'error' && event.toolName === sandboxRun.name && !stop.aborted) {\n const code = event.error.code\n if (code === 'sandbox_unconfirmed') unconfirmed = true\n if (code === 'sandbox_unavailable' || code === 'sandbox_failed' || code === 'sandbox_unconfirmed' || code === 'sandbox_empty') {\n const detail = details.get(event.callId)\n warnings.set(event.callId, {\n type: 'notice', noticeKind: 'warning', id: `sandbox-warning:${event.callId}`, code,\n text: code === 'sandbox_unavailable'\n ? 'The workspace computer is unavailable. I can continue with work that does not need it.'\n : 'The computer step did not return a confirmed answer. I can continue with work that does not need it.',\n ...(detail ? { detail } : {}),\n })\n }\n }\n router.onEvent?.(event)\n },\n })\n const events = (async function* () {\n for await (const event of producer.stream) {\n yield event\n // A box agent's question (`computer.questions`) reaches the member as the interaction it is; the answer\n // goes to the box through the app's interaction route.\n const side = event.type === 'tool.event' ? event.data as { kind?: unknown; data?: unknown } | undefined : undefined\n if (side?.kind === 'computer_interaction' && side.data && typeof side.data === 'object') yield side.data as ChatRouteEvent\n if (event.type === 'tool_result') {\n const warning = warnings.get(event.toolCallId)\n if (warning) yield warning\n }\n }\n })()\n // Closing before the wrapper's first pull must still abort the running Router.\n const end = events.return.bind(events)\n const fail = events.throw.bind(events)\n events.return = async value => {\n const closing = producer.stream.return(value)\n try { return await end(value) } finally { await closing }\n }\n events.throw = async error => {\n const closing = producer.stream.throw(error)\n try { return await fail(error) } finally { await closing }\n }\n return { ...producer, stream: events,\n terminalObserved: () => activeTasks === 0 && !unconfirmed,\n assistantParts: () => withWarnings(producer.assistantParts?.() ?? []),\n draftParts: () => withWarnings(producer.draftParts?.() ?? []),\n get model() { return producer.model },\n }\n } catch (error) {\n // Construction failures use the same tracked lifetime as stream failures, including a key still arriving.\n return createRouterTurnProducer({ ...router, systemPrompt: Promise.reject(error), signal: stop, onSettled: settle })\n }\n}\n","/**\n * Model failover for a STREAMING turn.\n *\n * `/model-resolution`'s `runWithModelFailover` already owns the policy: walk a\n * chain, classify a resolved-or-thrown signal, re-throw a non-outage failure\n * immediately, and carry the attempt trail. This module does NOT re-implement\n * any of that — it composes it. What it adds is the one thing a whole-call\n * primitive cannot express, because a stream fails PARTWAY:\n *\n * **A turn may only fail over before its first client-visible byte.**\n *\n * Once a text delta, tool call, or ask has reached the browser (and the\n * persisted transcript), restarting on another model would duplicate the\n * answer. So each attempt is probed: open the stream, pull events into a small\n * buffer, and decide at the first meaningful event whether this model is\n * serving. Committing replays the buffer and hands the live iterator through;\n * abandoning discards the buffer (those events describe the dead model's\n * session — including its `step-finish` usage, which must never be billed) and\n * lets `runWithModelFailover` walk to the next model.\n *\n * `liveLifecycleEvents` relaxes the buffer for progress only. `start`,\n * `status`, `model-processing`, and session lifecycle carry no answer and no\n * receipt, so a product may take them the moment they arrive and show what\n * the turn is waiting on.\n * OpenCode reports whole parts, so the buffer held every event for 16 s and\n * the product could show nothing through provisioning and agent startup. Off\n * by default: with it on, an abandoned model's progress stays in the stream.\n *\n * The classification itself is `isUpstreamUnavailable` verbatim, so this path\n * inherits the measured facts from the 2026-07-25 outage — above all that an\n * outage is NOT always a thrown error: the sandbox RESOLVES a terminal `error`\n * event carrying `{ errorCode: 'provider_inference_unavailable' }`, which a\n * classifier inspecting only `catch` misses entirely. That resolved shape is\n * the whole reason the breakage went unnoticed, so it is classified here first.\n *\n * Conservative by construction:\n * - A terminal failure that is NOT an outage (400, bad schema, content filter)\n * COMMITS rather than failing over — it surfaces to the user exactly as it\n * does today. Those fail identically on every model; walking the chain would\n * only multiply latency and spend to reach the same error.\n * - A clean stream that produced nothing NEVER walks the chain. An empty answer\n * is not evidence of a dead upstream, and a silent re-roll on another model is\n * precisely the unattributable downgrade this work exists to prevent. Opt-in\n * `emptyTurnRetries` re-runs the SAME model instead, which leaves attribution\n * untouched — measured on production 2026-07-27, an empty turn is a transient\n * platform flake that a same-model re-run recovers (8 hard cases: 7/8\n * delivered on the first pass, 8/8 with one re-run, at a cost of 1 extra turn\n * in 9). Default `0`, so the behavior is unchanged unless a product asks.\n * - A responsive chain of length 1 costs no extra call or latency and remains\n * byte-identical to no failover. A silent chain is now deliberately bounded.\n */\n\nimport {\n isUpstreamUnavailable,\n ModelFailoverExhaustedError,\n readUpstreamUnavailableCode,\n readHttpStatusHint,\n runWithModelFailover,\n type ModelFailoverAttempt,\n} from '../model-resolution/failover'\nimport type { ModelPolicy } from '../policy-filters/index'\nimport { asRecord, asString } from '../stream/index'\n\n/** Terminal event types that end an attempt with a failure verdict. */\nconst TERMINAL_FAILURE_TYPES = new Set(['error', 'session.run.failed'])\n\n/**\n * Part types that carry no transcript content. They are buffered like anything\n * else — replayed verbatim when the attempt commits — but their presence alone\n * never commits a model, so an outage arriving right after a `step-start` is\n * still recoverable. `step-finish` matters most: it carries the abandoned\n * attempt's token/cost receipt, which must be discarded rather than billed.\n */\nconst NON_COMMITTING_PART_TYPES = new Set(['step-start', 'step-finish'])\n\n/**\n * True when `event` puts content in front of the user (or in the persisted\n * transcript), making a restart on another model unsafe.\n *\n * Deliberately an allow-list of KNOWN-INERT types rather than a deny-list: an\n * unrecognized event commits. Getting this wrong in the safe direction costs a\n * missed failover; getting it wrong the other way duplicates a user's answer.\n */\nexport function isCommittingSandboxEvent(event: unknown): boolean {\n const record = asRecord(event)\n if (!record) return false\n const type = asString(record.type) ?? ''\n if (!type) return false\n\n if (type === 'message.part.updated') {\n const data = asRecord(record.data)\n const part = asRecord(data?.part)\n const partType = asString(part?.type) ?? ''\n if (NON_COMMITTING_PART_TYPES.has(partType)) return false\n // A text/reasoning part with NO content yet (the platform opens the part\n // with `text: \"\"` before the first token — verbatim in the 2026-07-26\n // capture) puts nothing in front of the user; discarding it cannot\n // duplicate an answer. The first real token commits.\n if (partType === 'text' || partType === 'reasoning') {\n return [data?.delta, part?.text, part?.content]\n .some(value => typeof value === 'string' && value.length > 0)\n }\n return true\n }\n\n // Session/turn lifecycle, progress status, and warnings belong to the\n // attempt, not the transcript — discardable with an abandoned model.\n // Captured examples: a dead model\n // emits `start`, `execution.started`, `status`×3, `session.updated`×2,\n // `warning`×2 BEFORE its terminal `error` — any one of them committing\n // would pin the turn to the dead model and kill the failover.\n if (\n type === 'start' ||\n type === 'execution.started' ||\n type === 'status' ||\n type === 'model-processing' ||\n type === 'model.processing' ||\n // Public Sandbox timing metadata: a request was attempted, not answered.\n type === 'model.first_request' ||\n type === 'session.created' ||\n type === 'session.updated' ||\n type === 'session.idle' ||\n type === 'step-start' ||\n type === 'step-finish' ||\n type === 'turn' ||\n type === 'warning'\n ) {\n return false\n }\n\n // Everything else — text/tool shapes the producer folds, asks, plans,\n // `result`/`done`, and any type this shell does not recognize — commits.\n return true\n}\n\n/**\n * Condense an abandoned attempt's raw failure text into something safe to show\n * a customer in the transcript.\n *\n * Measured on the live router 2026-07-27 19:40 UTC: an edge 5xx arrives as\n * Cloudflare's full HTML error PAGE, so the verbatim reason began\n * `<!DOCTYPE html>\\n<!--[if lt IE 7]> <html class=\"no-js ie6 oldie\"…` and the\n * fallback notice pasted 200 bytes of that markup into the answer the customer\n * reads. The cause is worth stating; the markup is not.\n *\n * Only the DISPLAY string is condensed. The full text stays on\n * `modelFailover.attempts[].reason` for the operator, so nothing is lost —\n * this narrows what the customer sees, never what telemetry records.\n */\nexport function summarizeFailoverReason(reason: string): string {\n const collapsed = reason.replace(/\\s+/g, ' ').trim()\n if (!collapsed) return 'upstream unavailable'\n\n // An HTML error page carries no message worth quoting — the status is the\n // whole content. Detected on the ORIGINAL text, before collapsing, because\n // that is the form the producer hands over.\n if (/<!doctype html|<html[\\s>]/i.test(collapsed)) {\n const status = readHttpStatusHint(collapsed)\n return status ? `HTTP ${status}` : 'upstream returned an error page'\n }\n\n // Anything else is a real message. Cap it so a verbose upstream cannot push\n // the answer off the screen, and cut on a word boundary when one is near.\n const LIMIT = 160\n if (collapsed.length <= LIMIT) return collapsed\n const clipped = collapsed.slice(0, LIMIT)\n const lastSpace = clipped.lastIndexOf(' ')\n return `${(lastSpace > LIMIT - 30 ? clipped.slice(0, lastSpace) : clipped).trimEnd()}…`\n}\n\n/** A terminal failure event, classified. `outage` decides failover vs surface. */\ninterface TerminalFailure {\n outage: boolean\n reason: string\n code?: string\n}\n\n/**\n * Classify a terminal failure event. Returns `null` for any non-terminal event.\n *\n * The RESOLVED shape is checked first and deliberately: the sandbox reports an\n * upstream outage by resolving `{ success: false, errorCode:\n * 'provider_inference_unavailable' }` inside a terminal `error` event's `data`,\n * never by throwing. Both `data` and the whole record are offered to\n * `isUpstreamUnavailable` so a payload nested either way is caught.\n */\n/**\n * Progress the consumer may see before the commit point: it names no model\n * output and carries no billing receipt, so streaming it live cannot duplicate\n * an answer or bill an abandoned attempt. `warning` and every\n * `message.part.updated` (including `step-start`/`step-finish`) stay buffered.\n */\nexport function isLiveLifecycleEvent(event: unknown): boolean {\n const type = asString(asRecord(event)?.type) ?? ''\n return (\n type === 'start' ||\n type === 'execution.started' ||\n type === 'status' ||\n type === 'model-processing' ||\n type === 'model.processing' ||\n // Public Sandbox timing metadata: a request was attempted, not answered.\n type === 'model.first_request' ||\n type === 'session.created' ||\n type === 'session.updated' ||\n type === 'session.idle'\n )\n}\n\nexport function classifyTerminalFailure(event: unknown): TerminalFailure | null {\n const record = asRecord(event)\n if (!record) return null\n const type = asString(record.type) ?? ''\n if (!TERMINAL_FAILURE_TYPES.has(type)) return null\n\n const data = asRecord(record.data)\n const outage = isUpstreamUnavailable(data) || isUpstreamUnavailable(record)\n const reason =\n asString(data?.message) ??\n asString(data?.error) ??\n asString(data?.reason) ??\n asString(record.message) ??\n `sandbox stream reported ${type}`\n const code =\n readUpstreamUnavailableCode(data) ??\n asString(data?.errorCode) ??\n asString(data?.code) ??\n readUpstreamUnavailableCode(record) ??\n asString(record.errorCode) ??\n asString(record.code)\n return { outage, reason, ...(code ? { code } : {}) }\n}\n\n/** A model that served: its buffered preamble plus the still-live iterator. */\ninterface AttemptCommit {\n committed: true\n buffered: unknown[]\n /** `null` when the stream already ended during the probe. */\n iterator: AsyncIterator<unknown> | null\n /** Cancel transport work when this attempt is drained or abandoned. */\n abort: () => void\n}\n\n/**\n * A model whose upstream is down. `error`/`errorCode` are read by\n * `runWithModelFailover`'s attempt-trail describe(), so the trail names the\n * real upstream cause rather than a wrapper's own words.\n */\ninterface AttemptOutage {\n committed: false\n error: string\n errorCode?: string\n timeoutCode?: ModelAttemptTimeoutCode\n}\n\ntype AttemptOutcome = AttemptCommit | AttemptOutage\n\n/** Open the raw turn stream for one specific model. */\nexport type OpenModelStream = (args: {\n model: string\n /** 1 for the preferred model, 2 for the first fallback, and so on. */\n attempt: number\n /** Aborted when this attempt times out, is abandoned, or finishes. Forward\n * this to `streamSandboxPrompt(..., { signal })` so a blocked transport is\n * cancelled immediately rather than only receiving iterator.return(). */\n signal: AbortSignal\n}) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>\n\n/** Fired when a model is abandoned and the next one is about to be tried. */\nexport interface ModelFallbackInfo {\n from: string\n to: string\n reason: string\n}\n\n/** Define inputs for streaming a turn across a model failover chain */\nexport interface ModelFailoverStreamOptions {\n /** Preferred model first, then fallbacks in descending preference. */\n models: readonly string[]\n open: OpenModelStream\n /**\n * Product admission policy applied to EVERY chain member before its stream\n * is opened — see `runWithModelFailover`'s `policy`. A member the policy\n * refuses is skipped (never opened, never sent the turn's data) and the walk\n * continues; an all-refused chain ends in `ModelFailoverExhaustedError`.\n */\n policy?: ModelPolicy\n /**\n * Maximum time to open/start one model's event source, including its first\n * iterator pull. Default 120 seconds, matching the sandbox provisioning\n * ceiling so cold infrastructure startup is bounded independently from\n * provider inference.\n */\n openTimeoutMs?: number\n /**\n * Hard deadline from the source's first lifecycle event to its first\n * answer-bearing event. Default 60 seconds. Processing/lifecycle events do\n * not commit the attempt and do not extend this deadline.\n */\n firstResponseTimeoutMs?: number\n /** Override the commit-point rule. Default {@link isCommittingSandboxEvent}. */\n isCommitting?: (event: unknown) => boolean\n /**\n * Stream {@link isLiveLifecycleEvent} progress to the consumer as it arrives\n * instead of holding it until the attempt commits. Default `false`, which\n * keeps an abandoned model's events entirely off the wire. With it on, such\n * an event is never replayed from the buffer, and one from an abandoned\n * attempt stays in the stream — it describes the sandbox, not the answer.\n */\n liveLifecycleEvents?: boolean\n onFallback?: (info: ModelFallbackInfo) => void\n /**\n * How many times to RE-RUN THE SAME MODEL when a turn completes having\n * produced no assistant text at all. Default `0` — byte-identical to no\n * retry.\n *\n * This is deliberately not a chain walk. Falling over to a different model\n * on an empty answer is the unattributable downgrade this module refuses to\n * do; re-running the SAME model changes nothing about attribution, because\n * the model that serves is the model that was asked for.\n *\n * Bounded by the same commit rule as failover: only a turn whose ONLY\n * committing event is a terminal receipt with no text is retried, so nothing\n * that reached the user can ever be produced twice.\n */\n emptyTurnRetries?: number\n /** Fired when an empty turn is discarded and the same model re-run. */\n onEmptyTurnRetry?: (info: EmptyTurnRetryInfo) => void\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** One same-model re-run of a turn that completed with no assistant text. */\nexport interface EmptyTurnRetryInfo {\n model: string\n /** 1 for the first re-run. */\n retry: number\n /** How many re-runs remain after this one. */\n remaining: number\n}\n\n/** The failover-wrapped stream plus the attribution every consumer needs. */\nexport interface ModelFailoverStreamHandle {\n events: AsyncGenerator<unknown, void, unknown>\n /** The model that actually served. `undefined` until the first pull resolves it. */\n servingModel(): string | undefined\n /** Every model tried, in order, with the reason each was abandoned. */\n attempts(): ModelFailoverAttempt[]\n /** True when the preferred model did not serve — the attributability signal. */\n usedFallback(): boolean\n}\n\n/** Default ceiling for opening/starting one source through its first event. */\nexport const DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS = 120_000\n\n/** Default ceiling for the first answer-bearing event after the source's first event. */\nexport const DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS = 60_000\n\n/** Structured timeout codes surfaced by the producer on final exhaustion. */\nexport type ModelAttemptTimeoutCode =\n | 'model_stream_open_timeout'\n | 'provider_first_response_timeout'\n\n/** Every configured model was exhausted and the final one timed out. */\nexport class ModelFailoverTimeoutError extends ModelFailoverExhaustedError {\n readonly code: ModelAttemptTimeoutCode\n readonly model: string\n readonly timeoutMs: number\n\n constructor(input: {\n attempts: ModelFailoverAttempt[]\n code: ModelAttemptTimeoutCode\n model: string\n timeoutMs: number\n }) {\n super(input.attempts)\n this.name = 'ModelFailoverTimeoutError'\n this.code = input.code\n this.model = input.model\n this.timeoutMs = input.timeoutMs\n this.message = input.code === 'model_stream_open_timeout'\n ? `Opening the model event source for ${input.model} exceeded ${input.timeoutMs}ms.`\n : `Model ${input.model} produced no first answer-bearing event within ${input.timeoutMs}ms.`\n }\n}\n\nfunction resolveTimeoutMs(value: number | undefined, fallback: number, label: string): number {\n if (value === undefined) return fallback\n if (!Number.isFinite(value) || value <= 0) {\n throw new RangeError(`${label} must be a finite number greater than 0`)\n }\n return Math.max(1, Math.trunc(value))\n}\n\nconst TIMED_OUT = Symbol('model-attempt-timed-out')\n\nfunction deadlineAfter(timeoutMs: number): {\n promise: Promise<typeof TIMED_OUT>\n clear: () => void\n} {\n let timer: ReturnType<typeof setTimeout> | undefined\n const promise = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs)\n })\n return {\n promise,\n clear: () => {\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n },\n }\n}\n\n/**\n * True when `event` is a terminal receipt (`result` / `done`) carrying no\n * assistant text.\n *\n * Measured on production `sandbox.tangle.tools` (28 turns through\n * the gtm-agent profile): a turn can end `{ outcome: { type: 'completed' } }`\n * with `finalText: ''` and zero token events — the platform reports success and\n * the customer's message is blank. It is not an outage, nothing throws, and\n * `isUpstreamUnavailable` correctly declines to classify it, so before this the\n * blank answer committed and shipped.\n */\nfunction isEmptyTerminalReceipt(event: unknown): boolean {\n const record = asRecord(event)\n if (!record) return false\n const type = asString(record.type) ?? ''\n if (type !== 'result' && type !== 'done') return false\n const data = asRecord(record.data)\n const text = asString(data?.finalText) ?? asString(data?.text) ?? ''\n return text.trim().length === 0\n}\n\n/**\n * Hard ceiling on same-model re-runs. A turn that comes back blank three times\n * running is not a flake this can retry away, and each pass costs a full\n * sandbox turn — so the budget is capped rather than trusted.\n */\nexport const MAX_EMPTY_TURN_RETRIES = 3\n\n/**\n * Coerce the caller's budget to a finite, bounded, non-negative integer.\n *\n * `Math.trunc(NaN)` is `NaN` and `retry >= NaN` is false for every `retry`, so\n * a naive clamp turns a bad config value into a loop that opens sandbox streams\n * until the worker dies. `Infinity` has the same shape. Both resolve to `0` —\n * an unusable budget disables the retry rather than running unbounded.\n */\nexport function resolveEmptyTurnRetries(value: number | undefined): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return 0\n const truncated = Math.trunc(value)\n if (truncated <= 0) return 0\n return Math.min(truncated, MAX_EMPTY_TURN_RETRIES)\n}\n\n/** Abandon a dead attempt's iterator. Never allowed to mask the outage. */\nasync function closeIterator(iterator: AsyncIterator<unknown>, log?: ModelFailoverStreamOptions['log']): Promise<void> {\n try {\n await iterator.return?.()\n } catch (err) {\n log?.('[chat-routes] abandoning a failed model stream threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n}\n\n/**\n * Wrap `open` in reactive model failover, streaming from the first model in\n * `models` that reaches its commit point.\n *\n * Zero added latency on the happy path: the preferred model is opened first and,\n * the moment it emits anything meaningful, its events flow straight through.\n *\n * @throws ModelFailoverTimeoutError when the final model times out,\n * ModelFailoverExhaustedError when every model's upstream is down, and\n * re-throws a non-outage error from the FIRST model without walking the\n * chain (the latter behaviors are inherited from\n * `runWithModelFailover`).\n */\nexport function streamWithModelFailover(\n options: ModelFailoverStreamOptions,\n): ModelFailoverStreamHandle {\n const committing = options.isCommitting ?? isCommittingSandboxEvent\n const emptyTurnRetries = resolveEmptyTurnRetries(options.emptyTurnRetries)\n const openTimeoutMs = resolveTimeoutMs(\n options.openTimeoutMs,\n DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS,\n 'openTimeoutMs',\n )\n const firstResponseTimeoutMs = resolveTimeoutMs(\n options.firstResponseTimeoutMs,\n DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS,\n 'firstResponseTimeoutMs',\n )\n const liveLifecycle = options.liveLifecycleEvents === true\n const progress = createProgressQueue()\n let serving: string | undefined\n let trail: ModelFailoverAttempt[] = []\n let fellBack = false\n const attemptState = { index: 0 }\n let finalTimeout: {\n code: ModelAttemptTimeoutCode\n model: string\n timeoutMs: number\n } | undefined\n\n /**\n * One open-and-drain pass. `empty` marks the pass as an EMPTY TURN — the\n * only committing event was a terminal receipt with no assistant text, so\n * nothing reached the user and the pass can be discarded without any risk of\n * producing an answer twice. It still carries the outcome it would otherwise\n * have returned, so exhausting the retry budget is byte-identical to no\n * retry at all.\n */\n const { drainOnce } = createModelAttemptDrainer(attemptState, options, openTimeoutMs, firstResponseTimeoutMs, committing, liveLifecycle, progress)\n\n const probe = async (model: string): Promise<AttemptOutcome> => {\n // Only the FINAL attempted model decides the exhaustion code. Clear a\n // prior model's timeout before this model can throw a different outage.\n finalTimeout = undefined\n for (let retry = 0; ; retry += 1) {\n const pass = await drainOnce(model)\n if (!pass.empty || retry >= emptyTurnRetries) {\n if (!pass.outcome.committed && pass.outcome.timeoutCode) {\n finalTimeout = {\n code: pass.outcome.timeoutCode,\n model,\n timeoutMs: pass.outcome.timeoutCode === 'model_stream_open_timeout'\n ? openTimeoutMs\n : firstResponseTimeoutMs,\n }\n } else {\n finalTimeout = undefined\n }\n return pass.outcome\n }\n // Discard the empty pass entirely — including its `step-finish` token\n // receipt, which must not be billed — and re-run the same model.\n const iterator = pass.outcome.committed ? pass.outcome.iterator : null\n if (pass.outcome.committed) pass.outcome.abort()\n if (iterator) void closeIterator(iterator, options.log)\n const info: EmptyTurnRetryInfo = { model, retry: retry + 1, remaining: emptyTurnRetries - retry - 1 }\n options.log?.('[chat-routes] turn completed with no assistant text; re-running the same model', {\n ...info,\n })\n options.onEmptyTurnRetry?.(info)\n }\n }\n\n const events = (async function* (): AsyncGenerator<unknown, void, unknown> {\n let handle: AttemptCommit\n // Progress arrives while the probe is still running. The queue closes only\n // after the verdict settles, so every event pushed before it is delivered\n // in order and ahead of the replayed buffer.\n const settled = runWithModelFailover<AttemptOutcome>({\n models: options.models,\n run: probe,\n ...(options.policy ? { policy: options.policy } : {}),\n // The probe has already classified the raw payload with\n // `isUpstreamUnavailable`; this reads its verdict rather than\n // re-classifying a wrapper object, so the two can never disagree.\n isUnavailableResult: (result) => result.committed === false,\n onFallback: (attempt, nextModel) => {\n const info: ModelFallbackInfo = {\n from: attempt.model,\n to: nextModel,\n reason: attempt.reason ?? 'upstream unavailable',\n }\n options.log?.('[chat-routes] model upstream unavailable; falling over', { ...info })\n options.onFallback?.(info)\n },\n }).finally(() => progress.close())\n // The verdict is read after the drain; mark the rejection handled until then.\n settled.catch(() => undefined)\n for (;;) {\n const item = await progress.pull()\n if (item === PROGRESS_CLOSED) break\n yield item\n }\n try {\n const outcome = await settled\n serving = outcome.model\n trail = outcome.attempts\n fellBack = outcome.usedFallback\n handle = outcome.value as AttemptCommit\n } catch (err) {\n // Exhaustion carries the full trail; keep it so the receipt still names\n // every model tried even though the turn produced nothing.\n const attempts = (err as { attempts?: ModelFailoverAttempt[] })?.attempts\n if (Array.isArray(attempts)) trail = attempts\n if (err instanceof ModelFailoverExhaustedError && finalTimeout) {\n throw new ModelFailoverTimeoutError({\n attempts: trail,\n ...finalTimeout,\n })\n }\n throw err\n }\n\n for (const event of handle.buffered) yield event\n\n const live = handle.iterator\n if (!live) {\n handle.abort()\n return\n }\n try {\n for (;;) {\n const next = await live.next()\n if (next.done) return\n yield next.value\n }\n } finally {\n // The consumer may abandon this generator mid-turn (client drop); close\n // the underlying stream rather than leaking it.\n handle.abort()\n await closeIterator(live, options.log)\n }\n })()\n\n return {\n events,\n servingModel: () => serving,\n attempts: () => trail,\n usedFallback: () => fellBack,\n }\n}\n\nconst PROGRESS_CLOSED: unique symbol = Symbol('progress-closed')\n\n/**\n * FIFO handoff from the probe (a plain promise chain) to the event generator.\n * `close` is idempotent and queues one sentinel behind everything pushed\n * before it, so a consumer never loses a progress event to the verdict.\n */\nfunction createProgressQueue(): {\n push(event: unknown): void\n close(): void\n pull(): Promise<unknown>\n} {\n const items: unknown[] = []\n const waiters: Array<(value: unknown) => void> = []\n let closed = false\n const deliver = (value: unknown): void => {\n const waiter = waiters.shift()\n if (waiter) waiter(value)\n else items.push(value)\n }\n return {\n push(event) {\n if (closed) return\n deliver(event)\n },\n close() {\n if (closed) return\n closed = true\n deliver(PROGRESS_CLOSED)\n },\n pull() {\n if (items.length > 0) return Promise.resolve(items.shift())\n if (closed) return Promise.resolve(PROGRESS_CLOSED)\n return new Promise((resolve) => waiters.push(resolve))\n },\n }\n}\n\nfunction createModelAttemptDrainer(\n attemptState: { index: number },\n options: ModelFailoverStreamOptions,\n openTimeoutMs: ReturnType<typeof resolveTimeoutMs>,\n firstResponseTimeoutMs: ReturnType<typeof resolveTimeoutMs>,\n committing: (event: unknown) => boolean,\n liveLifecycle: boolean,\n progress: ReturnType<typeof createProgressQueue>,\n) {\n const drainOnce = async (model: string): Promise<{ outcome: AttemptOutcome; empty: boolean }> => {\n attemptState.index += 1\n const controller = new AbortController()\n const abort = (): void => {\n if (!controller.signal.aborted) controller.abort()\n }\n const opening = Promise.resolve().then(() => options.open({\n model,\n attempt: attemptState.index,\n signal: controller.signal,\n }))\n const openDeadline = deadlineAfter(openTimeoutMs)\n let opened: AsyncIterable<unknown> | typeof TIMED_OUT\n try {\n opened = await Promise.race([opening, openDeadline.promise])\n } catch (err) {\n openDeadline.clear()\n abort()\n throw err\n }\n if (opened === TIMED_OUT) {\n openDeadline.clear()\n abort()\n // A Promise cannot be forcibly cancelled. If the abandoned open settles\n // later, close its iterator immediately so it cannot leak a connection.\n void opening.then(\n (lateSource) => {\n try {\n void closeIterator(lateSource[Symbol.asyncIterator](), options.log)\n } catch (err) {\n options.log?.('[chat-routes] closing a late model stream threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n (err) => {\n options.log?.('[chat-routes] abandoned model stream open rejected after timeout', {\n error: err instanceof Error ? err.message : String(err),\n })\n },\n )\n return {\n outcome: {\n committed: false,\n error: `Opening the model event source for ${model} exceeded ${openTimeoutMs}ms`,\n errorCode: 'model_stream_open_timeout',\n timeoutCode: 'model_stream_open_timeout',\n },\n empty: false,\n }\n }\n\n const source = opened\n let iterator: AsyncIterator<unknown>\n try {\n iterator = source[Symbol.asyncIterator]()\n } catch (err) {\n openDeadline.clear()\n abort()\n throw err\n }\n const buffered: unknown[] = []\n // Starting the source includes its first pull. `streamSandboxPrompt` is an\n // async generator, so its cold-start work does not execute until `next()`;\n // counting that time as provider inference would collapse the two phases.\n let next: IteratorResult<unknown> | typeof TIMED_OUT\n try {\n next = await Promise.race([\n Promise.resolve(iterator.next()),\n openDeadline.promise,\n ])\n } catch (err) {\n openDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n openDeadline.clear()\n if (next === TIMED_OUT) {\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: `Starting the model event source for ${model} exceeded ${openTimeoutMs}ms`,\n errorCode: 'model_stream_open_timeout',\n timeoutCode: 'model_stream_open_timeout',\n },\n empty: false,\n }\n }\n if (next.done) {\n abort()\n return { outcome: { committed: true, buffered, iterator: null, abort }, empty: true }\n }\n\n // One deadline for the WHOLE provider pre-response phase. Pulling a\n // lifecycle or processing event races the same promise; liveness cannot\n // reset the clock.\n const firstResponseDeadline = deadlineAfter(firstResponseTimeoutMs)\n\n for (;;) {\n const event = next.value\n let failure: TerminalFailure | null\n let commits = false\n try {\n failure = classifyTerminalFailure(event)\n commits = !failure && committing(event)\n } catch (err) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n if (failure?.outage) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: failure.reason,\n ...(failure.code ? { errorCode: failure.code } : {}),\n },\n empty: false,\n }\n }\n\n if (liveLifecycle && !failure && !commits && isLiveLifecycleEvent(event)) {\n progress.push(event)\n } else {\n buffered.push(event)\n }\n // A terminal NON-outage failure surfaces exactly as it does today.\n if (failure) {\n firstResponseDeadline.clear()\n return { outcome: { committed: true, buffered, iterator, abort }, empty: false }\n }\n if (commits) {\n firstResponseDeadline.clear()\n return { outcome: { committed: true, buffered, iterator, abort }, empty: isEmptyTerminalReceipt(event) }\n }\n\n // A THROWN failure propagates untouched: `runWithModelFailover` classifies\n // it (outage → next model, anything else → re-thrown to the caller).\n try {\n next = await Promise.race([\n Promise.resolve(iterator.next()),\n firstResponseDeadline.promise,\n ])\n } catch (err) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n if (next === TIMED_OUT) {\n firstResponseDeadline.clear()\n // Do not await `return()`: an async generator blocked inside `next()`\n // may not settle its return until that pull completes. Invoking it is\n // the cancellation signal; waiting for it would recreate the hang.\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: `Model ${model} produced no first answer-bearing event within ${firstResponseTimeoutMs}ms`,\n errorCode: 'provider_first_response_timeout',\n timeoutCode: 'provider_first_response_timeout',\n },\n empty: false,\n }\n }\n if (next.done) {\n firstResponseDeadline.clear()\n abort()\n // Clean end with nothing committing. Not an outage — but also not an\n // answer, so it is re-runnable on the same model.\n return { outcome: { committed: true, buffered, iterator: null, abort }, empty: true }\n }\n }\n }\n return { drainOnce }\n}\n","import type { SandboxChatProducerOptions } from './sandbox-producer'\nimport type { ChatTurnModelAttribution } from './turn-routes'\nimport { asRecord, asString, type JsonRecord } from '../stream/index'\nimport { buildModelChain } from '../model-resolution/failover'\nimport { streamWithModelFailover, resolveEmptyTurnRetries, summarizeFailoverReason, type ModelFailoverStreamHandle } from './model-failover-stream'\n\nfunction parseEffectiveBackend(data: JsonRecord): Omit<\n ChatTurnModelAttribution,\n 'requestedModel' | 'echoReceived'\n> | undefined {\n const backend = asRecord(data.effectiveBackend)\n if (!backend) return undefined\n const provider = asString(backend.provider)\n const model = asString(backend.model)\n const rawSource = asString(backend.source)\n const source =\n rawSource === 'request' || rawSource === 'environment' || rawSource === 'profile'\n ? rawSource\n : undefined\n if (!provider && !model && !source) return undefined\n return {\n ...(model ? { servedModel: model } : {}),\n ...(provider ? { servedProvider: provider } : {}),\n ...(source ? { servedSource: source } : {}),\n }\n}\n\nexport function createSandboxModelSource(options: SandboxChatProducerOptions, log: (message: string, meta?: Record<string, unknown>) => void) {\n if (options.openEvents && !options.model) {\n throw new Error(\n 'createSandboxChatProducer: `openEvents` requires `model` — failover must know which model it is running',\n )\n }\n if (!options.openEvents && !options.events) {\n throw new Error('createSandboxChatProducer: pass `openEvents` (failover-capable) or `events`')\n }\n // A fixed `events` stream cannot be re-opened, so the retry silently does\n // nothing. A config that asks for recovery and receives none is the exact\n // silent-no-op class this seam exists to remove — refuse it at construction\n // rather than let a product believe blank turns are being retried.\n if (!options.openEvents && resolveEmptyTurnRetries(options.emptyTurnRetries) > 0) {\n throw new Error(\n 'createSandboxChatProducer: `emptyTurnRetries` requires `openEvents` — a fixed `events` stream cannot be re-opened',\n )\n }\n const chain = options.model\n ? buildModelChain(options.model, options.modelFailover === false ? [] : (options.fallbackModels ?? []))\n : []\n\n /** Fallback notices waiting to be emitted. `onFallback` fires from inside the\n * first pull of the failover stream, where a generator cannot yield, so the\n * notice is queued and drained at the top of the next loop iteration —\n * landing immediately before the serving model's first event. */\n const pendingModelNotices: Array<{ id: string; text: string }> = []\n let modelNoticeCount = 0\n\n let openAttempts = 0\n let failover: ModelFailoverStreamHandle | undefined\n let source: AsyncIterable<unknown>\n if (options.openEvents) {\n const open = options.openEvents\n failover = streamWithModelFailover({\n models: chain,\n open: args => { openAttempts += 1; return open(args) },\n log,\n ...(options.modelPolicy ? { policy: options.modelPolicy } : {}),\n ...(options.openTimeoutMs !== undefined ? { openTimeoutMs: options.openTimeoutMs } : {}),\n ...(options.firstResponseTimeoutMs !== undefined\n ? { firstResponseTimeoutMs: options.firstResponseTimeoutMs }\n : {}),\n ...(options.emptyTurnRetries !== undefined ? { emptyTurnRetries: options.emptyTurnRetries } : {}),\n ...(options.onEmptyTurnRetry ? { onEmptyTurnRetry: options.onEmptyTurnRetry } : {}),\n ...(options.liveLifecycleEvents !== undefined ? { liveLifecycleEvents: options.liveLifecycleEvents } : {}),\n onFallback: (info) => {\n modelNoticeCount += 1\n pendingModelNotices.push({\n id: `model-fallback-${modelNoticeCount}`,\n // Named models on both sides: a quality regression after a downgrade\n // must be attributable to the model that actually answered. The\n // REASON is condensed — a real edge 5xx arrives as Cloudflare's HTML\n // error page, and the raw text put `<!DOCTYPE html><!--[if lt IE 7]>…`\n // into the customer's transcript. The verbatim text is still on\n // `modelFailover.attempts[].reason` for the operator.\n text: `${info.from} was unavailable (${summarizeFailoverReason(info.reason)}) — answered with ${info.to} instead.`,\n })\n options.onModelFallback?.(info)\n },\n })\n source = failover.events\n } else {\n source = options.events!\n }\n\n /** The model that ACTUALLY served this turn. Read lazily everywhere (the\n * `model` getter, the draft snapshot, the persisted row) so a fallback that\n * happens after the row was drafted still lands on the final write. */\n const servingModel = (): string | undefined => failover?.servingModel() ?? options.model\n const modelState = { effectiveBackend: undefined as ReturnType<typeof parseEffectiveBackend> }\n let substitutionNoticeQueued = false\n const servedModel = (): string | undefined => modelState.effectiveBackend?.servedModel ?? servingModel()\n\n const captureEffectiveBackend = (data: JsonRecord | undefined): void => {\n if (!data) return\n const parsed = parseEffectiveBackend(data)\n if (!parsed) return\n modelState.effectiveBackend = parsed\n const sentModel = servingModel()\n if (\n substitutionNoticeQueued ||\n !options.model ||\n !sentModel ||\n !parsed.servedModel ||\n sameModel(parsed.servedModel, sentModel)\n ) return\n substitutionNoticeQueued = true\n pendingModelNotices.push({\n id: 'model-substitution-1',\n text: `Requested ${sentModel} — the sandbox answered with ${parsed.servedModel} instead.`,\n })\n }\n return { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState, openAttempts: () => openAttempts }\n}\n\n/** The same model under a provider prefix (`zai-coding-plan/glm-5.3-flash` vs\n * `glm-5.3-flash`) is not a substitution; only a different model is. */\nfunction sameModel(a: string, b: string): boolean {\n const bare = (id: string) => id.slice(id.lastIndexOf('/') + 1).trim().toLowerCase()\n return bare(a) === bare(b)\n}\n","/**\n * Sandbox lane: bridge a raw sandbox event stream (`streamSandboxPrompt`) into\n * the `ChatTurnProducer` shape agent-runtime's `handleChatTurn` consumes AND\n * the client vocabulary `/web-react`'s `dispatchChatStreamLine` already parses\n * (`text` / `reasoning` / `tool_call` / `tool_result` / `usage` /\n * `notice` / structured `error` / `interaction`). Legal and tax each hand-rolled\n * this mapping differently;\n * this is that middle, composed from `/stream`'s normalizers — no new loop\n * logic, no SDK import (the event source is an injected `AsyncIterable`).\n *\n * Alongside the live mapping it accumulates the PERSISTED projection — the\n * `message.parts` rows `/chat-store` stores — via `normalizePersistedPart` /\n * `mergePersistedPart` / `finalizeAssistantParts`, plus the usage receipt from\n * `step-finish` parts. `createChatTurnRoutes` reads both after drain.\n */\n\nimport { createSandboxModelSource } from './sandbox-model-source'\n\nimport {\n cancelStatusFor,\n interactionPartKey,\n interactionToPersistedPart,\n isRenderableInteractionKind,\n noticePart,\n noticePartKey,\n parseInteractionCancel,\n parseInteractionRequest,\n type InteractionRequestWire,\n} from '../interactions/contract'\nimport {\n parsePlanSubmittedEvent,\n planToPersistedPart,\n} from '../plans/index'\nimport {\n asRecord,\n asString,\n draftAssistantParts,\n finalizeAssistantParts,\n finalizePendingInteractionParts,\n getPartKey,\n mergePersistedPart,\n normalizePersistedPart,\n normalizeToolEvent,\n terminalizeDanglingAssistantToolUpdates,\n type JsonRecord,\n type StreamEvent,\n} from '../stream/index'\nimport {\n ModelFailoverExhaustedError,\n type ModelFailoverAttempt,\n} from '../model-resolution/failover'\nimport type { ModelPolicy } from '../policy-filters/index'\nimport { isTerminalPromptEvent } from '../sandbox/prompt-events'\nimport { SandboxRunError } from '../sandbox/sandbox-run-error'\nimport {\n ModelFailoverTimeoutError,\n type EmptyTurnRetryInfo,\n type ModelFallbackInfo,\n type OpenModelStream,\n} from './model-failover-stream'\nimport { createReasoningClock, type ReasoningRunTime } from './reasoning-clock'\nimport type {\n ChatTurnRouteProducer,\n ChatTurnUsage,\n} from './turn-routes'\nimport { addStepFinishUsage } from './sandbox-turn-usage'\nimport type { ProducerWireEvent } from './wire'\n\n/** Outcome of a `promoteFilePart` attempt. `key`, when given, becomes the\n * persisted part's row key (e.g. `attachment:<path>`) so repeat promotions\n * of the same underlying file fold into one segment instead of appending;\n * omitted, the default `getPartKey` keying applies.\n *\n * On failure, `part` is an OPTIONAL substitute part to persist in place of\n * the raw url-bearing one — this is how a product swaps in a transcript\n * notice (gtm persists a `warning` notice part, never the transient url) for\n * a failed promotion instead of baking a `data:`/sandbox-path url into the\n * durable row. When `part` is present it is persisted (via the same\n * `recordPersistedPart` path as a success, honoring the optional `key`);\n * when absent, the existing raw-part fallback applies unchanged — so a\n * caller that only returns `{ succeeded: false, reason }` keeps today's\n * behavior verbatim. */\nexport type FilePartPromotionOutcome =\n | { succeeded: true; part: Record<string, unknown>; key?: string }\n | { succeeded: false; reason: string; part?: Record<string, unknown>; key?: string }\n\n/** Define options for producing sandbox chat events with rendering and interaction controls */\nexport interface SandboxChatProducerOptions {\n /** The raw sandbox event stream (e.g. `streamSandboxPrompt(...)`).\n *\n * An ALREADY-OPEN stream is bound to one model and cannot be reopened, so\n * this form can never fail over. Prefer {@link openEvents}; exactly one of\n * the two is required. */\n events?: AsyncIterable<unknown>\n /** Open the raw sandbox stream FOR A GIVEN MODEL — the failover-capable form\n * of {@link events}. The callback receives the model to run and returns the\n * same `AsyncIterable` `events` would have been (typically\n * `streamSandboxPrompt(shell, box, prompt, { ...opts, model })`).\n *\n * Wiring this turns failover ON with no further flag: whenever the resolved\n * chain (`model` + {@link fallbackModels}) holds more than one entry, a model\n * whose upstream is dead is abandoned BEFORE its first client-visible byte\n * and the next one is tried. A one-entry chain opens exactly once — no extra\n * call, no added latency, byte-identical to today.\n *\n * Requires {@link model}: failover has to know which model it is running. */\n openEvents?: OpenModelStream\n /** Recorded on the persisted assistant message. When failover moves the turn\n * to another model, the producer's `model` reports the model that ACTUALLY\n * served, not this preferred one — see {@link modelFailover}. */\n model?: string\n /** Models to try, in order, when `model`'s upstream is dead. Product config,\n * never a shell default: agent-app cannot know which ids are live, and a\n * baked list would rot into exactly the stale-liveness bug this guards\n * against. Empty/omitted → one attempt, today's behavior.\n *\n * Pick these deliberately. A same-family fallback is NOT automatically safe:\n * `gemini-2.5-flash` produced zero persisted deliverables in 2 of 3 measured\n * runs on a med-legal filing flow where `gemini-2.5-pro` succeeded. That is\n * why every fallback is surfaced (persisted `model`, a transcript notice, and\n * `modelFailover()`) instead of being applied silently. */\n fallbackModels?: readonly string[]\n /** Opt out of failover while still using {@link openEvents}. `false` collapses\n * the chain to `model` alone. */\n modelFailover?: false\n /**\n * Product admission policy applied to every chain member — the RESOLVED\n * preferred model AND every fallback — before its stream is opened. This is\n * the execution-time half of policy enforcement: it covers the model\n * whatever its source (request body, env, product default), and it is what\n * stops a compliant model's mid-turn 502 from re-running the turn's data\n * through a non-compliant fallback. A refused member is skipped with the\n * refusal recorded in `modelFailover().attempts`; an all-refused chain\n * exhausts. Omit → availability only (today's behavior).\n */\n modelPolicy?: ModelPolicy\n /** Maximum time to open/start one model event source through its first event.\n * Default 120 seconds. This is separate from provider first-output latency\n * so cold sandbox startup is not mislabeled as an inference failure. */\n openTimeoutMs?: number\n /** Hard deadline after the source's first lifecycle event for the first\n * answer-bearing event. Default 60 seconds. Processing/lifecycle events do\n * not extend it. */\n firstResponseTimeoutMs?: number\n /** Forward `start`/`status`/`model-processing`/session lifecycle to the\n * client as it arrives instead of after the commit point, so a product can\n * show what a turn is waiting on. Default `false`. An abandoned model's\n * progress then stays on the wire; its answer and receipt never do. */\n liveLifecycleEvents?: boolean\n /** Fired when a model is abandoned mid-chain (telemetry/alerting). The user\n * already sees a transcript notice; this is for the operator. */\n onModelFallback?: (info: ModelFallbackInfo) => void\n /** Re-run the SAME model this many times when a turn completes with no\n * assistant text at all. Default `0` (unchanged behavior). Requires\n * {@link openEvents} — there is nothing to re-open on a fixed stream.\n *\n * Distinct from {@link fallbackModels} on purpose: this never changes which\n * model answers, so it carries none of the attribution risk a downgrade\n * does. Measured on production 2026-07-27 through gtm-agent's profile, a\n * completed-but-blank turn is a transient platform flake — 8 hard cases went\n * 7/8 delivered to 8/8 with one re-run, costing 1 extra turn in 9. */\n emptyTurnRetries?: number\n /** Fired when a blank turn is discarded and the same model re-run. */\n onEmptyTurnRetry?: (info: EmptyTurnRetryInfo) => void\n /** Which ask kinds the product renders a card for. Anything else is\n * auto-declined (see `declineInteraction`) so the run never hangs in the\n * broker waiting on a card no client will show. Default: question/plan.\n * Products with per-turn plan mode can close over it without another option:\n * `(kind) => kind === 'question' || (kind === 'plan' && planEnabled)`.\n * The parsed request lets a product decline an ask by its content, such\n * as a question that duplicates a decision the product already shows. */\n isRenderableInteraction?: (kind: string, request: InteractionRequestWire) => boolean\n /** The transcript notice for an auto-declined ask; defaults to a policy line naming its kind. */\n declinedNotice?: (request: InteractionRequestWire, declineFailed: boolean) => string\n /** Resolve a non-renderable ask (wire `respondToSessionInteraction` with the\n * session's sidecar connection). Without it, a failure notice is emitted and\n * the run stays blocked until the broker times out. */\n declineInteraction?: (id: string) => Promise<void>\n /** Opt-in eager promotion of harness-emitted `file` parts. Unset, a `file`\n * part persists exactly as the harness sent it — a transient `url` (a\n * `data:` URI or in-sandbox path) baked into the transcript, which is\n * today's behavior and stays byte-identical if this is never wired. Set,\n * EVERY `file` part (never `image`, never any other kind) is routed\n * through this callback instead of `recordPersistedPart`'s default\n * fallback — including a part with NEITHER `id` NOR `url` (gtm always\n * attempts promotion; such a part simply fails \"carries no url\" and\n * resolves through the same failure path as any other rejection, rather\n * than being persisted raw and unpromoted) — so the product can durably\n * write the bytes and swap in a path-bearing part before the raw url ever\n * reaches the persisted transcript. Keyed per source-prefixed `id:<id>` /\n * `url:<url>` (an `id` and a `url` sharing the same text must never collide\n * onto one memo entry) and memoized by PROMISE (not result), so re-emitted\n * snapshot events for the same part —\n * the harness resends the whole part on every update, not just deltas —\n * fold onto the one in-flight or settled attempt rather than promoting\n * twice or racing two concurrent writes; a raw part with neither `id` nor\n * `url` cannot be keyed, so it is invoked UN-memoized (once per event) —\n * each occurrence is its own attempt. A rejecting promise is caught,\n * logged via `log`, and treated as `succeeded: false`. On `succeeded:\n * false` the outcome's optional `part` (a substitute — e.g. a warning\n * notice — see {@link FilePartPromotionOutcome}) persists in its place when\n * given; otherwise the raw part persists exactly as it does today — this\n * seam only decides whether to call the promoter and what to do with its\n * outcomes; the promotion mechanics (vault write, key derivation, notice\n * construction) live in the caller's callback, not here. */\n promoteFilePart?: (raw: JsonRecord) => Promise<FilePartPromotionOutcome>\n /** Append terminal error explanations to assistant text. Default true.\n * Set false when the application renders the structured error separately.\n * Error events, diagnostics, partial answers and tool settlement remain available. */\n includeErrorText?: boolean\n /** Record the terminal error explanation as an `error` notice part (persisted\n * on the assistant row and streamed as a `notice` event) instead of appending\n * it to the assistant text. A reloaded failed turn then carries a typed marker\n * a client renders in the danger tone, rather than prose indistinguishable\n * from the answer. Default false (today's text behavior). When true, the\n * error is never appended to the text, whatever `includeErrorText` says. */\n errorNotice?: boolean\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\ninterface TextTracker {\n /** Full accumulated text per part key, to derive suffix deltas from\n * snapshot-only harness events. */\n seen: Map<string, string>\n}\n\n/** Delta to emit for one text/reasoning part update: prefer the harness's\n * explicit delta; otherwise diff the snapshot against what was already\n * emitted for that part (snapshot-only harnesses re-send the whole text). */\nfunction textDelta(tracker: TextTracker, key: string, part: JsonRecord, rawDelta: unknown): string {\n const explicit = typeof rawDelta === 'string' ? rawDelta : undefined\n const previous = tracker.seen.get(key) ?? ''\n if (explicit !== undefined) {\n tracker.seen.set(key, previous + explicit)\n return explicit\n }\n const snapshot = asString(part.text) ?? asString(part.content) ?? ''\n if (!snapshot) return ''\n if (snapshot.startsWith(previous)) {\n tracker.seen.set(key, snapshot)\n return snapshot.slice(previous.length)\n }\n // The snapshot replaced the text outright — emit it whole; the persisted\n // projection stays correct because finalText is authoritative at finalize.\n tracker.seen.set(key, snapshot)\n return snapshot\n}\n\nfunction toFiniteNumber(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n return null\n}\n\n/** Parse authoritative usage from a terminal sandbox `result` or `done`. */\nfunction extractReportedTurnUsage(data: JsonRecord | null | undefined): ChatTurnUsage | null {\n const tokenUsage = asRecord(data?.tokenUsage)\n if (!tokenUsage) return null\n\n const inputTokens = toFiniteNumber(tokenUsage.inputTokens)\n const outputTokens = toFiniteNumber(tokenUsage.outputTokens)\n if (inputTokens === null || outputTokens === null) return null\n\n const reported: ChatTurnUsage = { inputTokens, outputTokens }\n const reasoningTokens = toFiniteNumber(tokenUsage.reasoningTokens)\n if (reasoningTokens !== null) reported.reasoningTokens = reasoningTokens\n const cacheReadTokens = toFiniteNumber(tokenUsage.cacheReadInputTokens)\n if (cacheReadTokens !== null) reported.cacheReadTokens = cacheReadTokens\n const cacheWriteTokens = toFiniteNumber(tokenUsage.cacheCreationInputTokens)\n if (cacheWriteTokens !== null) reported.cacheWriteTokens = cacheWriteTokens\n const costUsd = toFiniteNumber(data?.totalCostUsd) ?? toFiniteNumber(tokenUsage.cost)\n if (costUsd !== null) reported.costUsd = costUsd\n return reported\n}\n\n/** Native runtime usage events contain cumulative totals, including repeated terminal snapshots. */\nfunction extractUsageSnapshot(value: JsonRecord | null | undefined): ChatTurnUsage | null {\n const inputTokens = toFiniteNumber(value?.promptTokens)\n const outputTokens = toFiniteNumber(value?.completionTokens)\n if (inputTokens === null || outputTokens === null || inputTokens < 0 || outputTokens < 0) return null\n const reported: ChatTurnUsage = { inputTokens, outputTokens }\n const reasoningTokens = toFiniteNumber(value?.reasoningTokens)\n if (reasoningTokens !== null && reasoningTokens >= 0) reported.reasoningTokens = reasoningTokens\n const costUsd = toFiniteNumber(value?.providerCostUsd)\n if (costUsd !== null && costUsd >= 0) reported.costUsd = costUsd\n return reported\n}\n\nfunction applyTerminalUsage(reported: ChatTurnUsage, usage: ChatTurnUsage): void {\n usage.inputTokens = reported.inputTokens\n usage.outputTokens = reported.outputTokens\n if (reported.reasoningTokens !== undefined) usage.reasoningTokens = reported.reasoningTokens\n if (reported.cacheReadTokens !== undefined) usage.cacheReadTokens = reported.cacheReadTokens\n if (reported.cacheWriteTokens !== undefined) usage.cacheWriteTokens = reported.cacheWriteTokens\n if (reported.costUsd !== undefined) usage.costUsd = reported.costUsd\n}\n\nfunction sandboxStreamErrorMessage(data: unknown): string {\n const record = asRecord(data)\n const message = asString(record?.message) ?? asString(record?.error)\n if (message) return message\n try {\n return JSON.stringify(data) || 'Sandbox stream returned an error event without details.'\n } catch {\n return 'Sandbox stream returned an error event without details.'\n }\n}\n\n/** The typed reason a sandbox `error` event carries, or a generic stream-error code. */\nfunction sandboxStreamErrorCode(data: unknown): string {\n return asString(asRecord(data)?.code) ?? 'sandbox.stream_error'\n}\n\nfunction toProducerWireEvent(event: JsonRecord): ProducerWireEvent {\n return event as unknown as ProducerWireEvent\n}\n\nfunction sandboxStreamFailureDiagnostic(error: unknown): {\n userMessage: string\n failureNote: string\n code: string\n} {\n const streamMessage = (error as { streamMessage?: unknown })?.streamMessage\n const message = typeof streamMessage === 'string'\n ? streamMessage\n : error instanceof Error ? error.message : 'Sandbox stream failed'\n const diagnostics = asRecord((error as { diagnostics?: unknown })?.diagnostics)\n let diagnosticText: string | undefined\n if (diagnostics) {\n try {\n diagnosticText = JSON.stringify(diagnostics)\n } catch {\n diagnosticText = '[unserializable diagnostics]'\n }\n }\n const userMessage = [\n 'The sandbox model stream stopped before a clean completion.',\n `Error: ${message}`,\n 'Please retry. If it repeats, send these support details to the team.',\n ].join('\\n\\n')\n const failureNote = diagnosticText\n ? `sandbox-stream: ${message}; ${diagnosticText}`\n : `sandbox-stream: ${message}`\n let code = 'sandbox.stream_failed'\n if (error instanceof SandboxRunError) {\n code = error.code\n } else if (error instanceof ModelFailoverTimeoutError) {\n code = error.code\n } else if (error instanceof ModelFailoverExhaustedError) {\n code = error.upstreamCode ?? code\n }\n return { userMessage, failureNote, code }\n}\n\n/** Create a sandbox chat producer that manages chat turn routing with logging and interaction rendering options */\nexport function createSandboxChatProducer(options: SandboxChatProducerOptions): ChatTurnRouteProducer {\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind\n\n // ── model failover ────────────────────────────────────────────────────────\n // ON by default whenever the caller can reopen the stream (`openEvents`) and\n // named more than one model. There is no `enabled` flag on purpose: the class\n // of failure this fixes was a capability that shipped switched off, and a\n // second opt-in on top of supplying the chain would reproduce it exactly.\n const { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState, openAttempts } = createSandboxModelSource(options, log)\n\n const projectionState: SandboxProjectionState = {\n fullText: '',\n terminalObserved: false,\n stepCounter: 0,\n danglingToolsTerminalized: false,\n interactionOutcome: 'answered',\n warningCount: 0,\n errorNoticeCount: 0,\n }\n\n const { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder } = createSandboxProjection(projectionState, pendingModelNotices)\n\n let observedSourceEvent = false\n let preflightRefused = false\n async function* stream(): AsyncGenerator<ProducerWireEvent, void, unknown> {\n try {\n for await (const raw of source) {\n observedSourceEvent = true\n const record = asRecord(raw)\n captureEffectiveBackend(asRecord(record?.data))\n yield* drainModelNotices()\n if (!record || typeof record.type !== 'string') continue\n // Fold bare tool_call/tool_result shapes into the canonical part event;\n // everything else keeps its original record (verbatim forwarding must\n // not strip fields outside `data`).\n const normalized = normalizeToolEvent({ type: record.type, data: asRecord(record.data) })\n const event: StreamEvent = normalized.type === 'message.part.updated'\n ? normalized\n : { type: record.type, data: asRecord(record.data) }\n\n if (event.type === 'message.part.updated') {\n yield* projectSandboxMessagePart(event, tracker, recordPersistedPart, reasoningClock, projectionState, partMap, announcedToolArgs, settledTools, usage, options, log, promotedFileParts)\n continue\n }\n\n if (event.type === 'interaction') {\n const parsed = parseInteractionRequest(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction event', { error: parsed.error })\n continue\n }\n if (renderable(parsed.value.kind, parsed.value)) {\n recordPersistedPart(\n interactionToPersistedPart(parsed.value, 'pending'),\n undefined,\n interactionPartKey(parsed.value.id),\n )\n yield toProducerWireEvent(record)\n continue\n }\n // Non-renderable ask: the run is blocked in the broker until someone\n // answers. Decline it so the turn proceeds instead of hanging.\n let declineFailed = false\n if (options.declineInteraction) {\n try {\n await options.declineInteraction(parsed.value.id)\n } catch (err) {\n declineFailed = true\n log('[chat-routes] failed to auto-decline interaction', {\n id: parsed.value.id,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n } else {\n declineFailed = true\n log('[chat-routes] non-renderable interaction with no declineInteraction wired', {\n id: parsed.value.id,\n kind: parsed.value.kind,\n })\n }\n const text = options.declinedNotice?.(parsed.value, declineFailed) ?? (declineFailed\n ? `The agent requested ${parsed.value.kind} approval; declining it failed — it will expire on its own.`\n : `The agent requested ${parsed.value.kind} approval — auto-declined by policy.`)\n const notice = noticePart('auto-declined', `auto-declined-${parsed.value.id}`, text)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'auto-declined', text }\n continue\n }\n\n if (event.type === 'interaction.cancel') {\n const parsed = parseInteractionCancel(asRecord(record.data))\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed interaction.cancel event', { error: parsed.error })\n continue\n }\n const key = interactionPartKey(parsed.value.id)\n const existing = partMap.get(key)\n if (existing?.type === 'interaction' && existing.status === 'pending') {\n recordPersistedPart({\n ...existing,\n status: cancelStatusFor(parsed.value.reason),\n ...(parsed.value.reason ? { cancelReason: parsed.value.reason } : {}),\n }, undefined, key)\n }\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'plan.submitted') {\n const parsed = parsePlanSubmittedEvent(record)\n if (!parsed.succeeded) {\n log('[chat-routes] dropping malformed plan.submitted event', { error: parsed.error })\n continue\n }\n recordPersistedPart(planToPersistedPart(parsed.value), undefined)\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'warning') {\n const message = asString(event.data?.message)\n if (message) {\n projectionState.warningCount += 1\n const code = asString(event.data?.code)\n const text = code ? `${code}: ${message}` : message\n const notice = noticePart('warning', `warning-${projectionState.warningCount}`, text)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'warning', text }\n }\n // The flattened notice is additive; existing raw-warning consumers keep\n // receiving the original event too.\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'usage') {\n const reported = extractUsageSnapshot(asRecord(record.usage))\n if (reported) applyTerminalUsage(reported, usage)\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'result') {\n projectionState.terminalObserved = true\n const finalText = asString(event.data?.finalText)\n if (finalText) projectionState.fullText = finalText\n const reported = extractReportedTurnUsage(asRecord(event.data))\n if (reported) {\n applyTerminalUsage(reported, usage)\n yield* emitFinalUsage()\n } else {\n // Legacy result shape kept as a secondary fallback.\n const resultUsage = asRecord(event.data?.usage)\n if (resultUsage) {\n const input = Number(resultUsage.inputTokens)\n const output = Number(resultUsage.outputTokens)\n if (Number.isFinite(input)) usage.inputTokens = input\n if (Number.isFinite(output)) usage.outputTokens = output\n }\n }\n yield* emitTerminalizedTools()\n continue\n }\n\n if (event.type === 'done') {\n // SDK transport-loss cleanup emits a failed done without a backend\n // terminal receipt. Preserve an earlier result, but never unlock on\n // that synthetic observation ending alone.\n if (isTerminalPromptEvent(record)) projectionState.terminalObserved = true\n const reported = extractReportedTurnUsage(asRecord(event.data))\n if (reported) {\n applyTerminalUsage(reported, usage)\n yield* emitFinalUsage()\n }\n yield* emitTerminalizedTools()\n yield toProducerWireEvent(record)\n continue\n }\n\n if (event.type === 'error') {\n const message = sandboxStreamErrorMessage(event.data)\n const errorContent = projectionState.fullText.trim()\n ? `The sandbox model stream stopped before a clean completion.\\n\\nError: ${message}`\n : `The sandbox agent returned an error before producing a visible answer.\\n\\nError: ${message}`\n if (options.errorNotice) {\n yield* emitErrorNotice(errorContent, sandboxStreamErrorCode(event.data))\n } else if (options.includeErrorText !== false) {\n const errorDelta = projectionState.fullText ? `\\n\\n---\\n${errorContent}` : errorContent\n projectionState.fullText += errorDelta\n yield { type: 'text', text: errorDelta }\n }\n projectionState.interactionOutcome = 'expired'\n yield* emitTerminalizedTools()\n yield toProducerWireEvent(record)\n continue\n }\n\n // Remaining lifecycle events forward verbatim; the client parser ignores\n // unknown types.\n yield toProducerWireEvent(record)\n }\n // A model that fell over and then produced nothing never entered the loop\n // body; the downgrade must still be recorded.\n yield* drainModelNotices()\n } catch (streamErr) {\n // A later fallback refusal cannot clear an earlier unobserved execution.\n // Count opens at their owner: failover may buffer the first native events.\n preflightRefused = !observedSourceEvent && openAttempts() === 1\n && streamErr instanceof SandboxRunError && streamErr.code === 'sandbox_unavailable'\n const diagnostic = sandboxStreamFailureDiagnostic(streamErr)\n log('[chat-routes] sandbox stream failed', {\n failureNote: diagnostic.failureNote,\n error: streamErr instanceof Error ? streamErr.message : String(streamErr),\n })\n if (options.errorNotice) {\n yield* emitErrorNotice(diagnostic.userMessage, diagnostic.code)\n } else if (options.includeErrorText !== false) {\n const errorDelta = projectionState.fullText\n ? `\\n\\n---\\n${diagnostic.userMessage}`\n : diagnostic.userMessage\n projectionState.fullText += errorDelta\n yield { type: 'text', text: errorDelta }\n }\n projectionState.interactionOutcome = 'expired'\n yield* emitTerminalizedTools()\n yield {\n type: 'error',\n data: {\n message: diagnostic.userMessage,\n code: diagnostic.code,\n details: { failureNote: diagnostic.failureNote },\n },\n }\n } finally {\n reasoningClock.settle()\n }\n }\n\n return {\n stream: stream(),\n finalText: () => projectionState.fullText,\n terminalObserved: () => projectionState.terminalObserved || preflightRefused,\n assistantParts: () => finalizePendingInteractionParts(\n finalizeAssistantParts(partOrder, timedParts(), projectionState.fullText),\n projectionState.interactionOutcome,\n ),\n // Mid-stream snapshot for incremental persistence: the same accumulators,\n // WITHOUT the two completion-time settlements (`terminalizeDanglingTool*`\n // and `finalizePendingInteractionParts`). A running tool and an unanswered\n // ask are the correct live state; settling them early would persist\n // phantom failures the final write then reverses.\n draftParts: () => draftAssistantParts(partOrder, timedParts(), projectionState.fullText),\n usage: () => usage,\n // A GETTER, not a captured value: `turn-routes` reads `producer.model` at\n // draft-snapshot and persist time, both of which happen after the stream\n // resolved which model serves. A plain property would freeze the PREFERRED\n // model into the row and make a downgrade unattributable — the exact\n // failure mode this work exists to prevent.\n get model(): string | undefined {\n return servedModel()\n },\n modelFailover: () => ({\n model: servingModel(),\n attempts: failover?.attempts() ?? [],\n usedFallback: failover?.usedFallback() ?? false,\n }),\n modelAttribution: () => ({\n ...(options.model ? { requestedModel: options.model } : {}),\n ...(modelState.effectiveBackend ?? {}),\n echoReceived: modelState.effectiveBackend !== undefined,\n }),\n }\n}\n\ninterface SandboxProjectionState {\n fullText: string\n terminalObserved: boolean\n stepCounter: number\n danglingToolsTerminalized: boolean\n interactionOutcome: 'answered' | 'expired'\n warningCount: number\n errorNoticeCount: number\n}\n\nfunction createSandboxProjection(projectionState: SandboxProjectionState, pendingModelNotices: { id: string; text: string }[]) {\n const partOrder: string[] = []\n const partMap = new Map<string, JsonRecord>()\n const tracker: TextTracker = { seen: new Map() }\n /** Each reasoning part's start and end where the harness sent none: the same timing the engine's producer persists. */\n const reasoningClock = createReasoningClock<string>()\n const usage: ChatTurnUsage = {}\n /** Whether each announced tool_call carried populated arguments. */\n const announcedToolArgs = new Map<string, boolean>()\n const settledTools = new Set<string>()\n /** Id-less step boundaries: one occurrence per key, never merged. */\n\n /** `promoteFilePart` memo, keyed by `id ?? url` of the raw part. Holds the\n * PROMISE (never the settled result) so concurrent duplicate events for\n * the same part await the one in-flight attempt instead of each starting\n * their own; the promise never rejects (see below), so a later duplicate\n * reading a settled entry reuses that first outcome — success or\n * failure — rather than retrying. */\n const promotedFileParts = new Map<string, Promise<FilePartPromotionOutcome>>()\n\n function recordPersistedPart(part: JsonRecord, delta: string | undefined, keyOverride?: string): void {\n const persisted = normalizePersistedPart(part)\n if (!persisted) return\n const key = keyOverride ?? getPartKey(persisted)\n if (!partMap.has(key)) partOrder.push(key)\n partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta))\n }\n\n function* emitTerminalizedTools(): Generator<ProducerWireEvent, void, unknown> {\n if (projectionState.danglingToolsTerminalized) return\n projectionState.danglingToolsTerminalized = true\n const updates = terminalizeDanglingAssistantToolUpdates(partOrder, partMap, projectionState.fullText)\n for (const part of updates) {\n const toolId = asString(part.id)\n if (!toolId || settledTools.has(toolId)) continue\n settledTools.add(toolId)\n const state = asRecord(part.state)\n yield {\n type: 'tool_result',\n toolCallId: toolId,\n toolName: asString(part.tool) ?? 'tool',\n outcome: {\n ok: false,\n ...(asString(state?.error) ? { message: asString(state?.error) } : {}),\n },\n }\n }\n }\n\n function* emitFinalUsage(): Generator<ProducerWireEvent, void, unknown> {\n const promptTokens = usage.inputTokens ?? 0\n const completionTokens = usage.outputTokens ?? 0\n if (promptTokens || completionTokens) {\n yield {\n type: 'usage',\n usage: {\n promptTokens,\n completionTokens,\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.costUsd !== undefined ? { providerCostUsd: usage.costUsd } : {}),\n },\n }\n }\n }\n\n /** Emit any queued fallback notices, persisting each so the downgrade is in\n * the durable transcript and not only in the live stream. Uses the existing\n * `warning` notice kind deliberately: every shipped client already renders\n * it, whereas a bespoke kind would be dropped by `dispatchChatStreamLine`'s\n * filter — an attribution nobody sees is not attribution. */\n function* drainModelNotices(): Generator<ProducerWireEvent, void, unknown> {\n while (pendingModelNotices.length > 0) {\n const queued = pendingModelNotices.shift()!\n const notice = noticePart('warning', queued.id, queued.text)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'warning', text: queued.text }\n }\n }\n\n /** `errorNotice` mode: the terminal error as a persisted `error` notice part,\n * so the durable row says \"this turn failed\" in a typed field. */\n function* emitErrorNotice(text: string, code: string): Generator<ProducerWireEvent, void, unknown> {\n projectionState.errorNoticeCount += 1\n const notice = noticePart('error', `error-${projectionState.errorNoticeCount}`, text, code)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'error', text, code }\n }\n\n\n /** The persisted parts with each reasoning part's time: the harness's own, else the clock's. */\n const timedParts = (): Map<string, JsonRecord> => {\n const timed = new Map(partMap)\n for (const [key, part] of partMap) {\n if (part.type !== 'reasoning') continue\n const time = reasoningClock.time(key, asRecord(part.time) as ReasoningRunTime | undefined)\n if (time) timed.set(key, { ...part, time })\n }\n return timed\n }\n\n return { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder }\n}\n\nasync function* projectSandboxMessagePart(\n event: StreamEvent,\n tracker: TextTracker,\n recordPersistedPart: (part: JsonRecord, delta: string | undefined, keyOverride?: string) => void,\n reasoningClock: ReturnType<typeof createSandboxProjection>['reasoningClock'],\n projectionState: SandboxProjectionState,\n partMap: Map<string, JsonRecord>,\n announcedToolArgs: Map<string, boolean>,\n settledTools: Set<string>,\n usage: ChatTurnUsage,\n options: SandboxChatProducerOptions,\n log: (message: string, meta?: Record<string, unknown>) => void,\n promotedFileParts: Map<string, Promise<FilePartPromotionOutcome>>,\n): AsyncGenerator<ProducerWireEvent, void, unknown> {\n if (event.type === 'message.part.updated') {\n const part = asRecord(event.data?.part)\n if (!part) return\n const rawDelta = event.data?.delta\n const partType = String(part.type ?? '')\n\n if (partType === 'text' || partType === 'reasoning') {\n const key = getPartKey(part)\n const delta = textDelta(tracker, key, part, rawDelta)\n recordPersistedPart(part, delta || undefined)\n if (delta) {\n if (partType === 'reasoning') reasoningClock.reasoning(key)\n else reasoningClock.settle()\n if (partType === 'text') projectionState.fullText += delta\n yield { type: partType, text: delta }\n }\n return\n }\n\n if (partType === 'tool') {\n reasoningClock.settle()\n recordPersistedPart(part, undefined)\n const persisted = partMap.get(getPartKey(part))\n const state = asRecord(persisted?.state)\n const toolId = String(persisted?.id ?? '')\n const toolName = String(persisted?.tool ?? 'tool')\n const args = asRecord(state?.input) ?? {}\n const hasPopulatedArgs = Object.keys(args).length > 0\n const announcedWithPopulatedArgs = announcedToolArgs.get(toolId)\n if (\n toolId &&\n (announcedWithPopulatedArgs === undefined ||\n (!announcedWithPopulatedArgs && hasPopulatedArgs && !settledTools.has(toolId)))\n ) {\n announcedToolArgs.set(toolId, hasPopulatedArgs)\n yield {\n type: 'tool_call',\n call: { toolCallId: toolId, toolName, args },\n }\n }\n const status = String(state?.status ?? '')\n if (toolId && (status === 'completed' || status === 'error') && !settledTools.has(toolId)) {\n settledTools.add(toolId)\n yield {\n type: 'tool_result',\n toolCallId: toolId,\n toolName,\n outcome: {\n ok: status === 'completed',\n ...(state?.output !== undefined ? { result: state.output } : {}),\n ...(asString(state?.error) ? { message: asString(state?.error) } : {}),\n },\n }\n }\n return\n }\n\n if (partType === 'step-finish') {\n addStepFinishUsage(part, usage)\n // Persist the per-step receipt too (unique key per occurrence: the\n // parts have no id and two receipts must never merge into one).\n recordPersistedPart(part, undefined, `step-finish:#${projectionState.stepCounter++}`)\n const promptTokens = usage.inputTokens ?? 0\n const completionTokens = usage.outputTokens ?? 0\n if (promptTokens || completionTokens) {\n yield {\n type: 'usage',\n usage: {\n promptTokens,\n completionTokens,\n ...(usage.reasoningTokens !== undefined\n ? { reasoningTokens: usage.reasoningTokens }\n : {}),\n ...(usage.costUsd !== undefined ? { providerCostUsd: usage.costUsd } : {}),\n },\n }\n }\n return\n }\n\n if (partType === 'step-start') {\n recordPersistedPart(part, undefined, `step-start:#${projectionState.stepCounter}`)\n return\n }\n\n if (partType === 'file' && options.promoteFilePart) {\n const promote = options.promoteFilePart\n // Prefixed by source (`id:`/`url:`) rather than the bare raw string —\n // an `id` and a `url` that happen to share the same text (e.g. both\n // `\"abc\"`) would otherwise collide onto one memo entry and fold two\n // unrelated parts' promotions together. Internal Map key only; never\n // observable outside this module.\n const rawId = asString(part.id)\n const rawUrl = asString(part.url)\n const memoKey = rawId ? `id:${rawId}` : rawUrl ? `url:${rawUrl}` : undefined\n // Always invoke the callback for a `file` part when one is wired —\n // gtm never skips promotion outright, even for a part with neither\n // `id` nor `url` (it simply fails \"carries no url\" and resolves\n // through the ordinary failure path). Memoization by PROMISE only\n // applies when there is something to key it on; keyless parts are\n // invoked un-memoized, once per occurrence.\n //\n // `Promise.resolve().then(...)` (rather than calling `promote(part)`\n // directly) so a SYNC throw from a non-async `promoteFilePart` is\n // captured into the promise chain instead of escaping this function\n // call outright — `.catch` below only ever sees a rejection, never a\n // thrown exception that unwinds past `attempt()`.\n const attempt = (): Promise<FilePartPromotionOutcome> =>\n Promise.resolve()\n .then(() => promote(part))\n .catch((err) => {\n const reason = err instanceof Error ? err.message : String(err)\n log('[chat-routes] file part promotion threw', { key: memoKey ?? '(keyless)', error: reason })\n return { succeeded: false as const, reason }\n })\n\n let pending: Promise<FilePartPromotionOutcome>\n if (memoKey) {\n pending = promotedFileParts.get(memoKey) ?? attempt()\n promotedFileParts.set(memoKey, pending)\n } else {\n pending = attempt()\n }\n\n const outcome = await pending\n if (outcome.succeeded) {\n recordPersistedPart(outcome.part, undefined, outcome.key)\n } else if (outcome.part) {\n // Substitute part (e.g. a warning notice) takes the raw part's\n // place in the transcript — the transient url never lands.\n recordPersistedPart(outcome.part, undefined, outcome.key)\n } else {\n recordPersistedPart(part, undefined)\n }\n return\n }\n\n // Remaining storable kinds (file/image/subtask) have no live\n // vocabulary line; they persist so the transcript keeps them.\n recordPersistedPart(part, undefined)\n return\n }\n}\n","import { parseJsonObjectBody } from '../web/index'\nimport { redactErrorMessage } from '../redact/index'\nimport { INLINE_PARTS_MAX_BYTES } from './wire'\nimport type { ChatRouteEvent, ChatTurnProduceArgs, CreateChatTurnRoutesOptions } from './turn-route-contracts'\n\nexport interface ChatTurnCancelRequest extends Record<string, unknown> {\n threadId: string\n turnId: string\n cancellationToken?: string\n}\n\n/** Product identity and editor access have already been checked before target is called. */\nexport interface ChatTurnCancelArgs<TContext> {\n request: Request\n body: ChatTurnCancelRequest\n tenantId: string\n userId: string\n context?: TContext\n /** Supplied only by the execution owner after admission; never copied from a request body. */\n messageId?: string\n}\n\n/** Structural public Sandbox API; addressing always comes from the captured receipt. */\nexport interface ChatTurnCancelSource {\n id: string\n session(id: string): {\n interrupt(input: { executionId: string }): Promise<{ cancelled: boolean }>\n status(): Promise<{ id: string; status?: string; activeExecutionId?: string | null } | null>\n }\n}\n\n/** Acknowledges durable intent only; the execution owner still reconciles actual completion and side effects. */\nexport interface ChatTurnCancelControlResult {\n requested: boolean\n}\n\n/** Application fields are projected once; the shared owner never infers OAuth or source-key authority. */\nexport interface ChatTurnCancelTarget {\n capturedMetadata: Record<string, unknown>\n status: string | undefined\n dispatchToken?: string\n requiresDispatchToken: boolean\n /** Server-captured exact owner, never coordinates supplied by the caller.\n * Called after authorization and dispatch-token checks. A positive request\n * acknowledges intent; it must not mark native work stopped. */\n control?: {\n request(capturedMetadata: Record<string, unknown>): Promise<ChatTurnCancelControlResult>\n }\n native?: {\n state: string | undefined\n sandboxId?: string\n sessionId?: string\n executionId?: string\n /** Resolve the original authorized box only after the dispatch token and receipt are validated. */\n source(): Promise<ChatTurnCancelSource | null>\n }\n /** Compare the WHOLE captured record atomically, then merge the stopped fields. False changes nothing.\n * A requested-only control target never calls this; the execution owner confirms its terminal outcome. */\n markStopped(capturedMetadata: Record<string, unknown>, stoppedAt: string): Promise<boolean>\n}\n\nexport interface ChatTurnCancelOptions<TContext> {\n target(args: ChatTurnCancelArgs<TContext>): Promise<ChatTurnCancelTarget | Response>\n}\n\nconst targetChanged = () => Response.json({\n error: 'This Stop no longer matches the current turn attempt. Refresh its current state.',\n code: 'CANCEL_TARGET_CHANGED',\n}, { status: 409 })\nconst stateChanged = () => Response.json({\n error: 'This turn changed while Stop was pending. Refresh before trying Stop again.',\n code: 'CANCEL_STATE_CHANGED',\n}, { status: 409 })\nconst success = (sandboxInterrupted: boolean) => Response.json({ succeeded: true, sandboxInterrupted })\n\n/** Existing product Stop, composed with the same authorization and storage owner as chat. */\nexport async function cancelChatTurn<TContext>(request: Request, options: {\n authorize: CreateChatTurnRoutesOptions<TContext>['authorize']\n cancel?: ChatTurnCancelOptions<TContext>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}): Promise<Response> {\n if (!options.cancel || request.method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const [raw, invalid] = await parseJsonObjectBody(request, { maxBytes: INLINE_PARTS_MAX_BYTES })\n if (invalid) return invalid\n const threadId = typeof raw.threadId === 'string' ? raw.threadId.trim() : ''\n const turnId = typeof raw.turnId === 'string' ? raw.turnId.trim() : ''\n if (!threadId || !turnId) {\n return Response.json({ error: 'Missing workspaceId, threadId, or turnId' }, { status: 400 })\n }\n const body: ChatTurnCancelRequest = { ...raw, threadId, turnId,\n cancellationToken: typeof raw.cancellationToken === 'string' ? raw.cancellationToken : undefined }\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? {}))\n try {\n const auth = await options.authorize({ request, intent: 'cancel', body, threadId })\n if (!auth.ok) return auth.response\n if (auth.intent !== undefined && auth.intent !== 'cancel') {\n return Response.json({ error: 'Authorization did not allow this turn cancellation.', code: 'chat_authorization_intent_mismatch' }, { status: 403 })\n }\n const target = await options.cancel.target({ request, body, tenantId: auth.tenantId, userId: auth.userId,\n ...('context' in auth ? { context: auth.context } : {}) })\n if (target instanceof Response) return target\n if (target.requiresDispatchToken && (!body.cancellationToken || body.cancellationToken !== target.dispatchToken)) {\n return targetChanged()\n }\n if (target.status === 'stopped' || target.status === 'answered') return success(false)\n if (target.control) {\n const intent = await target.control.request(target.capturedMetadata)\n return intent.requested ? Response.json({ succeeded: true, sandboxInterrupted: false, cancellationRequested: true }) : targetChanged()\n }\n const markStopped = async () => await target.markStopped(target.capturedMetadata, new Date().toISOString())\n ? null : stateChanged()\n if (!target.native) return await markStopped() ?? success(false)\n const native = target.native\n if (native.state !== 'running' || !native.executionId || !native.sessionId || !native.sandboxId) {\n return Response.json({\n error: 'This turn has no confirmed native execution to stop. Refresh and try again.',\n code: 'NATIVE_CANCEL_TARGET_UNAVAILABLE',\n }, { status: 409 })\n }\n const source = await native.source()\n if (!source || source.id !== native.sandboxId) {\n return Response.json({ error: 'The turn was not marked stopped because its original sandbox is unavailable.' }, { status: 503 })\n }\n try {\n const session = source.session(native.sessionId)\n const interrupted = await session.interrupt({ executionId: native.executionId })\n if (!interrupted.cancelled) {\n const current = await session.status()\n const anotherExecution = typeof current?.activeExecutionId === 'string'\n && current.activeExecutionId.length > 0 && current.activeExecutionId !== native.executionId\n const terminal = current && ['completed', 'failed', 'cancelled'].includes(current.status ?? '')\n if (!current || current.id !== native.sessionId || current.activeExecutionId === native.executionId\n || (!anotherExecution && !terminal)) {\n throw new Error('The targeted native execution has not been confirmed stopped')\n }\n }\n return await markStopped() ?? success(interrupted.cancelled)\n } catch (error) {\n log('[chat-routes] native cancellation failed', { error: redactErrorMessage(error) })\n return Response.json({ error: 'The turn was not marked stopped because its native execution could not be confirmed interrupted.' }, { status: 502 })\n }\n } catch (error) {\n if (error instanceof Response) return error\n log('[chat-routes] cancellation failed', { error: redactErrorMessage(error) })\n return Response.json({ error: 'Turn cancellation is temporarily unavailable.' }, { status: 503 })\n }\n}\n\n\n/** Internal route observation of the same product Stop target. This reads only;\n * native interruption and metadata writes remain exclusive to cancelChatTurn. */\nexport async function* observeTurnCancellation<TContext, TResource>(\n source: AsyncIterable<ChatRouteEvent>,\n args: ChatTurnProduceArgs<TContext, TResource>,\n cancel: ChatTurnCancelOptions<TContext>,\n abort: AbortController,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n if (!args.userMessageId) { yield* source; return }\n const iterator = source[Symbol.asyncIterator]()\n let closed = false, stopped = false, drained = false, warned = false\n let polling: Promise<boolean> | undefined\n let notifyStop!: () => void\n const stop = new Promise<IteratorResult<ChatRouteEvent>>(resolve => { notifyStop = () => { resolve({ done: true, value: undefined }) } })\n const body: ChatTurnCancelRequest = { ...args.body, threadId: args.identity.sessionId,\n turnId: typeof args.body.turnId === 'string' ? args.body.turnId : '',\n cancellationToken: typeof args.body.cancellationToken === 'string' ? args.body.cancellationToken : undefined }\n const readTarget = async (): Promise<boolean> => {\n if (closed) return true\n try {\n const target = await cancel.target({ request: args.request, body, tenantId: args.identity.tenantId,\n userId: args.identity.userId, context: args.context, messageId: args.userMessageId! })\n if (closed) return true\n if (target instanceof Response) return false\n if (target.status === 'stopped' || target.status === 'superseded') {\n stopped = true\n abort.abort(new Error('The captured turn was stopped or superseded.'))\n notifyStop()\n } else if (target.status === 'answered') clearInterval(timer)\n return true\n } catch (error) {\n // Unknown state is not evidence of Stop. Completion requires a fresh\n // successful read; background observation keeps checking in the meantime.\n if (!warned) {\n warned = true\n console.error('[chat-routes] stop observation unavailable', { error: redactErrorMessage(error) })\n }\n return false\n }\n }\n const poll = (): Promise<boolean> => polling ??= readTarget().finally(() => { polling = undefined })\n const timer = setInterval(() => { void poll() }, 1_000)\n try {\n // A lazy source can establish its domain row readiness during this first pull.\n let pending = iterator.next()\n void pending.catch(() => {})\n void poll()\n while (!stopped) {\n let next: IteratorResult<ChatRouteEvent>\n try { next = await Promise.race([pending, stop]) }\n catch (error) { if (stopped) return; throw error }\n if (stopped) return\n if (next.done) {\n // A stream can finish after Stop committed but before the next tick.\n // Join the earlier snapshot, then demand a new read at the drain boundary.\n await polling\n if (!await poll()) throw new Error('The captured turn state could not be confirmed at completion')\n if (stopped) return\n drained = true\n return\n }\n yield next.value\n pending = iterator.next()\n void pending.catch(() => {})\n }\n } finally {\n closed = true\n clearInterval(timer)\n if (!drained) {\n const cleanup = iterator.return?.().catch(() => {})\n if (cleanup) args.waitUntil?.(cleanup)\n }\n }\n}\n","/** Validated request and transcript projections at the chat-route boundary. */\nimport { mentionInputToPart, toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport { normalizeClientTurnId } from '../stream/index'\nimport type { TurnTrace } from '../turn-trace/recorder'\nimport { formatServerTiming } from '../turn-trace/server-timing'\nimport { checkModelPolicy } from '../policy-filters/index'\nimport type { ChatTurnAuthorization, CreateChatTurnRoutesOptions } from './turn-route-contracts'\nimport {\n assertPromptPartsWithinCap,\n ChatTurnInputError,\n parseChatTurnParts,\n parseMentions,\n type ChatTurnFilePartInput,\n type ChatTurnRequestPayload,\n type ChatMention,\n} from './wire'\n\n/** A turn whose body parsed and whose caller `authorize` admitted. */\nexport type AdmittedTurn<TContext> = {\n parsed: ParsedTurnBody\n auth: Extract<ChatTurnAuthorization<TContext>, { ok: true; context: TContext }>\n trace: TurnTrace\n /** The route's read-only prefetch for this admitted identity (`./turn-prefetch`). */\n prefetched?: Promise<unknown>\n}\n\n/** Emits one stage on a progress-first stream. */\nexport type TurnProgressCallback = (phase: string, message: string) => void\n\nexport function errorResponse(err: ChatTurnInputError): Response {\n return Response.json({ code: err.code, error: err.message }, { status: err.status })\n}\n\nexport interface ParsedTurnBody {\n payload: ChatTurnRequestPayload\n content: string\n fileParts: ChatTurnFilePartInput[]\n mentions: ChatMention[]\n turnId: string | undefined\n}\n\n/**\n * The turn's admission as a `Server-Timing` value: `admission` for the\n * request-to-stream wall time, then each `admission.*` span the trace holds in\n * start order. A timed request reads where admission went from the response\n * headers alone; the same spans reach the trace sink.\n */\nexport function admissionServerTiming(trace: TurnTrace): string {\n const now = Date.now()\n const steps = trace.spans(now)\n .filter((span) => span.kind === 'admission')\n .sort((a, b) => a.startMs - b.startMs)\n .map((span) => ({ name: span.name, dur: span.endMs - span.startMs }))\n return formatServerTiming([{ name: 'admission', dur: now - trace.startedAt }, ...steps])\n}\n\n/** The admission policy's refusal of the model the turn names, or null when it allows it or names none. */\nexport async function namedModelRefusal(\n policy: CreateChatTurnRoutesOptions<unknown>['modelPolicy'],\n payload: ChatTurnRequestPayload,\n trace: TurnTrace,\n): Promise<Response | null> {\n const namedModel = typeof payload.model === 'string' ? payload.model.trim() : ''\n if (!policy || !namedModel) return null\n const decision = await trace.measure('admission.model_policy', 'admission', () =>\n checkModelPolicy(namedModel, policy.catalog, policy.filter, policy.context))\n return decision.allowed ? null : Response.json({ code: 'model_policy_denied', error: decision.reason }, { status: 403 })\n}\n\nexport function validateTurnBody(body: Record<string, unknown>): 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 = parseMentions(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)\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 const retryAttemptId = body.retryAttemptId\n if (retryAttemptId !== undefined && (\n typeof retryAttemptId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(retryAttemptId) || !turnId\n )) throw new ChatTurnInputError('retryAttemptId requires turnId and 1–64 letters, digits, underscores, or hyphens')\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. */\nexport function userPartsWithFiles(\n userParts: Array<Record<string, unknown>>,\n fileParts: ChatTurnFilePartInput[],\n mentions: ChatMention[],\n): ChatMessagePart[] {\n return toChatMessageParts([\n ...userParts,\n ...fileParts.map((part) => ({ ...part })),\n ...mentions.map((mention) => ({ ...mentionInputToPart(mention) })),\n ])\n}\n","/**\n * A turn addressed to several agents runs them at the same time, each as its\n * own producer with the same thread history: the route sees one stream,\n * persists one assistant row, and the row's parts carry a `speaker` part\n * before each responder's parts, in the order the mentions were typed, so a\n * transcript draws each answer under its author.\n *\n * Live, every responder is announced up front with a `speaker` event, in\n * mention order, and then every event carries `speaker` (the responder's\n * agent id) as it arrives, so a viewer draws one live block per responder and\n * sees them answer at the same time. When a responder ends, its `speaker`\n * event is sent again with `state` (`done` or `failed`), and the stored row's\n * speaker parts carry the same state. The stored order stays the order typed,\n * so the transcript rereads the same way every time.\n *\n * Parallel and independent on purpose: the agents are addressed, not chained.\n * A responder that fails leaves a notice under its own name and the others\n * still answer; the turn fails only when every responder did.\n */\nimport type { ChatTurnIdentity } from '@tangle-network/agent-runtime/durable'\nimport type { TurnTrace } from '../turn-trace/recorder'\nimport { errorResponse } from './turn-admission'\nimport type { ChatRouteEvent, ChatTurnAgentsOptions, ChatTurnAgentTarget, ChatTurnProduceArgs, ChatTurnRouteProducer, ChatTurnUsage } from './turn-route-contracts'\nimport { agentMentionsOf, ChatTurnInputError, type ChatMention } from './wire'\n\n/**\n * Name a turn's responders from its agent mentions, before any lock, row or\n * model call: the product's resolver maps mentioned ids to the profiles they\n * run as, and a mention it does not return is refused. The thread's binding\n * does not move. Returns the response to send on refusal, otherwise the\n * produce args carrying `agents` in mention order (unchanged when none).\n */\nexport async function addressAgents<TContext, TResource>(input: {\n options: { agents?: ChatTurnAgentsOptions<TContext> }\n mentions: readonly ChatMention[]\n identity: ChatTurnIdentity\n context: TContext\n produceArgs: ChatTurnProduceArgs<TContext, TResource>\n trace: TurnTrace\n}): Promise<Response | ChatTurnProduceArgs<TContext, TResource>> {\n const addressed = agentMentionsOf(input.mentions)\n if (addressed.length === 0) return input.produceArgs\n const { agents } = input.options\n if (!agents) {\n return errorResponse(new ChatTurnInputError('This chat does not address agents by mention', 400, 'agents_unsupported'))\n }\n const targets = await input.trace.measure('admission.agents', 'admission', () =>\n agents.resolve({ identity: input.identity, context: input.context, mentions: addressed }))\n const byId = new Map(targets.map((target) => [target.id, target]))\n const unknown = addressed.find((mention) => !byId.has(mention.agentId))\n if (unknown) return errorResponse(new ChatTurnInputError(`Unknown agent @${unknown.handle}`, 400, 'unknown_agent'))\n return { ...input.produceArgs, agents: addressed.map((mention) => byId.get(mention.agentId)!) }\n}\n\n/** The event a viewer receives when the next responder starts. */\nexport const SPEAKER_EVENT = 'speaker'\n\n/** A responder's speaker part; `state` once it ended. */\nexport function speakerPart(agent: ChatTurnAgentTarget, state?: 'done' | 'failed'): Record<string, unknown> {\n return { type: 'speaker', id: agent.id, name: agent.name, handle: agent.handle, ...(state ? { state } : {}) }\n}\n\n/**\n * What a responder reads as the message: the addressed handles leave the text\n * (they are addressing, not content) and one line names who it answers as and\n * who else is answering, so each agent answers its own part instead of\n * playing every role (both did, GTM production 2026-10-27).\n */\nfunction addressedTurnText(content: string, agent: ChatTurnAgentTarget, agents: readonly ChatTurnAgentTarget[]): string {\n let text = content\n for (const target of agents) {\n text = text.replace(new RegExp(`(^|\\\\s)@${escapeRegExp(target.handle)}(?=\\\\s|$|[.,;:!?])`, 'g'), '$1')\n }\n text = text.replace(/[ \\t]{2,}/g, ' ').trim()\n const others = agents.filter((target) => target.id !== agent.id).map((target) => `${target.name} (@${target.handle})`)\n const line = others.length === 0\n ? `You answer this message as ${agent.name} (@${agent.handle}).`\n : `You answer this message as ${agent.name} (@${agent.handle}). ${others.join(', ')} ${others.length === 1 ? 'answers' : 'answer'} it separately at the same time; do your part and leave theirs to them.`\n return text ? `${line}\\n\\n${text}` : line\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/** The responder's copy of the produce args: its agent, its execution id and the message as it reads it. */\nfunction responderArgs<TContext, TResource>(\n args: ChatTurnProduceArgs<TContext, TResource>, agent: ChatTurnAgentTarget, index: number,\n): ChatTurnProduceArgs<TContext, TResource> {\n const agents = args.agents ?? []\n const address = (text: string) => addressedTurnText(text, agent, agents)\n const prompt = typeof args.prompt === 'string'\n ? address(args.prompt)\n : (() => {\n let done = false\n return args.prompt.map((part) => {\n if (done || part.type !== 'text' || typeof (part as { text?: unknown }).text !== 'string') return part\n done = true\n return { ...part, text: address((part as { text: string }).text) }\n })\n })()\n return {\n ...args, agent, executionId: `${args.executionId}-${index + 1}`, prompt,\n body: { ...args.body, ...(typeof args.body.content === 'string' ? { content: address(args.body.content) } : {}) },\n }\n}\n\nexport async function composeAgentProducers<TContext, TResource>(\n args: ChatTurnProduceArgs<TContext, TResource>,\n produce: (final: ChatTurnProduceArgs<TContext, TResource>) => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>,\n): Promise<ChatTurnRouteProducer> {\n const agents = args.agents ?? []\n if (agents.length === 0) throw new Error('composeAgentProducers needs at least one responder')\n const producers: Array<ChatTurnRouteProducer | undefined> = agents.map(() => undefined)\n const cleanups: Array<Promise<void>> = []\n // One slot per responder: its events as they arrive, drained eagerly so every\n // producer runs now; the composite stream reads whichever slot has events.\n const slots = agents.map(() => ({ queue: [] as ChatRouteEvent[], done: false, error: undefined as unknown, failure: undefined as ChatRouteEvent | undefined }))\n const failedNotice = (agent: ChatTurnAgentTarget, message: string): ChatRouteEvent =>\n ({ type: 'notice', id: `speaker-failed:${agent.id}`, noticeKind: 'error', text: `${agent.name} could not answer: ${message}`, speaker: agent.id } as ChatRouteEvent)\n let wake: (() => void) | undefined\n const notify = () => { const w = wake; wake = undefined; w?.() }\n agents.forEach((agent, index) => {\n const slot = slots[index]!\n void (async () => {\n try {\n // Each responder runs under its own execution id, so two native sessions\n // started for one turn never share a key; the route keeps the turn's.\n const producer = await produce(responderArgs(args, agent, index))\n producers[index] = producer\n if (producer.cleanup) cleanups.push(producer.cleanup)\n for await (const event of producer.stream) {\n // A responder's own failure stays its own: the route fails the turn on an\n // `error` event, so it becomes a notice under this speaker unless every\n // responder fails (then the last failure is forwarded at the end).\n if (event.type === 'error' || event.type === 'session.run.failed') {\n slot.failure = { ...event, speaker: agent.id } as ChatRouteEvent\n const message = typeof event.data?.message === 'string' ? event.data.message : 'the run failed'\n slot.queue.push(failedNotice(agent, message))\n } else {\n slot.queue.push({ ...event, speaker: agent.id } as ChatRouteEvent)\n }\n notify()\n }\n } catch (error) {\n slot.error = error\n } finally {\n slot.done = true\n notify()\n }\n })()\n })\n // A responder has ended once its producer settled; it failed if it threw or reported a failure.\n const endOf = (index: number): 'done' | 'failed' | undefined => {\n const slot = slots[index]!\n if (!slot.done) return undefined\n return slot.error !== undefined || slot.failure !== undefined ? 'failed' : 'done'\n }\n const stream = (async function* (): AsyncGenerator<ChatRouteEvent> {\n for (const agent of agents) {\n yield { type: SPEAKER_EVENT, ...speakerPart(agent) } as ChatRouteEvent\n }\n const reported = new Set<number>()\n const ended = new Set<number>()\n for (;;) {\n if (args.admissionSignal?.aborted) return\n let yielded = false\n for (const [index, slot] of slots.entries()) {\n while (slot.queue.length > 0) { yield slot.queue.shift()!; yielded = true }\n if (slot.done && slot.error !== undefined && !reported.has(index)) {\n reported.add(index)\n const agent = agents[index]!\n yield failedNotice(agent, slot.error instanceof Error ? slot.error.message : String(slot.error))\n yielded = true\n }\n const end = slot.queue.length === 0 ? endOf(index) : undefined\n if (end && !ended.has(index)) {\n ended.add(index)\n yield { type: SPEAKER_EVENT, ...speakerPart(agents[index]!, end) } as ChatRouteEvent\n yielded = true\n }\n }\n if (slots.every((slot) => slot.done && slot.queue.length === 0)) {\n // Every responder failed: the turn fails, as a thrown producer error or the last failure event.\n const failed = slots.every((slot) => slot.error !== undefined || slot.failure !== undefined)\n if (failed) {\n const thrown = slots.find((slot) => slot.error !== undefined)?.error\n if (thrown !== undefined) throw thrown\n const failure = slots.map((slot) => slot.failure).find((event) => event !== undefined)\n if (failure) yield failure\n }\n return\n }\n if (!yielded) await new Promise<void>((resolve) => {\n wake = resolve\n if (slots.some((slot) => slot.queue.length > 0 || slot.done)) {\n // Something landed between the scan and the wait; re-scan unless everything scanned is already settled.\n const pending = slots.some((slot, index) => slot.queue.length > 0 || (slot.done && !ended.has(index)))\n if (pending || slots.every((slot) => slot.done)) { wake = undefined; resolve() }\n }\n })\n }\n })()\n const entries = () => agents.flatMap((agent, index) => (producers[index] ? [{ agent, producer: producers[index]! }] : []))\n const failureOf = (index: number): string | undefined => {\n const slot = slots[index]!\n if (slot.error !== undefined) return slot.error instanceof Error ? slot.error.message : String(slot.error)\n const data = slot.failure?.data\n return slot.failure ? (typeof data?.message === 'string' ? data.message : 'the run failed') : undefined\n }\n // Every responder keeps its header in the stored row; a failed one carries its notice after whatever it said.\n const partsOf = (index: number, read: 'assistantParts' | 'draftParts') => {\n const agent = agents[index]!\n const producer = producers[index]\n const own = producer?.[read]?.()\n const text = producer?.finalText() ?? ''\n const parts = own ?? (text ? [{ type: 'text', text }] : [])\n const failure = failureOf(index)\n const notice = failure === undefined ? [] : [{ type: 'notice', noticeKind: 'error', id: `speaker-failed:${agent.id}`, text: `${agent.name} could not answer: ${failure}` }]\n return [speakerPart(agent, endOf(index)), ...parts, ...notice]\n }\n const last = () => entries().at(-1)?.producer\n return {\n stream,\n finalText: () => entries().map(({ producer }) => producer.finalText()).filter((text) => text.trim() !== '').join('\\n\\n'),\n assistantParts: () => agents.flatMap((_, index) => partsOf(index, 'assistantParts')),\n draftParts: () => agents.flatMap((_, index) => partsOf(index, 'draftParts')),\n usage: () => entries().reduce<ChatTurnUsage>((sum, { producer }) => {\n const usage = producer.usage?.() ?? {}\n for (const [key, value] of Object.entries(usage)) {\n if (typeof value === 'number') (sum as Record<string, number>)[key] = ((sum as Record<string, number>)[key] ?? 0) + value\n }\n return sum\n }, {}),\n terminalObserved: () => entries().every(({ producer }) => producer.terminalObserved?.() ?? true),\n get model() { return last()?.model },\n modelFailover: () => last()?.modelFailover?.() as ReturnType<NonNullable<ChatTurnRouteProducer['modelFailover']>>,\n modelAttribution: () => last()?.modelAttribution?.() as ReturnType<NonNullable<ChatTurnRouteProducer['modelAttribution']>>,\n cleanup: (async () => { await Promise.all(cleanups) })(),\n }\n}\n","/** Public contracts for admission, execution, persistence and chat-route hooks. */\nimport type { SandboxPromptExecutionLimits } from '../sandbox/prompt-options'\nimport type { ChatTurnStoreBindings } from './route-storage'\nimport type { NativeCompletionHandoffOptions, NativeTurnTimingFacts } from './native-turn-timing'\nimport type { ChatMessageValues } from '../chat-store/core'\nimport type { ChatTurnPrefetch, ChatTurnPrefetchIdentity } from './turn-prefetch'\nimport type { ChatTurnIdentity, ChatTurnProducer } from '@tangle-network/agent-runtime/durable'\nimport type { ChatMessagePart } from '../chat-store/parts'\nimport type { InteractionAnswerRoute, InteractionAnswerRouteOptions } from '../interactions/route'\nimport type { ModelFailoverAttempt } from '../model-resolution/failover'\nimport type { ModelPolicy } from '../policy-filters/index'\nimport type { PersistedChatMessageForTurn, TurnEventStore } from '../stream/index'\nimport type { D1LikeForTurns } from '../stream/turn-buffer'\nimport type { TurnStreamAuth } from '../turn-stream/adapters'\nimport type { TurnSpan, TurnSpanAttrs, TurnTrace, TurnTraceSink, TurnTraceSummary } from '../turn-trace/recorder'\nimport type { TurnRoutePhase } from './turn-progress'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { AgentMention, ChatTurnPartInput, ChatTurnRequestPayload } from './wire'\nimport type { RouterTurnProducerOptions } from './router-producer'\nimport type { HybridTurnProducerOptions } from './hybrid-producer'\nimport type { SandboxChatProducerOptions } from './sandbox-producer'\nimport type { ChatTurnCancelOptions, ChatTurnCancelRequest } from './cancellation'\n\n/** The route supplies request tracing, cancellation and the admission fence.\n * Domain callbacks supply model, credentials, policy, tools and prompt data. */\nexport type ChatTurnRouterConfiguration = Omit<RouterTurnProducerOptions, 'trace' | 'traceId' | 'signal' | 'userMessage' | 'history'> & {\n userMessage?: RouterTurnProducerOptions['userMessage']\n history?: RouterTurnProducerOptions['history']\n}\nexport type ChatTurnHybridConfiguration = Omit<HybridTurnProducerOptions, 'trace' | 'traceId' | 'signal' | 'userMessage' | 'history'> & {\n userMessage?: HybridTurnProducerOptions['userMessage']\n history?: HybridTurnProducerOptions['history']\n}\nexport type ChatTurnRouterBackend = ChatTurnRouteProducer | ChatTurnRouterConfiguration | ChatTurnHybridConfiguration\nexport type ChatTurnSandboxBackend = ChatTurnRouteProducer | SandboxChatProducerOptions\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: ChatMessageValues & {\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 }): 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: Partial<ChatMessageValues>): 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 /** Pending resource retirement after stream termination. The route tracks it\n * with the request's waitUntil, including when admission refuses an early\n * Router call. Cleanup must handle and report its own failures. */\n cleanup?: Promise<void>\n /** No unconfirmed native execution remains: a terminal was observed or local preflight prevented dispatch. */\n terminalObserved?(): boolean\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 /** Omit for existing callers; a full execution authorization may name its intent explicitly. */\n intent?: 'turn'\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 | {\n ok: true\n /** Identity/access for this operation only; it cannot start a turn. */\n intent: 'replay' | 'running' | 'cancel'\n tenantId: string\n userId: string\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 /** This request's bound host continuation, when supplied to turn(request, ctx). */\n waitUntil?: ChatTurnRequestContext['waitUntil']\n intent: 'turn' | 'replay' | 'running' | 'cancel'\n /** Parsed, validated POST body for a turn or cancellation. */\n body?: ChatTurnRequestPayload | ChatTurnCancelRequest\n /** The buffered turn id being replayed (replay intent only). */\n turnId?: string\n /** The thread whose running turns are being discovered. Prewarm also uses\n * running authorization, without a thread on page-open; the product may\n * authorize its verified workspace or refuse that operation. */\n threadId?: string\n /** The turn's trace (turn intent only). A product records its own child spans (a billing read, a workspace check) so the\n * admission wait is named by step; the route already records `admission.authorize` around the whole call. */\n trace?: TurnTrace\n /** The `admission.authorize` span (turn intent only): the parent for those child spans, so they nest under it. */\n span?: TurnSpan\n /** Turn intent with the route's `prefetch` option set: call it as soon as the caller's identity is verified, before\n * the rest of the checks, so the prefetch reads beside them (see `./turn-prefetch`). */\n identified?(identity: ChatTurnPrefetchIdentity): void\n}\n\n/** What `prepareTurn` receives: the admitted turn, before the conversation loads. */\nexport interface ChatTurnPrepareArgs<TContext> {\n request: Request\n /** This request's bound host continuation, when supplied to turn(request, ctx). */\n waitUntil?: ChatTurnRequestContext['waitUntil']\n /** Parsed, validated POST body. */\n body: ChatTurnRequestPayload\n tenantId: string\n userId: string\n threadId: string\n /** The context `authorize` returned; mutate it in place to finish it. */\n context: TContext\n /** Name the stage this work is in. On a progress-first stream it reaches the\n * client as a `session.run.phase` event; otherwise it is a no-op. */\n progress(phase: string, message: string): void\n}\n\n/** `prepareTurn`'s verdict: proceed, or answer with the product's response. */\nexport type ChatTurnPrepareResult = { ok: true } | { ok: false; response: Response }\n\n/** What `afterAuthorize` receives: the admitted turn, before the conversation loads and before any lock, read or write. */\nexport interface ChatTurnAfterAuthorizeArgs<TContext> {\n request: Request\n /** This request's bound host continuation, when supplied to turn(request, ctx). */\n waitUntil?: ChatTurnRequestContext['waitUntil']\n /** Parsed, validated POST body. */\n body: ChatTurnRequestPayload\n tenantId: string\n userId: string\n threadId: string\n /** The context `authorize` returned. Keep what the seam starts on it: `prepareTurn`, every later seam and `produce` receive the same object. */\n context: TContext\n /** The turn's trace, for the spans of the work the seam starts. */\n trace: TurnTrace\n}\n\n/** Frees what `afterAuthorize` started, for a turn that ends before `produce` takes it. */\nexport type ChatTurnAfterAuthorizeRelease<TResource = unknown> = (() => void | Promise<void>) | {\n /** Acquisition must clean up any partial resource when it rejects. */\n resource: Promise<TResource>\n /** Called once when this turn ends, including a refusal before acquisition resolves. */\n dispose(resource: TResource): void | Promise<void>\n}\n\n/** Trusted per-turn limits supplied by a server adapter, never by the body. */\nexport interface ChatTurnExecutionLimits extends SandboxPromptExecutionLimits {\n maxInputTokens?: 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/** A workspace agent a turn is addressed to, resolved by the product from an\n * `@` mention. `id` is the stable profile id the mention carried. */\nexport interface ChatTurnAgentTarget {\n id: string\n handle: string\n name: string\n /** The profile this responder runs as. A product's `produce` reads it from\n * `args.agent` and runs the turn as that agent instead of the thread's\n * bound one; the binding itself does not move. */\n profile?: AgentProfile\n}\n\n/** How a route turns `@agent` mentions into responders. */\nexport interface ChatTurnAgentsOptions<TContext> {\n /** Resolve the mentioned agents to the targets this caller may address.\n * Return only the ids you recognise for this workspace: a mention whose id\n * is missing from the result is refused as `unknown_agent` before anything\n * runs. Order is ignored; responders answer in mention order. */\n resolve(args: { identity: ChatTurnIdentity; context: TContext; mentions: AgentMention[] }): Promise<ChatTurnAgentTarget[]>\n}\n\n/** Define the arguments required to produce a chat turn with context and messaging details */\nexport interface ChatTurnProduceArgs<TContext, TResource = unknown> {\n /** The agent this producer answers as, when the turn was addressed to one\n * or more agents by mention. The route calls `produce` once per responder,\n * all at once, each with the same thread history and none seeing another's\n * answer, and persists their answers as one assistant row with a speaker\n * part before each, in mention order. Absent → the thread's own agent\n * answers, as before. */\n agent?: ChatTurnAgentTarget\n /** Every responder of this turn, in mention order. */\n agents?: ChatTurnAgentTarget[]\n request: Request\n /** The opaque resource afterAuthorize started; the route disposes it at this turn's end. */\n earlyResource?: Promise<TResource>\n /** This request's bound host continuation, when supplied to turn(request, ctx). */\n waitUntil?: ChatTurnRequestContext['waitUntil']\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 /** The turn's intent line (`intentLine`), or null when it was off, slow or\n * failed. Never rejects. A product puts it in the harness turn's context so\n * the agent knows what the founder was told it would do. */\n intentLine?: Promise<string | null>\n /** Server-authenticated limits for this turn. Never copied from the body. */\n executionLimits?: ChatTurnExecutionLimits\n /**\n * The turn's trace (`@tangle-network/agent-app/turn-trace`), bound to this turn's execution id. Pass it to the\n * Router engine (`trace`), `streamSandboxPrompt` and `ensureWorkspaceSandbox` so the turn's model calls, tool\n * calls and box claim are recorded under it; its `traceId` is what those calls send as `x-tangle-trace-id`.\n * The route records admission and persistence itself. Optional for source compatibility with synthetic\n * producers; every `createChatTurnRoutes` invocation supplies it.\n */\n trace?: TurnTrace\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` — a new row is not inserted yet. The dispatch-first policy\n * and `turnLock.acquire` see this for a fresh turn; a reused row's id is\n * already available from the history read, without another query.\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, including a reused row before dispatch policy;\n * also supplied to `contextGate`, `beforeTurn`, and `produce`. */\n userMessageId?: string | null\n /** True when this turn's own insert created `userMessageId`, so no earlier\n * attempt can have answered it; false when retry-dedup reused the row or no\n * row was written. A gate that refuses an already-answered retry can skip\n * its read when this is true. Already false for a reused row at backend\n * selection and lock acquisition; undefined for a fresh row until insertion. */\n userMessageInserted?: boolean\n /**\n * Transfer completion ownership to a product-owned durable runner. The\n * product MUST register that runner durably, then await this callback before\n * dispatching native execution. When timing transfer is used, persist the initial\n * timingFacts snapshot on the existing admission before registering that runner.\n * A callback rejection after registration retains durable ownership. Once it\n * resolves, this route remains a live event projector only: it no longer writes or settles the assistant\n * transcript, lifecycle hooks, lock, or replay-buffer status.\n *\n * Optional for source compatibility with synthetic producers. Every\n * `createChatTurnRoutes` invocation supplies it before `produce` runs.\n */\n handoffCompletion?: (options?: NativeCompletionHandoffOptions) => Promise<void>\n /** Serializable observations only; snapshots never predict events after handoff. */\n timingFacts?: () => NativeTurnTimingFacts\n /** What the route's `prefetch` read for this turn's admitted identity; set only when `prefetch` is configured. */\n prefetched?: Promise<unknown>\n /** Set for a fresh Router backend, which starts before the lock. Resolves to the final args (with\n * `userMessageId`, after `contextGate` and `beforeTurn`) once the admission chain commits, or rejects with\n * `TurnAdmissionRefusedError` when the turn is refused. Start the model call at once; write nothing durable,\n * and read nothing `beforeTurn` adds to `context`, until it resolves. */\n admitted?: Promise<ChatTurnProduceArgs<TContext, TResource>>\n /** Effective execution signal: product Stop/supersession, opted-in durable Stop/control loss,\n * and optional request-disconnect cancellation.\n * A fresh Router backend also aborts on admission refusal or when the route stops reading it.\n * Pass it to producer I/O; Router/Sandbox option data binds it automatically.\n * Early Router handoff waits for `admitted`. */\n admissionSignal?: AbortSignal\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/** 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/** This owner's cancellation observation: the signal aborts on Stop or control loss.\n * Closing observation does not release the lock or establish remote completion. */\nexport interface ChatTurnCancellation {\n signal: AbortSignal\n /** Close this owner's observation; never release the durable lock or claim remote work stopped. */\n close(): void | Promise<void>\n}\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; cancellation?: ChatTurnCancellation }\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, TResource = unknown> {\n acquire(args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnLockResult | Promise<ChatTurnLockResult>\n release(handle: unknown): void | Promise<void>\n /** Record a release for the durable owner to complete without freeing the lock; absent or false, the lock stays held. */\n park?(handle: unknown): Promise<boolean>\n /** Bring up whatever `acquire` will talk to, as soon as the turn is admitted\n * and while `prepareTurn` and the history read run. Never awaited; a failure\n * is logged and the turn goes on to `acquire` as usual. */\n warm?(target: { tenantId: string; userId: string; threadId: string; context: TContext }): void | Promise<void>\n}\n\ninterface ChatTurnLifecycleBase<TContext> {\n identity: ChatTurnIdentity\n executionId: string\n turnStreamId: string\n context: TContext\n /** Member row and backend observation facts, also reported on persistence failure. */\n userMessageId?: string | null\n backendTerminal?: boolean\n}\n/** When the turn's first visible word streamed, measured from `onTurnStart`. Absent when no word streamed. */\ninterface ChatTurnLifecycleTiming {\n /** Request receipt to onTurnStart; add to firstVisibleMs for request-origin latency. */\n admissionMs?: number\n /** First reasoning, tool activity or answer output, measured from onTurnStart. */\n firstVisibleMs?: number\n firstTextMs?: number\n /** Where the turn's wall time went: its share inside named spans and the time per kind of span. */\n trace?: TurnTraceSummary\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 /** Request receipt on the server clock. */\n requestReceivedAt: number\n admissionMs: 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>, ChatTurnLifecycleTiming {\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>, ChatTurnLifecycleTiming {\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 /** Follow-up work for a turn that ended cleanly: it runs with `onTurnComplete`'s own info once the assistant row is\n * persisted, the lifecycle hooks have fired and the thread's lock is released, under `waitUntil` where the host has\n * one. The member's next send never waits for it, so work that only decorates the answer (a model-written\n * checklist, a title, an index) belongs here and not in the producer's stream, where it holds the lock and the\n * stream open. It does not run for a failed, gated or handed-off turn. The turn's trace has ended; a product that\n * wants this work traced starts its own. A throw is logged and never reaches the member. */\n afterSettle?(info: ChatTurnLifecycleComplete<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 /** Persisted member row for this execution, when insertion was enabled. */\n userMessageId?: string | null\n /** False when a detached backend has not been observed to stop; its workspace stays fenced. */\n backendTerminal?: boolean\n identity: ChatTurnIdentity\n finalText: string\n context: TContext\n failed: boolean\n /** Final producer receipt, when it reports usage; absent counts remain unknown. */\n usage?: ChatTurnUsage\n failureReason?: string\n /** Typed reason of a failed turn, when its terminal error event names one. */\n failureCode?: 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/** Where a finished turn's trace goes, and the host's labels for its root span. Metadata only: never content. */\nexport interface ChatTurnTraceOptions<TContext> {\n /** Default: `createIntelligenceTurnTraceSink({ project: projectId })`, which reads the Sandbox product key from the environment. */\n sink?: TurnTraceSink\n /** Labels for the root span, e.g. the workspace id. Called once per exported turn. */\n labels?(info: { identity: ChatTurnIdentity; executionId: string; context: TContext }): TurnSpanAttrs\n}\n\n/** Define options to configure chat turn routes including authorization, storage, and event buffering */\nexport interface CreateChatTurnRoutesOptions<TContext = void, TResource = unknown> {\n /** Deployment bindings for the template defaults. Custom producers keep their own credentials and policy. */\n env?: import('./default-backend').ChatTurnEnvironment\n /** Disable the inherited prewarm endpoint explicitly. It warms only authenticated thread locks. */\n prewarm?: false\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 /** Let a turn address workspace agents by `@` mention: the composer's\n * `useFileMentions({ agents })` sends them, this resolves them to the\n * profiles they run as, and `produce` answers once per responder. Omit →\n * a turn carrying an agent mention is refused as `agents_unsupported`. */\n agents?: ChatTurnAgentsOptions<TContext>\n /** Resolve the exact authenticated stop target. Without this capability,\n * cancel returns 405 before parsing or authorization. */\n cancel?: ChatTurnCancelOptions<TContext>\n /** Read the turn's prompt inputs (profile, knowledge, catalogs) while `authorize` finishes: started when `authorize`\n * calls `args.identified`, or once it allows the turn. Read only: no writes, nothing paid or external beyond what\n * the verified identity allows. `produce` receives the result as `args.prefetched` only for an allowed turn of that\n * identity; a refusal aborts `args.signal` and drops it. Omit → nothing is prefetched. */\n prefetch?: ChatTurnPrefetch\n /** Finish the turn's context after `authorize` has admitted the caller and\n * before the conversation loads or the lock is taken: resolve the profile,\n * the model, anything that reads or writes product state. Keep `authorize`\n * to admission (identity, access, rate limits, input checks) so a refusal\n * stays fast and no write ever runs for a caller who is not admitted; on a\n * progress-first stream this work runs inside the stream and can name its\n * stages through `progress`. A refusal here is answered like a held lock:\n * a plain response without the progress header, a `turn.response` event\n * with it. Omit → nothing to prepare. */\n prepareTurn?(args: ChatTurnPrepareArgs<TContext>): ChatTurnPrepareResult | Promise<ChatTurnPrepareResult>\n /** Start the work this turn will need, the moment `authorize` and `modelPolicy` have admitted it, so that work overlaps\n * `prepareTurn`, the history read, the lock, the history recheck and the user-row insert instead of following them: the\n * workspace box, the keys a producer mints, a session ensure. Return `{resource, dispose}` to hand the route an\n * opaque acquisition promise: `produce` receives it as `args.earlyResource`, and the route disposes the value once\n * when the turn ends, including a refusal before acquisition resolves. Acquisition owns partial-failure cleanup.\n *\n * Admission has not finished, so the seam must start only work that the turn's refusal leaves harmless: a held lock\n * (409), a changed history, a gate's answer or a throw all end the turn without `produce`, and the work already\n * started runs on. Start nothing a second request for the same thread could not safely repeat, and nothing that\n * writes product state.\n *\n * Not awaited, and it must return synchronously: start the work and return, never wait for it. It may return a\n * legacy release function; the route calls it once, only if the turn ends without `produce` (the chain above, or a throw before the\n * engine took the turn), so a product frees credentials or leases the unused work holds. Once `produce` runs, the\n * work belongs to `produce` and the route never calls the release. A throw is logged and the turn goes on without\n * the early work. Omit → nothing starts early. */\n afterAuthorize?(args: ChatTurnAfterAuthorizeArgs<TContext>): void | ChatTurnAfterAuthorizeRelease<TResource>\n /** Product admission policy over the model a turn NAMES. When the request\n * body carries a `model`, it is checked here — after `authorize`, before\n * the conversation loads, the lock is taken, or any row is written — and a\n * refusal answers 403 with the policy's reason. Fail-closed: a named model\n * carrying no policy metadata is refused.\n *\n * This is half the enforcement. A body without `model` resolves to a\n * product default inside `produce`, which this seam never sees — enforce\n * that half at execution with `createSandboxChatProducer`'s `modelPolicy`\n * (or `runWithModelFailover`'s `policy` on a custom producer), which also\n * covers every fallback the turn could fail over to. Wire the SAME policy\n * object to both. Omit → no policy check (today's behavior). */\n modelPolicy?: ModelPolicy\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 | ChatTurnStoreBindings\n /** Build the turn stream after admission, or declare its execution backends.\n * Router calls start before the lock by default, after authorize has verified\n * identity/access. The model service enforces spend before paying a provider.\n * Output stays buffered until admission commits; a refusal cancels the call.\n * Return Router/Hybrid producer options to bind tracing, cancellation and\n * tool admission automatically. A custom Router producer must pass\n * admissionSignal and await admitted before tools or durable effects.\n * beforeTurn cannot patch a Router prompt already sent.\n *\n * when selects the Router backend (default true); false selects sandbox,\n * which always starts after admission. A function also starts after admission.\n * Reused user rows always finish admission before either backend starts. */\n produce?: import('./default-backend').ChatTurnDefaultBackend<TContext, TResource> | ((args: ChatTurnProduceArgs<TContext, TResource>) => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>) | {\n router(args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnRouterBackend | Promise<ChatTurnRouterBackend>\n when?(args: ChatTurnProduceArgs<TContext, TResource>): boolean\n sandbox?(args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnSandboxBackend | Promise<ChatTurnSandboxBackend>\n }\n /** Single-flight lock acquired before durable effects 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 * the binding-derived workspace lock. `false` explicitly disables it. Native\n * producers retain it until backend termination is observed. */\n turnLock?: ChatTurnLock<TContext, TResource> | false\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 an ordinary/Sandbox producer never run; an\n * early Router call is cancelled and discarded. 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, TResource>): 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?(\n args: ChatTurnProduceArgs<TContext, TResource>,\n /** `span` is the `admission.before_turn` span: the parent for a product's own child spans. */\n seam?: { span: TurnSpan },\n ): 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 /** 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 /**\n * Where each finished turn's trace goes. On by default: omit it and every turn goes to Tangle Intelligence under\n * `projectId` (`createIntelligenceTurnTraceSink`); pass `{ sink, labels }` to send it elsewhere or label it.\n * The route always records the turn's trace (`ChatTurnProduceArgs.trace`), reports its summary to `lifecycle`, and\n * writes one `agent_app_turn_trace` log line per turn (first text, coverage, time per kind); this sends the spans on.\n * The sink runs under `waitUntil` after the lifecycle hooks and after the turn lock is released, and its failure never\n * fails a turn. A turn handed to a durable owner (`handoffCompletion`) is exported when this request's live\n * projection ends, failed only when the projection saw an error. `false` is the only opt-out, and\n * `agent-app-signoff defaults` fails it until the app's `signoff.config.mjs` gives the reason.\n */\n turnTrace?: ChatTurnTraceOptions<TContext> | false\n /** Compose the interaction-answer endpoints (`/interactions`). Omit when the\n * product has no sidecar ask channel. */\n interactions?: InteractionAnswerRouteOptions\n /** Text for the route's own stages on a progress-first stream (`./turn-progress`).\n * Omitted stages keep `TURN_ROUTE_PHASE_MESSAGES`. */\n progressMessages?: Partial<Record<TurnRoutePhase, string>>\n /** Write and stream the turn's intent line ({@link ChatTurnIntentLine}). Omit → no line. */\n intentLine?: ChatTurnIntentLine<TContext>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** What `intentLine.generate` receives: the admitted turn's message and the thread's last few turns. */\nexport interface ChatTurnIntentLineArgs<TContext> {\n content: string\n /** The thread's last turns before this one, oldest first (at most {@link INTENT_LINE_HISTORY_MESSAGES}). */\n history: ReadonlyArray<{ role: 'user' | 'assistant' | 'system' | 'tool'; content: string }>\n tenantId: string\n userId: string\n threadId: string\n context: TContext\n /** Aborted when the line is no longer wanted (its deadline passed). */\n signal: AbortSignal\n}\n\n/**\n * The intent line: one plain sentence, written by a fast model call the moment\n * a turn is admitted, saying what the agent is about to do. It reaches a\n * progress-first client as a {@link TURN_INTENT_EVENT} while the harness boots,\n * and the turn's first answer text replaces it. It narrates intent and must\n * never answer or act. It fails open: a line later than `timeoutMs`, an error,\n * or an empty answer shows nothing.\n */\nexport interface ChatTurnIntentLine<TContext> {\n generate(args: ChatTurnIntentLineArgs<TContext>): Promise<string | null>\n /** Longest wait for the line. Default {@link INTENT_LINE_TIMEOUT_MS}. */\n timeoutMs?: number\n}\n\n/** A line slower than this shows nothing. */\nexport const INTENT_LINE_TIMEOUT_MS = 1_500\n/** Turns of the thread the line is written from. */\nexport const INTENT_LINE_HISTORY_MESSAGES = 6\n/** Longest line kept; anything longer is cut. */\nexport const INTENT_LINE_MAX_CHARS = 240\n\n/** Define routes to run, replay, and list running chat turns with streaming and reconnect support */\nexport interface ChatTurnRoutes {\n /** POST — warm the server-authorized workspace lock; verify a named thread before allowing it. Never provisions paid compute. */\n prewarm(request: Request): Promise<Response>\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. A request with\n * `TURN_PROGRESS_HEADER` gets a progress-first stream once it is\n * authorized (`./turn-progress`). */\n turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response>\n /** POST — stop the exact authorized execution; unavailable unless configured. */\n cancel(request: Request): 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 * The turn's read-only prefetch: the inputs its prompt needs (profile, knowledge, catalogs), read while `authorize`\n * finishes instead of after it.\n *\n * `authorize` calls `identified({ tenantId, userId })` once it has verified who is asking, and the route starts the\n * product's `prefetch` then, beside the rest of `authorize` (billing gates, rate limits). Nothing it read reaches the\n * producer unless `authorize` allows the turn for that same identity; on a refusal its signal aborts and its result\n * is dropped. An `authorize` that never calls `identified` still gets the prefetch, started once it allows the turn.\n *\n * Why: Legal's turns ran `authorize` (~716 ms) and then the prompt reads (~597 ms) in series before the model call\n * (dispatchMs median 1,567 ms); Creative overlaps the same reads by hand (creative-agent\n * chat-vertical.ts:289). The contract: the prefetch only reads. It writes nothing and calls nothing paid or external\n * as the member beyond what the verified identity already allows.\n */\nimport type { TurnTrace } from '../turn-trace/recorder'\nimport type { ChatTurnRequestPayload } from './wire'\n\n/** Who `authorize` verified the caller to be: the workspace (tenant) and the member. */\nexport interface ChatTurnPrefetchIdentity {\n tenantId: string\n userId: string\n}\n\nexport interface ChatTurnPrefetchArgs extends ChatTurnPrefetchIdentity {\n request: Request\n body: ChatTurnRequestPayload\n trace: TurnTrace\n /** Aborts when the turn is refused; stop reading. */\n signal: AbortSignal\n}\n\nexport type ChatTurnPrefetch = (args: ChatTurnPrefetchArgs) => unknown\n\nexport interface TurnPrefetchRun {\n /** For `authorize`: the caller's identity is verified; start the prefetch now. Later calls are ignored. */\n identified(identity: ChatTurnPrefetchIdentity): void\n /** `authorize` allowed the turn: the prefetch for this identity, started now if `identified` never ran or named\n * someone else. */\n admitted(identity: ChatTurnPrefetchIdentity): Promise<unknown>\n /** The turn was refused: abort the prefetch and drop what it read. */\n discard(): void\n}\n\nexport function startTurnPrefetch(\n prefetch: ChatTurnPrefetch,\n input: { request: Request; body: ChatTurnRequestPayload; trace: TurnTrace },\n): TurnPrefetchRun {\n let started: { identity: ChatTurnPrefetchIdentity; abort: AbortController; result: Promise<unknown> } | undefined\n const start = (identity: ChatTurnPrefetchIdentity) => {\n const abort = new AbortController()\n const result = input.trace.measure('admission.prefetch', 'admission', async () => prefetch({\n ...input, tenantId: identity.tenantId, userId: identity.userId, signal: abort.signal,\n }))\n // A refused turn never awaits it; its failure must not become an unhandled rejection.\n result.catch(() => {})\n started = { identity: { ...identity }, abort, result }\n }\n return {\n identified(identity) {\n if (!started) start(identity)\n },\n admitted(identity) {\n if (started && (started.identity.tenantId !== identity.tenantId || started.identity.userId !== identity.userId)) {\n // Read for a different identity than the one admitted: never hand it on.\n started.abort.abort()\n started = undefined\n }\n if (!started) start(identity)\n return started!.result\n },\n discard() {\n started?.abort.abort()\n started = undefined\n },\n }\n}\n","/** Admission-to-settlement execution for one authenticated chat turn. */\nimport { deriveExecutionId, handleChatTurn, type ChatTurnIdentity } from '@tangle-network/agent-runtime/durable'\nimport { toChatMessageParts } from '../chat-store/parts'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n resolveChatTurn,\n type BufferedTurnTap,\n type PersistedChatMessageForTurn,\n} from '../stream/index'\nimport type { TurnTraceSink, TurnTraceSnapshot, TurnTraceSummary } from '../turn-trace/recorder'\nimport { otlpTraceId } from '../turn-trace/otel'\nimport { noteMeasuredTurnFacts, readableTurnFailure } from '../turn-trace/turn-facts'\nimport { createNativeTimingTransfer, type NativeTimingTransfer } from './native-turn-timing'\nimport { createChatTurnOwnership } from './turn-ownership'\nimport {\n assistantRowIdForTurn,\n createAssistantDraftWriter,\n rowIdOf,\n type AssistantDraftStore,\n type AssistantDraftWriter,\n type DraftPersistenceTuning,\n} from './draft-persistence'\nimport { dispatchFirstFor, selectTurnProducer } from './dispatch-first'\nimport { observeTurnCancellation } from './cancellation'\nimport { admissionServerTiming, errorResponse, userPartsWithFiles, type AdmittedTurn, type TurnProgressCallback } from './turn-admission'\nimport { abortOnSignal, concatStreams, failureCodeOf, failureReasonOf, isVisibleOutput, isVisibleText, tapRawEvents, withStreamHeartbeat } from './turn-event-stream'\nimport type {\n ChatTurnLifecycleComplete,\n ChatTurnModelAttribution,\n ChatTurnProduceArgs,\n ChatTurnRequestContext,\n ChatTurnRouteProducer,\n ChatTurnTraceOptions,\n ChatRouteEvent,\n CreateChatTurnRoutesOptions,\n} from './turn-route-contracts'\nimport type { TurnRoutePhase } from './turn-progress'\nimport { ChatTurnInputError, type ChatTurnPartInput } from './wire'\nimport { addressAgents, composeAgentProducers } from './agent-producers'\nimport type { ResolvedChatTurnRoutesOptions } from './route-storage'\nimport type { AfterAuthorizeWork } from './early-turn-work'\n\n/** The thread's messages as the turn-identity resolver reads them. */\nasync function readTurnHistory(store: CreateChatTurnRoutesOptions<unknown>['store'], threadId: string): Promise<PersistedChatMessageForTurn[]> {\n return (await store.listMessages(threadId)).map((m) => ({\n id: m.id, role: m.role, content: m.content, parts: (m.parts ?? null) as PersistedChatMessageForTurn['parts'],\n }))\n}\n\ninterface TurnExecutionOptions<TContext, TResource> {\n options: ResolvedChatTurnRoutesOptions<TContext, TResource>\n draftStore: AssistantDraftStore\n draftTuning: DraftPersistenceTuning | null\n progressMessages: Record<TurnRoutePhase, string>\n traceOptions: ChatTurnTraceOptions<TContext> | undefined\n traceSink: TurnTraceSink | undefined\n startIntentLine(admitted: AdmittedTurn<TContext>): Promise<string | null> | undefined\n log(message: string, meta?: Record<string, unknown>): void\n}\n\n/** One requested-versus-served projection for persistence and both completion receipts. */\nfunction modelAttributionFields(attribution: ChatTurnModelAttribution | undefined) {\n return {\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 }\n}\n\n/** Bind the route's construction-time dependencies; each invocation retains its own turn state. */\n/** The lifecycle's timing for a settled turn, noted for the rollout timing store so it can fill a product row that\n * omits it (rollout/d1 `record`). */\nfunction settledTurnTiming(turnStreamId: string, at: {\n requestAt: number; startedAt: number; firstVisibleAt?: number\n firstTextAt?: number; model?: string\n failure?: { data?: Record<string, unknown>; error: unknown }\n}, trace: TurnTraceSummary) {\n const measured = {\n admissionMs: at.startedAt - at.requestAt,\n ...(at.firstVisibleAt === undefined ? {} : { firstVisibleMs: at.firstVisibleAt - at.startedAt }),\n ...(at.firstTextAt === undefined ? {} : { firstTextMs: at.firstTextAt - at.startedAt }),\n }\n const failureCode = at.failure ? readableTurnFailure(at.failure.error, at.failure.data) : undefined\n noteMeasuredTurnFacts(turnStreamId, { requestReceivedAt: at.requestAt, ...measured, ...(at.model ? { model: at.model } : {}),\n ...(failureCode ? { failureCode } : {}) })\n return { ...measured, trace }\n}\n\nexport function createAdmittedTurnRunner<TContext, TResource>(dependencies: TurnExecutionOptions<TContext, TResource>) {\n return (runAdmittedTurn<TContext, TResource>).bind(null, dependencies)\n}\n\nasync function runAdmittedTurn<TContext, TResource>({\n options, draftStore, draftTuning, progressMessages, traceOptions, traceSink, startIntentLine, log,\n}: TurnExecutionOptions<TContext, TResource>,\n request: Request,\n ctx: ChatTurnRequestContext | undefined,\n admitted: AdmittedTurn<TContext>,\n early: AfterAuthorizeWork<TResource>,\n progress?: TurnProgressCallback,\n startedIntent?: Promise<string | null>,\n): Promise<Response> {\n const { parsed, auth, trace } = admitted\n // A progress-first turn started its line at admission; any other starts it here.\n const intentLine = startedIntent ?? startIntentLine(admitted)\n const { payload, content, fileParts, mentions, turnId } = parsed\n const { tenantId, userId, context } = auth\n\n const preparedBatch = await prepareAdmittedTurn(options, trace, log, tenantId, userId, payload, context, request, progress, content, turnId, draftTuning, ctx?.waitUntil)\n if (preparedBatch instanceof Response) return preparedBatch\n const { turnStreamId, identity, executionId, chatTurn, readHistory, historyBeforeLock } = preparedBatch\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 // A product calls this only after it has durably registered the external\n // completion owner and before it dispatches native execution. Keeping the\n // public field optional preserves existing synthetic producers; this\n // assembled route always supplies it to the real `produce` invocation.\n const state = createAdmittedTurnState<TContext>()\n if (options.cancel) state.cancellationAbort = new AbortController()\n\n state.nativeTiming = createNativeTimingTransfer(() => ({\n turnStreamId, requestReceivedAt: trace.startedAt,\n ...(state.turnStarted ? { lifecycleStartedAt: state.turnStartedAtMs, admissionMs: state.turnStartedAtMs - trace.startedAt } : {}),\n ...(state.firstVisibleAtMs === undefined ? {} : { firstVisibleMs: state.firstVisibleAtMs - state.turnStartedAtMs }),\n ...(state.firstTextAtMs === undefined ? {} : { firstTextMs: state.firstTextAtMs - state.turnStartedAtMs }),\n }), error => log('[chat-routes] native timing persistence failed', { turnId: turnStreamId,\n error: error instanceof Error ? error.message : String(error) }))\n const { handoffCompletion, releaseLock } = createChatTurnOwnership(state, log, turnStreamId, options)\n\n let produceArgs: ChatTurnProduceArgs<TContext, TResource> = {\n request,\n waitUntil: ctx?.waitUntil,\n earlyResource: early.resource,\n admissionSignal: AbortSignal.any([\n state.executionAbort.signal,\n ...(state.cancellationAbort ? [state.cancellationAbort.signal] : []),\n ...(ctx?.cancelOnDisconnect ? [request.signal] : []),\n ]),\n body: payload,\n identity,\n context,\n prompt,\n executionId,\n turnStreamId,\n priorMessages: chatTurn.priorMessages, ...(chatTurn.reusedUserMessageId ? { userMessageId: chatTurn.reusedUserMessageId, userMessageInserted: false } : {}),\n handoffCompletion,\n timingFacts: state.nativeTiming.snapshot,\n trace,\n ...(intentLine ? { intentLine } : {}), ...(admitted.prefetched ? { prefetched: admitted.prefetched } : {}),\n ...(ctx?.executionLimits ? { executionLimits: ctx.executionLimits } : {}),\n }\n // Responders named from the product's own catalog, before any lock, row or model call.\n const addressed = await addressAgents({ options, mentions, identity, context, produceArgs, trace })\n if (addressed instanceof Response) return addressed\n produceArgs = addressed\n const selected = selectTurnProducer(options.produce, produceArgs)\n // Responders answer one after another, so nothing starts before the lock.\n const dispatched = produceArgs.agents ? undefined : dispatchFirstFor(selected, produceArgs, trace)\n if (dispatched) early.add(dispatched.refuse)\n const turnLock = options.turnLock\n if (turnLock) {\n const acquired = await trace.measure('admission.lock', 'admission', () => turnLock.acquire(produceArgs))\n if (!acquired.acquired) return acquired.response\n state.lockAcquired = true\n state.lockHandle = acquired.handle\n if (acquired.cancellation) {\n const cancellation = acquired.cancellation\n const abort = () => state.executionAbort.abort(cancellation.signal.reason)\n if (cancellation.signal.aborted) abort()\n else cancellation.signal.addEventListener('abort', abort, { once: true })\n state.closeCancellation = async () => {\n cancellation.signal.removeEventListener('abort', abort)\n await cancellation.close()\n }\n }\n }\n progress?.('preparing', progressMessages.preparing)\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\n // Set once persistence settles; `undefined` means it never ran.\n\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 { endTrace, exportTraceInBackground, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle } = createTurnSettlement(state, trace, options, executionId, traceSink, identity, traceOptions, context, turnStreamId, log, ctx, () => produceArgs.userMessageId)\n\n try {\n if (state.lockAcquired && JSON.stringify(await trace.measure('admission.history_recheck', 'admission', readHistory)) !== historyBeforeLock) {\n await releaseLock()\n return Response.json({\n code: 'chat_history_changed',\n error: 'The conversation changed while this turn was acquiring its lock. Refresh the conversation before starting new work.',\n }, { status: 409 })\n }\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 let userMessageInserted = false\n if (insertUserMessage) {\n userMessageId = rowIdOf(\n await trace.measure('admission.persist_user', 'admission', () => options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts, mentions),\n })),\n )\n userMessageInserted = userMessageId !== null\n }\n produceArgs = { ...produceArgs, userMessageId, userMessageInserted }\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 const contextGate = options.contextGate\n if (contextGate) {\n const gate = await trace.measure('admission.gate', 'admission', () => contextGate(produceArgs))\n if (gate.proceed === 'handoff') {\n await releaseLock()\n state.legacyHandoff = true\n endTrace(false, undefined)\n exportTraceInBackground()\n return gate.response\n }\n if (!gate.proceed) {\n await releaseLock()\n if (state.completionHandoff) {\n endTrace(false, undefined)\n exportTraceInBackground()\n return gate.response\n }\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 state.gatedTurn = true\n state.turnStartedAtMs = Date.now()\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: state.turnStartedAtMs,\n requestReceivedAt: trace.startedAt, admissionMs: state.turnStartedAtMs - trace.startedAt,\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 exportTraceInBackground()\n return gate.response\n }\n }\n\n // Observe + optionally augment the assembled producer input.\n const beforeTurn = options.beforeTurn\n if (beforeTurn) {\n const patch = await trace.measure('admission.before_turn', 'admission', (span) => beforeTurn(produceArgs, { span }))\n if (patch && Object.keys(patch).length && dispatched) throw new Error('beforeTurn cannot patch a Router turn already dispatched: its prompt is already sent')\n if (patch) produceArgs = { ...produceArgs, ...patch }\n }\n const streamSetup = trace.start('admission.stream_setup', 'admission')\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 state.tap = createBufferedTurnTap({\n store: options.turnStore,\n turnId: turnStreamId,\n scopeId: payload.threadId,\n coalesce: coalesceDeltas,\n })\n const turnMarker = { type: 'turn', turnId: turnStreamId }\n await state.tap.onEvent(turnMarker)\n if (state.completionHandoff) await state.tap!.detach()\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 state.draft = createAssistantDraftWriter({\n ...draftTuning,\n store: draftStore,\n threadId: payload.threadId,\n messageId: assistantRowIdForTurn(executionId),\n snapshot: () => {\n if (!state.producer || state.cancellationAbort?.signal.aborted) return null\n return {\n content: state.producer.finalText(),\n ...(state.producer.draftParts ? { parts: state.producer.draftParts() } : {}),\n ...(state.producer.usage ? { usage: state.producer.usage() } : {}),\n ...(state.producer.model ? { model: state.producer.model } : {}),\n }\n },\n ...(options.transformFinalText ? { transformText: options.transformFinalText } : {}),\n log,\n })\n // `contextGate` / `beforeTurn` may have handed ownership off before\n // the writer existed. Close this late-created writer immediately so it\n // cannot receive a later live event.\n if (state.completionHandoff) await state.draft.close()\n }\n\n state.turnStartedAtMs = Date.now()\n state.turnStarted = true\n if (options.lifecycle?.onTurnStart) {\n try {\n await options.lifecycle.onTurnStart({\n identity, executionId, turnStreamId, context, startedAt: state.turnStartedAtMs,\n requestReceivedAt: trace.startedAt, admissionMs: state.turnStartedAtMs - trace.startedAt,\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 streamSetup.end()\n\n const { result } = createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, trace, options, selected.produce, request, context, payload, assistantRowId)\n\n // The engine has the turn, and its first pull runs `produce`, which owns whatever `afterAuthorize` started.\n const { clientBody } = startTurnDrain(result, log, turnStreamId, state, endTrace, exportTrace, trace, ctx, request, fireTerminalLifecycle, releaseLock, runAfterSettle, early.settle)\n early.handOff()\n\n return createTurnReplayResponse(result.contentType, clientBody, turnMarker, trace)\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 (!state.completionHandoff) {\n if (state.turnStarted) await fireTerminalLifecycle(true, err)\n await releaseLock()\n }\n // A turn that failed before it started, or after a durable owner took it, still ends its trace here.\n endTrace(true, err)\n exportTraceInBackground()\n throw err\n }\n}\ninterface AdmittedTurnState<TContext> {\n executionAbort: AbortController\n closeCancellation: (() => Promise<void>) | undefined\n draft: AssistantDraftWriter | undefined\n tap: BufferedTurnTap | undefined\n nativeTiming: NativeTimingTransfer | undefined\n completionHandoff: boolean\n completionHandoffPromise: Promise<void> | undefined\n lockAcquired: boolean\n lockHandle: unknown\n lockReleased: boolean\n cancellationAbort?: AbortController\n producer: ChatTurnRouteProducer | undefined\n assistantMessageId: string | null | undefined\n runFailed: boolean\n lastFailureData: Record<string, unknown> | undefined\n turnStartedAtMs: number\n firstVisibleAtMs: number | undefined\n firstTextAtMs: number | undefined\n turnStarted: boolean\n lifecycleSettled: boolean\n settledTurn: ChatTurnLifecycleComplete<TContext> | undefined\n gatedTurn: boolean\n legacyHandoff: boolean\n pendingTraceExport: (() => void | Promise<void>) | undefined\n traceEnded: boolean\n}\n\nfunction createAdmittedTurnState<TContext>(): AdmittedTurnState<TContext> {\n return {\n executionAbort: new AbortController(), closeCancellation: undefined,\n draft: undefined,\n tap: undefined,\n nativeTiming: undefined,\n completionHandoff: false,\n completionHandoffPromise: undefined,\n lockAcquired: false,\n lockHandle: undefined,\n lockReleased: false,\n producer: undefined,\n assistantMessageId: undefined,\n runFailed: false,\n lastFailureData: undefined,\n turnStartedAtMs: 0,\n firstVisibleAtMs: undefined,\n firstTextAtMs: undefined,\n turnStarted: false,\n lifecycleSettled: false,\n settledTurn: undefined,\n gatedTurn: false,\n legacyHandoff: false,\n pendingTraceExport: undefined,\n traceEnded: false,\n }\n}\n\nasync function prepareAdmittedTurn<TContext, TResource>(\n options: TurnExecutionOptions<TContext, TResource>['options'],\n trace: AdmittedTurn<TContext>['trace'],\n log: (message: string, meta?: Record<string, unknown>) => void,\n tenantId: string,\n userId: string,\n payload: AdmittedTurn<TContext>['parsed']['payload'],\n context: TContext,\n request: Request,\n progress: TurnProgressCallback | undefined,\n content: string,\n turnId: string | undefined,\n draftTuning: TurnExecutionOptions<TContext, TResource>['draftTuning'],\n waitUntil: ChatTurnRequestContext['waitUntil'],\n) {\n if (options.turnLock?.warm) {\n // Overlaps the lock's first-use cost with prepareTurn and the history read.\n // Its span shows that cost: waking the workspace channel that holds the lock.\n const warmSpan = trace.start('admission.lock_warm', 'admission')\n const warmFailed = (err: unknown) => {\n warmSpan.end(undefined, err)\n log('[chat-routes] turnLock.warm failed', { error: err instanceof Error ? err.message : String(err) })\n }\n try {\n void Promise.resolve(options.turnLock.warm({ tenantId, userId, threadId: payload.threadId, context })).then(() => warmSpan.end(), warmFailed)\n } catch (err) {\n warmFailed(err)\n }\n }\n\n const prepareTurn = options.prepareTurn\n if (prepareTurn) {\n const prepared = await trace.measure('admission.prepare', 'admission', () => prepareTurn({\n request,\n waitUntil,\n body: payload,\n tenantId,\n userId,\n threadId: payload.threadId,\n context,\n progress: (phase, message) => progress?.(phase, message),\n }))\n if (!prepared.ok) return prepared.response\n }\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 readHistory = () => readTurnHistory(options.store, payload.threadId)\n const historySpan = trace.start('admission.history', 'admission')\n const existingMessages = await readHistory()\n // Lock acquisition is async and follows identity derivation. A previous\n // owner can settle in that gap; the new owner must not dispatch an identity\n // or prompt derived from the old history. Capture values now, including\n // parts, rather than retaining mutable message references across the lock.\n const historyBeforeLock = options.turnLock ? JSON.stringify(existingMessages) : undefined\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 //\n // The probe can only change the answer when the running reading would\n // reuse a row (no client turnId, and the user row behind the trailing\n // assistant rows repeats this content); the settled reading never reuses\n // past a trailing assistant row. Every other turn, including each ordinary\n // follow-up, skips the round trip with an identical result.\n let chatTurn = resolveChatTurn({ existingMessages, userContent: content, turnId, hasRunningTurn: false })\n if (draftTuning && existingMessages.at(-1)?.role === 'assistant') {\n const ifRunning = resolveChatTurn({ existingMessages, userContent: content, turnId, hasRunningTurn: true })\n if (!ifRunning.shouldInsertUserMessage) {\n let hasRunningTurn = false\n try {\n hasRunningTurn = ((await trace.measure('admission.running_probe', 'admission', () => options.turnStore.listRunning?.(payload.threadId), undefined, historySpan)) ?? []).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 if (hasRunningTurn) chatTurn = ifRunning\n }\n }\n historySpan.end({ messages: existingMessages.length })\n\n const identity: ChatTurnIdentity = {\n tenantId,\n sessionId: payload.threadId,\n userId,\n turnIndex: chatTurn.turnIndex,\n }\n const turnExecutionId = deriveExecutionId({\n projectId: options.projectId,\n sessionId: payload.threadId,\n turnIndex: chatTurn.turnIndex,\n })\n // Message identity preserves the original inputs; an explicit retry starts\n // another native execution with its own immutable completion receipt.\n const executionId = payload.retryAttemptId\n ? `${turnExecutionId}:retry:${payload.retryAttemptId}`\n : turnExecutionId\n if (executionId.length > 256) return errorResponse(new ChatTurnInputError('Retry execution id exceeds 256 bytes'))\n // From here the trace's id is the turn's execution id, the id every Router and Sandbox call sends.\n trace.bind(executionId)\n const turnStreamId = crypto.randomUUID()\n return { turnStreamId, identity, executionId, chatTurn, readHistory, historyBeforeLock }\n}\n\nfunction createTurnSettlement<TContext, TResource>(\n state: AdmittedTurnState<TContext>,\n trace: AdmittedTurn<TContext>['trace'],\n options: TurnExecutionOptions<TContext, TResource>['options'],\n executionId: string,\n traceSink: TurnExecutionOptions<TContext, TResource>['traceSink'],\n identity: ChatTurnIdentity,\n traceOptions: TurnExecutionOptions<TContext, TResource>['traceOptions'],\n context: TContext,\n turnStreamId: `${string}-${string}-${string}-${string}-${string}`,\n log: (message: string, meta?: Record<string, unknown>) => void,\n ctx: ChatTurnRequestContext | undefined,\n userMessageId: () => string | null | undefined,\n) {\n const assistantRowId = (): string | null => state.assistantMessageId ?? state.draft?.rowId() ?? null\n\n // Data of the event that marked the run failed — handed to `onTurnError`\n // when no drain throw supplies a richer cause.\n\n // Answer text stays separate from reasoning and tools.\n\n // What `lifecycle.afterSettle` receives: set when the turn ended cleanly with a producer that ran.\n\n // Set when `contextGate` answered the turn without running the producer.\n\n // Set when `contextGate` handed the turn to the product's durable owner (`{ proceed: 'handoff' }`).\n\n /**\n * End the turn's trace once: write its summary line, and arm its export for `exportTrace`. A turn handed to a\n * durable owner ends here when this request's live projection ends; the owner settles everything else.\n */\n const endTrace = (failed: boolean, terminalError: unknown): TurnTraceSnapshot => {\n const failureCode = failed\n ? (failureCodeOf(state.lastFailureData) ?? (terminalError instanceof Error ? terminalError.name : 'turn_failed'))\n : undefined\n const snapshot = trace.finish(failureCode === undefined ? {} : { error: failureCode })\n if (state.traceEnded) return snapshot\n state.traceEnded = true\n const handedOff = state.completionHandoff || state.legacyHandoff\n // One line per turn in the host's logs (Workers Logs), so first text and coverage are readable without Intelligence.\n console.info(JSON.stringify({\n event: 'agent_app_turn_trace',\n project: options.projectId,\n executionId,\n otlpTraceId: otlpTraceId(snapshot.traceId),\n failed,\n ...(failureCode ? { failureCode } : {}),\n ...(handedOff ? { handedOff: true } : {}),\n ...(state.gatedTurn ? { gated: true } : {}),\n ...snapshot.summary,\n }))\n // Sent by `exportTrace`, after the turn lock is released: a slow collector must not hold the next send.\n const sink = traceSink\n if (sink) {\n state.pendingTraceExport = () => sink(snapshot, {\n 'tangle.sessionId': identity.sessionId,\n 'tangle.userId': identity.userId,\n 'tangle.tenantId': identity.tenantId,\n 'tangle.turn.failed': failed,\n ...(state.gatedTurn ? { 'tangle.turn.gated': true } : {}),\n ...(handedOff ? { 'tangle.turn.handed_off': true } : {}),\n ...(failureCode ? { 'tangle.turn.failure_code': failureCode } : {}),\n ...(traceOptions?.labels?.({ identity, executionId, context }) ?? {}),\n })\n }\n return snapshot\n }\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 (state.lifecycleSettled) return\n state.lifecycleSettled = true\n // The trace ends with the turn, before the product's own hooks run, so their work is not in its wall time.\n const snapshot = endTrace(failed, terminalError)\n const lifecycle = options.lifecycle\n const backend = { userMessageId: userMessageId(),\n backendTerminal: Boolean(state.producer) && (state.producer?.terminalObserved?.() ?? true) }\n const durationMs = Date.now() - state.turnStartedAtMs\n const timing = settledTurnTiming(turnStreamId, {\n requestAt: trace.startedAt, startedAt: state.turnStartedAtMs,\n firstVisibleAt: state.firstVisibleAtMs, firstTextAt: state.firstTextAtMs, model: state.producer?.model,\n failure: failed ? { data: state.lastFailureData, error: terminalError } : undefined,\n }, snapshot.summary)\n try {\n if (!lifecycle) {\n // No hooks to run; the trace still goes to its sink below.\n } else if (failed) {\n await lifecycle.onTurnError?.({\n identity, executionId, turnStreamId, context, durationMs, ...timing, ...backend,\n error: terminalError ?? state.lastFailureData ?? new Error('chat turn failed'),\n })\n } else {\n const failoverInfo = state.producer?.modelFailover?.()\n const attribution = state.producer?.modelAttribution?.()\n const completed: ChatTurnLifecycleComplete<TContext> = {\n identity, executionId, turnStreamId, context, durationMs, ...timing, ...backend,\n finalText: state.cancellationAbort?.signal.aborted ? '' : state.producer?.finalText() ?? '',\n usage: state.producer?.usage?.() ?? {},\n assistantMessageId: assistantRowId(),\n ...(state.gatedTurn ? { gated: true } : {}),\n ...(state.producer?.model ? { model: state.producer.model } : {}),\n ...modelAttributionFields(attribution),\n ...(failoverInfo ? { modelFailover: failoverInfo } : {}),\n }\n if (!state.gatedTurn) state.settledTurn = completed\n await lifecycle.onTurnComplete?.(completed)\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 /** Send the finished trace to its sink. Never throws. */\n const exportTrace = async (): Promise<void> => {\n const send = state.pendingTraceExport\n state.pendingTraceExport = undefined\n if (!send) return\n try {\n await send()\n } catch (err) {\n log('[chat-routes] turn trace sink failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n /** The product's follow-up work for a turn that ended cleanly, once its lock is released. Never throws. */\n const runAfterSettle = async (): Promise<void> => {\n const info = state.settledTurn\n state.settledTurn = undefined\n const afterSettle = options.lifecycle?.afterSettle\n if (!info || !afterSettle) return\n try {\n await afterSettle(info)\n } catch (err) {\n log('[chat-routes] lifecycle.afterSettle failed', {\n turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n /** Export after the response is on its way: under `waitUntil` where the host has one. */\n const exportTraceInBackground = (): void => {\n const sent = exportTrace()\n if (ctx?.waitUntil) ctx.waitUntil(sent)\n else void sent.catch(() => { })\n }\n return { endTrace, exportTraceInBackground, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle }\n}\n\nfunction createTurnEngine<TContext, TResource>(\n identity: ChatTurnIdentity,\n ctx: ChatTurnRequestContext | undefined,\n log: (message: string, meta?: Record<string, unknown>) => void,\n state: AdmittedTurnState<TContext>,\n dispatched: ReturnType<typeof dispatchFirstFor<TContext, TResource>>,\n produceArgs: ChatTurnProduceArgs<TContext, TResource>,\n trace: AdmittedTurn<TContext>['trace'],\n options: TurnExecutionOptions<TContext, TResource>['options'],\n produce: ReturnType<typeof selectTurnProducer<TContext, TResource>>['produce'],\n request: Request,\n context: TContext,\n payload: AdmittedTurn<TContext>['parsed']['payload'],\n assistantRowId: () => string | null,\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 // The product's own admission work: its profile pin, prompt and producer construction.\n const producerStream = async function* () {\n const started = dispatched\n ? dispatched.take(produceArgs)\n : produceArgs.agents\n ? trace.measure('admission.produce', 'admission', () => composeAgentProducers(produceArgs, produce))\n : trace.measure('admission.produce', 'admission', () => produce(produceArgs))\n if (!dispatched) {\n const cleanup = started.then(producer => producer.cleanup, () => undefined)\n ctx?.waitUntil?.(cleanup)\n void cleanup.catch(() => {})\n }\n state.producer = await started\n yield* state.producer.stream\n }\n let source: AsyncIterable<ChatRouteEvent> = producerStream()\n // A durable owner connection already carries exact authenticated Stop.\n // Keep metadata observation only for existing non-adopting targets.\n if (options.cancel && state.cancellationAbort && !state.closeCancellation) {\n source = observeTurnCancellation(source, produceArgs, options.cancel, state.cancellationAbort)\n }\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: () => state.cancellationAbort?.signal.aborted ? '' : state.producer?.finalText() ?? '',\n }),\n onEvent: async (event) => {\n let timingChanged = false\n if (state.firstVisibleAtMs === undefined && isVisibleOutput(event)) {\n state.firstVisibleAtMs = Date.now()\n trace.markFirstVisible(state.firstVisibleAtMs)\n timingChanged = true\n }\n if (state.firstTextAtMs === undefined && isVisibleText(event)) {\n state.firstTextAtMs = Date.now()\n trace.markFirstText(state.firstTextAtMs)\n timingChanged = true\n }\n if (timingChanged) {\n const written = state.nativeTiming?.note()\n if (written && ctx?.waitUntil) ctx.waitUntil(written)\n }\n if (event.type === 'session.run.failed' || event.type === 'error') {\n state.runFailed = true\n state.lastFailureData = event.data\n }\n await state.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 if (!state.completionHandoff) state.draft?.notify(event)\n if (options.onEvent) await options.onEvent(event, context)\n },\n ...(options.transformFinalText ? { transformFinalText: options.transformFinalText } : {}),\n persistAssistantMessage: ({ finalText }) => trace.measure('persist.assistant', 'persist', async () => {\n if (state.completionHandoff) return\n if (state.cancellationAbort?.signal.aborted || (ctx?.cancelOnDisconnect && request.signal.aborted)) {\n await state.draft?.discard()\n state.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 = state.producer?.assistantParts ? state.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 state.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 state.assistantMessageId = state.draft?.rowId() ?? null\n return\n }\n if (state.cancellationAbort?.signal.aborted) {\n await state.draft?.discard()\n state.assistantMessageId = null\n return\n }\n const usage = state.producer?.usage?.() ?? {}\n const attribution = state.producer?.modelAttribution?.()\n const values = {\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(state.producer?.model ? { model: state.producer.model } : {}),\n ...modelAttributionFields(attribution),\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 (state.draft) {\n await state.draft.finalize(values)\n state.assistantMessageId = state.draft.rowId() ?? null\n return\n }\n state.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: async ({ identity: turnIdentity, finalText }: { identity: ChatTurnIdentity; finalText: string }) => {\n if (state.completionHandoff) return\n // Read AFTER the drain, so the model reported to billing is\n // the one that actually served — a fallback included.\n const failoverInfo = state.producer?.modelFailover?.()\n const attribution = state.producer?.modelAttribution?.()\n // The engine awaits this before the stream ends, so the product's completion work is a span, not a gap.\n return trace.measure('persist.on_turn_complete', 'persist', () => options.onTurnComplete!({\n identity: turnIdentity,\n userMessageId: produceArgs.userMessageId,\n backendTerminal: state.producer?.terminalObserved?.() ?? true,\n finalText,\n context,\n failed: state.runFailed,\n usage: state.producer?.usage?.(),\n assistantMessageId: assistantRowId(),\n ...(state.runFailed ? { failureReason: failureReasonOf(state.lastFailureData) } : {}),\n ...(state.runFailed && failureCodeOf(state.lastFailureData) ? { failureCode: failureCodeOf(state.lastFailureData) } : {}),\n ...(state.producer?.model ? { model: state.producer.model } : {}),\n ...modelAttributionFields(attribution),\n ...(failoverInfo ? { modelFailover: failoverInfo } : {}),\n }))\n },\n }\n : {}),\n ...(options.traceFlush ? { traceFlush: () => options.traceFlush!(context) } : {}),\n },\n })\n return { result }\n}\n\nfunction startTurnDrain<TContext>(\n result: ReturnType<typeof handleChatTurn>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n turnStreamId: `${string}-${string}-${string}-${string}-${string}`,\n state: AdmittedTurnState<TContext>,\n endTrace: (failed: boolean, terminalError: unknown) => TurnTraceSnapshot,\n exportTrace: () => Promise<void>,\n trace: AdmittedTurn<TContext>['trace'],\n ctx: ChatTurnRequestContext | undefined,\n request: Request,\n fireTerminalLifecycle: (failed: boolean, terminalError: unknown) => Promise<void>,\n releaseLock: () => Promise<void>,\n runAfterSettle: () => Promise<void>,\n settleResource: () => Promise<void>,\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 = state.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 (state.completionHandoff) {\n // The external owner settles transcript, lifecycle, lock and replay\n // status. Flush only the post-handoff live projection; EOF is an\n // observation stop, never a terminal verdict for that owner. The\n // trace is this request's own record, so it ends here.\n endTrace(failed, drainError)\n await Promise.all([state.tap!.detach(), state.nativeTiming?.flush(), exportTrace()])\n return\n }\n const finalize = trace.start('persist.finalize', 'persist')\n if (state.cancellationAbort?.signal.aborted || (ctx?.cancelOnDisconnect && request.signal.aborted)) {\n await state.draft?.discard()\n } else {\n await state.draft?.close()\n }\n try {\n await state.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 finalize.end()\n await fireTerminalLifecycle(failed, drainError)\n await releaseLock()\n // Both run after the lock is released and inside this waitUntil-tracked drain, so neither holds the next send.\n await Promise.all([exportTrace(), runAfterSettle()])\n })().finally(settleResource)\n if (ctx?.waitUntil) ctx.waitUntil(drained)\n else void drained.catch(() => { })\n return { clientBody }\n}\n\n\nfunction createTurnReplayResponse(\n contentType: string,\n clientBody: ReadableStream<Uint8Array>,\n turnMarker: { type: string; turnId: string },\n trace: Parameters<typeof admissionServerTiming>[0],\n): Response {\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': contentType,\n 'Cache-Control': 'no-cache',\n 'X-Turn-Id': turnMarker.turnId,\n 'Server-Timing': admissionServerTiming(trace),\n },\n })\n}\n","/** Serializable route observations transferred to the existing native admission owner. */\nimport type { NativeTurnTimingFacts } from '../turn-trace/turn-facts'\nexport type { NativeTurnTimingFacts } from '../turn-trace/turn-facts'\n\nexport interface NativeCompletionHandoffOptions {\n /** Persist on the existing admission, keyed by turnStreamId. Initial origin must survive before handoff. */\n persistTimingFacts?(facts: NativeTurnTimingFacts): Promise<void>\n}\n\nexport interface NativeTimingTransfer {\n snapshot(): NativeTurnTimingFacts\n register(options?: NativeCompletionHandoffOptions): Promise<void>\n note(): Promise<void>\n flush(): Promise<void>\n}\n\n/** Initial registration is fail-closed. Later observations are serialized and waitUntil-tracked by the route. */\nexport function createNativeTimingTransfer(\n read: () => NativeTurnTimingFacts,\n onError: (error: unknown) => void,\n): NativeTimingTransfer {\n let persist: NativeCompletionHandoffOptions['persistTimingFacts']\n let pending = Promise.resolve()\n return {\n snapshot: () => ({ ...read() }),\n async register(options) {\n if (!options?.persistTimingFacts) return\n await options.persistTimingFacts({ ...read() })\n persist = options.persistTimingFacts\n },\n note() {\n if (!persist) return pending\n const snapshot = { ...read() }\n const write = persist\n pending = pending.then(() => write(snapshot)).catch(onError)\n return pending\n },\n flush: () => pending,\n }\n}\n","import type { AssistantDraftWriter } from './draft-persistence'\nimport type { NativeCompletionHandoffOptions, NativeTimingTransfer } from './native-turn-timing'\nimport type { BufferedTurnTap } from '../stream/index'\nimport type { ChatTurnLock, ChatTurnRouteProducer } from './turn-route-contracts'\n\ninterface OwnershipState {\n producer?: ChatTurnRouteProducer\n completionHandoff: boolean\n completionHandoffPromise: Promise<void> | undefined\n nativeTiming: NativeTimingTransfer | undefined\n tap: BufferedTurnTap | undefined\n draft: AssistantDraftWriter | undefined\n lockAcquired: boolean\n lockReleased: boolean\n lockHandle: unknown\n closeCancellation?: () => Promise<void>\n}\n\n/** One transfer of terminal authority, retaining the route only as a live projector. */\nexport function createChatTurnOwnership(state: OwnershipState,\n log: (message: string, meta?: Record<string, unknown>) => void, turnStreamId: string,\n options: { turnLock?: Pick<ChatTurnLock<unknown>, 'release' | 'park'> },\n) {\n // A cleanup step that fails is logged and never stops the steps after it.\n const attempt = async (step: string, run: () => unknown): Promise<void> => {\n try { await run() } catch (err) { log(`[chat-routes] ${step} failed`, { turnId: turnStreamId, error: err instanceof Error ? err.message : String(err) }) }\n }\n const handoffCompletion = (handoff?: NativeCompletionHandoffOptions): Promise<void> => {\n if (!state.completionHandoffPromise) {\n state.completionHandoffPromise = (async () => {\n // Product registration already owns this turn. A callback failure must never\n // restore the route's terminal authority or permit a second settlement.\n state.completionHandoff = true\n let registrationFailed = false\n try {\n await state.nativeTiming?.register(handoff)\n } catch (error) {\n registrationFailed = true\n throw error\n } finally {\n await attempt('turn buffer detach', () => state.tap?.detach())\n try {\n await state.draft?.close()\n } catch (err) {\n if (!registrationFailed) throw err\n log('[chat-routes] draft close failed after native timing refusal', { turnId: turnStreamId,\n error: err instanceof Error ? err.message : String(err) })\n } finally {\n await state.closeCancellation?.()\n }\n }\n })()\n }\n return state.completionHandoffPromise\n }\n const releaseLock = async (): Promise<void> => {\n if (state.completionHandoff || !state.lockAcquired || state.lockReleased) return\n // Losing the live observation is not evidence that a detached backend stopped.\n // The exact execution stays fenced; a parked intent lets its durable owner release it once proven.\n if (state.producer?.terminalObserved && !state.producer.terminalObserved()) {\n await attempt('turnLock.park', () => options.turnLock?.park?.(state.lockHandle))\n await state.closeCancellation?.()\n return\n }\n state.lockReleased = true\n // Expected cooperative completion must not interpret its own release as\n // external loss of execution authority. A close failure must not skip release.\n await attempt('turn cancellation close', () => state.closeCancellation?.())\n await attempt('turnLock.release', () => options.turnLock!.release(state.lockHandle))\n }\n return { handoffCompletion, releaseLock }\n}\n","/** Bind backend configuration to this route's identity, trace and admission. */\nimport { createHybridTurnProducer, routerTurnHistory, turnPromptText } from './hybrid-producer'\nimport { createRouterTurnProducer } from './router-producer'\nimport { createSandboxChatProducer } from './sandbox-producer'\nimport type { ChatTurnProduceArgs, ChatTurnRouteProducer, ChatTurnRouterBackend, ChatTurnSandboxBackend } from './turn-route-contracts'\n\nfunction isProducer(value: ChatTurnRouterBackend | ChatTurnSandboxBackend): value is ChatTurnRouteProducer {\n return 'stream' in value && typeof value.stream === 'object' && value.stream !== null && Symbol.asyncIterator in value.stream\n}\n\nexport function routerRouteProducer<TContext, TResource>(value: ChatTurnRouterBackend, args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnRouteProducer {\n if (isProducer(value)) return value\n const options = {\n ...value,\n userMessage: value.userMessage ?? turnPromptText(args.prompt),\n history: value.history ?? routerTurnHistory(args.priorMessages, undefined, { pov: args.agent?.id }),\n trace: args.trace,\n traceId: args.trace?.traceId,\n signal: args.admissionSignal,\n // Domain fences may wait for a certified profile or per-turn resource.\n // They can only add a requirement; they never replace route admission.\n admitted: Promise.all([args.admitted, value.admitted]),\n }\n if (!('box' in value)) return createRouterTurnProducer(options)\n // A repeated call of the same turn's tool call is the same computer step, whatever the trace.\n const computer = value.box.computer && { parentExecutionId: args.executionId, ...value.box.computer }\n return createHybridTurnProducer({ ...options, box: { ...value.box, ...(computer ? { computer } : {}) } })\n}\n\nexport function sandboxRouteProducer<TContext, TResource>(value: ChatTurnSandboxBackend, args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnRouteProducer {\n if (isProducer(value)) return value\n const openEvents = value.openEvents\n return createSandboxChatProducer({ ...value, ...(openEvents && args.admissionSignal ? {\n openEvents: input => openEvents({ ...input, signal: AbortSignal.any([input.signal, args.admissionSignal!]) }),\n } : {}) })\n}\n","import type { ChatTurnRouteProducer } from './turn-route-contracts'\n\n/** Replace transport while keeping every capability on its original receiver.\n * Object.create alone breaks class private state; spreading snapshots getters.\n * The separate target also permits wrapping an Object.freeze'd producer. */\nexport function withProducerStream(\n producer: ChatTurnRouteProducer,\n stream: ChatTurnRouteProducer['stream'],\n): ChatTurnRouteProducer {\n return new Proxy(Object.create(producer) as ChatTurnRouteProducer, {\n get(_target, property) {\n if (property === 'stream') return stream\n const value: unknown = Reflect.get(producer, property, producer)\n return typeof value === 'function' ? value.bind(producer) : value\n },\n })\n}\n","/** Router calls overlap the lock, history recheck, user insert and gates.\n * authorize already verified identity/access; the model service enforces spend.\n * Events remain buffered until admission commits. Refusal cancels the call and\n * drops its output; tools and durable effects must wait for args.admitted.\n * Ordinary functions and Sandbox backends never execute speculatively.\n */\nimport type { TurnTrace } from '../turn-trace/recorder'\nimport type { NativeCompletionHandoffOptions } from './native-turn-timing'\nimport type { ChatRouteEvent, ChatTurnProduceArgs, ChatTurnRouteProducer } from './turn-route-contracts'\nimport { routerRouteProducer, sandboxRouteProducer } from './route-producer'\nimport { withProducerStream } from './producer-stream'\nimport type { ResolvedChatTurnRoutesOptions } from './route-storage'\n\n/** Thrown into `args.admitted` when the turn was refused after its producer started. */\nclass TurnAdmissionRefusedError extends Error {\n constructor() {\n super('The turn was refused after its producer started; its output was discarded.')\n this.name = 'TurnAdmissionRefusedError'\n }\n}\n\nexport interface DispatchedProducer<TContext, TResource = unknown> {\n /** The admission chain committed: hand the producer its final args and return it, with what it already emitted first. */\n take(args: ChatTurnProduceArgs<TContext, TResource>): Promise<ChatTurnRouteProducer>\n /** The turn ended without the producer: abort it and discard its output. Idempotent; a no-op after `take`. */\n refuse(): void\n}\n\n/**\n * Start `produce` now with the args known before the lock. `args.admitted`\n * resolves to the final args at `take`, or rejects at `refuse`; the producer\n * writes nothing durable before it resolves. Its stream is drained into memory\n * from the start, so a producer that only works while pulled still dispatches.\n */\nfunction dispatchProducerFirst<TContext, TResource = unknown>(\n produce: (args: ChatTurnProduceArgs<TContext, TResource>) => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>,\n args: ChatTurnProduceArgs<TContext, TResource>,\n trace: TurnTrace,\n): DispatchedProducer<TContext, TResource> {\n const abort = new AbortController()\n let admit!: (final: ChatTurnProduceArgs<TContext, TResource>) => void\n let reject!: (error: Error) => void\n const admitted = new Promise<ChatTurnProduceArgs<TContext, TResource>>((resolve, fail) => { admit = resolve; reject = fail })\n // A producer that never awaits `admitted` must not raise an unhandled rejection when the turn is refused.\n admitted.catch(() => {})\n let settled: 'taken' | 'refused' | undefined\n // Set when nobody will read the producer again: a refusal, or the route's reader closing after `take`.\n let stopped = false\n\n const queue: ChatRouteEvent[] = []\n let ended = false\n let failure: { error: unknown } | undefined\n let wake: (() => void) | undefined\n const notify = () => { const resume = wake; wake = undefined; resume?.() }\n let source: AsyncIterator<ChatRouteEvent> | undefined\n\n // A registered durable owner settles the transcript and the lock, so a producer may hand off only a committed turn.\n const handoffCompletion = args.handoffCompletion\n const started = trace.measure('admission.produce', 'admission', () => produce({\n ...args,\n admitted,\n admissionSignal: args.admissionSignal ? AbortSignal.any([args.admissionSignal, abort.signal]) : abort.signal,\n ...(handoffCompletion ? { handoffCompletion: (options?: NativeCompletionHandoffOptions) => admitted.then(() => handoffCompletion(options)) } : {}),\n }))\n // Register before construction resolves: admission can refuse and return\n // while a producer is still awaiting an ephemeral credential or resource.\n const cleanup = started.then(producer => producer.cleanup, () => undefined)\n args.waitUntil?.(cleanup)\n void cleanup.catch(() => {})\n const draining = started.then(async (producer) => {\n try {\n source = producer.stream[Symbol.asyncIterator]()\n for (;;) {\n const next = await source.next()\n if (next.done || stopped) break\n queue.push(next.value)\n notify()\n }\n } catch (error) {\n if (!stopped) failure = { error }\n } finally {\n ended = true\n notify()\n }\n }, (error: unknown) => {\n failure = { error }\n ended = true\n notify()\n })\n\n /** Nobody reads this producer again: abort its model call, close its stream and drop what it queued. */\n const stop = (reason: Error) => {\n if (stopped) return\n stopped = true\n abort.abort(reason)\n queue.length = 0\n notify()\n // A producer that ignores the signal is closed too; one suspended at an await finishes that await first.\n void started.then(() => source?.return?.(), () => {}).catch(() => {})\n }\n\n async function* replay(): AsyncGenerator<ChatRouteEvent, void, unknown> {\n try {\n for (;;) {\n while (queue.length) yield queue.shift()!\n if (ended) break\n await new Promise<void>((resolve) => { wake = resolve })\n }\n await draining\n if (failure) throw failure.error\n } finally {\n // The route stopped reading early (a disconnect under `cancelOnDisconnect`, an engine stop): stop the producer\n // as closing its own stream would have.\n if (!ended) stop(new Error('The turn stopped reading its producer.'))\n }\n }\n\n return {\n async take(final) {\n if (settled) throw new Error(`dispatch-first producer already ${settled}`)\n settled = 'taken'\n admit(final)\n const producer = await started\n return withProducerStream(producer, replay())\n },\n refuse() {\n if (settled) return\n settled = 'refused'\n reject(new TurnAdmissionRefusedError())\n stop(new TurnAdmissionRefusedError())\n },\n }\n}\n\n/** Select once, so admission's context mutations cannot switch execution backends. */\nexport function selectTurnProducer<TContext, TResource = unknown>(\n produce: ResolvedChatTurnRoutesOptions<TContext, TResource>['produce'],\n args: ChatTurnProduceArgs<TContext, TResource>,\n) {\n if (typeof produce === 'function') return { produce, router: false }\n if (produce.when?.(args) ?? true) return {\n produce: async (final: ChatTurnProduceArgs<TContext, TResource>) => routerRouteProducer(await produce.router(final), final),\n router: true,\n }\n if (!produce.sandbox) throw new Error('The turn selected the Sandbox backend without a Sandbox producer')\n const sandbox = produce.sandbox\n return { produce: async (final: ChatTurnProduceArgs<TContext, TResource>) => sandboxRouteProducer(await sandbox(final), final), router: false }\n}\n\n/** A reused user row must pass duplicate/refusal checks before another model call. */\nexport function dispatchFirstFor<TContext, TResource = unknown>(\n selected: ReturnType<typeof selectTurnProducer<TContext, TResource>>,\n args: ChatTurnProduceArgs<TContext, TResource>,\n trace: TurnTrace,\n): DispatchedProducer<TContext, TResource> | undefined {\n return selected.router && !args.userMessageId ? dispatchProducerFirst(selected.produce, args, trace) : undefined\n}\n","/** Stream framing, event inspection and cancellation around a chat producer. */\nimport type { ChatRouteEvent } from './turn-route-contracts'\n\n/** Best-effort human-readable cause from a terminal `error` /\n * `session.run.failed` event's `data`. */\nexport function 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/** The typed reason a terminal `error` / `session.run.failed` event's `data`\n * names, e.g. `sandbox.stream_failed` or an upstream code. */\nexport function failureCodeOf(data: Record<string, unknown> | undefined): string | undefined {\n const code = data?.code\n return typeof code === 'string' && code.length > 0 ? code : undefined\n}\n\n/** A word the user sees: a producer `text` event, or a sandbox text part delta. */\nexport function isVisibleText(event: ChatRouteEvent): boolean {\n const value = event as ChatRouteEvent & { text?: unknown }\n if (event.type === 'text') return typeof value.text === 'string' ? value.text.trim().length > 0 : true\n if (event.type !== 'message.part.updated') return false\n const part = event.data?.part as { type?: unknown } | undefined\n const delta = event.data?.delta\n return part?.type === 'text' && typeof delta === 'string' && delta.trim().length > 0\n}\n\n/** Output rendered by either lane; admission/status/usage events are not model output. */\nexport function isVisibleOutput(event: ChatRouteEvent): boolean {\n if (isVisibleText(event)) return true\n const value = event as ChatRouteEvent & { text?: unknown }\n if (event.type === 'reasoning') return typeof value.text === 'string' && value.text.trim().length > 0\n if (event.type === 'tool_call' || event.type === 'tool.call' || event.type === 'tool_result' || event.type === 'tool.result' || event.type === 'tool.event') return true\n if (event.type !== 'message.part.updated') return false\n const part = event.data?.part as { type?: unknown; text?: unknown } | undefined\n if (part?.type === 'tool') return true\n if (part?.type !== 'reasoning' && part?.type !== 'text') return false\n const text = event.data?.delta ?? part.text\n return typeof text === 'string' && text.trim().length > 0\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. */\nexport async 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. */\nexport async 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/** Sequential concat of byte streams (marker line, then the engine body). */\nexport function 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 */\nexport async 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","/** Request-owned speculative work: legacy release callbacks and opaque resource lifetimes. */\nimport type { ChatTurnAfterAuthorizeRelease } from './turn-route-contracts'\nimport { redactErrorMessage } from '../redact/index'\n\nexport interface AfterAuthorizeWork<TResource = unknown> {\n resource?: Promise<TResource>\n handOff(): void\n release(): Promise<void>\n settle(): Promise<void>\n add(release: () => void): void\n}\n\nexport function earlyTurnWork<TResource>(\n started: ChatTurnAfterAuthorizeRelease<TResource> | undefined,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AfterAuthorizeWork<TResource> {\n let free = typeof started === 'function' ? started : undefined\n const owned = typeof started === 'object' ? started : undefined\n void owned?.resource.catch(() => {})\n let handedOff = false\n let stopped: Promise<void> | undefined\n let also: Array<() => void> = []\n const report = (error: unknown) => log('[chat-routes] afterAuthorize release failed', { error: redactErrorMessage(error) })\n const settle = (): Promise<void> => stopped ??= (async () => {\n if (owned) await owned.dispose(await owned.resource)\n })().catch(report)\n return {\n resource: owned?.resource,\n handOff: () => { handedOff = true; free = undefined; also = [] },\n add: release => { also.push(release) },\n settle,\n release: async () => {\n const product = free\n const route = also\n free = undefined\n also = []\n for (const stop of route) stop()\n if (product) await Promise.resolve().then(product).catch(report)\n if (!handedOff) await settle()\n },\n }\n}\n","/** The template's backend assembly. Products supply policy; routes own lane selection. */\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { Harness } from '../harness/index'\nimport { createD1PrewarmClaimStore } from '../sandbox/prewarm-claim-d1'\nimport { runForegroundSandboxSingleFlight } from '../sandbox/foreground-single-flight'\nimport { ensureWorkspaceSandbox, peekWorkspaceSandbox, streamSandboxPrompt } from '../sandbox/index'\nimport type { SandboxRuntimeConfig } from '../sandbox/configuration'\nimport { sandboxPromptExecutionOptions, type StreamSandboxPromptOptions } from '../sandbox/prompt-options'\nimport type { ChatTurnStoreBindings } from './route-storage'\nimport { turnCarriesFiles } from './hybrid-producer'\nimport { normalizeChatPromptForSandbox } from './dispatch-parts'\nimport { assertPolicy, type ModelPolicy } from '../policy-filters/index'\nimport type { ChatTurnProduceArgs, ChatTurnHybridConfiguration } from './turn-route-contracts'\nimport type { RouterTurnTool } from '../runtime/router-turn'\nimport type { RouterTurnKey } from './router-producer'\nimport type { ComputerVault } from '../sandbox/computer-files'\nimport type { Outcome } from '../sandbox/outcome'\n\n/** Worker bindings are explicit; no ambient deployment credentials replace product policy. */\nexport interface ChatTurnEnvironment {\n DB?: ChatTurnStoreBindings['db']\n TURN_STREAM?: ChatTurnStoreBindings['lock']['namespace']\n TURN_STREAM_DO?: ChatTurnStoreBindings['lock']['namespace']\n TURN_STREAM_AUTH_SECRET?: string\n D1_REGION?: ChatTurnStoreBindings['region']\n TANGLE_API_KEY?: string\n TANGLE_ROUTER_URL?: string\n MODEL_NAME?: string\n SANDBOX_API_KEY?: string\n SANDBOX_GATEWAY_URL?: string\n}\n\n/** Domain data for the default lane, instead of constructing producers or admission hooks. */\nexport interface ChatTurnDefaultBackend<TContext = unknown, TResource = unknown> {\n model?: string\n systemPrompt?: string\n harness?: Harness\n effort?: StreamSandboxPromptOptions['effort']\n interactions?: StreamSandboxPromptOptions['interactions']\n /** Existing product provisioning, credentials, profiles and egress policy remain authoritative. */\n shell?: SandboxRuntimeConfig\n /** Explicitly keep every turn on the sandbox lane. */\n router?: false\n /** Who pays for the Router model call: the turn's key, or a per-turn lease (`createDelegatedTurnKeys`) the\n * producer revokes when the turn settles. Default `TANGLE_API_KEY`. Started before the turn lock, like the call. */\n funding?(args: ChatTurnProduceArgs<TContext, TResource>): RouterTurnKey | Promise<RouterTurnKey>\n /** The product's in-process tools for the Router model; `sandbox_run` is added after them. */\n tools?(args: ChatTurnProduceArgs<TContext, TResource>): RouterTurnTool[] | Promise<RouterTurnTool[]>\n /** What the computer step does beyond running the task: copy its files into the product's Vault, and run a model\n * the box key allows (`readSandboxRouterModels` with the payer's key). */\n computer?: {\n files?(args: ChatTurnProduceArgs<TContext, TResource>): ComputerVault | undefined\n allowedModels?(args: ChatTurnProduceArgs<TContext, TResource>, signal: AbortSignal): Promise<Outcome<readonly string[] | null>>\n }\n}\n\nexport function defaultChatShell(projectId: string, env: ChatTurnEnvironment, config: ChatTurnDefaultBackend): SandboxRuntimeConfig {\n return config.shell ?? {\n credentials: () => env.SANDBOX_API_KEY?.trim() && env.SANDBOX_GATEWAY_URL?.trim()\n ? { apiKey: env.SANDBOX_API_KEY.trim(), baseUrl: env.SANDBOX_GATEWAY_URL.trim() } : null,\n name: workspaceId => `${projectId}-${workspaceId}`.slice(0, 63),\n metadata: harness => ({ app: projectId, harness }),\n connectedIntegrationIds: async () => [], env: async () => ({}), files: async () => [], secrets: async () => [],\n profile: ({ systemPrompt, extraMcp }) => ({ name: projectId,\n prompt: { systemPrompt: systemPrompt ?? config.systemPrompt ?? '' },\n ...(extraMcp && Object.keys(extraMcp).length ? { mcp: extraMcp } : {}),\n }),\n provider: { apiKey: env.TANGLE_API_KEY, routerBaseUrl: env.TANGLE_ROUTER_URL,\n modelName: env.MODEL_NAME, defaultModel: config.model },\n }\n}\n\nexport function createDefaultChatBackend<TContext, TResource>(projectId: string, env: ChatTurnEnvironment, config: ChatTurnDefaultBackend<TContext, TResource>, bindings?: ChatTurnStoreBindings, modelPolicy?: ModelPolicy) {\n const shell = defaultChatShell(projectId, env, config)\n const harness = config.harness ?? 'opencode'\n const acquire = (args: ChatTurnProduceArgs<TContext, TResource>): Promise<SandboxInstance> => {\n const scope = { workspaceId: args.identity.tenantId, userId: args.identity.userId }\n if (!bindings) throw new Error('Default sandbox execution requires durable D1 claim bindings')\n return runForegroundSandboxSingleFlight({ claim: createD1PrewarmClaimStore(bindings.db), workspaceId: scope.workspaceId,\n trace: args.trace, harness, provision: () => ensureWorkspaceSandbox(shell, { ...scope, harness, trace: args.trace }),\n peek: () => peekWorkspaceSandbox(shell, scope), adopt: ({ box }) => box })\n }\n const modelFor = (args: ChatTurnProduceArgs<TContext, TResource>) => {\n const model = args.body.model ?? env.MODEL_NAME ?? config.model\n if (!model?.trim()) throw new Error('Default chat requires MODEL_NAME or produce.model')\n return model\n }\n const runOptions = (args: ChatTurnProduceArgs<TContext, TResource>) => ({\n model: modelFor(args), harness, detach: true as const,\n systemPrompt: config.systemPrompt, interactions: config.interactions,\n ...sandboxPromptExecutionOptions(args.executionLimits, args.body.effort ?? config.effort),\n })\n const promptOptions = (args: ChatTurnProduceArgs<TContext, TResource>): StreamSandboxPromptOptions => ({\n ...runOptions(args), sessionId: args.identity.sessionId, executionId: args.executionId,\n turnId: args.executionId, trace: args.trace, signal: args.admissionSignal,\n })\n return {\n when: (args: ChatTurnProduceArgs<TContext, TResource>) => config.router !== false\n && (Boolean(config.funding) || Boolean(env.TANGLE_API_KEY?.trim())) && !turnCarriesFiles(args.prompt)\n // The Router can cap total output but not a separate reasoning subset.\n && !(args.executionLimits?.maxReasoningTokens),\n async router(args: ChatTurnProduceArgs<TContext, TResource>): Promise<ChatTurnHybridConfiguration> {\n const model = modelFor(args)\n if (modelPolicy) await assertPolicy({ kind: 'model', id: model, ...modelPolicy })\n const base = env.TANGLE_ROUTER_URL?.trim().replace(/\\/+$/, '')\n const funding = config.funding\n const tools = config.tools ? await config.tools(args) : undefined\n const files = config.computer?.files?.(args)\n const allowedModels = config.computer?.allowedModels\n return { apiKey: funding ? Promise.resolve().then(() => funding(args)) : env.TANGLE_API_KEY!.trim(), model,\n ...(tools?.length ? { tools } : {}),\n reasoningEffort: args.executionLimits?.maxReasoningTokens === 0 ? 'none' : args.body.effort ?? config.effort,\n ...(args.executionLimits?.maxOutputTokens !== undefined ? {\n maxTokens: args.executionLimits.maxOutputTokens, maxCompletionTokens: args.executionLimits.maxOutputTokens,\n } : {}),\n ...(base ? { baseUrl: base.endsWith('/v1') ? base : `${base}/v1` } : {}),\n systemPrompt: { profile: shell.profile({ systemPrompt: config.systemPrompt, harness }) },\n box: { acquire: () => acquire(args), computer: {\n shell, prompt: runOptions(args), parentExecutionId: args.executionId,\n session: { id: `sandbox-run-${args.identity.sessionId}` },\n ...(allowedModels ? { models: { preferred: [model], allowed: (signal: AbortSignal) => allowedModels(args, signal) } } : {}),\n ...(files ? { files } : {}),\n } },\n }\n },\n sandbox: async (args: ChatTurnProduceArgs<TContext, TResource>) => {\n const model = modelFor(args)\n if (modelPolicy) await assertPolicy({ kind: 'model', id: model, ...modelPolicy })\n // Resolve the box before the producer, but dispatch only when the route pulls\n // openEvents: producer construction failure can never leave native work running.\n const box = await acquire(args)\n return { model, modelPolicy, modelFailover: false as const, errorNotice: true,\n openEvents: ({ model, signal }: { model: string; signal: AbortSignal }) => streamSandboxPrompt(shell, box,\n normalizeChatPromptForSandbox(args.prompt), { ...promptOptions(args), model, signal }),\n }\n },\n }\n}\n","/** Prewarm inherits the existing thread-read authority; it never infers spend authority. */\nimport { createWorkspacePrewarmRoute } from '../sandbox/prewarm-route'\nimport { turnStorageBindings } from './route-storage'\nimport type { CreateChatTurnRoutesOptions } from './turn-route-contracts'\n\nexport function createChatPrewarm<TContext, TResource>(options: CreateChatTurnRoutesOptions<TContext, TResource>) {\n if (options.prewarm === false) return async () => new Response(null, { status: 405 })\n const bindings = options.turnLock === false ? undefined : turnStorageBindings(options)\n const route = createWorkspacePrewarmRoute({\n turnStore: bindings,\n authorize: async ({ request, threadId }) => {\n const auth = await options.authorize({ request, intent: 'running', threadId })\n if (!auth.ok) return { status: 'denied', response: auth.response }\n if (auth.intent !== undefined && auth.intent !== 'running') return { status: 'denied',\n response: Response.json({ error: 'Authorization did not allow this read.', code: 'chat_authorization_intent_mismatch' }, { status: 403 }) }\n if (!bindings) return { status: 'declined', reason: 'lock_not_configured' }\n return { status: 'allowed', workspaceId: auth.tenantId, steps: [] }\n },\n })\n return (request: Request) => route(request, undefined)\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 → function after admission, or declared Router\n * and Sandbox backends. Router model calls overlap\n * admission by default; tools wait for commit.\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), `afterAuthorize` (start the box, keys\n * and session the turn will need the moment the caller is admitted, so they\n * overlap the lock and the user-row insert), `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 * `prepareTurn` (post-admission context work, run inside a progress-first\n * stream) is provisional: one consumer so far.\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 { withD1QueryCount, currentD1QueryCounter } from '../launch-invariants/d1-query-count'\nimport { createInteractionAnswerRoute } from '../interactions/route'\nimport { replayTurnEvents, stampReplaySeq } from '../stream/index'\nimport { parseJsonObjectBody } from '../web/index'\nimport { createTurnTrace, type TurnTrace, type TurnTraceSink } from '../turn-trace/recorder'\nimport { createIntelligenceTurnTraceSink } from '../turn-trace/otel'\nimport { storeSupportsDraftPersistence, type AssistantDraftStore, type DraftPersistenceTuning } from './draft-persistence'\nimport { startTurnPrefetch } from './turn-prefetch'\nimport { errorResponse, namedModelRefusal, validateTurnBody, type AdmittedTurn, type ParsedTurnBody, type TurnProgressCallback } from './turn-admission'\nimport { createAdmittedTurnRunner } from './turn-execution'\nimport { earlyTurnWork, type AfterAuthorizeWork } from './early-turn-work'\nimport {\n INTENT_LINE_TIMEOUT_MS,\n INTENT_LINE_HISTORY_MESSAGES,\n INTENT_LINE_MAX_CHARS,\n type ChatRouteEvent,\n type ChatTurnAfterAuthorizeRelease,\n type ChatTurnRequestContext,\n type ChatTurnRoutes,\n type CreateChatTurnRoutesOptions,\n} from './turn-route-contracts'\nimport {\n buildTurnPhaseEvent,\n TURN_INTENT_EVENT,\n TURN_PROGRESS_FIRST,\n TURN_PROGRESS_HEADER,\n TURN_ROUTE_PHASE_MESSAGES,\n turnResponseEventFor,\n type TurnIntentEvent,\n type TurnRoutePhase,\n} from './turn-progress'\nimport { ChatTurnInputError } from './wire'\nimport { resolveTurnStorage, turnStorageBindings, type ResolvedChatTurnRoutesOptions } from './route-storage'\nimport { createDefaultChatBackend, type ChatTurnDefaultBackend } from './default-backend'\nimport { createChatPrewarm } from './route-prewarm'\nimport { cancelChatTurn } from './cancellation'\n\nexport * from './turn-route-contracts'\n\n/** Parse and validate the body, then authorize the caller. */\nasync function admitTurn<TContext, TResource>(\n request: Request, trace: TurnTrace, options: CreateChatTurnRoutesOptions<TContext, TResource>,\n waitUntil: ChatTurnRequestContext['waitUntil'],\n): Promise<({ ok: true } & AdmittedTurn<TContext>) | { ok: false; response: Response }> {\n const parse = trace.start('admission.parse', 'admission')\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return { ok: false, response: badBody }\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return { ok: false, response: errorResponse(err) }\n throw err\n }\n parse.end()\n const prefetch = options.prefetch && startTurnPrefetch(options.prefetch, { request, body: parsed.payload, trace })\n let handedOff = false\n try {\n const auth = await trace.measure('admission.authorize', 'admission', (span) => options.authorize({ request, waitUntil, intent: 'turn', body: parsed.payload, trace, span, ...(prefetch ? { identified: prefetch.identified } : {}) }))\n if (!auth.ok) return { ok: false, response: auth.response }\n if (!('context' in auth) || (auth.intent !== undefined && auth.intent !== 'turn')) {\n return { ok: false, response: Response.json({ error: 'Authorization did not allow this turn.', code: 'chat_authorization_intent_mismatch' }, { status: 403 }) }\n }\n // Check the named model before side effects; the producer checks the unnamed model.\n const refusal = await namedModelRefusal(options.modelPolicy, parsed.payload, trace)\n if (refusal) return { ok: false, response: refusal }\n const admitted = { ok: true as const, parsed, auth, trace, ...(prefetch ? { prefetched: prefetch.admitted(auth) } : {}) }\n handedOff = true\n return admitted\n } finally {\n // Refusals and thrown admission errors both abandon the read-only work.\n if (!handedOff) prefetch?.discard()\n }\n}\n\n\n/** Build chat turn routes to handle and validate incoming chat requests with optional logging */\nexport function createChatTurnRoutes<TContext = void, TResource = unknown>(\n input: CreateChatTurnRoutesOptions<TContext, TResource>,\n): ChatTurnRoutes {\n const produce = input.produce\n const options: ResolvedChatTurnRoutesOptions<TContext, TResource> = {\n ...input, ...resolveTurnStorage(input),\n produce: typeof produce === 'function' || (produce && 'router' in produce && typeof produce.router === 'function')\n ? produce as ResolvedChatTurnRoutesOptions<TContext, TResource>['produce']\n : createDefaultChatBackend<TContext, TResource>(input.projectId, input.env ?? {}, produce as ChatTurnDefaultBackend<TContext, TResource> | undefined ?? {}, turnStorageBindings(input), input.modelPolicy),\n }\n const log = options.log ?? ((message, meta) => console.error(message, meta ?? ''))\n\n // A patch-capable store always keeps durable in-flight history on the shared cadence.\n const draftStore: AssistantDraftStore = options.store\n const draftTuning: DraftPersistenceTuning | null = storeSupportsDraftPersistence(draftStore) ? {} : null\n\n const progressMessages: Record<TurnRoutePhase, string> = { ...TURN_ROUTE_PHASE_MESSAGES, ...options.progressMessages }\n\n // Every turn's trace goes to Intelligence unless the product turns it off (`turnTrace: false`).\n const traceOptions = options.turnTrace === false ? undefined : options.turnTrace\n const traceSink: TurnTraceSink | undefined = options.turnTrace === false\n ? undefined\n : (traceOptions?.sink ?? createIntelligenceTurnTraceSink({ project: options.projectId }))\n\n /** Start the admitted turn's intent line; resolves to the line, or null. Never rejects. */\n function startIntentLine(admitted: AdmittedTurn<TContext>): Promise<string | null> | undefined {\n const intentLine = options.intentLine\n if (!intentLine) return undefined\n const { parsed, auth } = admitted\n const threadId = parsed.payload.threadId\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const deadline = new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n controller.abort()\n resolve(null)\n }, intentLine.timeoutMs ?? INTENT_LINE_TIMEOUT_MS)\n })\n const generated = (async () => {\n const history = (await options.store.listMessages(threadId))\n .slice(-INTENT_LINE_HISTORY_MESSAGES)\n .map((message) => ({ role: message.role, content: message.content }))\n const text = await intentLine.generate({\n content: parsed.content,\n history,\n tenantId: auth.tenantId,\n userId: auth.userId,\n threadId,\n context: auth.context,\n signal: controller.signal,\n })\n const line = typeof text === 'string' ? text.trim().replace(/\\s+/g, ' ') : ''\n return line ? line.slice(0, INTENT_LINE_MAX_CHARS) : null\n })().catch((err) => {\n if (!controller.signal.aborted) {\n log('[chat-routes] intent line failed; showing none', { error: err instanceof Error ? err.message : String(err) })\n }\n return null\n })\n return Promise.race([generated, deadline]).finally(() => clearTimeout(timer))\n }\n const runAdmittedTurn = createAdmittedTurnRunner({\n options, draftStore, draftTuning, progressMessages, traceOptions, traceSink, startIntentLine, log,\n })\n\n async function turn(request: Request, ctx?: ChatTurnRequestContext): Promise<Response> {\n // Parsing and authorization finish before any response opens, for both\n // shapes: a refusal is always a plain HTTP response that reveals nothing\n // beyond what it says, and nothing runs for a caller who is not admitted.\n // The turn's clock starts at the request, so admission is inside its trace.\n const requestContext = ctx?.waitUntil ? { ...ctx, waitUntil: ctx.waitUntil.bind(ctx) } : ctx\n const admitted = await admitTurn(request, createTurnTrace({ d1QueryCounter: currentD1QueryCounter() }), options, requestContext?.waitUntil)\n if (!admitted.ok) return admitted.response\n if (request.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST) return runTurn(request, requestContext, admitted)\n return progressFirstTurn(request, requestContext, admitted)\n }\n\n\n /**\n * Open the response stream as soon as the caller is admitted, so the client\n * shows the turn's real stage while the conversation loads, the lock is\n * taken and the product's pre-turn work runs. The turn runs exactly as\n * {@link runTurn} does; its stream is piped through, and any other response\n * it returns after admission (a held lock, a gate's answer, a handoff, a\n * failure) becomes one `turn.response` event that `settleTurnResponse` turns\n * back into that response on the client.\n */\n function progressFirstTurn(request: Request, ctx: ChatTurnRequestContext | undefined, admitted: AdmittedTurn<TContext>): Response {\n const receivedAt = Date.now()\n const encoder = new TextEncoder()\n const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()\n const writer = writable.getWriter()\n let clientGone = false\n const write = async (chunk: Uint8Array): Promise<void> => {\n if (clientGone) return\n try {\n await writer.write(chunk)\n } catch {\n clientGone = true\n }\n }\n const writeEvent = (event: ChatRouteEvent): Promise<void> => write(encoder.encode(`${JSON.stringify(event)}\\n`))\n const progress: TurnProgressCallback = (phase, message) => {\n void writeEvent(buildTurnPhaseEvent(phase, message, { sinceRequestMs: Date.now() - receivedAt }))\n }\n progress('accepted', progressMessages.accepted)\n\n // The intent line reaches the client between whole NDJSON lines: before the\n // turn's own stream, or at a line boundary of it (its chunks can split lines).\n const intent = startIntentLine(admitted)\n let piping = false\n let atLineStart = true\n let pendingIntent: TurnIntentEvent | null = null\n if (intent) {\n void intent.then((text) => {\n if (!text || clientGone) return\n const event: TurnIntentEvent = { type: TURN_INTENT_EVENT, data: { text, sinceRequestMs: Date.now() - receivedAt } }\n if (!piping || atLineStart) void writeEvent(event)\n else pendingIntent = event\n })\n }\n\n const pump = (async () => {\n let inner: Response\n try {\n inner = await runTurn(request, ctx, admitted, progress, intent)\n } catch (err) {\n log('[chat-routes] turn failed before it streamed', { error: err instanceof Error ? err.message : String(err) })\n inner = err instanceof Response ? err\n : Response.json({ error: 'The turn failed before it started. Try again.' }, { status: 500 })\n }\n if (!inner.body || !inner.headers.get('x-turn-id')) {\n await writeEvent(await turnResponseEventFor(inner))\n } else {\n const reader = inner.body.getReader()\n piping = true\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n atLineStart = value.length > 0 && value[value.length - 1] === 0x0a\n await write(value)\n if (atLineStart && pendingIntent) {\n const event = pendingIntent\n pendingIntent = null\n await writeEvent(event)\n }\n if (clientGone) {\n // The turn keeps running under its own drain; only this view stops.\n await reader.cancel().catch(() => {})\n break\n }\n }\n } catch (err) {\n log('[chat-routes] progress-first pipe failed', { error: err instanceof Error ? err.message : String(err) })\n }\n }\n if (!clientGone) await writer.close().catch(() => {})\n })()\n if (ctx?.waitUntil) ctx.waitUntil(pump)\n else void pump.catch(() => {})\n\n return new Response(readable, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n [TURN_PROGRESS_HEADER]: TURN_PROGRESS_FIRST,\n },\n })\n }\n\n /** Start the product's `afterAuthorize` work for an admitted turn. Never throws. */\n function startAfterAuthorize(request: Request, admitted: AdmittedTurn<TContext>, waitUntil: ChatTurnRequestContext['waitUntil']): AfterAuthorizeWork<TResource> {\n let release: ChatTurnAfterAuthorizeRelease<TResource> | undefined\n const { parsed, auth, trace } = admitted\n if (options.afterAuthorize) {\n try {\n const started = options.afterAuthorize({\n request,\n waitUntil,\n body: parsed.payload,\n tenantId: auth.tenantId,\n userId: auth.userId,\n threadId: parsed.payload.threadId,\n context: auth.context,\n trace,\n })\n if (started) release = started\n } catch (err) {\n log('[chat-routes] afterAuthorize failed; the turn goes on without it', { error: err instanceof Error ? err.message : String(err) })\n }\n }\n return earlyTurnWork(release, log)\n }\n\n /** Run an admitted turn with the product's `afterAuthorize` work started first and freed if no producer takes it. */\n async function runTurn(\n request: Request,\n ctx: ChatTurnRequestContext | undefined,\n admitted: AdmittedTurn<TContext>,\n progress?: TurnProgressCallback,\n startedIntent?: Promise<string | null>,\n ): Promise<Response> {\n const early = startAfterAuthorize(request, admitted, ctx?.waitUntil)\n try {\n return await runAdmittedTurn(request, ctx, admitted, early, progress, startedIntent)\n } finally {\n // A held lock, a changed history, a gate's answer, a handoff or a throw ends the turn without `produce`. The response\n // does not wait for the product to free what it started.\n const freed = early.release()\n if (ctx?.waitUntil) ctx.waitUntil(freed)\n else void freed\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 if (auth.intent !== undefined && auth.intent !== 'replay') {\n return Response.json({ error: 'Authorization did not allow this replay.', code: 'chat_authorization_intent_mismatch' }, { status: 403 })\n }\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 })\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 if (auth.intent !== undefined && auth.intent !== 'running') {\n return Response.json({ error: 'Authorization did not allow this running-turn read.', code: 'chat_authorization_intent_mismatch' }, { status: 403 })\n }\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 prewarm: createChatPrewarm(input),\n turn: (request, ctx) => withD1QueryCount(() => turn(request, ctx)),\n cancel: request => cancelChatTurn(request, { authorize: options.authorize, cancel: options.cancel, log }),\n replay,\n running,\n interactions: options.interactions ? createInteractionAnswerRoute(options.interactions) : null,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BO,IAAM,0BAA0B,MAAM;AAItC,IAAM,wBAAwB,IAAI,OAAO;AAEhD,IAAM,2BAA2B;AAEjC,SAAS,yBAAyB,OAA8B;AAC9D,QAAM,uBAAuB,MAAM,KAAK,EAAE,QAAQ,QAAQ,EAAE;AAC5D,MAAI,CAAC,qBAAqB,WAAW,GAAG,KAAK,qBAAqB,WAAW,EAAG,QAAO;AACvF,QAAM,WAAW,qBAAqB,MAAM,CAAC,EAAE,MAAM,GAAG;AACxD,MAAI,SAAS,KAAK,CAAC,YAAY,QAAQ,WAAW,KAAK,YAAY,OAAO,YAAY,IAAI,EAAG,QAAO;AACpG,SAAO,IAAI,SAAS,KAAK,GAAG,CAAC;AAC/B;AA+CO,SAAS,uBAAuB,MAAsB;AAC3D,QAAM,OAAO,KAAK,MAAM,OAAO,EAAE,IAAI,KAAK;AAC1C,QAAM,OAAO,KAAK,QAAQ,qBAAqB,GAAG,EAAE,QAAQ,QAAQ,GAAG;AACvE,UAAQ,QAAQ,QAAQ,MAAM,G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