zidane 5.6.11 → 5.6.13

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 (64) hide show
  1. package/README.md +19 -2
  2. package/dist/{agent-C9AKTU_V.d.ts → agent-ClkpElCZ.d.ts} +540 -55
  3. package/dist/agent-ClkpElCZ.d.ts.map +1 -0
  4. package/dist/chat.d.ts +47 -17
  5. package/dist/chat.d.ts.map +1 -1
  6. package/dist/chat.js +3 -3
  7. package/dist/{index-6f4T7Gc0.d.ts → index-CTDMMdIy.d.ts} +348 -3
  8. package/dist/index-CTDMMdIy.d.ts.map +1 -0
  9. package/dist/{index-DPN7TcXK.d.ts → index-v3Tzobqr.d.ts} +2 -2
  10. package/dist/{index-DPN7TcXK.d.ts.map → index-v3Tzobqr.d.ts.map} +1 -1
  11. package/dist/index.d.ts +4 -4
  12. package/dist/index.js +169 -8
  13. package/dist/index.js.map +1 -1
  14. package/dist/{login-BindcfKi.js → login-DS3sf6b5.js} +4 -4
  15. package/dist/{login-BindcfKi.js.map → login-DS3sf6b5.js.map} +1 -1
  16. package/dist/{mcp-0jRkIV0g.js → mcp-DGeB7-3D.js} +13 -2
  17. package/dist/mcp-DGeB7-3D.js.map +1 -0
  18. package/dist/mcp.d.ts +1 -1
  19. package/dist/mcp.js +1 -1
  20. package/dist/{messages-BfmXLDT4.js → messages-Dym8S_YH.js} +303 -8
  21. package/dist/messages-Dym8S_YH.js.map +1 -0
  22. package/dist/{presets-CmzMeWg2.js → presets-CZXS_87d.js} +2 -2
  23. package/dist/{presets-CmzMeWg2.js.map → presets-CZXS_87d.js.map} +1 -1
  24. package/dist/presets.d.ts +2 -2
  25. package/dist/presets.js +1 -1
  26. package/dist/{providers-C_ahnRBS.js → providers-beXyD9W9.js} +137 -21
  27. package/dist/providers-beXyD9W9.js.map +1 -0
  28. package/dist/providers.d.ts +2 -2
  29. package/dist/providers.js +3 -3
  30. package/dist/restate.d.ts +1 -1
  31. package/dist/session/sqlite.d.ts +1 -1
  32. package/dist/{session-PUzXZlG6.js → session-BRIsmBSY.js} +5 -2
  33. package/dist/session-BRIsmBSY.js.map +1 -0
  34. package/dist/session.d.ts +2 -2
  35. package/dist/session.js +3 -3
  36. package/dist/skills.d.ts +2 -2
  37. package/dist/{tools-CxOfTt3R.js → tools-DE9pR_NG.js} +515 -116
  38. package/dist/tools-DE9pR_NG.js.map +1 -0
  39. package/dist/tools.d.ts +3 -3
  40. package/dist/tools.js +1 -1
  41. package/dist/{transcript-anchors-DDCHSDdX.d.ts → transcript-anchors-D0TR6djV.d.ts} +4 -4
  42. package/dist/transcript-anchors-D0TR6djV.d.ts.map +1 -0
  43. package/dist/tui.d.ts +2 -2
  44. package/dist/tui.d.ts.map +1 -1
  45. package/dist/tui.js +12 -8
  46. package/dist/tui.js.map +1 -1
  47. package/dist/{turn-operations-CxE8BBau.js → turn-operations-6Yls2HuG.js} +907 -42
  48. package/dist/turn-operations-6Yls2HuG.js.map +1 -0
  49. package/dist/types-oKPBdCmL.js.map +1 -1
  50. package/dist/types.d.ts +3 -3
  51. package/docs/ARCHITECTURE.md +101 -20
  52. package/docs/CHAT.md +27 -5
  53. package/docs/RESTATE.md +1 -1
  54. package/docs/SKILL.md +39 -3
  55. package/package.json +5 -2
  56. package/dist/agent-C9AKTU_V.d.ts.map +0 -1
  57. package/dist/index-6f4T7Gc0.d.ts.map +0 -1
  58. package/dist/mcp-0jRkIV0g.js.map +0 -1
  59. package/dist/messages-BfmXLDT4.js.map +0 -1
  60. package/dist/providers-C_ahnRBS.js.map +0 -1
  61. package/dist/session-PUzXZlG6.js.map +0 -1
  62. package/dist/tools-CxOfTt3R.js.map +0 -1
  63. package/dist/transcript-anchors-DDCHSDdX.d.ts.map +0 -1
  64. package/dist/turn-operations-CxE8BBau.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages-Dym8S_YH.js","names":[],"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 * 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.\n */\nexport function fillEstimatedCost(usage: TurnUsage, provider: string): 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 return usage\n }\n\n const rates = model?.cost\n if (!rates)\n return usage\n\n const total\n = ((rates.input ?? 0) * (usage.input ?? 0)\n + (rates.output ?? 0) * (usage.output ?? 0)\n + (rates.cacheRead ?? 0) * (usage.cacheRead ?? 0)\n + (rates.cacheWrite ?? 0) * (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, TurnFinishReason } from '../types'\nimport { errorMessage, matchesContextExceeded } from '../errors'\nimport { renderSystemForWire, splitSystemPrompt } from '../system-prompt'\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\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 bytes may accumulate between two newline boundaries when\n * parsing an SSE stream. A broken or malicious server that emits an unbounded\n * stream of non-newline bytes would otherwise grow `buffer` without end and\n * eventually OOM the host. 8 MB is safely above the largest tool-call arg\n * JSON we reasonably expect and still catches a pathological stream in ~1 s on\n * a 10 MB/s connection.\n */\nconst SSE_MAX_BUFFER_BYTES = 8 * 1024 * 1024\n\nexport class OpenAICompatStreamError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'OpenAICompatStreamError'\n }\n}\n\nexport async function consumeSSE(\n response: Response,\n callbacks: StreamCallbacks,\n signal?: AbortSignal,\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: { input: number, output: number, cost?: number, cacheRead?: number, cacheCreation?: number } = { input: 0, output: 0 }\n const tcMap = new Map<number, { id: string, name: string, args: string }>()\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 if (signal?.aborted)\n break\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_BYTES) {\n throw new OpenAICompatStreamError(\n `SSE buffer exceeded ${SSE_MAX_BUFFER_BYTES} bytes 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 if (!line.startsWith('data: '))\n continue\n const data = line.slice(6).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 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 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}`,\n name: tc.function?.name || '',\n args: tc.function?.arguments || '',\n })\n }\n }\n }\n\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 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 usage = {\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 }\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\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 }\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 OpenRouter-style `reasoning_details` echoed back on assistant\n * messages. When `true`, `provider_reasoning` blocks whose `producer`/`model`\n * match the active route are forwarded; when `false` (default), they are\n * silently dropped to avoid 400s on hosts that strict-validate the schema.\n */\n supportsReasoning?: 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 activeModel = options.model\n\n for (const msg of messages) {\n const toolResults = msg.content.filter(b => b.type === 'tool_result')\n const toolCalls = msg.content.filter(b => b.type === 'tool_call')\n const textBlocks = msg.content.filter(b => b.type === 'text')\n const imageBlocks = msg.content.filter(b => b.type === 'image')\n // Provider-bound reasoning state — attached to the assistant message below\n // when the host supports it AND the active route matches the producer.\n const reasoningBlocks = reasoningEnabled\n ? msg.content\n .filter(b => b.type === 'provider_reasoning')\n .filter((b) => {\n if (b.producer !== 'openrouter')\n return false\n if (b.model && activeModel && b.model !== activeModel)\n return false\n return true\n })\n : []\n const reasoningDetails = reasoningBlocks.flatMap(b => b.details)\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.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 continue\n }\n\n // Tool calls → assistant message with tool_calls array\n if (toolCalls.length > 0) {\n const textContent = textBlocks.length > 0 ? textBlocks[0].text : 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 out.push(m)\n continue\n }\n\n // Images → multimodal array\n if (imageBlocks.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 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 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 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\nexport function buildAssistantContent(\n text: string,\n toolCalls: { id: string, name: string, input: Record<string, unknown> }[],\n thinking?: string,\n reasoning?: { details: unknown[], producer: 'openrouter', 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 if (reasoning && reasoning.details.length > 0) {\n const block: Extract<SessionContentBlock, { type: 'provider_reasoning' }> = {\n type: 'provider_reasoning',\n producer: reasoning.producer,\n details: reasoning.details,\n }\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 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 if (!err || typeof err !== 'object')\n return null\n\n if ((err as { name?: unknown }).name === 'AbortError')\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 return {\n kind: 'provider_error',\n providerCode: code ?? String(err.status),\n message: msg,\n retryable: isRetryableHttpStatus(err.status),\n }\n}\n\n/**\n * 429 + 5xx (except 501 Not Implemented) are safe to retry with backoff;\n * 4xx other than 429 are terminal (bad request, auth, not found, etc.).\n */\nfunction isRetryableHttpStatus(status: number): boolean {\n if (status === 429)\n return true\n if (status >= 500 && status !== 501)\n return true\n return false\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 OpenRouter's normalized reasoning envelope —\n * `reasoning: { effort | max_tokens | exclude }` on requests and structured\n * `reasoning_details[]` on assistant messages, round-tripped to preserve\n * extended-reasoning state across turns.\n *\n * - `true` — map zidane's `behavior.thinking` / `behavior.thinkingBudget` to\n * the request's `reasoning` field, capture `reasoning_details`\n * from streaming responses into `provider_reasoning` blocks, and\n * echo them back on subsequent assistant messages.\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 * 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\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\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\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 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 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 model: modelId,\n messages,\n max_tokens: maxTokens,\n stream: true,\n }\n\n // OpenRouter normalized reasoning request field. Only set when the host\n // advertises support — Chat Completions hosts that don't speak it would\n // 400 on the unknown field.\n if (reasoningEnabled) {\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\n return {\n assistantMessage: buildAssistantContent(\n result.text,\n result.toolCalls,\n result.thinking,\n reasoningEnabled && result.reasoningDetails.length > 0\n ? { details: result.reasoningDetails, producer: 'openrouter', model: modelId }\n : undefined,\n ),\n text: result.text,\n toolCalls: result.toolCalls,\n done: result.finishReason === 'stop' || result.toolCalls.length === 0,\n usage: fillEstimatedCost({\n input: result.usage.input,\n output: result.usage.output,\n ...(result.usage.cacheRead !== undefined ? { cacheRead: result.usage.cacheRead } : {}),\n ...(result.usage.cacheCreation !== undefined ? { cacheCreation: result.usage.cacheCreation } : {}),\n ...(result.usage.cost !== undefined ? { cost: result.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 } from '../types'\nimport { ASSISTANT_TOOL_CALLS_TAG, TOOL_RESULTS_TAG } from '../providers/openai-compat'\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 * 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 return {\n type: 'image' as const,\n source: { type: 'base64' as const, media_type: b.mediaType, data: 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 === '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 // 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 const input: Record<string, unknown> = rawArgs\n ? (typeof rawArgs === 'string' ? JSON.parse(rawArgs) : 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 }\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 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: '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\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 OpenRouter envelope;\n // 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 .map((block): AnthropicWireBlock => {\n switch (block.type) {\n case 'text':\n return { type: 'text', text: block.text }\n case 'image':\n return { type: 'image', source: { type: 'base64', media_type: block.mediaType, data: block.data } }\n case 'tool_call':\n return { type: 'tool_use', id: block.id, name: block.name, input: block.input }\n case 'tool_result': {\n const out: AnthropicWireBlock = {\n type: 'tool_result',\n tool_use_id: block.callId,\n content: encodeAnthropicToolResultContent(block.output),\n }\n if (block.isError)\n out.is_error = true\n return out\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 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\n // Tool results → tagged format\n if (toolResults.length > 0) {\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 },\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 → multimodal array\n if (imageBlocks.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 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\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\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAa,yBAAyB;;;;;;;;;;;;;;;;;;;;;AA8BtC,SAAgB,kBAAkB,QAAmC;CACnE,IAAI,OAAO,WAAW,GACpB,OAAO;EAAE,QAAQ;EAAI,SAAS;EAAI;CACpC,MAAM,MAAM,OAAO,QAAQ,uBAAuB;CAClD,IAAI,MAAM,GACR,OAAO;EAAE,QAAQ;EAAQ,SAAS;EAAI;CACxC,MAAM,aAAa,OAAO,MAAM,GAAG,IAAI;CACvC,MAAM,cAAc,OAAO,MAAM,MAAM,GAA8B;CAMrE,OAAO;EACL,QAAQ,sBAAsB,WAAW;EACzC,SAAS,qBAAqB,YAAY;EAC3C;;;;;;;;;;;;;AAcH,SAAgB,iBAAiB,YAAoB,aAA6B;CAChF,IAAI,YAAY,WAAW,GACzB,OAAO;CACT,IAAI,WAAW,WAAW,GACxB,OAAO,GAAG,uBAAuB,MAAM;CACzC,OAAO,GAAG,WAAW,MAAM,uBAAuB,MAAM;;;;;;;;;;;;;;AAe1D,SAAgB,oBAAoB,QAAgB,OAAuB;CACzE,IAAI,MAAM,WAAW,GACnB,OAAO;CACT,MAAM,EAAE,QAAQ,YAAY,YAAY,kBAAkB,OAAO;CAEjE,OAAO,iBADY,WAAW,WAAW,IAAI,QA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d,OACA,UAAiC,EAAE,EACjB;CAClB,MAAM,WAA6B,EAAE;CACrC,KAAK,MAAM,KAAK,OAAO;EACrB,IAAI,EAAE,SAAS,UACb;EACF,SAAS,KAAK;GAAE,MAAM,EAAE;GAAM,SAAS,EAAE;GAAS,CAAC;;CAErD,MAAM,SAAS,wBAAwB,UAAU,QAAQ,WAAW,EAAE,UAAU,QAAQ,UAAU,GAAG,EAAE,CAAC;CACxG,IAAI,CAAC,QAAQ,UACX,OAAO;CACT,OAAO,0BAA0B,QAAQ,QAAQ,UAAU,QAAQ,kBAAkB;;AAGvF,SAAgB,qBAAqB,KAAyD;CAC5F,MAAM,IAAa,IAAI;CAGvB,IAAI,KAAK,OAAO,MAAM,YAAY,CAAC,MAAM,QAAQ,EAAE,EAAE;EACnD,MAAM,MAAO,EAAyB;EACtC,IAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,YAAY,EACxD,OAAO,WAAW,IAAI;;CAI1B,IAAI,MAAM,QAAQ,EAAE,EAAE;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,IAAI;GAE3B,IAAI,EAAE,SAAS,aACb,OAAO,WAAW,IAAI;;EAI1B,OAAO,cAAc,IAAI;;CAI3B,IAAI,OAAO,MAAM,UACf,OAAO,cAAc,IAAI;CAI3B,OAAO,cAAc,IAAI"}
@@ -1,4 +1,4 @@
1
- import { a as multiEdit, i as readFile, n as createSpawnTool, o as listFiles, r as shellKill, t as writeFile, u as edit, y as shell } from "./tools-CxOfTt3R.js";
1
+ import { a as multiEdit, i as readFile, n as createSpawnTool, o as listFiles, r as shellKill, t as writeFile, u as edit, y as shell } from "./tools-DE9pR_NG.js";
2
2
  //#region src/presets/basic.ts
3
3
  /**
4
4
  * Core tools available in every basic preset (without spawn).
@@ -107,4 +107,4 @@ function composePresets(...presets) {
107
107
  //#endregion
108
108
  export { basic_default as i, definePreset as n, basicTools as r, composePresets as t };
109
109
 
110
- //# sourceMappingURL=presets-CmzMeWg2.js.map
110
+ //# sourceMappingURL=presets-CZXS_87d.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"presets-CmzMeWg2.js","names":[],"sources":["../src/presets/basic.ts","../src/presets/index.ts"],"sourcesContent":["import { definePreset } from '.'\nimport { edit, listFiles, multiEdit, readFile, shell, shellKill, writeFile } from '../tools'\nimport { createSpawnTool } from '../tools/spawn'\n\n/**\n * Core tools available in every basic preset (without spawn).\n *\n * `edit` and `multi_edit` ship in the basic set because surgical edits are the\n * default modality for production agents — `write_file` is for full overwrites.\n * `glob` and `grep` are exported but opt-in: not every agent needs codebase\n * search, and shipping them by default would force `tool:gate` work onto\n * consumers that prefer the model to use `shell` + classic Unix tools.\n */\nexport const basicTools = { shell, shellKill, readFile, writeFile, listFiles, edit, multiEdit }\n\nexport default definePreset({\n name: 'basic',\n system: 'You are a helpful assistant with access to shell, file reading, file writing, surgical and multi-edit tools, directory listing, and sub-agent spawning. Prefer `edit` / `multi_edit` for in-place changes and `write_file` for full file overwrites. Use them to accomplish tasks in the project directory.',\n // `persist: true` shares the parent's session with every child agent — child\n // turns land in `session.turns` tagged with their own `runId`, and the run\n // itself is recorded in `session.runs` with `parentRunId` + `depth`. That's\n // what lets a reloaded TUI session reconstruct the full subagent tree (see\n // `eventsFromTurns` in `tui/store.ts`). Hosts that want children in-memory\n // only can construct their own preset with `createSpawnTool()`.\n tools: { ...basicTools, spawn: createSpawnTool({ persist: true }) },\n})\n","import type { AgentHooks, AgentOptions } from '../agent'\n\nexport type { AgentHookMap } from '../agent'\n\n/**\n * A preset is a reusable slice of `AgentOptions` — spread it into `createAgent()`\n * to configure tools, a default system prompt, aliases, behavior defaults, and\n * agent-lifetime hooks.\n *\n * `provider`, `execution`, `session`, and internal fields are excluded so presets\n * remain shareable and composable.\n *\n * ```ts\n * import { basic } from 'zidane/presets'\n * createAgent({ ...basic, provider })\n * ```\n *\n * ### Composing multiple presets\n *\n * Bare `...spread` is shallow — `{ ...a, ...b }` overwrites every key `b`\n * defines, including `hooks`. Use {@link composePresets} when you want\n * field-aware merging (per-event hook concat, tools shallow-merge, etc.):\n *\n * ```ts\n * createAgent({ ...composePresets(basic, telemetry, mine), provider })\n * ```\n */\nexport type Preset = Omit<Partial<AgentOptions>, 'provider' | 'execution' | 'session' | 'mcpConnector'>\n\n/**\n * Identity helper for type inference when defining a preset.\n */\nexport function definePreset(config: Preset): Preset {\n return config\n}\n\n/**\n * Field-aware composition of presets. Right-most preset wins for scalar fields;\n * objects shallow-merge; arrays and hook handler lists concatenate. Designed so\n * stacking presets does the obvious thing without the spread-collision footgun:\n *\n * - `name`, `system`, `eager`, `skills` → last-defined wins\n * - `tools`, `toolAliases`, `behavior` → shallow-merge (later keys override)\n * - `behavior.dedupTools`, `behavior.toolBudgets` → **deep-merge** (per-tool-name; later wins on collision)\n * - `mcpServers` → concat with last-wins on `name` collision\n * - `hooks` → per-event concat; every handler fires\n *\n * `hooks` always emerges as `event → handler[]` so downstream registration\n * (in `createAgent`) sees a uniform shape. Order of handlers within an event\n * follows preset order: earlier presets register first.\n *\n * `mcpServers` is deduped by `name` because shipping two servers with the same\n * name would trip the connector at runtime — a later preset overriding an\n * earlier preset's `github` server is the practical intent.\n *\n * `behavior.dedupTools` and `behavior.toolBudgets` get the same per-key deep-merge\n * because they are tool-name-keyed records — a preset that ships a dedup hasher\n * for one tool should not erase a hasher another preset ships for a different\n * tool. Last-wins still applies on a per-tool collision so a downstream preset\n * can override an upstream preset's policy for one specific tool. Other\n * `behavior` fields keep last-wins semantics.\n */\nexport function composePresets(...presets: Preset[]): Preset {\n const out: Preset = {}\n const hooksByEvent: { [K in keyof AgentHooks]?: AgentHooks[K][] } = {}\n // Keep mcpServers in source-order on first sight, but allow later\n // declarations to override earlier ones with the same `name`. A `Map`\n // keyed by name gives O(1) override + stable iteration.\n const mcpByName = new Map<string, NonNullable<Preset['mcpServers']>[number]>()\n\n for (const p of presets) {\n if (p.name !== undefined)\n out.name = p.name\n if (p.system !== undefined)\n out.system = p.system\n if (p.eager !== undefined)\n out.eager = p.eager\n if (p.skills !== undefined)\n out.skills = p.skills\n if (p.tools)\n out.tools = { ...out.tools, ...p.tools }\n if (p.toolAliases)\n out.toolAliases = { ...out.toolAliases, ...p.toolAliases }\n if (p.behavior) {\n // Top-level shallow-merge first; then deep-merge the two tool-name-keyed\n // sub-records so per-tool entries from earlier presets aren't clobbered.\n const merged: NonNullable<Preset['behavior']> = { ...out.behavior, ...p.behavior }\n if (out.behavior?.dedupTools || p.behavior.dedupTools) {\n merged.dedupTools = { ...out.behavior?.dedupTools, ...p.behavior.dedupTools }\n }\n if (out.behavior?.toolBudgets || p.behavior.toolBudgets) {\n merged.toolBudgets = { ...out.behavior?.toolBudgets, ...p.behavior.toolBudgets }\n }\n out.behavior = merged\n }\n if (p.mcpServers) {\n for (const server of p.mcpServers)\n mcpByName.set(server.name, server)\n }\n if (p.hooks) {\n for (const [event, handler] of Object.entries(p.hooks)) {\n if (handler === undefined)\n continue\n const list = Array.isArray(handler) ? handler : [handler]\n const key = event as keyof AgentHooks\n // Safe cast: we read the loose `AgentHookMap` shape (handler-or-array)\n // and re-emit only as arrays. Each `list` element matches the event's\n // handler signature by construction (the input was typed `AgentHookMap`).\n const bucket = (hooksByEvent[key] ??= []) as unknown[]\n bucket.push(...(list as unknown[]))\n }\n }\n }\n\n if (mcpByName.size > 0)\n out.mcpServers = [...mcpByName.values()]\n\n if (Object.keys(hooksByEvent).length > 0)\n out.hooks = hooksByEvent\n\n return out\n}\n\nexport { default as basic, basicTools } from './basic'\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,aAAa;CAAE;CAAO;CAAW;CAAU;CAAW;CAAW;CAAM;CAAW;AAE/F,IAAA,gBAAe,aAAa;CAC1B,MAAM;CACN,QAAQ;CAOR,OAAO;EAAE,GAAG;EAAY,OAAO,gB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AAC,QAAQ;GACzD,MAAM,MAAM;GAKZ,CADgB,aAAa,SAAS,EAAE,EACjC,KAAK,GAAI,KAAmB;;;CAKzC,IAAI,UAAU,OAAO,GACnB,IAAI,aAAa,CAAC,GAAG,UAAU,QAAQ,CAAC;CAE1C,IAAI,OAAO,KAAK,aAAa,CAAC,SAAS,GACrC,IAAI,QAAQ;CAEd,OAAO"}
1
+ {"version":3,"file":"presets-CZXS_87d.js","names":[],"sources":["../src/presets/basic.ts","../src/presets/index.ts"],"sourcesContent":["import { definePreset } from '.'\nimport { edit, listFiles, multiEdit, readFile, shell, shellKill, writeFile } from '../tools'\nimport { createSpawnTool } from '../tools/spawn'\n\n/**\n * Core tools available in every basic preset (without spawn).\n *\n * `edit` and `multi_edit` ship in the basic set because surgical edits are the\n * default modality for production agents — `write_file` is for full overwrites.\n * `glob` and `grep` are exported but opt-in: not every agent needs codebase\n * search, and shipping them by default would force `tool:gate` work onto\n * consumers that prefer the model to use `shell` + classic Unix tools.\n */\nexport const basicTools = { shell, shellKill, readFile, writeFile, listFiles, edit, multiEdit }\n\nexport default definePreset({\n name: 'basic',\n system: 'You are a helpful assistant with access to shell, file reading, file writing, surgical and multi-edit tools, directory listing, and sub-agent spawning. Prefer `edit` / `multi_edit` for in-place changes and `write_file` for full file overwrites. Use them to accomplish tasks in the project directory.',\n // `persist: true` shares the parent's session with every child agent — child\n // turns land in `session.turns` tagged with their own `runId`, and the run\n // itself is recorded in `session.runs` with `parentRunId` + `depth`. That's\n // what lets a reloaded TUI session reconstruct the full subagent tree (see\n // `eventsFromTurns` in `tui/store.ts`). Hosts that want children in-memory\n // only can construct their own preset with `createSpawnTool()`.\n tools: { ...basicTools, spawn: createSpawnTool({ persist: true }) },\n})\n","import type { AgentHooks, AgentOptions } from '../agent'\n\nexport type { AgentHookMap } from '../agent'\n\n/**\n * A preset is a reusable slice of `AgentOptions` — spread it into `createAgent()`\n * to configure tools, a default system prompt, aliases, behavior defaults, and\n * agent-lifetime hooks.\n *\n * `provider`, `execution`, `session`, and internal fields are excluded so presets\n * remain shareable and composable.\n *\n * ```ts\n * import { basic } from 'zidane/presets'\n * createAgent({ ...basic, provider })\n * ```\n *\n * ### Composing multiple presets\n *\n * Bare `...spread` is shallow — `{ ...a, ...b }` overwrites every key `b`\n * defines, including `hooks`. Use {@link composePresets} when you want\n * field-aware merging (per-event hook concat, tools shallow-merge, etc.):\n *\n * ```ts\n * createAgent({ ...composePresets(basic, telemetry, mine), provider })\n * ```\n */\nexport type Preset = Omit<Partial<AgentOptions>, 'provider' | 'execution' | 'session' | 'mcpConnector'>\n\n/**\n * Identity helper for type inference when defining a preset.\n */\nexport function definePreset(config: Preset): Preset {\n return config\n}\n\n/**\n * Field-aware composition of presets. Right-most preset wins for scalar fields;\n * objects shallow-merge; arrays and hook handler lists concatenate. Designed so\n * stacking presets does the obvious thing without the spread-collision footgun:\n *\n * - `name`, `system`, `eager`, `skills` → last-defined wins\n * - `tools`, `toolAliases`, `behavior` → shallow-merge (later keys override)\n * - `behavior.dedupTools`, `behavior.toolBudgets` → **deep-merge** (per-tool-name; later wins on collision)\n * - `mcpServers` → concat with last-wins on `name` collision\n * - `hooks` → per-event concat; every handler fires\n *\n * `hooks` always emerges as `event → handler[]` so downstream registration\n * (in `createAgent`) sees a uniform shape. Order of handlers within an event\n * follows preset order: earlier presets register first.\n *\n * `mcpServers` is deduped by `name` because shipping two servers with the same\n * name would trip the connector at runtime — a later preset overriding an\n * earlier preset's `github` server is the practical intent.\n *\n * `behavior.dedupTools` and `behavior.toolBudgets` get the same per-key deep-merge\n * because they are tool-name-keyed records — a preset that ships a dedup hasher\n * for one tool should not erase a hasher another preset ships for a different\n * tool. Last-wins still applies on a per-tool collision so a downstream preset\n * can override an upstream preset's policy for one specific tool. Other\n * `behavior` fields keep last-wins semantics.\n */\nexport function composePresets(...presets: Preset[]): Preset {\n const out: Preset = {}\n const hooksByEvent: { [K in keyof AgentHooks]?: AgentHooks[K][] } = {}\n // Keep mcpServers in source-order on first sight, but allow later\n // declarations to override earlier ones with the same `name`. A `Map`\n // keyed by name gives O(1) override + stable iteration.\n const mcpByName = new Map<string, NonNullable<Preset['mcpServers']>[number]>()\n\n for (const p of presets) {\n if (p.name !== undefined)\n out.name = p.name\n if (p.system !== undefined)\n out.system = p.system\n if (p.eager !== undefined)\n out.eager = p.eager\n if (p.skills !== undefined)\n out.skills = p.skills\n if (p.tools)\n out.tools = { ...out.tools, ...p.tools }\n if (p.toolAliases)\n out.toolAliases = { ...out.toolAliases, ...p.toolAliases }\n if (p.behavior) {\n // Top-level shallow-merge first; then deep-merge the two tool-name-keyed\n // sub-records so per-tool entries from earlier presets aren't clobbered.\n const merged: NonNullable<Preset['behavior']> = { ...out.behavior, ...p.behavior }\n if (out.behavior?.dedupTools || p.behavior.dedupTools) {\n merged.dedupTools = { ...out.behavior?.dedupTools, ...p.behavior.dedupTools }\n }\n if (out.behavior?.toolBudgets || p.behavior.toolBudgets) {\n merged.toolBudgets = { ...out.behavior?.toolBudgets, ...p.behavior.toolBudgets }\n }\n out.behavior = merged\n }\n if (p.mcpServers) {\n for (const server of p.mcpServers)\n mcpByName.set(server.name, server)\n }\n if (p.hooks) {\n for (const [event, handler] of Object.entries(p.hooks)) {\n if (handler === undefined)\n continue\n const list = Array.isArray(handler) ? handler : [handler]\n const key = event as keyof AgentHooks\n // Safe cast: we read the loose `AgentHookMap` shape (handler-or-array)\n // and re-emit only as arrays. Each `list` element matches the event's\n // handler signature by construction (the input was typed `AgentHookMap`).\n const bucket = (hooksByEvent[key] ??= []) as unknown[]\n bucket.push(...(list as unknown[]))\n }\n }\n }\n\n if (mcpByName.size > 0)\n out.mcpServers = [...mcpByName.values()]\n\n if (Object.keys(hooksByEvent).length > 0)\n out.hooks = hooksByEvent\n\n return out\n}\n\nexport { default as basic, basicTools } from './basic'\n"],"mappings":";;;;;;;;;;;AAaA,MAAa,aAAa;CAAE;CAAO;CAAW;CAAU;CAAW;CAAW;CAAM;CAAW;AAE/F,IAAA,gB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,IAAI,YAAY,KAAA,GACd;GACF,MAAM,OAAO,MAAM,QAAQ,QAAQ,GAAG,UAAU,CAAC,QAAQ;GACzD,MAAM,MAAM;GAKZ,CADgB,aAAa,SAAS,EAAE,EACjC,KAAK,GAAI,KAAmB;;;CAKzC,IAAI,UAAU,OAAO,GACnB,IAAI,aAAa,CAAC,GAAG,UAAU,QAAQ,CAAC;CAE1C,IAAI,OAAO,KAAK,aAAa,CAAC,SAAS,GACrC,IAAI,QAAQ;CAEd,OAAO"}
package/dist/presets.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { n as AgentHookMap } from "./agent-C9AKTU_V.js";
2
- import { a as basicTools, i as _default, n as composePresets, r as definePreset, t as Preset } from "./index-6f4T7Gc0.js";
1
+ import { n as AgentHookMap } from "./agent-ClkpElCZ.js";
2
+ import { a as basicTools, i as _default, n as composePresets, r as definePreset, t as Preset } from "./index-CTDMMdIy.js";
3
3
  export { AgentHookMap, Preset, _default as basic, basicTools, composePresets, definePreset };
package/dist/presets.js CHANGED
@@ -1,2 +1,2 @@
1
- import { i as basic_default, n as definePreset, r as basicTools, t as composePresets } from "./presets-CmzMeWg2.js";
1
+ import { i as basic_default, n as definePreset, r as basicTools, t as composePresets } from "./presets-CZXS_87d.js";
2
2
  export { basic_default as basic, basicTools, composePresets, definePreset };