@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.
Files changed (59) hide show
  1. package/dist/assistant/index.js +5 -5
  2. package/dist/chat-react/index.js +3 -3
  3. package/dist/chat-routes/index.js +19 -11
  4. package/dist/chat-routes/index.js.map +1 -1
  5. package/dist/chat-routes/turn-event-stream.d.ts +10 -1
  6. package/dist/chat-routes/turn-execution.d.ts +34 -3
  7. package/dist/chat-routes/turn-intent.d.ts +5 -0
  8. package/dist/chat-routes/turn-progress.d.ts +25 -1
  9. package/dist/chat-routes/turn-route-contracts.d.ts +31 -2
  10. package/dist/chat-routes/turn-settlement.d.ts +23 -0
  11. package/dist/chat-store/index.js +2 -2
  12. package/dist/{chunk-NAMSFODC.js → chunk-4YBNKXUE.js} +54 -4
  13. package/dist/chunk-4YBNKXUE.js.map +1 -0
  14. package/dist/{chunk-K2JPSXKI.js → chunk-6YLVFV3F.js} +39 -3
  15. package/dist/chunk-6YLVFV3F.js.map +1 -0
  16. package/dist/{chunk-PZTBXHPE.js → chunk-725RZ5JQ.js} +2 -2
  17. package/dist/{chunk-ONIIKYVV.js → chunk-77UNTK66.js} +357 -290
  18. package/dist/chunk-77UNTK66.js.map +1 -0
  19. package/dist/{chunk-KPCNNFBO.js → chunk-AOSQ5JCO.js} +41 -2
  20. package/dist/{chunk-KPCNNFBO.js.map → chunk-AOSQ5JCO.js.map} +1 -1
  21. package/dist/{chunk-GOKFD7ZZ.js → chunk-BMRKOPL6.js} +2 -2
  22. package/dist/{chunk-E633CJFH.js → chunk-COUT2WD5.js} +2 -2
  23. package/dist/{chunk-7VJCMEEE.js → chunk-DPD7LY3T.js} +11 -6
  24. package/dist/chunk-DPD7LY3T.js.map +1 -0
  25. package/dist/{chunk-5WVGSCBN.js → chunk-MGW25KMR.js} +4 -4
  26. package/dist/{chunk-IAK227OO.js → chunk-Q7NELHRU.js} +2 -2
  27. package/dist/{chunk-QFT2V2OE.js → chunk-RSSK6FUF.js} +2 -2
  28. package/dist/{chunk-4YZKDWMB.js → chunk-SADNHPAY.js} +2 -2
  29. package/dist/{chunk-LTCRS46I.js → chunk-VUI4IUIM.js} +25 -7
  30. package/dist/chunk-VUI4IUIM.js.map +1 -0
  31. package/dist/operator/index.js +2 -2
  32. package/dist/preset-cloudflare/index.js +6 -6
  33. package/dist/public-consultation/index.d.ts +1 -1
  34. package/dist/public-consultation/index.js +8 -8
  35. package/dist/runtime/index.js +3 -3
  36. package/dist/runtime/router-turn.js +2 -2
  37. package/dist/sandbox/index.js +4 -4
  38. package/dist/turn-stream/cancellation.d.ts +16 -0
  39. package/dist/turn-stream/core.d.ts +4 -0
  40. package/dist/turn-stream/do.d.ts +4 -2
  41. package/dist/turn-stream/hosted-turn.d.ts +20 -0
  42. package/dist/turn-stream/index.js +122 -5
  43. package/dist/turn-stream/index.js.map +1 -1
  44. package/dist/turn-trace/index.js +1 -1
  45. package/dist/web-react/chat-stream.d.ts +4 -2
  46. package/dist/web-react/index.js +13 -5
  47. package/package.json +1 -1
  48. package/dist/chunk-7VJCMEEE.js.map +0 -1
  49. package/dist/chunk-K2JPSXKI.js.map +0 -1
  50. package/dist/chunk-LTCRS46I.js.map +0 -1
  51. package/dist/chunk-NAMSFODC.js.map +0 -1
  52. package/dist/chunk-ONIIKYVV.js.map +0 -1
  53. /package/dist/{chunk-PZTBXHPE.js.map → chunk-725RZ5JQ.js.map} +0 -0
  54. /package/dist/{chunk-GOKFD7ZZ.js.map → chunk-BMRKOPL6.js.map} +0 -0
  55. /package/dist/{chunk-E633CJFH.js.map → chunk-COUT2WD5.js.map} +0 -0
  56. /package/dist/{chunk-5WVGSCBN.js.map → chunk-MGW25KMR.js.map} +0 -0
  57. /package/dist/{chunk-IAK227OO.js.map → chunk-Q7NELHRU.js.map} +0 -0
  58. /package/dist/{chunk-QFT2V2OE.js.map → chunk-RSSK6FUF.js.map} +0 -0
  59. /package/dist/{chunk-4YZKDWMB.js.map → chunk-SADNHPAY.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/chat-routes/turn-progress.ts","../src/chat-routes/wire.ts"],"sourcesContent":["/**\n * Turn progress: the real stage a chat turn is in, on the turn stream.\n *\n * A turn can spend seconds before its first answer token: authorization, the\n * conversation load, the single-flight lock, the product's pre-turn work, a\n * sandbox, the harness and the model's first token. `session.run.phase` events\n * name those stages as they happen, so a chat shows where the turn is instead\n * of a spinner.\n *\n * A client that sends {@link TURN_PROGRESS_HEADER} gets the response stream as\n * soon as the route has parsed the body and `authorize` has admitted the\n * caller. Authorization never runs inside the stream: every refusal it makes\n * (400, 401, 402, 403, 404, 429) is a plain HTTP response, so an unadmitted\n * caller sees no stage, holds no stream and starts no work. After admission,\n * anything the route answers with a non-stream response (a held lock's 409, a\n * gate's own response, a handoff, a failure) arrives as one\n * {@link TURN_RESPONSE_EVENT} carrying that response's status, headers and\n * body, and {@link settleTurnResponse} turns it back into the `Response` the\n * caller already handles. A client that does not send the header gets exactly\n * the responses it got before.\n *\n * Product work that only an admitted turn may do (resolving its profile and\n * model, any write) belongs in `prepareTurn`, which runs after admission and,\n * on a progress-first stream, inside it with its own named stages.\n * `tests/chat-routes/authorize-before-stream.test.ts` is the gate that keeps\n * every shared route behind its `authorize`.\n *\n * Browser-safe and import-free: the server route and the web client share it.\n */\n\n/** Request header that asks for a progress-first turn stream. */\nexport const TURN_PROGRESS_HEADER = 'x-turn-progress'\n/** The only value of {@link TURN_PROGRESS_HEADER}. The route echoes it on a progress-first response. */\nexport const TURN_PROGRESS_FIRST = 'first'\n\n/** Stream event naming the turn's current stage. Non-terminal and never turn content. */\nexport const TURN_PHASE_EVENT = 'session.run.phase'\n\n/**\n * Stages the shared route emits before the producer runs. Products add their\n * own (a sandbox product emits `provisioning`, `starting`,\n * `awaiting-first-token`).\n * - `accepted`: the caller is admitted; the conversation and the lock are loading.\n * - `preparing`: the turn holds its lock; the product's pre-turn work is running.\n */\nexport type TurnRoutePhase = 'accepted' | 'preparing'\n\n/** The data of a {@link TURN_PHASE_EVENT}. */\nexport type TurnPhaseData = {\n /** Stage id: a {@link TurnRoutePhase} or a product's own stage. */\n phase: string\n /** Text the client shows verbatim. */\n message: string\n /** A keepalive for the current stage rather than a new stage. */\n heartbeat?: boolean\n /** Milliseconds since the current wait began. */\n elapsedMs?: number\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_PHASE_EVENT} as it crosses the wire. */\nexport type TurnPhaseEvent = { type: typeof TURN_PHASE_EVENT; data: TurnPhaseData }\n\n/** Default text for the route's own stages. Products override it through `createChatTurnRoutes({ progressMessages })`. */\nexport const TURN_ROUTE_PHASE_MESSAGES: Record<TurnRoutePhase, string> = {\n accepted: 'Loading your conversation…',\n preparing: 'Preparing the agent…',\n}\n\n/** Build a {@link TURN_PHASE_EVENT}. */\nexport function buildTurnPhaseEvent(\n phase: string,\n message: string,\n opts: { heartbeat?: boolean; elapsedMs?: number; sinceRequestMs?: number } = {},\n): TurnPhaseEvent {\n return {\n type: TURN_PHASE_EVENT,\n data: {\n phase,\n message,\n ...(opts.heartbeat ? { heartbeat: true } : {}),\n ...(typeof opts.elapsedMs === 'number' ? { elapsedMs: opts.elapsedMs } : {}),\n ...(typeof opts.sinceRequestMs === 'number' ? { sinceRequestMs: opts.sinceRequestMs } : {}),\n },\n }\n}\n\n/** True for a {@link TURN_PHASE_EVENT} with a usable `phase` and `message`. */\nexport function isTurnPhaseEvent(event: unknown): event is TurnPhaseEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { phase?: unknown; message?: unknown } }\n return candidate.type === TURN_PHASE_EVENT\n && typeof candidate.data?.phase === 'string'\n && typeof candidate.data?.message === 'string'\n}\n\n/**\n * Stream event carrying the turn's intent line: one plain sentence, written by\n * a fast model call at admission, saying what the agent is about to do (\"Looking\n * at your three competitors' pricing pages, then I'll draft the comparison.\").\n * A client shows it as a labeled status line, never as the answer, until the\n * turn's first answer text replaces it. It narrates intent; it never answers\n * or acts. Non-terminal and never turn content; at most one per turn.\n */\nexport const TURN_INTENT_EVENT = 'session.run.intent'\n\n/** The data of a {@link TURN_INTENT_EVENT}. */\nexport type TurnIntentData = {\n /** The sentence, shown verbatim. */\n text: string\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_INTENT_EVENT} as it crosses the wire. */\nexport type TurnIntentEvent = { type: typeof TURN_INTENT_EVENT; data: TurnIntentData }\n\n/** True for a {@link TURN_INTENT_EVENT} with non-empty text. */\nexport function isTurnIntentEvent(event: unknown): event is TurnIntentEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { text?: unknown } }\n return candidate.type === TURN_INTENT_EVENT\n && typeof candidate.data?.text === 'string'\n && candidate.data.text.trim().length > 0\n}\n\n/** Terminal event of a progress-first stream that ended without a turn: the response the route returned instead. */\nexport const TURN_RESPONSE_EVENT = 'turn.response'\n\n/** The data of a {@link TURN_RESPONSE_EVENT}. */\nexport type TurnResponseData = {\n status: number\n /** Response headers other than `set-cookie` and framing headers. */\n headers: Record<string, string>\n body: string\n}\n\n/** Headers a {@link TURN_RESPONSE_EVENT} cannot carry: cookies cannot be set after the stream opened, and framing belongs to the outer response. */\nconst UNCARRIED_HEADERS = new Set(['set-cookie', 'content-length', 'content-encoding', 'transfer-encoding', 'connection'])\n\n/** Error code {@link settleTurnResponse} reports when a progress-first stream closes before the turn started. */\nexport const TURN_STREAM_LOST_CODE = 'turn_stream_lost'\n\n/** Serialize a non-stream response for a {@link TURN_RESPONSE_EVENT}. */\nexport async function turnResponseEventFor(response: Response): Promise<{ type: typeof TURN_RESPONSE_EVENT; data: TurnResponseData }> {\n const headers: Record<string, string> = {}\n response.headers.forEach((value, key) => {\n if (!UNCARRIED_HEADERS.has(key.toLowerCase())) headers[key.toLowerCase()] = value\n })\n return { type: TURN_RESPONSE_EVENT, data: { status: response.status, headers, body: await response.text() } }\n}\n\n/**\n * Settle a turn response for a client that sent {@link TURN_PROGRESS_HEADER}.\n *\n * Reads the stream's leading progress events, handing each to `onPhase` (and an\n * intent line to `onIntent`, or dropping it when there is none), until the\n * first other event. A {@link TURN_RESPONSE_EVENT} resolves to a `Response`\n * with the original status, headers and body, so the caller's existing error\n * handling runs unchanged. Any other event resolves to a `Response` whose body\n * starts at that event and continues with the rest of the stream. A response\n * that is not progress-first is returned as it is.\n */\nexport async function settleTurnResponse(\n response: Response,\n onPhase: (phase: TurnPhaseData) => void,\n onIntent?: (intent: TurnIntentData) => void,\n): Promise<Response> {\n if (response.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST || !response.body) return response\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n const encoder = new TextEncoder()\n let buffer = ''\n let ended = false\n for (;;) {\n let newline = buffer.indexOf('\\n')\n while (newline < 0) {\n if (ended) {\n // The stream closed inside the progress prefix: the turn never started.\n return Response.json(\n { error: 'The connection closed before the turn started. Try again.', code: TURN_STREAM_LOST_CODE },\n { status: 502 },\n )\n }\n const { done, value } = await reader.read()\n if (done) {\n ended = true\n buffer += decoder.decode()\n // A final line without its newline is still a line.\n if (buffer.trim()) buffer += '\\n'\n } else {\n buffer += decoder.decode(value, { stream: true })\n }\n newline = buffer.indexOf('\\n')\n }\n const line = buffer.slice(0, newline).trim()\n if (!line) {\n buffer = buffer.slice(newline + 1)\n continue\n }\n let event: unknown\n try {\n event = JSON.parse(line)\n } catch {\n event = null\n }\n if (isTurnPhaseEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onPhase(event.data)\n continue\n }\n // An intent line is progress too: a response the route answers after it\n // (a held lock's 409) still settles with its own status.\n if (isTurnIntentEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onIntent?.(event.data)\n continue\n }\n const answered = event as { type?: unknown; data?: Partial<TurnResponseData> } | null\n if (answered?.type === TURN_RESPONSE_EVENT && typeof answered.data?.status === 'number') {\n await reader.cancel().catch(() => {})\n return new Response(answered.data.status === 204 || answered.data.status === 304 ? null : String(answered.data.body ?? ''), {\n status: answered.data.status,\n headers: answered.data.headers ?? {},\n })\n }\n return streamFrom(reader, buffer, encoder, response)\n }\n}\n\n/** The rest of a progress-first stream, starting with bytes already read. */\nfunction streamFrom(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n pending: string,\n encoder: TextEncoder,\n original: Response,\n): Response {\n let first = pending\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (first) {\n controller.enqueue(encoder.encode(first))\n first = ''\n return\n }\n const { done, value } = await reader.read()\n if (done) controller.close()\n else controller.enqueue(value)\n },\n cancel(reason) {\n return reader.cancel(reason)\n },\n })\n return new Response(body, { status: original.status, headers: original.headers })\n}\n","import { isWorkspaceFileExportable } from '../web/file-export'\nimport { TURN_PROGRESS_FIRST, TURN_PROGRESS_HEADER } from './turn-progress'\nimport type { ReasoningEffort } from '@tangle-network/agent-interface'\n\n/**\n * Wire contract between the chat client (composer + `streamChatTurn`) and the\n * assembled server vertical (`createChatTurnRoutes`). This module must remain\n * browser-safe: `/web-react` re-exports these types into browser bundles, so\n * imports must not reach a Node builtin or an engine package.\n *\n * The client part shape permits an absolute file path until the server converts\n * it to the URL required by the sandbox SDK. It is derived here, not imported,\n * so the client bundle never touches the SDK.\n */\n\nexport interface ChatTurnTextPartInput {\n type: 'text'\n text: string\n}\n\n/** A non-text prompt part the upload route hands back and the client echoes\n * on send. `url` carries an inline `data:` URI for small files; `path` is a\n * sandbox workspace reference for large ones (the >1 MiB gateway body cap\n * makes the two-step upload mandatory). */\nexport interface ChatTurnFilePartInput {\n type: 'image' | 'file'\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\n/** Resolve input as either a text part or a file part of a chat turn */\nexport type ChatTurnPartInput = ChatTurnTextPartInput | ChatTurnFilePartInput\n\n/** A chat turn's automatic sentinel plus the canonical agent reasoning levels. */\nexport type ChatReasoningEffort = 'auto' | ReasoningEffort\n\n// ── producer stream vocabulary ───────────────────────────────────────────────\n\n/** Represent a text event produced by a source with a fixed type and associated text content */\nexport interface ProducerTextEvent {\n type: 'text'\n text: string\n}\n\n/** Define an event representing reasoning output with a fixed type and associated text */\nexport interface ProducerReasoningEvent {\n type: 'reasoning'\n text: string\n}\n\n/** Represent an event triggered by a producer tool call with its identifier, name, and arguments */\nexport interface ProducerToolCallEvent {\n type: 'tool_call'\n call: {\n toolCallId: string\n toolName: string\n args: Record<string, unknown>\n }\n}\n\n/** Describe the structure of an event representing the result of a producer tool call */\nexport interface ProducerToolResultEvent {\n type: 'tool_result'\n toolCallId: string\n toolName: string\n outcome: {\n ok: boolean\n result?: unknown\n message?: string\n /** Typed reason for a failed call, when the producer knows it. */\n code?: string\n }\n}\n\n/** Describe cumulative provider usage reported by a producer. */\nexport interface ProducerUsageEvent {\n type: 'usage'\n usage: {\n promptTokens: number\n completionTokens: number\n /** Prompt tokens the provider served from its prompt cache. */\n cachedPromptTokens?: number\n reasoningTokens?: number\n toolTokens?: number\n toolCallCount?: number\n providerCostUsd?: number\n /** Present only when the provider enforced the complete execution budget. */\n budgetEnforced?: boolean\n }\n}\n\n/** Define the structure for a producer notice event with type, id, kind, and text fields */\nexport interface ProducerNoticeEvent {\n type: 'notice'\n id: string\n /** Kept inline with `/interactions`' `NoticeKind` so this file stays import-free. */\n noticeKind: 'warning' | 'auto-declined' | 'error'\n text: string\n /** Typed reason, on an `error` notice. */\n code?: string\n /** The failure's redacted cause chain, persisted with the notice and not rendered. */\n detail?: string\n}\n\n/** Represent an error event emitted by a producer containing message, code, and optional details */\nexport interface ProducerErrorEvent {\n type: 'error'\n data: {\n message: string\n code?: string\n details?: Record<string, unknown>\n }\n}\n\n/** Stable raw lifecycle/interaction/plan/route events forwarded unchanged. */\nexport type ProducerPassthroughEventType =\n | 'turn'\n | 'metadata'\n | 'interaction'\n | 'interaction.cancel'\n | 'plan.submitted'\n | 'done'\n | 'warning'\n /** A tool's typed side event while it runs (`data`: toolCallId, toolName, kind, data, at). */\n | 'tool.event'\n | 'session.run.started'\n | 'session.run.completed'\n | 'session.run.failed'\n | 'turn_status'\n\n/** Define an event carrying passthrough data with flexible properties for producer communication */\nexport interface ProducerPassthroughEvent {\n type: ProducerPassthroughEventType\n data?: Record<string, unknown>\n /** Route markers and raw passthroughs may carry `turnId`, `status`, `seq`, etc. */\n [key: string]: unknown\n}\n\n/** Represent events emitted by a producer during its operation for processing and handling */\nexport type ProducerWireEvent =\n | ProducerTextEvent\n | ProducerReasoningEvent\n | ProducerToolCallEvent\n | ProducerToolResultEvent\n | ProducerUsageEvent\n | ProducerNoticeEvent\n | ProducerErrorEvent\n | ProducerPassthroughEvent\n\n/** The image/file split an attachment is rendered and persisted under — the\n * same discriminant as {@link ChatMentionKind}, but a distinct name because an\n * attachment carries content the product uploaded (`ChatAttachmentInput`)\n * while a mention points at a file the box already has. Defined HERE (the\n * import-free layer) so `ChatAttachmentInput` can reference it and the client\n * composer imports it without pulling the persisted-part vocabulary;\n * `/chat-store`'s parts module re-exports it alongside the attachment helpers. */\nexport type ChatAttachmentKind = 'image' | 'file'\n\n/** `POST` turn-body entry describing a file already uploaded to the product's\n * store (vault/object-store) — distinct from an inline {@link\n * ChatTurnFilePartInput} (which carries bytes) and from a {@link FileMention}\n * (a sandbox path the box already holds). The route resolves this field with\n * {@link resolveChatAttachments}: every path is re-validated and every size is\n * re-derived from the stored body, so nothing here is trusted as sent. */\nexport interface ChatAttachmentInput {\n path: string\n name: string\n size: number\n mediaType: string\n kind: ChatAttachmentKind\n}\n\n/** POST body for the turn route. `content` may be empty when `parts` carry the\n * message (an image-only send). Product routing fields (workspaceId etc.) ride\n * alongside and are read by the product's `authorize` seam. */\nexport interface ChatTurnRequestPayload {\n threadId: string\n content?: string\n /** Non-text parts from the upload route, echoed back verbatim. */\n parts?: ChatTurnFilePartInput[]\n /** `@`-picked file mentions for this turn — path references into the\n * workspace sandbox, NOT uploads, so they travel in their own field rather\n * than as `parts` entries. A product whose `parts` field is already spoken\n * for (an attachment sentinel) can still send mentions, and mentions\n * persist as their own `ChatMentionPart`s so a retry rebuilds them. The\n * route validates this field with {@link parseFileMentions} and replaces it\n * on the payload with the validated, deduped list. */\n mentions?: ChatMention[]\n /** Files uploaded to the product's store ahead of the turn — path\n * references, NOT inline bytes (those ride `parts`). Validated and\n * size-re-derived by {@link resolveChatAttachments} into persistable\n * attachment parts; a product whose `parts` field is spoken for by inline\n * uploads still sends store-backed files here. */\n attachments?: ChatAttachmentInput[]\n model?: string\n effort?: ChatReasoningEffort\n harness?: string\n /** Client-generated idempotency key for the logical turn (retry-safe). */\n turnId?: string\n /** New token for a deliberate retry; reuse it for transport retries of that attempt. */\n retryAttemptId?: string\n [key: string]: unknown\n}\n\n/** `fetch` init for the turn route — the one place the client wire shape is\n * serialized, so composer glue and products never drift from the server's\n * parser. */\nexport function chatTurnRequestInit(\n payload: ChatTurnRequestPayload,\n options: { progressFirst?: boolean } = {},\n): RequestInit {\n return {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n // Ask for a progress-first stream (`./turn-progress`); settle the response with `settleTurnResponse`.\n ...(options.progressFirst ? { [TURN_PROGRESS_HEADER]: TURN_PROGRESS_FIRST } : {}),\n },\n body: JSON.stringify(payload),\n }\n}\n\n// ── inline-part byte budget ─────────────────────────────────────────────────\n//\n// The sandbox gateway caps request bodies at 1 MiB; a turn body whose inline\n// `data:` parts exceed it dies at the gateway with an opaque 413. Enforce the\n// budget at the route boundary instead, with headroom for the JSON envelope\n// (same fail-loud-at-the-choke-point style as /sandbox's provision-payload and\n// env-size gates).\n\n/** Define the maximum byte size allowed for inline parts in data processing */\nexport const INLINE_PARTS_MAX_BYTES = 950_000\n\n// ── dispatch (parts[]) budget vocabulary ────────────────────────────────────\n//\n// The default caps `buildDispatchParts` sizes an attachment/mention dispatch\n// against — the sidecar/proxy limits an assembled `parts` array crosses, one\n// step past `INLINE_PARTS_MAX_BYTES` (which gates the raw turn BODY). Grouped\n// here, in the import-free layer, so the numbers are one overridable\n// vocabulary the client can read and a product can tune per call rather than\n// constants buried in the server module. NOTE: these model sidecar/proxy caps,\n// not a product's MIME accept-list or vault bucketing — those are DOMAIN\n// values the product supplies, never defaulted here.\n\n/** Hard cap on the whole `/prompt` request body as it crosses the sandbox\n * proxy — smaller in practice than a raw-file write cap because a dispatch\n * carries several inline parts plus the flattened history in one request. */\nexport const DISPATCH_REQUEST_MAX_BYTES = 1024 * 1024\n\n/** Bytes reserved off the top of {@link DISPATCH_REQUEST_MAX_BYTES} for the\n * JSON structure around the parts array (keys, delimiters, per-part\n * `type`/`filename`/`mediaType` fields) that {@link base64WireLen} does not\n * account for — keeps the inline budget off the exact proxy cap where one\n * stray byte trips the 413. */\nexport const DISPATCH_STRUCTURAL_RESERVE_BYTES = 64 * 1024\n\n/** Sidecar's hard cap on the `parts` array of one prompt request — a dispatch\n * must never assemble more parts than this or the whole turn 400s. */\nexport const DISPATCH_MAX_PARTS = 64\n\n/** Product-side cap on media parts per dispatch (current turn + carried\n * history), well under {@link DISPATCH_MAX_PARTS}. History trimming that keeps\n * a transcript's native media under this is a PRODUCT concern (the pointer\n * block keeps trimmed media reachable); `buildDispatchParts` enforces only the\n * total {@link DISPATCH_MAX_PARTS} cap. */\nexport const DISPATCH_MAX_MEDIA_PARTS = 24\n\n/** Size a base64-encoded string occupies on the wire given the raw\n * (pre-encoding) byte length: base64 packs 3 raw bytes into 4 output\n * characters, rounded up to the next multiple of 4. */\nexport function base64WireLen(byteLen: number): number {\n return Math.ceil(byteLen / 3) * 4\n}\n\n/**\n * Render a raw byte count as a human-readable size (`512B`, `3KB`, `12MB\n * 500KB`). Ported EXACTLY from gtm-agent's `attachment-limits.ts` — byte-\n * identical implementation, not a reinterpretation — so `resolve-attachments`'s\n * and `promote-file-part`'s error strings match gtm's wording verbatim. Lives\n * in the import-free wire layer (not `resolve-attachments.ts` alone) because\n * BOTH the aggregate-cap message here and the per-file oversize message in\n * `promote-file-part.ts` need it; a browser composer wanting the same\n * formatting for a client-side pre-check can also import it with no engine\n * pulled in.\n */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`\n if (bytes >= 1024 * 1024) {\n const megabytes = Math.floor(bytes / (1024 * 1024))\n const remainder = bytes % (1024 * 1024)\n return remainder === 0 ? `${megabytes}MB` : `${megabytes}MB ${formatBytes(remainder)}`\n }\n return `${Math.round(bytes / 1024)}KB`\n}\n\n/** Represent errors for invalid chat turn inputs with status and code properties */\nexport class ChatTurnInputError extends Error {\n constructor(message: string, readonly status = 400, readonly code = 'INVALID_CHAT_TURN') {\n super(message)\n this.name = 'ChatTurnInputError'\n }\n}\n\nfunction partByteSize(part: ChatTurnPartInput): number {\n let bytes = 0\n if (part.type === 'text') return part.text.length\n if (part.url) bytes += part.url.length\n if (part.path) bytes += part.path.length\n return bytes\n}\n\n/** Calculate the total byte size of an array of chat turn parts */\nexport function promptPartsByteSize(parts: ChatTurnPartInput[]): number {\n return parts.reduce((total, part) => total + partByteSize(part), 0)\n}\n\n/** Throws `ChatTurnInputError` (413) when the parts' inline payload would blow\n * the gateway cap. Path-ref parts are tiny by construction and always pass. */\nexport function assertPromptPartsWithinCap(\n parts: ChatTurnPartInput[],\n maxBytes = INLINE_PARTS_MAX_BYTES,\n): void {\n const total = promptPartsByteSize(parts)\n if (total <= maxBytes) return\n const largest = [...parts].sort((a, b) => partByteSize(b) - partByteSize(a))[0]\n const largestName = largest && largest.type !== 'text' ? largest.filename ?? largest.path ?? largest.type : 'text'\n throw new ChatTurnInputError(\n `Inline prompt parts total ${total}B, over the ${maxBytes}B budget (largest: ${largestName}, ${largest ? partByteSize(largest) : 0}B). ` +\n 'Upload large files through the upload route so they travel as sandbox path references.',\n 413,\n 'PROMPT_PARTS_TOO_LARGE',\n )\n}\n\n// ── file mentions ────────────────────────────────────────────────────────\n//\n// A file mention (`@`-picked in the composer, sandbox-ui#184) is a path\n// reference into the workspace sandbox — no byte upload. These helpers turn\n// a resolved mention list into wire parts and the prompt pointer block that\n// tells the agent where to read them from.\n\n/** A file mention resolved from the composer's `@`-picker: the\n * workspace-relative path plus enough metadata to build a prompt part and\n * pointer text. `path` is the canonical identity — the mention pill's\n * `MentionItem.id` for the file kind (`/web-react`'s `useFileMentions`). */\nexport interface FileMention {\n path: string\n name: string\n size?: number\n}\n\n/** An agent mention from the composer's `@`-picker: a workspace agent the\n * turn is addressed to. `handle` is the `@`-token identity (the pill's\n * `MentionItem.id`, what the message text carries as `@<handle>`);\n * `agentId` is the stable profile id, so a renamed agent still resolves from\n * an old message. A file mention has no `kind`; this one always does. */\nexport interface AgentMention {\n kind: 'agent'\n agentId: string\n handle: string\n name: string\n}\n\n/** Everything the composer can `@`: a file in the box or an agent in the workspace. */\nexport type ChatMention = FileMention | AgentMention\n\nexport function isAgentMention(mention: ChatMention): mention is AgentMention {\n return (mention as AgentMention).kind === 'agent'\n}\n\n/** The file mentions of a validated list, for the seams that read the box. */\nexport function fileMentionsOf(mentions: readonly ChatMention[]): FileMention[] {\n return mentions.filter((mention): mention is FileMention => !isAgentMention(mention))\n}\n\n/** The agent mentions of a validated list, in mention order: the turn's responders. */\nexport function agentMentionsOf(mentions: readonly ChatMention[]): AgentMention[] {\n return mentions.filter(isAgentMention)\n}\n\n/** A handle is what a person types after `@`: lowercase letters, digits and\n * hyphens, as `normalizeProfileName` in `/agent-profiles` spells a name. */\nexport const AGENT_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/\n\n/** The handle a profile name gets: lowercase, runs of anything else become one\n * hyphen, no leading or trailing hyphen, at most 63 characters. \"Research\n * Lead\" is `research-lead`. One spelling for the composer, the route and the\n * rail, so a product never derives its own. An empty result (a name with no\n * letters or digits) is `agent`. */\nexport function agentHandle(name: string): string {\n const handle = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 63).replace(/-+$/, '')\n return handle || 'agent'\n}\nconst AGENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/\n\nconst MENTION_IMAGE_MEDIA_TYPES: ReadonlyMap<string, string> = new Map([\n ['.png', 'image/png'],\n ['.jpg', 'image/jpeg'],\n ['.jpeg', 'image/jpeg'],\n ['.gif', 'image/gif'],\n ['.webp', 'image/webp'],\n ['.svg', 'image/svg+xml'],\n ['.bmp', 'image/bmp'],\n ['.heic', 'image/heic'],\n ['.heif', 'image/heif'],\n ['.avif', 'image/avif'],\n])\n\nfunction extensionOf(path: string): string {\n const base = path.split('/').filter(Boolean).pop() ?? path\n const dot = base.lastIndexOf('.')\n return dot > 0 ? base.slice(dot).toLowerCase() : ''\n}\n\n/** The `image/*` mime for a mention path by extension, or `undefined` for\n * anything not in the known image set (dispatched as `type: 'file'`). */\nexport function mediaTypeForMentionPath(path: string): string | undefined {\n return MENTION_IMAGE_MEDIA_TYPES.get(extensionOf(path))\n}\n\n/** The image/file split a mention is rendered and persisted under — the\n * composer pill's icon, the dispatched part's `type`, and\n * `ChatMentionPart.mentionKind` are all this one value. */\nexport type ChatMentionKind = 'image' | 'file' | 'agent'\n\n/** `image` when the path's extension is in the known image set (the same table\n * {@link mediaTypeForMentionPath} reads), `file` otherwise. Exported so a\n * client that needs only the discriminant — a pill icon, a persisted part's\n * `mentionKind` — never re-declares the extension table; two frozen copies of\n * one mime table is how one gains a format and the other doesn't. */\nexport function mentionKindForPath(path: string): ChatMentionKind {\n return mediaTypeForMentionPath(path) ? 'image' : 'file'\n}\n\n/** Define options to resolve mention paths when converting file mentions to parts */\nexport interface FileMentionsToPartsOptions {\n /** Resolve a mention's workspace-relative path to the absolute path the\n * dispatched part should carry (e.g. a host prefixing the in-box vault\n * root). Default: identity — the path travels unchanged. */\n resolvePath?: (path: string) => string\n}\n\n/** Maps resolved file mentions to path-only `ChatTurnFilePartInput`s —\n * `image` vs `file` by extension, and always a `path`, never a `url` (the\n * url/path XOR invariant: a mention is a sandbox path reference, never\n * inline bytes). */\nexport function fileMentionsToParts(\n mentions: readonly ChatMention[],\n opts: FileMentionsToPartsOptions = {},\n): ChatTurnFilePartInput[] {\n const resolvePath = opts.resolvePath ?? ((path: string) => path)\n // An agent mention addresses a responder; it points at nothing in the box.\n return fileMentionsOf(mentions).map((mention) => {\n const mediaType = mediaTypeForMentionPath(mention.path)\n const part: ChatTurnFilePartInput = {\n type: mediaType ? 'image' : 'file',\n filename: mention.name,\n path: resolvePath(mention.path),\n }\n if (mediaType) part.mediaType = mediaType\n return part\n })\n}\n\n/** The agent-facing pointer block appended to the dispatched prompt — never\n * persisted in message `content`. Empty array → `''` so callers can append\n * unconditionally. This is the sole producer of that text: the current\n * turn's dispatch and any history projection built from the same mention\n * list both route through here, so the two can't drift apart. */\nexport function buildMentionPromptBlock(\n mentions: readonly (Pick<FileMention, 'name' | 'path'> | AgentMention)[],\n): string {\n const files = mentions.filter((m): m is Pick<FileMention, 'name' | 'path'> => (m as AgentMention).kind !== 'agent')\n if (files.length === 0) return ''\n const lines = files.map((m) => `- ${m.name} (${m.path})`)\n return `\\n\\nMentioned files — read them from these paths:\\n${lines.join('\\n')}`\n}\n\n// ── mention validation ───────────────────────────────────────────────────\n//\n// This package owns BOTH ends of the mention path contract — it emits paths\n// from `createSandboxFileIndexRoute` and consumes them in `fileMentionsToParts`\n// / `buildMentionPromptBlock` — so the validation belongs here rather than in\n// each app that wires the pair up. A mention names a file that already exists\n// in the sandbox, so validation is a pure path/charset/count check with no\n// I/O: existence is proven later, when the agent reads the path and the turn\n// fails loudly if it is gone.\n\n/** Hard cap on mentions per turn. Bounds the prompt pointer block, the\n * persisted parts, and whatever media budget a dispatch draws from them. */\nexport const MENTION_MAX_COUNT = 16\n\n/** Longest mention display name accepted — bounds the pointer-block text and\n * the transcript pill label. */\nconst MAX_MENTION_NAME_LENGTH = 256\n/** Longest mention path accepted. */\nconst MAX_MENTION_PATH_LENGTH = 1024\n\n/** Represent the result of a sandbox mention path check indicating success or failure with an error message */\nexport type SandboxMentionPathCheck =\n | { succeeded: true }\n | { succeeded: false; error: string }\n\n/**\n * Validate a workspace-relative sandbox mention path. Rejects traversal (a\n * `..` path segment), absolute paths (leading `/`), backslashes, and null\n * bytes — the four ways a path picked in a client can escape the root the\n * index route scanned.\n *\n * Spaces and unicode are deliberately ALLOWED: in-box filenames are arbitrary,\n * and an ASCII-only charset would silently drop real files from a feature\n * whose whole job is naming them.\n */\nexport function validateSandboxMentionPath(path: unknown): SandboxMentionPathCheck {\n if (typeof path !== 'string' || path.length === 0) {\n return { succeeded: false, error: 'mention path must be a non-empty string' }\n }\n if (path.length > MAX_MENTION_PATH_LENGTH) {\n return { succeeded: false, error: `mention path must not exceed ${MAX_MENTION_PATH_LENGTH} characters` }\n }\n if (path.includes('\\0')) {\n return { succeeded: false, error: 'mention path must not contain null bytes' }\n }\n if (path.includes('\\\\')) {\n return { succeeded: false, error: 'mention path must not contain backslashes' }\n }\n if (path.startsWith('/')) {\n return { succeeded: false, error: 'mention path must be workspace-relative, not absolute' }\n }\n if (path.split('/').some((segment) => segment === '..')) {\n return { succeeded: false, error: 'mention path must not contain \"..\" segments' }\n }\n return { succeeded: true }\n}\n\nfunction parseFileMention(value: unknown, index: number): FileMention {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ChatTurnInputError(`mentions[${index}] must be an object`)\n }\n const record = value as Record<string, unknown>\n\n const pathCheck = validateSandboxMentionPath(record.path)\n if (!pathCheck.succeeded) throw new ChatTurnInputError(`mentions[${index}]: ${pathCheck.error}`)\n\n if (!isWorkspaceFileExportable(record.path as string)) {\n throw new ChatTurnInputError(`mentions[${index}]: file is not exportable`)\n }\n\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n throw new ChatTurnInputError(`mentions[${index}].name must be a non-empty string`)\n }\n if (name.length > MAX_MENTION_NAME_LENGTH) {\n throw new ChatTurnInputError(`mentions[${index}].name must not exceed ${MAX_MENTION_NAME_LENGTH} characters`)\n }\n\n const size = record.size\n if (size !== undefined) {\n if (typeof size !== 'number' || !Number.isFinite(size)) {\n throw new ChatTurnInputError(`mentions[${index}].size must be a finite number`)\n }\n if (size < 0) {\n throw new ChatTurnInputError(`mentions[${index}].size must not be negative`)\n }\n }\n\n return { path: record.path as string, name, ...(typeof size === 'number' ? { size } : {}) }\n}\n\n/**\n * Validates the untyped `mentions` array off the wire, mirroring\n * {@link parseChatTurnParts}: the typed list, or `ChatTurnInputError` (400)\n * naming the offending entry. Never sanitizes-and-continues — a traversal path\n * is a rejected request, not a trimmed one.\n *\n * A path repeated within one turn is deduped to its first occurrence rather\n * than rejected: mentioning the same file twice is plausible user input, not\n * an attack.\n */\n/** The validated, deduped mention list off the wire: files by path, agents\n * by id, in the order typed. One cap covers both kinds. */\nexport function parseMentions(raw: unknown): ChatMention[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('mentions must be an array')\n if (raw.length > MENTION_MAX_COUNT) {\n throw new ChatTurnInputError(`mentions must not exceed ${MENTION_MAX_COUNT} entries`)\n }\n\n const mentions: ChatMention[] = []\n const seen = new Set<string>()\n for (let index = 0; index < raw.length; index += 1) {\n const entry = raw[index] as Record<string, unknown> | null\n const mention = entry && typeof entry === 'object' && entry.kind === 'agent'\n ? parseAgentMention(entry, index)\n : parseFileMention(raw[index], index)\n const key = isAgentMention(mention) ? `agent:${mention.agentId}` : `file:${mention.path}`\n if (seen.has(key)) continue\n seen.add(key)\n mentions.push(mention)\n }\n return mentions\n}\n\n/** The file mentions of the wire list; agent mentions are validated and set aside. */\nexport function parseFileMentions(raw: unknown): FileMention[] {\n return fileMentionsOf(parseMentions(raw))\n}\n\nfunction parseAgentMention(record: Record<string, unknown>, index: number): AgentMention {\n const agentId = record.agentId\n if (typeof agentId !== 'string' || !AGENT_ID_PATTERN.test(agentId)) {\n throw new ChatTurnInputError(`mentions[${index}].agentId must be 1–128 letters, digits, dots, colons, underscores or hyphens`)\n }\n const handle = record.handle\n if (typeof handle !== 'string' || !AGENT_HANDLE_PATTERN.test(handle)) {\n throw new ChatTurnInputError(`mentions[${index}].handle must be lowercase letters, digits and hyphens`)\n }\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n throw new ChatTurnInputError(`mentions[${index}].name must be a non-empty string`)\n }\n if (name.length > MAX_MENTION_NAME_LENGTH) {\n throw new ChatTurnInputError(`mentions[${index}].name must not exceed ${MAX_MENTION_NAME_LENGTH} characters`)\n }\n return { kind: 'agent', agentId, handle, name: name.trim() }\n}\n\n/** Validates the untyped `parts` array off the wire. Returns the typed parts\n * or throws `ChatTurnInputError` (400) naming the offending entry. */\nexport function parseChatTurnParts(raw: unknown): ChatTurnFilePartInput[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('parts must be an array')\n return raw.map((entry, index) => {\n const part = entry as Record<string, unknown> | null\n if (!part || typeof part !== 'object') {\n throw new ChatTurnInputError(`parts[${index}] must be an object`)\n }\n if (part.type !== 'image' && part.type !== 'file') {\n throw new ChatTurnInputError(`parts[${index}].type must be 'image' or 'file'`)\n }\n for (const key of ['filename', 'mediaType', 'url', 'path'] as const) {\n if (part[key] !== undefined && typeof part[key] !== 'string') {\n throw new ChatTurnInputError(`parts[${index}].${key} must be a string`)\n }\n }\n if (part.content !== undefined) {\n throw new ChatTurnInputError(`parts[${index}].content is not supported; 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(`parts[${index}] requires exactly one url or path`)\n }\n if (path && !path.startsWith('/')) {\n throw new ChatTurnInputError(`parts[${index}].path must be absolute`)\n }\n\n const filename = typeof part.filename === 'string' ? part.filename.trim() : undefined\n if (part.type === 'file' && !filename) {\n throw new ChatTurnInputError(`parts[${index}].filename is required for file parts`)\n }\n return {\n type: part.type,\n ...(filename ? { filename } : {}),\n ...(part.mediaType !== undefined ? { mediaType: part.mediaType as string } : {}),\n ...(url ? { url } : { path: path! }),\n }\n })\n}\n"],"mappings":";;;;;AA+BO,IA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C;AAAA,IACjF;AACA,QAAI,QAAQ,CAAC,KAAK,WAAW,GAAG,GAAG;AACjC,YAAM,IAAI,mBAAmB,SAAS,KAAK,yBAAyB;AAAA,IACtE;AAEA,UAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,SAAS,KAAK,IAAI;AAC5E,QAAI,KAAK,SAAS,UAAU,CAAC,UAAU;AACrC,YAAM,IAAI,mBAAmB,SAAS,KAAK,uCAAuC;AAAA,IACpF;AACA,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,MAC/B,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAoB,IAAI,CAAC;AAAA,MAC9E,GAAI,MAAM,EAAE,IAAI,IAAI,EAAE,KAAY;AAAA,IACpC;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/turn-trace/phase-timing.ts","../src/turn-trace/recorder.ts","../src/turn-trace/otel.ts","../src/turn-trace/server-timing.ts","../src/turn-trace/traced-fetch.ts"],"sourcesContent":["import type { TurnSpan, TurnSpanAttrs, TurnSpanKind, TurnTrace } from './recorder'\n\n/** Domain-named phases and concurrent work over the turn's existing clock and D1 counter. */\nexport interface TurnPhaseTiming {\n readonly startedAt: number\n mark(name: string): void\n track<T>(name: string, work: Promise<T>, attrsOf?: (value: T) => TurnSpanAttrs): Promise<T>\n within(parent: TurnSpan | undefined): void\n phases(): Record<string, number>\n concurrent(): Record<string, number>\n queries(): Record<string, number>\n}\n\nexport interface TurnPhaseTimingOptions {\n prefix: string\n startedAt?: number\n kinds?: Readonly<Record<string, TurnSpanKind>>\n}\n\n/** The recorder supplies its clock/counter; this module has no host or Node dependency. */\nexport function turnPhaseTiming(trace: TurnTrace, options: TurnPhaseTimingOptions,\n now: () => number, counter?: { readonly queries: number }): TurnPhaseTiming {\n const startedAt = options.startedAt ?? trace.startedAt\n let last = startedAt, floor = startedAt, lastQuery = counter?.queries ?? 0\n let parent: TurnSpan | undefined\n const phases: Record<string, number> = {}, concurrent: Record<string, number> = {}, queries: Record<string, number> = {}\n const kind = (name: string) => options.kinds?.[name] ?? 'admission'\n const label = (name: string) => `${options.prefix}.${name}`\n return {\n startedAt,\n mark(name) {\n const at = now()\n phases[name] = (phases[name] ?? 0) + at - last\n if (counter) {\n queries[name] = (queries[name] ?? 0) + counter.queries - lastQuery\n lastQuery = counter.queries\n }\n trace.record(label(name), kind(name), parent ? Math.max(last, floor) : last, at, {}, parent)\n last = at\n },\n track(name, work, attrsOf) {\n const began = now(), span = trace.start(label(name), kind(name))\n void work.then(value => { concurrent[name] = now() - began; span.end(attrsOf?.(value)) },\n error => { concurrent[name] = now() - began; span.end(undefined, error) }).catch(() => {})\n return work\n },\n within(span) { parent = span; floor = now() },\n phases: () => ({ ...phases }), concurrent: () => ({ ...concurrent }), queries: () => counter ? { ...queries } : {},\n }\n}\n","import { turnPhaseTiming, type TurnPhaseTiming, type TurnPhaseTimingOptions } from './phase-timing'\n/**\n * One trace per agent turn: a root span for the turn's wall time and named\n * child spans for where that time went (admission, each model call, each tool\n * call, the box claim and prompt, persistence).\n *\n * This module only records. It has no imports, so the Router engine, the\n * sandbox helpers and the chat route share it from any runtime, a Worker\n * included. `./otel` turns a finished trace into OTLP spans for Tangle\n * Intelligence.\n *\n * The turn's trace id is its execution id in the charset every hop accepts\n * ({@link turnTraceId}), sent as `x-tangle-trace-id` on every Router and\n * Sandbox call, so a Router dispatch row and a sandbox record join the turn's\n * spans by one id.\n */\n\n/** What a span's time is spent on. Each instant of the turn is credited to the deepest open span's kind. */\nexport type TurnSpanKind =\n | 'admission'\n | 'router'\n | 'model'\n | 'network'\n | 'tool'\n | 'sandbox'\n | 'persist'\n | 'other'\n\nexport const TURN_SPAN_KINDS: readonly TurnSpanKind[] = ['admission', 'router', 'model', 'network', 'tool', 'sandbox', 'persist', 'other']\n\n/** Bounded primitive metadata. Never prompts, answers, tool arguments or credentials. */\nexport type TurnSpanAttrs = Record<string, string | number | boolean>\n\nexport interface TurnSpanRecord {\n spanId: string\n /** The root span's id for a top-level child. */\n parentSpanId: string\n name: string\n kind: TurnSpanKind\n startMs: number\n endMs: number\n attrs: TurnSpanAttrs\n /** Set when the span ended in failure; a short code or message, never content. */\n error?: string\n /** True when the turn finished while the span was still open. */\n unfinished?: boolean\n}\n\nexport interface TurnSpan {\n readonly id: string\n /** Merge attributes. A later value replaces an earlier one. */\n set(attrs: TurnSpanAttrs): TurnSpan\n /** End now. A second call changes nothing. `error` marks the span failed. */\n end(attrs?: TurnSpanAttrs, error?: unknown): void\n /** A child that starts now. */\n child(name: string, kind: TurnSpanKind, attrs?: TurnSpanAttrs): TurnSpan\n /** A child whose times are already known. */\n record(name: string, kind: TurnSpanKind, startMs: number, endMs: number, attrs?: TurnSpanAttrs): TurnSpan\n}\n\n/** How much of the turn's wall time is inside named spans, and what the time was spent on. */\nexport interface TurnTraceSummary {\n traceId: string\n wallMs: number\n /** Wall time inside at least one child span. */\n coveredMs: number\n /** `coveredMs / wallMs` as a percentage, one decimal. */\n coveragePct: number\n uncoveredMs: number\n /** The longest stretch with no span open: where an unnamed wait hides. */\n largestGapMs: number\n /** Wall time credited to the deepest open span's kind. Sums to `coveredMs`. */\n byKind: Record<TurnSpanKind, number>\n spans: number\n modelCalls: number\n toolCalls: number\n /** Spans refused after the per-turn cap. */\n dropped: number\n /** From the request to the first visible text the member could read (see {@link TurnTrace.markFirstText}); absent when none streamed. */\n firstTextMs?: number\n /** Headline latency: request to first reasoning, tool activity or answer output. */\n firstVisibleMs?: number\n /** D1 round trips in the turn scope, when its binding is instrumented. */\n d1Queries?: number\n /** From the request to the first model request: the wait the app owns before the model can start. */\n dispatchMs?: number\n /** Each admission and sandbox span's duration by name, less its `admission.` or `sandbox.` prefix: where the wait before first output went. */\n admission?: Record<string, number>; sandbox?: Record<string, number>\n /** Prompt tokens over every model call, and how many of them the provider served from its prompt cache. */\n inputTokens?: number\n cachedInputTokens?: number\n}\n\nexport interface TurnTraceSnapshot {\n traceId: string\n /** The id the root span is exported under. */\n rootSpanId: string\n executionId: string\n startedAt: number\n endedAt: number\n spans: TurnSpanRecord[]\n summary: TurnTraceSummary\n /** `ok`, or the failure the turn ended with. */\n status: 'ok' | 'error'\n error?: string\n}\n\n/** Where a finished turn's trace goes. `labels` are the host's metadata for the root span (session, user, workspace). */\nexport type TurnTraceSink = (snapshot: TurnTraceSnapshot, labels: TurnSpanAttrs) => void | Promise<void>\n\nexport interface TurnTrace {\n /** The turn's execution id in the charset the Router and Sandbox accept. Send it as `x-tangle-trace-id`. */\n readonly traceId: string\n readonly executionId: string\n readonly startedAt: number\n /** The span a top-level child hangs from. */\n readonly root: TurnSpan\n /** Name the turn's execution id once it is known. Spans recorded earlier keep their times. */\n bind(executionId: string): void\n start(name: string, kind: TurnSpanKind, attrs?: TurnSpanAttrs, parent?: TurnSpan): TurnSpan\n /** A span whose times are already known; `error` marks it failed, as `end` does for an open one. */\n record(name: string, kind: TurnSpanKind, startMs: number, endMs: number, attrs?: TurnSpanAttrs, parent?: TurnSpan, error?: unknown): TurnSpan\n /** Run `work` inside a span; the span ends when it settles, failed if it throws. */\n measure<T>(name: string, kind: TurnSpanKind, work: (span: TurnSpan) => Promise<T> | T, attrs?: TurnSpanAttrs, parent?: TurnSpan): Promise<T>\n /**\n * Note that the turn's first visible text reached the member. The chat route calls it on the first text event of\n * either lane; a product that owns its turn calls it itself. Only the first call counts. The summary's\n * `firstTextMs` then reads from the request, so it holds admission, the box or the Router, and the model.\n */\n markFirstText(at?: number): void\n /** Mark the first reasoning, tool activity or answer output. Only the first call counts. */\n markFirstVisible(at?: number): void\n /** Sequential phases and concurrent work share this turn's existing clock and query counter. */\n timing(options: TurnPhaseTimingOptions): TurnPhaseTiming\n /** Read the current numbers without ending the trace. */\n summary(now?: number): TurnTraceSummary\n /** Read the spans recorded so far without ending the trace; an open span reads as ending at `now`. */\n spans(now?: number): TurnSpanRecord[]\n /** End the trace: open spans close at `endedAt`, and later spans are refused. A second call returns the first result. */\n finish(outcome?: { error?: unknown; endedAt?: number }): TurnTraceSnapshot\n}\n\nexport interface CreateTurnTraceOptions {\n /** Epoch ms the turn began (default now). A route passes its request time so admission is inside the trace. */\n startedAt?: number\n executionId?: string\n now?: () => number\n /** Most spans one turn keeps (default 1000); the rest are counted as dropped. */\n maxSpans?: number\n /** Live counter captured by the server turn owner; no Node dependency in the recorder. */\n d1QueryCounter?: { readonly queries: number }\n}\nconst MAX_ATTRS = 48\nconst MAX_ATTR_STRING = 200\n\n/**\n * The turn's execution id as a trace id. Execution ids carry `:` (`app:session:turn`),\n * which the Router drops from `x-tangle-trace-id`, so every character outside\n * `[A-Za-z0-9_-]` becomes `_`. An id already in the charset is returned as it is.\n */\nexport function turnTraceId(executionId: string): string {\n // An id in the charset is the caller's own, whatever its length (the Router drops one under 8 characters; it is not rewritten here).\n if (/^[\\w-]{1,200}$/.test(executionId)) return executionId\n const id = executionId.replace(/[^\\w-]/g, '_').slice(0, 200)\n return id.length >= 8 ? id : id.padEnd(8, '_')\n}\n\nfunction randomHex(bytes: number): string {\n const out = new Uint8Array(bytes)\n if (typeof globalThis.crypto?.getRandomValues === 'function') globalThis.crypto.getRandomValues(out)\n else for (let i = 0; i < bytes; i++) out[i] = Math.floor(Math.random() * 256)\n return Array.from(out, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction boundedAttrs(attrs: TurnSpanAttrs): TurnSpanAttrs {\n const out: TurnSpanAttrs = {}\n let count = 0\n for (const [key, value] of Object.entries(attrs)) {\n if (count >= MAX_ATTRS) break\n if (typeof value === 'number' && !Number.isFinite(value)) continue\n out[key.slice(0, 80)] = typeof value === 'string' ? value.slice(0, MAX_ATTR_STRING) : value\n count++\n }\n return out\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return (error.name === 'Error' ? error.message : `${error.name}: ${error.message}`).slice(0, MAX_ATTR_STRING)\n return String(error).slice(0, MAX_ATTR_STRING)\n}\n\nconst zeroKinds = (): Record<TurnSpanKind, number> => ({\n admission: 0, router: 0, model: 0, network: 0, tool: 0, sandbox: 0, persist: 0, other: 0,\n})\n\nconst round1 = (value: number) => Math.round(value * 10) / 10\n\n/**\n * Coverage and the per-kind split for a set of spans over `[startMs, endMs]`.\n * Exported for a reader that holds the spans of a finished trace.\n */\nexport function summarizeTurnSpans(\n spans: readonly Pick<TurnSpanRecord, 'spanId' | 'parentSpanId' | 'kind' | 'name' | 'startMs' | 'endMs'>[],\n rootSpanId: string,\n startMs: number,\n endMs: number,\n traceId: string,\n dropped = 0,\n): TurnTraceSummary {\n const wallMs = Math.max(0, endMs - startMs)\n const parent = new Map(spans.map((span) => [span.spanId, span.parentSpanId]))\n const depthOf = (id: string): number => {\n let depth = 0\n for (let at = parent.get(id); at !== undefined && at !== rootSpanId; at = parent.get(at)) {\n depth++\n if (depth > 64) break\n }\n return depth\n }\n const clipped = spans\n .map((span) => ({ span, start: Math.max(startMs, span.startMs), end: Math.min(endMs, span.endMs), depth: depthOf(span.spanId) }))\n .filter((entry) => entry.end > entry.start)\n const points = [...new Set([startMs, endMs, ...clipped.flatMap((entry) => [entry.start, entry.end])])].sort((a, b) => a - b)\n const byKind = zeroKinds()\n let coveredMs = 0\n let largestGapMs = 0\n let gap = 0\n for (let i = 0; i + 1 < points.length; i++) {\n const from = points[i]!\n const to = points[i + 1]!\n let deepest: (typeof clipped)[number] | undefined\n for (const entry of clipped) {\n if (entry.start <= from && entry.end >= to && (!deepest || entry.depth > deepest.depth || (entry.depth === deepest.depth && entry.start > deepest.start))) deepest = entry\n }\n if (deepest) {\n byKind[deepest.span.kind] += to - from\n coveredMs += to - from\n gap = 0\n } else {\n gap += to - from\n largestGapMs = Math.max(largestGapMs, gap)\n }\n }\n for (const kind of TURN_SPAN_KINDS) byKind[kind] = round1(byKind[kind])\n return {\n traceId,\n wallMs: round1(wallMs),\n coveredMs: round1(coveredMs),\n coveragePct: wallMs > 0 ? round1((coveredMs / wallMs) * 100) : 0,\n uncoveredMs: round1(wallMs - coveredMs),\n largestGapMs: round1(largestGapMs),\n byKind,\n spans: spans.length,\n modelCalls: spans.filter((span) => span.name === 'model.call').length,\n toolCalls: spans.filter((span) => span.name === 'tool.call').length,\n dropped,\n }\n}\n\n/** The summary fields read from span names and attributes: dispatch time, the admission split and prompt-cache use. */\nfunction spanMeasurements(spans: readonly TurnSpanRecord[], startedAt: number): Partial<TurnTraceSummary> {\n const split: Record<'admission' | 'sandbox', Record<string, number>> = { admission: {}, sandbox: {} }\n let firstModelCall: number | undefined\n let inputTokens: number | undefined\n let cachedInputTokens: number | undefined\n for (const span of spans) {\n if (span.kind === 'admission' || span.kind === 'sandbox') {\n const step = span.name.replace(/^(admission|sandbox)\\./, '')\n split[span.kind][step] = round1((split[span.kind][step] ?? 0) + span.endMs - span.startMs)\n }\n if (span.name !== 'model.call') continue\n firstModelCall = Math.min(firstModelCall ?? span.startMs, span.startMs)\n const input = span.attrs['gen_ai.usage.input_tokens']\n if (typeof input === 'number') inputTokens = (inputTokens ?? 0) + input\n const cached = span.attrs['gen_ai.usage.cache_read.input_tokens']\n if (typeof cached === 'number') cachedInputTokens = (cachedInputTokens ?? 0) + cached\n }\n return {\n ...(firstModelCall === undefined ? {} : { dispatchMs: round1(Math.max(0, firstModelCall - startedAt)) }),\n ...Object.fromEntries(Object.entries(split).filter(([, steps]) => Object.keys(steps).length)),\n ...(inputTokens === undefined ? {} : { inputTokens }),\n ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),\n }\n}\n\nexport function createTurnTrace(options: CreateTurnTraceOptions = {}): TurnTrace {\n const now = options.now ?? Date.now\n const startedAt = options.startedAt ?? now()\n const maxSpans = options.maxSpans ?? 1000\n const rootId = randomHex(8)\n let executionId = options.executionId ?? `pending_${randomHex(6)}`\n let traceId = turnTraceId(executionId)\n const records = new Map<string, TurnSpanRecord>()\n const open = new Set<string>()\n let dropped = 0\n let finished: TurnTraceSnapshot | undefined\n let firstVisibleAt: number | undefined\n let firstTextAt: number | undefined\n\n // A refused or late span still returns a handle, so instrumentation never branches on the trace's state.\n const inert = (id: string): TurnSpan => {\n const handle: TurnSpan = {\n id,\n set: () => handle,\n end: () => {},\n child: () => inert(rootId),\n record: () => inert(rootId),\n }\n return handle\n }\n\n const handleFor = (id: string): TurnSpan => {\n const handle: TurnSpan = {\n id,\n set(attrs) {\n const record = records.get(id)\n if (record && !finished) record.attrs = boundedAttrs({ ...record.attrs, ...attrs })\n return handle\n },\n end(attrs, error) {\n const record = records.get(id)\n if (!record || !open.has(id) || finished) return\n open.delete(id)\n record.endMs = Math.max(record.startMs, now())\n if (attrs) record.attrs = boundedAttrs({ ...record.attrs, ...attrs })\n if (error !== undefined) record.error = errorText(error)\n },\n child: (name, kind, attrs) => trace.start(name, kind, attrs, handle),\n record: (name, kind, start, end, attrs) => trace.record(name, kind, start, end, attrs, handle),\n }\n return handle\n }\n\n const add = (name: string, kind: TurnSpanKind, startMs: number, endMs: number | undefined, attrs: TurnSpanAttrs | undefined, parent: TurnSpan | undefined,\n error?: unknown): TurnSpan => {\n if (finished) return inert(rootId)\n if (records.size >= maxSpans) {\n dropped++\n return inert(rootId)\n }\n const spanId = randomHex(8)\n records.set(spanId, {\n spanId,\n parentSpanId: parent && parent.id !== spanId ? parent.id : rootId,\n name: name.slice(0, 80),\n kind,\n startMs,\n endMs: endMs ?? startMs,\n attrs: attrs ? boundedAttrs(attrs) : {},\n ...(error === undefined ? {} : { error: errorText(error) }),\n })\n if (endMs === undefined) open.add(spanId)\n return handleFor(spanId)\n }\n\n const rootHandle: TurnSpan = {\n id: rootId,\n set: () => rootHandle,\n end: () => {},\n child: (name, kind, attrs) => trace.start(name, kind, attrs),\n record: (name, kind, start, end, attrs) => trace.record(name, kind, start, end, attrs),\n }\n\n const withMeasurements = (summary: TurnTraceSummary, spans: readonly TurnSpanRecord[]): TurnTraceSummary => ({\n ...summary,\n ...spanMeasurements(spans, startedAt),\n ...(firstVisibleAt === undefined ? {} : { firstVisibleMs: round1(firstVisibleAt - startedAt) }),\n ...(firstTextAt === undefined ? {} : { firstTextMs: round1(firstTextAt - startedAt) }),\n ...(options.d1QueryCounter === undefined ? {} : { d1Queries: options.d1QueryCounter.queries }),\n })\n\n const trace: TurnTrace = {\n get traceId() { return traceId },\n get executionId() { return executionId },\n startedAt,\n root: rootHandle,\n bind(id) {\n executionId = id\n traceId = turnTraceId(id)\n },\n start: (name, kind, attrs, parent) => add(name, kind, now(), undefined, attrs, parent),\n record: (name, kind, startMs, endMs, attrs, parent, error) => add(name, kind, startMs, Math.max(startMs, endMs), attrs, parent, error),\n async measure(name, kind, work, attrs, parent) {\n const span = trace.start(name, kind, attrs, parent)\n try {\n const result = await work(span)\n span.end()\n return result\n } catch (error) {\n span.end(undefined, error)\n throw error\n }\n },\n markFirstVisible(at) {\n if (finished || firstVisibleAt !== undefined) return\n firstVisibleAt = Math.max(startedAt, at ?? now())\n },\n markFirstText(at) {\n if (finished || firstTextAt !== undefined) return\n firstTextAt = Math.max(startedAt, at ?? now())\n firstVisibleAt ??= firstTextAt\n },\n timing: phaseOptions => turnPhaseTiming(trace, phaseOptions, now, options.d1QueryCounter),\n summary(at) {\n if (finished) return finished.summary\n const end = at ?? now()\n const spans = trace.spans(end)\n return withMeasurements(summarizeTurnSpans(spans, rootId, startedAt, end, traceId, dropped), spans)\n },\n spans(at) {\n const end = at ?? finished?.endedAt ?? now()\n return [...records.values()].map((record) => open.has(record.spanId) ? { ...record, endMs: end } : { ...record })\n },\n finish(outcome) {\n if (finished) return finished\n const endedAt = Math.max(startedAt, outcome?.endedAt ?? now())\n for (const id of open) {\n const record = records.get(id)!\n record.endMs = Math.max(record.startMs, endedAt)\n record.unfinished = true\n }\n open.clear()\n const spans = [...records.values()].sort((a, b) => a.startMs - b.startMs)\n finished = {\n traceId,\n rootSpanId: rootId,\n executionId,\n startedAt,\n endedAt,\n spans,\n summary: withMeasurements(summarizeTurnSpans(spans, rootId, startedAt, endedAt, traceId, dropped), spans),\n status: outcome?.error === undefined ? 'ok' : 'error',\n ...(outcome?.error === undefined ? {} : { error: errorText(outcome.error) }),\n }\n return finished\n },\n }\n return trace\n}\n","/**\n * A finished turn trace as OTLP spans, sent to Tangle Intelligence.\n *\n * The attribute vocabulary is the one agent-runtime's span builders write\n * (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.*`,\n * `gen_ai.tool.name`, OpenInference's span kind, `agent.parent.confidence`), and\n * the wire shape is the one its `createOtelExporter` posts to\n * `<base>/v1/otlp/v1/traces`.\n *\n * It does not import agent-runtime. The runtime root pulls the whole sandbox\n * SDK into a Worker bundle, and the SDK's chain client imports `viem`, which a\n * Worker build cannot resolve (Hospitality's release failed on exactly that);\n * and its exporter keeps a timer a Worker refuses at module scope. One OTLP\n * POST per finished turn needs neither.\n */\nimport {\n msToUnixNano, type OtlpSpan, type OtlpTraceExport, otlpTraceExport, readOtlpPartialSuccess, toOtlpAttributes, toW3CTraceId,\n} from '@tangle-network/agent-trace-contract/otlp'\nimport { TURN_SPAN_KINDS, turnTraceId, type TurnSpanAttrs, type TurnSpanKind, type TurnTraceSink, type TurnTraceSnapshot } from './recorder'\n\nexport type { OtlpSpan, OtlpTraceExport } from '@tangle-network/agent-trace-contract/otlp'\n\n/** The root span's measured numbers: one decimal, so each is always a `doubleValue`. */\nconst ROOT_MEASUREMENTS: ReadonlySet<string> = new Set([\n 'tangle.duration_ms',\n 'tangle.turn.wall_ms',\n 'tangle.turn.covered_ms',\n 'tangle.turn.coverage_pct',\n 'tangle.turn.uncovered_ms',\n 'tangle.turn.largest_gap_ms',\n 'tangle.turn.first_visible_ms',\n 'tangle.turn.first_text_ms',\n ...TURN_SPAN_KINDS.map((kind) => `tangle.turn.${kind}_ms`),\n])\n\n/**\n * A Tangle trace id as the 32-hex OTLP trace id. The rule is agent-trace-contract's `toW3CTraceId`, the one the Sandbox\n * SDK, agent-eval and agent-runtime use too, so every export of the same turn lands in the same OTLP trace.\n */\nexport function otlpTraceId(traceId: string): string {\n return toW3CTraceId(traceId)\n}\n\n/** OpenInference span kind per turn span: model calls read as LLM, tool calls as TOOL. */\nconst SPAN_KIND: Partial<Record<string, 'LLM' | 'TOOL'>> = { 'model.call': 'LLM', 'tool.call': 'TOOL' }\n\n/**\n * The root span (`agent_app.turn`) carries the host's labels and the turn's\n * numbers: wall time, the share inside child spans, and the time credited to\n * each kind of span. Children follow under it.\n */\nexport function buildTurnTraceOtelSpans(snapshot: TurnTraceSnapshot, labels: TurnSpanAttrs = {}): OtlpSpan[] {\n const traceId = otlpTraceId(snapshot.traceId)\n const root = snapshot.rootSpanId\n const { summary } = snapshot\n const rootAttrs: Record<string, string | number | boolean> = {\n ...labels,\n 'openinference.span.kind': 'CHAIN',\n 'tangle.execution_id': snapshot.executionId,\n 'tangle.trace_id': snapshot.traceId,\n 'tangle.started_at_ms': snapshot.startedAt,\n 'tangle.completed_at_ms': snapshot.endedAt,\n 'tangle.duration_ms': summary.wallMs,\n 'tangle.turn.wall_ms': summary.wallMs,\n 'tangle.turn.covered_ms': summary.coveredMs,\n 'tangle.turn.coverage_pct': summary.coveragePct,\n 'tangle.turn.uncovered_ms': summary.uncoveredMs,\n 'tangle.turn.largest_gap_ms': summary.largestGapMs,\n 'tangle.turn.spans': summary.spans,\n 'tangle.turn.model_calls': summary.modelCalls,\n 'tangle.turn.tool_calls': summary.toolCalls,\n ...(summary.firstVisibleMs === undefined ? {} : { 'tangle.turn.first_visible_ms': summary.firstVisibleMs }),\n ...(summary.firstTextMs === undefined ? {} : { 'tangle.turn.first_text_ms': summary.firstTextMs }),\n ...(summary.d1Queries === undefined ? {} : { 'tangle.turn.d1_queries': summary.d1Queries }),\n ...(summary.dropped ? { 'tangle.turn.spans_dropped': summary.dropped } : {}),\n ...Object.fromEntries(TURN_SPAN_KINDS.map((kind: TurnSpanKind) => [`tangle.turn.${kind}_ms`, summary.byKind[kind]])),\n }\n const spans: OtlpSpan[] = [{\n traceId,\n spanId: root,\n name: 'agent_app.turn',\n kind: 1,\n startTimeUnixNano: msToUnixNano(snapshot.startedAt),\n endTimeUnixNano: msToUnixNano(snapshot.endedAt),\n attributes: toOtlpAttributes(rootAttrs, { doubles: ROOT_MEASUREMENTS }),\n status: snapshot.status === 'ok' ? { code: 1 } : { code: 2, ...(snapshot.error ? { message: snapshot.error } : {}) },\n }]\n for (const span of snapshot.spans) {\n const attrs: Record<string, string | number | boolean> = {\n ...span.attrs,\n 'openinference.span.kind': SPAN_KIND[span.name] ?? 'CHAIN',\n 'tangle.turn.span_kind': span.kind,\n 'agent.parent.confidence': 'explicit',\n ...(span.name === 'tool.call' ? { 'gen_ai.operation.name': 'execute_tool' } : {}),\n ...(span.unfinished ? { 'tangle.turn.unfinished': true } : {}),\n ...(span.error ? { 'error.message': span.error } : {}),\n }\n spans.push({\n traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n kind: 1,\n startTimeUnixNano: msToUnixNano(span.startMs),\n endTimeUnixNano: msToUnixNano(span.endMs),\n attributes: toOtlpAttributes(attrs),\n status: span.error ? { code: 2, message: span.error } : { code: 1 },\n })\n }\n return spans\n}\n\nexport interface IntelligenceTurnTraceSinkOptions {\n /** The Intelligence project the spans belong to, e.g. `legal-agent`. */\n project: string\n /**\n * The tenant key the ingest requires. Omit it: the sink reads the Sandbox product key from the first of\n * `SANDBOX_PRODUCTION_API_KEY`, `TCLOUD_SANDBOX_API_KEY` and `SANDBOX_API_KEY` that is set, the platform key the\n * ingest verifies. Legal's Worker `TANGLE_API_KEY` got 401 on every export (#468), so a key is never assumed: a refusal is a console warning.\n */\n apiKey?: string\n /** Default `https://intelligence.tangle.tools`; spans go to `<base>/v1/otlp/v1/traces`. */\n baseUrl?: string\n /** Called with a short reason when a delivery fails. Never receives span content. Default: a console warning. */\n onError?: (reason: string) => void\n /** Milliseconds one POST may take (default 5000). */\n timeoutMs?: number\n}\n\nconst DEFAULT_INTELLIGENCE_BASE_URL = 'https://intelligence.tangle.tools'\n/** The Sandbox product key names, in the order the apps' sandbox lanes prefer them. Read per delivery: a Worker's env is not populated at module scope. */\nconst INGEST_KEY_ENV = ['SANDBOX_PRODUCTION_API_KEY', 'TCLOUD_SANDBOX_API_KEY', 'SANDBOX_API_KEY'] as const\n\n/** The key the ingest verifies, from the host's environment: what the sink uses when it is given none, and what an app's other Intelligence client should use too. */\nexport function resolveIngestKey(): string | undefined {\n if (typeof process === 'undefined') return undefined\n for (const name of INGEST_KEY_ENV) {\n const value = process.env?.[name]?.trim()\n if (value) return value\n }\n return undefined\n}\nconst SCOPE = { name: '@tangle-network/agent-app', version: 'turn-trace' }\n\n/**\n * The sink a chat route or a Worker turn hands each finished trace to: one OTLP POST per turn, awaited, so a host that\n * runs it under `waitUntil` keeps the isolate alive until delivery. It never throws; every failure, including a missing\n * key and a non-2xx answer, goes to `onError` (a console warning by default), because a silent sink hid Legal's 401s.\n */\nexport function createIntelligenceTurnTraceSink(options: IntelligenceTurnTraceSinkOptions): TurnTraceSink {\n const url = `${(options.baseUrl ?? DEFAULT_INTELLIGENCE_BASE_URL).replace(/\\/+$/, '')}/v1/otlp/v1/traces`\n const report = options.onError ?? ((reason: string) => console.warn(`[turn-trace] export failed: ${reason}`))\n const fail = (reason: string) => { try { report(reason.slice(0, 200)) } catch { /* telemetry only */ } }\n let missingKeyReported = false\n return async (snapshot, labels) => {\n const apiKey = options.apiKey?.trim() || resolveIngestKey()\n if (!apiKey) {\n if (!missingKeyReported) fail(`no ingest key: set ${INGEST_KEY_ENV.join(', ')} or pass apiKey`)\n missingKeyReported = true\n return\n }\n try {\n const body = otlpTraceExport(\n toOtlpAttributes({ 'service.name': options.project, 'tangle.project': options.project }),\n SCOPE,\n buildTurnTraceOtelSpans(snapshot, { project: options.project, ...labels }),\n )\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(options.timeoutMs ?? 5_000),\n })\n const text = await response.text()\n if (!response.ok) return fail(`HTTP ${response.status} from the OTLP ingest`)\n // A 2xx can still refuse part of a batch (`partialSuccess.rejectedSpans`).\n const { rejectedSpans } = readOtlpPartialSuccess(text)\n if (rejectedSpans > 0) fail(`the OTLP ingest rejected ${rejectedSpans} spans`)\n } catch (error) {\n fail(error instanceof Error ? error.message : 'turn trace export failed')\n }\n }\n}\n\n/**\n * One finished turn's spans as an OTLP JSON export, read back from where its sink sent them; null when the store holds\n * no trace for that execution (not exported yet, past retention, or written by another app).\n */\nexport type TurnTraceReader = (executionId: string, options?: { signal?: AbortSignal }) => Promise<OtlpTraceExport | null>\n\n/** A span as Intelligence's `GET /v1/traces/:traceId/spans` serializes it: resource, scope and span attributes merged. */\ninterface IntelligenceSpanRow {\n id: string\n parentSpanId?: string | null\n name: string\n startUnixNano: string\n endUnixNano: string\n attributes?: Record<string, unknown> | null\n statusCode?: string | null\n}\n\n/**\n * Attributes the reader leaves out: the ones the ingest merged in from the export's resource and scope (the export\n * carries them once, outside the spans), and a failed span's error text, which quotes whatever the thrown error held\n * (an ORM error's parameters, a provider's 400 quoting the prompt). A failed span keeps its error status.\n */\nconst OMITTED_ATTRS: ReadonlySet<string> = new Set([\n 'service.name', 'tangle.project', 'otel.scope.name', 'otel.scope.version', 'otel.original_attributes', 'otel.attribute_collisions',\n 'error.message',\n])\n\n/**\n * The turn spans `createIntelligenceTurnTraceSink` exported for `executionId`, rebuilt as the OTLP export it posted.\n * Only spans under this package's scope whose root names this execution are kept: a span another exporter wrote into\n * the same trace (a box agent, the Router) can carry prompt or answer text, and this sink's spans carry metadata only.\n */\nfunction turnTraceExport(rows: IntelligenceSpanRow[], executionId: string, project: string): OtlpTraceExport | null {\n const ours = rows.filter((row) =>\n row.attributes?.['otel.scope.name'] === SCOPE.name && row.attributes?.['otel.scope.version'] === SCOPE.version)\n const spanId = (row: IntelligenceSpanRow) => row.id.slice(row.id.lastIndexOf(':') + 1)\n const kept = new Set(ours.filter((row) => row.name === 'agent_app.turn' && row.attributes?.['tangle.execution_id'] === executionId).map(spanId))\n if (kept.size === 0) return null\n // The roots' descendants, whatever order the rows come in.\n for (let size = -1; size !== kept.size;) {\n size = kept.size\n for (const row of ours) if (row.parentSpanId && kept.has(row.parentSpanId)) kept.add(spanId(row))\n }\n const traceId = otlpTraceId(turnTraceId(executionId))\n const spans = ours.filter((row) => kept.has(spanId(row))).map((row): OtlpSpan => {\n const attrs = Object.fromEntries(Object.entries(row.attributes ?? {})\n .filter(([key, value]) => !OMITTED_ATTRS.has(key) && ['string', 'number', 'boolean'].includes(typeof value))) as Record<string, string | number | boolean>\n return {\n traceId,\n spanId: spanId(row),\n ...(row.parentSpanId ? { parentSpanId: row.parentSpanId } : {}),\n name: row.name,\n kind: 1,\n startTimeUnixNano: row.startUnixNano,\n endTimeUnixNano: row.endUnixNano,\n attributes: toOtlpAttributes(attrs, row.name === 'agent_app.turn' ? { doubles: ROOT_MEASUREMENTS } : {}),\n status: { code: row.statusCode === 'ERROR' ? 2 : row.statusCode === 'OK' ? 1 : 0 },\n }\n })\n return otlpTraceExport(toOtlpAttributes({ 'service.name': project, 'tangle.project': project }), SCOPE, spans)\n}\n\n/**\n * Read a turn's trace back from Tangle Intelligence with the key its sink sends under (the same options), so a chat\n * route can show a turn's owner its own waterfall. Intelligence scopes the read to the key's tenant and redacts at\n * ingest; this keeps only the turn exporter's own spans. Throws when Intelligence refuses or cannot be reached.\n */\nexport function createIntelligenceTurnTraceReader(options: Omit<IntelligenceTurnTraceSinkOptions, 'onError'>): TurnTraceReader {\n const base = (options.baseUrl ?? DEFAULT_INTELLIGENCE_BASE_URL).replace(/\\/+$/, '')\n return async (executionId, { signal } = {}) => {\n const apiKey = options.apiKey?.trim() || resolveIngestKey()\n if (!apiKey) throw new Error(`no Intelligence key: set ${INGEST_KEY_ENV.join(', ')} or pass apiKey`)\n const rows: IntelligenceSpanRow[] = []\n let cursor: string | null = null\n // The recorder keeps at most 1000 spans a turn and Intelligence pages 5000 by default, so one page is the norm.\n for (let page = 0; page < 10; page++) {\n const query: string = cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''\n const response = await fetch(`${base}/v1/traces/${otlpTraceId(turnTraceId(executionId))}/spans${query}`, {\n headers: { authorization: `Bearer ${apiKey}` },\n signal: AbortSignal.any([AbortSignal.timeout(options.timeoutMs ?? 5_000), ...(signal ? [signal] : [])]),\n })\n if (!response.ok) throw new Error(`HTTP ${response.status} from Intelligence`)\n const body = await response.json() as { items?: IntelligenceSpanRow[]; nextCursor?: string | null }\n rows.push(...(body.items ?? []))\n cursor = body.nextCursor ?? null\n if (!cursor) break\n }\n return turnTraceExport(rows, executionId, options.project)\n }\n}\n","import type { ServerTimingEntry } from '@tangle-network/agent-core/server-timing'\n\nexport { formatServerTiming, parseServerTiming, type ServerTimingEntry } from '@tangle-network/agent-core/server-timing'\n\n/** Flat span attributes for the entries: `server_timing.<name>_ms` for a duration, `server_timing.<name>` for a `desc`. */\nexport function serverTimingAttrs(entries: readonly ServerTimingEntry[]): Record<string, string | number> {\n const out: Record<string, string | number> = {}\n for (const entry of entries.slice(0, 32)) {\n const key = entry.name.replace(/[^\\w]/g, '_')\n if (entry.dur !== undefined && entry.dur >= 0) out[`server_timing.${key}_ms`] = Math.round(entry.dur * 10) / 10\n else if (entry.desc !== undefined) out[`server_timing.${key}`] = entry.desc.slice(0, 120)\n }\n return out\n}\n","import type { TurnSpan, TurnTrace } from './recorder'\nimport { otlpTraceId } from './otel'\nimport { parseServerTiming, serverTimingAttrs } from './server-timing'\n\nconst counters = new WeakMap<TurnTrace, Map<string, number>>()\n\n/** 1-based count of `name` spans started through {@link nextCallIndex} on this trace. */\nexport function nextCallIndex(trace: TurnTrace, name: string): number {\n const byName = counters.get(trace) ?? new Map<string, number>()\n counters.set(trace, byName)\n const next = (byName.get(name) ?? 0) + 1\n byName.set(name, next)\n return next\n}\n\n/**\n * The Router's own steps before its provider fetch, as children of `router.pre_upstream` (`origin` is the Router's\n * handler start on this clock, `end` its `upstream_start`). `t_authed` and `t_admitted` are offsets from the handler\n * start: `router.auth` runs to the first, `router.admission` (budgets, credits, routing) to the second, and\n * `router.dispatch` (body, pricing, the dispatch row, the spend hold) to the provider fetch. `dispatch_row` and\n * `spend_authorize` are durations that run back to back and end just before the fetch, so they are placed backwards\n * from `end`. A step the header does not carry is left out, and nothing is placed outside `[origin, end]`.\n */\nfunction recordRouterSteps(parent: TurnSpan, origin: number, end: number, stamp: (name: string) => number | undefined): void {\n const offset = (name: string) => {\n const ms = stamp(name)\n return ms === undefined ? undefined : Math.min(end, origin + ms)\n }\n let at = origin\n for (const [step, name] of [['t_authed', 'router.auth'], ['t_admitted', 'router.admission']] as const) {\n const until = offset(step)\n if (until === undefined || until <= at) continue\n parent.record(name, 'router', at, until)\n at = until\n }\n if (end <= at) return\n const dispatch = parent.record('router.dispatch', 'router', at, end)\n let stepEnd = end\n for (const step of ['spend_authorize', 'dispatch_row']) {\n const ms = stamp(step)\n if (ms === undefined) continue\n const start = Math.max(at, stepEnd - ms)\n dispatch.record(`router.${step}`, 'router', start, stepEnd)\n stepEnd = start\n }\n}\n\nexport interface TracedModelFetchOptions {\n /** The span a model call hangs from. Default: the trace's root. */\n parent?: TurnSpan\n /** The model the request asks for. */\n model?: string\n /** Receives each model call's span as it starts, so the engine can add the token counts when usage arrives. */\n onSpan?: (span: TurnSpan) => void\n}\n\n/** FNV-1a over a string, as 8 hex: a fingerprint that tells two prompts apart without carrying their text. */\nfunction fingerprint(text: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193)\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\n/** Where a request's cacheable prefix stops matching the last one: fingerprints and lengths of its system message, its\n * tools and its first 4k and 16k characters. Metadata only; a body that is not a JSON chat request records nothing. */\nfunction prefixAttrs(body: unknown): Record<string, string | number> {\n if (typeof body !== 'string') return {}\n try {\n const request = JSON.parse(body) as { messages?: Array<{ role?: string; content?: unknown }>; tools?: unknown }\n const system = request.messages?.find(message => message.role === 'system')?.content\n const systemText = typeof system === 'string' ? system : JSON.stringify(system ?? '')\n const tools = JSON.stringify(request.tools ?? [])\n return {\n 'gen_ai.request.body_chars': body.length,\n 'gen_ai.request.system_chars': systemText.length, 'gen_ai.request.system_fnv': fingerprint(systemText),\n 'gen_ai.request.tools_chars': tools.length, 'gen_ai.request.tools_fnv': fingerprint(tools),\n 'gen_ai.request.prefix_4k_fnv': fingerprint(body.slice(0, 4096)), 'gen_ai.request.prefix_16k_fnv': fingerprint(body.slice(0, 16384)),\n }\n } catch {\n return {}\n }\n}\n\n/**\n * `fetch` for a model request, recording one `model.call` span per send: the\n * wall time from the request to the end of its body, the time to the first\n * byte, and the Router's own `Server-Timing` so the wait before the first byte\n * splits into network and server time.\n *\n * Children partition the call:\n * - `network`: the wait for headers, less the Router's server time;\n * - `router.pre_upstream`: the Router's work before its provider fetch\n * (`upstream_start`), split by its own steps (see {@link recordRouterSteps});\n * - `router.upstream_wait`: the provider's time to response headers\n * (`upstream_headers`);\n * - `model.stream`: headers to the end of the body.\n * Without a `Server-Timing` header the first byte's wait is one `model.wait`\n * span, because the split is not known.\n *\n * The response body is passed through unchanged; the span ends when the body\n * ends, errors or is cancelled.\n */\nexport function tracedModelFetch(trace: TurnTrace, inner: typeof fetch, options: TracedModelFetchOptions = {}): typeof fetch {\n return async (input, init) => {\n const sentAt = Date.now()\n const span = trace.start('model.call', 'model', {\n 'gen_ai.operation.name': 'chat',\n 'call.index': nextCallIndex(trace, 'model.call'),\n ...(options.model ? { 'gen_ai.request.model': options.model } : {}),\n ...prefixAttrs(init?.body),\n }, options.parent)\n options.onSpan?.(span)\n let response: Response\n try {\n // Fetch replaces Request headers when init.headers is supplied. Preserve\n // that precedence while parenting Router's spans to this exact send.\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))\n headers.set('traceparent', `00-${otlpTraceId(trace.traceId)}-${span.id}-01`)\n response = await inner(input, { ...init, headers })\n } catch (error) {\n span.end({ 'http.failed': true }, error)\n throw error\n }\n const headersAt = Date.now()\n const timing = parseServerTiming(response.headers.get('server-timing')?.slice(0, 4096))\n // The last entry: a fallback chain repeats a step, and the response is the last provider's.\n const stamp = (name: string) => {\n for (let i = timing.length - 1; i >= 0; i--) if (timing[i]!.name === name && timing[i]!.dur !== undefined && timing[i]!.dur! >= 0) return timing[i]!.dur\n return undefined\n }\n const preUpstreamMs = stamp('upstream_start')\n const upstreamWaitMs = stamp('upstream_headers')\n const waitMs = headersAt - sentAt\n span.set({ 'http.status_code': response.status, ttfb_ms: waitMs, ...serverTimingAttrs(timing) })\n\n let firstByteAt: number | undefined\n const finish = (endedAt: number, error?: unknown, cancelled?: boolean) => {\n const known = preUpstreamMs !== undefined || upstreamWaitMs !== undefined\n if (known) {\n const serverMs = Math.min(waitMs, (preUpstreamMs ?? 0) + (upstreamWaitMs ?? 0))\n const networkMs = waitMs - serverMs\n let at = sentAt\n span.record('network', 'network', at, at + networkMs, { 'network.ms': Math.round(networkMs) })\n at += networkMs\n if (preUpstreamMs !== undefined) {\n const end = Math.min(headersAt, at + preUpstreamMs)\n recordRouterSteps(span.record('router.pre_upstream', 'router', at, end), at, end, stamp)\n at = end\n }\n if (upstreamWaitMs !== undefined) span.record('router.upstream_wait', 'model', at, headersAt)\n span.set({ network_ms: Math.round(networkMs), router_server_ms: Math.round(serverMs) })\n } else {\n span.record('model.wait', 'model', sentAt, headersAt, { split: 'unknown' })\n }\n span.record('model.stream', 'model', headersAt, Math.max(headersAt, endedAt))\n const failure = error ?? (response.status >= 400 ? `http_${response.status}` : undefined)\n span.end({\n ...(firstByteAt !== undefined ? { ttft_ms: firstByteAt - sentAt } : {}),\n ...(cancelled ? { cancelled: true } : {}),\n }, failure)\n }\n\n if (!response.body) {\n finish(headersAt)\n return response\n }\n const reader = response.body.getReader()\n let settled = false\n const settle = (error?: unknown, cancelled?: boolean) => {\n if (settled) return\n settled = true\n finish(Date.now(), error, cancelled)\n }\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read()\n if (done) {\n settle()\n controller.close()\n return\n }\n firstByteAt ??= Date.now()\n controller.enqueue(value)\n } catch (error) {\n settle(error)\n controller.error(error)\n }\n },\n async cancel(reason) {\n settle(undefined, true)\n await reader.cancel(reason)\n },\n })\n return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers })\n }\n}\n"],"mappings":";AAoBO,SAAS,gBAAgB,OAAkB,SAChD,KAAmB,SAAyD;AAC5E,QAAM,YAAY,QAAQ,aAAa,MAAM;AAC7C,MAAI,OAAO,WAAW,QAAQ,WAAW,YAAY,SAAS,WAAW;AACzE,MAAI;AACJ,QAAM,SAAiC,CAAC,GAAG,aAAqC,CAAC,GAAG,UAAkC,CAAC;AACvH,QAAM,OAAO,CAAC,SAAiB,QAAQ,QAAQ,IAAI,KAAK;AACxD,QAAM,QAAQ,CAAC,SAAiB,GAAG,QAAQ,MAAM,IAAI,IAAI;AACzD,SAAO;AAAA,IACL;AAAA,IACA,KAAK,MAAM;AACT,YAAM,KAAK,IAAI;AACf,aAAO,IAAI,KAAK,OAAO,IAAI,KAAK,KAAK,KAAK;AAC1C,UAAI,SAAS;AACX,gBAAQ,IAAI,KAAK,QAAQ,IAAI,KAAK,KAAK,QAAQ,UAAU;AACzD,oBAAY,QAAQ;AAAA,MACtB;AACA,YAAM,OAAO,MAAM,IAAI,GAAG,KAAK,IAAI,GAAG,SAAS,KAAK,IAAI,MAAM,KAAK,IAAI,MAAM,IAAI,CAAC,GAAG,MAAM;AAC3F,aAAO;AAAA,IACT;AAAA,IACA,MAAM,MAAM,MAAM,SAAS;AACzB,YAAM,QAAQ,IAAI,GAAG,OAAO,MAAM,MAAM,MAAM,IAAI,GAAG,KAAK,IAAI,CAAC;AAC/D,WAAK,KAAK;AAAA,QAAK,WAAS;AAAE,qBAAW,IAAI,IAAI,IAAI,IAAI;AAAO,eAAK,IAAI,UAAU,KAAK,CAAC;AAAA,QAAE;AAAA,QACrF,WAAS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rE,GAAI,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;AAAA,MACzC,GAAG,OAAO;AAAA,IACZ;AAEA,QAAI,CAAC,SAAS,MAAM;AAClB,aAAO,SAAS;AAChB,aAAO;AAAA,IACT;AACA,UAAM,SAAS,SAAS,KAAK,UAAU;AACvC,QAAI,UAAU;AACd,UAAM,SAAS,CAAC,OAAiB,cAAwB;AACvD,UAAI,QAAS;AACb,gBAAU;AACV,aAAO,KAAK,IAAI,GAAG,OAAO,SAAS;AAAA,IACrC;AACA,UAAM,OAAO,IAAI,eAA2B;AAAA,MAC1C,MAAM,KAAK,YAAY;AACrB,YAAI;AACF,gBAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAC1C,cAAI,MAAM;AACR,mBAAO;AACP,uBAAW,MAAM;AACjB;AAAA,UACF;AACA,0BAAgB,KAAK,IAAI;AACzB,qBAAW,QAAQ,KAAK;AAAA,QAC1B,SAAS,OAAO;AACd,iBAAO,KAAK;AACZ,qBAAW,MAAM,KAAK;AAAA,QACxB;AAAA,MACF;AAAA,MACA,MAAM,OAAO,QAAQ;AACnB,eAAO,QAAW,IAAI;AACtB,cAAM,OAAO,OAAO,MAAM;AAAA,MAC5B;AAAA,IACF,CAAC;AACD,WAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,SAAS,QAAQ,YAAY,SAAS,YAAY,SAAS,SAAS,QAAQ,CAAC;AAAA,EACnH;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/chat-routes/sandbox-turn-usage.ts","../src/chat-routes/visible-text.ts","../src/chat-routes/draft-persistence.ts","../src/chat-routes/model-failover-stream.ts","../src/chat-routes/turn-event-stream.ts","../src/chat-routes/failure-wording.ts"],"sourcesContent":["import { asRecord, type JsonRecord } from '../stream/index'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Every usage field a turn can record, in column order. */\nexport const TURN_USAGE_KEYS = [\n 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'costUsd', 'harnessCostUsd',\n] as const\n\n/** The usage fields a turn measured; unknown ones stay absent, never zero. */\nexport function measuredUsage(usage: ChatTurnUsage | undefined): ChatTurnUsage {\n const measured: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) if (usage?.[key] !== undefined) measured[key] = usage[key]\n return measured\n}\n\n/** Add one canonical Sandbox `step-finish` receipt to a turn total. */\nexport function addStepFinishUsage(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost\n}\n","/**\n * Apply a product's final-text transform (a PII redactor, for example) to every\n * stored part a reader sees as words: the answer's text parts and the reasoning\n * parts, which also hold a Router turn's pre-tool narration. One rule for the\n * final row, the draft row and the detached-turn row.\n */\nexport function transformVisibleTextParts<T>(\n parts: readonly T[],\n transform: (text: string) => string | Promise<string>,\n): Promise<T[]> {\n return Promise.all(parts.map(async (part) => {\n const type = String((part as { type?: unknown }).type ?? '')\n return type === 'text' || type === 'reasoning'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part\n }))\n}\n","/**\n * Incremental (\"draft\") persistence of the assistant row WHILE a turn streams.\n *\n * Why this exists — the scale argument, not a convenience:\n *\n * A live turn is readable from two places. The hot path is the session\n * gateway's in-memory/Redis event buffer, which exists so a viewer survives a\n * network blip: it is keyed one sorted set per session, refreshed on every\n * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x\n * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to\n * cover \"a viewer who opens the tab later\" is a category error: it buys memory\n * proportional to the increase and still serves nothing to a viewer who\n * arrives past the new horizon.\n *\n * So the hot buffer must stay SHORT (live delivery + reconnect only), and\n * durable storage must serve history. That only works if durable storage\n * actually HAS the in-flight turn — which, before this module, it did not: the\n * assistant row was written once, after the stream drained. A viewer arriving\n * mid-turn past the hot window read an empty transcript.\n *\n * This module closes that gap: the assistant row is inserted early and patched\n * on a coalesced cadence, so the durable transcript is at most one interval\n * (default 2 s) behind the live stream and the hot buffer never has to be the\n * history tier.\n *\n * Mechanism only. It owns no vocabulary: the caller supplies the snapshot\n * function, the store, and the deterministic row id.\n *\n * Four properties the cadence guarantees:\n * - **Time-floored.** At most one write per `intervalMs`, never one per token.\n * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,\n * status pings, and lifecycle envelopes never do.\n * - **Single-flight.** A write already in flight suppresses the next trigger\n * instead of queueing; the final write is authoritative regardless of how\n * many drafts landed.\n * - **Best-effort.** A store failure is logged and swallowed — a durability\n * optimization must never kill a healthy stream (the same rule\n * `withDurableChatProjection` already states).\n */\n\nimport type { ChatMessageValues } from '../chat-store/core'\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport type { ChatTurnUsage } from './turn-routes'\nimport { measuredUsage } from './sandbox-turn-usage'\nimport { transformVisibleTextParts } from './visible-text'\n\n/** Message row shape the writer reads back when re-entering a turn. */\nexport interface DraftStoredMessage extends Pick<AssistantRowValues, keyof ChatTurnUsage> {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n}\n\n/** Values written to the assistant row — the intersection of the append and\n * patch shapes, so one snapshot serves both. */\nexport interface AssistantRowValues extends ChatMessageValues {}\n\n/** The store capability incremental persistence needs on top of\n * `appendMessage`. A store without `updateMessage` cannot patch a row, so it\n * cannot draft at all — the caller keeps today's single-write behavior. */\nexport interface AssistantDraftStore {\n listMessages(threadId: string): Promise<DraftStoredMessage[]>\n appendMessage(input: AssistantRowValues & {\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n }): Promise<unknown>\n updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** Live snapshot of the assistant body, taken from the producer's own\n * accumulators. `parts` is the DRAFT projection (`draftParts()`), never the\n * finalized one — see `draftAssistantParts`. */\nexport interface AssistantDraftSnapshot {\n content: string\n parts?: Array<Record<string, unknown>>\n usage?: ChatTurnUsage\n model?: string\n}\n\n/** Product-tunable cadence. Defaults are stated on each field; a product with\n * a chattier or heavier workload moves them without forking the writer. */\nexport interface DraftPersistenceTuning {\n /** Minimum wall-clock gap between draft writes, in ms. Default 2000.\n *\n * Justification for 2 s, from a measured tool-heavy production run (517\n * stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the\n * dirty gate turns 517 candidate writes into <= 45, while leaving the\n * durable row at most 2 s stale — an order of magnitude below the time it\n * takes a viewer to open a tab and render, so a late viewer never perceives\n * the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per\n * run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant\n * shards. Lower it and write amplification grows with no perceptible\n * freshness gain; raise it past ~5 s and a late viewer starts seeing a\n * visibly truncated answer. */\n intervalMs?: number\n /** Serialized-parts size (bytes) past which the interval backs off, so a\n * turn accumulating a megabyte-scale `parts` blob does not rewrite it every\n * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->\n * interval x 5. The final write is never throttled. */\n backoffBytes?: number\n /** Per-tool-part output cap applied to DRAFTS ONLY, in serialized UTF-8\n * bytes (including JSON escaping and the preview marker). A tool returning\n * a large blob would otherwise be rewritten in full on every draft.\n * `draftTruncated` marks a clipped preview even if the cap cannot fit its\n * text marker; below 2 bytes the draft omits the output value. The final\n * write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. This is not a bound on the whole parts array. */\n maxDraftToolOutputBytes?: number\n}\n\n/** Define the inputs required to construct an assistant draft writer */\nexport interface AssistantDraftWriterOptions extends DraftPersistenceTuning {\n store: AssistantDraftStore\n threadId: string\n /** DETERMINISTIC row id for this turn's assistant message — the whole\n * idempotency mechanism. Derived from the turn's existing identity\n * (`deriveExecutionId` in the interactive lane, the turn id in the detached\n * lane), so a re-entered turn addresses the SAME row: the writer looks the\n * id up before its first insert and patches what it finds. */\n messageId: string\n /** Read the producer's live accumulators. Returns null before the producer\n * is resolved (the assembly defers box resolution into the first pull). */\n snapshot(): AssistantDraftSnapshot | null\n /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the\n * draft's scalar content AND every draft text part — parity with the final\n * write, or incremental persistence would re-open the at-rest PII leak that\n * transform closed, just seconds earlier and on every turn. */\n transformText?(text: string): string | Promise<string>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Coalescing writer that keeps one durable assistant row in step with a\n * streaming turn. Created per turn; not reusable. */\nexport interface AssistantDraftWriter {\n /** Arm/trigger a draft write from one engine event. Synchronous by design —\n * the write itself is fire-and-forget so the stream is never blocked on\n * store latency. */\n notify(event: { type?: unknown }): void\n /** Stop drafting and settle any in-flight write. Called before the final\n * write so a late draft can never clobber the authoritative row. */\n close(): Promise<void>\n /** Write the AUTHORITATIVE completion values onto this turn's row —\n * insert-or-patch under the same deterministic id, un-throttled and\n * un-truncated. Errors propagate: the final write is the one that must not\n * fail silently. Implies {@link close}. */\n finalize(values: AssistantRowValues): Promise<void>\n /** The durable row this turn is writing, once one exists. */\n rowId(): string | undefined\n /** Retract the row for a turn that produced nothing (mirrors the final\n * write's empty-turn skip, which leaves no row at all today). Also retracts\n * a row a PREVIOUS attempt left behind, so a re-entered turn that ends\n * empty converges on \"no row\" rather than a stale partial. */\n discard(): Promise<void>\n /** Diagnostics: how many draft writes actually reached the store. */\n writeCount(): number\n}\n\n/** Event types that carry assistant content and therefore arm a draft write.\n * An allowlist on purpose: an unknown type (a product heartbeat, a bespoke\n * passthrough) must NEVER arm a write, or a silent producer would rewrite the\n * same row forever. */\nconst CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'text',\n 'reasoning',\n 'tool_call',\n 'tool_result',\n 'usage',\n 'notice',\n 'error',\n 'file',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n 'message.part.updated',\n])\n\nconst DEFAULT_INTERVAL_MS = 2000\nconst DEFAULT_BACKOFF_BYTES = 262144\nconst DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768\nconst encoder = new TextEncoder()\n\n/** True when this event should arm a draft write. */\nexport function isDraftContentEvent(event: { type?: unknown }): boolean {\n return typeof event?.type === 'string' && CONTENT_EVENT_TYPES.has(event.type)\n}\n\n/** Caps one tool part's `output` for a DRAFT write. Metadata marks every\n * clipped preview, with a text marker when it fits. Finalization restores the\n * untruncated value. */\nfunction capDraftToolOutput(part: Record<string, unknown>, maxBytes: number): Record<string, unknown> {\n if (maxBytes <= 0) return part\n if (String(part.type ?? '') !== 'tool') return part\n const state = part.state\n if (!state || typeof state !== 'object') return part\n const record = state as Record<string, unknown>\n const output = record.output\n if (output === undefined) return part\n const text = typeof output === 'string' ? output : safeStringify(output)\n // A longer string cannot fit even before escaping. Avoid serializing and\n // encoding the entire large tool body just to establish that lower bound.\n const serialized = typeof output === 'string' && text.length <= maxBytes ? safeStringify(text) : text\n if (serialized.length <= maxBytes && encoder.encode(serialized).byteLength <= maxBytes) return part\n const metadata = (record.metadata && typeof record.metadata === 'object' ? record.metadata : {}) as Record<string, unknown>\n return {\n ...part,\n state: {\n ...record,\n output: draftOutputPreview(text, maxBytes),\n metadata: { ...metadata, draftTruncated: true },\n },\n }\n}\n\n/** A preview is a string even when the retained output is structured. Bound\n * that stored string, whose JSON escaping may expand the source a second\n * time. Never cut a valid surrogate pair while finding the fitting prefix. */\nfunction draftOutputPreview(text: string, maxBytes: number): string | undefined {\n if (maxBytes < 2) return undefined\n const marker = '…[draft-truncated]'\n const suffix = serializedBytes(marker) <= maxBytes ? marker : ''\n const prefix = (end: number): string => {\n if (end > 0 && (text.codePointAt(end - 1) ?? 0) > 0xffff) end -= 1\n return text.slice(0, end)\n }\n let low = 0\n let high = Math.min(text.length, Math.floor(maxBytes))\n while (low < high) {\n const middle = Math.ceil((low + high) / 2)\n if (serializedBytes(prefix(middle) + suffix) <= maxBytes) low = middle\n else high = middle - 1\n }\n return prefix(low) + suffix\n}\n\nfunction serializedBytes(value: unknown): number {\n return encoder.encode(safeStringify(value)).byteLength\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return String(value)\n }\n}\n\n/** Build the coalescing draft writer for one turn. */\nexport function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter {\n const log = options.log ?? (() => {})\n const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS\n const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES\n const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES\n\n let dirty = false\n let closed = false\n let inFlight: Promise<void> | undefined\n let lastWriteAt = 0\n let lastBlobBytes = 0\n let rowId: string | undefined\n let writes = 0\n\n /** Interval for the NEXT write, backed off by the size of the last blob\n * written — a turn accumulating a huge parts array rewrites it less often. */\n function currentIntervalMs(): number {\n if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5\n if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5)\n return baseIntervalMs\n }\n\n async function projectValues(snapshot: AssistantDraftSnapshot): Promise<AssistantRowValues> {\n const transform = options.transformText\n const content = transform ? await transform(snapshot.content) : snapshot.content\n let parts: ChatMessagePart[] | undefined\n if (snapshot.parts) {\n const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput))\n const redacted = transform ? await transformVisibleTextParts(capped, transform) : capped\n parts = toChatMessageParts(redacted)\n }\n const usage = snapshot.usage ?? {}\n return {\n content,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(snapshot.model ? { model: snapshot.model } : {}),\n ...measuredUsage(usage),\n }\n }\n\n /** Adopt the row a PREVIOUS attempt at this turn already inserted, if any.\n * This lookup — by the deterministic id, through the store's ordinary read\n * — is the whole crash-safety mechanism: no new state, no extra column, no\n * second index. */\n async function adoptRow(): Promise<string | undefined> {\n if (rowId) return rowId\n const existing = (await options.store.listMessages(options.threadId)).find(\n (message) => message.id === options.messageId,\n )\n if (existing) rowId = existing.id\n return rowId\n }\n\n /** Insert-or-patch one set of values onto this turn's single row. */\n async function writeOnce(values: AssistantRowValues): Promise<void> {\n if (await adoptRow()) {\n await options.store.updateMessage!(rowId!, values)\n writes += 1\n return\n }\n const inserted = await options.store.appendMessage({\n id: options.messageId,\n threadId: options.threadId,\n role: 'assistant',\n ...values,\n })\n // The `?? options.messageId` tail is valid HERE and only here: this writer\n // supplied the id, so a store that returns nothing still wrote that row.\n // A caller that did not assign an id has no such fallback — which is why\n // `rowIdOf` deliberately stops at the honest read.\n rowId = rowIdOf(inserted) ?? options.messageId\n writes += 1\n }\n\n function trigger(): void {\n if (closed) return\n if (!dirty) return\n // Single-flight: a write already in flight SUPPRESSES this trigger rather\n // than queueing behind it. `dirty` stays armed, so the next event after it\n // lands writes the newer snapshot — one write is never spent on state a\n // later one supersedes.\n if (inFlight) return\n const now = Date.now()\n // The first content event writes immediately (a late viewer sees a row at\n // once); the time floor governs every write after it.\n if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return\n const snapshot = options.snapshot()\n if (!snapshot) return\n // Nothing to persist yet: an armed-but-empty snapshot (first event is a\n // tool call with no text and no parts) would insert a blank row.\n if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return\n dirty = false\n lastWriteAt = now\n inFlight = (async () => {\n try {\n const values = await projectValues(snapshot)\n lastBlobBytes = values.parts ? serializedBytes(values.parts) : 0\n await writeOnce(values)\n } catch (err) {\n // Best-effort by contract: a store outage degrades freshness for late\n // viewers, it does not fail a healthy turn.\n log('[chat-routes] incremental assistant persistence failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n } finally {\n inFlight = undefined\n // A trigger that arrived while this write was in flight left `dirty`\n // armed with a NEWER snapshot. Re-run it here or that state would sit\n // unwritten until the next content event — and if this was the last\n // event of a quiet stretch, until the final write.\n if (dirty && !closed) trigger()\n }\n })()\n }\n\n return {\n notify(event) {\n if (closed) return\n if (isDraftContentEvent(event)) dirty = true\n trigger()\n },\n async close() {\n closed = true\n if (inFlight) await inFlight\n },\n async finalize(values) {\n closed = true\n if (inFlight) await inFlight\n await writeOnce(values)\n },\n rowId: () => rowId,\n async discard() {\n closed = true\n if (inFlight) await inFlight\n if (!options.store.deleteMessage) return\n try {\n if (!(await adoptRow())) return\n await options.store.deleteMessage(rowId!)\n rowId = undefined\n } catch (err) {\n log('[chat-routes] draft assistant row discard failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n writeCount: () => writes,\n }\n}\n\n/** True when a store can support incremental persistence at all. Without\n * `updateMessage` a draft row could never be patched, so the caller keeps\n * today's exact single-write behavior. */\nexport function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean {\n return typeof store.updateMessage === 'function'\n}\n\n/** The row id an `appendMessage` actually returned, or `null` when the store\n * returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed\n * `Promise<unknown>` so a product adapter is free to resolve `void`; every\n * caller that wants to NAME the row it just wrote has to read defensively.\n *\n * Deliberately no fallback to a caller-assigned id — see `writeOnce`, which\n * adds its own. A caller that let the store mint the id has nothing to fall\n * back TO, and guessing one would report a row that may not exist. */\nexport function rowIdOf(inserted: unknown): string | null {\n const id = (inserted as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\nexport { assistantRowIdForTurn } from '../turn-trace/url'\n","/**\n * Model failover for a STREAMING turn.\n *\n * `/model-resolution`'s `runWithModelFailover` already owns the policy: walk a\n * chain, classify a resolved-or-thrown signal, re-throw a non-outage failure\n * immediately, and carry the attempt trail. This module does NOT re-implement\n * any of that — it composes it. What it adds is the one thing a whole-call\n * primitive cannot express, because a stream fails PARTWAY:\n *\n * **A turn may only fail over before its first client-visible byte.**\n *\n * Once a text delta, tool call, or ask has reached the browser (and the\n * persisted transcript), restarting on another model would duplicate the\n * answer. So each attempt is probed: open the stream, pull events into a small\n * buffer, and decide at the first meaningful event whether this model is\n * serving. Committing replays the buffer and hands the live iterator through;\n * abandoning discards the buffer (those events describe the dead model's\n * session — including its `step-finish` usage, which must never be billed) and\n * lets `runWithModelFailover` walk to the next model.\n *\n * `liveLifecycleEvents` relaxes the buffer for progress only. `start`,\n * `status`, `model-processing`, and session lifecycle carry no answer and no\n * receipt, so a product may take them the moment they arrive and show what\n * the turn is waiting on.\n * OpenCode reports whole parts, so the buffer held every event for 16 s and\n * the product could show nothing through provisioning and agent startup. Off\n * by default: with it on, an abandoned model's progress stays in the stream.\n *\n * The classification itself is `isUpstreamUnavailable` verbatim, so this path\n * inherits the measured facts from the 2026-07-25 outage — above all that an\n * outage is NOT always a thrown error: the sandbox RESOLVES a terminal `error`\n * event carrying `{ errorCode: 'provider_inference_unavailable' }`, which a\n * classifier inspecting only `catch` misses entirely. That resolved shape is\n * the whole reason the breakage went unnoticed, so it is classified here first.\n *\n * Conservative by construction:\n * - A terminal failure that is NOT an outage (400, bad schema, content filter)\n * COMMITS rather than failing over — it surfaces to the user exactly as it\n * does today. Those fail identically on every model; walking the chain would\n * only multiply latency and spend to reach the same error.\n * - A clean stream that produced nothing NEVER walks the chain. An empty answer\n * is not evidence of a dead upstream, and a silent re-roll on another model is\n * precisely the unattributable downgrade this work exists to prevent. Opt-in\n * `emptyTurnRetries` re-runs the SAME model instead, which leaves attribution\n * untouched — measured on production 2026-07-27, an empty turn is a transient\n * platform flake that a same-model re-run recovers (8 hard cases: 7/8\n * delivered on the first pass, 8/8 with one re-run, at a cost of 1 extra turn\n * in 9). Default `0`, so the behavior is unchanged unless a product asks.\n * - A responsive chain of length 1 costs no extra call or latency and remains\n * byte-identical to no failover. A silent chain of two or more models is\n * bounded by the first-answer deadline; one model keeps only its open deadline.\n */\n\nimport {\n isUpstreamUnavailable,\n ModelFailoverExhaustedError,\n readUpstreamUnavailableCode,\n readHttpStatusHint,\n runWithModelFailover,\n type ModelFailoverAttempt,\n} from '../model-resolution/failover'\nimport type { ModelPolicy } from '../policy-filters/index'\nimport { asRecord, asString } from '../stream/index'\n\n/** Terminal event types that end an attempt with a failure verdict. */\nconst TERMINAL_FAILURE_TYPES = new Set(['error', 'session.run.failed'])\n\n/**\n * Part types that carry no transcript content. They are buffered like anything\n * else — replayed verbatim when the attempt commits — but their presence alone\n * never commits a model, so an outage arriving right after a `step-start` is\n * still recoverable. `step-finish` matters most: it carries the abandoned\n * attempt's token/cost receipt, which must be discarded rather than billed.\n */\nconst NON_COMMITTING_PART_TYPES = new Set(['step-start', 'step-finish'])\n\n/**\n * True when `event` puts content in front of the user (or in the persisted\n * transcript), making a restart on another model unsafe.\n *\n * Deliberately an allow-list of KNOWN-INERT types rather than a deny-list: an\n * unrecognized event commits. Getting this wrong in the safe direction costs a\n * missed failover; getting it wrong the other way duplicates a user's answer.\n */\nexport function isCommittingSandboxEvent(event: unknown): boolean {\n const record = asRecord(event)\n if (!record) return false\n const type = asString(record.type) ?? ''\n if (!type) return false\n\n if (type === 'message.part.updated') {\n const data = asRecord(record.data)\n const part = asRecord(data?.part)\n const partType = asString(part?.type) ?? ''\n if (NON_COMMITTING_PART_TYPES.has(partType)) return false\n // A text/reasoning part with NO content yet (the platform opens the part\n // with `text: \"\"` before the first token — verbatim in the 2026-07-26\n // capture) puts nothing in front of the user; discarding it cannot\n // duplicate an answer. The first real token commits.\n if (partType === 'text' || partType === 'reasoning') {\n return [data?.delta, part?.text, part?.content]\n .some(value => typeof value === 'string' && value.length > 0)\n }\n return true\n }\n\n // Session/turn lifecycle, progress status, and warnings belong to the\n // attempt, not the transcript — discardable with an abandoned model.\n // Captured examples: a dead model\n // emits `start`, `execution.started`, `status`×3, `session.updated`×2,\n // `warning`×2 BEFORE its terminal `error` — any one of them committing\n // would pin the turn to the dead model and kill the failover.\n if (\n type === 'start' ||\n type === 'execution.started' ||\n type === 'status' ||\n type === 'model-processing' ||\n type === 'model.processing' ||\n // Public Sandbox timing metadata: a request was attempted, not answered.\n type === 'model.first_request' ||\n type === 'session.created' ||\n type === 'session.updated' ||\n type === 'session.idle' ||\n type === 'step-start' ||\n type === 'step-finish' ||\n type === 'turn' ||\n type === 'warning'\n ) {\n return false\n }\n\n // Everything else — text/tool shapes the producer folds, asks, plans,\n // `result`/`done`, and any type this shell does not recognize — commits.\n return true\n}\n\n/**\n * Condense an abandoned attempt's raw failure text into something safe to show\n * a customer in the transcript.\n *\n * Measured on the live router 2026-07-27 19:40 UTC: an edge 5xx arrives as\n * Cloudflare's full HTML error PAGE, so the verbatim reason began\n * `<!DOCTYPE html>\\n<!--[if lt IE 7]> <html class=\"no-js ie6 oldie\"…` and the\n * fallback notice pasted 200 bytes of that markup into the answer the customer\n * reads. The cause is worth stating; the markup is not.\n *\n * Only the DISPLAY string is condensed. The full text stays on\n * `modelFailover.attempts[].reason` for the operator, so nothing is lost —\n * this narrows what the customer sees, never what telemetry records.\n */\nexport function summarizeFailoverReason(reason: string): string {\n const collapsed = reason.replace(/\\s+/g, ' ').trim()\n if (!collapsed) return 'upstream unavailable'\n\n // An HTML error page carries no message worth quoting — the status is the\n // whole content. Detected on the ORIGINAL text, before collapsing, because\n // that is the form the producer hands over.\n if (/<!doctype html|<html[\\s>]/i.test(collapsed)) {\n const status = readHttpStatusHint(collapsed)\n return status ? `HTTP ${status}` : 'upstream returned an error page'\n }\n\n // Anything else is a real message. Cap it so a verbose upstream cannot push\n // the answer off the screen, and cut on a word boundary when one is near.\n const LIMIT = 160\n if (collapsed.length <= LIMIT) return collapsed\n const clipped = collapsed.slice(0, LIMIT)\n const lastSpace = clipped.lastIndexOf(' ')\n return `${(lastSpace > LIMIT - 30 ? clipped.slice(0, lastSpace) : clipped).trimEnd()}…`\n}\n\n/** A terminal failure event, classified. `outage` decides failover vs surface. */\ninterface TerminalFailure {\n outage: boolean\n reason: string\n code?: string\n}\n\n/**\n * Classify a terminal failure event. Returns `null` for any non-terminal event.\n *\n * The RESOLVED shape is checked first and deliberately: the sandbox reports an\n * upstream outage by resolving `{ success: false, errorCode:\n * 'provider_inference_unavailable' }` inside a terminal `error` event's `data`,\n * never by throwing. Both `data` and the whole record are offered to\n * `isUpstreamUnavailable` so a payload nested either way is caught.\n */\n/**\n * Progress the consumer may see before the commit point: it names no model\n * output and carries no billing receipt, so streaming it live cannot duplicate\n * an answer or bill an abandoned attempt. `warning` and every\n * `message.part.updated` (including `step-start`/`step-finish`) stay buffered.\n */\nexport function isLiveLifecycleEvent(event: unknown): boolean {\n const type = asString(asRecord(event)?.type) ?? ''\n return (\n type === 'start' ||\n type === 'execution.started' ||\n type === 'status' ||\n type === 'model-processing' ||\n type === 'model.processing' ||\n // Public Sandbox timing metadata: a request was attempted, not answered.\n type === 'model.first_request' ||\n type === 'session.created' ||\n type === 'session.updated' ||\n type === 'session.idle'\n )\n}\n\nexport function classifyTerminalFailure(event: unknown): TerminalFailure | null {\n const record = asRecord(event)\n if (!record) return null\n const type = asString(record.type) ?? ''\n if (!TERMINAL_FAILURE_TYPES.has(type)) return null\n\n const data = asRecord(record.data)\n const outage = isUpstreamUnavailable(data) || isUpstreamUnavailable(record)\n const reason =\n asString(data?.message) ??\n asString(data?.error) ??\n asString(data?.reason) ??\n asString(record.message) ??\n `sandbox stream reported ${type}`\n const code =\n readUpstreamUnavailableCode(data) ??\n asString(data?.errorCode) ??\n asString(data?.code) ??\n readUpstreamUnavailableCode(record) ??\n asString(record.errorCode) ??\n asString(record.code)\n return { outage, reason, ...(code ? { code } : {}) }\n}\n\n/** A model that served: its buffered preamble plus the still-live iterator. */\ninterface AttemptCommit {\n committed: true\n buffered: unknown[]\n /** `null` when the stream already ended during the probe. */\n iterator: AsyncIterator<unknown> | null\n /** Cancel transport work when this attempt is drained or abandoned. */\n abort: () => void\n}\n\n/**\n * A model whose upstream is down. `error`/`errorCode` are read by\n * `runWithModelFailover`'s attempt-trail describe(), so the trail names the\n * real upstream cause rather than a wrapper's own words.\n */\ninterface AttemptOutage {\n committed: false\n error: string\n errorCode?: string\n timeoutCode?: ModelAttemptTimeoutCode\n}\n\ntype AttemptOutcome = AttemptCommit | AttemptOutage\n\n/** Open the raw turn stream for one specific model. */\nexport type OpenModelStream = (args: {\n model: string\n /** 1 for the preferred model, 2 for the first fallback, and so on. */\n attempt: number\n /** Aborted when this attempt times out, is abandoned, or finishes. Forward\n * this to `streamSandboxPrompt(..., { signal })` so a blocked transport is\n * cancelled immediately rather than only receiving iterator.return(). */\n signal: AbortSignal\n}) => AsyncIterable<unknown> | Promise<AsyncIterable<unknown>>\n\n/** Fired when a model is abandoned and the next one is about to be tried. */\nexport interface ModelFallbackInfo {\n from: string\n to: string\n reason: string\n}\n\n/** Define inputs for streaming a turn across a model failover chain */\nexport interface ModelFailoverStreamOptions {\n /** Preferred model first, then fallbacks in descending preference. */\n models: readonly string[]\n open: OpenModelStream\n /**\n * Product admission policy applied to EVERY chain member before its stream\n * is opened — see `runWithModelFailover`'s `policy`. A member the policy\n * refuses is skipped (never opened, never sent the turn's data) and the walk\n * continues; an all-refused chain ends in `ModelFailoverExhaustedError`.\n */\n policy?: ModelPolicy\n /**\n * Maximum time to open/start one model's event source, including its first\n * iterator pull. Default 120 seconds, matching the sandbox provisioning\n * ceiling so cold infrastructure startup is bounded independently from\n * provider inference.\n */\n openTimeoutMs?: number\n /**\n * Hard deadline from the source's first lifecycle event to its first\n * answer-bearing event. Default 60 seconds when the chain has another model\n * to fail over to; a one-model chain has no default deadline, because ending\n * its only attempt loses an answer a slow first token was still bringing.\n * Processing/lifecycle events do not commit the attempt and do not extend\n * this deadline.\n */\n firstResponseTimeoutMs?: number\n /** Override the commit-point rule. Default {@link isCommittingSandboxEvent}. */\n isCommitting?: (event: unknown) => boolean\n /**\n * Stream {@link isLiveLifecycleEvent} progress to the consumer as it arrives\n * instead of holding it until the attempt commits. Default `false`, which\n * keeps an abandoned model's events entirely off the wire. With it on, such\n * an event is never replayed from the buffer, and one from an abandoned\n * attempt stays in the stream — it describes the sandbox, not the answer.\n */\n liveLifecycleEvents?: boolean\n onFallback?: (info: ModelFallbackInfo) => void\n /**\n * How many times to RE-RUN THE SAME MODEL when a turn completes having\n * produced no assistant text at all. Default `0` — byte-identical to no\n * retry.\n *\n * This is deliberately not a chain walk. Falling over to a different model\n * on an empty answer is the unattributable downgrade this module refuses to\n * do; re-running the SAME model changes nothing about attribution, because\n * the model that serves is the model that was asked for.\n *\n * Bounded by the same commit rule as failover: only a turn whose ONLY\n * committing event is a terminal receipt with no text is retried, so nothing\n * that reached the user can ever be produced twice.\n */\n emptyTurnRetries?: number\n /** Fired when an empty turn is discarded and the same model re-run. */\n onEmptyTurnRetry?: (info: EmptyTurnRetryInfo) => void\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** One same-model re-run of a turn that completed with no assistant text. */\nexport interface EmptyTurnRetryInfo {\n model: string\n /** 1 for the first re-run. */\n retry: number\n /** How many re-runs remain after this one. */\n remaining: number\n}\n\n/** The failover-wrapped stream plus the attribution every consumer needs. */\nexport interface ModelFailoverStreamHandle {\n events: AsyncGenerator<unknown, void, unknown>\n /** The model that actually served. `undefined` until the first pull resolves it. */\n servingModel(): string | undefined\n /** Every model tried, in order, with the reason each was abandoned. */\n attempts(): ModelFailoverAttempt[]\n /** True when the preferred model did not serve — the attributability signal. */\n usedFallback(): boolean\n}\n\n/** Default ceiling for opening/starting one source through its first event. */\nexport const DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS = 120_000\n\n/** Default ceiling for the first answer-bearing event after the source's first event. */\nexport const DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS = 60_000\n\n/** Structured timeout codes surfaced by the producer on final exhaustion. */\nexport type ModelAttemptTimeoutCode =\n | 'model_stream_open_timeout'\n | 'provider_first_response_timeout'\n\n/** Every configured model was exhausted and the final one timed out. */\nexport class ModelFailoverTimeoutError extends ModelFailoverExhaustedError {\n readonly code: ModelAttemptTimeoutCode\n readonly model: string\n readonly timeoutMs: number\n\n constructor(input: {\n attempts: ModelFailoverAttempt[]\n code: ModelAttemptTimeoutCode\n model: string\n timeoutMs: number\n }) {\n super(input.attempts)\n this.name = 'ModelFailoverTimeoutError'\n this.code = input.code\n this.model = input.model\n this.timeoutMs = input.timeoutMs\n this.message = input.code === 'model_stream_open_timeout'\n ? `Opening the model event source for ${input.model} exceeded ${input.timeoutMs}ms.`\n : `Model ${input.model} produced no first answer-bearing event within ${input.timeoutMs}ms.`\n }\n}\n\nfunction resolveTimeoutMs(value: number | undefined, fallback: number, label: string): number {\n if (value === undefined) return fallback\n if (!Number.isFinite(value) || value <= 0) {\n throw new RangeError(`${label} must be a finite number greater than 0`)\n }\n return Math.max(1, Math.trunc(value))\n}\n\nconst TIMED_OUT = Symbol('model-attempt-timed-out')\n\nfunction deadlineAfter(timeoutMs: number | null): {\n promise: Promise<typeof TIMED_OUT>\n clear: () => void\n} {\n let timer: ReturnType<typeof setTimeout> | undefined\n // No deadline: a promise that never settles, so the race is the stream alone.\n const promise = new Promise<typeof TIMED_OUT>((resolve) => {\n if (timeoutMs !== null) timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs)\n })\n return {\n promise,\n clear: () => {\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n },\n }\n}\n\n/**\n * True when `event` is a terminal receipt (`result` / `done`) carrying no\n * assistant text.\n *\n * Measured on production `sandbox.tangle.tools` (28 turns through\n * the gtm-agent profile): a turn can end `{ outcome: { type: 'completed' } }`\n * with `finalText: ''` and zero token events — the platform reports success and\n * the customer's message is blank. It is not an outage, nothing throws, and\n * `isUpstreamUnavailable` correctly declines to classify it, so before this the\n * blank answer committed and shipped.\n */\nfunction isEmptyTerminalReceipt(event: unknown): boolean {\n const record = asRecord(event)\n if (!record) return false\n const type = asString(record.type) ?? ''\n if (type !== 'result' && type !== 'done') return false\n const data = asRecord(record.data)\n const text = asString(data?.finalText) ?? asString(data?.text) ?? ''\n return text.trim().length === 0\n}\n\n/**\n * Hard ceiling on same-model re-runs. A turn that comes back blank three times\n * running is not a flake this can retry away, and each pass costs a full\n * sandbox turn — so the budget is capped rather than trusted.\n */\nexport const MAX_EMPTY_TURN_RETRIES = 3\n\n/**\n * Coerce the caller's budget to a finite, bounded, non-negative integer.\n *\n * `Math.trunc(NaN)` is `NaN` and `retry >= NaN` is false for every `retry`, so\n * a naive clamp turns a bad config value into a loop that opens sandbox streams\n * until the worker dies. `Infinity` has the same shape. Both resolve to `0` —\n * an unusable budget disables the retry rather than running unbounded.\n */\nexport function resolveEmptyTurnRetries(value: number | undefined): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return 0\n const truncated = Math.trunc(value)\n if (truncated <= 0) return 0\n return Math.min(truncated, MAX_EMPTY_TURN_RETRIES)\n}\n\n/** Abandon a dead attempt's iterator. Never allowed to mask the outage. */\nasync function closeIterator(iterator: AsyncIterator<unknown>, log?: ModelFailoverStreamOptions['log']): Promise<void> {\n try {\n await iterator.return?.()\n } catch (err) {\n log?.('[chat-routes] abandoning a failed model stream threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n}\n\n/**\n * Wrap `open` in reactive model failover, streaming from the first model in\n * `models` that reaches its commit point.\n *\n * Zero added latency on the happy path: the preferred model is opened first and,\n * the moment it emits anything meaningful, its events flow straight through.\n *\n * @throws ModelFailoverTimeoutError when the final model times out,\n * ModelFailoverExhaustedError when every model's upstream is down, and\n * re-throws a non-outage error from the FIRST model without walking the\n * chain (the latter behaviors are inherited from\n * `runWithModelFailover`).\n */\nexport function streamWithModelFailover(\n options: ModelFailoverStreamOptions,\n): ModelFailoverStreamHandle {\n const committing = options.isCommitting ?? isCommittingSandboxEvent\n const emptyTurnRetries = resolveEmptyTurnRetries(options.emptyTurnRetries)\n const openTimeoutMs = resolveTimeoutMs(\n options.openTimeoutMs,\n DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS,\n 'openTimeoutMs',\n )\n // A deadline exists to walk the chain. With one model there is nowhere to\n // walk, so the default only turned a slow first token into a lost answer:\n // a 2026-11-13 Discovery director turn ended at 60 s on its only model, and\n // on 2026-11-18 the same director's first reasoning token took 296 s on a\n // 295k-token context. The open deadline still bounds a stream that never\n // opens; a product that wants this bound for one model names it.\n const firstResponseTimeoutMs = options.firstResponseTimeoutMs === undefined && options.models.length < 2\n ? null\n : resolveTimeoutMs(\n options.firstResponseTimeoutMs,\n DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS,\n 'firstResponseTimeoutMs',\n )\n const liveLifecycle = options.liveLifecycleEvents === true\n const progress = createProgressQueue()\n let serving: string | undefined\n let trail: ModelFailoverAttempt[] = []\n let fellBack = false\n const attemptState = { index: 0 }\n let finalTimeout: {\n code: ModelAttemptTimeoutCode\n model: string\n timeoutMs: number\n } | undefined\n\n /**\n * One open-and-drain pass. `empty` marks the pass as an EMPTY TURN — the\n * only committing event was a terminal receipt with no assistant text, so\n * nothing reached the user and the pass can be discarded without any risk of\n * producing an answer twice. It still carries the outcome it would otherwise\n * have returned, so exhausting the retry budget is byte-identical to no\n * retry at all.\n */\n const { drainOnce } = createModelAttemptDrainer(attemptState, options, openTimeoutMs, firstResponseTimeoutMs, committing, liveLifecycle, progress)\n\n const probe = async (model: string): Promise<AttemptOutcome> => {\n // Only the FINAL attempted model decides the exhaustion code. Clear a\n // prior model's timeout before this model can throw a different outage.\n finalTimeout = undefined\n for (let retry = 0; ; retry += 1) {\n const pass = await drainOnce(model)\n if (!pass.empty || retry >= emptyTurnRetries) {\n if (!pass.outcome.committed && pass.outcome.timeoutCode) {\n finalTimeout = {\n code: pass.outcome.timeoutCode,\n model,\n timeoutMs: pass.outcome.timeoutCode === 'model_stream_open_timeout'\n ? openTimeoutMs\n : firstResponseTimeoutMs ?? 0,\n }\n } else {\n finalTimeout = undefined\n }\n return pass.outcome\n }\n // Discard the empty pass entirely — including its `step-finish` token\n // receipt, which must not be billed — and re-run the same model.\n const iterator = pass.outcome.committed ? pass.outcome.iterator : null\n if (pass.outcome.committed) pass.outcome.abort()\n if (iterator) void closeIterator(iterator, options.log)\n const info: EmptyTurnRetryInfo = { model, retry: retry + 1, remaining: emptyTurnRetries - retry - 1 }\n options.log?.('[chat-routes] turn completed with no assistant text; re-running the same model', {\n ...info,\n })\n options.onEmptyTurnRetry?.(info)\n }\n }\n\n const events = (async function* (): AsyncGenerator<unknown, void, unknown> {\n let handle: AttemptCommit\n // Progress arrives while the probe is still running. The queue closes only\n // after the verdict settles, so every event pushed before it is delivered\n // in order and ahead of the replayed buffer.\n const settled = runWithModelFailover<AttemptOutcome>({\n models: options.models,\n run: probe,\n ...(options.policy ? { policy: options.policy } : {}),\n // The probe has already classified the raw payload with\n // `isUpstreamUnavailable`; this reads its verdict rather than\n // re-classifying a wrapper object, so the two can never disagree.\n isUnavailableResult: (result) => result.committed === false,\n onFallback: (attempt, nextModel) => {\n const info: ModelFallbackInfo = {\n from: attempt.model,\n to: nextModel,\n reason: attempt.reason ?? 'upstream unavailable',\n }\n options.log?.('[chat-routes] model upstream unavailable; falling over', { ...info })\n options.onFallback?.(info)\n },\n }).finally(() => progress.close())\n // The verdict is read after the drain; mark the rejection handled until then.\n settled.catch(() => undefined)\n for (;;) {\n const item = await progress.pull()\n if (item === PROGRESS_CLOSED) break\n yield item\n }\n try {\n const outcome = await settled\n serving = outcome.model\n trail = outcome.attempts\n fellBack = outcome.usedFallback\n handle = outcome.value as AttemptCommit\n } catch (err) {\n // Exhaustion carries the full trail; keep it so the receipt still names\n // every model tried even though the turn produced nothing.\n const attempts = (err as { attempts?: ModelFailoverAttempt[] })?.attempts\n if (Array.isArray(attempts)) trail = attempts\n if (err instanceof ModelFailoverExhaustedError && finalTimeout) {\n throw new ModelFailoverTimeoutError({\n attempts: trail,\n ...finalTimeout,\n })\n }\n throw err\n }\n\n for (const event of handle.buffered) yield event\n\n const live = handle.iterator\n if (!live) {\n handle.abort()\n return\n }\n try {\n for (;;) {\n const next = await live.next()\n if (next.done) return\n yield next.value\n }\n } finally {\n // The consumer may abandon this generator mid-turn (client drop); close\n // the underlying stream rather than leaking it.\n handle.abort()\n await closeIterator(live, options.log)\n }\n })()\n\n return {\n events,\n servingModel: () => serving,\n attempts: () => trail,\n usedFallback: () => fellBack,\n }\n}\n\nconst PROGRESS_CLOSED: unique symbol = Symbol('progress-closed')\n\n/**\n * FIFO handoff from the probe (a plain promise chain) to the event generator.\n * `close` is idempotent and queues one sentinel behind everything pushed\n * before it, so a consumer never loses a progress event to the verdict.\n */\nfunction createProgressQueue(): {\n push(event: unknown): void\n close(): void\n pull(): Promise<unknown>\n} {\n const items: unknown[] = []\n const waiters: Array<(value: unknown) => void> = []\n let closed = false\n const deliver = (value: unknown): void => {\n const waiter = waiters.shift()\n if (waiter) waiter(value)\n else items.push(value)\n }\n return {\n push(event) {\n if (closed) return\n deliver(event)\n },\n close() {\n if (closed) return\n closed = true\n deliver(PROGRESS_CLOSED)\n },\n pull() {\n if (items.length > 0) return Promise.resolve(items.shift())\n if (closed) return Promise.resolve(PROGRESS_CLOSED)\n return new Promise((resolve) => waiters.push(resolve))\n },\n }\n}\n\nfunction createModelAttemptDrainer(\n attemptState: { index: number },\n options: ModelFailoverStreamOptions,\n openTimeoutMs: ReturnType<typeof resolveTimeoutMs>,\n firstResponseTimeoutMs: number | null,\n committing: (event: unknown) => boolean,\n liveLifecycle: boolean,\n progress: ReturnType<typeof createProgressQueue>,\n) {\n const drainOnce = async (model: string): Promise<{ outcome: AttemptOutcome; empty: boolean }> => {\n attemptState.index += 1\n const controller = new AbortController()\n const abort = (): void => {\n if (!controller.signal.aborted) controller.abort()\n }\n const opening = Promise.resolve().then(() => options.open({\n model,\n attempt: attemptState.index,\n signal: controller.signal,\n }))\n const openDeadline = deadlineAfter(openTimeoutMs)\n let opened: AsyncIterable<unknown> | typeof TIMED_OUT\n try {\n opened = await Promise.race([opening, openDeadline.promise])\n } catch (err) {\n openDeadline.clear()\n abort()\n throw err\n }\n if (opened === TIMED_OUT) {\n openDeadline.clear()\n abort()\n // A Promise cannot be forcibly cancelled. If the abandoned open settles\n // later, close its iterator immediately so it cannot leak a connection.\n void opening.then(\n (lateSource) => {\n try {\n void closeIterator(lateSource[Symbol.asyncIterator](), options.log)\n } catch (err) {\n options.log?.('[chat-routes] closing a late model stream threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n (err) => {\n options.log?.('[chat-routes] abandoned model stream open rejected after timeout', {\n error: err instanceof Error ? err.message : String(err),\n })\n },\n )\n return {\n outcome: {\n committed: false,\n error: `Opening the model event source for ${model} exceeded ${openTimeoutMs}ms`,\n errorCode: 'model_stream_open_timeout',\n timeoutCode: 'model_stream_open_timeout',\n },\n empty: false,\n }\n }\n\n const source = opened\n let iterator: AsyncIterator<unknown>\n try {\n iterator = source[Symbol.asyncIterator]()\n } catch (err) {\n openDeadline.clear()\n abort()\n throw err\n }\n const buffered: unknown[] = []\n // Starting the source includes its first pull. `streamSandboxPrompt` is an\n // async generator, so its cold-start work does not execute until `next()`;\n // counting that time as provider inference would collapse the two phases.\n let next: IteratorResult<unknown> | typeof TIMED_OUT\n try {\n next = await Promise.race([\n Promise.resolve(iterator.next()),\n openDeadline.promise,\n ])\n } catch (err) {\n openDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n openDeadline.clear()\n if (next === TIMED_OUT) {\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: `Starting the model event source for ${model} exceeded ${openTimeoutMs}ms`,\n errorCode: 'model_stream_open_timeout',\n timeoutCode: 'model_stream_open_timeout',\n },\n empty: false,\n }\n }\n if (next.done) {\n abort()\n return { outcome: { committed: true, buffered, iterator: null, abort }, empty: true }\n }\n\n // One deadline for the WHOLE provider pre-response phase. Pulling a\n // lifecycle or processing event races the same promise; liveness cannot\n // reset the clock.\n const firstResponseDeadline = deadlineAfter(firstResponseTimeoutMs)\n\n for (;;) {\n const event = next.value\n let failure: TerminalFailure | null\n let commits = false\n try {\n failure = classifyTerminalFailure(event)\n commits = !failure && committing(event)\n } catch (err) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n if (failure?.outage) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: failure.reason,\n ...(failure.code ? { errorCode: failure.code } : {}),\n },\n empty: false,\n }\n }\n\n if (liveLifecycle && !failure && !commits && isLiveLifecycleEvent(event)) {\n progress.push(event)\n } else {\n buffered.push(event)\n }\n // A terminal NON-outage failure surfaces exactly as it does today.\n if (failure) {\n firstResponseDeadline.clear()\n return { outcome: { committed: true, buffered, iterator, abort }, empty: false }\n }\n if (commits) {\n firstResponseDeadline.clear()\n return { outcome: { committed: true, buffered, iterator, abort }, empty: isEmptyTerminalReceipt(event) }\n }\n\n // A THROWN failure propagates untouched: `runWithModelFailover` classifies\n // it (outage → next model, anything else → re-thrown to the caller).\n try {\n next = await Promise.race([\n Promise.resolve(iterator.next()),\n firstResponseDeadline.promise,\n ])\n } catch (err) {\n firstResponseDeadline.clear()\n abort()\n void closeIterator(iterator, options.log)\n throw err\n }\n if (next === TIMED_OUT) {\n firstResponseDeadline.clear()\n // Do not await `return()`: an async generator blocked inside `next()`\n // may not settle its return until that pull completes. Invoking it is\n // the cancellation signal; waiting for it would recreate the hang.\n abort()\n void closeIterator(iterator, options.log)\n return {\n outcome: {\n committed: false,\n error: `Model ${model} produced no first answer-bearing event within ${firstResponseTimeoutMs}ms`,\n errorCode: 'provider_first_response_timeout',\n timeoutCode: 'provider_first_response_timeout',\n },\n empty: false,\n }\n }\n if (next.done) {\n firstResponseDeadline.clear()\n abort()\n // Clean end with nothing committing. Not an outage — but also not an\n // answer, so it is re-runnable on the same model.\n return { outcome: { committed: true, buffered, iterator: null, abort }, empty: true }\n }\n }\n }\n return { drainOnce }\n}\n","/** Stream framing, event inspection and cancellation around a chat producer. */\nimport type { ChatRouteEvent } from './turn-route-contracts'\n\n/** The original data of a failure event whose reason a producer withheld from the person. A Symbol key: JSON, and so\n * the wire and the turn buffer, drops it, while the route's own hooks read it through {@link serverFailureData}. */\nexport const WITHHELD_FAILURE: unique symbol = Symbol('withheld failure')\n\n/** A failure event's data as the server records it: the withheld original when a producer kept one, else as streamed. */\nexport function serverFailureData(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n const original = (data as { [WITHHELD_FAILURE]?: unknown } | undefined)?.[WITHHELD_FAILURE]\n return original !== null && typeof original === 'object' ? original as Record<string, unknown> : data\n}\n\n/** Best-effort human-readable cause from a terminal `error` /\n * `session.run.failed` event's `data`. */\nexport function failureReasonOf(data: Record<string, unknown> | undefined): string | undefined {\n if (!data) return undefined\n const message = data.message ?? data.error ?? data.reason\n if (typeof message === 'string' && message.length > 0) return message\n return undefined\n}\n\n/** The typed reason a terminal `error` / `session.run.failed` event's `data`\n * names, e.g. `sandbox.stream_failed` or an upstream code. */\nexport function failureCodeOf(data: Record<string, unknown> | undefined): string | undefined {\n const code = data?.code\n return typeof code === 'string' && code.length > 0 ? code : undefined\n}\n\n/** A word the user sees: a producer `text` event, or a sandbox text part delta. */\nexport function isVisibleText(event: ChatRouteEvent): boolean {\n const value = event as ChatRouteEvent & { text?: unknown }\n if (event.type === 'text') return typeof value.text === 'string' ? value.text.trim().length > 0 : true\n if (event.type !== 'message.part.updated') return false\n const part = event.data?.part as { type?: unknown } | undefined\n const delta = event.data?.delta\n return part?.type === 'text' && typeof delta === 'string' && delta.trim().length > 0\n}\n\n/** Output rendered by either lane; admission/status/usage events are not model output. */\nexport function isVisibleOutput(event: ChatRouteEvent): boolean {\n if (isVisibleText(event)) return true\n const value = event as ChatRouteEvent & { text?: unknown }\n if (event.type === 'reasoning') return typeof value.text === 'string' && value.text.trim().length > 0\n if (event.type === 'tool_call' || event.type === 'tool.call' || event.type === 'tool_result' || event.type === 'tool.result' || event.type === 'tool.event') return true\n if (event.type !== 'message.part.updated') return false\n const part = event.data?.part as { type?: unknown; text?: unknown } | undefined\n if (part?.type === 'tool') return true\n if (part?.type !== 'reasoning' && part?.type !== 'text') return false\n const text = event.data?.delta ?? part.text\n return typeof text === 'string' && text.trim().length > 0\n}\n\n// ── producer-stream wrappers (heartbeat + raw tap) ───────────────────────────\n\n/** Fire `onRawEvent` for each producer event, before the engine frames it.\n * Best-effort — a telemetry throw is logged, never propagated. */\nexport async function* tapRawEvents(\n source: AsyncIterable<ChatRouteEvent>,\n onRawEvent: (event: ChatRouteEvent) => void | Promise<void>,\n log: (message: string, meta?: Record<string, unknown>) => void,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n for await (const event of source) {\n try {\n await onRawEvent(event)\n } catch (err) {\n log('[chat-routes] onRawEvent failed', { error: err instanceof Error ? err.message : String(err) })\n }\n yield event\n }\n}\n\n/** Inject a keepalive whenever `intervalMs` elapses with no source event. The\n * silent window (elapsed + tick) resets on every real event, so a producer\n * that keeps emitting never triggers a heartbeat. Closes the source on early\n * return, matching a `for await` over it. */\nexport async function* withStreamHeartbeat(\n source: AsyncIterable<ChatRouteEvent>,\n intervalMs: number,\n makeEvent: (info: { elapsedMs: number; tick: number }) => ChatRouteEvent,\n): AsyncGenerator<ChatRouteEvent, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n let pending = iterator.next()\n let windowStart = Date.now()\n let tick = 0\n for (;;) {\n let timer: ReturnType<typeof setTimeout> | undefined\n let winner: 'event' | 'heartbeat'\n try {\n const heartbeat = new Promise<'heartbeat'>((resolve) => {\n timer = setTimeout(() => resolve('heartbeat'), intervalMs)\n })\n winner = await Promise.race([pending.then(() => 'event' as const), heartbeat])\n } finally {\n // Clear the pending timer on EVERY exit — including a `pending`\n // rejection — so a rejected source never orphans a setTimeout that\n // keeps the runtime alive for up to `intervalMs`.\n if (timer !== undefined) clearTimeout(timer)\n }\n if (winner === 'heartbeat') {\n tick += 1\n yield makeEvent({ elapsedMs: Date.now() - windowStart, tick })\n continue\n }\n const result = await pending\n if (result.done) return\n yield result.value\n pending = iterator.next()\n windowStart = Date.now()\n tick = 0\n }\n } finally {\n await iterator.return?.()\n }\n}\n\n/** Sequential concat of byte streams (marker line, then the engine body). */\nexport function concatStreams(streams: ReadableStream<Uint8Array>[]): ReadableStream<Uint8Array> {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const next = streams[index++]\n if (!next) {\n controller.close()\n return\n }\n reader = next.getReader()\n }\n const { done, value } = await reader.read()\n if (done) {\n reader = null\n continue\n }\n controller.enqueue(value)\n return\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n for (const stream of streams.slice(index)) await stream.cancel(reason)\n },\n })\n}\n\n/**\n * Stop a producer pull as soon as an opted-in caller disconnects.\n * `AsyncIterator.return()` alone cannot interrupt a pending `next()` call, so\n * race each pull with the request signal and close the source in `finally`.\n */\nexport async function* abortOnSignal<T>(\n source: AsyncIterable<T>,\n signal: AbortSignal,\n): AsyncGenerator<T, void, unknown> {\n const iterator = source[Symbol.asyncIterator]()\n try {\n for (;;) {\n const next = await nextWithAbort(iterator, signal)\n if (next.done) return\n yield next.value\n }\n } finally {\n await closeIteratorAfterAbort(iterator)\n }\n}\n\nfunction nextWithAbort<T>(\n iterator: AsyncIterator<T>,\n signal: AbortSignal,\n): Promise<IteratorResult<T>> {\n if (signal.aborted) return Promise.reject(new Error('chat turn cancelled'))\n return new Promise((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n if (settled) return\n settled = true\n cleanup()\n reject(new Error('chat turn cancelled'))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n if (signal.aborted) {\n onAbort()\n return\n }\n Promise.resolve()\n .then(() => iterator.next())\n .then(\n (result) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(result)\n },\n (error: unknown) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n\nconst ABORT_CLEANUP_TIMEOUT_MS = 50\n\nasync function closeIteratorAfterAbort<T>(iterator: AsyncIterator<T>): Promise<void> {\n let closing: PromiseLike<unknown> | undefined\n try {\n const result = iterator.return?.()\n if (result) closing = Promise.resolve(result)\n } catch {\n return\n }\n if (!closing) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.resolve(closing).catch(() => undefined),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, ABORT_CLEANUP_TIMEOUT_MS)\n }),\n ])\n } finally {\n if (timeout !== undefined) clearTimeout(timeout)\n }\n}\n","/**\n * What a person reads when a sandbox turn fails: only sentences written here. Harness, provider and Router text is read\n * only to classify the failure, by its code, its HTTP status or a recognized phrase, and the person reads that class's\n * fixed sentence. No part of the reason is shown; the only values in a sentence are times parsed and formatted here.\n * The server keeps the reason, in its log and under a Symbol key the route's own failure hooks read. `personFacing`\n * applies this to every event the sandbox producer yields.\n */\n\nimport { ModelFailoverExhaustedError } from '../model-resolution/failover'\nimport { SandboxRunError } from '../sandbox/sandbox-run-error'\nimport { asRecord, asString, type JsonRecord } from '../stream/index'\nimport { getChatFundingRecovery } from '../web/turn-funding-recovery'\nimport { ModelFailoverTimeoutError } from './model-failover-stream'\nimport { WITHHELD_FAILURE } from './turn-event-stream'\nimport { TURN_USAGE_KEYS } from './sandbox-turn-usage'\n\ntype Log = (message: string, meta?: Record<string, unknown>) => void\n\nconst utcTime = (at: Date) => `${at.toISOString().slice(11, 19)} UTC`\n\nexport const FAILED_TURN_TEXT = 'That answer stopped before it finished. Please send your question again.'\nconst SENTENCES = {\n settlement: 'The answer above is complete.',\n model_key_refused: \"The assistant's model refused its access key, so this message was not answered. \"\n + 'If the assistant has just started, send it again in a minute; if this repeats, tell the team.',\n budget_exhausted: \"This assistant's spending budget is used up. Raise its cap or wait for it to reset, then send again.\",\n balance_low: 'Insufficient credits to cover this request. Add funds, then send again.',\n model_policy: \"That model isn't available here. Choose another model and send again.\",\n grant_model_unsupported: \"This assistant's model can't run here. Ask the team to choose a supported model.\",\n grant_activation_missing: \"This assistant couldn't connect to its model. Tell the team; sending again won't help.\",\n profile_unsupported: \"This assistant's setup can't run here. Ask the team to update it.\",\n provider_retry: 'The model provider is busy, so the request is being retried.',\n}\n\n/** A harness's provider retry wait (OpenCode's raw `retry` status) as one sentence with its next attempt's time. */\nexport function providerRetryNotice(event: { type: string; data?: unknown }): string | undefined {\n const retry = event.type === 'raw' ? asRecord(asRecord(event.data)?.event) : undefined\n if (retry?.type !== 'retry' || !(Number(retry.next) > 0)) return undefined\n return `The model provider is busy; retrying at ${utcTime(new Date(Number(retry.next)))}.`\n}\n\n/** A terminal provider wait (`…, reset at <ISO>`, agent-container provider-retry-wait.ts) as one sentence with its time. */\nexport function providerResetSentence(message: string): string | undefined {\n const at = new Date(message.match(/reset at (\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z)/)?.[1] ?? NaN)\n if (Number.isNaN(at.getTime())) return undefined\n return `The model provider asked us to wait. Try again after ${utcTime(at)} on ${at.toISOString().slice(0, 10)}.`\n}\n\n/** The typed code for a harness whose model refused its key, so a product can tell it from other stream failures. */\nexport const MODEL_KEY_REFUSED_CODE = 'model.key_refused'\n\n/** A harness whose model provider refused its key (\"Invalid API key\", OpenCode's `OPENCODE_ERROR`) as plain words, true\n * both for a newly started box whose harness called the model before its minted key was in place (it recovers within\n * minutes) and for a key that is wrong. The raw error goes to the log, never to the person. */\nexport function modelKeyRefusedSentence(message: string): string | undefined {\n const lower = message.toLowerCase()\n const refused = lower.includes('invalid api key') || (/\\b401\\b/.test(message) && /unauthori[sz]ed|api key/.test(lower))\n return refused ? SENTENCES.model_key_refused : undefined\n}\n\n/** The Router's refusals of a key's budget, and of a balance too low for one request. */\nconst ROUTER_BUDGET = [\"This key's monthly budget is exhausted\", \"This key's lifetime budget is exhausted\",\n 'Monthly budget exceeded (', 'The key or product budget cannot cover']\n\n/** How a failure reads to the person: its class and that class's fixed sentence. */\nexport interface FailureView {\n class: string\n shown: string\n}\n\n/** Refusals by code, each as its fixed sentence: they fail the same way again, so none asks the person to resend. */\nconst REFUSALS = new Map<string, keyof typeof SENTENCES>([\n ['MODEL_REFUSED', 'model_policy'], ['model_policy_denied', 'model_policy'], ['budget_exceeded', 'budget_exhausted'],\n ['grant_model_unsupported', 'grant_model_unsupported'], ['grant_activation_missing', 'grant_activation_missing'],\n ['profile_unsupported', 'profile_unsupported'], [MODEL_KEY_REFUSED_CODE, 'model_key_refused'],\n])\n\n/** Classes a person reads after a lead line, so a client that recognizes the stored failure prefix still finds them. */\nconst LED_CLASSES: ReadonlySet<string> = new Set(['funding', 'balance_low', 'model_policy', 'grant_model_unsupported',\n 'grant_activation_missing', 'profile_unsupported'])\n\n/** Warnings a person may read, each as a sentence written here; any other warning is dropped. */\nconst WARNING_SENTENCES = new Map<string, string>([\n ['empty_visible_output_retry', 'The model returned no visible answer, so it is trying once more.'],\n ['OPENCODE_STEP_TRUNCATED', 'A step of this answer was cut short, so the answer may be incomplete.'],\n ['OPENCODE_PROVIDER_RETRY', SENTENCES.provider_retry],\n ['CODEX_UNEXPECTED_APPROVAL', 'The agent asked for an approval it does not need here, and it was declined.'],\n ['CODEX_UNEXPECTED_QUESTION', 'The agent asked a question it cannot ask here, and it was declined.'],\n ['EXECUTION_INTERRUPTED', 'This answer was interrupted before it finished.'],\n ['FILE_DENIED', 'The agent was refused access to a file.'],\n])\n\n/** A model failover trail: `All N model(s) failed. <model>: <reason> | <model>: <reason>`. */\nconst FAILOVER_TRAIL = /^All \\d+ model\\(s\\) failed\\. /\n\n/** A failover trail read for its last attempt only; any other reason as it is. */\nfunction lastAttempt(reason: string): string {\n if (!FAILOVER_TRAIL.test(reason)) return reason\n const attempts = reason.replace(FAILOVER_TRAIL, '')\n const last = attempts.slice(attempts.lastIndexOf(' | ') + 1).replace(/^\\| /, '')\n const colon = last.indexOf(': ')\n return colon < 0 ? last : last.slice(colon + 2)\n}\n\n/** The class of a failure and its sentence, or `undefined` for the default, withheld class. Linear in the reason. */\nfunction classify(reason: string, code: string | undefined, status: unknown): FailureView | undefined {\n const refusal = REFUSALS.get(code ?? '')\n if (refusal) return { class: refusal, shown: SENTENCES[refusal] }\n const funding = getChatFundingRecovery({ code: code === 'PAYMENT_REQUIRED' ? 'insufficient_credits' : code })\n const last = lastAttempt(reason)\n if (!funding) {\n const wait = providerResetSentence(last)\n if (wait) return { class: 'provider_wait', shown: wait }\n const kind = modelKeyRefusedSentence(last) ? 'model_key_refused'\n : ROUTER_BUDGET.some((phrase) => last.includes(phrase)) ? 'budget_exhausted'\n : last.includes('Available credits cannot cover') ? 'balance_low' : undefined\n if (kind) return { class: kind, shown: SENTENCES[kind] }\n }\n const recovery = funding ?? getChatFundingRecovery({ message: last })\n ?? (Number(status) === 402 ? getChatFundingRecovery({ code: 'insufficient_credits' }) : null)\n if (!recovery) return undefined\n // The recovery UI's own words, so a client that reads the sentence still opens billing.\n const paidAccess = recovery.reason === 'paid_access_required' ? 'Inference requires verified paid access. ' : ''\n return { class: 'funding', shown: `${recovery.title}. ${paidAccess}${recovery.message}` }\n}\n\n/** The turn, thread, session and execution ids a record carries, for the server log. */\nexport function failureIds(source: unknown): Record<string, string> {\n const record = asRecord(source)\n return Object.fromEntries(['turnId', 'threadId', 'sessionId', 'executionId']\n .flatMap((key) => typeof record?.[key] === 'string' && record[key] ? [[key, record[key] as string]] : []))\n}\n\n/** The text a failure adds to the answer: its sentence, after a lead line for the classes that carry one. */\nexport function failureText(view: FailureView, partialAnswer: string): string {\n if (!LED_CLASSES.has(view.class)) return view.shown\n const lead = partialAnswer.trim()\n ? 'The sandbox model stream stopped before a clean completion.'\n : 'The sandbox agent returned an error before producing a visible answer.'\n return `${lead}\\n\\nError: ${view.shown}`\n}\n\n/** Protocol reason values, not arbitrary identifiers or prose. */\nconst REASONS = new Set(['provider_error', 'abort'])\nconst USAGE_KEYS = new Set<string>([...TURN_USAGE_KEYS, 'cacheReadInputTokens', 'cacheCreationInputTokens', 'cost', 'totalCostUsd'])\n\n/** Failure carriers in precedence order, shared by the reason and code extractors. */\nfunction failureSources(event: unknown) {\n const record = asRecord(event)\n const data = asRecord(record?.data)\n const raw = asRecord(data?.event)\n return [data, asRecord(data?.error), asRecord(asRecord(data?.properties)?.error), record, asRecord(record?.error),\n raw, asRecord(raw?.error), asRecord(raw?.item)]\n}\n\n/** The reason stays server-side; a closed protocol reason is a class, not prose. */\nexport function failureReason(event: unknown): string {\n for (const row of failureSources(event)) {\n const reason = asString(row?.message) ?? asString(row?.error) ?? asString(row?.detail) ?? asString(row?.details)\n ?? (REASONS.has(String(row?.reason)) ? undefined : asString(row?.reason)) ?? asString(asRecord(row?.data)?.message)\n if (reason) return reason\n }\n return ''\n}\n\n/** Event types that carry a failure reason; `done` and `status` do too when their status is `failed`. */\nconst FAILURE_TYPES: ReadonlySet<string> = new Set(['error', 'warning', 'session.run.failed', 'session.error'])\n\n/** One code extractor for the wire, raw harness events and the answer text. */\nexport function failureCode(event: unknown): string | undefined {\n return failureSources(event).map((row) => asString(row?.code)).find(Boolean)\n}\n\n/** Allowed fields must also have scalar values: a known key cannot smuggle a nested reason onto the wire. */\nfunction visibleValues(data: JsonRecord): JsonRecord {\n return Object.fromEntries(Object.entries(data).filter(([key, value]) => {\n if (['turnId', 'threadId', 'sessionId', 'executionId', 'code'].includes(key)) return typeof value === 'string' && /^[\\w.:-]+$/.test(value)\n if (key === 'reason') return typeof value === 'string' && REASONS.has(value)\n if (key === 'retryable') return typeof value === 'boolean'\n if (key === 'status' && value === 'failed') return true\n return (['status', 'statusCode', 'retryAt', 'resetAt'].includes(key) || USAGE_KEYS.has(key)) && typeof value === 'number' && Number.isFinite(value)\n }))\n}\n\n/** A failure event as the person reads it: every text field reads `shown`, `details` keeps only its value keys, and the\n * original data, with its reason, rides under `WITHHELD_FAILURE`, which JSON (the wire, the turn buffer) drops. */\nfunction shownFailure(event: JsonRecord, shown: string, reason: string): JsonRecord {\n const data = asRecord(event.data) ?? {}\n const visible = { ...visibleValues(data), ...visibleValues({ code: failureCode(event) }), message: shown }\n const details = visibleValues(asRecord(data.details) ?? {})\n if (Object.keys(details).length) Object.assign(visible, { details })\n for (const key of ['usage', 'tokenUsage']) {\n const usage = Object.fromEntries(Object.entries(asRecord(data[key]) ?? {}).filter(([name, value]) =>\n USAGE_KEYS.has(name) && typeof value === 'number' && Number.isFinite(value)))\n if (Object.keys(usage).length) Object.assign(visible, { [key]: usage })\n }\n const original = typeof data.message === 'string' ? data : { ...data, message: reason }\n return { type: event.type, data: Object.assign(visible, { [WITHHELD_FAILURE]: original }) }\n}\n\n/** One turn's person-facing filter. `view` classifies a failure reason; every reason is logged once, at warn (`log`,\n * else `console.warn`), with its class and ids, and the same reason reads the same wherever it appears. `warning`\n * gives an allowed warning's sentence. `event` is every event the producer yields as it may reach the client.\n * `hasAnswer` says whether the turn already shows answer text. */\nexport function personFacing(options: { log?: Log; failedTurnText: string; hasAnswer?: () => boolean }) {\n const views = new Map<string, FailureView>()\n // The turn's first failure that reads in its own words; a withheld failed `done` or `status` reads it too.\n let named: FailureView | undefined\n const droppedWarnings = new Set<string>()\n const warn = (message: string, meta: Record<string, unknown>) => (options.log ?? console.warn)(message, meta)\n const view = (reason: string, code?: string, status?: unknown, meta: Record<string, unknown> = {}): FailureView => {\n const settled = code?.startsWith('settlement_') ?? false\n const answered = settled && options.hasAnswer?.()\n const key = [reason, code, Number(status) === 402, answered].join('\\n')\n const known = views.get(key)\n if (known) return known\n // A settlement check that fails after a charged answer leaves that answer whole: sending again would charge again.\n const seen = (answered ? { class: 'settlement', shown: SENTENCES.settlement } : undefined)\n ?? classify(reason, code, status)\n ?? { class: settled ? 'settlement' : 'runtime_failure', shown: options.failedTurnText }\n warn('[chat-routes] turn failure withheld from the person', { failureClass: seen.class, code, error: reason, ...meta })\n views.set(key, seen)\n if (seen.shown !== options.failedTurnText) named ??= seen\n return seen\n }\n /** An allowed warning's sentence, or `undefined` for any other warning, which is dropped and logged once. */\n const warning = (code: string | undefined, message: string, meta: Record<string, unknown> = {}): string | undefined => {\n const shown = WARNING_SENTENCES.get(code ?? '')\n if (shown || droppedWarnings.has(`${code}\\n${message}`)) return shown\n droppedWarnings.add(`${code}\\n${message}`)\n warn('[chat-routes] harness warning withheld from the person', { failureClass: 'harness_warning', code, error: message, ...meta })\n return undefined\n }\n /** An event as it may reach the client, or `undefined` for a dropped warning. A failure carrier always reads its class's\n * sentence, even when no reason can be found in it. */\n const event = (event: JsonRecord): JsonRecord | undefined => {\n const data = asRecord(event.data)\n const raw = event.type === 'raw' ? asRecord(data?.event) : undefined\n if (raw) {\n const part = asRecord(raw.part)\n const item = asRecord(raw.item)?.type === 'error' ? asRecord(raw.item) : undefined\n if (raw.type !== 'error' && raw.type !== 'retry' && raw.type !== 'turn.failed' && !('error' in raw) && !item) {\n return part?.type === 'tool' ? { ...event, data: { ...data, event: { ...raw, part: withoutToolList(part) } } } : event\n }\n const reason = failureReason(event)\n const shown = raw.type === 'retry' ? SENTENCES.provider_retry : view(reason, failureCode(event), raw.statusCode ?? raw.status, failureIds(data)).shown\n return { type: 'raw', data: { ...(shownFailure(event, shown, reason).data as JsonRecord),\n event: { type: raw.type === 'retry' ? 'retry' : 'error', ...visibleValues({ code: failureCode(event) }), message: shown } } }\n }\n const failed = (event.type === 'done' || event.type === 'status') && data?.status === 'failed'\n if (!failed && !FAILURE_TYPES.has(String(event.type))) return event\n const reason = failureReason(event)\n if (event.type === 'warning') {\n const shown = warning(failureCode(event), reason, failureIds(data))\n return shown ? shownFailure(event, shown, reason) : undefined\n }\n const status = data?.statusCode ?? (failed ? undefined : data?.status)\n const own = view(reason, failureCode(event), status, failureIds(data))\n // A turn's end reads the sentence its error, answer text and saved message carry, not the generic one.\n return shownFailure(event, (failed && own.shown === options.failedTurnText && named ? named : own).shown, reason)\n }\n return { view, warning, event }\n}\n\n/** A thrown sandbox stream as the operator's failure note, its code and its raw reason. */\nexport function sandboxStreamFailureDiagnostic(error: unknown): { failureNote: string; code: string; reason: string } {\n const streamMessage = (error as { streamMessage?: unknown })?.streamMessage\n const message = typeof streamMessage === 'string'\n ? streamMessage\n : error instanceof Error ? error.message : 'Sandbox stream failed'\n let failureNote = `sandbox-stream: ${message}`\n try {\n const diagnostics = asRecord((error as { diagnostics?: unknown })?.diagnostics)\n if (diagnostics) failureNote += `; ${JSON.stringify(diagnostics)}`\n } catch {\n failureNote += '; [unserializable diagnostics]'\n }\n const ownCode = asString(asRecord(error)?.code)\n const last = error instanceof ModelFailoverExhaustedError ? error.attempts.at(-1) : undefined\n const reason = last?.reason ?? message\n let code = 'sandbox.stream_failed'\n if (error instanceof SandboxRunError) {\n code = error.code\n } else if (error instanceof ModelFailoverTimeoutError) {\n code = error.code\n } else if (error instanceof ModelFailoverExhaustedError) {\n code = last?.errorCode ?? (last && error.attempts.every((attempt) => attempt.reason?.includes(' is not admitted by policy: '))\n ? 'model_policy_denied' : code)\n } else if (ownCode && (REFUSALS.has(ownCode) || getChatFundingRecovery({ code: ownCode })\n || ownCode === 'PAYMENT_REQUIRED' || ownCode.startsWith('settlement_'))) {\n code = ownCode\n }\n if (modelKeyRefusedSentence(reason) && code === 'sandbox.stream_failed') code = MODEL_KEY_REFUSED_CODE\n return { failureNote, code, reason }\n}\n\nconst UNAVAILABLE_TOOL_TEXT = \"That tool isn't available.\"\n\n/** Text without the list of every tool a harness appends to a refused or repeated tool call. */\nfunction withoutToolListTail(text: string): string {\n const at = text.indexOf('Available tools:')\n return at < 0 ? text : text.slice(0, at).trimEnd()\n}\n\n/** A tool part as the person may read it, live and stored: a failed call's `error` and `output` lose the harness's list\n * of every tool, and the harness's `invalid` repair tool, which stands in for a call to a tool the model does not have,\n * reads one sentence. Inputs, metadata and a completed call's output (a document it read) stay whole. */\nexport function withoutToolList(part: JsonRecord): JsonRecord {\n // Bare tool_result events have flat fields until recordPersistedPart normalizes them.\n const nested = asRecord(part.state)\n const state = nested ?? part\n const invalid = part.tool === 'invalid'\n const shown: JsonRecord = { ...state }\n for (const key of ['error', 'output']) {\n if (typeof shown[key] !== 'string' || (key === 'output' && !invalid && state.status !== 'error')) continue\n shown[key] = invalid ? UNAVAILABLE_TOOL_TEXT : withoutToolListTail(shown[key] as string)\n }\n if (invalid) shown.input = { ...asRecord(state.input), error: UNAVAILABLE_TOOL_TEXT }\n return nested ? { ...part, state: shown } : shown\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAIO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EAAe;AAAA,EAAgB;AAAA,EAAmB;AAAA,EAAmB;AAAA,EAAoB;AAAA,EAAW;AACtG;AAGO,SAAS,cAAc,OAAiD;AAC7E,QAAM,WAA0B,CAAC;AACjC,aAAW,OAAO,gBAAiB,KAAI,QAAQ,GAAG,MAAM,OAAW,UAAS,GAAG,IAAI,MAAM,GAAG;AAC5F,SAAO;AACT;AAGO,SAAS,mBAAmB,MAAkB,OAA4B;AAC/E,QAAM,SAAS,SAAS,KAAK,MAAM;AACnC,MAAI,QAAQ;AACV,UAAM,QAAQ,SAAS,OAAO,KAAK;AACnC,UAAM,MAAM,CAAC,SAA6B,UAAuC;AAC/E,YAAM,IAAI,OAAO,KAAK;AACtB,UAAI,CAAC,OAAO,SAAS,CAAC,EAAG,QAAO;AAChC,cAAQ,WAAW,KAAK;AAAA,IAC1B;AACA,UAAM,cAAc,IAAI,MAAM,aAAa,OAAO,KAAK;AACvD,UAAM,eAAe,IAAI,MAAM,cAAc,OAAO,MAAM;AAC1D,UAAM,kBAAkB,IAAI,MAAM,iBAAiB,OAAO,SAAS;AACnE,QAAI,OAAO;AACT,YAAM,kBAAkB,IAAI,MA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