@tangle-network/agent-app 0.63.17 → 0.63.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-profiles/d1.js +2 -2
- package/dist/agent-profiles/index.js +2 -2
- package/dist/agent-profiles/switch.d.ts +1 -1
- package/dist/agent-profiles/switch.js +1 -1
- package/dist/app-auth/index.js.map +1 -1
- package/dist/chat-routes/hybrid-producer.d.ts +1 -1
- package/dist/chat-routes/index.js +11 -11
- package/dist/chat-routes/model-failover-stream.d.ts +1 -1
- package/dist/chat-routes/turn-prefetch.d.ts +1 -1
- package/dist/{chunk-Z4RD5UF7.js → chunk-2PCNHHN2.js} +2 -2
- package/dist/{chunk-I6BZVIRH.js → chunk-3CI35I4X.js} +1 -1
- package/dist/chunk-3CI35I4X.js.map +1 -0
- package/dist/{chunk-ISP6ZH3G.js → chunk-3Q3UEWKK.js} +1 -1
- package/dist/chunk-3Q3UEWKK.js.map +1 -0
- package/dist/{chunk-VDYEVCQQ.js → chunk-5WSSH3X5.js} +2 -2
- package/dist/chunk-5WSSH3X5.js.map +1 -0
- package/dist/{chunk-NUWSPR5O.js → chunk-G3LZITCA.js} +2 -2
- package/dist/{chunk-IX6UVHXY.js → chunk-JKECSYDB.js} +2 -2
- package/dist/{chunk-6GX3UHQW.js → chunk-K3A2YAIX.js} +6 -6
- package/dist/chunk-K3A2YAIX.js.map +1 -0
- package/dist/{chunk-5GSZGTPJ.js → chunk-KA6LD4OI.js} +3 -3
- package/dist/{chunk-A3BJDXPX.js → chunk-LMIP4OVR.js} +5 -5
- package/dist/chunk-LMIP4OVR.js.map +1 -0
- package/dist/{chunk-MT6ZTQGD.js → chunk-N5RWYR5N.js} +1 -1
- package/dist/chunk-N5RWYR5N.js.map +1 -0
- package/dist/{chunk-7VTGB4DM.js → chunk-OSMMEMDH.js} +1 -1
- package/dist/chunk-OSMMEMDH.js.map +1 -0
- package/dist/{chunk-5FAKBTCK.js → chunk-OYFA7BAK.js} +1 -1
- package/dist/chunk-OYFA7BAK.js.map +1 -0
- package/dist/{chunk-7EDNPQHW.js → chunk-OZDMIYES.js} +1 -1
- package/dist/chunk-OZDMIYES.js.map +1 -0
- package/dist/{chunk-ZLX4BA27.js → chunk-QUT3T2IN.js} +1 -1
- package/dist/chunk-QUT3T2IN.js.map +1 -0
- package/dist/{chunk-PK65B6HP.js → chunk-UJYEBQMS.js} +1 -1
- package/dist/{chunk-PK65B6HP.js.map → chunk-UJYEBQMS.js.map} +1 -1
- package/dist/{chunk-5UQJ7F3P.js → chunk-UULUBF5J.js} +1 -1
- package/dist/chunk-UULUBF5J.js.map +1 -0
- package/dist/{chunk-LRYY3OX7.js → chunk-VEPII3YP.js} +4 -4
- package/dist/chunk-VEPII3YP.js.map +1 -0
- package/dist/{chunk-AVBNS64P.js → chunk-W6G2HF6M.js} +1 -1
- package/dist/chunk-W6G2HF6M.js.map +1 -0
- package/dist/{chunk-4GINUJPF.js → chunk-WRCMVBUJ.js} +1 -1
- package/dist/{chunk-4GINUJPF.js.map → chunk-WRCMVBUJ.js.map} +1 -1
- package/dist/{chunk-E3AOUTIR.js → chunk-XGFGSZS5.js} +2 -2
- package/dist/chunk-XGFGSZS5.js.map +1 -0
- package/dist/{chunk-EKXG4JSN.js → chunk-YRWUJKW5.js} +2 -2
- package/dist/chunk-YRWUJKW5.js.map +1 -0
- package/dist/journeys/artifacts.d.ts +1 -0
- package/dist/journeys/cli.js +1 -1
- package/dist/journeys/index.js +55 -18
- package/dist/journeys/index.js.map +1 -1
- package/dist/journeys/journey.d.ts +1 -0
- package/dist/journeys/score.d.ts +1 -1
- package/dist/journeys/scoreboard.d.ts +1 -2
- package/dist/journeys/send.d.ts +1 -2
- package/dist/launch-invariants/auth-lookup-cache.d.ts +1 -1
- package/dist/launch-invariants/catalog.d.ts +3 -3
- package/dist/launch-invariants/cli.js +3 -3
- package/dist/launch-invariants/index.d.ts +1 -1
- package/dist/launch-invariants/index.js +3 -3
- package/dist/launch-invariants/index.js.map +1 -1
- package/dist/launch-invariants/limit-alarms.d.ts +1 -1
- package/dist/launch-invariants/pasted-code.d.ts +1 -1
- package/dist/launch-invariants/schedule.d.ts +1 -1
- package/dist/launch-invariants/settlement.d.ts +2 -2
- package/dist/launch-invariants/sized-reads.d.ts +1 -1
- package/dist/launch-invariants/testing.js +3 -3
- package/dist/model-resolution/index.js +1 -1
- package/dist/platform/billable-turn-admission.d.ts +1 -1
- package/dist/platform/delegated-keys.d.ts +2 -2
- package/dist/platform/delegated-turn-keys.d.ts +1 -1
- package/dist/platform/index.js.map +1 -1
- package/dist/preflight/cli.js +1 -1
- package/dist/preflight/index.d.ts +1 -1
- package/dist/preflight/index.js +1 -1
- package/dist/preset-cloudflare/index.js +6 -6
- package/dist/public-consultation/index.js +9 -9
- package/dist/rollout/cli.js +1 -1
- package/dist/rollout/d1.js +1 -1
- package/dist/rollout/index.d.ts +1 -1
- package/dist/rollout/index.js +1 -1
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/router-turn.d.ts +3 -3
- package/dist/runtime/router-turn.js +2 -2
- package/dist/runtime/turn-knowledge.d.ts +1 -1
- package/dist/sandbox/index.js +5 -5
- package/dist/sandbox/model.d.ts +1 -1
- package/dist/sandbox/prewarm-claim-d1.d.ts +1 -1
- package/dist/sandbox/prewarm.d.ts +2 -2
- package/dist/sandbox/reuse-state.d.ts +1 -1
- package/dist/sandbox/terminal-connection.d.ts +4 -4
- package/dist/sandbox/warm-lease.d.ts +2 -2
- package/dist/sandbox/warm-receipts.d.ts +1 -1
- package/dist/signoff/app-defaults.d.ts +1 -1
- package/dist/signoff/cli.js +2 -2
- package/dist/signoff/index.js +2 -2
- package/dist/signoff/surface-ladder.d.ts +2 -2
- package/dist/signoff/workspace-surface.d.ts +1 -1
- package/dist/stream/index.js +2 -2
- package/dist/stream/turn-buffer.d.ts +1 -1
- package/dist/turn-health/index.js +1 -1
- package/dist/turn-health/index.js.map +1 -1
- package/dist/turn-stream/adapters.d.ts +1 -1
- package/dist/turn-stream/core.d.ts +1 -1
- package/dist/turn-stream/index.js +2 -2
- package/dist/turn-trace/index.js +1 -1
- package/dist/turn-trace/otel.d.ts +1 -1
- package/dist/workspace-export/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5FAKBTCK.js.map +0 -1
- package/dist/chunk-5UQJ7F3P.js.map +0 -1
- package/dist/chunk-6GX3UHQW.js.map +0 -1
- package/dist/chunk-7EDNPQHW.js.map +0 -1
- package/dist/chunk-7VTGB4DM.js.map +0 -1
- package/dist/chunk-A3BJDXPX.js.map +0 -1
- package/dist/chunk-AVBNS64P.js.map +0 -1
- package/dist/chunk-E3AOUTIR.js.map +0 -1
- package/dist/chunk-EKXG4JSN.js.map +0 -1
- package/dist/chunk-I6BZVIRH.js.map +0 -1
- package/dist/chunk-ISP6ZH3G.js.map +0 -1
- package/dist/chunk-LRYY3OX7.js.map +0 -1
- package/dist/chunk-MT6ZTQGD.js.map +0 -1
- package/dist/chunk-VDYEVCQQ.js.map +0 -1
- package/dist/chunk-ZLX4BA27.js.map +0 -1
- /package/dist/{chunk-Z4RD5UF7.js.map → chunk-2PCNHHN2.js.map} +0 -0
- /package/dist/{chunk-NUWSPR5O.js.map → chunk-G3LZITCA.js.map} +0 -0
- /package/dist/{chunk-IX6UVHXY.js.map → chunk-JKECSYDB.js.map} +0 -0
- /package/dist/{chunk-5GSZGTPJ.js.map → chunk-KA6LD4OI.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/loop.ts","../src/runtime/gzip-request.ts","../src/runtime/openai-stream.ts","../src/runtime/turn-knowledge.ts","../src/runtime/reply-language.ts","../src/runtime/router-turn.ts","../src/runtime/turn-continuation.ts"],"sourcesContent":["/**\n * The bounded agent tool-loop — owned by `@tangle-network/agent-runtime`.\n *\n * A model turn may emit tool calls (integration-hub actions, the app tools from\n * `../tools`, delegation). The loop streams a turn, collects the executable tool\n * calls, dispatches each, appends the results to history in OpenAI\n * function-calling shape, and re-runs so the model reads them — bounded by\n * `maxToolTurns`, a wall-clock `deadlineMs`, and a `maxCostUsd` budget.\n *\n * The history shape is the OpenAI function-calling contract: the assistant turn\n * that emitted tool calls is preserved as an `assistant` message carrying its\n * `tool_calls` array, and each result is its own `{ role: 'tool', tool_call_id,\n * content }` message keyed to the call. A strict model (Claude, and any\n * OpenAI-compatible provider that validates tool history) needs this to read its\n * own tool use back; folding results into a `user` message makes such models\n * re-issue the same call in a loop.\n *\n * The loop is substrate-owned (`runToolLoop` / `streamToolLoop`); the app\n * supplies `streamTurn` (wrapping its model endpoint) and `executeToolCall`\n * (routing to its integration + app-tool executors). The app-facing names below\n * are 1:1 aliases of the canonical symbols, kept so this package's consumers and\n * the in-package `createAgentRuntime` read against a single, stable vocabulary.\n *\n * This is the LEAF the runtime barrel and its children both import — keeping the\n * tool-loop vocabulary out of any import cycle. The barrel re-exports it.\n */\n\nexport {\n runToolLoop as runAppToolLoop,\n streamToolLoop as streamAppToolLoop,\n} from '@tangle-network/agent-runtime/tool-loop'\nexport type {\n ToolLoopCall as LoopToolCall,\n ToolLoopAssistantToolCall as LoopAssistantToolCall,\n ToolLoopMessage as LoopMessage,\n ToolLoopEvent,\n ToolLoopStopReason,\n ToolLoopResult,\n RunToolLoopOptions as AppToolLoopOptions,\n StreamToolLoopOptions as StreamAppToolLoopOptions,\n StreamToolLoopYield as StreamLoopYield,\n} from '@tangle-network/agent-runtime/tool-loop'\n\n/**\n * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.\n *\n * This is the app's own `Raw` event type for the streaming loop — the canonical\n * `streamToolLoop<Raw>` is generic over it. It widens the substrate's\n * tool-loop event with `reasoning` (DeepSeek/router `reasoning_content` /\n * `thinking` deltas, rendered as thinking sections) and `usage` (per-message\n * token accounting) — neither belongs in the substrate's loop contract, so they\n * stay here. The adapter maps each into the `streamTurn` seam; `text` and\n * `tool_call` drive the loop, `reasoning` / `usage` pass through to the UI.\n */\nexport type LoopEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n /** The model has begun a tool call: its name is known, its arguments are\n * still streaming. Emitted once per call, before its `tool_call`. Lets a\n * caller start slow work the call will need (resuming a sandbox box for\n * `sandbox_run`) while the arguments arrive. Consumers that do not care\n * ignore it: it never drives the loop. */\n | { type: 'tool_call_start'; toolCallId?: string; toolName: string }\n | {\n type: 'tool_call'\n call: import('@tangle-network/agent-runtime/tool-loop').ToolLoopCall\n }\n | { type: 'usage'; usage: { promptTokens: number; completionTokens: number; cachedPromptTokens?: number } }\n | { type: 'other'; event: unknown }\n","/**\n * `fetch` that gzips a large string request body before it leaves the app.\n *\n * A Router turn sends its whole system prompt on every model call. From a\n * Worker in another region, a 37k-token prompt (about 150 kB of JSON) spent\n * 118–672 ms uploading before the Router's first step (tangle-router\n * `body_read`), because each round trip of a new connection carries only a\n * slow-start window. Prompt JSON compresses about tenfold, so the upload fits\n * in fewer round trips. The Tangle Router decodes `Content-Encoding: gzip` on\n * /v1/chat/completions, /v1/messages and /v1/responses; another endpoint may not.\n */\nexport function gzipRequestBodies(base: typeof fetch, minBytes: number): typeof fetch {\n return async (input, init) => {\n const body = init?.body\n if (typeof body !== 'string' || body.length < minBytes / 3) return base(input, init)\n const headers = new Headers(init?.headers)\n if (headers.has('content-encoding')) return base(input, init)\n const bytes = new TextEncoder().encode(body)\n if (bytes.byteLength < minBytes) return base(input, init)\n const compressed = await new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream('gzip'))).arrayBuffer()\n headers.set('content-encoding', 'gzip')\n headers.delete('content-length')\n return base(input, { ...init, headers, body: compressed })\n }\n}\n","/**\n * OpenAI-compatible stream → `LoopEvent` adapter, for NON-sandbox copilots.\n *\n * `streamAppToolLoop` takes a `streamTurn` seam that yields `LoopEvent`s. A\n * sandboxed agent produces those from its container; a browser/edge copilot\n * instead calls a model directly. The Tangle Router, the tcloud SDK, and most\n * providers all speak the OpenAI Chat Completions streaming shape — so the ONE\n * reusable piece is assembling that stream (content deltas + FRAGMENTED\n * tool-call deltas) into `LoopEvent`s. That assembly is the boilerplate every\n * copilot would re-write (and get wrong — OpenAI streams tool-call arguments in\n * pieces across chunks).\n *\n * This does NOT implement an HTTP client beyond a minimal `fetch` + SSE reader\n * (browser/edge/Node-safe, zero deps). For richer transport use the tcloud SDK\n * or the Vercel AI SDK and pipe their stream through {@link toLoopEvents}.\n */\nimport type { LoopEvent, LoopMessage, LoopToolCall } from './loop'\nimport { normalizeModelId } from './model-catalog'\n\n/** Minimal OpenAI Chat Completions streaming chunk (structural — no `openai` dep). */\nexport interface OpenAIStreamChunk {\n /** The model that produced this chunk. The Tangle Router reports the DATED\n * upstream id here (`gpt-5-2025-08-07`) whether or not it substituted, so\n * this is a served-model source only after id folding — see\n * {@link OpenAICompatServedModel}. */\n model?: string\n choices?: Array<{\n delta?: {\n content?: string | null\n /** Reasoning deltas — DeepSeek/router use `reasoning_content`; some proxies use `thinking`. */\n reasoning_content?: string | null\n thinking?: string | null\n tool_calls?: Array<{\n index: number\n id?: string\n function?: { name?: string; arguments?: string }\n /** Provider-specific call data the next request must echo back. Gemini 3\n * sends `{ google: { thought_signature } }` here and answers HTTP 400\n * when a later request's assistant `tool_calls` entry lacks it. */\n extra_content?: unknown\n }>\n }\n finish_reason?: string | null\n }>\n /** A failure the service reports inside the stream (the Tangle Router's\n * `empty_completion`, `reasoning_budget_exhausted`, `stream_idle_timeout`, …). */\n error?: { code?: string | null; message?: string | null; type?: string | null }\n /** Token accounting (requires `stream_options.include_usage`). Cumulative for\n * the call: the Tangle Router can send it on more than one chunk. */\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n /** Prompt tokens the provider served from its prompt cache (Gemini implicit caching, OpenAI, Anthropic through the Router). */\n prompt_tokens_details?: { cached_tokens?: number | null } | null\n } | null\n}\n\ninterface PartialToolCall {\n id?: string\n name: string\n args: string\n extraContent?: unknown\n announced: boolean\n}\n\n/**\n * Map an OpenAI-compat streaming chunk iterator to `LoopEvent`s: each content\n * delta → a `text` event; tool-call deltas are accumulated by index across\n * chunks and emitted as one complete `tool_call` event when the stream finishes\n * (arguments JSON-parsed; an empty/garbled args string yields `{}` rather than\n * throwing). Works for the Tangle Router, tcloud, or any OpenAI-compat source.\n *\n * A call's `extra_content` is kept as `providerFields.extra_content`, which the\n * tool loop echoes on the call's assistant `tool_calls` entry in the next request.\n * Usage is cumulative per call and may arrive on several chunks, so it is\n * yielded once, the last value, when the stream ends.\n *\n * Each call also yields one `tool_call_start` as soon as its name arrives,\n * while its arguments are still streaming, so a caller can start work the call\n * will need. Providers send the whole name in the call's first delta.\n */\nexport async function* toLoopEvents(chunks: AsyncIterable<OpenAIStreamChunk>): AsyncIterable<LoopEvent> {\n const calls = new Map<number, PartialToolCall>()\n let usage: { promptTokens: number; completionTokens: number; cachedPromptTokens?: number } | undefined\n for await (const chunk of chunks) {\n // Usage can ride a chunk with an empty choices array — read it before the\n // choice guard. Each report is cumulative, so the last one is the call's.\n if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {\n // Cumulative like the rest, but a provider may send the details on an earlier chunk only: keep the largest.\n const reported = chunk.usage.prompt_tokens_details?.cached_tokens\n const cached = typeof reported === 'number' ? Math.max(reported, usage?.cachedPromptTokens ?? 0) : usage?.cachedPromptTokens\n usage = {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\n ...(typeof cached === 'number' ? { cachedPromptTokens: cached } : {}),\n }\n }\n const choice = chunk.choices?.[0]\n if (!choice) continue\n const content = choice.delta?.content\n if (content) yield { type: 'text', text: content }\n const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking\n if (reasoning) yield { type: 'reasoning', text: reasoning }\n for (const tc of choice.delta?.tool_calls ?? []) {\n const cur = calls.get(tc.index) ?? { name: '', args: '', announced: false }\n if (tc.id) cur.id = tc.id\n if (tc.function?.name) cur.name += tc.function.name\n if (tc.function?.arguments) cur.args += tc.function.arguments\n if (tc.extra_content !== undefined) cur.extraContent = tc.extra_content\n calls.set(tc.index, cur)\n if (!cur.announced && cur.name) {\n cur.announced = true\n yield { type: 'tool_call_start', ...(cur.id ? { toolCallId: cur.id } : {}), toolName: cur.name }\n }\n }\n }\n if (usage) yield { type: 'usage', usage }\n for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {\n if (!c.name) continue\n yield {\n type: 'tool_call',\n call: {\n toolCallId: c.id,\n toolName: c.name,\n args: safeParse(c.args),\n ...(c.extraContent !== undefined ? { providerFields: { extra_content: c.extraContent } } : {}),\n } satisfies LoopToolCall,\n }\n }\n}\n\nfunction safeParse(s: string): Record<string, unknown> {\n if (!s.trim()) return {}\n try {\n const v = JSON.parse(s)\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Which model actually served one direct-router turn.\n *\n * The router substitutes models on purpose — a quota-walled primary comes back\n * `200` answered by a different model — and says so in response headers. This\n * lane used to drop the whole `Response` after taking `.body`, so a turn\n * requested as `claude-sonnet-4-6` and answered by `openai/gpt-5` was recorded\n * by its caller as Claude: per-model quality scoring blamed the wrong model and\n * cost used the wrong price basis.\n *\n * Map this onto the shell's existing attribution contract rather than inventing\n * a second channel — `ChatTurnRouteProducer.modelAttribution()` (`/chat-routes`):\n *\n * modelAttribution: () => ({ requestedModel, servedModel, echoReceived: true })\n *\n * Leave that contract's `servedSource` unset: its union is sandbox\n * profile-resolution vocabulary with no router analogue.\n */\nexport interface OpenAICompatServedModel {\n /** The model id this turn asked for (`OpenAICompatStreamTurnOptions.model`). */\n requestedModel: string\n /** The model the router/provider reports having actually served. */\n servedModel: string\n /** Where `servedModel` was read from. The header is the router's own\n * substitution signal; the body is the backstop that survives CORS. */\n source: 'router_header' | 'response_body'\n /** True when served differs from requested after id folding. Folded, not\n * compared raw: the body reports a dated id on EVERY turn, so `!==` would\n * claim a substitution every time. */\n substituted: boolean\n /** `x-tangle-failover` `trigger=` — why the router swapped. Absent when the\n * router did not inject the substitute (a caller-supplied fallback chain\n * sets the served-model header without the failover one). */\n trigger?: string\n /** `x-tangle-failover` `degraded=`. */\n degraded?: boolean\n}\n\n/** Parse `from=…; to=…; trigger=…; degraded=…` down to the fields we report.\n * Absent/garbled segments are simply omitted — attribution is best-effort and\n * must never fail a turn that is otherwise streaming fine. */\nfunction parseFailoverHeader(raw: string | null): { trigger?: string; degraded?: boolean } {\n if (!raw) return {}\n const fields = new Map<string, string>()\n for (const segment of raw.split(';')) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n fields.set(segment.slice(0, eq).trim().toLowerCase(), segment.slice(eq + 1).trim())\n }\n const trigger = fields.get('trigger')\n const degraded = fields.get('degraded')\n return {\n ...(trigger ? { trigger } : {}),\n ...(degraded != null ? { degraded: degraded === 'true' } : {}),\n }\n}\n\n/** Define options for configuring an OpenAI-compatible streaming chat turn including API details and tools */\nexport interface OpenAICompatStreamTurnOptions {\n /** OpenAI-compat base URL (e.g. the Tangle Router `https://router.tangle.tools/v1`). */\n baseUrl: string\n apiKey: string\n model: string\n /** OpenAI tool definitions — pass `buildAppToolOpenAITools(taxonomy)` so the\n * model can call the app tools. Omit for a tool-free copilot. */\n tools?: unknown[]\n temperature?: number\n fetchImpl?: typeof fetch\n /** Extra body fields (e.g. `max_tokens`). */\n extraBody?: Record<string, unknown>\n /** Extra request headers, e.g. a trace id the router records with the generation. */\n headers?: Record<string, string>\n /**\n * Called at most ONCE per turn, as soon as the serving model is\n * determinable, with what actually answered. Never called when neither the\n * header nor the body names a model — silence means \"learned nothing\", not\n * \"nothing was substituted\".\n *\n * `streamTurn` runs once per TOOL turn, so a multi-turn `runAppToolLoop`\n * fires this once per turn; take the last for row attribution.\n */\n onServedModel?: (served: OpenAICompatServedModel) => void\n}\n\n/**\n * Build a `streamTurn` that calls an OpenAI-compatible `/chat/completions`\n * endpoint (Tangle Router / tcloud / any compat provider) with `stream: true`\n * and yields `LoopEvent`s via {@link toLoopEvents}. Browser/edge/Node-safe —\n * just `fetch` + an SSE reader. Drop straight into `streamAppToolLoop`:\n *\n * const cfg = resolveTangleModelConfig() // or { baseUrl, apiKey, model }\n * streamAppToolLoop({ streamTurn: createOpenAICompatStreamTurn({ ...cfg, tools }), executeToolCall, ... })\n */\nexport function createOpenAICompatStreamTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n return (messages) =>\n toLoopEvents(\n streamChatCompletions(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\n stream: true,\n stream_options: { include_usage: true },\n ...(opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...opts.extraBody,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined, opts.headers),\n )\n}\n\n/**\n * The buffered sibling of {@link createOpenAICompatStreamTurn}: one\n * `/chat/completions` request without `stream`, answered by one JSON\n * completion, yielded as the same `LoopEvent`s (the same tool-call assembly and\n * served-model attribution). For an endpoint or ledger that expects one buffered\n * completion per model call.\n */\nexport function createOpenAICompatCompletionTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n return (messages) =>\n toLoopEvents(\n completionAsChunk(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\n ...(opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...opts.extraBody,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined, opts.headers),\n )\n}\n\n/** One buffered OpenAI-compat completion (structural — no `openai` dep). */\ninterface OpenAICompletion {\n model?: string\n choices?: Array<{\n message?: {\n content?: string | null\n reasoning_content?: string | null\n tool_calls?: Array<{ id?: string; function?: { name?: string; arguments?: string }; extra_content?: unknown }>\n }\n finish_reason?: string | null\n }>\n usage?: OpenAIStreamChunk['usage']\n}\n\nasync function* completionAsChunk(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n headers?: Record<string, string>,\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await doFetch(url, {\n method: 'POST',\n headers: { ...headers, Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) throw await httpFailure(res, 'completion')\n const completion = await res.json() as OpenAICompletion\n if (attribution) {\n const served = servedFromHeader(res, attribution.requestedModel)\n ?? (completion.model ? servedFromBody(completion.model, attribution.requestedModel) : undefined)\n if (served) attribution.report(served)\n }\n const choice = completion.choices?.[0]\n const message = choice?.message\n // The whole completion as one chunk, so `toLoopEvents` assembles it exactly as a stream.\n yield {\n ...(completion.model ? { model: completion.model } : {}),\n choices: [{\n delta: {\n content: message?.content ?? null,\n reasoning_content: message?.reasoning_content ?? null,\n tool_calls: (message?.tool_calls ?? []).map((call, index) => ({\n index,\n ...(call.id ? { id: call.id } : {}),\n function: { name: call.function?.name ?? '', arguments: call.function?.arguments ?? '' },\n ...(call.extra_content !== undefined ? { extra_content: call.extra_content } : {}),\n })),\n },\n finish_reason: choice?.finish_reason ?? null,\n }],\n ...(completion.usage ? { usage: completion.usage } : {}),\n }\n}\n\nasync function httpFailure(res: Response, kind: 'stream' | 'completion' | 'responses'): Promise<Error> {\n const text = res.body ? await res.text().catch(() => '') : ''\n const error = new Error(`OpenAI-compat ${kind} failed (HTTP ${res.status})${text ? `: ${text.slice(0, 1000)}` : ''}`)\n // Stamp the NUMERIC status. `isUpstreamUnavailable` (`/model-resolution`)\n // reads a numeric field first and prose only as a backstop, and a\n // Cloudflare EDGE 502 gives it nothing else to read: `content-type:\n // text/plain`, a body of `error code: 502`, and none of the router's own\n // `x-tangle-*` headers, because the origin never ran. Carrying the status\n // as data keeps THIS path — the browser/edge copilot lane, which calls the\n // router directly — out of the string-matching business entirely.\n Object.assign(error, { status: res.status })\n return error\n}\n\nfunction servedFromHeader(res: Response, requestedModel: string): OpenAICompatServedModel | undefined {\n const servedHeader = res.headers.get('x-tangle-served-model')\n if (!servedHeader) return undefined\n return {\n requestedModel,\n servedModel: servedHeader,\n source: 'router_header',\n substituted: normalizeModelId(servedHeader) !== normalizeModelId(requestedModel),\n ...parseFailoverHeader(res.headers.get('x-tangle-failover')),\n }\n}\n\nfunction servedFromBody(model: string, requestedModel: string): OpenAICompatServedModel {\n return {\n requestedModel,\n servedModel: model,\n source: 'response_body',\n substituted: normalizeModelId(model) !== normalizeModelId(requestedModel),\n }\n}\n\n/** Stream + parse an OpenAI-compat SSE response into chunks. Tolerates `data:`\n * framing, multi-line buffers, and the terminal `[DONE]`. */\nasync function* streamChatCompletions(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n headers?: Record<string, string>,\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await postOpenAIEventStream(doFetch, url, apiKey, body, headers)\n if (!res.ok || !res.body) throw await httpFailure(res, 'stream')\n // Served-model attribution, fired at most once, as early as it is knowable.\n //\n // The header comes first because it is the router's OWN substitution signal:\n // `X-Tangle-Served-Model` is set only when the served model differs from the\n // requested one, so its presence is authoritative and it arrives before the\n // first byte of content. `X-Tangle-Failover` rides along only when the router\n // itself picked the substitute (a caller-supplied fallback chain sets the\n // former without the latter), which is why `trigger`/`degraded` are optional.\n //\n // The body is the backstop for when the header cannot reach us. In a BROWSER,\n // headers are invisible to JS unless the server lists them in\n // `Access-Control-Expose-Headers` — tangle-router#324 added both, but that\n // only helps once it is DEPLOYED, and any other OpenAI-compat endpoint\n // pointed at this client exposes nothing. The chunk `model` field is not\n // subject to CORS, so it keeps the browser lane attributable regardless.\n let reported = false\n const report = (served: OpenAICompatServedModel): void => {\n if (reported || !attribution) return\n reported = true\n attribution.report(served)\n }\n if (attribution) {\n const served = servedFromHeader(res, attribution.requestedModel)\n if (served) report(served)\n }\n for await (const data of readOpenAISseFrames(res.body)) {\n let chunk: OpenAIStreamChunk\n try {\n chunk = JSON.parse(data) as OpenAIStreamChunk\n } catch {\n continue /* skip a partial/garbled SSE frame */\n }\n // Body fallback: only when the header said nothing. Fold both ids before\n // comparing — the router reports the dated upstream id (`gpt-5-2025-08-07`)\n // for a request of `openai/gpt-5` even with NO substitution, so a raw\n // `!==` would report a swap on literally every turn.\n if (attribution && !reported && chunk.model) report(servedFromBody(chunk.model, attribution.requestedModel))\n // A failure inside a 200 stream ends the call by name instead of reading as a blank answer.\n if (chunk.error) throw streamFailure(chunk.error)\n yield chunk\n\n }\n}\n\n/** The error a stream's own error frame becomes: its `code` and message, for the caller's failure categories. */\nfunction streamFailure(failure: NonNullable<OpenAIStreamChunk['error']>): Error {\n const code = failure.code || failure.type || 'stream_error'\n return Object.assign(new Error(`OpenAI-compat stream failed: ${code}${failure.message ? `: ${failure.message.slice(0, 1000)}` : ''}`), { code, streamFailure: true })\n}\n\n/** OpenAI models answer reasoning summaries only on the Responses API; chat completions carry none. */\nexport function isOpenAIResponsesModel(model: string): boolean {\n return /^(?:openai\\/)?(?:gpt-|o\\d|chatgpt-)/i.test(model.trim())\n}\n\n/** The chat-completions history the tool loop keeps, as Responses `instructions` and `input` items. */\nexport function toResponsesInput(messages: LoopMessage[]): { instructions?: string; input: Array<Record<string, unknown>> } {\n const instructions: string[] = []\n const input: Array<Record<string, unknown>> = []\n for (const message of messages) {\n const content = typeof message.content === 'string' ? message.content : ''\n if (message.role === 'system') {\n if (content) instructions.push(content)\n } else if (message.role === 'tool') {\n input.push({ type: 'function_call_output', call_id: message.tool_call_id ?? '', output: content })\n } else if (message.role === 'assistant' && message.tool_calls?.length) {\n if (content.trim()) input.push({ role: 'assistant', content })\n for (const call of message.tool_calls) {\n input.push({ type: 'function_call', call_id: call.id, name: call.function.name, arguments: call.function.arguments })\n }\n } else if (message.role === 'user' || message.role === 'assistant') {\n input.push({ role: message.role, content })\n }\n }\n return { ...(instructions.length ? { instructions: instructions.join('\\n\\n') } : {}), input }\n}\n\n/** Chat-completions tool definitions as Responses function tools. */\nfunction toResponsesTools(tools: unknown[] | undefined): Array<Record<string, unknown>> {\n return (tools ?? []).flatMap((tool) => {\n const fn = (tool as { function?: { name?: string; description?: string; parameters?: unknown } }).function\n return fn?.name ? [{ type: 'function', name: fn.name, ...(fn.description ? { description: fn.description } : {}),\n parameters: fn.parameters ?? { type: 'object', properties: {} } }] : []\n })\n}\n\n/**\n * Build a `streamTurn` on the OpenAI Responses API (`POST /responses`, streamed),\n * for OpenAI models whose reasoning reaches a caller only there, as\n * `response.reasoning_summary_text.delta` events. Each Responses event is\n * mapped onto the chat-completions chunk shape {@link toLoopEvents} reads, so\n * text, reasoning, fragmented function calls, usage and served-model\n * attribution behave exactly as on {@link createOpenAICompatStreamTurn}.\n *\n * `extraBody` keys from the chat path are translated: `max_tokens` and\n * `max_completion_tokens` become `max_output_tokens`, and `reasoning_effort`\n * becomes `reasoning.effort` with `summary: 'auto'`. Stateless: earlier tool\n * calls are replayed as `function_call` / `function_call_output` items.\n */\nexport function createOpenAIResponsesTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n const { max_tokens: maxTokens, max_completion_tokens: maxCompletion, reasoning_effort: effort, ...rest } = opts.extraBody ?? {}\n const maxOutput = maxCompletion ?? maxTokens\n return (messages) => {\n const { instructions, input } = toResponsesInput(messages)\n const tools = toResponsesTools(opts.tools)\n return toLoopEvents(streamResponses(doFetch, `${base}/responses`, opts.apiKey, {\n model: opts.model,\n ...(instructions ? { instructions } : {}),\n input,\n stream: true,\n store: false,\n ...(tools.length ? { tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...(maxOutput !== undefined ? { max_output_tokens: maxOutput } : {}),\n ...(effort !== undefined ? { reasoning: { effort, summary: 'auto' } } : {}),\n ...rest,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined, opts.headers))\n }\n}\n\ninterface ResponsesEvent {\n type?: string\n delta?: string\n output_index?: number\n summary_index?: number\n item?: { type?: string; call_id?: string; name?: string; arguments?: string }\n response?: { model?: string; usage?: { input_tokens?: number; output_tokens?: number; input_tokens_details?: { cached_tokens?: number | null } | null }; error?: { code?: string; message?: string } }\n error?: { code?: string; message?: string }\n message?: string\n}\n\n/** Stream a Responses API call as chat-completions chunks. A failed or errored response throws. */\nasync function* streamResponses(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n headers?: Record<string, string>,\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await postOpenAIEventStream(doFetch, url, apiKey, body, headers)\n if (!res.ok || !res.body) throw await httpFailure(res, 'responses')\n let reported = false\n const report = (served: OpenAICompatServedModel) => {\n if (reported || !attribution) return\n reported = true\n attribution.report(served)\n }\n if (attribution) {\n const served = servedFromHeader(res, attribution.requestedModel)\n if (served) report(served)\n }\n let lastSummary: string | null = null\n for await (const data of readOpenAISseFrames(res.body)) {\n let event: ResponsesEvent\n try {\n event = JSON.parse(data) as ResponsesEvent\n } catch {\n continue\n }\n switch (event.type) {\n case 'response.output_text.delta':\n if (event.delta) yield { choices: [{ delta: { content: event.delta } }] }\n break\n case 'response.reasoning_summary_text.delta': {\n if (!event.delta) break\n // Separate summary parts the way the model wrote them.\n const part = `${event.output_index ?? 0}:${event.summary_index ?? 0}`\n const lead = lastSummary !== null && lastSummary !== part ? '\\n\\n' : ''\n lastSummary = part\n yield { choices: [{ delta: { reasoning_content: lead + event.delta } }] }\n break\n }\n case 'response.output_item.added':\n if (event.item?.type === 'function_call' && event.item.name) {\n yield { choices: [{ delta: { tool_calls: [{ index: event.output_index ?? 0,\n ...(event.item.call_id ? { id: event.item.call_id } : {}),\n function: { name: event.item.name, arguments: event.item.arguments ?? '' } }] } }] }\n }\n break\n case 'response.function_call_arguments.delta':\n if (event.delta) yield { choices: [{ delta: { tool_calls: [{ index: event.output_index ?? 0, function: { arguments: event.delta } }] } }] }\n break\n case 'response.completed':\n case 'response.incomplete': {\n const model = event.response?.model\n if (attribution && !reported && model) report(servedFromBody(model, attribution.requestedModel))\n const usage = event.response?.usage\n yield { ...(model ? { model } : {}), choices: [],\n ...(usage ? { usage: { prompt_tokens: usage.input_tokens ?? 0, completion_tokens: usage.output_tokens ?? 0,\n ...(usage.input_tokens_details ? { prompt_tokens_details: usage.input_tokens_details } : {}) } } : {}) }\n return\n }\n case 'response.failed':\n case 'error': {\n const failure = event.response?.error ?? event.error ?? { message: event.message }\n throw new Error(`OpenAI-compat responses failed: ${(failure?.code ? `${failure.code}: ` : '') + (failure?.message ?? 'no detail')}`.slice(0, 300))\n }\n default:\n break\n }\n\n }\n}\n\n\n/** The common framing used by both OpenAI SSE protocols; payload parsing stays with each protocol. */\nasync function* readOpenAISseFrames(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trim()\n if (data === '[DONE]') return\n yield data\n }\n }\n}\n\n\nfunction postOpenAIEventStream(doFetch: typeof fetch, url: string, apiKey: string, body: Record<string, unknown>, headers?: Record<string, string>): Promise<Response> {\n return doFetch(url, {\n method: 'POST',\n headers: { ...headers, Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'text/event-stream' },\n body: JSON.stringify(body),\n })\n}\n","/**\n * Knowledge in every turn: the index of an app's knowledge files, the full\n * text of the small ones, and the rule that keeps answers on them.\n *\n * Measured on Hospitality production (2026-10-11): a Router turn that had to\n * discover files through list/read tools answered 17/17 correctly but needed\n * 3 tool calls (first words 12-17 s), and a turn that skipped the tools\n * answered from model defaults (\"checkout 11:00\" when the file said 12 pm).\n * Putting the text in the prompt removes both failure modes.\n */\n/** The fields read from an agent-runtime workspace-store entry; structural so older runtimes still type-check. */\ninterface KnowledgeEntry { path: string; kind: string; content?: string; bytes?: { size: number } }\n\n/** One knowledge file a turn carries; `text` is null when it is too large or not readable here. */\nexport interface TurnKnowledgeFile {\n path: string\n size: number\n text: string | null\n}\n\nexport interface TurnKnowledgeBudget {\n /** Files at most this many bytes have their text included. Default 8 000. */\n fileBytes?: number\n /** Total text bytes across files. Default 16 000. */\n textBytes?: number\n /** Most files listed. Default 60. */\n maxFiles?: number\n}\n\nconst DEFAULT_FILE_BYTES = 8_000\nconst DEFAULT_TEXT_BYTES = 16_000\nconst DEFAULT_MAX_FILES = 60\n\n/** Apply the byte budget in path order: small files keep their text until the total is spent. */\nexport function budgetTurnKnowledge(files: readonly TurnKnowledgeFile[], budget: TurnKnowledgeBudget = {}): TurnKnowledgeFile[] {\n const fileBytes = budget.fileBytes ?? DEFAULT_FILE_BYTES\n let remaining = budget.textBytes ?? DEFAULT_TEXT_BYTES\n return [...files].sort((a, b) => a.path.localeCompare(b.path)).slice(0, budget.maxFiles ?? DEFAULT_MAX_FILES)\n .map(file => {\n const fits = file.text !== null && file.size <= fileBytes && file.size <= remaining\n if (fits) remaining -= file.size\n return { path: file.path, size: file.size, text: fits ? file.text : null }\n })\n}\n\n/**\n * The prompt lines for a turn's knowledge. `readTool` names the tool that\n * opens a listed file whose text is not shown; without one, such a file is\n * listed by name only.\n */\nexport function turnKnowledgeInstructions(files: readonly TurnKnowledgeFile[], options: { readTool?: string } = {}): string[] {\n const read = options.readTool\n return [\n 'Answer questions about this business or its work (hours, times, policies, codes, passwords, prices, contacts, amenities, procedures) only from the knowledge in these instructions, the knowledge files below, or a tool result. Never give a typical or assumed value, and do not say something is absent unless a source says so.' +\n (read ? ` When a listed file without its text may cover the question, read it with ${read} before answering.` : '') +\n ' When nothing covers it, say you do not have that information and offer to ask the owner.' +\n ' When two sources disagree, give each value with the source that states it and ask the owner which is current; never pick one silently.',\n ...files.map(file => file.text !== null ? `Knowledge file ${file.path}:\\n${file.text}`\n : `Knowledge file ${file.path} (${file.size} bytes, text not shown)${read ? `: read it with ${read} when the question may be covered by it.` : '.'}`),\n // The disagree rule above, read before the files, named a conflict in 10 of 20 bench turns\n // (hospitality, 3 of 5 in production); repeated after the files as a check it named 20 of 20,\n // and 10 of 10 single-file answers stayed unchanged (gemini-3.5-flash-lite, 2026-10-12,\n // hospitality-agent #441).\n ...(files.length > 1 ? ['Before answering from these files, check every file that states the asked fact. When they state different values, give each value with its file name and ask the owner which is current.'] : []),\n ]\n}\n\n/** A workspace store's knowledge files (kind `file` under `prefix`) as turn knowledge, within the budget. */\nexport async function workspaceKnowledgeForTurn(\n store: { list(workspaceId: string, prefix: string): Promise<readonly KnowledgeEntry[]> },\n workspaceId: string,\n options: TurnKnowledgeBudget & { prefix?: string } = {},\n): Promise<TurnKnowledgeFile[]> {\n const entries = await store.list(workspaceId, options.prefix ?? '/files/')\n return budgetTurnKnowledge(entries.filter(entry => entry.kind === 'file').map(entry => ({\n path: entry.path,\n size: entry.content !== undefined ? new TextEncoder().encode(entry.content).byteLength : entry.bytes?.size ?? 0,\n text: entry.content ?? null,\n })), options)\n}\n","/**\n * The language a Router turn replies in, for every agent app: the sender's current\n * message decides, then the conversation's. It names no language on purpose. On\n * 2026-10-12 a hospitality turn whose context said \"saved language for notices is\n * Spanish\" answered 10 of 19 English questions in Spanish; a model follows any\n * language the prompt names. Saved preferences belong to messages the app starts.\n */\nexport function replyLanguageInstruction(): string {\n return 'Reply in the language of the sender\\'s current message, or in the language they ask for in it. ' +\n 'When its language is unclear (a short acknowledgement, a photo, a voice note), continue in the conversation\\'s language. ' +\n 'Change a saved language only when the sender asks for it in this message; a message written in another language is not that request.'\n}\n\n// ISO 639-1. Names come from Intl, in English, Spanish and the language's own name,\n// so a request for any language is recognised without a hand-kept list.\nconst LANGUAGE_CODES = ('aa ab af ak am an ar as av ay az ba be bg bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es ' +\n 'et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik io is it iu ja jv ka kg ki kj kk kl km kn ko kr ' +\n 'ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mr ms mt my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu ' +\n 'rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo ' +\n 'xh yi yo za zh zu').split(' ')\n// Always recognised, whatever the runtime's Intl data: generic words and the common\n// languages in English, Spanish and their own names (plus हिंदी beside हिन्दी).\nconst CORE_NAMES = [\n 'language', 'languages', 'idioma', 'idiomas', 'langue', 'lingua', 'língua', 'sprache',\n 'english', 'inglés', 'ingles', 'spanish', 'español', 'espanol', 'castellano', 'french', 'français', 'francés',\n 'portuguese', 'português', 'portugués', 'german', 'deutsch', 'alemán', 'italian', 'italiano', 'japanese', '日本語',\n 'japonés', 'chinese', '中文', '汉语', 'chino', 'korean', '한국어', 'coreano', 'arabic', 'العربية', 'árabe', 'hindi',\n 'हिन्दी', 'हिंदी', 'russian', 'русский', 'ruso', 'dutch', 'nederlands', 'neerlandés', 'hebrew', 'עברית', 'hebreo',\n 'turkish', 'türkçe', 'turco', 'vietnamese', 'tiếng việt', 'vietnamita', 'catalan', 'català', 'catalán',\n]\n// Language names that are everyday words: \"ya he ido\", \"él cree\", \"que me venda\",\n// \"odia\", \"from afar\", \"ewe\", \"Latin America\", \"shoe polish\".\nconst COMMON_WORDS = new Set(['ido', 'cree', 'venda', 'odia', 'afar', 'ewe', 'latin', 'polish'])\n\nlet patterns: RegExp[] | undefined\nfunction languagePatterns(): RegExp[] {\n if (patterns) return patterns\n const names = new Set(CORE_NAMES)\n for (const locale of ['en', 'es', ...LANGUAGE_CODES]) {\n let display: Intl.DisplayNames\n // A runtime without Intl language data still has CORE_NAMES.\n try { display = new Intl.DisplayNames([locale], { type: 'language' }) } catch { continue }\n for (const code of locale === 'en' || locale === 'es' ? LANGUAGE_CODES : [locale]) {\n const name = display.of(code)?.toLowerCase()\n if (name && name !== code && name.length >= 3 && !COMMON_WORDS.has(name)) names.add(name)\n }\n }\n // Latin-script names need word edges (\"pedido\" must not match Ido); scripts written\n // without spaces, such as 日本語, match anywhere.\n return patterns = [...names].map(name => {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n return /^[\\p{Script=Latin}\\s'-]+$/u.test(name) ? new RegExp(`(?<!\\\\p{L})${escaped}(?!\\\\p{L})`, 'iu') : new RegExp(escaped, 'iu')\n })\n}\n\n/**\n * True when the message names a language. A tool that saves a reply-language\n * preference requires it, using its `context.userMessage`, so the model cannot\n * save a language the sender never asked for.\n */\nexport function asksForLanguage(message: string | undefined): boolean {\n return typeof message === 'string' && languagePatterns().some(pattern => pattern.test(message))\n}\n","/**\n * One conversational turn answered by a model through the Tangle Router, with\n * the app's own tools executed in-process — no sandbox in the path.\n *\n * This is the default runtime for conversational turns in an agent app: the\n * product supplies the principal's tools, the profile prompt and the\n * conversation; the engine streams words as the model writes them, runs tool\n * calls through the bounded `streamAppToolLoop`, and returns one outcome.\n * Long, file or code work belongs to the sandbox, reached through a tool the\n * product adds to `tools`.\n *\n * Every failure is an outcome, never a throw. A durable turn owner retries\n * thrown errors, and a retry after a tool ran would repeat that tool's effect\n * (\"never re-run a turn automatically\", docs/agent-app-lessons.md). The only\n * automatic repeat is one model call that failed before any word or tool.\n *\n * Bounded paid lanes run this same engine inside a protected Router model grant\n * (`runProtectedRouterTurn` in `./protected-router-turn`, outside this entry so a\n * Worker bundle never pulls the grant client).\n */\nimport { streamAppToolLoop, type LoopEvent, type LoopMessage, type LoopToolCall, type ToolLoopStopReason } from './loop'\nimport { DEFAULT_TANGLE_ROUTER_BASE_URL } from './model'\nimport { gzipRequestBodies } from './gzip-request'\nimport { createOpenAICompatCompletionTurn, createOpenAICompatStreamTurn, createOpenAIResponsesTurn, isOpenAIResponsesModel } from './openai-stream'\nimport { turnKnowledgeInstructions, type TurnKnowledgeFile } from './turn-knowledge'\nimport { replyLanguageInstruction } from './reply-language'\nimport { placeExecution, type PlacementRecord, type VacuousAxis } from '@tangle-network/agent-runtime/placement'\nimport { turnTraceId, type TurnSpan, type TurnTrace } from '../turn-trace/recorder'\nimport { nextCallIndex, tracedModelFetch } from '../turn-trace/traced-fetch'\nexport { DURABLE_HOP_BUDGET_MS, turnCheckpointPath, workspaceTurnCheckpoints, type CheckpointWorkspaceStore, type TurnCheckpointStore } from './turn-continuation'\nexport { budgetTurnKnowledge, turnKnowledgeInstructions, workspaceKnowledgeForTurn, type TurnKnowledgeBudget, type TurnKnowledgeFile } from './turn-knowledge'\nexport { asksForLanguage, replyLanguageInstruction } from './reply-language'\n\n/** A tool the turn may call. Structurally an `McpToolDefinition` whose env is already bound. */\nexport interface RouterTurnTool {\n name: string\n description: string\n /** JSON Schema for the arguments object. */\n inputSchema: Record<string, unknown>\n run(args: Record<string, unknown>, context: RouterTurnToolContext): Promise<unknown>\n}\n\n/** What a running tool gets besides its arguments. */\nexport interface RouterTurnToolContext {\n /** This call's identity, shared by streamed parts, tool history and a native child execution. */\n callId?: string\n /** The effective turn cancellation signal. Tools must pass it to cancellable I/O. */\n signal?: AbortSignal\n /**\n * Report a typed side event while the tool runs (a graph edit, a file written, a\n * progress step). It streams at once as a `tool_event` and is recorded in the\n * outcome's `toolEvents`. Events sent after the call settles are dropped.\n */\n emit(kind: string, data?: unknown): void\n /** The sender's message this turn answers, so a tool can act only on what was asked (see {@link asksForLanguage}). */\n userMessage: string\n /** The turn's trace, when the turn records one. A tool that waits on a box or a service adds its own child spans under {@link span}. */\n trace?: TurnTrace\n /** This tool call's `tool.call` span; the parent of any span the tool records. */\n span?: TurnSpan\n}\n\n/** One side event a tool reported while it ran. */\nexport interface RouterTurnToolEvent {\n callId: string\n toolName: string\n kind: string\n data: unknown\n at: number\n}\n\n/** What the turn is doing, in the order it happens, for a live view. */\nexport type RouterTurnEvent =\n | { type: 'text'; segment: number; delta: string }\n /** Hidden reasoning the model streamed (`reasoning_content` / `thinking`), for a thinking view. Never part of the answer. */\n | { type: 'reasoning'; delta: string }\n /** The safe repeat is starting a fresh model call on `model`; what the failed call reasoned is finished. */\n | { type: 'repeat'; model: string }\n /** The model named a tool; its arguments are still streaming. Lets a caller start slow work the call will need\n * (the box `sandbox_run` runs in) seconds before the call itself. `toolName` is the app's name. */\n | { type: 'tool_start'; toolName: string }\n | { type: 'tool'; callId: string; toolName: string; status: 'running'; input: Record<string, unknown>; startedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'completed'; output: unknown; startedAt: number; endedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'error'; error: { code: string; message: string }; startedAt: number; endedAt: number }\n | { type: 'usage'; promptTokens: number; completionTokens: number; cachedPromptTokens?: number }\n | ({ type: 'tool_event' } & RouterTurnToolEvent)\n\nexport interface RouterTurnFailure {\n /** `model_http_<status>`, `model_stream_<code>` (an error frame inside the stream, e.g. `model_stream_empty_completion`),\n * `model_unavailable`, `model_empty`, `turn_<stopReason>`, `turn_aborted`,\n * `turn_tool_limit`, `router_unconfigured` or `placement_fallback_refused`; under a protected grant also the `grant_*` and\n * `settlement_*` codes of `./protected-router-turn`. */\n code: string\n status?: number\n message: string\n /** The model service's own error text, at most 1000 characters (e.g. `key_budget_exhausted`), so an app can\n * tell a spend cap from a missing balance. Never a credential. */\n detail?: string\n}\n\nexport interface RouterTurnOutcome {\n /** Every text segment the model wrote, joined by blank lines. */\n text: string\n /** The model the router reports having served, when it said. */\n servedModel: string | null\n toolCalls: Array<{ callId: string; toolName: string; ok: boolean }>\n /** Token use summed over every model call in the turn, as the router reported it. `cachedPromptTokens` are the\n * prompt tokens the provider served from its prompt cache; absent when no call reported them. */\n usage: { promptTokens: number; completionTokens: number; modelCalls: number; cachedPromptTokens?: number }\n /** Reasoning the turn streamed (deltas and characters). Zero when the model sent none; absent when no model was called. */\n reasoning?: { deltas: number; chars: number }\n /** Every side event the turn's tools reported, in order (at most 500). */\n toolEvents: RouterTurnToolEvent[]\n failure?: RouterTurnFailure\n /**\n * Set instead of a failure when the turn reached its budget at a clean point\n * (every tool call answered). The turn is not over: persist this and call\n * `runRouterTurn` again with `continueFrom` in a durable process to finish it.\n * `text` holds everything the turn has written so far, across hops.\n */\n continuation?: RouterTurnContinuation\n /** Where the turn was placed, when the caller asked for placement. */\n placement?: PlacementRecord\n}\n\n/** A checkpointed Router turn: the conversation after the system prompt, ready to continue. JSON-safe. */\nexport interface RouterTurnContinuation {\n messages: LoopMessage[]\n /** Hops this turn has already run, including this one. */\n hops: number\n /** Reply text every hop so far wrote; the final hop's outcome `text` includes it. */\n text: string\n}\n\n/**\n * What placement reads for a Router turn: the resolved profile, the tools the\n * turn would hold, and a model the sender chose. Declared data only.\n */\nexport interface RouterTurnPlacementInput {\n profile: object\n toolNames?: readonly string[]\n /** A model other than the profile's needs the sandbox to choose between them. */\n requestedModel?: string\n /** Deny-only permissions grant nothing a Router turn lacks. Default: ['permissions']. */\n vacuousAxes?: readonly VacuousAxis[]\n /** The app inlines the profile's skill text into the prompt. */\n inlineSkills?: boolean\n}\n\n/**\n * Where one conversational turn runs: `inference` or `loop` run here in\n * `runRouterTurn`; `sandbox` means the profile or request needs a computer\n * (a harness, files, MCP servers, skills that are not inlined, another model).\n * Throws `PlacementRefusedError` when no tier can meet every requirement.\n */\nexport function placeRouterTurn(input: RouterTurnPlacementInput): PlacementRecord {\n return placeExecution({\n profile: input.profile,\n requirements: {\n ...(input.toolNames?.length ? { tools: [...input.toolNames] } : {}),\n ...(input.requestedModel ? { model: input.requestedModel } : {}),\n },\n context: { interactive: false, inferenceAvailable: true, loopAvailable: true },\n vacuousAxes: input.vacuousAxes ?? ['permissions'],\n ...(input.inlineSkills ? { inlineSkills: true } : {}),\n })\n}\n\n/** One tool call's result as the model reads it. */\nexport type RouterTurnToolOutcome = { ok: true; result: unknown } | { ok: false; code: string; message: string }\n\nexport interface RouterTurnOptions {\n apiKey: string\n model: string\n /** Defaults to the Tangle Router. */\n baseUrl?: string\n systemPrompt: string\n userMessage: string\n /** Earlier turns. Plain text messages, or OpenAI function-calling history (an assistant message\n * carrying `tool_calls` and the `tool` messages answering them) so the model sees what it did. */\n history?: Array<{ role: 'user' | 'assistant'; content: string } | LoopMessage>\n tools?: RouterTurnTool[]\n /** Wall-clock budget in ms for this hop. Default 90 s. At the budget the outcome carries a\n * `continuation` instead of failing; the model call or tool already running finishes first. */\n budgetMs?: number\n /** Continue a checkpointed turn; `userMessage` and `history` are ignored. */\n continueFrom?: RouterTurnContinuation\n /** Runaway watchdog on model turns. Default: the tool loop's own watchdog, far above any legitimate turn, so\n * `budgetMs` bounds the turn. A fixed 12 failed Legal's formation turns, which need 12 tools in 13 model calls\n * (2026-10-20, turn_backstop on 2 of 6). */\n maxToolTurns?: number\n maxTokens?: number\n /** Sent as `x-tangle-trace-id` so the router's generation joins the app's trace. Characters the Router\n * refuses in that header (the `:` of an execution id) become `_`; see {@link turnTraceId}. Default: the\n * `trace`'s id. */\n traceId?: string\n /**\n * The turn's trace (`@tangle-network/agent-app/turn-trace`). Every model request is recorded as a\n * `model.call` span with the Router's `Server-Timing` split into network and server time, and every tool\n * call as a `tool.call` span that tool-side spans hang from. Without it nothing is recorded.\n */\n trace?: TurnTrace\n fetchImpl?: typeof fetch\n onEvent?: (event: RouterTurnEvent) => void\n /** Map a thrown tool error to what the model reads. Default: an error carrying string `code`\n * (and numeric `status`) is reported with its message; anything else is a generic failure. */\n toolError?: (error: unknown) => { code: string; message: string; status?: number } | null\n /** Called for a tool failure the default mapping hides from the model, for the app's logs. */\n onToolFailure?: (toolName: string, error: unknown) => void\n /** Cancels the turn: the model call in flight is aborted, no further tool starts, and the\n * outcome carries `turn_aborted`. Effects of tools that already ran are kept. */\n signal?: AbortSignal\n /** Default true: one repeat of a model call that failed before any word or tool, and of a blank\n * answer. Pass false when a second billable call needs the caller's own decision; the failure is\n * then returned as it happened. */\n repeat?: boolean\n /** Default true. False takes each model call as one buffered completion instead of a stream. */\n stream?: boolean\n /** Sent as `reasoning_effort`. */\n reasoningEffort?: string\n /**\n * The caller shows the model's reasoning as it streams (`onEvent` `reasoning` events). With `onEvent`, a\n * streamed chat call and the safe repeat on, the Router then releases the stream at the first reasoning frame\n * instead of holding it for the first word, and returns Gemini's thought summaries (gateway\n * `streamReasoningImmediately`). Default false; `createRouterTurnProducer` turns it on.\n */\n showReasoning?: boolean\n /** Sent as `max_completion_tokens`: one model call's visible and reasoning tokens together. */\n maxCompletionTokens?: number\n /** At most this many tool calls run. The next one is refused before it runs and the turn ends\n * with `turn_tool_limit`. */\n maxToolCalls?: number\n /** Replace a domain-specific tool result; return undefined to use the shared serialization and limit. */\n renderToolResult?: (toolName: string, outcome: RouterTurnToolOutcome) => string | undefined\n /**\n * Place the turn before any model call, using `model` as the executed model rather than\n * the optional `requestedModel` hint. A turn placed in the sandbox returns at once\n * with `placement` and failure `placement_sandbox`, so the app runs it there instead.\n */\n placement?: Omit<RouterTurnPlacementInput, 'toolNames'>\n temperature?: number\n /** Models tried in order when a model call fails before any word or tool, or answers blank. Without it,\n * that safe repeat uses `model` again. `repeat: false` turns both off. */\n fallbackModels?: readonly string[]\n /** Resend one model request that answered 408, 425, 429 or 5xx, or failed to connect, before its stream\n * began, with exponential backoff (a `retry-after` up to 8 s is honoured). `attempts` counts the first\n * send (default 1, no resend). With more than one, resends go on past `attempts` until 45 s have passed\n * since the first send, so an outage of that length costs the turn a pause instead of the turn.\n * `timeoutMs` bounds each attempt, stream included. */\n retry?: { attempts?: number; timeoutMs?: number; baseDelayMs?: number }\n /** Characters of one tool result the model reads when no `renderToolResult` is given. Default 12 000. */\n toolResultLimit?: number\n /**\n * Which model API carries the turn. `auto` (default) uses the Responses API for an OpenAI model asked to\n * reason (`reasoningEffort` other than `none`), since OpenAI returns reasoning summaries only there, or given\n * tools, since GPT-6.1 Sol and GPT-6 Astra take function tools only there (the Router refuses them on chat\n * completions with `model_requires_responses_for_tools`), and chat completions otherwise. A buffered turn\n * (`stream: false`) always uses chat completions.\n */\n api?: 'auto' | 'chat' | 'responses'\n /**\n * Gzip a model request body of at least this many bytes (`Content-Encoding: gzip`), so a large system prompt\n * uploads in fewer round trips. Unset defaults to 32 KiB for the origin of DEFAULT_TANGLE_ROUTER_BASE_URL;\n * other origins send bodies as they are. An explicit threshold wins; a negative value disables gzip.\n */\n gzipRequestAboveBytes?: number\n}\n\nconst DEFAULT_BUDGET_MS = 90_000\nconst RETRY_STATUS = new Set([408, 425, 429, 500, 502, 503, 504])\n// The Router names a refusal no resend of the same model can fix: every\n// credential for it is out of quota, rejected or suspended (tangle-router\n// `X-Tangle-Failure-Category`). The turn moves to its next fallback model at once.\nconst DEAD_CREDENTIAL_CATEGORIES = new Set(['provider_quota_exhausted', 'provider_key_invalid', 'provider_account_suspended'])\nconst MAX_RETRY_DELAY_MS = 8_000\n// How long a request that may resend keeps resending a retryable answer. The Router answers 503 without calling a\n// model while Platform cannot verify the turn's key: on 2026-10-20 Platform's event loop stalled 16 s (10:30) and a\n// Platform deploy restarted it (11:36), and three sends inside 1 to 16 s failed two Legal turns that 45 s\n// would have carried through.\nconst RETRY_WINDOW_MS = 45_000\nconst TOOL_EVENT_LIMIT = 500\n/** Marks a tool's typed event inside a loop progress update. */\nconst TOOL_EVENT = '__routerTurnToolEvent'\nconst TOOL_RESULT_LIMIT = 12_000\n\n/** OpenAI-compatible function names allow only `[A-Za-z0-9_-]{1,64}`; app tool names often use dots. */\nexport function routerFunctionName(name: string): string {\n return name.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)\n}\n\nexport interface RouterTurnPromptSections {\n /** Every section that is the same on each turn of a workspace, first, so the bytes repeat turn after turn. */\n prefix: string\n /** What this turn adds: its `context`. Empty when there is none. */\n tail: string\n /** `prefix` then `tail`: the system prompt the model reads. */\n text: string\n}\n\nexport interface RouterTurnPromptOptions {\n /** Sections the same on every turn of a workspace (skills, tool guidance, catalogs, references). They go in the\n * prefix, after the profile's prompt, so a provider's prompt cache serves them. */\n stable?: readonly string[]\n /** This turn's own sections (the clock, the board, what changed, ids). They go last, after every stable byte. */\n context?: readonly string[]\n toolNames?: readonly string[]\n /** Knowledge files every turn carries; see {@link turnKnowledgeInstructions}. They change only when the workspace\n * edits them, so they close the prefix. */\n knowledge?: { files: readonly TurnKnowledgeFile[]; readTool?: string }\n /** Under a test runner (Vitest, Jest, `NODE_ENV=test`) the composition throws when the prefix carries a per-turn\n * byte ({@link perTurnPrefixBytes}), so an app's own tests fail before a timestamp costs every turn its prompt\n * cache. It never runs outside a test runner. `false` turns the check off for a prefix that is meant to vary. */\n checkStablePrefix?: boolean\n}\n\n// A clock to the minute is per-turn by construction: ISO (`2026-10-22T08:15`, `2026-10-22 08:15`), `Date#toString`\n// (`Wed Oct 22 2026 08:15:00`) and `Date#toUTCString` (`Wed, 22 Oct 2026 08:15:00`).\nconst PER_TURN_CLOCKS = [\n /\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}/,\n /\\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{2} \\d{4} \\d{2}:\\d{2}/,\n /\\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \\d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4} \\d{2}:\\d{2}/,\n]\n/** A turn section shorter than this may repeat a stable phrase; only longer ones are looked for in the prefix. */\nconst MIN_REPEATED_CONTEXT = 24\n\n/**\n * The per-turn bytes in a prompt prefix: a clock to the minute, and any of this turn's `context` sections (or the\n * caller's own per-turn values: ids, the member's message) that also appear there. Empty for a cacheable prefix.\n */\nexport function perTurnPrefixBytes(prefix: string, perTurn: readonly string[] = []): string[] {\n const found = PER_TURN_CLOCKS.flatMap(pattern => prefix.match(pattern)?.[0] ?? [])\n for (const value of perTurn) {\n const trimmed = value.trim()\n if (trimmed.length >= MIN_REPEATED_CONTEXT && prefix.includes(trimmed)) found.push(trimmed.slice(0, 80))\n }\n return found\n}\n\nfunction underTestRunner(): boolean {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env\n return Boolean(env && (env.VITEST || env.JEST_WORKER_ID || env.NODE_ENV === 'test'))\n}\n\n/**\n * The lean system prompt for a Router turn, split where its bytes stop repeating. The prefix holds the profile's\n * system prompt, appended prompt and instructions, the reply-language rule, the caller's `stable` sections and the\n * knowledge files; the tail holds the turn's `context`. Tool names are rewritten to the function names the model\n * actually calls.\n *\n * A provider serves a repeated prompt prefix from its cache: through the Router, Gemini served 38,685 of\n * 40,734 prompt tokens from cache on each repeat of a stable 150 kB prefix, and none when a timestamp came first\n * (2026-10-22). One per-turn byte early in the prompt therefore costs the whole prompt on every turn, so nothing\n * per-turn belongs in `stable` or the profile's prompt; under a test runner a clock or a repeated `context` section in\n * the prefix throws (`checkStablePrefix`).\n */\nexport function composeRouterTurnPromptSections(\n profile: { prompt?: { systemPrompt?: string; appendSystemPrompt?: string; instructions?: readonly string[] } },\n options: RouterTurnPromptOptions = {},\n): RouterTurnPromptSections {\n const knowledge = options.knowledge ? turnKnowledgeInstructions(options.knowledge.files, { readTool: options.knowledge.readTool }) : []\n const names = [...(options.toolNames ?? [])].sort((a, b) => b.length - a.length)\n const render = (parts: readonly string[]) => names.reduce((out, name) => out.split(name).join(routerFunctionName(name)),\n parts.filter(part => part.trim()).join('\\n\\n'))\n const authored = [profile.prompt?.systemPrompt ?? '', profile.prompt?.appendSystemPrompt ?? '', ...(profile.prompt?.instructions ?? []),\n replyLanguageInstruction(), ...(options.stable ?? [])]\n const prefix = render([...authored, ...knowledge])\n const tail = render(options.context ?? [])\n // The workspace's knowledge files are its own text and may quote a time; the check reads what the app authored.\n if (options.checkStablePrefix !== false && underTestRunner()) {\n const perTurn = perTurnPrefixBytes(render(authored), (options.context ?? []).map(section => render([section])))\n if (perTurn.length) {\n throw new Error(`composeRouterTurnPromptSections: the stable prefix carries per-turn bytes (${perTurn.map(value => JSON.stringify(value)).join(', ')}); `\n + 'move them to `context` so the prompt cache serves the prefix, or pass `checkStablePrefix: false`.')\n }\n }\n return { prefix, tail, text: [prefix, tail].filter(Boolean).join('\\n\\n') }\n}\n\n/** The system prompt {@link composeRouterTurnPromptSections} composes, as one string. */\nexport function composeRouterTurnPrompt(\n profile: { prompt?: { systemPrompt?: string; appendSystemPrompt?: string; instructions?: readonly string[] } },\n options: RouterTurnPromptOptions = {},\n): string {\n return composeRouterTurnPromptSections(profile, options).text\n}\n\nconst joinText = (parts: string[]) => parts.map(part => part.trim()).filter(Boolean).join('\\n\\n')\n\nfunction defaultToolError(error: unknown): { code: string; message: string; status?: number } | null {\n const value = error as { code?: unknown; status?: unknown; message?: unknown; issues?: unknown }\n if (Array.isArray(value?.issues)) {\n return { code: 'invalid_arguments', message: JSON.stringify(value.issues).slice(0, 600) }\n }\n if (typeof value?.code === 'string' && typeof value.message === 'string') {\n return { code: value.code, message: value.message, ...(typeof value.status === 'number' ? { status: value.status } : {}) }\n }\n return null\n}\n\nfunction renderResult(outcome: RouterTurnToolOutcome, limit = TOOL_RESULT_LIMIT): string {\n if (!outcome.ok) return `Error (${outcome.code}): ${outcome.message}`\n let text: string\n try { text = typeof outcome.result === 'string' ? outcome.result : JSON.stringify(outcome.result ?? null) }\n catch { text = String(outcome.result) }\n return text.length > limit ? `${text.slice(0, limit)}…` : text\n}\n\n/** Add one model call's usage to the turn's totals and to that call's span. */\nfunction addCallUsage(\n usage: RouterTurnOutcome['usage'],\n call: { promptTokens: number; completionTokens: number; cachedPromptTokens?: number },\n span: TurnSpan | undefined,\n): void {\n usage.promptTokens += call.promptTokens\n usage.completionTokens += call.completionTokens\n usage.modelCalls++\n const cached = call.cachedPromptTokens\n if (cached !== undefined) usage.cachedPromptTokens = (usage.cachedPromptTokens ?? 0) + cached\n span?.set({\n 'gen_ai.usage.input_tokens': call.promptTokens,\n 'gen_ai.usage.output_tokens': call.completionTokens,\n ...(cached !== undefined ? { 'gen_ai.usage.cache_read.input_tokens': cached } : {}),\n })\n}\n\nexport async function runRouterTurn(options: RouterTurnOptions): Promise<RouterTurnOutcome> {\n // A continued turn answers the last user message in its checkpoint.\n const lastUser = options.continueFrom?.messages.filter(message => message.role === 'user').at(-1)?.content\n const currentUserMessage = options.continueFrom ? (typeof lastUser === 'string' ? lastUser : '') : options.userMessage\n const placement = options.placement\n ? placeRouterTurn({ ...options.placement, requestedModel: options.model, toolNames: (options.tools ?? []).map(tool => tool.name) })\n : undefined\n if (placement?.chosen === 'sandbox') {\n return { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [], placement,\n failure: { code: 'placement_sandbox', message: placement.reason } }\n }\n const { apiKey } = options\n if (!apiKey) {\n return { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [],\n ...(placement ? { placement } : {}),\n failure: { code: 'router_unconfigured', message: 'The model credential is not configured.' } }\n }\n const emit = options.onEvent ?? (() => {})\n const { signal } = options\n // A cancelled turn sends nothing more, whatever the injected fetch does with the signal.\n const attempts = Math.max(1, Math.floor(options.retry?.attempts ?? 1))\n const attemptTimeoutMs = options.retry?.timeoutMs\n const baseDelayMs = options.retry?.baseDelayMs ?? 500\n const pause = (ms: number) => new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason)\n const timer = setTimeout(resolve, ms)\n signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason) }, { once: true })\n })\n const traceId = options.traceId !== undefined ? turnTraceId(options.traceId) : options.trace?.traceId\n const { trace } = options\n const transportState = { currentModel: options.model, lastModelSpan: undefined as TurnSpan | undefined }\n const { fetchImpl } = createRouterTurnTransport(options, trace, transportState, signal, attempts, attemptTimeoutMs, baseDelayMs, pause)\n\n const extraBody = {\n ...(options.maxTokens ? { max_tokens: options.maxTokens } : {}),\n ...(options.maxCompletionTokens ? { max_completion_tokens: options.maxCompletionTokens } : {}),\n ...(options.reasoningEffort ? { reasoning_effort: options.reasoningEffort } : {}),\n }\n const byFunction = new Map<string, RouterTurnTool>()\n for (const tool of options.tools ?? []) {\n const fn = routerFunctionName(tool.name)\n if (!byFunction.has(fn)) byFunction.set(fn, tool)\n }\n let servedModel: string | null = null\n const reasoningAsked = Boolean(options.reasoningEffort) && options.reasoningEffort !== 'none'\n // Legal 2026-10-19/20: the Router refused the gpt-6.1-sol fallback's tool turn on chat completions with a 400 in 2\n // of 2 fallbacks, so the fallback that should have saved those turns failed them.\n const responsesForTools = byFunction.size > 0\n const useResponses = (model: string) => options.stream !== false &&\n (options.api === 'responses' || ((options.api ?? 'auto') === 'auto' && (reasoningAsked || responsesForTools) &&\n isOpenAIResponsesModel(model)))\n // A caller that shows reasoning asks the Router to release a streamed chat call at the first reasoning frame\n // rather than hold it for the first word, which also makes it return Gemini's thought summaries (tangle-router\n // gateway option `streamReasoningImmediately`). The cost: once reasoning has been shown the Router no longer\n // switches models silently. A reasoning-only finish or a stall arrives as an error frame (`empty_completion`,\n // `stream_idle_timeout`), which ends the call by name and takes the safe repeat on the next fallback model, so\n // the option is sent only while that repeat is on. The stall timer stays the Router's own (120 s): Gemini sends a\n // tool call whole, so a stream is silent while the model writes the call. On Legal (2026-10-20) healthy calls went\n // up to 44.6 s from their last word to their tool call and 66 s from their first frame to it, and a 45 s timer cut\n // 2 of 30 turns after their first sentence.\n const bodyFor = (model: string) => options.showReasoning && options.onEvent && options.repeat !== false &&\n options.stream !== false && !useResponses(model)\n ? { ...extraBody, gateway: { streamReasoningImmediately: true } }\n : extraBody\n const streamTurnFor = (model: string) => (options.stream === false ? createOpenAICompatCompletionTurn\n : useResponses(model) ? createOpenAIResponsesTurn : createOpenAICompatStreamTurn)({\n baseUrl: options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL,\n apiKey,\n model,\n ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n tools: [...byFunction.entries()].map(([name, tool]) => ({\n type: 'function', function: { name, description: tool.description, parameters: tool.inputSchema },\n })),\n ...(Object.keys(bodyFor(model)).length ? { extraBody: bodyFor(model) } : {}),\n ...(traceId ? { headers: { 'x-tangle-trace-id': traceId } } : {}),\n ...(fetchImpl ? { fetchImpl } : {}),\n onServedModel: served => {\n servedModel = served.servedModel\n if (served.servedModel) transportState.lastModelSpan?.set({ 'gen_ai.response.model': served.servedModel })\n },\n })\n const segments: string[] = []\n const usage: RouterTurnOutcome['usage'] = { promptTokens: 0, completionTokens: 0, modelCalls: 0 }\n // How much reasoning the turn streamed: the number an app logs to measure reasoning coverage.\n const reasoning = { deltas: 0, chars: 0 }\n const toolCalls: RouterTurnOutcome['toolCalls'] = []\n const toolEvents: RouterTurnToolEvent[] = []\n const started = new Map<string, number>()\n const priorCallIds = new Set((options.continueFrom?.messages ?? options.history ?? []).flatMap(message => [\n ...('tool_calls' in message ? (message.tool_calls ?? []).map(call => call.id) : []),\n ...('tool_call_id' in message && message.tool_call_id ? [message.tool_call_id] : []),\n ]))\n let segmentOpen = false\n let toolsRan = 0\n let checkpoint: LoopMessage[] | null = null\n let toolLimitReached = false\n const deadline = Date.now() + (options.budgetMs ?? DEFAULT_BUDGET_MS)\n const callIdOf = (id: string | undefined, toolName: string) => {\n if (id) return id\n let fallback = `${toolName}-${started.size}`\n while (started.has(fallback) || priorCallIds.has(fallback)) fallback += '_'\n return fallback\n }\n\n let placementFailure: RouterTurnFailure | undefined\n const run = async (model: string): Promise<ToolLoopStopReason | 'tool_limit' | 'placement_refused'> => {\n // A safe model retry still cannot change execution tier after this turn began.\n if (placement && options.placement && model !== options.model) {\n const next = placeRouterTurn({ ...options.placement, requestedModel: model,\n toolNames: (options.tools ?? []).map(tool => tool.name) })\n if (next.chosen !== placement.chosen) {\n placementFailure = { code: 'placement_fallback_refused', message: `The fallback model cannot run in this turn's placement: ${next.reason}` }\n return 'placement_refused'\n }\n }\n transportState.currentModel = model\n const streamTurn = streamTurnFor(model)\n for await (const step of streamAppToolLoop<LoopEvent>({\n systemPrompt: options.systemPrompt,\n ...(options.continueFrom\n ? { priorMessages: options.continueFrom.messages }\n : { userMessage: options.userMessage, priorMessages: (options.history ?? []) as LoopMessage[] }),\n streamTurn,\n extractText: event => event.type === 'text' ? event.text : '',\n extractToolCall: event => event.type === 'tool_call' ? event.call : null,\n isExecutableTool: name => byFunction.has(name),\n deadlineMs: deadline,\n ...(options.maxToolTurns !== undefined ? { maxToolTurns: options.maxToolTurns } : {}),\n labelFor: call => byFunction.get(call.toolName)?.name ?? call.toolName,\n renderResult: (label, outcome) => options.renderToolResult?.(label, outcome) ?? renderResult(outcome, options.toolResultLimit),\n executeToolCall: async (call: LoopToolCall, context) => {\n const tool = byFunction.get(call.toolName)\n if (!tool) return { ok: false, code: 'unknown_tool', message: `No tool named ${call.toolName}` }\n if (signal?.aborted) return { ok: false, code: 'aborted', message: 'The turn was cancelled before this tool ran.' }\n if (options.maxToolCalls !== undefined && toolsRan >= options.maxToolCalls) {\n toolLimitReached = true\n return { ok: false, code: 'tool_limit', message: 'The turn reached its tool-call limit.' }\n }\n toolsRan++\n // A tool's typed event rides the loop's progress channel, so it streams in order before the result.\n const emitEvent = (kind: string, data?: unknown) => context?.progress({ data: { [TOOL_EVENT]: kind, data } })\n const toolSpan = trace?.start('tool.call', 'tool', {\n 'gen_ai.tool.name': tool.name,\n 'tool.call_id': call.toolCallId ?? '',\n 'call.index': nextCallIndex(trace, 'tool.call'),\n })\n try {\n const result = await tool.run(call.args, {\n ...(call.toolCallId ? { callId: call.toolCallId } : {}),\n emit: emitEvent,\n userMessage: currentUserMessage,\n ...(signal ? { signal } : {}),\n ...(trace && toolSpan ? { trace, span: toolSpan } : {}),\n })\n toolSpan?.end({ 'tool.ok': true })\n return { ok: true, result }\n } catch (error) {\n const mapped = (options.toolError ?? defaultToolError)(error)\n // The span names the failure by its code; a thrown message can carry customer text.\n toolSpan?.end({ 'tool.ok': false }, mapped?.code ?? 'tool_failed')\n if (mapped) return { ok: false, ...mapped }\n options.onToolFailure?.(tool.name, error)\n return { ok: false, code: 'tool_failed', message: 'The tool failed; tell the user what could not be completed.' }\n }\n },\n })) {\n if (step.kind === 'event') {\n const event = step.event\n if (event.type === 'text' && event.text) {\n // A turn that owns its trace outside createChatTurnRoutes (a Durable Object turn) gets first_text_ms here.\n trace?.markFirstText()\n if (!segmentOpen) { segments.push(''); segmentOpen = true }\n segments[segments.length - 1] += event.text\n emit({ type: 'text', segment: segments.length, delta: event.text })\n } else if (event.type === 'reasoning' && event.text) {\n reasoning.deltas++\n reasoning.chars += event.text.length\n emit({ type: 'reasoning', delta: event.text })\n } else if (event.type === 'usage') {\n addCallUsage(usage, event.usage, transportState.lastModelSpan)\n emit({ type: 'usage', ...event.usage })\n } else if (event.type === 'tool_call_start') {\n emit({ type: 'tool_start', toolName: byFunction.get(event.toolName)?.name ?? event.toolName })\n } else if (event.type === 'tool_call') {\n segmentOpen = false\n const tool = byFunction.get(event.call.toolName)\n // The loop yields this event before extracting its call. Normalize a missing id once,\n // so execution, progress, result and replay history reuse the displayed identity.\n event.call.toolCallId ||= callIdOf(undefined, event.call.toolName)\n const callId = event.call.toolCallId\n started.set(callId, Date.now())\n emit({ type: 'tool', callId, toolName: tool?.name ?? event.call.toolName, status: 'running',\n input: event.call.args, startedAt: started.get(callId)! })\n }\n } else if (step.kind === 'tool_progress') {\n const tool = byFunction.get(step.toolName)\n const marked = step.update.data as { [TOOL_EVENT]?: unknown; data?: unknown } | undefined\n // A tool's own emit carries its kind; plain loop progress (a step count, a message) is kind `progress`.\n const typed = typeof marked?.[TOOL_EVENT] === 'string'\n const event: RouterTurnToolEvent = {\n callId: callIdOf(step.toolCallId, step.toolName), toolName: tool?.name ?? step.toolName,\n kind: typed ? marked![TOOL_EVENT] as string : 'progress',\n data: typed ? marked!.data ?? null : step.update, at: Date.now(),\n }\n if (toolEvents.length < TOOL_EVENT_LIMIT) toolEvents.push(event)\n emit({ type: 'tool_event', ...event })\n } else if (step.kind === 'tool_result') {\n const tool = byFunction.get(step.toolName)\n const callId = callIdOf(step.toolCallId, step.toolName)\n const startedAt = started.get(callId) ?? Date.now()\n const toolName = tool?.name ?? step.toolName\n toolCalls.push({ callId, toolName, ok: step.outcome.ok })\n emit(step.outcome.ok\n ? { type: 'tool', callId, toolName, status: 'completed', output: step.outcome.result, startedAt, endedAt: Date.now() }\n : { type: 'tool', callId, toolName, status: 'error', startedAt, endedAt: Date.now(),\n error: { code: step.outcome.code, message: step.outcome.message } })\n // The refused call never ran; the turn ends here rather than asking the model again.\n if (toolLimitReached) return 'tool_limit'\n } else if (step.kind === 'capped') {\n if (step.stopReason === 'deadline' && step.messages) checkpoint = step.messages\n return step.stopReason\n }\n }\n return 'completed'\n }\n\n const outcome = (failure?: RouterTurnFailure): RouterTurnOutcome => ({\n text: joinText([options.continueFrom?.text ?? '', ...segments]),\n servedModel, toolCalls, usage: { ...usage }, reasoning: { ...reasoning }, toolEvents: [...toolEvents], ...(placement ? { placement } : {}), ...(failure ? { failure } : {}),\n })\n const repeat = options.repeat !== false\n // The safe repeat walks this chain: the next fallback model, or the same model once.\n const repeats = !repeat ? [] : options.fallbackModels?.length ? [...options.fallbackModels] : [options.model]\n let stop: ToolLoopStopReason | 'tool_limit' | 'placement_refused'\n try {\n try {\n stop = await run(options.model)\n } catch (error) {\n // Safe to repeat only while nothing was said and no tool ran.\n const next = repeats.shift()\n if (next === undefined || signal?.aborted || toolsRan > 0 || segments.length > 0) throw error\n emit({ type: 'repeat', model: next })\n stop = await run(next)\n }\n } catch (error) {\n if (signal?.aborted) return outcome({ code: 'turn_aborted', message: 'The turn was cancelled.' })\n const status = (error as { status?: unknown }).status\n // An error frame inside a 200 stream (`openai-stream`'s stream failure) keeps the service's code.\n const streamCode = (error as { streamFailure?: unknown; code?: unknown }).streamFailure === true ? (error as { code?: unknown }).code : undefined\n if (typeof streamCode === 'string' && /^[\\w.-]{1,80}$/.test(streamCode)) {\n return outcome({ code: `model_stream_${streamCode}`, message: 'The model service ended the reply with an error.',\n detail: error instanceof Error ? error.message.slice(0, 1000) : streamCode })\n }\n // The stream adapter puts the service's own text after the status; keep it, short, for the app's error categories.\n const detail = error instanceof Error ? error.message.match(/\\(HTTP \\d+\\): ([\\s\\S]*)$/)?.[1]?.slice(0, 1000) : undefined\n return outcome(typeof status === 'number'\n ? { code: `model_http_${status}`, status, message: 'The model service did not answer.', ...(detail ? { detail } : {}) }\n : { code: 'model_unavailable', message: 'The model service did not answer.' })\n }\n if (placementFailure) return outcome(placementFailure)\n if (stop === 'deadline' && checkpoint) {\n return { ...outcome(), continuation: { messages: checkpoint,\n hops: (options.continueFrom?.hops ?? 0) + 1,\n text: outcome().text } }\n }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n // A model can end its turn with neither a word nor a tool call (gemini-2.5-flash did on 8 of\n // 53 \"remember\" turns, 2026-10-11). Nothing was said and nothing ran, so one repeat is safe;\n // an answer still blank is a typed failure, never a successful empty reply.\n if (!segments.some(part => part.trim()) && !options.continueFrom?.text.trim()) {\n const next = repeats.shift()\n if (toolsRan === 0 && next !== undefined) {\n emit({ type: 'repeat', model: next })\n try { stop = await run(next) } catch { stop = 'completed' }\n if (placementFailure) return outcome(placementFailure)\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n }\n if (!segments.some(part => part.trim())) {\n return outcome({ code: 'model_empty', message: 'The model finished without writing a reply.' })\n }\n }\n return outcome()\n}\n\nfunction createRouterTurnTransport(\n options: RouterTurnOptions,\n trace: RouterTurnOptions['trace'],\n transportState: { currentModel: string; lastModelSpan: TurnSpan | undefined },\n signal: RouterTurnOptions['signal'],\n attempts: number,\n attemptTimeoutMs: number | undefined,\n baseDelayMs: number,\n pause: (ms: number) => Promise<void>,\n) {\n const gzipAbove = options.gzipRequestAboveBytes ?? (\n URL.canParse(options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL) &&\n new URL(options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL).origin === new URL(DEFAULT_TANGLE_ROUTER_BASE_URL).origin\n ? 32 * 1024 : undefined\n )\n const baseFetch: typeof fetch | undefined = gzipAbove !== undefined && gzipAbove >= 0\n ? gzipRequestBodies(options.fetchImpl ?? fetch, gzipAbove)\n : options.fetchImpl\n // Each HTTP send is its own `model.call` span, so a retried 503 is visible beside the send that answered.\n const sendOnce: typeof fetch | undefined = trace\n ? tracedModelFetch(trace, baseFetch ?? fetch, {\n onSpan: span => { transportState.lastModelSpan = span; span.set({ 'gen_ai.request.model': transportState.currentModel }) },\n })\n : baseFetch\n const fetchImpl: typeof fetch | undefined = signal || attempts > 1 || attemptTimeoutMs\n ? async (input, init) => {\n const firstSentAt = Date.now()\n // Resending stops once the attempts and the retry window are both spent; one attempt never resends.\n const spent = (attempt: number) => attempts === 1 || (attempt >= attempts && Date.now() - firstSentAt >= RETRY_WINDOW_MS)\n for (let attempt = 1;;attempt++) {\n signal?.throwIfAborted()\n const signals = [signal, attemptTimeoutMs ? AbortSignal.timeout(attemptTimeoutMs) : undefined]\n .filter((value): value is AbortSignal => Boolean(value))\n const attemptSignal = signals.length > 1 ? AbortSignal.any(signals) : signals[0]\n const backoff = () => Math.min(MAX_RETRY_DELAY_MS, baseDelayMs * 2 ** (attempt - 1)) * (0.5 + Math.random() / 2)\n // The wait before a resend is its own span, so the time between two sends is named, not a gap.\n const wait = (ms: number, reason: string) => trace\n ? trace.measure('model.retry_wait', 'other', () => pause(ms), { 'retry.attempt': attempt, 'retry.reason': reason, 'retry.wait_ms': Math.round(ms) })\n : pause(ms)\n let response: Response\n try {\n // A cancelled turn sends nothing more, whatever the injected fetch does with the signal.\n response = await (sendOnce ?? fetch)(input, { ...init, ...(attemptSignal ? { signal: attemptSignal } : {}) })\n } catch (error) {\n if (signal?.aborted || spent(attempt)) throw error\n await wait(backoff(), 'send_failed')\n continue\n }\n // Nothing has streamed yet, so a resend repeats no word and no tool.\n if (spent(attempt) || !RETRY_STATUS.has(response.status)) return response\n if (DEAD_CREDENTIAL_CATEGORIES.has(response.headers.get('x-tangle-failure-category') ?? '')) return response\n const retryAfter = Number(response.headers.get('retry-after'))\n await response.body?.cancel().catch(() => { })\n await wait(Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, MAX_RETRY_DELAY_MS) : backoff(), `http_${response.status}`)\n }\n }\n : sendOnce\n return { fetchImpl }\n}\n","/**\n * A Router turn never fails because of time. `runRouterTurn` stops at its hop\n * budget at a clean point and returns a `continuation`; the host saves it here\n * and runs the next hop in a durable process (a Durable Object alarm or a Queue\n * consumer: 15 minutes of wall time each), posting into the same conversation.\n *\n * Checkpoints live in the app's workspace store under `/turns/<turnId>/`, which\n * a Files view (`/files/`) never lists.\n */\nimport type { RouterTurnContinuation } from './router-turn'\n\n/** Wall time a durable hop may plan for: a Durable Object alarm or Queue consumer gets 15 minutes. */\nexport const DURABLE_HOP_BUDGET_MS = 14 * 60_000\n\n/** Where a turn's checkpoint waits between hops. */\nexport interface TurnCheckpointStore {\n save(turnId: string, continuation: RouterTurnContinuation): Promise<void>\n load(turnId: string): Promise<RouterTurnContinuation | null>\n clear(turnId: string): Promise<void>\n}\n\ninterface CheckpointEntry { content?: string; revision: number }\n\n/** The fields of an agent-runtime `WorkspaceStore` a checkpoint needs; structural so any adapter fits. */\nexport interface CheckpointWorkspaceStore {\n get(workspaceId: string, path: string): Promise<CheckpointEntry | null>\n put(input: { workspaceId: string; path: string; kind: 'file'; ifRevision: number | null; actor: string; content: string }): Promise<unknown>\n delete(input: { workspaceId: string; path: string; actor: string }): Promise<unknown>\n}\n\nexport function turnCheckpointPath(turnId: string): string {\n return `/turns/${encodeURIComponent(turnId)}/checkpoint.json`\n}\n\n/** Turn checkpoints in a workspace store, written as `actor`. */\nexport function workspaceTurnCheckpoints(store: CheckpointWorkspaceStore, workspaceId: string, actor: string): TurnCheckpointStore {\n return {\n async save(turnId, continuation) {\n const path = turnCheckpointPath(turnId)\n const current = await store.get(workspaceId, path)\n await store.put({ workspaceId, path, kind: 'file', ifRevision: current?.revision ?? null, actor,\n content: JSON.stringify(continuation) })\n },\n async load(turnId) {\n const entry = await store.get(workspaceId, turnCheckpointPath(turnId))\n return entry?.content ? JSON.parse(entry.content) as RouterTurnContinuation : null\n },\n async clear(turnId) {\n await store.delete({ workspaceId, path: turnCheckpointPath(turnId), actor })\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA;AAAA,EACiB;AAAA,EACG;AAAA,OACb;;;ACnBA,SAAS,kBAAkB,MAAoB,UAAgC;AACpF,SAAO,OAAO,OAAO,SAAS;AAC5B,UAAM,OAAO,MAAM;AACnB,QAAI,OAAO,SAAS,YAAY,KAAK,SAAS,WAAW,EAAG,QAAO,KAAK,OAAO,IAAI;AACnF,UAAM,UAAU,IAAI,QAAQ,MAAM,OAAO;AACzC,QAAI,QAAQ,IAAI,kBAAkB,EAAG,QAAO,KAAK,OAAO,IAAI;AAC5D,UAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,IAAI;AAC3C,QAAI,MAAM,aAAa,SAAU,QAAO,KAAK,OAAO,IAAI;AACxD,UAAM,aAAa,MAAM,IAAI,SAAS,IAAI,KAAK,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,YAAY,IAAI,kBAAkB,MAAM,CAAC,CAAC,EAAE,YAAY;AACzH,YAAQ,IAAI,oBAAoB,MAA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,SAAS,MAAM,EAAG,QAAO;AACjE,UAAI,2BAA2B,IAAI,SAAS,QAAQ,IAAI,2BAA2B,KAAK,EAAE,EAAG,QAAO;AACpG,YAAM,aAAa,OAAO,SAAS,QAAQ,IAAI,aAAa,CAAC;AAC7D,YAAM,SAAS,MAAM,OAAO,EAAE,MAAM,MAAM;AAAA,MAAE,CAAC;AAC7C,YAAM,KAAK,OAAO,SAAS,UAAU,KAAK,aAAa,IAAI,KAAK,IAAI,aAAa,KAAM,kBAAkB,IAAI,QAAQ,GAAG,QAAQ,SAAS,MAAM,EAAE;AAAA,IACnJ;AAAA,EACF,IACE;AACJ,SAAO,EAAE,UAAU;AACrB;","names":["outcome"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent-profiles/switch.ts"],"sourcesContent":["/**\n * Chat profile-switch parsing with no dependencies, so browser code can import it without the\n * profile schemas: through the agent-profiles barrel it pulled zod and the schemas into\n * Hospitality's first page (254 KB of its 1,396 KB initial JavaScript, 2026-10-11).\n */\nexport function parseProfileSwitch(text: string): { name: string } | { invalid: true } | null {\n const trimmed = text.trim()\n if (!/^switch\\s+to\\b/i.test(trimmed)) return null\n const match = /^switch[ \\t]+to[ \\t]+([^\\r\\n]+)$/i.exec(trimmed)\n return match?.[1]?.trim() ? { name: match[1].trim() } : { invalid: true }\n}\n\nexport function normalizeProfileName(name: string): string {\n return name.trim().replace(/\\s+/g, ' ').toLowerCase()\n}\n"],"mappings":";AAKO,SAAS,mBAAmB,MAA2D;AAC5F,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,CAAC,kBAAkB,KAAK,OAAO,EAAG,QAAO;AAC7C,QAAM,QAAQ,oCAAoC,KAAK,OAAO;AAC9D,SAAO,QAAQ,CAAC,GAAG,KAAK,IAAI,EAAE,MAAM,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,KAAK;AAC1E;AAEO,SAAS,qBAAqB,MAAsB;AACzD,SAAO,KAAK,KAAK,EAAE,QAAQ,QAAQ,GAAG,EAAE,YAAY;AACtD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stream/turn-buffer.ts"],"sourcesContent":["/**\n * Resumable chat turns — the router-path answer to \"streams resume on\n * disconnect\" (issue #27). A turn's loop events are teed into a store as they\n * stream; the turn keeps running under `ctx.waitUntil` when the client drops;\n * a reconnecting client replays the buffered tail by sequence number and\n * keeps following until the turn completes.\n *\n * POST /chat/stream → pumpBufferedTurn(...) + live NDJSON\n * GET /chat/stream/:turnId → replayTurnEvents({ fromSeq }) → NDJSON\n *\n * Storage is a structural seam ({@link TurnEventStore}); a D1 implementation\n * ships here because that's what Cloudflare products have (KV is unsuitable:\n * eventually consistent cross-isolate). Per-token deltas would mean hundreds\n * of rows per turn, so consecutive text/reasoning deltas are coalesced within\n * a flush window before they are persisted — replay yields slightly chunkier\n * deltas with identical concatenation.\n */\n\nexport type TurnStatus = 'running' | 'complete' | 'error'\n\n/** A running row is a renewable lease, not permanent truth. If the process\n * driving a turn dies before writing a terminal status, reconnect discovery\n * must eventually stop returning that abandoned row. */\nexport const DEFAULT_RUNNING_TURN_LEASE_MS = 5 * 60_000\n\n/** Keep a healthy turn's lease comfortably ahead of expiry without turning\n * per-token streaming into status-write traffic. */\nexport const DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS = 30_000\n\n/** Represent a buffered turn event with a sequence number and serialized event data */\nexport interface BufferedTurnEvent {\n seq: number\n /** The serialized event line (JSON string, no trailing newline). */\n event: string\n}\n\n/** Manage and query turn events and their lifecycle statuses within a scoped event store */\nexport interface TurnEventStore {\n /**\n * Append rows while the turn is live. Implementations must ignore rows that\n * arrive after `setStatus` publishes `complete` or `error`; the terminal\n * status is the replay fence for a detached live projection.\n */\n append(turnId: string, events: BufferedTurnEvent[]): Promise<void>\n read(turnId: string, fromSeq: number): Promise<BufferedTurnEvent[]>\n /** Record turn lifecycle. `scopeId` (a thread/session id) is optional and lets\n * {@link TurnEventStore.listRunning} rediscover this turn after a client reload\n * loses the turnId; stores that don't track scope ignore it. */\n setStatus(turnId: string, status: TurnStatus, scopeId?: string, options?: TurnStatusWriteOptions): Promise<void>\n getStatus(turnId: string): Promise<TurnStatus | null>\n /** Unexpired running turnIds for a scope, newest first — so a reloaded client\n * (clientRunId lost) can find and resume the in-flight turn without reviving\n * a row abandoned by a dead process. Optional: a store records it only if\n * `setStatus` was given a `scopeId`. */\n listRunning?(scopeId: string): Promise<string[]>\n /** Remove one turn's buffered events and keep its status, so a genuine\n * re-stream after a crash starts at seq 0 without interleaving orphaned\n * rows. `runDetachedTurn` requires it to recover a `running` turn. */\n resetEvents?(turnId: string): Promise<void>\n /** Explicitly remove one turn's events and status. Optional so existing\n * custom stores remain source-compatible; the built-in D1 and memory stores\n * provide it. */\n deleteTurn?(turnId: string): Promise<void>\n /** Remove terminal turns whose status was updated before `before` (Unix\n * milliseconds or a Date). Running turns are never eligible. */\n pruneTerminalTurns?(before: number | Date): Promise<number>\n /** Running turns last renewed before `before` (Unix ms), oldest first, at most\n * `limit`: the candidates {@link settleOrphanedTurns} settles. */\n listStaleRunning?(before: number, limit: number): Promise<StaleRunningTurn[]>\n /** The last `count` events of a turn, newest first; a bounded read of the tail. */\n readTail?(turnId: string, count: number): Promise<BufferedTurnEvent[]>\n}\n\n/** A running turn nothing has renewed since `updatedAt`. */\nexport interface StaleRunningTurn {\n turnId: string\n scopeId: string | null\n /** Unix ms of the last status write. */\n updatedAt: number\n /** Set on a plan follow-up claim (`createD1PlanFollowUpGate`), which keeps its own staleness and does not renew. */\n leaseToken?: string | null\n}\n\n/**\n * Settling a stream nothing produces any more. A sweep that ends an orphaned\n * stream must not move it in time, since reports place a stream by its update\n * time, and must not end one whose producer came back meanwhile.\n */\nexport interface TurnStatusWriteOptions {\n /** Keep the row's update time; a new row still takes the current time. */\n preserveUpdatedAt?: boolean\n /** Write only when the row is still `running` and was last updated before this time (Unix ms). */\n onlyIfRunningBefore?: number\n}\n\n/** Configure running-turn lease evaluation. The clock is injectable so store\n * contract tests do not sleep. Keep the default in production unless a\n * deployment also tunes the buffer's renewal interval. */\nexport interface TurnEventStoreOptions {\n runningTurnLeaseMs?: number\n now?: () => number\n}\n\n// ── coalescing ────────────────────────────────────────────────────────────\n\ntype AnyRecord = Record<string, unknown>\n\nfunction deltaTypeOf(ev: unknown): 'text' | 'reasoning' | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? (e.event as AnyRecord | undefined) : e) as AnyRecord | undefined\n if (!inner || typeof inner !== 'object') return null\n if ((inner.type === 'text' || inner.type === 'reasoning') && typeof inner.text === 'string') {\n return inner.type\n }\n return null\n}\n\nfunction innerOf(ev: unknown): AnyRecord | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? e.event : e) as AnyRecord | undefined\n return inner && typeof inner === 'object' ? inner : null\n}\n\n/**\n * The key of a live-state event whose latest value supersedes earlier ones:\n * the model-processing heartbeat, and a harness's raw update of a text or\n * reasoning part (it carries the part's whole state, keyed by part id). Null\n * for every other event.\n */\nfunction liveStateKeyOf(ev: unknown): string | null {\n const inner = innerOf(ev)\n if (!inner) return null\n if (inner.type === 'model-processing') return 'model-processing'\n if (inner.type !== 'raw') return null\n const raw = (inner.data as AnyRecord | undefined)?.event as AnyRecord | undefined\n const part = raw?.part as AnyRecord | undefined\n if ((raw?.type === 'text' || raw?.type === 'reasoning') && typeof part?.id === 'string') return `raw:${part.id}`\n return null\n}\n\n/** Whether an event only projects live progress, so it may wait for the flush window and be coalesced. */\nexport function isLiveProgressEvent(ev: unknown): boolean {\n return deltaTypeOf(ev) !== null || liveStateKeyOf(ev) !== null\n}\n\n/**\n * Merge text and reasoning deltas of the same type into one event, across the\n * live-state events a harness interleaves with them, and keep only the latest\n * of each live-state event. A reasoning model streams three events per token\n * (its raw part update, a model-processing heartbeat and the delta); merging\n * only adjacent deltas wrote all three as rows (2026-10-10: 1.63 M rows in a\n * day, 59,659 in one turn). Any other event is a boundary nothing merges\n * across. Concatenation-preserving: replaying the coalesced stream produces\n * the same accumulated text, and the latest state of every part.\n */\nexport function coalesceDeltas(events: unknown[]): unknown[] {\n const out: unknown[] = []\n let run: { type: 'text' | 'reasoning'; index: number } | null = null\n let stateSlots = new Map<string, number>()\n for (const ev of events) {\n const type = deltaTypeOf(ev)\n if (type) {\n if (run && run.type === type) {\n const merged = JSON.parse(JSON.stringify(out[run.index])) as AnyRecord\n innerOf(merged)!.text = String(innerOf(out[run.index])!.text) + String(innerOf(ev)!.text)\n out[run.index] = merged\n } else {\n out.push(ev)\n run = { type, index: out.length - 1 }\n }\n continue\n }\n const key = liveStateKeyOf(ev)\n if (key) {\n const slot = stateSlots.get(key)\n if (slot === undefined) {\n out.push(ev)\n stateSlots.set(key, out.length - 1)\n } else {\n out[slot] = ev\n }\n continue\n }\n out.push(ev)\n run = null\n stateSlots = new Map()\n }\n return out\n}\n\nfunction asPartUpdate(ev: unknown): { partId: unknown; delta: unknown } | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object' || e.type !== 'message.part.updated') return null\n const data = e.data as AnyRecord | undefined\n if (!data || typeof data !== 'object') return null\n const part = data.part as AnyRecord | undefined\n const partId = part?.id ?? data.partId ?? part?.partId ?? null\n return { partId, delta: data.delta }\n}\n\n/**\n * Coalesce consecutive `message.part.updated` deltas for the SAME part into one\n * event. agent-runtime products stream `ChatStreamEvent` NDJSON\n * (`{type:'message.part.updated', data:{part, delta}}`); pumped through the\n * buffer with the default tool-loop coalescer, every per-token delta persists as\n * its own row because that coalescer never recognizes the shape. Pass this as\n * {@link PumpBufferedTurnOptions.coalesce} instead.\n *\n * Concatenation-preserving for BOTH consumer styles: the merged event keeps the\n * LATEST event's `data.part` (already the cumulative accumulation) and sets\n * `data.delta` to the concatenation of the merged deltas, so a client that\n * appends `delta` and one that reads the cumulative `part` both reconstruct the\n * identical final text.\n */\nexport function coalesceChatStreamEvents(events: unknown[]): unknown[] {\n const out: unknown[] = []\n for (const ev of events) {\n const cur = asPartUpdate(ev)\n const prevEv = out[out.length - 1]\n const prev = prevEv ? asPartUpdate(prevEv) : null\n if (cur && prev && cur.partId != null && cur.partId === prev.partId) {\n // Base the merged row on the latest event (its `part` is the most complete\n // accumulation); carry forward the summed delta.\n const merged = JSON.parse(JSON.stringify(ev)) as AnyRecord\n ;(merged.data as AnyRecord).delta = String(prev.delta ?? '') + String(cur.delta ?? '')\n out[out.length - 1] = merged\n continue\n }\n out.push(ev)\n }\n return out\n}\n\n// ── buffering core (the tap) ────────────────────────────────────────────────\n\n/** Define options for buffering and flushing turn events with optional live client delivery and event coalescing */\nexport interface BufferedTurnOptions {\n store: TurnEventStore\n turnId: string\n /** Deliver one serialized line to the live client. Throwing here (client\n * disconnected) does NOT stop buffering — events keep persisting. */\n write?: (line: string) => Promise<void> | void\n /** Flush buffered events to the store at most this often. Default 400ms. */\n flushIntervalMs?: number\n /** Flush window once a durable owner has taken the turn ({@link BufferedTurnTap.detach}). Live-progress events\n * wait for it; any other event flushes at once, after them. Default 2000ms. */\n detachedFlushIntervalMs?: number\n /** Per-flush coalescer. Default {@link coalesceDeltas} (tool-loop text/reasoning\n * deltas). agent-runtime products streaming `ChatStreamEvent` pass\n * {@link coalesceChatStreamEvents} so per-token deltas don't each persist as a\n * row. Must be concatenation-preserving. */\n coalesce?: (events: unknown[]) => unknown[]\n /** Optional scope (thread/session id) recorded with the turn status, so\n * {@link TurnEventStore.listRunning} can find this turn after a reload. */\n scopeId?: string\n /** How often to renew the running-turn lease while a producer is alive.\n * The timer is backed up by event-driven renewal when a runtime freezes\n * unreferenced timers during remote I/O. Default\n * {@link DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS}. */\n runningTurnRenewIntervalMs?: number\n}\n\n/** A push-driven buffer for a turn whose producer the caller does NOT own. */\nexport interface BufferedTurnTap {\n /** Buffer one event: persist (coalesced, on the flush window) + best-effort\n * live-deliver. Wire to a push source's per-event hook (e.g. agent-runtime\n * `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call. */\n onEvent(raw: unknown): Promise<void>\n /** Settle the turn: final flush + set status. Call after the producer resolves\n * ('complete') or rejects ('error'). 'error' flushes what was produced first. */\n done(status?: Extract<TurnStatus, 'complete' | 'error'>): Promise<void>\n /**\n * Give terminal-status ownership to an external durable runner. Stops this\n * tap's running-lease renewal and flushes its current projection, but keeps\n * `onEvent` available as an append-only live-observation path. After the\n * handoff, an event that is not live progress (a marker, interaction, tool\n * event, error or terminal event) flushes before `onEvent` returns, so a\n * durable owner cannot publish terminal status ahead of it; live progress\n * (deltas, heartbeats, raw part updates) is coalesced over\n * `detachedFlushIntervalMs`. Call it again when observation ends to flush any\n * final event.\n *\n * A caller MUST have registered that durable owner before detaching: this\n * method intentionally writes no replacement status.\n */\n detach(): Promise<void>\n}\n\n/**\n * The buffering core. Sequence-numbers every event, delivers it to `write`\n * (best-effort — a disconnected client never stops buffering), and flushes to\n * the store in coalesced batches. Drives both transports:\n *\n * • {@link pumpBufferedTurn} — when you OWN an `AsyncIterable` producer.\n * • this tap (`onEvent`/`done`) — when the producer owns iteration and only\n * hands you a push callback (agent-runtime `handleChatTurn`'s `hooks.onEvent`\n * + the finished body). Durability stays here in the shell; the engine needs\n * no `TurnEventStore` seam.\n */\n/** Serialized characters of pending events that force a flush before the window ends. */\nconst MAX_PENDING_CHARS = 64 * 1024\n\nexport function createBufferedTurnTap(opts: BufferedTurnOptions): BufferedTurnTap {\n const flushIntervalMs = opts.flushIntervalMs ?? 400\n const detachedFlushIntervalMs = opts.detachedFlushIntervalMs ?? 2000\n let pendingChars = 0\n const coalesce = opts.coalesce ?? coalesceDeltas\n const startedAt = Date.now()\n let seq = 0\n let clientGone = false\n let pending: unknown[] = []\n let lastFlush = Date.now()\n let started = false\n let settled = false\n let detached = false\n let renewalTimer: ReturnType<typeof setTimeout> | undefined\n let renewal: Promise<void> = Promise.resolve()\n let lastRenewedAt = 0\n const runningTurnRenewIntervalMs = Math.max(\n 1,\n opts.runningTurnRenewIntervalMs ?? DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,\n )\n\n function clearRenewalTimer(): void {\n if (renewalTimer !== undefined) clearTimeout(renewalTimer)\n renewalTimer = undefined\n }\n\n function scheduleRenewal(): void {\n if (settled || detached || !opts.scopeId) return\n clearRenewalTimer()\n const elapsedMs = Math.max(0, Date.now() - lastRenewedAt)\n const delayMs = Math.max(1, runningTurnRenewIntervalMs - elapsedMs)\n renewalTimer = setTimeout(() => {\n renewalTimer = undefined\n void renewLease()\n }, delayMs)\n // A deliberately abandoned tap in a Node test must not keep the process\n // alive until the production renewal interval elapses.\n if (typeof renewalTimer === 'object' && 'unref' in renewalTimer) {\n renewalTimer.unref()\n }\n }\n\n async function renewLease(): Promise<void> {\n if (settled || detached || !opts.scopeId) return\n clearRenewalTimer()\n lastRenewedAt = Date.now()\n renewal = renewal\n .then(() => opts.store.setStatus(opts.turnId, 'running', opts.scopeId))\n .catch(() => {})\n await renewal\n scheduleRenewal()\n }\n\n async function flush(): Promise<void> {\n if (pending.length === 0) return\n const batch = coalesce(pending)\n pending = []\n pendingChars = 0\n const rows = batch.map((ev) => ({ seq: ++seq, event: JSON.stringify(ev) }))\n await opts.store.append(opts.turnId, rows)\n lastFlush = Date.now()\n }\n\n async function ensureStarted(): Promise<void> {\n if (started) return\n started = true\n // An external durable owner may have detached before the first observed\n // event. It owns status from that point, so this tap must never resurrect\n // its running lease.\n if (detached) return\n await opts.store.setStatus(opts.turnId, 'running', opts.scopeId)\n lastRenewedAt = Date.now()\n scheduleRenewal()\n }\n\n return {\n async onEvent(raw) {\n await ensureStarted()\n // Cloudflare may freeze an unreferenced timer while a producer is\n // awaiting remote I/O. A real event (including the route heartbeat)\n // therefore also renews any lease whose interval has elapsed.\n if (\n !detached &&\n opts.scopeId &&\n Date.now() - lastRenewedAt >= runningTurnRenewIntervalMs\n ) {\n await renewLease()\n }\n // Stamp ms-since-turn-start so any stored turn is replayable AND traceable\n // (see ../trace) from the same buffered rows.\n const ev = raw && typeof raw === 'object' ? { ...(raw as Record<string, unknown>), _t: Date.now() - startedAt } : raw\n const line = JSON.stringify(ev)\n pending.push(ev)\n pendingChars += line?.length ?? 0\n if (!clientGone && opts.write) {\n try {\n // Live delivery carries a provisional ordering hint, not the persisted\n // seq (coalescing changes seq assignment); clients resume with the\n // seqs from replay, or 0 for \"everything\".\n await opts.write(line)\n } catch {\n clientGone = true\n }\n }\n // Once detached, a turn marker, interaction, tool event, error or terminal event persists at once (with the\n // progress before it), and live progress waits for the window, so a reasoning model's per-token events do\n // not each become a row. An external owner's terminal status can fence at most the last window of progress.\n const due = detached\n ? !isLiveProgressEvent(ev) || Date.now() - lastFlush >= detachedFlushIntervalMs\n : Date.now() - lastFlush >= flushIntervalMs\n if (due || pendingChars >= MAX_PENDING_CHARS) await flush()\n },\n async done(status = 'complete') {\n await ensureStarted()\n if (detached) {\n await flush()\n return\n }\n settled = true\n clearRenewalTimer()\n await renewal\n if (status === 'error') {\n await flush().catch(() => {})\n await opts.store.setStatus(opts.turnId, 'error', opts.scopeId).catch(() => {})\n return\n }\n await flush()\n await opts.store.setStatus(opts.turnId, 'complete', opts.scopeId)\n },\n async detach() {\n detached = true\n clearRenewalTimer()\n // A renewal already queued before detach may be writing `running`. Wait\n // for it before returning so the durable owner can safely publish a\n // terminal status after the awaited handoff.\n await renewal\n await flush()\n },\n }\n}\n\n// ── pump (producer side) ──────────────────────────────────────────────────\n\n/** Define options to pump data from an asynchronous iterable source with buffered turn control */\nexport interface PumpBufferedTurnOptions extends BufferedTurnOptions {\n source: AsyncIterable<unknown>\n}\n\n/**\n * Drive a turn to completion regardless of the live client, when you OWN the\n * producer as an `AsyncIterable`. A thin driver over {@link createBufferedTurnTap}.\n * Returns a promise that resolves when the turn finishes — hand it to\n * `ctx.waitUntil` so a disconnect can't kill the turn. Never rejects on\n * client-write failure; a source error marks the turn 'error' (after flushing\n * what was produced) and rethrows.\n */\nexport async function pumpBufferedTurn(opts: PumpBufferedTurnOptions): Promise<void> {\n const tap = createBufferedTurnTap(opts)\n try {\n for await (const raw of opts.source) await tap.onEvent(raw)\n await tap.done('complete')\n } catch (err) {\n await tap.done('error')\n throw err\n }\n}\n\n// ── replay (consumer side) ────────────────────────────────────────────────\n\n/** Define options for replaying turn events with control over sequence, polling, and timeout */\nexport interface ReplayTurnEventsOptions {\n store: TurnEventStore\n turnId: string\n /** Replay strictly after this sequence number (0 = from the beginning). */\n fromSeq?: number\n /** Poll cadence while the turn is still running. Default 500ms. */\n pollMs?: number\n /** Give up following a 'running' turn after this long. Default 120s. */\n timeoutMs?: number\n}\n\n/**\n * Yield buffered events after `fromSeq`, then keep polling while the turn is\n * still 'running' until it completes, errors, or times out. Terminates with a\n * final `{seq: -1, event: '{\"type\":\"turn_status\",...}'}` marker so clients\n * know why the replay ended.\n */\nexport async function* replayTurnEvents(opts: ReplayTurnEventsOptions): AsyncGenerator<BufferedTurnEvent> {\n const pollMs = opts.pollMs ?? 500\n const timeoutMs = opts.timeoutMs ?? 120_000\n let cursor = opts.fromSeq ?? 0\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n const batch = await opts.store.read(opts.turnId, cursor)\n for (const row of batch) {\n cursor = Math.max(cursor, row.seq)\n yield row\n }\n const status = await opts.store.getStatus(opts.turnId)\n if (status !== 'running') {\n // Writers flush before publishing terminal status; include rows committed after the first read.\n yield* await opts.store.read(opts.turnId, cursor)\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: status ?? 'unknown' }) }\n return\n }\n if (Date.now() >= deadline) {\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: 'timeout' }) }\n return\n }\n await new Promise((r) => setTimeout(r, pollMs))\n }\n}\n\n/**\n * Serialize a replayed row for the wire, stamping the buffer ordinal ONTO the\n * line so a reconnecting client can continue from `?fromSeq=<lastSeq>`.\n *\n * The seq lives on the {@link BufferedTurnEvent} row wrapper, not inside the\n * serialized event — `flush()` builds `{seq: ++seq, event: JSON.stringify(ev)}`.\n * A route that enqueues `row.event` alone therefore emits lines with no seq at\n * all, and every client cursor silently pins to 0: each reconnect refetches the\n * whole turn and re-applies every delta onto already-rendered state. This\n * restores the contract `web-react/chat-stream` already documents (\"replayed\n * lines carry an extra `seq` — transparently ignored\").\n *\n * The `{seq: -1}` `turn_status` sentinel is passed through unstamped: it is a\n * terminator, not a cursor position, and stamping it would move a client's\n * cursor to -1.\n *\n * Fail-soft by construction — a line that is not a JSON object passes through\n * verbatim. A stamping bug must degrade to today's behaviour, never break a\n * replay.\n */\nexport function stampReplaySeq(row: BufferedTurnEvent): string {\n if (row.seq <= 0) return row.event\n const line = row.event\n // Cheap splice instead of parse+stringify: these rows are already canonical\n // JSON objects from `JSON.stringify`, and replay is a hot per-event path.\n if (line.charCodeAt(0) !== 0x7b /* { */) return line\n const rest = line.slice(1)\n return rest.trimStart().startsWith('}')\n ? `{\"seq\":${row.seq}${rest}`\n : `{\"seq\":${row.seq},${rest}`\n}\n\n// ── D1 store ──────────────────────────────────────────────────────────────\n\n/** A bound D1 statement used by the turn store. */\nexport interface D1BoundForTurns {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n first<T = Record<string, unknown>>(): Promise<T | null>\n}\n\n/** Minimal structural D1 contract (Cloudflare `D1Database` satisfies it). */\nexport interface D1LikeForTurns {\n prepare(sql: string): {\n bind(...values: unknown[]): D1BoundForTurns\n }\n /** D1's only atomic primitive. Retention refuses a driver without it rather\n * than deleting events and status in separate, reorderable requests. */\n batch?(statements: D1BoundForTurns[]): Promise<unknown[]>\n}\n\nfunction normalizeTurnCutoff(before: number | Date): { milliseconds: number; iso: string } {\n const milliseconds = before instanceof Date ? before.getTime() : before\n if (!Number.isFinite(milliseconds)) {\n throw new RangeError('turn retention cutoff must be a finite Unix-millisecond timestamp or a valid Date')\n }\n const date = new Date(milliseconds)\n if (!Number.isFinite(date.getTime())) {\n throw new RangeError('turn retention cutoff is outside the supported Date range')\n }\n return { milliseconds, iso: date.toISOString() }\n}\n\nasync function runAtomicTurnBatch(\n db: D1LikeForTurns,\n statements: D1BoundForTurns[],\n): Promise<unknown[]> {\n if (typeof db.batch !== 'function') {\n throw new Error('turn retention requires D1 batch() for atomic deletion')\n }\n return db.batch(statements)\n}\n\nfunction changesFromD1Result(result: unknown): number {\n if (!result || typeof result !== 'object') return 0\n const meta = (result as { meta?: unknown }).meta\n if (meta && typeof meta === 'object') {\n const changes = (meta as { changes?: unknown }).changes\n if (typeof changes === 'number' && Number.isFinite(changes)) return changes\n }\n const changes = (result as { changes?: unknown }).changes\n return typeof changes === 'number' && Number.isFinite(changes) ? changes : 0\n}\n\n/** Schema for the D1 store — append to the product's migrations. */\nexport const TURN_EVENTS_MIGRATION_SQL = `\nCREATE TABLE IF NOT EXISTS turn_events (\n turnId TEXT NOT NULL,\n seq INTEGER NOT NULL,\n event TEXT NOT NULL,\n PRIMARY KEY (turnId, seq)\n);\nCREATE TABLE IF NOT EXISTS turn_status (\n turnId TEXT PRIMARY KEY,\n status TEXT NOT NULL,\n scopeId TEXT,\n updatedAt TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_turn_status_scope ON turn_status (scopeId, status);\nCREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);\n`\n\n/** For deployments whose `turn_status` table predates `scopeId`/`listRunning` —\n * run once to add the column (the CREATE above already includes it for new\n * deployments). SQLite ignores a duplicate-add error if already applied. */\nexport const TURN_STATUS_SCOPE_MIGRATION_SQL = `ALTER TABLE turn_status ADD COLUMN scopeId TEXT;`\n\n/** Run once before using `createD1PlanFollowUpGate`: it adds the lease column\n * the gate fences its claims on. Stores that never take follow-up claims do\n * not need it, so the base turn tables leave it out. */\nexport const TURN_STATUS_LEASE_MIGRATION_SQL = 'ALTER TABLE turn_status ADD COLUMN leaseToken TEXT;'\n\n/** For deployments that already have the turn tables, add the index used by\n * terminal-turn retention without rerunning the table migration. */\nexport const TURN_STATUS_RETENTION_MIGRATION_SQL = 'CREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);'\n\n/** Resolve a TurnEventStore that appends and reads turn events using a D1-like database interface */\n/** 100 D1 variables per statement, three per row. */\nconst D1_APPEND_CHUNK = 33\n\nexport function createD1TurnEventStore(\n db: D1LikeForTurns,\n options: TurnEventStoreOptions = {},\n): TurnEventStore {\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, events) {\n if (!events.length) return\n // One multi-row insert per flush window keeps write volume bounded, but\n // D1 caps a statement at 100 bound variables, so a burst of more than 33\n // events (a subagent finishing, a long tool result) failed the whole\n // flush with `D1_ERROR: too many SQL variables` and killed the turn.\n // Rows are appended in order across chunks; a partial failure leaves a\n // prefix, which the ordered `seq` column already tolerates on replay.\n for (let start = 0; start < events.length; start += D1_APPEND_CHUNK) {\n const chunk = events.slice(start, start + D1_APPEND_CHUNK)\n const placeholders = chunk.map(() => '(?, ?, ?)').join(', ')\n const values = chunk.flatMap((e) => [turnId, e.seq, e.event])\n await db\n .prepare(\n `WITH pending(turnId, seq, event) AS (VALUES ${placeholders})\n INSERT OR IGNORE INTO turn_events (turnId, seq, event)\n SELECT pending.turnId, pending.seq, pending.event\n FROM pending\n WHERE NOT EXISTS (\n SELECT 1 FROM turn_status\n WHERE turn_status.turnId = pending.turnId\n AND turn_status.status IN ('complete', 'error')\n )`,\n )\n .bind(...values)\n .run()\n }\n },\n async read(turnId, fromSeq) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? AND seq > ? ORDER BY seq ASC')\n .bind(turnId, fromSeq)\n .all<{ seq: number; event: string }>()\n return results\n },\n async setStatus(turnId, status, scopeId, options = {}) {\n const at = new Date(now()).toISOString()\n if (options.onlyIfRunningBefore !== undefined) {\n // A guarded write never creates a row: it settles one that exists, is running and is stale.\n await db\n .prepare(\n `UPDATE turn_status SET status = ?, scopeId = COALESCE(?, scopeId)${options.preserveUpdatedAt ? '' : ', updatedAt = ?'} WHERE turnId = ? AND status = 'running' AND updatedAt < ?`,\n )\n .bind(...[status, scopeId ?? null, ...(options.preserveUpdatedAt ? [] : [at]), turnId, new Date(options.onlyIfRunningBefore).toISOString()])\n .run()\n return\n }\n // COALESCE preserves a scopeId set on the initial 'running' write when a\n // later 'complete'/'error' write passes none.\n await db\n .prepare(\n `INSERT INTO turn_status (turnId, status, scopeId, updatedAt) VALUES (?, ?, ?, ?) ON CONFLICT(turnId) DO UPDATE SET status = excluded.status, scopeId = COALESCE(excluded.scopeId, turn_status.scopeId)${options.preserveUpdatedAt ? '' : ', updatedAt = excluded.updatedAt'}`,\n )\n .bind(turnId, status, scopeId ?? null, at)\n .run()\n },\n async getStatus(turnId) {\n const row = await db.prepare('SELECT status FROM turn_status WHERE turnId = ?').bind(turnId).first<{ status: TurnStatus }>()\n return row?.status ?? null\n },\n async listRunning(scopeId) {\n const { results } = await db\n .prepare(\n \"SELECT turnId FROM turn_status WHERE scopeId = ? AND status = 'running' AND updatedAt >= ? ORDER BY updatedAt DESC, rowid DESC\",\n )\n .bind(scopeId, new Date(now() - runningTurnLeaseMs).toISOString())\n .all<{ turnId: string }>()\n return results.map((r) => r.turnId)\n },\n async resetEvents(turnId) {\n await db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId).run()\n },\n async deleteTurn(turnId) {\n await runAtomicTurnBatch(db, [\n db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId),\n db.prepare('DELETE FROM turn_status WHERE turnId = ?').bind(turnId),\n ])\n },\n async listStaleRunning(before, limit) {\n const { results } = await db\n // `*` so a deployment that applied TURN_STATUS_LEASE_MIGRATION_SQL also returns its follow-up claims' leaseToken.\n .prepare(\"SELECT * FROM turn_status WHERE status = 'running' AND updatedAt < ? ORDER BY updatedAt ASC LIMIT ?\")\n .bind(new Date(before).toISOString(), Math.max(1, Math.floor(limit)))\n .all<{ turnId: string; scopeId: string | null; updatedAt: string; leaseToken?: string | null }>()\n return results.map((row) => ({\n turnId: row.turnId,\n scopeId: row.scopeId ?? null,\n updatedAt: Date.parse(row.updatedAt),\n ...(row.leaseToken ? { leaseToken: row.leaseToken } : {}),\n }))\n },\n async readTail(turnId, count) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? ORDER BY seq DESC LIMIT ?')\n .bind(turnId, Math.max(1, Math.floor(count)))\n .all<{ seq: number; event: string }>()\n return results\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before)\n const terminalBefore = \"status IN ('complete', 'error') AND updatedAt < ?\"\n const results = await runAtomicTurnBatch(db, [\n db\n .prepare(\n `DELETE FROM turn_events WHERE turnId IN (SELECT turnId FROM turn_status WHERE ${terminalBefore})`,\n )\n .bind(cutoff.iso),\n db.prepare(`DELETE FROM turn_status WHERE ${terminalBefore}`).bind(cutoff.iso),\n ])\n return changesFromD1Result(results[1])\n },\n }\n}\n\n/** In-memory store for tests and keyless local dev. */\nexport function createMemoryTurnEventStore(\n options: TurnEventStoreOptions = {},\n): TurnEventStore {\n const events = new Map<string, BufferedTurnEvent[]>()\n const status = new Map<string, TurnStatus>()\n const scopes = new Map<string, string>()\n const order: string[] = []\n const updatedAt = new Map<string, number>()\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, rows) {\n if (status.get(turnId) === 'complete' || status.get(turnId) === 'error') return\n const list = events.get(turnId) ?? []\n list.push(...rows)\n events.set(turnId, list)\n },\n async read(turnId, fromSeq) {\n return (events.get(turnId) ?? []).filter((e) => e.seq > fromSeq)\n },\n async setStatus(turnId, s, scopeId, options = {}) {\n if (options.onlyIfRunningBefore !== undefined) {\n const stale = status.get(turnId) === 'running' && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < options.onlyIfRunningBefore\n if (!stale) return\n }\n const existed = status.has(turnId)\n status.set(turnId, s)\n if (scopeId) scopes.set(turnId, scopeId)\n if (!order.includes(turnId)) order.push(turnId)\n if (!(options.preserveUpdatedAt && existed)) updatedAt.set(turnId, now())\n },\n async getStatus(turnId) {\n return status.get(turnId) ?? null\n },\n async listRunning(scopeId) {\n const cutoff = now() - runningTurnLeaseMs\n return order\n .filter(\n (turnId) =>\n status.get(turnId) === 'running' &&\n scopes.get(turnId) === scopeId &&\n (updatedAt.get(turnId) ?? Number.NEGATIVE_INFINITY) >= cutoff,\n )\n .sort((left, right) => {\n const updatedDelta = (updatedAt.get(right) ?? 0) - (updatedAt.get(left) ?? 0)\n return updatedDelta || order.indexOf(right) - order.indexOf(left)\n })\n },\n async resetEvents(turnId) {\n events.delete(turnId)\n },\n async deleteTurn(turnId) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n const index = order.indexOf(turnId)\n if (index >= 0) order.splice(index, 1)\n },\n async listStaleRunning(before, limit) {\n return order\n .filter((turnId) => status.get(turnId) === 'running' && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < before)\n .sort((left, right) => (updatedAt.get(left) ?? 0) - (updatedAt.get(right) ?? 0))\n .slice(0, Math.max(1, Math.floor(limit)))\n .map((turnId) => ({ turnId, scopeId: scopes.get(turnId) ?? null, updatedAt: updatedAt.get(turnId)! }))\n },\n async readTail(turnId, count) {\n return (events.get(turnId) ?? []).slice(-Math.max(1, Math.floor(count))).reverse()\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before).milliseconds\n const removable = order.filter((turnId) => {\n const s = status.get(turnId)\n return (s === 'complete' || s === 'error') && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < cutoff\n })\n for (const turnId of removable) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n }\n if (removable.length) {\n const removed = new Set(removable)\n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AC,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC,CAAC,EAAE,QAAQ;AAAA,IACnF;AAAA,IACA,MAAM,mBAAmB,QAAQ;AAC/B,YAAM,SAAS,oBAAoB,MAAM,EAAE;AAC3C,YAAM,YAAY,MAAM,OAAO,CAAC,WAAW;AACzC,cAAM,IAAI,OAAO,IAAI,MAAM;AAC3B,gBAAQ,MAAM,cAAc,MAAM,aAAa,UAAU,IAAI,MAAM,KAAK,OAAO,qBAAqB;AAAA,MACtG,CAAC;AACD,iBAAW,UAAU,WAAW;AAC9B,eAAO,OAAO,MAAM;AACpB,eAAO,OAAO,MAAM;AACpB,eAAO,OAAO,MAAM;AACpB,kBAAU,OAAO,MAAM;AAAA,MACzB;AACA,UAAI,UAAU,QAAQ;AACpB,cAAM,UAAU,IAAI,IAAI,SAAS;AACjC,iBAAS,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;AAC1C,cAAI,QAAQ,IAAI,MAAM,CAAC,CAAE,EAAG,OAAM,OAAO,GAAG,CAAC;AAAA,QAC/C;AAAA,MACF;AACA,aAAO,UAAU;AAAA,IACnB;AAAA,EACF;AACF;","names":["changes","options"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/launch-invariants/catalog.ts"],"sourcesContent":["/**\n * The launch invariants every agent app holds, and the budgets they are held to.\n *\n * Each one is a failure GTM shipped to production on 2026-10-10 and fixed by\n * hand. They are listed here once so every app checks the same rule with the\n * same numbers, and `agent-app-invariants` reports each by its id.\n */\n\n/** Budgets the invariants are measured against. */\nexport const LAUNCH_BUDGETS = {\n /** Most bytes one query may return in a scheduled job or report route: one sized batch with room for its listing. */\n queryBytes: 8 * 1024 * 1024,\n /** Most the live heap may grow while one scheduled job runs on a day-sized fixture. */\n heapGrowthBytes: 40 * 1024 * 1024,\n /** Most bytes of a large column one sized read returns; a single larger row is read alone. */\n sizedReadBytes: 4 * 1024 * 1024,\n /** Most stored events one long turn may write. */\n turnEvents: 5_000,\n /** A turn whose owner stopped reaches its terminal state within this long. */\n settleWithinMs: 15 * 60_000,\n /** Turn recovery and orphan settlement run at least this often. */\n recoveryEveryMs: 15 * 60_000,\n /** Longest a cached auth lookup may be served while the store cannot answer. */\n authCacheTtlMs: 60_000,\n /** A platform-limit alarm fires at this share of the limit. */\n alarmRatio: 0.8,\n /** A Worker isolate's memory. */\n workerMemoryBytes: 128 * 1024 * 1024,\n /** Rows one D1 query may read before an alarm; a sized read stays far below it (GTM's 1.63 M-event scan overloaded D1). */\n d1RowsPerQuery: 250_000,\n /** A workspace box's disk: the Sandbox SDK's default tier (10 GB). */\n sandboxDiskBytes: 10 * 1024 ** 3,\n /** Platform snapshots per box; the cap GTM hit on 2026-10-10. */\n snapshotCount: 25,\n /** Operator key requests per minute. */\n keyRatePerMinute: 60,\n /** Hours one resource's limit alarm waits before it repeats. */\n alarmRepeatHours: 6,\n /** Cloudflare's gzip limit on a Worker's Total Upload on the paid plan, in KiB; Legal deployed 9,659 KiB (94%) on 2026-10-19. */\n workerUploadGzipKiB: 10 * 1024,\n /** Cloudflare's raw limit on a Worker's Total Upload, in KiB. */\n workerUploadRawKiB: 64 * 1024,\n} as const\n\nexport type LaunchInvariantId =\n | 'bounded-reads'\n | 'memory-budget'\n | 'isolated-jobs'\n | 'honest-settlement'\n | 'coalesced-events'\n | 'auth-survives-d1-stall'\n | 'authorize-before-stream'\n | 'limit-alarms'\n | 'pasted-code-reaches-chat'\n\nexport interface LaunchInvariant {\n id: LaunchInvariantId\n title: string\n /** The rule, as the conformance report states it. */\n rule: string\n /** The production failure the rule answers. */\n incident: string\n}\n\nexport const LAUNCH_INVARIANTS: readonly LaunchInvariant[] = [\n {\n id: 'bounded-reads',\n title: 'Bounded reads',\n rule: 'No query in a scheduled job or report route returns more than 8 MB; large columns are read in sized batches of at most 4 MB.',\n incident: 'GTM turn health read 500 replies with their parts (122 MB of a 128 MB Worker); the reliability report scanned 1.63 M events and overloaded D1.',\n },\n {\n id: 'memory-budget',\n title: 'Memory budget',\n rule: 'Every scheduled job runs on a day-sized fixture with live-heap growth of at most 40 MB, and every scheduled job is covered.',\n incident: 'GTM sweeps exceeded the Worker\\'s 128 MB six times; a regex slice kept in a Map pinned whole tool outputs.',\n },\n {\n id: 'isolated-jobs',\n title: 'Isolated scheduled jobs',\n rule: 'Each scheduled invocation runs exactly one job, and turn recovery and orphan settlement run at least every 15 minutes.',\n incident: 'At 21:00Z turn health ran out of memory while the hourly sweeps shared one run, and none of the eight queued after it ran.',\n },\n {\n id: 'honest-settlement',\n title: 'Honest turn settlement',\n rule: 'Every turn reaches exactly one terminal state (an answer, a typed failure with Retry, or a Stop counted on its own) within 15 minutes of its owner stopping; failures are attributed to the request time, and a completed run with an aborted tool is a failure.',\n incident: 'Stale running rows (51 settled by hand), failure notices 8–11 h late, and completions with aborted tools counted as answers.',\n },\n {\n id: 'coalesced-events',\n title: 'Coalesced turn events',\n rule: 'A recorded long turn stores at most 5,000 events: text and reasoning deltas are merged before storage.',\n incident: 'A reasoning model wrote 59,659 events in one turn and 1.63 M in a day.',\n },\n {\n id: 'auth-survives-d1-stall',\n title: 'Auth survives a D1 stall',\n rule: 'A key or session verified within 60 s keeps working while D1 errors or stalls; the cache is used only then, never past revoke or expiry, and is keyed by SHA-256.',\n incident: 'An overloaded D1 failed sign-in and API-key checks for credentials that were valid moments before.',\n },\n {\n id: 'authorize-before-stream',\n title: 'Authorization before any stream',\n rule: 'A refused request gets a plain response; no stream opens and no product state is touched before authorization resolves.',\n incident: 'agent-app 0.60.48–0.60.49 opened a progress-first stream before authorize ran.',\n },\n {\n id: 'limit-alarms',\n title: 'Platform-limit alarms at 80%',\n rule: 'Worker memory, D1 rows per query, sandbox disk, snapshot count and key rate each have a declared limit and an alarm that fires at 80%.',\n incident: '19 platform-limit events on 2026-10-10, each found after it failed a customer.',\n },\n {\n id: 'pasted-code-reaches-chat',\n title: 'Pasted code reaches the chat',\n rule: 'An authenticated chat message carrying pasted code (shell, SQL, markup) gets the route\\'s normal response; no app filter, sanitizer or edge rule refuses it.',\n incident: 'On 2026-10-11 a chat message containing `cat /etc/passwd` got Cloudflare\\'s 403 block page from gtm.tangle.tools instead of reaching the Worker.',\n },\n]\n\n/** The invariant ids in report order. */\nexport const LAUNCH_INVARIANT_IDS: readonly LaunchInvariantId[] = LAUNCH_INVARIANTS.map((invariant) => invariant.id)\n\n/** One checked outcome of one invariant, for one subject (a job, a route, a scenario). */\nexport interface InvariantVerdict {\n invariant: LaunchInvariantId\n /** What was checked: a job name, a route, a scenario. */\n subject: string\n pass: boolean\n /** Findings, one line each. On a pass, what was proven. */\n details: string[]\n /** Measurements behind the verdict, for the report. */\n data?: Record<string, unknown>\n /**\n * Set when the app recorded this failure as known, with why and who owns the\n * fix. The report counts it as not holding; it does not fail the suite.\n */\n knownFailing?: string\n}\n\n/** A verdict whose message names every finding, for a test runner's failure output. */\nexport function describeVerdict(verdict: InvariantVerdict): string {\n const head = `${verdict.pass ? 'PASS' : 'FAIL'} ${verdict.invariant} — ${verdict.subject}`\n return verdict.details.length ? `${head}\\n ${verdict.details.join('\\n ')}` : head\n}\n"],"mappings":";AASO,IAAM,iBAAiB;AAAA;AAAA,EAE5B,YAAY,IAAI,OAAO;AAAA;AAAA,EAEvB,iBAAiB,KAAK,OAAO;AAAA;AAAA,EAE7B,gBAAgB,IAAI,OAAO;AAAA;AAAA,EAE3B,YAAY;AAAA;AAAA,EAEZ,gBAAgB,KAAK;AAAA;AAAA,EAErB,iBAAiB,KAAK;AAAA;AAAA,EAEtB,gBAAgB;AAAA;AAAA,EAEhB,YAAY;AAAA;AAAA,EAEZ,mBAAmB,MAAM,OAAO;AAAA;AAAA,EAEhC,gBAAgB;AAAA;AAAA,EAEhB,kBAAkB,KAAK,QAAQ;AAAA;AAAA,EAE/B,eAAe;AAAA;AAAA,EAEf,kBAAkB;AAAA;AAAA,EAElB,kBAAkB;AAAA;AAAA,EAElB,qBAAqB,KAAK;AAAA;AAAA,EAE1B,oBAA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