@tangle-network/agent-app 4.0.35 → 4.0.37
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/assistant/index.js +5 -5
- package/dist/chat-react/index.js +3 -3
- package/dist/chat-routes/index.js +19 -11
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/turn-event-stream.d.ts +10 -1
- package/dist/chat-routes/turn-execution.d.ts +34 -3
- package/dist/chat-routes/turn-intent.d.ts +5 -0
- package/dist/chat-routes/turn-progress.d.ts +25 -1
- package/dist/chat-routes/turn-route-contracts.d.ts +31 -2
- package/dist/chat-routes/turn-settlement.d.ts +23 -0
- package/dist/chat-store/index.js +2 -2
- package/dist/{chunk-NAMSFODC.js → chunk-4YBNKXUE.js} +54 -4
- package/dist/chunk-4YBNKXUE.js.map +1 -0
- package/dist/{chunk-K2JPSXKI.js → chunk-6YLVFV3F.js} +39 -3
- package/dist/chunk-6YLVFV3F.js.map +1 -0
- package/dist/{chunk-PZTBXHPE.js → chunk-725RZ5JQ.js} +2 -2
- package/dist/{chunk-ONIIKYVV.js → chunk-77UNTK66.js} +357 -290
- package/dist/chunk-77UNTK66.js.map +1 -0
- package/dist/{chunk-KPCNNFBO.js → chunk-AOSQ5JCO.js} +41 -2
- package/dist/{chunk-KPCNNFBO.js.map → chunk-AOSQ5JCO.js.map} +1 -1
- package/dist/{chunk-GOKFD7ZZ.js → chunk-BMRKOPL6.js} +2 -2
- package/dist/{chunk-E633CJFH.js → chunk-COUT2WD5.js} +2 -2
- package/dist/{chunk-7VJCMEEE.js → chunk-DPD7LY3T.js} +11 -6
- package/dist/chunk-DPD7LY3T.js.map +1 -0
- package/dist/{chunk-5WVGSCBN.js → chunk-MGW25KMR.js} +4 -4
- package/dist/{chunk-IAK227OO.js → chunk-Q7NELHRU.js} +2 -2
- package/dist/{chunk-QFT2V2OE.js → chunk-RSSK6FUF.js} +2 -2
- package/dist/{chunk-4YZKDWMB.js → chunk-SADNHPAY.js} +2 -2
- package/dist/{chunk-LTCRS46I.js → chunk-VUI4IUIM.js} +25 -7
- package/dist/chunk-VUI4IUIM.js.map +1 -0
- package/dist/operator/index.js +2 -2
- package/dist/preset-cloudflare/index.js +6 -6
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +8 -8
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/router-turn.js +2 -2
- package/dist/sandbox/index.js +4 -4
- package/dist/turn-stream/cancellation.d.ts +16 -0
- package/dist/turn-stream/core.d.ts +4 -0
- package/dist/turn-stream/do.d.ts +4 -2
- package/dist/turn-stream/hosted-turn.d.ts +20 -0
- package/dist/turn-stream/index.js +122 -5
- package/dist/turn-stream/index.js.map +1 -1
- package/dist/turn-trace/index.js +1 -1
- package/dist/web-react/chat-stream.d.ts +4 -2
- package/dist/web-react/index.js +13 -5
- package/package.json +1 -1
- package/dist/chunk-7VJCMEEE.js.map +0 -1
- package/dist/chunk-K2JPSXKI.js.map +0 -1
- package/dist/chunk-LTCRS46I.js.map +0 -1
- package/dist/chunk-NAMSFODC.js.map +0 -1
- package/dist/chunk-ONIIKYVV.js.map +0 -1
- /package/dist/{chunk-PZTBXHPE.js.map → chunk-725RZ5JQ.js.map} +0 -0
- /package/dist/{chunk-GOKFD7ZZ.js.map → chunk-BMRKOPL6.js.map} +0 -0
- /package/dist/{chunk-E633CJFH.js.map → chunk-COUT2WD5.js.map} +0 -0
- /package/dist/{chunk-5WVGSCBN.js.map → chunk-MGW25KMR.js.map} +0 -0
- /package/dist/{chunk-IAK227OO.js.map → chunk-Q7NELHRU.js.map} +0 -0
- /package/dist/{chunk-QFT2V2OE.js.map → chunk-RSSK6FUF.js.map} +0 -0
- /package/dist/{chunk-4YZKDWMB.js.map → chunk-SADNHPAY.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/chat-routes/redact-values.ts","../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/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-trace-route.ts","../src/chat-routes/turn-prefetch.ts","../src/chat-routes/turn-execution.ts","../src/chat-routes/producer-trace.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-settlement.ts","../src/chat-routes/early-turn-work.ts","../src/chat-routes/default-backend.ts","../src/chat-routes/route-prewarm.ts","../src/chat-routes/turn-intent.ts","../src/chat-routes/turn-routes.ts","../src/chat-routes/gateway-adapter.ts"],"sourcesContent":["/**\n * Redaction by value: a product registers the secret values one turn could expose (a credential its box holds in its\n * environment), and every string the turn streams or stores has each occurrence replaced. By value, never by pattern, so\n * nothing that merely looks like a secret is touched and nothing registered slips through under another shape.\n * workspace-export/secrets.ts's scanner also masks credential-shaped patterns and secret-named keys, which would change\n * a live event's structure; a turn's stream takes values only, with the same `[redacted]` marker.\n */\nimport { REDACTED } from '../workspace-export/secrets'\nimport { WITHHELD_FAILURE } from './turn-event-stream'\n\n/** Values shorter than this are never registered: a short value would redact ordinary text. */\nconst MIN_SECRET_LENGTH = 8\n\nexport type ValueRedactor = <T>(value: T) => T\n\n/** A redactor for these values, or undefined when none qualifies: object keys and string values alike. Longest first, so\n * a value that contains another wins. */\nexport function valueRedactor(values: readonly string[] | undefined): ValueRedactor | undefined {\n const secrets = [...new Set((values ?? []).filter((v) => typeof v === 'string' && v.length >= MIN_SECRET_LENGTH))]\n .sort((a, b) => b.length - a.length)\n if (secrets.length === 0) return undefined\n const text = (s: string) => secrets.some((v) => s.includes(v)) ? secrets.reduce((acc, v) => acc.split(v).join(REDACTED), s) : s\n const walk = (v: unknown): unknown => {\n if (typeof v === 'string') return text(v)\n if (Array.isArray(v)) return v.map(walk)\n if (v === null || typeof v !== 'object') return v\n const out = Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [text(k), walk(x)]))\n // A withheld failure's original, for the route's hooks only, is redacted too and kept under its Symbol key.\n const withheld = (v as { [WITHHELD_FAILURE]?: unknown })[WITHHELD_FAILURE]\n return withheld === undefined ? out : Object.assign(out, { [WITHHELD_FAILURE]: walk(withheld) })\n }\n return walk as ValueRedactor\n}\n\n/** Every event of a stream, redacted. A value split across two text deltas is caught where the turn is stored, not live. */\nexport async function* redactEvents<T>(source: AsyncIterable<T>, redact: ValueRedactor): AsyncGenerator<T> {\n for await (const event of source) yield redact(event)\n}\n","/**\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, narratesBefore, 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 // Text parts a lookup tool call followed: the round's narration of its work, not the answer.\n const narration = new Set<Record<string, unknown>>()\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 if (textPart && narratesBefore(options.tools?.find(tool => tool.name === event.toolName))) narration.add(textPart)\n textPart = null\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 // Narration becomes a reasoning part only when the model answered after its last tool call;\n // a turn whose only text narrated a failed tool keeps that text as its answer.\n if (parts.some(part => part.type === 'text' && !narration.has(part) && String(part.text).trim())) {\n for (const part of narration) part.type = 'reasoning'\n }\n const final = await options.onOutcome?.(result)\n if (final && final.trailingText) {\n result.text += final.trailingText\n result.answer += 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?.answer ?? '',\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 // The settle runs after the answer, before the row is written: each wait in it is named in the turn's trace.\n const step = <T>(name: string, work: () => Promise<T>) =>\n router.trace ? router.trace.measure(`hybrid.settle.${name}`, 'sandbox', work) : work()\n const settle = () => settled ??= (async () => {\n abort.abort(new Error('The hybrid turn settled'))\n const starting = box.started ?? start\n // A box the speculator started is waited out before it is released.\n if (starting) await step('box_start', () => starting.catch(() => undefined))\n const results = await step('release', () =>\n 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","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, 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 stays off the transcript (an upstream's own text can be an\n // HTML error page or a harness report); the failover stream logs it,\n // and `modelFailover.attempts[].reason` keeps it for the operator.\n text: `The model ${info.from} stopped; trying ${info.to}.`,\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 type { ModelFailoverAttempt } 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 failureIds,\n failureCode,\n failureReason,\n failureText,\n FAILED_TURN_TEXT,\n MODEL_KEY_REFUSED_CODE,\n personFacing,\n providerRetryNotice,\n sandboxStreamFailureDiagnostic,\n withoutToolList,\n} from './failure-wording'\nimport type {\n EmptyTurnRetryInfo,\n ModelFallbackInfo,\n OpenModelStream,\n} from './model-failover-stream'\nimport { createReasoningClock, type ReasoningRunTime } from './reasoning-clock'\nexport { MODEL_KEY_REFUSED_CODE, modelKeyRefusedSentence, providerResetSentence, providerRetryNotice } from './failure-wording'\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 when the chain has a model to fail\n * over to, none for a one-model chain. 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 /** What the person reads (text, error notice, error event) for a failure whose reason the producer withholds. Default\n * \"That answer stopped before it finished. Please send your question again.\"; a product that changes it adds its\n * words to turn-health's `errorReplyPrefixes`. */\n failedTurnText?: string\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 harnessCostUsd = toFiniteNumber(data?.totalCostUsd) ?? toFiniteNumber(tokenUsage.cost)\n if (harnessCostUsd !== null) reported.harnessCostUsd = harnessCostUsd\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 harnessCostUsd = toFiniteNumber(value?.providerCostUsd)\n if (harnessCostUsd !== null && harnessCostUsd >= 0) reported.harnessCostUsd = harnessCostUsd\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.harnessCostUsd !== undefined) usage.harnessCostUsd = reported.harnessCostUsd\n}\n\n\nfunction toProducerWireEvent(event: JsonRecord): ProducerWireEvent {\n return event as unknown as ProducerWireEvent\n}\n\n/** The producer's stream with every event passed through `shown` just before it leaves, and an event `shown` drops\n * skipped; next, return and throw reach the source unchanged, so cancellation and error injection behave as on the\n * source itself. */\nfunction shownStream(\n source: AsyncGenerator<ProducerWireEvent, void, unknown>,\n shown: (event: JsonRecord) => JsonRecord | undefined,\n): AsyncGenerator<ProducerWireEvent, void, unknown> {\n const map = async (step: Promise<IteratorResult<ProducerWireEvent, void>>): Promise<IteratorResult<ProducerWireEvent, void>> => {\n const result = await step\n if (result.done) return result\n const value = shown(result.value as unknown as JsonRecord)\n return value ? { done: false, value: toProducerWireEvent(value) } : map(source.next())\n }\n return {\n [Symbol.asyncIterator]() { return this },\n next(...args) { return map(source.next(...args)) },\n return(value) { return map(source.return(value)) },\n throw(error) { return map(source.throw(error)) },\n async [Symbol.asyncDispose]() { await this.return(undefined) },\n }\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 const person = personFacing({ log: options.log, failedTurnText: options.failedTurnText ?? FAILED_TURN_TEXT,\n hasAnswer: () => projectionState.answered })\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 answered: false,\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 // OpenCode sleeps out a provider wait of up to 300 s in silence; each retry status arrives raw, once per attempt.\n const retry = providerRetryNotice(event)\n if (retry) {\n const notice = noticePart('warning', `warning-${++projectionState.warningCount}`, retry)\n recordPersistedPart(notice, undefined, noticePartKey(notice.id))\n yield { type: 'notice', id: notice.id, noticeKind: 'warning', text: retry }\n }\n if (event.type === 'warning') {\n // Only an allowed warning becomes a notice, in a sentence written for it; `person` logs and drops any other.\n const text = person.warning(asString(event.data?.code), failureReason(record), failureIds(event.data))\n if (text) {\n projectionState.warningCount += 1\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 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) Object.assign(projectionState, { fullText: finalText, answered: true })\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 // The same reason the wire's error event carries, so the text and the event read the same sentence.\n const reason = failureReason(record)\n const view = person.view(reason, failureCode(record), event.data?.statusCode ?? event.data?.status, failureIds(event.data))\n const errorContent = failureText(view, projectionState.fullText)\n if (options.errorNotice) {\n const code = view.class === 'model_key_refused' ? MODEL_KEY_REFUSED_CODE : failureCode(record) ?? 'sandbox.stream_error'\n yield* emitErrorNotice(errorContent, code)\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 as they came (through `person`); the client parser ignores 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 // `person` logs the reason once, with its class and failure note.\n const statusCode = asRecord(streamErr)?.statusCode ?? asRecord(streamErr)?.status\n const view = person.view(diagnostic.reason, diagnostic.code, statusCode,\n { ...failureIds(asRecord(streamErr)?.diagnostics), failureNote: diagnostic.failureNote })\n const userMessage = failureText(view, projectionState.fullText)\n if (options.errorNotice) {\n yield* emitErrorNotice(userMessage, diagnostic.code)\n } else if (options.includeErrorText !== false) {\n const errorDelta = projectionState.fullText\n ? `\\n\\n---\\n${userMessage}`\n : userMessage\n projectionState.fullText += errorDelta\n yield { type: 'text', text: errorDelta }\n }\n projectionState.interactionOutcome = 'expired'\n yield* emitTerminalizedTools()\n // The status goes with the reason, so the event reads on the wire as the text above reads.\n yield toProducerWireEvent({ type: 'error', data: { message: diagnostic.reason, code: diagnostic.code,\n ...(statusCode !== undefined ? { statusCode } : {}), details: { failureNote: diagnostic.failureNote } } })\n } finally {\n reasoningClock.settle()\n }\n }\n\n return {\n // Every event leaves through `person`: no failure reason or tool list reaches the person's client.\n stream: shownStream(stream(), person.event),\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 /** The model's own answer text has arrived, apart from any failure text appended to `fullText`. */\n answered: boolean\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.harnessCostUsd !== undefined ? { providerCostUsd: usage.harnessCostUsd } : {}),\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') Object.assign(projectionState, { fullText: projectionState.fullText + delta, answered: true })\n yield { type: partType, text: delta }\n }\n return\n }\n\n if (partType === 'tool') {\n reasoningClock.settle()\n // The stored part, and the tool_call and tool_result read from it, never carry the list of every tool.\n recordPersistedPart(withoutToolList(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.harnessCostUsd !== undefined ? { providerCostUsd: usage.harnessCostUsd } : {}),\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 { TurnHostControlNamespace } from '../turn-stream/cancellation'\nimport type { TurnSpan, TurnSpanAttrs, TurnTrace, TurnTraceSink, TurnTraceSummary } from '../turn-trace/recorder'\nimport type { TurnTraceReader } from '../turn-trace/otel'\nimport type { TurnHostControlTarget, 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 /** What the Platform ledger charged (Sandbox `PromptResult.costUsd`); absent when nothing was charged or read. */\n costUsd?: number\n /** The harness's own reported token cost; a failed turn keeps its model spend here. */\n harnessCostUsd?: 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 /** Set by `TurnStreamDO` on the turn it runs for `turnHost`: the route runs it there, never forwarding it again. */\n hosted?: boolean\n /** Supplied only by the existing per-turn host. Independent of browser disconnect;\n * retain through the owned drain/disposal and forward this context unchanged. */\n hostControl?: {\n readonly hostId: string\n readonly signal: AbortSignal\n bind(target: TurnHostControlTarget, owner: { namespace: TurnHostControlNamespace; auth: TurnStreamAuth }): Promise<void>\n }\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 /** The route's turn-lock handle, read when needed: undefined before the lock is acquired and without a `turnLock`.\n * A durable completion owner releases it when it settles the turn after `handoffCompletion`\n * (preset-cloudflare `NativeCompletionPayload.lock`). */\n lock?: () => unknown\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 /** Keep the lock held for the durable owner a turn hands off to (`handoffCompletion`), for a lock whose stale-lock\n * reclaim would read the turn as dead once the route stops renewing it. The owner's release still frees it. */\n holdForHandoff?(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 /** Reads a turn's trace back for {@link ChatTurnRoutes.trace}. Default with no `sink`: `createIntelligenceTurnTraceReader({\n * project: projectId })`. A product with its own sink passes the reader for the same store; without one, the turn\n * receipt names no `traceUrl` and the route answers 404. */\n read?: TurnTraceReader\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 /** `false` disables the prewarm endpoint; `'box'` also brings up the default backend's box on page open (paid compute). */\n prewarm?: false | 'box'\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 /** Run each browser turn in a new object of the app's turn-stream binding instead of the browser's request, so the\n * turn finishes, persists and releases its lock after the browser leaves; the request only streams the object's\n * response. The binding's `TurnStreamDO` subclass passes `turnRoutes`, building these same routes; authorization,\n * lock, tap, persistence and Stop run there unchanged, on the forwarded request with its cookies. Omit → every turn\n * runs in the request, under its `waitUntil`.\n *\n * These turns still run in the request: one with neither a `Cookie` nor an `Authorization` header (`authorize`\n * refuses it there, so it never costs an object), one given `executionLimits` or `cancelOnDisconnect: true`, and one\n * whose object cannot be reached, logged once as `turn_host_unavailable`.\n *\n * Deploying it:\n * - Compatibility date 2026-10-01 or later, or the flag `durable_object_io_tasks_prevent_eviction`, so the object\n * stays alive while the turn's work is pending and no client is connected.\n * - The whole turn's CPU time counts against the one forwarded request. Set `limits.cpu_ms` (up to 300000) for\n * long turns.\n * - A code deploy resets active objects under the `immediate` update strategy. Give the turn-stream class a\n * `deferred` code update strategy whose `max_delay` covers your longest turn. Cloudflare lets in-flight requests\n * finish without access to the object's own storage, which a hosted turn never uses.\n * - The class's `turnRoutes` must pass `ctx` through unchanged: its `hosted` mark stops the object forwarding the\n * turn again. */\n turnHost?: import('../turn-stream/adapters').TurnHost\n /** Opt-in early host-control identity, before full paid authorization. Verify the\n * caller's identity, editor access and the actual thread's workspace. Return the\n * canonical workspace as tenantId; this grants no permission to execute. Only\n * requests with x-turn-host-control:first call it; an unavailable host still\n * refuses execution after this identity check. Legacy HTTP refusals\n * are unchanged. Any authorized editor may Stop the exact workspace invocation. */\n authorizeHostControl?(args: { request: Request; body: ChatTurnRequestPayload }): Promise<\n { ok: true; tenantId: string } | { ok: false; response: Response }>\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. With a lock that uses the default reclaim, the route\n * wrote a running row for `args.turnStreamId` at acquire; the owner\n * settles it (or it lapses with its lease).\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 /** Secret values this turn could expose (a credential the product placed in its box's environment). Every\n * occurrence becomes `[redacted]` in the live stream, the turn buffer, the draft and the stored row, matched by value,\n * never by pattern; values under 8 characters are ignored. The product redacts its own history reads the same way. */\n redactValues?(turn: { tenantId: string; userId: string; threadId: string }): readonly string[] | Promise<readonly 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 (and with `prewarm: 'box'` its box, under `ctx.waitUntil`); verify a named thread first. */\n prewarm(request: Request, ctx?: ChatTurnRequestContext): Promise<Response>\n /** POST — run one turn, streaming NDJSON. First line is the receipt\n * `{type:'turn', turnId, traceId?, traceUrl?}`: the replay handle, the turn's\n * OTLP trace id and where {@link trace} serves it; 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`). The separate opt-in hosted control\n * envelope requires authorizeHostControl and a client control handler. */\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 — the turn's own trace as OTLP JSON, for its owner: the waterfall a product shows and a member downloads. Mount\n * it at `<turn path>/turns/:turnId/trace`, the `traceUrl` the turn receipt names; `turnId` is the turn's execution\n * id. The caller is authorized as `running` on the turn's thread, so only a caller who may read that thread gets it;\n * everyone else, and a turn whose trace is not stored yet, gets 404. Metadata only: the turn exporter's spans. */\n trace(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 * A turn's trace for its owner: where `createChatTurnRoutes` sends and reads each turn's spans, the trace fields of\n * the turn receipt, and `routes.trace`, which serves one turn's spans to a caller who may read its thread.\n */\nimport { deriveExecutionId } from '@tangle-network/agent-runtime/durable'\nimport { createIntelligenceTurnTraceReader, createIntelligenceTurnTraceSink, otlpTraceId, type TurnTraceReader } from '../turn-trace/otel'\nimport { turnTraceId, type TurnTraceSink } from '../turn-trace/recorder'\nimport { turnTraceUrl } from '../turn-trace/url'\nimport type { ChatTurnAuthorization, ChatTurnAuthorizeArgs, ChatTurnTraceOptions } from './turn-route-contracts'\n\n/** The route's trace store: every turn goes to Intelligence unless the product turns it off (`turnTrace: false`). */\nexport function turnTraceWiring<TContext>(projectId: string, turnTrace: ChatTurnTraceOptions<TContext> | false | undefined) {\n const traceOptions = turnTrace === false ? undefined : turnTrace\n const traceSink: TurnTraceSink | undefined = turnTrace === false\n ? undefined\n : (traceOptions?.sink ?? createIntelligenceTurnTraceSink({ project: projectId }))\n // The default sink's store is read back with the same key; a product's own sink names its reader.\n const traceReader: TurnTraceReader | undefined = turnTrace === false\n ? undefined\n : (traceOptions?.read ?? (traceOptions?.sink ? undefined : createIntelligenceTurnTraceReader({ project: projectId })))\n /** The turn receipt's trace fields: the OTLP trace the turn's spans export under, and where its owner reads them. */\n const traceReceipt = (request: Request, executionId: string): Record<string, string> => ({\n ...(traceSink ? { traceId: otlpTraceId(turnTraceId(executionId)) } : {}),\n ...(traceReader ? { traceUrl: turnTraceUrl(new URL(request.url).pathname, executionId) } : {}),\n })\n return { traceOptions, traceSink, traceReader, traceReceipt }\n}\n\n/** `routes.trace`: the turn's trace for a caller who may read its thread; 404 for anyone else and for a trace not stored yet. */\nexport function createTurnTraceRoute<TContext>({ projectId, authorize, reader, log }: {\n projectId: string\n authorize(args: ChatTurnAuthorizeArgs): Promise<ChatTurnAuthorization<TContext>>\n reader: TurnTraceReader | undefined\n log(message: string, meta?: Record<string, unknown>): void\n}) {\n const notFound = (code: string) =>\n Response.json({ error: 'No trace for this turn.', code }, { status: 404, headers: { 'Cache-Control': 'private, no-store' } })\n return async (request: Request, params: { turnId: string }): Promise<Response> => {\n // A router may hand the id over decoded or not; an execution id always has `:`, its encoded form never does.\n const raw = params.turnId?.trim() ?? ''\n let executionId: string\n try {\n executionId = raw.includes(':') ? raw : decodeURIComponent(raw)\n } catch {\n return notFound('turn_trace_not_found')\n }\n const threadId = executionThreadId(executionId, projectId)\n if (!threadId) return notFound('turn_trace_not_found')\n // Reading a turn's trace is reading its thread: the same check as running-turn discovery, on the product's rows.\n const auth = await authorize({ request, intent: 'running', threadId })\n // Not signed in and the product's own outage stay what they are; every other refusal reads as no such turn.\n if (!auth.ok) return auth.response.status === 401 || auth.response.status >= 500 ? auth.response : notFound('turn_trace_not_found')\n if (auth.intent !== undefined && auth.intent !== 'running') return notFound('turn_trace_not_found')\n if (!reader) return notFound('turn_trace_unreadable')\n let exported: Awaited<ReturnType<TurnTraceReader>>\n try {\n exported = await reader(executionId, { signal: request.signal })\n } catch (err) {\n log('[chat-routes] turn trace read failed', { error: err instanceof Error ? err.message : String(err) })\n return Response.json({ error: 'The trace store did not answer. Try again.', code: 'turn_trace_unavailable' }, { status: 502 })\n }\n if (!exported) return notFound('turn_trace_not_found')\n return Response.json(exported, { headers: { 'Cache-Control': 'private, no-store' } })\n }\n}\n\n/** The thread an execution id of this project names (`deriveExecutionId`, then an optional `:retry:<id>`), or null. */\nfunction executionThreadId(executionId: string, projectId: string): string | null {\n const [, session, index] = executionId.split(':')\n if (!session || !/^\\d+$/.test(index ?? '')) return null\n try {\n const threadId = decodeURIComponent(session)\n const turnExecutionId = deriveExecutionId({ projectId, sessionId: threadId, turnIndex: Number(index) })\n return executionId === turnExecutionId || executionId.startsWith(`${turnExecutionId}:retry:`) ? threadId : null\n } catch {\n return null // malformed encoding, or a turn index or id deriveExecutionId refuses\n }\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 { redactEvents, valueRedactor, type ValueRedactor } from './redact-values'\nimport {\n coalesceDeltas,\n createBufferedTurnTap,\n resolveChatTurn,\n type BufferedTurnTap,\n type PersistedChatMessageForTurn,\n} from '../stream/index'\nimport type { TurnTraceSink, TurnTraceSnapshot } from '../turn-trace/recorder'\nimport { traceProducerStream } from './producer-trace'\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 {\n abortOnSignal, concatStreams, failureCodeOf, failureReasonOf, isVisibleOutput, isVisibleText, serverFailureData, tapRawEvents,\n withStreamHeartbeat,\n} from './turn-event-stream'\nimport type {\n ChatTurnLifecycleComplete,\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 { measuredUsage } from './sandbox-turn-usage'\nimport type { ResolvedChatTurnRoutesOptions } from './route-storage'\nimport type { AfterAuthorizeWork } from './early-turn-work'\nimport { transformVisibleTextParts } from './visible-text'\nimport { createTurnSettlement, modelAttributionFields } from './turn-settlement'\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 traceReceipt(request: Request, executionId: string): Record<string, string>\n startIntentLine(admitted: AdmittedTurn<TContext>, stop?: AbortSignal): Promise<string | null> | undefined\n log(message: string, meta?: Record<string, unknown>): void\n}\n\n/** Bind the route's construction-time dependencies; each invocation retains its own turn state. */\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, traceReceipt, 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 const hostStop = ctx?.hostControl?.signal\n hostStop?.throwIfAborted()\n // A progress-first turn started its line at admission; any other starts it here.\n const intentLine = startedIntent ?? startIntentLine(admitted, ctx?.hostControl?.signal)\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 hostStop?.throwIfAborted()\n const { turnStreamId, identity, executionId, chatTurn, readHistory, historyBeforeLock } = preparedBatch\n // Registered secret values never reach the stream, the buffer, the draft or the stored row (redact-values.ts).\n const redact = options.redactValues ? valueRedactor(await options.redactValues({ tenantId, userId, threadId: payload.threadId })) : undefined\n hostStop?.throwIfAborted()\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 || ctx?.hostControl) state.cancellationAbort = new AbortController()\n if (hostStop) {\n const abort = () => state.cancellationAbort!.abort(hostStop.reason)\n if (hostStop.aborted) abort()\n else hostStop.addEventListener('abort', abort, { once: true })\n }\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, markRunning, stopRenewal, releaseBeforeDrain } =\n createChatTurnOwnership(state, log, turnStreamId, options, payload.threadId)\n\n let produceArgs: ChatTurnProduceArgs<TContext, TResource> = {\n lock: () => state.lockHandle,\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 hostStop?.throwIfAborted()\n produceArgs = addressed\n const { endTrace, exportTraceInBackground, startLifecycle, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle } = createTurnSettlement(state, trace, options, executionId, traceSink, identity, traceOptions, context, turnStreamId, log, ctx, () => produceArgs.userMessageId)\n\n try {\n const selected = selectTurnProducer(options.produce, produceArgs)\n hostStop?.throwIfAborted()\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', () => {\n hostStop?.throwIfAborted()\n return turnLock.acquire(produceArgs)\n })\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 // An acquire already in flight may finish after Stop; retain its exact handle\n // and cancellation connection before the existing catch closes/releases it.\n hostStop?.throwIfAborted()\n progress?.('preparing', progressMessages.preparing)\n // The running row is written beside the history recheck, inside its span.\n const [history] = state.lockAcquired\n ? await trace.measure('admission.history_recheck', 'admission', () => {\n hostStop?.throwIfAborted()\n return Promise.all([readHistory(), markRunning()])\n }) : []\n hostStop?.throwIfAborted()\n if (state.lockAcquired && JSON.stringify(history) !== historyBeforeLock) {\n await releaseBeforeDrain('error')\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', () => {\n hostStop?.throwIfAborted()\n return options.store.appendMessage({\n threadId: payload.threadId,\n role: 'user',\n content,\n parts: userPartsWithFiles(chatTurn.userParts, fileParts, mentions),\n })\n }),\n )\n userMessageInserted = userMessageId !== null\n }\n produceArgs = { ...produceArgs, userMessageId, userMessageInserted }\n hostStop?.throwIfAborted()\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 releaseBeforeDrain('handoff')\n state.legacyHandoff = true\n endTrace(false, undefined)\n exportTraceInBackground()\n return gate.response\n }\n if (!gate.proceed) {\n await releaseBeforeDrain('complete')\n if (state.completionHandoff) {\n endTrace(false, undefined)\n exportTraceInBackground()\n return gate.response\n }\n // A gate still reports its lifecycle; no model billing/persistence hook runs.\n const lifecycleStarted = startLifecycle(true)\n if (lifecycleStarted) await lifecycleStarted\n await fireTerminalLifecycle(false, undefined)\n exportTraceInBackground()\n return gate.response\n }\n }\n\n // Observe + optionally augment the assembled producer input.\n hostStop?.throwIfAborted()\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 hostStop?.throwIfAborted()\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, ...traceReceipt(request, executionId) }\n await state.tap.onEvent(turnMarker)\n await stopRenewal() // the tap renews the running row from here\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 const snapshot = {\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 return redact ? redact(snapshot) : snapshot\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 const lifecycleStarted = startLifecycle()\n if (lifecycleStarted) await lifecycleStarted\n streamSetup.end()\n\n hostStop?.throwIfAborted()\n\n const { result } = createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, trace, options, selected.produce, request, context, payload, assistantRowId, redact)\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 (selection/acquire, 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 releaseBeforeDrain('error')\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}\nexport interface 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 producerError: unknown\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 producerError: 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 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 redact: ValueRedactor | undefined,\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* traceProducerStream(state.producer.stream, trace)\n }\n let source: AsyncIterable<ChatRouteEvent> = redact ? redactEvents(producerStream(), redact) : 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 (ctx?.hostControl) source = abortOnSignal(source, ctx.hostControl.signal)\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 try { for await (const event of source) yield event }\n catch (error) {\n state.producerError = state.lastFailureData ?? error\n throw error\n }\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 = serverFailureData(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 transformVisibleTextParts(rawParts, options.transformFinalText)\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 unredacted = {\n content: finalText,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(state.producer?.model ? { model: state.producer.model } : {}),\n ...modelAttributionFields(attribution),\n ...measuredUsage(usage),\n }\n const values = redact ? redact(unredacted) : unredacted\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","/**\n * The product producer's own time at either end of its stream. Before its first event it does its setup (keys, reads,\n * prompt composition, a box it resolves itself); after its last it runs the cleanup its stream holds until it returns\n * (revocations, a charge). Neither is inside a span the route records, so each was a gap no span named: 745 ms and\n * 1,382 ms of a 12.6 s Tax Router turn, 2,720 ms and 1,296 ms of a 20.5 s box turn. A product that measures its own\n * steps inside them (`trace.measure`) nests nothing here: these two spans only say whose time it was.\n */\nimport type { TurnTrace } from '../turn-trace/recorder'\n\n/** A producer's stream, unchanged, recording `produce.setup` until its first event and `produce.settle` from the request\n * after its last event until it ends. It only times `next`; `return` and `throw` reach the producer's own iterator\n * untouched, so `yield*` over it behaves exactly as over the producer (a producer reads an early `return` as a stop). */\nexport function traceProducerStream<T>(stream: AsyncIterable<T>, trace: TurnTrace): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator](): AsyncIterator<T> {\n const inner = stream[Symbol.asyncIterator]()\n let first = true\n return {\n async next(...args: [] | [undefined]) {\n const asked = Date.now()\n const result = await inner.next(...args)\n // Only the first wait and the last are the producer's own; the waits between events are its model and tools.\n if (first) trace.record('produce.setup', 'other', asked, Date.now())\n else if (result.done) trace.record('produce.settle', 'other', asked, Date.now())\n first = false\n return result\n },\n ...(inner.return ? { return: inner.return.bind(inner) } : {}),\n ...(inner.throw ? { throw: inner.throw.bind(inner) } : {}),\n }\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 { DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS, type BufferedTurnTap, type TurnEventStore } 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' | 'holdForHandoff'>; turnStore?: Pick<TurnEventStore, 'setStatus'> },\n scopeId?: string,\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 // The running row a lock reclaim reads, written only for a lock that reads it (`holdForHandoff` marks the default\n // reclaim): at acquire, then renewed on the tap's interval, so a turn still in `contextGate` or `beforeTurn` holds\n // its lock. It stops when the tap takes the row over, at hand-off, or at release. Writes are chained: none lands late.\n const store = options.turnLock?.holdForHandoff ? options.turnStore : undefined\n let runningRow: Promise<void> | undefined\n let renewal: ReturnType<typeof setInterval> | undefined\n const markRunning = async (): Promise<void> => {\n if (!store) return\n const write = () => (runningRow = (runningRow ?? Promise.resolve()).catch(() => {})\n .then(() => store.setStatus(turnStreamId, 'running', scopeId)))\n const first = write()\n renewal = setInterval(() => void write().catch(() => {}), DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS)\n return first\n }\n const stopRenewal = async (): Promise<void> => {\n clearInterval(renewal)\n renewal = undefined\n await runningRow?.catch(() => {}) // a late `running` write must not land over what follows\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 await stopRenewal()\n // A lock whose reclaim would read the handed-off turn as dead once nothing renews its row holds for the owner,\n // whose release of the exact lock frees it.\n if (state.lockAcquired && options.turnLock?.holdForHandoff) {\n // Nothing renews a handed-off turn's row, so an unheld lock could be reclaimed under the native run: a failed\n // call is retried; a `false` (the lock is gone or fenced) is final.\n let held: boolean | undefined\n for (let tries = 0; tries < 3 && held === undefined; tries++) {\n if (tries) await new Promise(resolve => setTimeout(resolve, 250 * tries))\n held = await Promise.resolve().then(() => options.turnLock!.holdForHandoff!(state.lockHandle)).then(Boolean, () => undefined)\n }\n if (!held) log('[chat-routes] turn lock hand-off hold failed', { turnId: turnStreamId, class: 'turn_lock_handoff_hold_failed' })\n }\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 /** Release a turn that never reached its drain, settling its running row with `end` first: through the tap's own\n * close when the tap exists, else directly. A gate's hand-off leaves the row to the product's owner. */\n const releaseBeforeDrain = async (end: 'complete' | 'error' | 'handoff'): Promise<void> => {\n await stopRenewal()\n if (end !== 'handoff' && !state.completionHandoff) {\n if (state.tap) await attempt('turn buffer close', () => state.tap!.done(end))\n else if (store && runningRow) await attempt('running row settle', () => store.setStatus(turnStreamId, end, scopeId))\n }\n await releaseLock()\n }\n return { handoffCompletion, releaseLock, markRunning, stopRenewal, releaseBeforeDrain }\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","/** Lifecycle hooks and trace settlement for the route's existing live projection. */\nimport type { ChatTurnIdentity } from '@tangle-network/agent-runtime/durable'\nimport type { TurnTraceSink, TurnTraceSnapshot, TurnTraceSummary } from '../turn-trace/recorder'\nimport { otlpTraceId } from '../turn-trace/otel'\nimport { noteMeasuredTurnFacts, readableTurnFailure } from '../turn-trace/turn-facts'\nimport type { AdmittedTurn } from './turn-admission'\nimport type { AdmittedTurnState } from './turn-execution'\nimport { failureCodeOf } from './turn-event-stream'\nimport type { ResolvedChatTurnRoutesOptions } from './route-storage'\nimport type {\n ChatTurnLifecycleComplete, ChatTurnModelAttribution, ChatTurnRequestContext, ChatTurnTraceOptions,\n} from './turn-route-contracts'\n\n/** One requested-versus-served projection for persistence and both completion receipts. */\nexport function 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/** 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 createTurnSettlement<TContext, TResource>(\n state: AdmittedTurnState<TContext>,\n trace: AdmittedTurn<TContext>['trace'],\n options: ResolvedChatTurnRoutesOptions<TContext, TResource>,\n executionId: string,\n traceSink: TurnTraceSink | undefined,\n identity: ChatTurnIdentity,\n traceOptions: ChatTurnTraceOptions<TContext> | undefined,\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 /**\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 /** Gated turns report telemetry without claiming that a producer started. */\n const startLifecycle = (gated = false): Promise<void> | undefined => {\n if (gated) state.gatedTurn = true\n state.turnStartedAtMs = Date.now()\n if (!gated) state.turnStarted = true\n const lifecycle = options.lifecycle\n if (!lifecycle?.onTurnStart) return\n return (async () => {\n try {\n await 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 }\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 // Keep the actual producer cause for server hooks when Runtime emits only a\n // message. A late Stop never replaces a richer failure already observed.\n terminalError ??= state.producerError\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, startLifecycle, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle }\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 { createSandboxPrewarmer } from '../sandbox/prewarm'\nimport { runForegroundSandboxSingleFlight } from '../sandbox/foreground-single-flight'\nimport { ensureWorkspaceSandbox, peekWorkspaceSandbox, streamSandboxPrompt } from '../sandbox/index'\nimport type { SandboxRuntimeConfig } from '../sandbox/configuration'\nimport type { ProviderResolutionConfig } from '../sandbox/model'\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 /** A model's own provider, keyed by the exact model id a turn carries; any other model runs on the shell's. The box is\n * created on the shell's provider, and only an api-mode keyless provider there gets the box its own Router key, so a\n * pool of an OpenCode free model and a Router model puts the Router member on the shell and the free one here.\n * A function is resolved for each turn, so a turn can carry its own key, e.g. a child of the caller's linked key. */\n providers?: Readonly<Record<string, ProviderResolutionConfig\n | ((args: ChatTurnProduceArgs<TContext, TResource>) => ProviderResolutionConfig | Promise<ProviderResolutionConfig>)>>\n /** Explicitly keep every turn on the sandbox lane. */\n router?: false\n /** A durable owner for a sandbox turn, so its answer outlives the request (a closed tab, a lost connection): called\n * after the box is resolved and the turn lock is held, before the prompt is dispatched, with the session and execution the dispatch uses.\n * It registers the owner (preset-cloudflare `createNativeCompletionOwner`, as creative-agent does) and then calls\n * `args.handoffCompletion()`. A throw fails the turn before any native work starts. */\n completionOwner?(input: { args: ChatTurnProduceArgs<TContext, TResource>; box: SandboxInstance; sessionId: string; executionId: string }): Promise<void>\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<TContext, TResource>(projectId: string, env: ChatTurnEnvironment, config: ChatTurnDefaultBackend<TContext, TResource>): 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 const warmer = bindings && createSandboxPrewarmer(shell, { claim: createD1PrewarmClaimStore(bindings.db), mode: 'create-or-resume', claimTtlSeconds: 45 })\n return {\n prewarm: (scope: { workspaceId: string; userId: string }) => warmer ? warmer.prewarm({ ...scope, harness }).then(warm => warm.completion) : Promise.resolve(),\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 // A model with its own provider (`providers`) runs where that provider does: the sandbox lane.\n && !config.providers?.[args.body.model ?? env.MODEL_NAME ?? config.model ?? ''],\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 // A per-turn provider resolves here, before the box and the stream: a refused mint fails the producer's\n // construction, which never leaves native work running, so the turn lock is released, not parked.\n const own = config.providers?.[model]\n const provider = typeof own === 'function' ? await own(args) : own\n const box = await acquire(args)\n const completionOwner = config.completionOwner\n const dispatch = (signal: AbortSignal) => streamSandboxPrompt(provider ? { ...shell, provider } : shell, box,\n normalizeChatPromptForSandbox(args.prompt), { ...promptOptions(args), model, signal })\n return { model, modelPolicy, modelFailover: false as const, errorNotice: true,\n // The route pulls openEvents only after the turn lock, so the durable owner registers holding it.\n openEvents: ({ signal }: { model: string; signal: AbortSignal }) => completionOwner\n ? (async function* () {\n await completionOwner({ args, box, sessionId: args.identity.sessionId, executionId: args.executionId })\n yield* dispatch(signal)\n })()\n : dispatch(signal),\n }\n },\n }\n}\n","/** Prewarm inherits thread-read authority; only a product's `prewarm: 'box'` spends, under `waitUntil` so a canceled request keeps no claim. */\nimport { createWorkspacePrewarmRoute } from '../sandbox/prewarm-route'\nimport { turnStorageBindings } from './route-storage'\nimport type { ChatTurnRequestContext, CreateChatTurnRoutesOptions } from './turn-route-contracts'\n\nexport function createChatPrewarm<TContext, TResource>(options: CreateChatTurnRoutesOptions<TContext, TResource>, box?: (scope: { workspaceId: string; userId: string }) => Promise<unknown>) {\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<ChatTurnRequestContext | undefined>({\n turnStore: bindings,\n authorize: async ({ request, context, 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 if (options.prewarm === 'box' && box) context?.waitUntil?.(box({ workspaceId: auth.tenantId, userId: auth.userId }))\n return { status: 'allowed', workspaceId: auth.tenantId, steps: [] }\n },\n })\n return (request: Request, ctx?: ChatTurnRequestContext) => route(request, ctx)\n}\n","/** Optional intent preview for an already admitted turn; never owns execution. */\nimport type { AdmittedTurn } from './turn-admission'\nimport type { ResolvedChatTurnRoutesOptions } from './route-storage'\nimport { INTENT_LINE_TIMEOUT_MS, INTENT_LINE_HISTORY_MESSAGES, INTENT_LINE_MAX_CHARS } from './turn-route-contracts'\n\n/** Start the admitted turn's intent line; resolves to the line, or null. Never rejects. */\nexport function startTurnIntentLine<TContext, TResource>(\n options: ResolvedChatTurnRoutesOptions<TContext, TResource>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n admitted: AdmittedTurn<TContext>,\n stop?: AbortSignal,\n): 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 const signal = stop ? AbortSignal.any([controller.signal, stop]) : controller.signal\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 signal.throwIfAborted()\n const history = (await options.store.listMessages(threadId))\n .slice(-INTENT_LINE_HISTORY_MESSAGES)\n .map((message) => ({ role: message.role, content: message.content }))\n signal.throwIfAborted()\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,\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 (!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","/**\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 * `turnHost` runs it in a Durable Object instead,\n * which outlives the browser's request\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 } from '../turn-trace/recorder'\nimport { createTurnTraceRoute, turnTraceWiring } from './turn-trace-route'\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 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_HOST_CONTROL_HEADER,\n TURN_HOST_CONTROL_FIRST,\n TURN_HOST_CONTROL_EVENT,\n TURN_ROUTE_PHASE_MESSAGES,\n turnResponseEventFor,\n type TurnIntentEvent,\n type TurnRoutePhase,\n type TurnHostControlTarget,\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'\nimport { forwardTurnToHost, type TurnHost } from '../turn-stream/adapters'\nimport type { TurnHostControlNamespace } from '../turn-stream/cancellation'\nimport { createTurnView, turnControlResponse } from './turn-event-stream'\nimport { startTurnIntentLine } from './turn-intent'\n\nexport * from './turn-route-contracts'\n\nasync function parseTurn(request: Request, trace: TurnTrace): Promise<ParsedTurnBody | Response> {\n const parse = trace.start('admission.parse', 'admission')\n const [rawBody, badBody] = await parseJsonObjectBody(request)\n if (badBody) return badBody\n let parsed: ParsedTurnBody\n try {\n parsed = validateTurnBody(rawBody)\n } catch (err) {\n if (err instanceof ChatTurnInputError) return errorResponse(err)\n throw err\n }\n parse.end()\n return parsed\n}\n\n/** Parse once, then authorize execution; early host identity never replaces this gate. */\nasync function admitTurn<TContext, TResource>(\n request: Request, trace: TurnTrace, options: CreateChatTurnRoutesOptions<TContext, TResource>,\n waitUntil: ChatTurnRequestContext['waitUntil'], parsedBody?: ParsedTurnBody,\n): Promise<({ ok: true } & AdmittedTurn<TContext>) | { ok: false; response: Response }> {\n const parsed = parsedBody ?? await parseTurn(request, trace)\n if (parsed instanceof Response) return { ok: false, response: parsed }\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 backend = typeof produce === 'function' || (produce && 'router' in produce && typeof produce.router === 'function') ? undefined\n : createDefaultChatBackend<TContext, TResource>(input.projectId, input.env ?? {}, produce as ChatTurnDefaultBackend<TContext, TResource> | undefined ?? {}, turnStorageBindings(input), input.modelPolicy)\n const options: ResolvedChatTurnRoutesOptions<TContext, TResource> = {\n ...input, ...resolveTurnStorage(input), produce: backend ?? produce as ResolvedChatTurnRoutesOptions<TContext, TResource>['produce'],\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, traceSink, traceReader, traceReceipt } = turnTraceWiring(options.projectId, options.turnTrace)\n\n const startIntentLine = (admitted: AdmittedTurn<TContext>, stop?: AbortSignal) => startTurnIntentLine(options, log, admitted, stop)\n const runAdmittedTurn = createAdmittedTurnRunner({\n options, draftStore, draftTuning, progressMessages, traceOptions, traceSink, traceReceipt, startIntentLine, log,\n })\n // A hosted turn's object is placed with the turn lock's channel unless the host names a place.\n const turnHost = input.turnHost && { locationHint: turnStorageBindings(input)?.region, ...input.turnHost }\n\n /** Run the turn in a new turn-stream object. An object that cannot be reached leaves the turn to this request, as\n * without `turnHost`; a throw from the turn's own code in the object stays a throw, as it would be here. */\n async function hostTurn(host: TurnHost, request: Request, ctx?: ChatTurnRequestContext): Promise<Response> {\n try {\n const response = await forwardTurnToHost(host, request.clone())\n void request.body?.cancel().catch(() => {})\n return response\n } catch (err) {\n if ((err as { remote?: unknown } | null)?.remote === true) throw err\n // No second execution owner after the opt-in host might have published H.\n if (request.headers.get(TURN_HOST_CONTROL_HEADER) === TURN_HOST_CONTROL_FIRST) {\n return Response.json({ error: 'The turn host is unavailable.', code: 'turn_control_unavailable' }, { status: 503 })\n }\n log('[chat-routes] turn host unavailable; the turn runs in this request', {\n class: 'turn_host_unavailable', error: err instanceof Error ? err.name : typeof err })\n return withD1QueryCount(() => turn(request, ctx))\n }\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 trace = createTurnTrace({ d1QueryCounter: currentD1QueryCounter() })\n if (request.headers.get(TURN_HOST_CONTROL_HEADER) === TURN_HOST_CONTROL_FIRST) {\n const control = requestContext?.hosted && requestContext.hostControl\n if (!options.authorizeHostControl) {\n return Response.json({ error: 'Early hosted control is unavailable.', code: 'turn_control_unavailable' }, { status: 503 })\n }\n const parsed = await parseTurn(request, trace)\n if (parsed instanceof Response) return parsed\n const identity = await options.authorizeHostControl({ request, body: parsed.payload })\n if (!identity.ok) return identity.response\n if (!control) return Response.json({ error: 'The turn host is unavailable.', code: 'turn_control_unavailable' }, { status: 503 })\n const namespace = turnHost?.namespace as TurnHostControlNamespace | undefined\n if (!namespace || typeof namespace.idFromString !== 'function') {\n return Response.json({ error: 'The host control binding is unavailable.', code: 'turn_control_unavailable' }, { status: 503 })\n }\n if (!identity.tenantId.trim()) return new Response('Invalid control identity', { status: 403 })\n const target: TurnHostControlTarget = { hostId: control.hostId, workspaceId: identity.tenantId,\n threadId: parsed.payload.threadId, ...(parsed.payload.turnId ? { clientTurnId: parsed.payload.turnId } : {}),\n ...(parsed.payload.retryAttemptId ? { retryAttemptId: parsed.payload.retryAttemptId } : {}) }\n await control.bind(target, { namespace, auth: turnHost!.auth })\n const admission = admitTurn(request, trace, options, requestContext?.waitUntil, parsed)\n .then(result => result.ok ? result : result.response)\n return progressFirstTurn(request, requestContext, admission, target)\n }\n const admitted = await admitTurn(request, trace, 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,\n admission: AdmittedTurn<TContext> | Promise<AdmittedTurn<TContext> | Response>, control?: TurnHostControlTarget,\n ): Response {\n const receivedAt = Date.now()\n const encoder = new TextEncoder()\n const view = createTurnView()\n const writeEvent = (event: ChatRouteEvent): void => view.write(encoder.encode(`${JSON.stringify(event)}\\n`))\n const progress: TurnProgressCallback = (phase, message) => {\n writeEvent(buildTurnPhaseEvent(phase, message, { sinceRequestMs: Date.now() - receivedAt }))\n }\n if (control) writeEvent({ type: TURN_HOST_CONTROL_EVENT, data: { ...control } })\n let piping = false\n let atLineStart = true\n let pendingIntent: TurnIntentEvent | null = null\n\n const pump = (async () => {\n let inner: Response\n try {\n const admitted = await admission\n if (admitted instanceof Response) inner = admitted\n else if (control && admitted.auth.tenantId !== control.workspaceId) inner = new Response('Control identity changed', { status: 403 })\n else if (ctx?.hostControl?.signal.aborted) inner = turnControlResponse(ctx.hostControl.signal)\n else {\n progress('accepted', progressMessages.accepted)\n // Intent is execution work: never start it before full admission/Stop gate.\n const intent = startIntentLine(admitted, ctx?.hostControl?.signal)\n if (intent) void intent.then(text => {\n if (!text || view.disconnected) return\n const event: TurnIntentEvent = { type: TURN_INTENT_EVENT, data: { text, sinceRequestMs: Date.now() - receivedAt } }\n if (!piping || atLineStart) writeEvent(event)\n else pendingIntent = event\n })\n inner = await runTurn(request, ctx, admitted, progress, intent)\n }\n } catch (err) {\n log('[chat-routes] turn failed before it streamed', { error: err instanceof Error ? err.message : String(err) })\n inner = ctx?.hostControl?.signal.aborted && err === ctx.hostControl.signal.reason\n ? turnControlResponse(ctx.hostControl.signal) : 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 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 view.write(value)\n if (atLineStart && pendingIntent) {\n const event = pendingIntent\n pendingIntent = null\n writeEvent(event)\n }\n if (view.disconnected) {\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 view.close()\n })()\n if (ctx?.waitUntil) ctx.waitUntil(pump)\n else void pump.catch(() => {})\n\n return new Response(view.readable, {\n headers: {\n 'Content-Type': 'application/x-ndjson',\n 'Cache-Control': 'no-cache',\n [TURN_PROGRESS_HEADER]: TURN_PROGRESS_FIRST,\n ...(control ? { [TURN_HOST_CONTROL_HEADER]: TURN_HOST_CONTROL_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 if (ctx?.hostControl?.signal.aborted) return turnControlResponse(ctx.hostControl.signal)\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, backend?.prewarm),\n // A request with no credential runs here, where `authorize` refuses it, so it never costs an object.\n turn: (request, ctx) => turnHost && !ctx?.hosted && ctx?.executionLimits === undefined && ctx?.cancelOnDisconnect !== true\n && (request.headers.has('cookie') || request.headers.has('authorization'))\n ? hostTurn(turnHost, request, ctx) : withD1QueryCount(() => turn(request, ctx)),\n cancel: request => cancelChatTurn(request, { authorize: options.authorize, cancel: options.cancel, log }),\n replay,\n trace: createTurnTraceRoute({ projectId: options.projectId, authorize: options.authorize, reader: traceReader, log }),\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,IAAM,oBAAoB;AAMnB,SAAS,cAAc,QAAkE;AAC9F,QAAM,UAAU,CAAC,GAAG,IAAI,KAAK,UAAU,CAAC,GAAG,OAAO,CAAC,MAAM,OAAO,MAAM,YAAY,EAAE,UAAU,iBAAiB,CAAC,CAAC,EAC9G,KAAK,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM;AACrC,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,QAAM,OAAO,CAAC,MAAc,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,IAAI,QAAQ,OAAO,CAAC,KAAK,MAAM,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