zidane 5.10.13 → 5.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +26 -0
  2. package/dist/{agent-BHkvYIH9.d.ts → agent-B7ilLoh8.d.ts} +63 -4
  3. package/dist/agent-B7ilLoh8.d.ts.map +1 -0
  4. package/dist/chat/pure.d.ts +3 -3
  5. package/dist/chat.d.ts +6 -6
  6. package/dist/chat.js +2 -2
  7. package/dist/contexts/docker.d.ts +1 -1
  8. package/dist/contexts/docker.d.ts.map +1 -1
  9. package/dist/contexts/docker.js +53 -14
  10. package/dist/contexts/docker.js.map +1 -1
  11. package/dist/contexts/e2b.d.ts +168 -0
  12. package/dist/contexts/e2b.d.ts.map +1 -0
  13. package/dist/contexts/e2b.js +261 -0
  14. package/dist/contexts/e2b.js.map +1 -0
  15. package/dist/{contexts-BJVgG0LY.js → contexts-DglWSzmR.js} +59 -9
  16. package/dist/contexts-DglWSzmR.js.map +1 -0
  17. package/dist/contexts.d.ts +3 -3
  18. package/dist/contexts.js +1 -1
  19. package/dist/eval.d.ts +1 -1
  20. package/dist/eval.js +4 -4
  21. package/dist/{headless-CPaunZsU.js → headless-CYHU4ZB-.js} +6 -6
  22. package/dist/{headless-CPaunZsU.js.map → headless-CYHU4ZB-.js.map} +1 -1
  23. package/dist/headless.d.ts +1 -1
  24. package/dist/headless.js +1 -1
  25. package/dist/{index-C4aT2kO_.d.ts → index-C-zEbeFI.d.ts} +13 -101
  26. package/dist/index-C-zEbeFI.d.ts.map +1 -0
  27. package/dist/{index-C_t8tW_X.d.ts → index-CrMb8jCE.d.ts} +2 -2
  28. package/dist/{index-C_t8tW_X.d.ts.map → index-CrMb8jCE.d.ts.map} +1 -1
  29. package/dist/{index-BIo67xLV.d.ts → index-CsRdmSh6.d.ts} +10 -3
  30. package/dist/index-CsRdmSh6.d.ts.map +1 -0
  31. package/dist/index.d.ts +7 -6
  32. package/dist/index.js +11 -10
  33. package/dist/index.js.map +1 -1
  34. package/dist/{interpolate-Dy7Lunvg.js → interpolate-CTfr0GdR.js} +19 -1
  35. package/dist/{interpolate-Dy7Lunvg.js.map → interpolate-CTfr0GdR.js.map} +1 -1
  36. package/dist/logger-Bd4Wn9Hc.d.ts +102 -0
  37. package/dist/logger-Bd4Wn9Hc.d.ts.map +1 -0
  38. package/dist/logger-Ktm-lj1s.js +300 -0
  39. package/dist/logger-Ktm-lj1s.js.map +1 -0
  40. package/dist/{login-0jP1pnSJ.js → login-DVLJzf-S.js} +4 -301
  41. package/dist/login-DVLJzf-S.js.map +1 -0
  42. package/dist/{mcp-tevNihk_.js → mcp-DPneQbw2.js} +21 -8
  43. package/dist/mcp-DPneQbw2.js.map +1 -0
  44. package/dist/mcp.d.ts +1 -1
  45. package/dist/mcp.js +1 -1
  46. package/dist/{messages-C_1AmSpk.js → messages-DJ7xdoUg.js} +5 -1
  47. package/dist/messages-DJ7xdoUg.js.map +1 -0
  48. package/dist/output/stream-json.d.ts +2 -2
  49. package/dist/output/stream-json.js +1 -1
  50. package/dist/output/terminal.d.ts +2 -2
  51. package/dist/output/terminal.js +1 -0
  52. package/dist/output/terminal.js.map +1 -1
  53. package/dist/{presets-Cm2BPJaU.js → presets-Q0yUDRA6.js} +2 -2
  54. package/dist/{presets-Cm2BPJaU.js.map → presets-Q0yUDRA6.js.map} +1 -1
  55. package/dist/presets.d.ts +2 -2
  56. package/dist/presets.js +1 -1
  57. package/dist/{providers-BGBB18zz.js → providers-BPdi7cUU.js} +73 -11
  58. package/dist/providers-BPdi7cUU.js.map +1 -0
  59. package/dist/providers.d.ts +1 -1
  60. package/dist/providers.js +2 -2
  61. package/dist/restate.d.ts +2 -2
  62. package/dist/restate.js +4 -1
  63. package/dist/restate.js.map +1 -1
  64. package/dist/session/sqlite.d.ts +1 -1
  65. package/dist/session/sqlite.d.ts.map +1 -1
  66. package/dist/session/sqlite.js +36 -4
  67. package/dist/session/sqlite.js.map +1 -1
  68. package/dist/{session-CtAWwwkn.js → session-D4GckETs.js} +69 -21
  69. package/dist/session-D4GckETs.js.map +1 -0
  70. package/dist/session.d.ts +2 -2
  71. package/dist/session.js +3 -3
  72. package/dist/shell-quote-BmnhZmdM.js +33 -0
  73. package/dist/shell-quote-BmnhZmdM.js.map +1 -0
  74. package/dist/skills.d.ts +3 -3
  75. package/dist/skills.js +1 -1
  76. package/dist/skills.js.map +1 -1
  77. package/dist/{tool-formatters-D_fX6FGl.d.ts → tool-formatters-DXO8rGut.d.ts} +2 -2
  78. package/dist/{tool-formatters-D_fX6FGl.d.ts.map → tool-formatters-DXO8rGut.d.ts.map} +1 -1
  79. package/dist/tools/fetch-url.d.ts +1 -1
  80. package/dist/tools/web-search.d.ts +1 -1
  81. package/dist/{tools-NxnEmzYg.js → tools-DqNkGwfd.js} +80 -73
  82. package/dist/tools-DqNkGwfd.js.map +1 -0
  83. package/dist/tools.d.ts +2 -2
  84. package/dist/tools.js +1 -1
  85. package/dist/{transcript-anchors-B_c7gWot.js → transcript-anchors-C3tVPR5n.js} +8 -8
  86. package/dist/{transcript-anchors-B_c7gWot.js.map → transcript-anchors-C3tVPR5n.js.map} +1 -1
  87. package/dist/{transcript-anchors-DA6XawEU.d.ts → transcript-anchors-p-ZsBSEF.d.ts} +10 -4
  88. package/dist/transcript-anchors-p-ZsBSEF.d.ts.map +1 -0
  89. package/dist/tui.d.ts +3 -3
  90. package/dist/tui.js +151 -41
  91. package/dist/tui.js.map +1 -1
  92. package/dist/{turn-operations-CCl7rpbT.d.ts → turn-operations-DD1D5VFx.d.ts} +3 -3
  93. package/dist/{turn-operations-CCl7rpbT.d.ts.map → turn-operations-DD1D5VFx.d.ts.map} +1 -1
  94. package/dist/{types-BibzMDjX.d.ts → types-B39tBba1.d.ts} +69 -2
  95. package/dist/types-B39tBba1.d.ts.map +1 -0
  96. package/dist/types.d.ts +5 -5
  97. package/docs/EXECUTION_CONTEXT.md +257 -0
  98. package/docs/RUN_IN_BACKGROUND.md +8 -0
  99. package/package.json +57 -24
  100. package/dist/agent-BHkvYIH9.d.ts.map +0 -1
  101. package/dist/contexts-BJVgG0LY.js.map +0 -1
  102. package/dist/index-BIo67xLV.d.ts.map +0 -1
  103. package/dist/index-C4aT2kO_.d.ts.map +0 -1
  104. package/dist/login-0jP1pnSJ.js.map +0 -1
  105. package/dist/mcp-tevNihk_.js.map +0 -1
  106. package/dist/messages-C_1AmSpk.js.map +0 -1
  107. package/dist/providers-BGBB18zz.js.map +0 -1
  108. package/dist/session-CtAWwwkn.js.map +0 -1
  109. package/dist/tools-NxnEmzYg.js.map +0 -1
  110. package/dist/transcript-anchors-DA6XawEU.d.ts.map +0 -1
  111. package/dist/types-BibzMDjX.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages-DJ7xdoUg.js","names":["documentMarker"],"sources":["../src/system-prompt.ts","../src/providers/cost.ts","../src/providers/schema-sanitize.ts","../src/providers/openai-compat.ts","../src/session/messages.ts"],"sourcesContent":["/**\n * System-prompt boundary marker — splits a system prompt into a stable static\n * prefix (cached) and a per-turn dynamic suffix (NOT cached).\n *\n * Why this exists: providers attach `cache_control` markers on the last block\n * of the system prompt, so the cached prefix covers the entire system text.\n * Any byte change anywhere — including a per-turn `<env>` rewrite — busts the\n * cache for the doctrine that sits below. A literal marker in the system\n * string lets providers split it into:\n *\n * ┌──────────────┐ cache_control: ephemeral\n * │ STATIC half │ — doctrine, skills catalog, tool catalog,\n * │ │ user instructions\n * ├──────────────┤ ← SYSTEM_PROMPT_BOUNDARY\n * │ DYNAMIC half │ — env, cwd, mtimes, anything per-turn\n * └──────────────┘ (no cache_control)\n *\n * The static prefix rides the prompt cache across turns/sessions; the dynamic\n * suffix re-bills per turn. Net effect: a cwd change between turns no longer\n * invalidates 4 KB of doctrine.\n *\n * Wire contract:\n *\n * - `splitSystemPrompt(s)` is pure; missing marker ⇒ entire string is static\n * (current behavior — no caller is forced to opt in).\n * - `renderSystemForWire(s)` strips the marker so it never reaches the model;\n * used by every provider before the bytes hit the wire, including the\n * cache-disabled path on providers that DO support `cache_control`.\n * - The marker uses underscores rather than XML/punctuation so it's\n * unambiguous when scanning prompts manually and unlikely to collide with\n * model-written content.\n * - Providers handle the split internally (Anthropic emits a 2-block array;\n * OpenAI-compat splits the leading `system` message into multi-part text).\n * Callers always pass a single `string` — no API break.\n */\n\n/**\n * Literal marker inserted in a system prompt to separate cacheable doctrine\n * from per-turn dynamic content. Providers split on this token.\n *\n * Underscored on both sides for visual distinctiveness — a stray instance in\n * model-written prose is implausible. Don't change the value without shipping\n * a migration; existing sessions carry the old marker in their cached\n * prompts.\n */\nexport const SYSTEM_PROMPT_BOUNDARY = '__ZIDANE_SYSTEM_PROMPT_BOUNDARY__'\n\n/** Result of {@link splitSystemPrompt} — both halves stripped of the marker. */\nexport interface SystemPromptParts {\n /** Bytes BEFORE the marker (or the entire string when no marker present). Cacheable. */\n static: string\n /** Bytes AFTER the marker. Empty when no marker present. NOT cached. */\n dynamic: string\n}\n\n/**\n * Split a system prompt around the first {@link SYSTEM_PROMPT_BOUNDARY}.\n *\n * Splits on the FIRST occurrence — subsequent markers are folded into the\n * dynamic half. This way callers can append additional `<env>` style blocks\n * with extra markers without each one creating a new cache layer (Anthropic\n * caps breakpoints; we use the budget elsewhere). The marker itself is\n * stripped from both sides — providers attach `cache_control` directly to\n * the static half's text content.\n *\n * A single blank line (`\\n\\n`) immediately adjacent to the marker on each\n * side is trimmed — callers conventionally write\n * `<doctrine>\\n\\n<MARKER>\\n\\n<env>` and expect the rendered wire bytes to\n * read as one logical paragraph. Blank lines beyond that immediate pair\n * (e.g. `\\n\\n\\n<env>`) are preserved verbatim so callers composing their\n * own spacing don't lose intentional gaps.\n *\n * Pure / no I/O / no allocation when the marker is absent (returns the input\n * verbatim on the static side and the empty string on the dynamic side).\n */\nexport function splitSystemPrompt(system: string): SystemPromptParts {\n if (system.length === 0)\n return { static: '', dynamic: '' }\n const idx = system.indexOf(SYSTEM_PROMPT_BOUNDARY)\n if (idx < 0)\n return { static: system, dynamic: '' }\n const staticPart = system.slice(0, idx)\n const dynamicPart = system.slice(idx + SYSTEM_PROMPT_BOUNDARY.length)\n // Strip a single immediately-adjacent newline pair on each side. Callers\n // typically write `<doctrine>\\n\\n<MARKER>\\n\\n<env>` and expect the rendered\n // wire bytes to read as one logical paragraph. The trim is bounded so\n // intentional blank lines further out (e.g. `\\n\\n\\n<env>`) are preserved\n // for callers that compose their own spacing.\n return {\n static: trimTrailingBlankLine(staticPart),\n dynamic: trimLeadingBlankLine(dynamicPart),\n }\n}\n\n/**\n * Compose a system prompt from a static prefix and an optional dynamic\n * suffix. Inserts {@link SYSTEM_PROMPT_BOUNDARY} between them only when the\n * dynamic side is non-empty — single-block prompts stay marker-free, so\n * callers that never opt in pay zero overhead and providers fall back to the\n * existing whole-string caching path.\n *\n * Spacing is `\\n\\n` on both sides of the marker so doctrine fragments,\n * which conventionally separate sections with a blank line, read cleanly\n * around the boundary.\n */\nexport function joinSystemPrompt(staticPart: string, dynamicPart: string): string {\n if (dynamicPart.length === 0)\n return staticPart\n if (staticPart.length === 0)\n return `${SYSTEM_PROMPT_BOUNDARY}\\n\\n${dynamicPart}`\n return `${staticPart}\\n\\n${SYSTEM_PROMPT_BOUNDARY}\\n\\n${dynamicPart}`\n}\n\n/**\n * Append `extra` to the STATIC half of a system prompt, preserving any\n * existing dynamic suffix.\n *\n * Used by the agent to fold in run-stable content (skills catalog, lazy tool\n * catalog) without bumping it into the dynamic half — both catalogs are\n * built once per run and remain byte-stable for the duration, so they\n * belong in the cached prefix.\n *\n * Returns a new string; the input is not mutated. When `extra` is empty,\n * returns the input verbatim.\n */\nexport function appendStaticSection(system: string, extra: string): string {\n if (extra.length === 0)\n return system\n const { static: staticPart, dynamic } = splitSystemPrompt(system)\n const nextStatic = staticPart.length === 0 ? extra : `${staticPart}\\n\\n${extra}`\n return joinSystemPrompt(nextStatic, dynamic)\n}\n\n/**\n * Append `extra` to the DYNAMIC half of a system prompt. Inserts the boundary\n * marker if the input didn't already carry one.\n *\n * Used by hosts (typically the TUI) to inject per-turn state — current cwd,\n * IDE selection, project root — without forcing every caller to know the\n * marker format. The host's `system:transform` hook rewrites the dynamic\n * half each turn; the static doctrine above stays byte-stable and rides the\n * cache.\n *\n * Returns a new string; the input is not mutated. When `extra` is empty,\n * returns the input verbatim.\n */\nexport function appendDynamicSection(system: string, extra: string): string {\n if (extra.length === 0)\n return system\n const { static: staticPart, dynamic } = splitSystemPrompt(system)\n const nextDynamic = dynamic.length === 0 ? extra : `${dynamic}\\n\\n${extra}`\n return joinSystemPrompt(staticPart, nextDynamic)\n}\n\n/**\n * Replace the entire dynamic half of a system prompt with `next`. Used by\n * the TUI's `<env>` rewriter where the entire dynamic section is regenerated\n * each turn rather than appended to.\n *\n * When `next` is empty, drops the dynamic half (and the marker) entirely.\n */\nexport function replaceDynamicSection(system: string, next: string): string {\n const { static: staticPart } = splitSystemPrompt(system)\n return joinSystemPrompt(staticPart, next)\n}\n\n/**\n * Strip the boundary marker so it never reaches the wire — collapses\n * `<static>${BOUNDARY}<dynamic>` into `<static>\\n\\n<dynamic>` for providers\n * that can't honor `cache_control` (vanilla OpenAI Chat Completions, Codex,\n * Cerebras, ...) or for the cache-disabled path on any provider.\n *\n * Cache-aware providers re-derive the split from the original (un-rendered)\n * system string via `splitSystemPrompt` — `renderSystemForWire` is the\n * marker-free counterpart used to build the actual wire bytes.\n *\n * No-op when the input has no marker. Pure / no I/O.\n */\nexport function renderSystemForWire(system: string): string {\n if (system.length === 0)\n return system\n const parts = splitSystemPrompt(system)\n if (parts.dynamic.length === 0)\n return parts.static\n if (parts.static.length === 0)\n return parts.dynamic\n return `${parts.static}\\n\\n${parts.dynamic}`\n}\n\n/** True when `system` contains the boundary marker. */\nexport function hasSystemPromptBoundary(system: string): boolean {\n return system.includes(SYSTEM_PROMPT_BOUNDARY)\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\n/** Strip a single trailing `\\n\\n` (and any leftover trailing whitespace within that pair). */\nfunction trimTrailingBlankLine(s: string): string {\n // Walk back across at most two `\\n` separated only by spaces/tabs.\n let end = s.length\n let newlines = 0\n while (end > 0 && newlines < 2) {\n const ch = s.charCodeAt(end - 1)\n if (ch === 0x0A) {\n newlines += 1\n end -= 1\n continue\n }\n if (ch === 0x20 || ch === 0x09) {\n end -= 1\n continue\n }\n break\n }\n return newlines > 0 ? s.slice(0, end) : s\n}\n\n/** Strip a single leading `\\n\\n` (and any leftover leading whitespace within that pair). */\nfunction trimLeadingBlankLine(s: string): string {\n let start = 0\n let newlines = 0\n while (start < s.length && newlines < 2) {\n const ch = s.charCodeAt(start)\n if (ch === 0x0A) {\n newlines += 1\n start += 1\n continue\n }\n if (ch === 0x20 || ch === 0x09) {\n start += 1\n continue\n }\n break\n }\n return newlines > 0 ? s.slice(start) : s\n}\n","import type { TurnUsage } from '../types'\nimport { getModel } from '@earendil-works/pi-ai'\n\ninterface ModelCostRates {\n input?: number\n output?: number\n cacheRead?: number\n cacheWrite?: number\n}\n\n/**\n * Per-MTok rates for models not yet in pi-ai's bundled registry. Keyed by\n * `provider:modelId`. Consulted only when pi-ai's `getModel` misses, so a\n * later dep bump that bundles the model transparently takes over.\n */\nconst EXTRA_COST_RATES: Readonly<Record<string, ModelCostRates>> = {\n // Claude Fable 5 — $10/$50 per MTok (cache rates at the standard 0.1×/1.25×).\n 'anthropic:claude-fable-5': { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },\n // Claude Opus 4.8 — same pricing as 4.7 ($5/$25 per MTok).\n 'anthropic:claude-opus-4-8': { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },\n // Arcee Trinity — platform pricing per MTok.\n 'arcee:trinity-large-thinking': { input: 0.25, output: 0.8 },\n 'arcee:trinity-large-preview': { input: 0.45, output: 0.15 },\n 'arcee:trinity-mini': { input: 0.045, output: 0.15 },\n // Baseten Model APIs — published per-MTok rates (cached-input discount as\n // cacheRead). GLM 5.1 / Nemotron Ultra omitted: no published rate yet.\n 'baseten:zai-org/GLM-5': { input: 0.95, output: 3.15, cacheRead: 0.2 },\n 'baseten:zai-org/GLM-4.7': { input: 0.6, output: 2.2, cacheRead: 0.12 },\n 'baseten:moonshotai/Kimi-K2.6': { input: 1, output: 3.9, cacheRead: 0.2 },\n 'baseten:moonshotai/Kimi-K2.5': { input: 0.6, output: 3, cacheRead: 0.12 },\n 'baseten:deepseek-ai/DeepSeek-V4-Pro': { input: 1.74, output: 3.48, cacheRead: 0.145 },\n 'baseten:nvidia/Nemotron-120B-A12B': { input: 0.3, output: 0.75, cacheRead: 0.06 },\n 'baseten:openai/gpt-oss-120b': { input: 0.1, output: 0.5 },\n}\n\n/**\n * Per-rate multipliers applied to the looked-up base rates before computing the\n * total. Used for premium-priced modes (e.g. Anthropic fast mode at 2×/6×). A\n * missing key defaults to `1` (no change).\n */\nexport interface CostMultiplier {\n input?: number\n output?: number\n cacheRead?: number\n cacheWrite?: number\n}\n\n/**\n * Fill in `usage.cost` from pi-ai's bundled price registry when the\n * provider didn't report one. Provider-reported cost (e.g. OpenRouter's\n * `total_cost`, OpenAI's pi-ai-computed total) always wins — we only\n * estimate when `usage.cost` is undefined.\n *\n * Lookup is `(provider, usage.modelId)`. On a miss (unknown / unbundled\n * model), `cost` stays undefined and the footer indicator hides — better\n * than fabricating a $0.\n *\n * The number is an estimate: token counts come from the API, rates from\n * the locally-bundled registry that refreshes with `@earendil-works/pi-ai`\n * version bumps. If a provider changes prices between bumps the figure\n * will drift until the dep updates. An optional `multiplier` scales the\n * base rates for premium modes (e.g. fast mode) before totaling.\n */\nexport function fillEstimatedCost(\n usage: TurnUsage,\n provider: string,\n multiplier?: CostMultiplier,\n): TurnUsage {\n if (usage.cost !== undefined)\n return usage\n if (!usage.modelId)\n return usage\n\n // pi-ai's `getModel` is typed for `KnownProvider` × `keyof models[P]`; we\n // accept arbitrary strings here (the openai-compat adapter routes both known\n // and user-defined endpoint names through this helper) and let the function's\n // runtime throw on a miss.\n const lookup = getModel as (p: string, m: string) => { cost?: ModelCostRates } | undefined\n let model: { cost?: ModelCostRates } | undefined\n try {\n model = lookup(provider, usage.modelId)\n }\n catch {\n model = undefined\n }\n\n // pi-ai miss → fall back to the local rate table for models it hasn't bundled.\n const rates = model?.cost ?? EXTRA_COST_RATES[`${provider}:${usage.modelId}`]\n if (!rates)\n return usage\n\n const mul = multiplier ?? {}\n const total\n = ((rates.input ?? 0) * (mul.input ?? 1) * (usage.input ?? 0)\n + (rates.output ?? 0) * (mul.output ?? 1) * (usage.output ?? 0)\n + (rates.cacheRead ?? 0) * (mul.cacheRead ?? 1) * (usage.cacheRead ?? 0)\n + (rates.cacheWrite ?? 0) * (mul.cacheWrite ?? 1) * (usage.cacheCreation ?? 0)) / 1_000_000\n\n if (total <= 0)\n return usage\n\n return { ...usage, cost: total }\n}\n","/**\n * JSON Schema sanitizer for tool `inputSchema` forwarded to LLM providers.\n *\n * Why this exists: MCP servers ship arbitrary JSON Schema in `tools/list`.\n * Anthropic and (to a lesser extent) OpenAI reject specific keyword\n * combinations with a 400 on `messages.create`, and the error message\n * lands deep inside an SDK exception that consumers blame on their own\n * code. The most common failure modes in the wild:\n *\n * - Root `$ref` (server-published schema lives under `#/$defs/X`).\n * - Root `oneOf` / `anyOf` / `allOf` (Anthropic allows neither at the\n * top level; expects `type: 'object'`).\n * - `type: ['object', 'null']` at the root (nullable variants of an\n * otherwise valid object schema).\n * - Missing `properties` on an object root.\n * - `nullable: true` (Swagger / OpenAPI 3.0 idiom — not standard JSON\n * Schema, ignored by every modern provider but Anthropic warns).\n * - Nested `$ref` pointing at `#/definitions/X` without the schema\n * actually inlining the referenced definition.\n *\n * Pure rewrite. Returns a new schema (or the same reference when nothing\n * needed to change — the hot path on stable tool registries) and a list\n * of `warnings` describing each rewrite. Providers call\n * `sanitizeToolSpecs` from `formatTools` so every tool — eager MCP, lazy\n * MCP, native, skill — gets the same treatment, and warnings surface\n * through `console.warn` once per batch (the seen-set in\n * `sanitizeToolSpecs` is local to one call, so a stable bad schema logs\n * once per request rather than every turn).\n *\n * Scope:\n * - Pure function. No I/O, no globals.\n * - Bounded recursion (`MAX_DEPTH = 32`) so a malicious server can't\n * wedge the agent with a deeply self-referential schema.\n * - Bounded `$ref` resolution (`MAX_REF_HOPS = 16`) for the same\n * reason. Cycles fall back to `{}` (permissive) rather than\n * throwing — the request still succeeds, the schema is just looser.\n *\n * Non-goals:\n * - Validating that the schema is internally consistent.\n * - Cleaning up tool *descriptions* (handled elsewhere).\n * - Provider-side feature detection (handled by the provider's own\n * `formatTools`; this module is a syntactic guard, not a semantic one).\n */\n\n/** Strictness profile — picks which transformations to apply. */\nexport type SchemaSanitizeProfile = 'anthropic' | 'openai' | 'permissive'\n\nexport interface SchemaSanitizeOptions {\n /** Strictness profile. Defaults to `'permissive'`. */\n profile?: SchemaSanitizeProfile\n /**\n * Tool name for context in warnings. Optional — when set, every warning\n * is prefixed with `[tool:<name>] ` so log lines correlate to the tool.\n */\n toolName?: string\n}\n\nexport interface SchemaSanitizeResult {\n /** Sanitized schema, safe to forward to the provider. */\n schema: Record<string, unknown>\n /**\n * Human-readable strings describing each rewrite the sanitizer performed.\n * Empty on a clean schema. Consumers may log these (recommended) or\n * thread them through a hook for observability.\n */\n warnings: string[]\n}\n\n/** Max nesting depth before sub-schemas are replaced with `{}`. */\nconst MAX_DEPTH = 32\n\n/** Max `$ref` hop count before resolution gives up. */\nconst MAX_REF_HOPS = 16\n\n/** Keys that hold a single sub-schema. */\nconst SUBSCHEMA_KEYS = ['items', 'additionalProperties', 'contains', 'not', 'if', 'then', 'else', 'propertyNames'] as const\n\n/**\n * Keys that hold a record of sub-schemas.\n *\n * `$defs` / `definitions` are intentionally NOT included — they're\n * metaschema storage, only reached via `$ref` resolution (which has its\n * own walker in `resolveRef`), and `enforceRoot` strips them at the\n * wire layer once inlining is done. Recursing into them would cost\n * cycles and produce warnings about sub-trees the provider never sees.\n */\nconst SUBSCHEMA_RECORD_KEYS = ['properties', 'patternProperties', 'dependentSchemas'] as const\n\n/** Keys that hold an array of sub-schemas. */\nconst SUBSCHEMA_ARRAY_KEYS = ['oneOf', 'anyOf', 'allOf', 'prefixItems'] as const\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Resolve a JSON pointer like `#/$defs/Foo` against `root`. Returns\n * `undefined` when the pointer doesn't resolve or hops past `MAX_REF_HOPS`.\n * The caller treats `undefined` as \"give up, leave as a permissive schema\".\n */\nfunction resolveRef(root: Record<string, unknown>, ref: string, hops = 0): Record<string, unknown> | undefined {\n if (hops > MAX_REF_HOPS)\n return undefined\n if (!ref.startsWith('#/'))\n return undefined\n\n const parts = ref.slice(2).split('/').map(decodeRefSegment)\n let cursor: unknown = root\n for (const part of parts) {\n if (!isPlainObject(cursor))\n return undefined\n cursor = cursor[part]\n }\n if (!isPlainObject(cursor))\n return undefined\n\n if (typeof cursor.$ref === 'string')\n return resolveRef(root, cursor.$ref, hops + 1)\n return cursor\n}\n\nfunction decodeRefSegment(seg: string): string {\n return seg.replace(/~1/g, '/').replace(/~0/g, '~')\n}\n\ninterface SanitizeCtx {\n root: Record<string, unknown>\n warnings: string[]\n profile: SchemaSanitizeProfile\n prefix: string\n}\n\n/**\n * Recursively sanitize a sub-schema. Returns the **original** reference\n * when nothing needed to change — every turn's `formatTools` re-runs the\n * sanitizer, and the no-alloc fast path keeps the hot loop cheap when\n * the registered tool set is already clean. Returns a fresh object when\n * any rewrite happened; never mutates the input.\n *\n * The dirty-tracking is local to each frame so a clean sub-tree under a\n * dirty parent doesn't get cloned uselessly.\n */\nfunction sanitizeNode(node: unknown, ctx: SanitizeCtx, depth: number, path: string): Record<string, unknown> {\n if (depth > MAX_DEPTH) {\n ctx.warnings.push(`${ctx.prefix}schema nested deeper than ${MAX_DEPTH} levels at ${path || '$'} — replaced with permissive {}`)\n return {}\n }\n if (!isPlainObject(node))\n return {}\n\n let dirty = false\n let working: Record<string, unknown> = node\n\n // Inline `$ref` first so subsequent passes see the resolved shape.\n // Sibling keys (per JSON Schema 2019-09+ semantics) win over the\n // referenced definition. Unresolvable refs collapse to whatever\n // siblings remained so the surrounding schema still validates.\n if (typeof working.$ref === 'string') {\n const ref = working.$ref\n const resolved = resolveRef(ctx.root, ref)\n const { $ref: _drop, ...rest } = working\n if (resolved) {\n ctx.warnings.push(`${ctx.prefix}inlined $ref \"${ref}\" at ${path || '$'}`)\n working = { ...resolved, ...rest }\n }\n else {\n ctx.warnings.push(`${ctx.prefix}dropped unresolvable $ref \"${ref}\" at ${path || '$'}`)\n working = rest\n }\n dirty = true\n }\n\n // OpenAPI 3.0 `nullable` → JSON-Schema `type: [..., 'null']`. Modern\n // providers don't recognise `nullable`; Anthropic in particular ignores\n // it silently, which lets the model emit `null` and then the validator\n // complains the value isn't the declared type. Translation keeps the\n // intent explicit on the wire.\n if (working.nullable === true) {\n if (!dirty) {\n working = { ...working }\n dirty = true\n }\n const t = working.type\n if (typeof t === 'string') {\n working.type = [t, 'null']\n ctx.warnings.push(`${ctx.prefix}converted nullable:true → type:[${t},null] at ${path || '$'}`)\n }\n else if (Array.isArray(t) && !t.includes('null')) {\n working.type = [...t, 'null']\n ctx.warnings.push(`${ctx.prefix}converted nullable:true → type:[…,null] at ${path || '$'}`)\n }\n else if (Array.isArray(t)) {\n // Redundant — type already includes 'null'. Silent strip keeps the\n // wire shape clean without surfacing a warning the caller can't act on.\n }\n else {\n ctx.warnings.push(`${ctx.prefix}stripped nullable:true at ${path || '$'} (no base type)`)\n }\n delete working.nullable\n }\n\n // Sub-schema recursion. Sweep every key that JSON Schema 2020-12\n // reserves for nested schemas; leave annotation keywords (`title`,\n // `description`, `examples`, `default`, ...) and validation keywords\n // (`minimum`, `pattern`, ...) alone.\n for (const key of SUBSCHEMA_KEYS) {\n const child = working[key]\n if (isPlainObject(child)) {\n const sanitized = sanitizeNode(child, ctx, depth + 1, `${path}/${key}`)\n if (sanitized !== child) {\n if (!dirty) {\n working = { ...working }\n dirty = true\n }\n working[key] = sanitized\n }\n }\n }\n\n for (const key of SUBSCHEMA_RECORD_KEYS) {\n const rec = working[key]\n if (isPlainObject(rec)) {\n let recDirty = false\n let out: Record<string, unknown> = rec\n for (const [k, v] of Object.entries(rec)) {\n const sanitized = sanitizeNode(v, ctx, depth + 1, `${path}/${key}/${k}`)\n if (sanitized !== v) {\n if (!recDirty) {\n out = { ...rec }\n recDirty = true\n }\n out[k] = sanitized\n }\n }\n if (recDirty) {\n if (!dirty) {\n working = { ...working }\n dirty = true\n }\n working[key] = out\n }\n }\n }\n\n for (const key of SUBSCHEMA_ARRAY_KEYS) {\n const arr = working[key]\n if (Array.isArray(arr)) {\n let arrDirty = false\n let out: unknown[] = arr\n for (let i = 0; i < arr.length; i++) {\n const sanitized = sanitizeNode(arr[i], ctx, depth + 1, `${path}/${key}/${i}`)\n if (sanitized !== arr[i]) {\n if (!arrDirty) {\n out = [...arr]\n arrDirty = true\n }\n out[i] = sanitized\n }\n }\n if (arrDirty) {\n if (!dirty) {\n working = { ...working }\n dirty = true\n }\n working[key] = out\n }\n }\n }\n\n return working\n}\n\n/**\n * Apply root-level coercions every supported provider expects:\n *\n * - `type === 'object'` (Anthropic requires it; OpenAI tolerates more\n * but rejects unions at root in strict mode).\n * - `properties` is a plain object (Anthropic 400s when missing).\n * - No root-level `$ref` / `oneOf` / `anyOf` / `allOf` (Anthropic rejects;\n * OpenAI behaviour varies by endpoint).\n * - `$defs` / `definitions` stripped (recursive pass already inlined\n * refs; the metaschema storage is dead weight at the wire layer).\n *\n * Applied for every profile because portability matters more than the\n * marginal permissiveness of any one host. Profile-specific extras\n * (currently `$schema` stripping on `anthropic`) are gated below.\n */\nfunction enforceRoot(schema: Record<string, unknown>, ctx: SanitizeCtx): Record<string, unknown> {\n // Decide what the final shape needs first, then materialise a clone\n // only when at least one change is required. The recursive pass calls\n // this last, so a fully-clean schema reaches the wire as the exact\n // reference the consumer passed in.\n let out: Record<string, unknown> = schema\n let dirty = false\n const dirtyOnce = (): void => {\n if (!dirty) {\n out = { ...schema }\n dirty = true\n }\n }\n\n const t = out.type\n if (Array.isArray(t)) {\n if (t.includes('object')) {\n dirtyOnce()\n out.type = 'object'\n if (t.length > 1)\n ctx.warnings.push(`${ctx.prefix}collapsed root type:[${t.join(',')}] to 'object'`)\n }\n else {\n dirtyOnce()\n ctx.warnings.push(`${ctx.prefix}root type:[${t.join(',')}] does not include 'object' — coerced to 'object'`)\n out.type = 'object'\n }\n }\n else if (typeof t === 'string' && t !== 'object') {\n dirtyOnce()\n ctx.warnings.push(`${ctx.prefix}coerced root type:'${t}' → 'object'`)\n out.type = 'object'\n }\n else if (t === undefined) {\n dirtyOnce()\n out.type = 'object'\n }\n\n // Anthropic + OpenAI both require `properties` on object schemas — even\n // when empty. Synthesise the object so the wire shape is well-formed.\n if (!isPlainObject(out.properties)) {\n if ('properties' in out)\n ctx.warnings.push(`${ctx.prefix}replaced non-object 'properties' at root with {}`)\n dirtyOnce()\n out.properties = {}\n }\n\n for (const key of ['oneOf', 'anyOf', 'allOf'] as const) {\n if (key in out) {\n dirtyOnce()\n ctx.warnings.push(`${ctx.prefix}stripped root '${key}' (providers require a single object schema)`)\n delete out[key]\n }\n }\n\n if ('$ref' in out) {\n dirtyOnce()\n ctx.warnings.push(`${ctx.prefix}stripped root $ref`)\n delete out.$ref\n }\n\n if ('$defs' in out) {\n dirtyOnce()\n delete out.$defs\n }\n if ('definitions' in out) {\n dirtyOnce()\n delete out.definitions\n }\n\n if (ctx.profile === 'anthropic' && '$schema' in out) {\n dirtyOnce()\n delete out.$schema\n }\n\n return out\n}\n\n/**\n * Sanitize a single tool's `inputSchema` for safe forwarding to the\n * provider. Returns the rewritten schema + a list of warnings describing\n * everything that changed.\n *\n * Never mutates the input. Returns the **same reference** when no rewrite\n * was needed (clean-schema fast path) — `sanitizeToolSpecs` relies on\n * this to keep the formatTools hot loop allocation-free across turns\n * when the registered tool set is already wire-valid.\n */\nexport function sanitizeToolSchema(\n input: unknown,\n options: SchemaSanitizeOptions = {},\n): SchemaSanitizeResult {\n const profile: SchemaSanitizeProfile = options.profile ?? 'permissive'\n const prefix = options.toolName ? `[tool:${options.toolName}] ` : ''\n\n // Non-object inputs always allocate a fresh `{}` root — there's no\n // possible identity to preserve, and the wire still needs a valid object\n // schema either way. `sanitizeToolSpecs` won't hit its no-alloc path for\n // these, which is fine; the model has nothing useful to call on a\n // malformed inputSchema anyway.\n if (!isPlainObject(input)) {\n return {\n schema: { type: 'object', properties: {} },\n warnings: [],\n }\n }\n\n const ctx: SanitizeCtx = {\n root: input,\n warnings: [],\n profile,\n prefix,\n }\n\n const recursed = sanitizeNode(input, ctx, 0, '')\n const enforced = enforceRoot(recursed, ctx)\n\n return { schema: enforced, warnings: ctx.warnings }\n}\n\n/**\n * Convenience: sanitize a batch of tools and emit a single de-duped\n * `console.warn` per unique warning line. Returns the rewritten tools\n * preserving original ordering and reference identity for clean schemas\n * (no reallocation when nothing needed to change).\n *\n * The sanitiser runs every request, so log noise from a stable bad\n * schema would multiply across turns; the de-dupe keeps the signal\n * useful in production logs without dropping the first occurrence.\n */\nexport function sanitizeToolSpecs<T extends { name: string, inputSchema?: unknown }>(\n tools: readonly T[],\n options: { profile?: SchemaSanitizeProfile, onWarning?: (line: string) => void } = {},\n): T[] {\n const seen = new Set<string>()\n const out: T[] = []\n for (const tool of tools) {\n const result = sanitizeToolSchema(tool.inputSchema, {\n profile: options.profile,\n toolName: tool.name,\n })\n if (result.warnings.length === 0 && result.schema === tool.inputSchema) {\n out.push(tool)\n continue\n }\n for (const line of result.warnings) {\n if (seen.has(line))\n continue\n seen.add(line);\n (options.onWarning ?? defaultWarn)(line)\n }\n out.push({ ...tool, inputSchema: result.schema })\n }\n return out\n}\n\nfunction defaultWarn(line: string): void {\n console.warn(`[zidane:schema] ${line}`)\n}\n","/**\n * OpenAI-compatible provider factory + shared utilities.\n *\n * `openaiCompat(params)` returns a `Provider` that talks to any OpenAI-compatible\n * HTTP endpoint (OpenRouter, Cerebras, Baseten, Fireworks, Groq, local LM servers, ...).\n * Helpers (`consumeSSE`, `toOAIMessages`, ...) are shared by the bespoke `openrouter`\n * and `cerebras` wrappers, which pin defaults on top of this factory.\n */\n\nimport type { Provider, ProviderCapabilities, StreamCallbacks, StreamOptions, ToolResult, ToolSpec, TurnResult } from '.'\nimport type { ClassifiedError } from '../errors'\nimport type { SessionContentBlock, SessionMessage, ThinkingLevel, ToolResultContent, ToolResultDocumentContent, TurnFinishReason } from '../types'\nimport { estimateTokens } from '../compact/utils'\nimport { classifyErrorPrelude, errorMessage, isRetryableHttpStatus, matchesContextExceeded, matchesToolPairingError } from '../errors'\nimport { renderSystemForWire, splitSystemPrompt } from '../system-prompt'\nimport { documentBlockMarker } from '../types'\nimport { fillEstimatedCost } from './cost'\nimport { sanitizeToolSpecs } from './schema-sanitize'\n\n// ---------------------------------------------------------------------------\n// OpenAI-compatible types\n// ---------------------------------------------------------------------------\n\nexport interface OAIMessage {\n role: 'system' | 'user' | 'assistant' | 'tool'\n content?: unknown\n tool_calls?: { id: string, type: 'function', function: { name: string, arguments: string } }[]\n tool_call_id?: string\n /**\n * OpenRouter normalized reasoning envelope. Echoed back unmodified on assistant\n * messages so the gateway can resume an extended-reasoning chain on the\n * upstream route. Ignored by hosts that don't speak the envelope.\n */\n reasoning_details?: unknown[]\n /**\n * Plain reasoning string echoed back on assistant messages for vLLM-style\n * reasoning models (Arcee Trinity-Thinking, DeepSeek-R1). Arcee's API accepts\n * `reasoning_content`; some self-hosted vLLM versions read `reasoning`.\n */\n reasoning_content?: string\n reasoning?: string\n}\n\nexport interface OAITool {\n type: 'function'\n function: { name: string, description: string, parameters: Record<string, unknown> }\n}\n\n// Sentinel tags zidane uses to round-trip tool_calls / tool_results through\n// the OpenAI-compat session shape. `toOpenAI` writes them; `fromOpenAI` reads\n// them back. The `__zidane_` prefix avoids collisions with any literal `_tag`\n// value a host might emit on real wire messages.\nexport const TOOL_RESULTS_TAG = '__zidane_tool_results__'\nexport const ASSISTANT_TOOL_CALLS_TAG = '__zidane_assistant_tc__'\n\n// ---------------------------------------------------------------------------\n// SSE stream parser\n// ---------------------------------------------------------------------------\n\n/**\n * Ceiling on how many UTF-16 code units may accumulate between two newline\n * boundaries when parsing an SSE stream. A broken or malicious server that\n * emits an unbounded stream of non-newline bytes would otherwise grow `buffer`\n * without end and eventually OOM the host. Measured in JS string length (UTF-16\n * units, 8M units ≈ 8–24 MB of UTF-8 input) rather than bytes — close enough\n * for a pathological-stream tripwire without paying `Buffer.byteLength` on\n * every chunk. Safely above the largest tool-call arg JSON we reasonably\n * expect.\n */\nconst SSE_MAX_BUFFER_LENGTH = 8 * 1024 * 1024\n\nexport class OpenAICompatStreamError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'OpenAICompatStreamError'\n }\n}\n\ninterface OpenAICompatUsage {\n input: number\n output: number\n cost?: number\n cacheRead?: number\n cacheCreation?: number\n}\n\nfunction usageFromChunk(chunk: Record<string, unknown>): OpenAICompatUsage | null {\n const chunkUsage = chunk.usage as\n | {\n prompt_tokens?: number\n completion_tokens?: number\n total_cost?: number\n cache_discount?: number\n prompt_tokens_details?: {\n cached_tokens?: number\n cache_creation_input_tokens?: number\n cache_write_tokens?: number\n }\n cache_creation_input_tokens?: number\n }\n | undefined\n\n if (chunkUsage) {\n const cachedRead = chunkUsage.prompt_tokens_details?.cached_tokens\n // OpenRouter surfaces cache writes via `prompt_tokens_details.cache_creation_input_tokens`\n // (Anthropic passthrough) or `cache_write_tokens` (normalized form). Either is cumulative\n // for the request, so pick whichever the route populated.\n const cachedWrite = chunkUsage.prompt_tokens_details?.cache_creation_input_tokens\n ?? chunkUsage.prompt_tokens_details?.cache_write_tokens\n ?? chunkUsage.cache_creation_input_tokens\n return {\n input: chunkUsage.prompt_tokens ?? 0,\n output: chunkUsage.completion_tokens ?? 0,\n cost: chunkUsage.total_cost ?? undefined,\n ...(typeof cachedRead === 'number' && cachedRead > 0 ? { cacheRead: cachedRead } : {}),\n ...(typeof cachedWrite === 'number' && cachedWrite > 0 ? { cacheCreation: cachedWrite } : {}),\n }\n }\n\n // Ollama's native streaming final chunk reports usage with these field names.\n // Some gateways expose that shape even when clients use an OpenAI-compatible\n // route, so accept it here before falling back to local estimates.\n const promptEvalCount = chunk.prompt_eval_count\n const evalCount = chunk.eval_count\n if (typeof promptEvalCount === 'number' || typeof evalCount === 'number') {\n return {\n input: typeof promptEvalCount === 'number' ? promptEvalCount : 0,\n output: typeof evalCount === 'number' ? evalCount : 0,\n }\n }\n\n return null\n}\n\nexport async function consumeSSE(\n response: Response,\n callbacks: StreamCallbacks,\n signal?: AbortSignal,\n) {\n // A null body (e.g. a 204, or a proxy that returns headers but no stream)\n // would otherwise NPE on `.getReader()` with an opaque TypeError.\n if (!response.body) {\n throw new OpenAICompatStreamError(\n 'Streaming response had no body — upstream returned an empty stream (status '\n + `${response.status} ${response.statusText}).`,\n )\n }\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n let text = ''\n let thinking = ''\n let finishReason = 'stop'\n let usage: OpenAICompatUsage = { input: 0, output: 0 }\n const tcMap = new Map<number, { id: string, name: string, args: string }>()\n // Per-stream nonce mixed into fabricated tool-call ids. A bare\n // `call_${index}` is stable ACROSS turns — when a host omits ids on every\n // turn, turn N's `call_0` collides with turn 1's, the pairing pass strips\n // the \"duplicate\" tool_use plus its result, and the model loops on\n // `[Tool use interrupted]` forever (the Kimi/Fireworks pairing-storm\n // signature). The nonce keeps fabricated ids unique per request.\n const idNonce = Math.random().toString(36).slice(2, 10)\n // OpenRouter `reasoning_details` deltas, keyed by item index. Items are merged\n // field-by-field: text/summary concatenate, signature/data/format/id/type are\n // last-write-wins (they only appear once per item in practice).\n const reasoningMap = new Map<number, Record<string, unknown>>()\n let sawReasoningDetails = false\n\n try {\n while (true) {\n // Abort can land either between reads (caught here) or mid-`read()`\n // (fetch rejects with AbortError). Throw the same AbortError shape on\n // this path so both converge on `classifyOpenAICompatError` →\n // `{ kind: 'aborted' }` instead of returning partial content as a\n // normal result depending on timing.\n if (signal?.aborted)\n throw new DOMException('The operation was aborted.', 'AbortError')\n const { done, value } = await reader.read()\n if (done)\n break\n\n buffer += decoder.decode(value, { stream: true })\n // Cap the line-less buffer. Any single event must fit under the ceiling.\n if (buffer.length > SSE_MAX_BUFFER_LENGTH) {\n throw new OpenAICompatStreamError(\n `SSE buffer exceeded ${SSE_MAX_BUFFER_LENGTH} characters without a line boundary — upstream may be streaming non-SSE data.`,\n )\n }\n const lines = buffer.split('\\n')\n buffer = lines.pop() || ''\n\n for (const line of lines) {\n // Spec allows both `data:` and `data: ` — the `.trim()` below\n // absorbs the optional single space after the colon.\n if (!line.startsWith('data:'))\n continue\n const data = line.slice(5).trim()\n if (data === '[DONE]')\n continue\n\n let chunk: Record<string, unknown>\n try {\n chunk = JSON.parse(data) as Record<string, unknown>\n }\n catch {\n // Malformed JSON frame — skip (SSE keepalives, injected comments, etc.)\n continue\n }\n\n const parsedUsage = usageFromChunk(chunk)\n if (parsedUsage)\n usage = parsedUsage\n\n const choices = chunk.choices as Array<Record<string, unknown>> | undefined\n const choice = choices?.[0]\n if (!choice)\n continue\n const fr = choice.finish_reason as string | undefined\n if (fr)\n finishReason = fr\n\n const delta = choice.delta as Record<string, unknown> | undefined\n\n // OpenRouter normalized reasoning envelope. Items arrive as deltas keyed\n // by `index`; merge into a stable list and stream the visible text portion\n // through `onThinking` so the UI sees reasoning live.\n const reasoningDeltaArr = delta?.reasoning_details as Array<Record<string, unknown>> | undefined\n if (reasoningDeltaArr && reasoningDeltaArr.length > 0) {\n sawReasoningDetails = true\n for (const item of reasoningDeltaArr) {\n const idx = (typeof item.index === 'number' ? item.index : 0)\n const existing = reasoningMap.get(idx) ?? {}\n // Concatenate text/summary across deltas.\n if (typeof item.text === 'string') {\n existing.text = ((existing.text as string | undefined) ?? '') + item.text\n thinking += item.text\n callbacks.onThinking?.(item.text)\n }\n if (typeof item.summary === 'string') {\n existing.summary = ((existing.summary as string | undefined) ?? '') + item.summary\n thinking += item.summary\n callbacks.onThinking?.(item.summary)\n }\n // Last-write-wins for opaque fields.\n for (const key of ['type', 'signature', 'data', 'format', 'id'] as const) {\n const v = item[key]\n if (typeof v === 'string')\n existing[key] = v\n }\n reasoningMap.set(idx, existing)\n }\n }\n\n // Legacy text-only reasoning fields (DeepSeek `reasoning_content`,\n // pre-`reasoning_details` OpenRouter, Qwen-thinking, …). Suppressed\n // when the structured envelope is in flight to avoid double-counting\n // the same reasoning text into the `thinking` buffer.\n if (!sawReasoningDetails) {\n const thinkingDelta = (delta?.reasoning_content ?? delta?.reasoning) as string | undefined\n if (thinkingDelta) {\n thinking += thinkingDelta\n callbacks.onThinking?.(thinkingDelta)\n }\n }\n\n const contentDelta = delta?.content as string | undefined\n if (contentDelta) {\n text += contentDelta\n callbacks.onText(contentDelta)\n }\n\n const toolCallsDelta = delta?.tool_calls as Array<{\n index: number\n id?: string\n function?: { name?: string, arguments?: string }\n }> | undefined\n if (toolCallsDelta) {\n for (const tc of toolCallsDelta) {\n const existing = tcMap.get(tc.index)\n if (existing) {\n // Some hosts deliver `id` / `function.name` on a later delta\n // than the first one for an index — backfill them so the call\n // doesn't keep the fabricated nonce id / empty name.\n if (tc.id)\n existing.id = tc.id\n existing.name ||= tc.function?.name ?? ''\n if (tc.function?.arguments)\n existing.args += tc.function.arguments\n }\n else {\n tcMap.set(tc.index, {\n id: tc.id || `call_${tc.index}_${idNonce}`,\n name: tc.function?.name || '',\n args: tc.function?.arguments || '',\n })\n }\n }\n }\n }\n }\n }\n catch (err) {\n // On a non-abort error (SSE buffer overflow, transport crash), cancel\n // the reader so the underlying HTTP body is actually terminated rather\n // than left half-consumed (a bare releaseLock() leaks the socket until\n // GC). Aborts already tear the body down via the fetch signal, so skip\n // the redundant cancel there.\n const isAbort = err instanceof Error && err.name === 'AbortError'\n if (!isAbort)\n await reader.cancel().catch(() => {})\n throw err\n }\n finally {\n reader.releaseLock()\n }\n\n // Tool call JSON is accumulated across many deltas. If the stream truncates\n // mid-object (network hiccup, server crash) `tc.args` won't parse — fall\n // back to an empty input and surface a stream error rather than letting the\n // whole turn reject with `SyntaxError: Unexpected end of JSON input`, which\n // gives callers no actionable signal.\n const toolCalls: Array<{ id: string, name: string, input: Record<string, unknown> }> = []\n for (const tc of tcMap.values()) {\n if (!tc.args) {\n toolCalls.push({ id: tc.id, name: tc.name, input: {} })\n continue\n }\n try {\n toolCalls.push({ id: tc.id, name: tc.name, input: JSON.parse(tc.args) as Record<string, unknown> })\n }\n catch (err) {\n throw new OpenAICompatStreamError(\n `Tool call \"${tc.name}\" (${tc.id}) arguments were truncated or malformed: ${errorMessage(err)}`,\n )\n }\n }\n\n // Sort by index so `reasoning_details` round-trip preserves item order.\n const reasoningDetails = Array.from(reasoningMap.entries())\n .sort(([a], [b]) => a - b)\n .map(([, item]) => item)\n\n return { text, thinking, toolCalls, finishReason, usage, reasoningDetails }\n}\n\n// ---------------------------------------------------------------------------\n// Message conversion: SessionMessage[] → OAIMessage[]\n// ---------------------------------------------------------------------------\n\n/**\n * Encode a single image block as an OpenAI `image_url` multi-part entry.\n */\nfunction toImageUrlPart(img: { mediaType: string, data: string }) {\n return {\n type: 'image_url' as const,\n image_url: { url: `data:${img.mediaType};base64,${img.data}` },\n }\n}\n\nfunction documentMarker(doc: ToolResultDocumentContent): string {\n return documentBlockMarker(doc, 'document omitted')\n}\n\n/**\n * Summarize a `tool_result` output for the companion-user-message path — text blocks\n * are joined (separated by `\\n`) so the tool message carries all textual context; image\n * blocks are collected in a flat list for the companion user message.\n *\n * Used only on the fallback path; the native path walks `output` in-order to preserve\n * text↔image interleaving.\n */\nfunction summarizeToolResultOutput(output: string | ToolResultContent[]): {\n text: string\n images: Array<{ mediaType: string, data: string }>\n} {\n if (typeof output === 'string')\n return { text: output, images: [] }\n\n const texts: string[] = []\n const images: Array<{ mediaType: string, data: string }> = []\n for (const block of output) {\n if (block.type === 'text')\n texts.push(block.text)\n else if (block.type === 'image')\n images.push({ mediaType: block.mediaType, data: block.data })\n else if (block.type === 'document')\n texts.push(documentMarker(block))\n }\n return { text: texts.join('\\n'), images }\n}\n\n/**\n * Options that influence OpenAI-compat message shaping.\n *\n * `imageInToolResult` defaults to `false`: the loop routes images via a companion\n * user message emitted immediately after the `tool` message. Providers with\n * genuine multi-part tool support can set it to `true` to emit a single\n * multi-part `tool` message instead.\n */\ninterface ToOAIOptions {\n imageInToolResult?: boolean\n /**\n * Host accepts provider-bound reasoning state echoed back on assistant\n * messages. The exact wire shape is selected by `reasoningMode`: OpenRouter's\n * structured `reasoning_details[]` envelope, or vLLM/Arcee's plain\n * `reasoning_content` / `reasoning` string. When `false` (default), stored reasoning blocks\n * are silently dropped to avoid 400s on hosts that strict-validate the schema.\n */\n supportsReasoning?: boolean\n /**\n * Reasoning round-trip shape. `'openrouter'` echoes structured\n * `reasoning_details[]`; `'reasoning_content'` echoes the plain reasoning\n * string (vLLM/Arcee). Only consulted when `supportsReasoning` is `true`.\n * Default: `'openrouter'`.\n */\n reasoningMode?: 'openrouter' | 'reasoning_content'\n /**\n * Wire field used to echo plain reasoning in `'reasoning_content'` mode.\n * Default: `'reasoning'` (broadest vLLM compatibility).\n */\n reasoningContentField?: 'reasoning_content' | 'reasoning'\n /**\n * Normalize `content: null` → `''` on assistant tool-call turns. Default off.\n */\n normalizeNullContent?: boolean\n /**\n * Active model id. Used to gate `provider_reasoning` blocks — reasoning state\n * is bound to the route that produced it, so a model switch invalidates the\n * embedded signatures.\n */\n model?: string\n}\n\nexport function toOAIMessages(system: string, messages: SessionMessage[], options: ToOAIOptions = {}): OAIMessage[] {\n // Collapse the system-prompt boundary marker before it leaves the harness —\n // it's purely structural metadata for `applyOAICacheBreakpoints`, not\n // content the model should see. Cache-aware routes call the breakpoint\n // helper with the ORIGINAL `system` so the split is preserved on the wire;\n // cache-disabled routes get a clean, marker-free system message here.\n const renderedSystem = renderSystemForWire(system)\n const out: OAIMessage[] = [{ role: 'system', content: renderedSystem }]\n const nativeImageInTool = options.imageInToolResult === true\n const reasoningEnabled = options.supportsReasoning === true\n const reasoningMode = options.reasoningMode ?? 'openrouter'\n const reasoningContentField = options.reasoningContentField ?? 'reasoning'\n const normalizeNullContent = options.normalizeNullContent === true\n const activeModel = options.model\n // Producer whose stored `provider_reasoning` blocks are valid for the active\n // route shape. `reasoning_content` mode round-trips `'vllm'` blocks; the\n // default `'openrouter'` mode round-trips `'openrouter'` blocks.\n const reasoningProducer: 'openrouter' | 'vllm' = reasoningMode === 'reasoning_content' ? 'vllm' : 'openrouter'\n\n for (const msg of messages) {\n // Single-pass partition into per-kind buckets — avoids re-walking\n // `msg.content` once per block type (P5). Reasoning blocks are gated here\n // by producer + active route, matching the previous double-filter.\n const toolResults: Extract<SessionContentBlock, { type: 'tool_result' }>[] = []\n const toolCalls: Extract<SessionContentBlock, { type: 'tool_call' }>[] = []\n const textBlocks: Extract<SessionContentBlock, { type: 'text' }>[] = []\n const imageBlocks: Extract<SessionContentBlock, { type: 'image' }>[] = []\n const documentBlocks: Extract<SessionContentBlock, { type: 'document' }>[] = []\n const reasoningBlocks: Extract<SessionContentBlock, { type: 'provider_reasoning' }>[] = []\n for (const b of msg.content) {\n switch (b.type) {\n case 'tool_result':\n toolResults.push(b)\n break\n case 'tool_call':\n toolCalls.push(b)\n break\n case 'text':\n textBlocks.push(b)\n break\n case 'image':\n imageBlocks.push(b)\n break\n case 'document':\n documentBlocks.push(b)\n break\n case 'provider_reasoning':\n // Provider-bound reasoning state — kept only when the host supports\n // it, the producer matches the active mode's shape, AND the active\n // route matches the producing model (signatures/CoT are route-bound).\n if (reasoningEnabled\n && b.producer === reasoningProducer\n && !(b.model && activeModel && b.model !== activeModel)) {\n reasoningBlocks.push(b)\n }\n break\n }\n }\n const reasoningDetails = reasoningBlocks.flatMap(b => b.producer === 'openrouter' ? b.details : [])\n // Plain reasoning text (vLLM/Arcee) — concatenated across blocks in order.\n const reasoningText = reasoningMode === 'reasoning_content'\n ? reasoningBlocks.map(b => b.producer === 'vllm' ? b.reasoningText : '').filter(Boolean).join('')\n : ''\n\n // Tool results → individual tool messages (plus optional companion user message for images)\n if (toolResults.length > 0) {\n for (const tr of toolResults) {\n // Pure-string output → text-only fast path, wire-identical to pre-multimodal behavior.\n if (typeof tr.output === 'string') {\n out.push({ role: 'tool', tool_call_id: tr.callId, content: tr.output })\n continue\n }\n\n // Native multi-part path — walk blocks in order so text↔image interleaving is preserved.\n if (nativeImageInTool) {\n const parts = tr.output.map(block => block.type === 'image'\n ? toImageUrlPart({ mediaType: block.mediaType, data: block.data })\n : { type: 'text' as const, text: block.type === 'document' ? documentMarker(block) : block.text })\n out.push({ role: 'tool', tool_call_id: tr.callId, content: parts })\n continue\n }\n\n // Companion-user-message fallback (Claude Desktop / Cline pattern).\n // Works on any Chat Completions endpoint that accepts images in user messages.\n const { text, images } = summarizeToolResultOutput(tr.output)\n if (images.length === 0) {\n // Structured array happened to be text-only — collapse to pure-text path.\n out.push({ role: 'tool', tool_call_id: tr.callId, content: text })\n continue\n }\n\n const noun = images.length === 1 ? 'image' : 'images'\n const attachedMarker = `[${images.length} ${noun} attached — see next user message]`\n const toolMarker = text.length > 0 ? `${text}\\n\\n${attachedMarker}` : attachedMarker\n out.push({ role: 'tool', tool_call_id: tr.callId, content: toolMarker })\n\n out.push({\n role: 'user',\n content: [\n ...images.map(toImageUrlPart),\n { type: 'text' as const, text: `(${noun} returned by tool call ${tr.callId})` },\n ],\n })\n }\n // A message can legitimately carry text/image/document blocks alongside\n // its tool_results (e.g. a user follow-up typed while tools ran). Don't\n // drop them — fall through to the non-tool-result shaping below.\n if (textBlocks.length === 0 && imageBlocks.length === 0 && documentBlocks.length === 0)\n continue\n }\n\n // Tool calls → assistant message with tool_calls array\n if (toolCalls.length > 0) {\n const textContent = textBlocks.length > 0\n ? textBlocks.map(b => b.text).join('\\n')\n : (normalizeNullContent ? '' : null)\n const m: OAIMessage = {\n role: 'assistant',\n content: textContent,\n tool_calls: toolCalls.map(tc => ({\n id: tc.id,\n type: 'function' as const,\n function: { name: tc.name, arguments: JSON.stringify(tc.input) },\n })),\n }\n if (reasoningDetails.length > 0)\n m.reasoning_details = reasoningDetails\n if (reasoningText.length > 0)\n m[reasoningContentField] = reasoningText\n out.push(m)\n continue\n }\n\n // Images/documents → multimodal array. Documents are represented as text\n // markers because Chat Completions has no portable PDF/document block.\n if (imageBlocks.length > 0 || documentBlocks.length > 0) {\n const parts: unknown[] = imageBlocks.map(img => ({\n type: 'image_url',\n image_url: { url: `data:${img.mediaType};base64,${img.data}` },\n }))\n for (const b of documentBlocks)\n parts.push({ type: 'text', text: documentMarker(b) })\n for (const b of textBlocks) {\n parts.push({ type: 'text', text: b.text })\n }\n const m: OAIMessage = { role: msg.role, content: parts }\n if (msg.role === 'assistant' && reasoningDetails.length > 0)\n m.reasoning_details = reasoningDetails\n if (msg.role === 'assistant' && reasoningText.length > 0)\n m[reasoningContentField] = reasoningText\n out.push(m)\n continue\n }\n\n // Pure text\n let pushed: OAIMessage\n if (textBlocks.length === 1) {\n pushed = { role: msg.role, content: textBlocks[0].text }\n }\n else if (textBlocks.length > 1) {\n pushed = { role: msg.role, content: textBlocks.map(b => ({ type: 'text', text: b.text })) }\n }\n else {\n pushed = { role: msg.role, content: null }\n }\n if (msg.role === 'assistant' && reasoningDetails.length > 0)\n pushed.reasoning_details = reasoningDetails\n if (msg.role === 'assistant' && reasoningText.length > 0)\n pushed[reasoningContentField] = reasoningText\n out.push(pushed)\n }\n\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Prompt caching\n// ---------------------------------------------------------------------------\n\nconst EPHEMERAL = { type: 'ephemeral' as const }\n\n/**\n * Add `cache_control: { type: 'ephemeral' }` breakpoints to the system message's\n * last text part and the last message's final content part.\n *\n * Mutates `messages` in place. Converts plain-string content into a single-element\n * content array so the cache marker can attach — this shape is accepted verbatim by\n * OpenRouter's Anthropic and Gemini routes and ignored by routes with automatic\n * caching (OpenAI, DeepSeek, Grok, Groq, Moonshot).\n *\n * Skip conditions (safe no-ops):\n * - Empty messages array.\n * - Assistant messages with no text (tool-call-only) — attaching a cache marker to a\n * `tool_calls` block has no defined semantics, so we skip and let the prior\n * system/tools breakpoints carry caching.\n *\n * System-prompt boundary handling: when `originalSystem` (the un-rendered\n * system text passed to {@link toOAIMessages}) contains\n * {@link SYSTEM_PROMPT_BOUNDARY}, the leading system message is rewritten as\n * a two-part array — `cache_control` lands on the static prefix only, so\n * per-turn churn in the dynamic suffix doesn't invalidate the cached\n * doctrine above. `originalSystem` defaults to `undefined` for back-compat;\n * omit it (or pass a marker-free string) for the single-block historic\n * behavior.\n */\nexport function applyOAICacheBreakpoints(messages: OAIMessage[], originalSystem?: string): void {\n if (messages.length === 0)\n return\n\n const first = messages[0]\n if (first.role === 'system')\n markSystemMessage(first, originalSystem)\n\n const lastIdx = messages.length - 1\n if (lastIdx > 0)\n markLastContentPart(messages[lastIdx])\n}\n\n/**\n * Place the cache marker on the static prefix of the system message. When\n * `originalSystem` carried {@link SYSTEM_PROMPT_BOUNDARY}, the message becomes\n * a two-part array — static (cached) then dynamic (uncached). Otherwise falls\n * through to {@link markLastContentPart} for the historic single-block\n * treatment.\n *\n * String-only branch — system messages produced by {@link toOAIMessages} are\n * always plain strings (`{ role: 'system', content: <rendered> }`). Hosts\n * that supply pre-built multi-part system messages bypass this branch and\n * get the generic last-block treatment.\n */\nfunction markSystemMessage(msg: OAIMessage, originalSystem?: string): void {\n if (typeof msg.content !== 'string' || msg.content.length === 0) {\n markLastContentPart(msg)\n return\n }\n // `originalSystem` is the authoritative source for the boundary split —\n // `msg.content` has typically been pre-rendered by `toOAIMessages` and no\n // longer carries the marker. Fall back to `msg.content` itself when no\n // original was supplied (or an empty original) so an external caller that\n // embedded a marker directly doesn't leak it into the cached block.\n const splitSource = originalSystem && originalSystem.length > 0\n ? originalSystem\n : msg.content\n const parts = splitSystemPrompt(splitSource)\n if (parts.dynamic.length === 0) {\n // No marker — wrap the (already marker-free) string in a single cached\n // block. `parts.static` equals `splitSource` in this branch.\n msg.content = [{ type: 'text', text: parts.static, cache_control: EPHEMERAL }]\n return\n }\n const next: Array<Record<string, unknown>> = []\n if (parts.static.length > 0)\n next.push({ type: 'text', text: parts.static, cache_control: EPHEMERAL })\n next.push({ type: 'text', text: parts.dynamic })\n msg.content = next\n}\n\n/**\n * Mark the last content part of an OAI message with `cache_control`. Normalizes\n * string content into a `[{ type: 'text', text, cache_control }]` array so the\n * marker has a block to attach to.\n *\n * No-op for messages without string or array content (tool-call-only assistant\n * messages fall through; the system/tools breakpoints carry the cache prefix).\n */\nfunction markLastContentPart(msg: OAIMessage): void {\n if (typeof msg.content === 'string') {\n if (msg.content.length === 0)\n return\n msg.content = [{ type: 'text', text: msg.content, cache_control: EPHEMERAL }]\n return\n }\n if (!Array.isArray(msg.content) || msg.content.length === 0)\n return\n\n const parts = msg.content as Array<Record<string, unknown>>\n const lastBlockIdx = parts.length - 1\n parts[lastBlockIdx] = { ...parts[lastBlockIdx], cache_control: EPHEMERAL }\n}\n\n/**\n * Return a copy of `tools` with `cache_control` on the last entry.\n *\n * OpenRouter accepts the marker alongside the standard `type` + `function` fields\n * and forwards it when routing to Anthropic/Gemini. Leaves the non-cached tools\n * unchanged so the caller's reference is not mutated.\n */\nexport function applyOAIToolCacheBreakpoint(tools: OAITool[]): OAITool[] {\n if (tools.length === 0)\n return tools\n const lastIdx = tools.length - 1\n return tools.map((tool, i) =>\n i === lastIdx ? ({ ...tool, cache_control: EPHEMERAL } as OAITool & { cache_control: typeof EPHEMERAL }) : tool,\n )\n}\n\n// ---------------------------------------------------------------------------\n// Shared message builders\n// ---------------------------------------------------------------------------\n\nexport function formatTools(tools: ToolSpec[]): OAITool[] {\n // Same sanitization Anthropic gets — OpenAI-compat hosts (OpenRouter,\n // Cerebras, Groq, ...) reject the same root-level shapes (missing\n // `properties` on object schemas, root `$ref` / `oneOf` / `anyOf`). The\n // `openai` profile is a touch more permissive about annotation\n // keywords, but the core rewrites are identical.\n const sanitized = sanitizeToolSpecs(tools, { profile: 'openai' })\n return sanitized.map(t => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.inputSchema as Record<string, unknown> },\n }))\n}\n\nexport function userMessage(content: string): SessionMessage {\n return { role: 'user', content: [{ type: 'text', text: content }] }\n}\n\nexport function assistantMessage(content: string): SessionMessage {\n return { role: 'assistant', content: [{ type: 'text', text: content }] }\n}\n\nexport function toolResultsMessage(results: ToolResult[]): SessionMessage {\n return {\n role: 'user',\n content: results.map(r => ({\n type: 'tool_result' as const,\n callId: r.id,\n output: r.content,\n ...(r.isError ? { isError: true as const } : {}),\n })),\n }\n}\n\n/**\n * Recover human-readable reasoning text from an OpenRouter-style\n * `reasoning_details` array. Used as a fallback when a `reasoning_content`-mode\n * host emits the structured envelope instead of the plain text field — the\n * `text` / `summary` fields carry the visible chain-of-thought; opaque fields\n * (signature/data/format) are ignored.\n */\nfunction extractReasoningDetailsText(details: unknown[]): string {\n let out = ''\n for (const item of details) {\n if (!item || typeof item !== 'object')\n continue\n const rec = item as Record<string, unknown>\n if (typeof rec.text === 'string')\n out += rec.text\n else if (typeof rec.summary === 'string')\n out += rec.summary\n }\n return out\n}\n\nexport function buildAssistantContent(\n text: string,\n toolCalls: { id: string, name: string, input: Record<string, unknown> }[],\n thinking?: string,\n reasoning?:\n | { details: unknown[], producer: 'openrouter', model?: string }\n | { reasoningText: string, producer: 'vllm', model?: string },\n): SessionMessage {\n const content: SessionContentBlock[] = []\n // `provider_reasoning` precedes `thinking` so re-attached envelopes arrive\n // before the legacy text mirror in the assistant content list.\n const hasReasoning = reasoning\n && (reasoning.producer === 'openrouter'\n ? reasoning.details.length > 0\n : reasoning.reasoningText.length > 0)\n if (reasoning && hasReasoning) {\n const block: Extract<SessionContentBlock, { type: 'provider_reasoning' }> = reasoning.producer === 'openrouter'\n ? { type: 'provider_reasoning', producer: 'openrouter', details: reasoning.details }\n : { type: 'provider_reasoning', producer: 'vllm', reasoningText: reasoning.reasoningText }\n if (reasoning.model)\n block.model = reasoning.model\n content.push(block)\n }\n if (thinking)\n content.push({ type: 'thinking', text: thinking })\n if (text)\n content.push({ type: 'text', text })\n for (const tc of toolCalls) {\n content.push({ type: 'tool_call', id: tc.id, name: tc.name, input: tc.input })\n }\n // Never persist an empty assistant content array — replaying\n // `{ role: 'assistant', content: [] }` to providers that strict-validate\n // (Anthropic) 400s the whole request. Marker text mirrors the pairing\n // repair convention in `session/messages.ts`.\n if (content.length === 0)\n content.push({ type: 'text', text: '[no content]' })\n return { role: 'assistant', content }\n}\n\n// ---------------------------------------------------------------------------\n// Error classification\n// ---------------------------------------------------------------------------\n\n/**\n * HTTP error thrown when an OpenAI-compatible endpoint returns a non-OK response.\n *\n * The body is best-effort JSON-parsed; `error.message` / `error.code` / `error.type`\n * are extracted for clean downstream classification.\n */\nexport class OpenAICompatHttpError extends Error {\n readonly status: number\n readonly providerCode?: string\n readonly bodyText: string\n\n constructor(status: number, bodyText: string) {\n let message = bodyText\n let code: string | undefined\n try {\n const parsed = JSON.parse(bodyText)\n message = parsed?.error?.message ?? bodyText\n code = parsed?.error?.code ?? parsed?.error?.type\n }\n catch {\n // Leave message as the raw body.\n }\n super(`HTTP ${status}: ${message}`)\n this.name = 'OpenAICompatHttpError'\n this.status = status\n this.providerCode = code\n this.bodyText = bodyText\n }\n}\n\nconst TRAILING_SLASH_RE = /\\/$/\n\n/**\n * Classify an OpenAI-compatible error into `ClassifiedError`.\n *\n * Recognizes:\n * - `AbortError` (from fetch) → `aborted`.\n * - `OpenAICompatHttpError` with a context-exceeded code or message → `context_exceeded`.\n * - Any other `OpenAICompatHttpError` → `provider_error`.\n *\n * Returns `null` for unrecognized error shapes (the loop falls back to `AgentProviderError`).\n */\nexport function classifyOpenAICompatError(err: unknown): ClassifiedError | null {\n const prelude = classifyErrorPrelude(err)\n if (prelude === 'not-object')\n return null\n if (prelude === 'aborted')\n return { kind: 'aborted' }\n\n // A truncated / malformed SSE stream is a transient network-level failure —\n // typically worth a retry from the caller's perspective.\n if (err instanceof OpenAICompatStreamError) {\n return {\n kind: 'provider_error',\n providerCode: 'stream_error',\n message: err.message,\n retryable: true,\n }\n }\n\n if (!(err instanceof OpenAICompatHttpError))\n return null\n\n const code = err.providerCode\n const msg = err.message\n\n if (code === 'context_length_exceeded' || matchesContextExceeded(msg)) {\n return {\n kind: 'context_exceeded',\n providerCode: code ?? 'context_length_exceeded',\n message: msg,\n }\n }\n\n if (matchesToolPairingError(msg)) {\n return {\n kind: 'tool_pairing_corruption',\n providerCode: code ?? 'invalid_request_error',\n message: msg,\n }\n }\n\n return {\n kind: 'provider_error',\n providerCode: code ?? String(err.status),\n message: msg,\n retryable: isRetryableHttpStatus(err.status),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Finish-reason mapping\n// ---------------------------------------------------------------------------\n\n/**\n * Map an OpenAI-compatible `finish_reason` string to the zidane `TurnFinishReason` union.\n */\nexport function mapOAIFinishReason(reason: string | null | undefined): TurnFinishReason | undefined {\n if (!reason)\n return undefined\n switch (reason) {\n case 'stop':\n return 'stop'\n case 'tool_calls':\n case 'function_call':\n return 'tool-calls'\n case 'length':\n return 'length'\n case 'content_filter':\n return 'content-filter'\n default:\n return 'other'\n }\n}\n\n// ---------------------------------------------------------------------------\n// openaiCompat factory\n// ---------------------------------------------------------------------------\n\n/**\n * Auth header config. `scheme` is prepended to the api key with a space, e.g.\n * `{ name: 'Authorization', scheme: 'Bearer' }` → `Authorization: Bearer <key>`.\n * Omit `scheme` for raw header values (e.g. `{ name: 'X-Api-Key' }` → `X-Api-Key: <key>`).\n *\n * Real-world examples:\n * - Default OpenAI / OpenRouter / Cerebras: `{ name: 'Authorization', scheme: 'Bearer' }`.\n * - Baseten: `{ name: 'Authorization', scheme: 'Api-Key' }`.\n * - Some gateways: `{ name: 'X-Api-Key' }`.\n */\nexport interface OpenAICompatAuthHeader {\n name: string\n scheme?: string\n}\n\nexport interface OpenAICompatParams {\n /** Bearer-style API key. */\n apiKey: string\n /** Base URL — `/chat/completions` is appended. */\n baseURL: string\n /** Default model id when `run({ model })` is omitted. */\n defaultModel?: string\n /** Provider name exposed as `Provider.name`. Defaults to `'openai-compat'`. */\n name?: string\n /** Auth header shape. Defaults to `{ name: 'Authorization', scheme: 'Bearer' }`. */\n authHeader?: OpenAICompatAuthHeader\n /** Extra headers sent with every request (e.g. referer, user-agent). */\n extraHeaders?: Record<string, string>\n /**\n * Provider-level capability flags. Routed into the message shaper and the\n * agent loop so images in tool results + user messages are handled correctly\n * for the underlying model.\n *\n * Defaults when omitted: `vision: false`, `imageInToolResult: false` — a\n * conservative assumption matching most OSS text-only OpenAI-compat\n * endpoints. Override when routing to a known vision-capable endpoint\n * (e.g. OpenRouter vision models, Baseten image-capable deployments).\n */\n capabilities?: ProviderCapabilities\n /**\n * Whether this endpoint honors `cache_control: { type: 'ephemeral' }` markers\n * on message content parts and tool definitions.\n *\n * - `true` — inject markers when the caller asks for caching. OpenRouter routes\n * to Anthropic/Gemini forward the markers; routes to OpenAI/DeepSeek/\n * Grok/Groq/Moonshot ignore them (those backends cache automatically).\n * - `false` — never inject markers. Safe default for endpoints that strictly\n * validate the request schema (OpenAI direct, most OSS inference\n * servers) and would reject unknown fields.\n *\n * Default: `false`. The `openrouter` wrapper sets this to `true`.\n */\n cacheBreakpoints?: boolean\n /**\n * Whether this endpoint speaks a reasoning round-trip shape selected by\n * `reasoningMode` — either OpenRouter's normalized `reasoning` request field\n * plus structured `reasoning_details[]`, or vLLM/Arcee's plain\n * `reasoning_content` assistant-message field.\n *\n * - `true` — capture compatible reasoning fields from streaming responses\n * into `provider_reasoning` blocks and echo them back on\n * subsequent assistant messages. In `'openrouter'` mode, also map\n * zidane's `behavior.thinking` / `behavior.thinkingBudget` to the\n * request's `reasoning` field.\n * - `false` — never set the field; drop any stored `provider_reasoning`\n * blocks before sending. Safe default for hosts that strict-\n * validate the request schema.\n *\n * Default: `false`. The `openrouter` wrapper sets this to `true`.\n */\n supportsReasoning?: boolean\n /**\n * Shape used to round-trip reasoning state across turns when\n * `supportsReasoning` is `true`. Ignored when `supportsReasoning` is `false`.\n *\n * - `'openrouter'` (default) — capture/echo OpenRouter's structured\n * `reasoning_details[]` envelope.\n * - `'reasoning_content'` — capture the plain `reasoning_content` string and\n * echo it back on assistant messages (DeepSeek-R1 reasoning parser / Arcee\n * Trinity-Thinking served via vLLM). See\n * https://docs.arcee.ai/capabilities/reasoning-traces.\n *\n * Default: `'openrouter'`.\n */\n reasoningMode?: 'openrouter' | 'reasoning_content'\n /**\n * Field name to use when echoing plain reasoning back upstream in\n * `'reasoning_content'` mode. The OpenAI SDK returns `reasoning_content`, but\n * some self-hosted vLLM versions only read `reasoning` on input (vllm#38488).\n * Default: `'reasoning'`.\n */\n reasoningContentField?: 'reasoning_content' | 'reasoning'\n /**\n * Normalize `content: null` → `''` on assistant tool-call turns. Some\n * reasoning models (Arcee/vLLM) degrade or emit malformed follow-ups when a\n * tool-call assistant message carries a null content. Off by default to keep\n * the wire byte-identical for existing providers (OpenRouter, Cerebras, …).\n */\n normalizeNullContent?: boolean\n /**\n * Generic pass-through for fields on the Chat Completions request body that\n * zidane does not yet type. Spread into the request before the typed core\n * (model / messages / tools / max_tokens / stream / tool_choice), so\n * explicit options always win on collision.\n *\n * Forward-compat escape hatch for endpoints that ship one-off fields ahead\n * of zidane (e.g. OpenAI `reasoning_effort`, OpenRouter `provider` routing,\n * vendor-specific `safety_level` knobs).\n */\n extraBodyParams?: Record<string, unknown>\n /**\n * Per-request reasoning body planner for hosts whose thinking knob is a\n * vendor-specific request field rather than OpenRouter's `reasoning` object\n * (e.g. Baseten's `reasoning_effort` / `chat_template_args.enable_thinking`).\n * Called on every `stream()` with the resolved model + thinking options;\n * the returned fields are merged into the request body (after\n * `extraBodyParams`, before the typed core, so model/messages/etc. still\n * win on collision). Return `undefined` to send nothing.\n */\n planReasoningRequest?: (ctx: {\n model: string\n thinking?: ThinkingLevel\n thinkingBudget?: number\n }) => Record<string, unknown> | undefined\n}\n\n/**\n * Map zidane's `ThinkingLevel` + optional explicit budget to the OpenRouter\n * `reasoning` request field. Returns `undefined` when reasoning should not be\n * sent (off, or no level + no budget).\n *\n * - `'low' | 'medium' | 'high'` → `{ effort }`.\n * - `'minimal'` → `{ effort: 'low' }` (closest match in OpenRouter's vocabulary).\n * - `'adaptive'` → `{}` (let upstream decide; OpenRouter passes through).\n * - explicit `thinkingBudget` → `{ max_tokens }` overlaid on the level.\n */\nfunction planOpenRouterReasoning(\n thinking: ThinkingLevel | undefined,\n thinkingBudget: number | undefined,\n): Record<string, unknown> | undefined {\n if ((!thinking || thinking === 'off') && typeof thinkingBudget !== 'number')\n return undefined\n const out: Record<string, unknown> = {}\n if (thinking && thinking !== 'off' && thinking !== 'adaptive') {\n out.effort = thinking === 'minimal' ? 'low' : thinking\n }\n if (typeof thinkingBudget === 'number' && thinkingBudget > 0) {\n out.max_tokens = thinkingBudget\n }\n return out\n}\n\nfunction usageWasReported(usage: OpenAICompatUsage): boolean {\n return usage.input > 0\n || usage.output > 0\n || (usage.cacheRead ?? 0) > 0\n || (usage.cacheCreation ?? 0) > 0\n || usage.cost !== undefined\n}\n\nfunction estimateMissingUsage(body: Record<string, unknown>, result: Awaited<ReturnType<typeof consumeSSE>>): OpenAICompatUsage {\n return {\n input: estimateTokens(JSON.stringify({\n messages: body.messages,\n tools: body.tools,\n })),\n output: estimateTokens([\n result.thinking,\n result.text,\n result.toolCalls.length > 0 ? JSON.stringify(result.toolCalls) : '',\n ].filter(Boolean).join('\\n')),\n }\n}\n\n/**\n * Factory for any OpenAI-compatible HTTP endpoint.\n *\n * Speaks the standard `POST /chat/completions` + `stream: true` + SSE dialect.\n * Thin wrappers (`openrouter`, `cerebras`) call this with pinned defaults.\n *\n * @example Baseten (non-standard auth scheme)\n * ```ts\n * openaiCompat({\n * name: 'baseten',\n * apiKey: process.env.BASETEN_API_KEY!,\n * baseURL: process.env.BASETEN_PROXY_URL!,\n * authHeader: { name: 'Authorization', scheme: 'Api-Key' },\n * })\n * ```\n */\nexport function openaiCompat(params: OpenAICompatParams): Provider {\n const name = params.name ?? 'openai-compat'\n const defaultModel = params.defaultModel ?? 'gpt-4o-mini'\n const authHeaderName = params.authHeader?.name ?? 'Authorization'\n const authHeaderValue = params.authHeader?.scheme\n ? `${params.authHeader.scheme} ${params.apiKey}`\n : (params.authHeader ? params.apiKey : `Bearer ${params.apiKey}`)\n const extraHeaders = params.extraHeaders ?? {}\n const endpoint = `${params.baseURL.replace(TRAILING_SLASH_RE, '')}/chat/completions`\n const capabilities: ProviderCapabilities = {\n vision: params.capabilities?.vision ?? false,\n imageInToolResult: params.capabilities?.imageInToolResult ?? false,\n }\n\n const cacheBreakpointsEnabled = params.cacheBreakpoints === true\n const reasoningEnabled = params.supportsReasoning === true\n const reasoningMode = params.reasoningMode ?? 'openrouter'\n const reasoningContentField = params.reasoningContentField ?? 'reasoning'\n const normalizeNullContent = params.normalizeNullContent === true\n\n return {\n name,\n meta: { defaultModel, capabilities },\n formatTools,\n userMessage,\n assistantMessage,\n toolResultsMessage,\n classifyError: classifyOpenAICompatError,\n\n async stream(options: StreamOptions, callbacks: StreamCallbacks): Promise<TurnResult> {\n const modelId = options.model || defaultModel\n const messages = toOAIMessages(options.system, options.messages, {\n imageInToolResult: capabilities.imageInToolResult === true,\n supportsReasoning: reasoningEnabled,\n reasoningMode,\n reasoningContentField,\n normalizeNullContent,\n model: modelId,\n })\n // Prompt caching — insert `cache_control: { type: 'ephemeral' }` breakpoints on\n // the system message's last text part, the last tool definition, and the last\n // message's final content part. Only emitted when the factory was constructed\n // with `cacheBreakpoints: true` (set by the `openrouter` wrapper); endpoints\n // that strict-validate the request schema otherwise reject unknown fields.\n const shouldCache = cacheBreakpointsEnabled && options.cache !== false\n if (shouldCache) {\n // Forward the un-rendered `options.system` so the boundary split\n // lands on the wire — `toOAIMessages` already collapsed the marker\n // into the rendered system content, but the cache helper needs the\n // original byte stream to split correctly.\n applyOAICacheBreakpoints(messages, options.system)\n }\n\n // max_tokens must cover both thinking budget and response tokens\n const maxTokens = options.thinkingBudget\n ? options.thinkingBudget + options.maxTokens\n : options.maxTokens\n\n // Vendor-specific thinking fields (Baseten `reasoning_effort` /\n // `chat_template_args`, …) planned per request. Sits between the static\n // extraBodyParams and the typed core in spread order.\n const reasoningBody = params.planReasoningRequest?.({\n model: modelId,\n thinking: options.thinking,\n thinkingBudget: options.thinkingBudget,\n })\n\n const body: Record<string, unknown> = {\n // Spread first so the typed core below wins on collision — explicit\n // always overrides generic.\n ...(params.extraBodyParams ?? {}),\n ...(reasoningBody ?? {}),\n model: modelId,\n messages,\n max_tokens: maxTokens,\n stream: true,\n }\n\n // OpenRouter normalized reasoning request field. Only set in\n // `'openrouter'` mode — vLLM/Arcee hosts don't speak the `reasoning`\n // object on requests (thinking there is controlled by serving flags) and\n // would 400 on the unknown field.\n if (reasoningEnabled && reasoningMode === 'openrouter') {\n const reasoning = planOpenRouterReasoning(options.thinking, options.thinkingBudget)\n if (reasoning)\n body.reasoning = reasoning\n }\n\n if (options.tools && (options.tools as unknown[]).length > 0) {\n body.tools = shouldCache\n ? applyOAIToolCacheBreakpoint(options.tools as OAITool[])\n : options.tools\n }\n\n if (options.toolChoice) {\n if (options.toolChoice.type === 'tool' && options.toolChoice.name)\n body.tool_choice = { type: 'function', function: { name: options.toolChoice.name } }\n else if (options.toolChoice.type === 'required')\n body.tool_choice = 'required'\n else\n body.tool_choice = 'auto'\n }\n\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n [authHeaderName]: authHeaderValue,\n 'Content-Type': 'application/json',\n ...extraHeaders,\n },\n body: JSON.stringify(body),\n signal: options.signal,\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new OpenAICompatHttpError(response.status, errorText)\n }\n\n const result = await consumeSSE(response, callbacks, options.signal)\n const finishReason = mapOAIFinishReason(result.finishReason)\n const usage = usageWasReported(result.usage)\n ? result.usage\n : estimateMissingUsage(body, result)\n\n // Build the provider-bound reasoning block to persist for the next turn.\n // `'openrouter'` → structured details; `'reasoning_content'` → the plain\n // reasoning string captured into `result.thinking` during the stream.\n let reasoningArg:\n | { details: unknown[], producer: 'openrouter', model?: string }\n | { reasoningText: string, producer: 'vllm', model?: string }\n | undefined\n // In `reasoning_content` mode the plain reasoning is round-tripped via the\n // `provider_reasoning` (vllm) block, so suppress the redundant `thinking`\n // mirror to avoid persisting the same text twice. (OpenRouter keeps the\n // mirror — its structured `details` aren't human-readable.)\n let thinkingForBlock: string | undefined = result.thinking\n if (reasoningEnabled) {\n if (reasoningMode === 'reasoning_content') {\n // Plain reasoning normally lands in `result.thinking`. Guard against a\n // host that emits the structured `reasoning_details` envelope instead\n // (which suppresses the legacy text capture in `consumeSSE`) by\n // recovering any visible text from those items.\n const reasoningText = result.thinking.length > 0\n ? result.thinking\n : extractReasoningDetailsText(result.reasoningDetails)\n if (reasoningText.length > 0) {\n reasoningArg = { reasoningText, producer: 'vllm', model: modelId }\n thinkingForBlock = undefined\n }\n }\n else if (result.reasoningDetails.length > 0) {\n reasoningArg = { details: result.reasoningDetails, producer: 'openrouter', model: modelId }\n }\n }\n\n return {\n assistantMessage: buildAssistantContent(\n result.text,\n result.toolCalls,\n thinkingForBlock,\n reasoningArg,\n ),\n text: result.text,\n toolCalls: result.toolCalls,\n done: result.toolCalls.length === 0,\n usage: fillEstimatedCost({\n input: usage.input,\n output: usage.output,\n ...(usage.cacheRead !== undefined ? { cacheRead: usage.cacheRead } : {}),\n ...(usage.cacheCreation !== undefined ? { cacheCreation: usage.cacheCreation } : {}),\n ...(usage.cost !== undefined ? { cost: usage.cost } : {}),\n ...(finishReason ? { finishReason } : {}),\n modelId,\n }, name),\n }\n },\n }\n}\n","/**\n * Canonical SessionMessage format with converters from/to Anthropic and OpenAI-compat formats.\n */\n\nimport type { Provider } from '../providers'\nimport type { SessionContentBlock, SessionMessage, ToolResultContent, ToolResultDocumentContent } from '../types'\nimport { ASSISTANT_TOOL_CALLS_TAG, TOOL_RESULTS_TAG } from '../providers/openai-compat'\nimport { reconcileImageMediaType } from '../tools/image-sniff'\nimport { documentBlockMarker } from '../types'\n\ntype ToolCallBlock = Extract<SessionContentBlock, { type: 'tool_call' }>\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Decode an Anthropic `tool_result.content` wire value back to zidane's canonical\n * `string | ToolResultContent[]` shape.\n *\n * Anthropic accepts three shapes in the wire: `string`, `Array<{type:'text',text}>`,\n * or `Array<{type:'text'|'image', ...}>`. We collapse to `string` only when every\n * block is text to keep simple cases readable.\n */\nfunction decodeAnthropicToolResultContent(content: unknown): string | ToolResultContent[] {\n if (typeof content === 'string')\n return content\n\n if (!Array.isArray(content))\n return JSON.stringify(content)\n\n const blocks: ToolResultContent[] = []\n for (const raw of content) {\n if (!raw || typeof raw !== 'object')\n continue\n const b = raw as Record<string, unknown>\n if (b.type === 'text' && typeof b.text === 'string') {\n blocks.push({ type: 'text', text: b.text })\n continue\n }\n if (b.type === 'image' && b.source && typeof b.source === 'object') {\n const src = b.source as Record<string, unknown>\n if (src.type === 'base64' && typeof src.data === 'string' && typeof src.media_type === 'string') {\n blocks.push({ type: 'image', mediaType: src.media_type, data: src.data })\n continue\n }\n }\n // Unknown block → stringify into text for visibility.\n blocks.push({ type: 'text', text: JSON.stringify(raw) })\n }\n\n if (blocks.length === 0)\n return ''\n\n const hasNonText = blocks.some(b => b.type !== 'text')\n if (!hasNonText)\n return blocks.map(b => (b as { type: 'text', text: string }).text).join('\\n')\n\n return blocks\n}\n\n/**\n * Build an Anthropic `image.source` block, reconciling the declared media\n * type against the actual magic bytes.\n *\n * Anthropic's API rejects the entire request when `media_type` disagrees\n * with the payload (`messages.N.content.K.image.source.base64: The image\n * was specified using the X media type, but the image appears to be a\n * Y image`). The upstream sources of `{type:'image'}` blocks each sniff\n * before producing the block (read_file / MCP / TUI paste), but this\n * wire-boundary reconciliation is a final safety net for any future code\n * path or host-supplied prompt part that slips through without sniffing.\n *\n * The reconciler is conservative: it overrides only when the magic bytes\n * positively identify a *different* known format. Unknown / too-short\n * payloads pass `mediaType` through unchanged.\n */\nfunction anthropicImageSource(mediaType: string, data: string): { type: 'base64', media_type: string, data: string } {\n return { type: 'base64' as const, media_type: reconcileImageMediaType(mediaType, data), data }\n}\n\nfunction anthropicDocumentBlocks(doc: Pick<ToolResultDocumentContent, 'mediaType' | 'data' | 'encoding' | 'name'>): AnthropicWireBlock[] {\n if (doc.encoding === 'base64' && doc.mediaType === 'application/pdf') {\n return [{\n type: 'document',\n source: { type: 'base64', media_type: 'application/pdf', data: doc.data },\n ...(doc.name ? { title: doc.name } : {}),\n }]\n }\n\n const header = doc.name\n ? `<attachment name=\"${doc.name}\" media_type=\"${doc.mediaType}\" encoding=\"${doc.encoding}\">`\n : `<attachment media_type=\"${doc.mediaType}\" encoding=\"${doc.encoding}\">`\n return [{ type: 'text', text: `${header}\\n${doc.data}\\n</attachment>` }]\n}\n\nfunction documentMarker(doc: ToolResultDocumentContent): string {\n return documentBlockMarker(doc, 'document attached')\n}\n\n/**\n * Coerce a tool-call id to Anthropic's wire constraint `^[a-zA-Z0-9_-]+$`.\n *\n * Sessions started under another provider (OpenAI-compat / OpenRouter /\n * Cerebras) or carrying MCP-namespaced calls can hold ids with `.`, `:`,\n * `/` or other characters that 400 the request the moment the user switches\n * to an Anthropic model (`messages.N.content.M.tool_use.id: String should\n * match pattern '^[a-zA-Z0-9_-]+$'`).\n *\n * The mapping is deterministic — every disallowed char becomes `_` — so a\n * `tool_use` and its paired `tool_result` (sanitized identically below) keep\n * matching ids and the pairing survives. When sanitization actually changed\n * the id, a short hash of the ORIGINAL id is appended so distinct inputs\n * that would collapse to the same replacement (`call.1` vs `call_1` vs\n * `call:1`) stay distinct on the wire. Empty ids get a stable placeholder\n * so the block stays well-formed.\n */\nconst ANTHROPIC_TOOL_ID_INVALID = /[^\\w-]/g\nfunction sanitizeAnthropicToolId(id: string): string {\n if (!id)\n return 'tool_0'\n // `replace` with a global regex is idempotent for already-valid ids and\n // avoids the stateful `lastIndex` pitfall of reusing a `/g` regex `.test()`.\n const sanitized = id.replace(ANTHROPIC_TOOL_ID_INVALID, '_')\n if (sanitized === id)\n return id\n return `${sanitized}_${shortIdHash(id)}`\n}\n\n/**\n * Tiny FNV-1a hash rendered in base36 — collision-resistant enough to keep\n * sanitized tool ids distinct, deterministic so `tool_use` / `tool_result`\n * pairs derived from the same original id always match.\n */\nfunction shortIdHash(value: string): string {\n let hash = 0x811C9DC5\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return (hash >>> 0).toString(36)\n}\n\n/**\n * Encode zidane's canonical `string | ToolResultContent[]` shape to Anthropic's\n * wire format for `tool_result.content`.\n */\nfunction encodeAnthropicToolResultContent(\n output: string | ToolResultContent[],\n): string | Array<{ type: 'text', text: string } | { type: 'image', source: { type: 'base64', media_type: string, data: string } }> {\n if (typeof output === 'string')\n return output\n return output.map((b) => {\n if (b.type === 'text')\n return { type: 'text' as const, text: b.text }\n if (b.type === 'document')\n return { type: 'text' as const, text: documentMarker(b) }\n return {\n type: 'image' as const,\n source: anthropicImageSource(b.mediaType, b.data),\n }\n })\n}\n\n// ---------------------------------------------------------------------------\n// fromAnthropic\n// ---------------------------------------------------------------------------\n\nexport function fromAnthropic(msg: { role: string, content: unknown }): SessionMessage {\n const role = msg.role as 'user' | 'assistant'\n const content: SessionContentBlock[] = []\n\n if (typeof msg.content === 'string') {\n content.push({ type: 'text', text: msg.content })\n return { role, content }\n }\n\n if (Array.isArray(msg.content)) {\n for (const block of msg.content) {\n if (!block || typeof block !== 'object')\n continue\n const b = block as Record<string, unknown>\n\n if (b.type === 'text') {\n content.push({ type: 'text', text: b.text as string })\n }\n else if (b.type === 'image') {\n const source = b.source as Record<string, unknown>\n if (source?.type === 'base64') {\n content.push({ type: 'image', mediaType: source.media_type as string, data: source.data as string })\n }\n }\n else if (b.type === 'document') {\n const source = b.source as Record<string, unknown>\n if (source?.type === 'base64' && typeof source.media_type === 'string' && typeof source.data === 'string') {\n content.push({\n type: 'document',\n mediaType: source.media_type,\n data: source.data,\n encoding: 'base64',\n ...(typeof b.title === 'string' ? { name: b.title } : {}),\n })\n }\n else if (source?.type === 'text' && typeof source.media_type === 'string' && typeof source.data === 'string') {\n content.push({\n type: 'document',\n mediaType: source.media_type,\n data: source.data,\n encoding: 'text',\n ...(typeof b.title === 'string' ? { name: b.title } : {}),\n })\n }\n }\n else if (b.type === 'tool_use') {\n content.push({ type: 'tool_call', id: b.id as string, name: b.name as string, input: b.input as Record<string, unknown> })\n }\n else if (b.type === 'tool_result') {\n const output = decodeAnthropicToolResultContent(b.content)\n const block: Extract<SessionContentBlock, { type: 'tool_result' }> = {\n type: 'tool_result',\n callId: b.tool_use_id as string,\n output,\n }\n if (b.is_error === true)\n block.isError = true\n content.push(block)\n }\n else if (b.type === 'thinking') {\n const block: Extract<SessionContentBlock, { type: 'thinking' }> = {\n type: 'thinking',\n text: (b.thinking as string | undefined) ?? '',\n }\n if (typeof b.signature === 'string') {\n block.signature = b.signature\n // Tag the producer so cross-provider senders can drop foreign signatures.\n block.signatureProducer = 'anthropic'\n }\n content.push(block)\n }\n else if (b.type === 'redacted_thinking') {\n // Encrypted reasoning that must be echoed back unmodified to keep\n // interleaved-thinking + tool-use chains working on Sonnet 3.7+/Opus 4.x.\n content.push({ type: 'redacted_thinking', data: (b.data as string | undefined) ?? '' })\n }\n else if (b.type === 'server_tool_use') {\n // Anthropic server-tool invocation (e.g. `web_search_20250305`). Captured\n // so multi-turn citation context survives — Anthropic's docs require\n // these blocks to be echoed back on follow-up turns.\n content.push({\n type: 'server_tool_use',\n producer: 'anthropic',\n id: (b.id as string | undefined) ?? '',\n name: (b.name as string | undefined) ?? '',\n input: (b.input as Record<string, unknown> | undefined) ?? {},\n })\n }\n else if (b.type === 'web_search_tool_result') {\n // Pairs with `server_tool_use`. `content` is opaque (search hit array\n // with `encrypted_content` / `encrypted_index`) — store unchanged.\n content.push({\n type: 'server_tool_result',\n producer: 'anthropic',\n toolUseId: (b.tool_use_id as string | undefined) ?? '',\n toolName: 'web_search',\n content: b.content,\n })\n }\n // Unknown block types are silently skipped\n }\n }\n\n return { role, content }\n}\n\n// ---------------------------------------------------------------------------\n// fromOpenAI\n// ---------------------------------------------------------------------------\n\nexport function fromOpenAI(msg: { role: string, content: unknown }): SessionMessage {\n const role = msg.role as 'user' | 'assistant'\n const content: SessionContentBlock[] = []\n const c: unknown = msg.content\n\n if (c == null) {\n return { role, content }\n }\n\n if (typeof c === 'string') {\n content.push({ type: 'text', text: c })\n return { role, content }\n }\n\n if (typeof c === 'object' && !Array.isArray(c) && (c as { _tag?: unknown })._tag === ASSISTANT_TOOL_CALLS_TAG) {\n const tagged = c as { text?: unknown, tool_calls?: unknown }\n if (typeof tagged.text === 'string' && tagged.text) {\n content.push({ type: 'text', text: tagged.text })\n }\n if (Array.isArray(tagged.tool_calls)) {\n for (const raw of tagged.tool_calls) {\n if (!raw || typeof raw !== 'object')\n continue\n const tc = raw as { id?: string, function?: { name?: string, arguments?: unknown } }\n const rawArgs = tc.function?.arguments\n // Malformed argument JSON (truncated stream, hand-edited history)\n // must not kill the whole conversion — fall back to `{}`, same\n // degradation `consumeSSE` applies to truncated tool-call args.\n let input: Record<string, unknown> = {}\n if (typeof rawArgs === 'string') {\n try {\n input = JSON.parse(rawArgs) as Record<string, unknown>\n }\n catch {\n input = {}\n }\n }\n else if (rawArgs && typeof rawArgs === 'object') {\n input = rawArgs as Record<string, unknown>\n }\n content.push({ type: 'tool_call', id: tc.id ?? '', name: tc.function?.name ?? '', input })\n }\n }\n return { role, content }\n }\n\n if (typeof c === 'object' && !Array.isArray(c) && (c as { _tag?: unknown })._tag === TOOL_RESULTS_TAG) {\n const tagged = c as { results?: unknown, text?: unknown }\n if (Array.isArray(tagged.results)) {\n for (const raw of tagged.results) {\n if (!raw || typeof raw !== 'object')\n continue\n const r = raw as { tool_call_id?: string, content?: string | ToolResultContent[] }\n content.push({ type: 'tool_result', callId: r.tool_call_id ?? '', output: r.content ?? '' })\n }\n }\n // Sibling text preserved by `toOpenAI` alongside the results.\n if (typeof tagged.text === 'string' && tagged.text)\n content.push({ type: 'text', text: tagged.text })\n return { role, content }\n }\n\n if (Array.isArray(c)) {\n for (const block of c) {\n if (!block || typeof block !== 'object')\n continue\n const b = block as Record<string, unknown>\n\n if (b.type === 'text') {\n content.push({ type: 'text', text: b.text as string })\n }\n else if (b.type === 'image_url') {\n const imageUrl = (b.image_url as Record<string, unknown>)?.url as string\n if (imageUrl?.startsWith('data:')) {\n const [meta, data] = imageUrl.slice(5).split(',', 2)\n const mediaType = meta.replace(';base64', '')\n content.push({ type: 'image', mediaType, data })\n }\n }\n }\n return { role, content }\n }\n\n return { role, content }\n}\n\n// ---------------------------------------------------------------------------\n// toAnthropic\n// ---------------------------------------------------------------------------\n\ntype AnthropicWireBlock\n = | { type: 'text', text: string }\n | { type: 'image', source: { type: 'base64', media_type: string, data: string } }\n | { type: 'document', source: { type: 'base64' | 'text', media_type: string, data: string }, title?: string }\n | { type: 'tool_use', id: string, name: string, input: Record<string, unknown> }\n | { type: 'tool_result', tool_use_id: string, content: ReturnType<typeof encodeAnthropicToolResultContent>, is_error?: true }\n | { type: 'thinking', thinking: string, signature: string }\n | { type: 'redacted_thinking', data: string }\n | { type: 'server_tool_use', id: string, name: string, input: Record<string, unknown> }\n | { type: 'web_search_tool_result', tool_use_id: string, content: unknown }\n\nexport function toAnthropic(msg: SessionMessage): { role: string, content: unknown } {\n const blocks: AnthropicWireBlock[] = msg.content\n // Drop foreign reasoning state. Three independent rejection paths,\n // each driven by an Anthropic API constraint we've hit in production:\n //\n // 1. `signatureProducer === 'openai'` — OpenAI's `encrypted_content`\n // isn't a valid Anthropic HMAC; sending it 400s with an unhelpful\n // \"invalid signature\" error.\n // 2. `type === 'thinking' && !signature` — Anthropic's\n // `ThinkingBlockParam` requires a signature field. A non-Anthropic\n // producer that doesn't sign thinking (Cerebras, Gemini, OSS via\n // OpenAI-compat, etc.) leaves a block in the session that 400s\n // here with `messages.N.content.M.thinking.signature: Field\n // required` the next time the user picks an Anthropic model. Drop\n // them — the model can re-think on its own turn, no info loss\n // beyond the prior provider's chain-of-thought, which Anthropic\n // can't consume anyway.\n // 3. `type === 'provider_reasoning'` — opaque provider-bound reasoning\n // state; not an Anthropic block type at all.\n .filter((b) => {\n if (b.type === 'provider_reasoning')\n return false\n if (b.type !== 'thinking')\n return true\n if (b.signatureProducer === 'openai')\n return false\n if (!b.signature)\n return false\n return true\n })\n .flatMap((block): AnthropicWireBlock[] => {\n switch (block.type) {\n case 'text':\n return [{ type: 'text', text: block.text }]\n case 'image':\n return [{ type: 'image', source: anthropicImageSource(block.mediaType, block.data) }]\n case 'document':\n return anthropicDocumentBlocks(block)\n case 'tool_call':\n return [{ type: 'tool_use', id: sanitizeAnthropicToolId(block.id), name: block.name, input: block.input }]\n case 'tool_result': {\n const out: AnthropicWireBlock = {\n type: 'tool_result',\n tool_use_id: sanitizeAnthropicToolId(block.callId),\n content: encodeAnthropicToolResultContent(block.output),\n }\n if (block.isError)\n out.is_error = true\n const docs = typeof block.output === 'string'\n ? []\n : block.output.filter((part): part is Extract<ToolResultContent, { type: 'document' }> => part.type === 'document')\n return [out, ...docs.flatMap(anthropicDocumentBlocks)]\n }\n case 'thinking':\n // Filter above guarantees `signature` is present and either\n // anthropic-produced or legacy (back-compat for pre-tagging\n // Anthropic sessions where producer was never recorded).\n return [{ type: 'thinking', thinking: block.text, signature: block.signature ?? '' }]\n case 'redacted_thinking':\n return [{ type: 'redacted_thinking', data: block.data }]\n case 'server_tool_use':\n // Anthropic-produced server-tool invocation echoed back so the\n // model can resume the citation chain. Producer is always\n // `anthropic` (other providers don't emit this variant).\n return [{ type: 'server_tool_use', id: sanitizeAnthropicToolId(block.id), name: block.name, input: block.input }]\n case 'server_tool_result':\n return [{ type: 'web_search_tool_result', tool_use_id: sanitizeAnthropicToolId(block.toolUseId), content: block.content }]\n default:\n return [{ type: 'text', text: '' }]\n }\n })\n\n // Simplify to plain string if only one text block\n const first = blocks[0]\n if (blocks.length === 1 && first.type === 'text')\n return { role: msg.role, content: first.text }\n\n return { role: msg.role, content: blocks }\n}\n\n// ---------------------------------------------------------------------------\n// toOpenAI\n// ---------------------------------------------------------------------------\n\nexport function toOpenAI(msg: SessionMessage): { role: string, content: unknown } {\n const toolCalls = msg.content.filter(b => b.type === 'tool_call')\n const toolResults = msg.content.filter(b => b.type === 'tool_result')\n const textBlocks = msg.content.filter(b => b.type === 'text')\n const imageBlocks = msg.content.filter(b => b.type === 'image')\n const documentBlocks = msg.content.filter(b => b.type === 'document')\n\n // Tool results → tagged format. Sibling text blocks (a user follow-up\n // typed while tools ran) ride along on `text` — the early return here\n // used to silently drop them, breaking round-trip fidelity vs. the wire\n // shaper (`toOAIMessages`), which preserves them.\n if (toolResults.length > 0) {\n const siblingText = textBlocks.map(b => b.text).join('\\n')\n return {\n role: msg.role,\n content: {\n _tag: TOOL_RESULTS_TAG,\n results: toolResults.map(tr => ({ tool_call_id: tr.callId, content: tr.output })),\n ...(siblingText ? { text: siblingText } : {}),\n },\n }\n }\n\n // Tool calls → tagged format\n if (toolCalls.length > 0) {\n const textContent = textBlocks.length > 0 ? textBlocks[0].text : null\n return {\n role: msg.role,\n content: {\n _tag: ASSISTANT_TOOL_CALLS_TAG,\n text: textContent,\n tool_calls: toolCalls.map(tc => ({\n id: tc.id,\n type: 'function',\n function: { name: tc.name, arguments: JSON.stringify(tc.input) },\n })),\n },\n }\n }\n\n // Images/documents → multimodal array. Documents have no portable OpenAI\n // Chat Completions block here, so preserve them as markers.\n if (imageBlocks.length > 0 || documentBlocks.length > 0) {\n const parts: unknown[] = imageBlocks.map(img => ({\n type: 'image_url',\n image_url: { url: `data:${img.mediaType};base64,${img.data}` },\n }))\n for (const b of documentBlocks)\n parts.push({ type: 'text', text: documentMarker(b) })\n for (const b of textBlocks)\n parts.push({ type: 'text', text: b.text })\n return { role: msg.role, content: parts }\n }\n\n // Pure text → string\n if (textBlocks.length === 1)\n return { role: msg.role, content: textBlocks[0].text }\n\n // Multiple text blocks or empty\n if (textBlocks.length > 1)\n return { role: msg.role, content: textBlocks.map(b => ({ type: 'text', text: b.text })) }\n\n return { role: msg.role, content: null }\n}\n\n// ---------------------------------------------------------------------------\n// autoDetectAndConvert\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// ensureToolResultPairing\n// ---------------------------------------------------------------------------\n\n/**\n * Placeholder content inserted into a synthetic `tool_result` when the harness\n * has to repair an orphan `tool_use`. Exported so downstream consumers\n * (training-data collectors, HFI submission) can reject any payload containing\n * it — the marker satisfies the wire-level pairing contract structurally but\n * the content itself is fake and would poison fine-tuning data.\n */\nexport const SYNTHETIC_TOOL_RESULT_PLACEHOLDER = '[Tool result missing due to internal error]'\n\n/**\n * Replacement text for an assistant message whose every content block was\n * stripped during pairing repair (e.g. the only blocks were orphan\n * `tool_call`s). Providers reject empty `content` arrays — the marker keeps\n * the turn shape valid while signaling \"this assistant turn lost its\n * outputs\" to the model so it can recover.\n */\nexport const TOOL_USE_INTERRUPTED_MARKER = '[Tool use interrupted]'\n\n/**\n * Replacement text for a user message whose every content block was a\n * `tool_result` with no matching upstream `tool_call` (e.g. the assistant\n * pair was stripped by an earlier compaction). Same role as\n * {@link TOOL_USE_INTERRUPTED_MARKER} on the user side.\n */\nexport const ORPHANED_TOOL_RESULT_MARKER = '[Orphaned tool result removed due to conversation resume]'\n\n/**\n * Classification of a single repair the pairing pass performed. Surfaced via\n * {@link EnsureToolResultPairingOptions.onRepair} so consumers can wire\n * telemetry, debug logs, or strict-mode rejection without re-implementing the\n * walk.\n *\n * Each entry corresponds to one of the corruption modes documented on\n * {@link ensureToolResultPairing}.\n */\nexport type PairingRepairMode\n = | 'orphan-tool-use-prepend' // mode 1: tool_use with no matching tool_result; next msg is user → prepend synthetic\n | 'orphan-tool-use-append' // mode 2: tool_use is followed by nothing (or a non-user msg) → append synthetic user turn\n | 'orphan-tool-result-strip' // mode 3: tool_result with no preceding tool_call → strip block\n | 'duplicate-tool-use-strip' // mode 4: duplicate tool_use id across assistant msgs → strip later instance\n | 'duplicate-tool-result-strip' // mode 5: duplicate tool_result callId in one user msg → strip later instance\n | 'empty-assistant-marker' // mode 6: assistant msg emptied by mode-4 stripping → replace with marker text\n | 'duplicate-tool-use-remint' // persist-time: fresh turn reused an existing tool_call id → re-minted before persist (loop-side, not part of ensureToolResultPairing)\n\nexport interface PairingRepair {\n mode: PairingRepairMode\n /** Tool-use / tool-result id this repair concerns. Absent for empty-marker repairs. */\n callId?: string\n /** Zero-based index into the INPUT `messages` array where the corruption was found. */\n messageIndex: number\n}\n\nexport interface EnsureToolResultPairingOptions {\n /**\n * Fired once per repair the pass performed. Synchronous so the loop can\n * stay on its hot path. Throwing from the callback aborts the pass —\n * consumers wanting fail-fast (strict mode) can re-throw with their own\n * typed error.\n */\n onRepair?: (repair: PairingRepair) => void\n}\n\n/**\n * Defensive repair pass that rewrites a message list so it satisfies the\n * wire-level `tool_use` ↔ `tool_result` adjacency contract every modern\n * provider enforces.\n *\n * Anthropic 400s on orphans with `'tool_use' ids were found without\n * 'tool_result' blocks immediately after` (and its inverse, `tool_result\n * must be preceded by a tool_call with the same toolCallId`). OpenAI's\n * Chat Completions API rejects most mismatches with a 400 too.\n *\n * Six repair modes — modeled after Anthropic's Claude Code defenses:\n *\n * | # | Corruption | Repair |\n * |---|------------|--------|\n * | 1 | assistant `tool_use` whose next user msg lacks a matching `tool_result` | **Prepend** a synthetic `tool_result` block carrying {@link SYNTHETIC_TOOL_RESULT_PLACEHOLDER} with `isError: true` |\n * | 2 | assistant `tool_use` followed by nothing (or by a non-user msg) | **Insert** a new synthetic user message with the same placeholder |\n * | 3 | user `tool_result` with no preceding assistant `tool_call` | **Strip** the orphan block; if it empties the msg, replace with {@link ORPHANED_TOOL_RESULT_MARKER} text block |\n * | 4 | duplicate `tool_call.id` across assistant messages (CC-1212) | **Strip** later instances + their matching tool_results |\n * | 5 | duplicate `tool_result.callId` within a single user message | **Dedupe** by `callId`, keep first |\n * | 6 | assistant message emptied by mode-4 stripping | **Replace** content with {@link TOOL_USE_INTERRUPTED_MARKER} text block |\n *\n * **Repair, not drop.** Earlier versions of this pass simply dropped orphan\n * blocks, which (a) silently rewrote history the model had reasoned over and\n * (b) cascaded — dropping an assistant tool_call would orphan its\n * tool_result, which would then get dropped too, removing any trace of\n * \"what the model tried to do\" from the transcript. The repair-based pass\n * preserves the model's tool_use shape and patches the dangling result with\n * an `is_error` placeholder so the model sees \"I tried X, the result was\n * lost\" and can retry intelligently.\n *\n * Adjacency contract: `tool_result` blocks must live in the user message\n * IMMEDIATELY following the assistant message that emitted the matching\n * `tool_use`. The pass enforces strict adjacency — a tool_result two\n * messages downstream of its tool_call is still an orphan.\n *\n * Idempotent: returns the input reference unchanged when no repairs were\n * necessary. Re-running on already-repaired output is a no-op.\n *\n * Pure: does not mutate input messages or their content arrays — every\n * repair allocates a fresh array / object.\n */\nexport function ensureToolResultPairing(\n messages: SessionMessage[],\n options: EnsureToolResultPairingOptions = {},\n): SessionMessage[] {\n if (messages.length === 0)\n return messages\n\n const fireRepair = options.onRepair ?? (() => {})\n\n // Pre-pass: first-occurrence index of every assistant `tool_call.id`.\n // Mode 4 strips any block whose first occurrence wasn't in the current\n // message — the first instance wins so the original semantics stand.\n const firstSeenAt = new Map<string, number>()\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i]\n if (msg.role !== 'assistant')\n continue\n for (const block of msg.content) {\n if (block.type === 'tool_call' && !firstSeenAt.has(block.id))\n firstSeenAt.set(block.id, i)\n }\n }\n\n // Scoped to this call. Keyed by INPUT index of the user message that\n // should receive prepended synthetic results from the prior assistant\n // turn's mode-1 repair. Drained as the outer loop reaches each user msg.\n const pendingOrphansByUserIndex = new Map<number, string[]>()\n\n let changed = false\n const markChanged = () => { changed = true }\n const out: SessionMessage[] = []\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i]\n\n if (msg.role === 'assistant') {\n processAssistantMessage({\n index: i,\n msg,\n messages,\n firstSeenAt,\n pendingOrphansByUserIndex,\n out,\n fireRepair,\n markChanged,\n })\n }\n else {\n processUserMessage({\n index: i,\n msg,\n pendingOrphansByUserIndex,\n out,\n fireRepair,\n markChanged,\n })\n }\n }\n\n return changed ? out : messages\n}\n\ninterface ProcessAssistantArgs {\n index: number\n msg: SessionMessage\n messages: SessionMessage[]\n firstSeenAt: Map<string, number>\n pendingOrphansByUserIndex: Map<number, string[]>\n out: SessionMessage[]\n fireRepair: (repair: PairingRepair) => void\n markChanged: () => void\n}\n\n/**\n * Process one assistant message: strip mode-4 duplicates, queue mode-1 / 2\n * orphan-tool-use repairs for the next user message (or insert a synthetic\n * one), and emit a mode-6 marker when dedup empties the message.\n */\nfunction processAssistantMessage(args: ProcessAssistantArgs): void {\n const { index, msg, messages, firstSeenAt, pendingOrphansByUserIndex, out, fireRepair, markChanged } = args\n\n // Mode 4: drop tool_call blocks that are duplicates either:\n // - across messages (first occurrence was in an earlier assistant msg), or\n // - within this same message (same id appearing twice in one turn —\n // pathological but observed in the wild with retry-replay providers).\n //\n // The per-message `seenHere` set guards against the intra-message case:\n // `firstSeenAt` records only the first OCCURRENCE per id, so two blocks\n // sharing an id within the same message both pass the cross-message\n // check (`firstSeenAt.get(id) === index`). The local set tracks which\n // ids we've already kept this iteration and strips later repeats.\n const dedupedContent: SessionContentBlock[] = []\n const seenHere = new Set<string>()\n let dedupedChanged = false\n for (const block of msg.content) {\n if (block.type === 'tool_call') {\n const isCrossMsgDup = firstSeenAt.get(block.id) !== index\n const isIntraMsgDup = seenHere.has(block.id)\n if (isCrossMsgDup || isIntraMsgDup) {\n dedupedChanged = true\n fireRepair({ mode: 'duplicate-tool-use-strip', callId: block.id, messageIndex: index })\n continue\n }\n seenHere.add(block.id)\n }\n dedupedContent.push(block)\n }\n\n const surviving = collectIds<ToolCallBlock>(dedupedContent, 'tool_call', b => b.id)\n const next = messages[index + 1]\n const nextIsUser = next && next.role === 'user'\n const nextResultIds = nextIsUser ? collectResultIds(next.content) : new Set<string>()\n const orphans: string[] = []\n for (const id of surviving) {\n if (!nextResultIds.has(id))\n orphans.push(id)\n }\n\n // Emit the (possibly deduped) assistant message — modes 1 / 2 patch the\n // matching user side rather than touching tool_use blocks.\n emitAssistantAfterDedup({ index, msg, dedupedContent, dedupedChanged, out, fireRepair, markChanged })\n\n if (orphans.length === 0)\n return\n\n // Mode 1: stash for the next user msg processor to prepend.\n if (nextIsUser) {\n markChanged()\n pendingOrphansByUserIndex.set(index + 1, orphans)\n for (const callId of orphans)\n fireRepair({ mode: 'orphan-tool-use-prepend', callId, messageIndex: index })\n return\n }\n\n // Mode 2: synthesize a user message with placeholders for every orphan.\n markChanged()\n out.push({\n role: 'user',\n content: orphans.map(callId => syntheticResultBlock(callId)),\n })\n for (const callId of orphans)\n fireRepair({ mode: 'orphan-tool-use-append', callId, messageIndex: index })\n}\n\ninterface EmitAssistantArgs {\n index: number\n msg: SessionMessage\n dedupedContent: SessionContentBlock[]\n dedupedChanged: boolean\n out: SessionMessage[]\n fireRepair: (repair: PairingRepair) => void\n markChanged: () => void\n}\n\nfunction emitAssistantAfterDedup(args: EmitAssistantArgs): void {\n const { index, msg, dedupedContent, dedupedChanged, out, fireRepair, markChanged } = args\n if (!dedupedChanged) {\n out.push(msg)\n return\n }\n markChanged()\n if (dedupedContent.length === 0) {\n out.push({ ...msg, content: [{ type: 'text', text: TOOL_USE_INTERRUPTED_MARKER }] })\n fireRepair({ mode: 'empty-assistant-marker', messageIndex: index })\n return\n }\n out.push({ ...msg, content: dedupedContent })\n}\n\ninterface ProcessUserArgs {\n index: number\n msg: SessionMessage\n pendingOrphansByUserIndex: Map<number, string[]>\n out: SessionMessage[]\n fireRepair: (repair: PairingRepair) => void\n markChanged: () => void\n}\n\n/**\n * Process one user message: dedup mode-5 duplicate tool_results, strip\n * mode-3 orphans whose tool_call is missing from the previously-emitted\n * assistant message, and prepend any synthetic results queued by the prior\n * assistant's mode-1 repair.\n */\nfunction processUserMessage(args: ProcessUserArgs): void {\n const { index, msg, pendingOrphansByUserIndex, out, fireRepair, markChanged } = args\n const queuedOrphans = pendingOrphansByUserIndex.get(index)\n pendingOrphansByUserIndex.delete(index)\n\n const prev = out.length > 0 ? out[out.length - 1] : null\n const validIds = prev && prev.role === 'assistant'\n ? collectIds<ToolCallBlock>(prev.content, 'tool_call', b => b.id)\n : new Set<string>()\n\n // Pass 1 — mode 5: dedupe by callId within this msg.\n const seenCallIds = new Set<string>()\n let modifiedHere = false\n const afterDedup: SessionContentBlock[] = []\n for (const block of msg.content) {\n if (block.type !== 'tool_result') {\n afterDedup.push(block)\n continue\n }\n if (seenCallIds.has(block.callId)) {\n modifiedHere = true\n fireRepair({ mode: 'duplicate-tool-result-strip', callId: block.callId, messageIndex: index })\n continue\n }\n seenCallIds.add(block.callId)\n afterDedup.push(block)\n }\n\n // Pass 2 — mode 3: strip orphan tool_results.\n const afterStrip: SessionContentBlock[] = []\n for (const block of afterDedup) {\n if (block.type === 'tool_result' && !validIds.has(block.callId)) {\n modifiedHere = true\n fireRepair({ mode: 'orphan-tool-result-strip', callId: block.callId, messageIndex: index })\n continue\n }\n afterStrip.push(block)\n }\n\n // Pass 3: prepend queued mode-1 synthetic results.\n const finalContent: SessionContentBlock[] = queuedOrphans\n ? [...queuedOrphans.map(syntheticResultBlock), ...afterStrip]\n : afterStrip\n\n if (!modifiedHere && queuedOrphans === undefined) {\n out.push(msg)\n return\n }\n\n markChanged()\n if (finalContent.length === 0) {\n out.push({ ...msg, content: [{ type: 'text', text: ORPHANED_TOOL_RESULT_MARKER }] })\n return\n }\n out.push({ ...msg, content: finalContent })\n}\n\n// ---------------------------------------------------------------------------\n// remintDuplicateToolCallIds — persist-time duplicate-id healing\n// ---------------------------------------------------------------------------\n\nexport interface RemintResult {\n /** Tool calls with duplicate ids replaced. Same reference when unchanged. */\n toolCalls: Array<{ id: string, name: string, input: Record<string, unknown> }>\n /** Assistant content with matching `tool_call` block ids rewritten. Same reference when unchanged. */\n content: SessionContentBlock[]\n /** One entry per re-minted occurrence, in emission order. */\n reminted: Array<{ oldId: string, newId: string }>\n}\n\n/**\n * Re-mint tool-call ids that collide with ids already present in the\n * transcript (or with an earlier sibling in the same turn), BEFORE the turn\n * is persisted and its tools dispatched.\n *\n * Why this exists: some providers/serving stacks emit non-globally-unique\n * tool_use ids (per-turn counters like `call_0`, retry-replay duplicates,\n * Kimi-K2.6 on Fireworks). The wire-time pairing pass\n * ({@link ensureToolResultPairing}) can only STRIP such duplicates — which\n * erases the model's tool calls and results from the wire view, stalls\n * progress, and re-accumulates repairs quadratically because the persisted\n * session keeps the corrupted ids. Re-minting at persist time keeps the\n * pairing intact instead: the call, its execution, and its tool_result all\n * carry the fresh id, so the pairing pass has nothing to strip on any later\n * turn.\n *\n * Fresh ids are `${oldId}_r{n}` with `n` bumped until unique — deterministic\n * shape, Anthropic-wire-safe charset (given a safe input id), and visibly\n * traceable back to the original.\n *\n * Alignment contract: `toolCalls` and the `tool_call` blocks inside\n * `content` are two views of the same emission and MUST be in the same\n * order (true for every provider — both are built from one source array).\n * Occurrences are matched positionally per old id so intra-turn duplicates\n * map to distinct fresh ids on both views.\n *\n * Pure: returns the input references unchanged when no id collides.\n */\nexport function remintDuplicateToolCallIds(\n toolCalls: ReadonlyArray<{ id: string, name: string, input: Record<string, unknown> }>,\n content: readonly SessionContentBlock[],\n priorIds: ReadonlySet<string>,\n): RemintResult {\n const seen = new Set(priorIds)\n const reminted: Array<{ oldId: string, newId: string }> = []\n // Final id per occurrence, queued per old id so the content walk below\n // can re-associate positionally (handles intra-turn duplicates).\n const finalIdQueues = new Map<string, string[]>()\n\n let changed = false\n const outCalls = toolCalls.map((tc) => {\n let finalId = tc.id\n if (seen.has(tc.id)) {\n let n = 1\n while (seen.has(`${tc.id}_r${n}`))\n n++\n finalId = `${tc.id}_r${n}`\n reminted.push({ oldId: tc.id, newId: finalId })\n changed = true\n }\n seen.add(finalId)\n const queue = finalIdQueues.get(tc.id)\n if (queue)\n queue.push(finalId)\n else\n finalIdQueues.set(tc.id, [finalId])\n return finalId === tc.id ? tc : { ...tc, id: finalId }\n })\n\n if (!changed) {\n return {\n toolCalls: toolCalls as RemintResult['toolCalls'],\n content: content as SessionContentBlock[],\n reminted,\n }\n }\n\n const outContent = content.map((block) => {\n if (block.type !== 'tool_call')\n return block\n const queue = finalIdQueues.get(block.id)\n const finalId = queue?.shift()\n if (finalId === undefined || finalId === block.id)\n return block\n return { ...block, id: finalId }\n })\n\n return { toolCalls: outCalls as RemintResult['toolCalls'], content: outContent, reminted }\n}\n\nfunction syntheticResultBlock(callId: string): SessionContentBlock {\n return {\n type: 'tool_result',\n callId,\n output: SYNTHETIC_TOOL_RESULT_PLACEHOLDER,\n isError: true,\n }\n}\n\nfunction collectResultIds(content: SessionContentBlock[]): Set<string> {\n const ids = new Set<string>()\n for (const block of content) {\n if (block.type === 'tool_result')\n ids.add(block.callId)\n }\n return ids\n}\n\nfunction collectIds<B extends SessionContentBlock>(\n content: SessionContentBlock[],\n type: B['type'],\n getId: (block: B) => string,\n): Set<string> {\n const ids = new Set<string>()\n for (const block of content) {\n if (block.type === type)\n ids.add(getId(block as B))\n }\n return ids\n}\n\n// ---------------------------------------------------------------------------\n// Resume-time filters (L1)\n// ---------------------------------------------------------------------------\n\n/**\n * Drop ASSISTANT turns whose every `tool_call` block is unresolved\n * (no matching `tool_result` block anywhere later in the transcript).\n * Tool_call blocks with at least one matching tool_result are kept — modes\n * 1/3 of {@link ensureToolResultPairing} handle the partial-pair case at\n * wire-send time.\n *\n * Use case: session resume. A turn that emitted three `tool_use` blocks but\n * never persisted the matching `tool_result` turn (process death, crash,\n * `kill -9`) leaves the transcript with an orphan that Anthropic rejects on\n * the FIRST API call after reload. Dropping the whole assistant turn — not\n * just the orphan blocks — preserves text-only turns that legitimately\n * carry reasoning the model wants to see again.\n *\n * Does NOT mint fresh ids: re-id'ing on every resume would cause\n * exponential transcript growth across repeated resumes of an interrupted\n * session.\n *\n * Pure: returns the input reference unchanged when no turn was dropped.\n */\nexport function filterUnresolvedToolUses<T extends { role: string, content: SessionContentBlock[] }>(\n turns: T[],\n): T[] {\n if (turns.length === 0)\n return turns\n\n // Gather every resolved tool_result id (visible anywhere later in the\n // transcript). A tool_use is \"resolved\" iff its id appears in this set.\n const resolvedIds = new Set<string>()\n for (const turn of turns) {\n for (const block of turn.content) {\n if (block.type === 'tool_result')\n resolvedIds.add(block.callId)\n }\n }\n\n let changed = false\n const out: T[] = []\n for (const turn of turns) {\n if (turn.role !== 'assistant') {\n out.push(turn)\n continue\n }\n const toolCalls = turn.content.filter(b => b.type === 'tool_call')\n if (toolCalls.length === 0) {\n out.push(turn)\n continue\n }\n const allUnresolved = toolCalls.every(b => b.type === 'tool_call' && !resolvedIds.has(b.id))\n if (allUnresolved) {\n changed = true\n continue\n }\n out.push(turn)\n }\n return changed ? out : turns\n}\n\n/**\n * Classification of a session's tail state for resume purposes.\n *\n * - `'clean'` — the trailing turn is a user message (the model would respond\n * next), or the transcript is empty. Safe to resume by appending a fresh\n * user prompt.\n * - `'interrupted'` — the trailing turn is an assistant message that has at\n * least one `tool_call` block with no matching `tool_result` anywhere\n * later. The run was almost certainly killed between persisting the\n * assistant turn and persisting its tool-results turn. Hosts that want\n * Claude-Code-style auto-resume can detect this and inject a\n * `\"Continue from where you left off.\"` user message before the next run.\n * - `'completed'` — the trailing turn is an assistant message with no\n * orphan tool_calls. The model considers itself done. Hosts that want to\n * resume must supply a new prompt; auto-continuation here would be a\n * non-sequitur.\n */\nexport type TurnInterruptionState = 'clean' | 'interrupted' | 'completed'\n\n/**\n * Inspect a session's trailing turn to classify whether the run was\n * interrupted mid-tool-call. Pure / synchronous — does not modify the input.\n *\n * Pair with {@link filterUnresolvedToolUses} on the resume path: filter\n * first so the result reflects the post-cleanup state (a turn whose orphans\n * were stripped reads as 'completed', not 'interrupted').\n */\nexport function detectTurnInterruption<T extends { role: string, content: SessionContentBlock[] }>(\n turns: T[],\n): TurnInterruptionState {\n if (turns.length === 0)\n return 'clean'\n const last = turns[turns.length - 1]\n if (last.role === 'user')\n return 'clean'\n if (last.role !== 'assistant')\n return 'clean'\n // Walk all turns to find resolved tool_result ids — a tool_use anywhere\n // earlier in the run may still be answered by a later tool_result.\n const resolvedIds = new Set<string>()\n for (const turn of turns) {\n for (const block of turn.content) {\n if (block.type === 'tool_result')\n resolvedIds.add(block.callId)\n }\n }\n for (const block of last.content) {\n if (block.type === 'tool_call' && !resolvedIds.has(block.id))\n return 'interrupted'\n }\n return 'completed'\n}\n\n/**\n * Default directive injected by {@link ensureEndsWithUserMessage} when the\n * caller doesn't pass one. Neutral enough to read sensibly in any context —\n * compaction passes its own directive, the agent loop falls back to this.\n *\n * The trailing newline is omitted on purpose; provider `userMessage()`\n * helpers wrap the content in the right block shape and any trailing\n * whitespace would land in the wire payload as-is.\n */\nexport const DEFAULT_USER_TAIL_DIRECTIVE = 'Continue.'\n\n/**\n * Guarantee a message list ends with a `role: 'user'` message, appending a\n * synthetic directive when it doesn't.\n *\n * Why: Anthropic's API (and several OpenAI-compat reasoning models — opus\n * 4.7, the o-series translation layers on Bedrock/Vertex) rejects requests\n * whose final message is `role: 'assistant'` with\n * \"This model does not support assistant message prefill. The conversation\n * must end with a user message.\"\n *\n * Triggers in zidane:\n * - Compaction over a session whose last turn is the agent's response\n * (the common case — autocompact fires right after `agent.run()`).\n * - Schema enforcement after an assistant text turn (no `tool_use`, so\n * `ensureToolResultPairing` doesn't synthesize a user tail).\n * - `context:transform` hooks that strip the trailing user turn.\n *\n * The pair-repair pass {@link ensureToolResultPairing} already covers the\n * orphan-`tool_use` case via mode 2; this helper closes the plain-text\n * assistant-tail case. They compose: run pair-repair first, then this\n * pass, so an assistant turn with orphan tool_uses gets its synthetic\n * `tool_result` user turn AND this pass is a no-op (the synthetic turn\n * is already user-role).\n *\n * Empty input passes through unchanged — the caller's \"nothing to send\"\n * guard is responsible for that case; we don't materialize a conversation\n * out of an empty list.\n *\n * Idempotent: returns the input reference unchanged when the list is\n * already user-terminated (or empty).\n *\n * @param messages Wire-ready message list.\n * @param provider Provider whose `userMessage()` shape we use so the\n * synthetic turn matches the wire format the rest of\n * the list already follows.\n * @param directive Text to put in the synthetic user message. Defaults\n * to {@link DEFAULT_USER_TAIL_DIRECTIVE} (\"Continue.\").\n * Compaction overrides this with a summary-specific cue.\n */\nexport function ensureEndsWithUserMessage(\n messages: SessionMessage[],\n provider: Provider,\n directive: string = DEFAULT_USER_TAIL_DIRECTIVE,\n): SessionMessage[] {\n if (messages.length === 0)\n return messages\n if (messages[messages.length - 1].role === 'user')\n return messages\n return [...messages, provider.userMessage(directive)]\n}\n\n// ---------------------------------------------------------------------------\n// toWireMessages — canonical \"give me provider-ready messages\" projection\n// ---------------------------------------------------------------------------\n\nexport interface ToWireMessagesOptions {\n /**\n * Pairing-repair telemetry. Fires once per repair the underlying\n * {@link ensureToolResultPairing} pass performs. Mirrors the\n * `pairing:repair` hook surface so consumers can wire structured logging\n * without an agent instance.\n */\n onRepair?: (repair: PairingRepair) => void\n /**\n * When set, also runs {@link ensureEndsWithUserMessage} so the result is\n * safe for assistant-prefill-rejecting models (opus 4.7, o-series\n * translation layers). Omit to skip — pure pairing repair only.\n */\n provider?: Provider\n /**\n * Override for the synthetic user-tail directive. Only consulted when\n * `provider` is set. Defaults to {@link DEFAULT_USER_TAIL_DIRECTIVE}.\n */\n userTailDirective?: string\n}\n\n/**\n * Build a wire-ready `SessionMessage[]` from raw persisted `SessionTurn[]`.\n *\n * **The canonical \"I want to send these to a provider\" projection.** Use\n * this — not raw `session.turns` / `store.getTurns()` — when constructing a\n * provider request outside `agent.run()`. The agent's own wire pipeline\n * (`executeTurn` in `src/loop.ts`) applies the same repair just-in-time;\n * downstream consumers that bypass the loop hit `tool_result must be\n * preceded by a tool_call` 400s precisely because they shipped raw turns.\n *\n * Pipeline:\n * 1. Filter `system`-role turns (the wire only carries user/assistant).\n * 2. {@link ensureToolResultPairing} — repairs all six orphan / dup\n * corruption modes by inserting synthetic placeholders rather than\n * dropping (preserves the model's tool_use shape).\n * 3. {@link ensureEndsWithUserMessage} when `options.provider` is set —\n * guards against assistant-tail prefill rejection (opus 4.7, o-series).\n *\n * Pure + idempotent. Does not mutate the input turns. Re-running on the\n * output is a no-op.\n *\n * **Do not feed the result back into `session.setTurns` / `appendTurns`.**\n * The repair can insert `SYNTHETIC_TOOL_RESULT_PLACEHOLDER` / `[Orphaned\n * tool result removed …]` markers; round-tripping those into persisted\n * state contaminates the session's reasoning history and defeats the\n * \"don't rewrite the past\" invariant the wire-only repair was designed\n * around.\n */\nexport function toWireMessages(\n turns: readonly { role: 'user' | 'assistant' | 'system', content: SessionContentBlock[] }[],\n options: ToWireMessagesOptions = {},\n): SessionMessage[] {\n const messages: SessionMessage[] = []\n for (const t of turns) {\n if (t.role === 'system')\n continue\n messages.push({ role: t.role, content: t.content })\n }\n const paired = ensureToolResultPairing(messages, options.onRepair ? { onRepair: options.onRepair } : {})\n if (!options.provider)\n return paired\n return ensureEndsWithUserMessage(paired, options.provider, options.userTailDirective)\n}\n\nexport function autoDetectAndConvert(msg: { role: string, content: unknown }): SessionMessage {\n const c: unknown = msg.content\n\n // OpenAI-compat tagged messages\n if (c && typeof c === 'object' && !Array.isArray(c)) {\n const tag = (c as { _tag?: unknown })._tag\n if (typeof tag === 'string' && tag.startsWith('__zidane_'))\n return fromOpenAI(msg)\n }\n\n // Array: inspect block types\n if (Array.isArray(c)) {\n for (const block of c) {\n if (!block || typeof block !== 'object')\n continue\n const b = block as Record<string, unknown>\n if (b.type === 'tool_use' || (b.type === 'tool_result' && 'tool_use_id' in b)) {\n return fromAnthropic(msg)\n }\n if (b.type === 'image_url') {\n return fromOpenAI(msg)\n }\n }\n // Default array → Anthropic\n return fromAnthropic(msg)\n }\n\n // String → either format is the same\n if (typeof c === 'string') {\n return fromAnthropic(msg)\n }\n\n // Default\n return fromAnthropic(msg)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;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AC5F,MAAM,IAAa,IAAI;CAGvB,IAAI,KAAK,OAAO,MAAM,YAAY,CAAC,MAAM,QAAQ,CAAC,GAAG;EACnD,MAAM,MAAO,EAAyB;EACtC,IAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,WAAW,GACvD,OAAO,WAAW,GAAG;CACzB;CAGA,IAAI,MAAM,QAAQ,CAAC,GAAG;EACpB,KAAK,MAAM,SAAS,GAAG;GACrB,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B;GACF,MAAM,IAAI;GACV,IAAI,EAAE,SAAS,cAAe,EAAE,SAAS,iBAAiB,iBAAiB,GACzE,OAAO,cAAc,GAAG;GAE1B,IAAI,EAAE,SAAS,aACb,OAAO,WAAW,GAAG;EAEzB;EAEA,OAAO,cAAc,GAAG;CAC1B;CAGA,IAAI,OAAO,MAAM,UACf,OAAO,cAAc,GAAG;CAI1B,OAAO,cAAc,GAAG;AAC1B"}
@@ -1,5 +1,5 @@
1
- import { t as Agent } from "../agent-BHkvYIH9.js";
2
- import { Hn as HeadlessResult, In as FormattedHeadlessResult, Ln as FormattedHeadlessTurnEvent, Vn as HeadlessOutputFormat, zn as HeadlessEvent } from "../index-C4aT2kO_.js";
1
+ import { t as Agent } from "../agent-B7ilLoh8.js";
2
+ import { An as HeadlessOutputFormat, En as FormattedHeadlessTurnEvent, On as HeadlessEvent, Tn as FormattedHeadlessResult, jn as HeadlessResult } from "../index-C-zEbeFI.js";
3
3
 
4
4
  //#region src/output/stream-json.d.ts
5
5
  type StreamJsonOutputFormat = HeadlessOutputFormat;
@@ -1,4 +1,4 @@
1
- import { i as formattedHeadlessTurnEventToJsonl, n as formatHeadlessResult, o as installHeadlessEventAdapter, r as formatHeadlessTurnEvent } from "../headless-CPaunZsU.js";
1
+ import { i as formattedHeadlessTurnEventToJsonl, n as formatHeadlessResult, o as installHeadlessEventAdapter, r as formatHeadlessTurnEvent } from "../headless-CYHU4ZB-.js";
2
2
  //#region src/output/stream-json.ts
3
3
  function resolveFormatOptions(options) {
4
4
  return {
@@ -1,5 +1,5 @@
1
- import { r as AgentHooks, t as Agent } from "../agent-BHkvYIH9.js";
2
- import { t as Preset } from "../index-C4aT2kO_.js";
1
+ import { r as AgentHooks, t as Agent } from "../agent-B7ilLoh8.js";
2
+ import { t as Preset } from "../index-C-zEbeFI.js";
3
3
 
4
4
  //#region src/output/terminal.d.ts
5
5
  interface TerminalOutputOptions {
@@ -237,6 +237,7 @@ async function setupTerminalOutput(agent, model, prompt, preset, options = {}) {
237
237
  line += ` in ${chalk.green(timeStr)}`;
238
238
  if (totalCacheCreation || totalCacheRead) line += `\n Cache: ${chalk.blue(totalCacheCreation)} created / ${chalk.blue(totalCacheRead)} read`;
239
239
  if (cost) line += `\n💸 Cost: ${chalk.yellow(`$${cost.toFixed(6)}`)}`;
240
+ if (agent.execution.type === "sandbox" && agent.handle?.id) line += `\n📦 Sandbox: ${chalk.cyan(agent.handle.id)}`;
240
241
  if (children && children.length > 0) {
241
242
  line += `\n Children: ${chalk.magenta(children.length)}`;
242
243
  for (const child of children) {