zidane 5.3.0 → 5.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-CYpPKn5Z.d.ts → agent-bKs7MRT2.d.ts} +430 -5
- package/dist/agent-bKs7MRT2.d.ts.map +1 -0
- package/dist/chat.d.ts +310 -6
- package/dist/chat.d.ts.map +1 -1
- package/dist/chat.js +2 -2
- package/dist/{errors-COmsomd5.js → errors-Byb0F8B9.js} +44 -2
- package/dist/errors-Byb0F8B9.js.map +1 -0
- package/dist/{index-D-cTScN3.d.ts → index-BlMvPh9X.d.ts} +57 -10
- package/dist/index-BlMvPh9X.d.ts.map +1 -0
- package/dist/{index-Cc-q1hLT.d.ts → index-CTmNaIDb.d.ts} +2 -2
- package/dist/{index-Cc-q1hLT.d.ts.map → index-CTmNaIDb.d.ts.map} +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +10 -10
- package/dist/{interpolate-BhmHKD6x.js → interpolate-ERgZUxgg.js} +2 -2
- package/dist/{interpolate-BhmHKD6x.js.map → interpolate-ERgZUxgg.js.map} +1 -1
- package/dist/{login-BXVt5wuA.js → login-CNS9_8Ue.js} +3 -3
- package/dist/{login-BXVt5wuA.js.map → login-CNS9_8Ue.js.map} +1 -1
- package/dist/{mcp-B1psg7jf.js → mcp-ZsSFo4Dp.js} +2 -2
- package/dist/{mcp-B1psg7jf.js.map → mcp-ZsSFo4Dp.js.map} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +1 -1
- package/dist/{messages-DsbMYNmt.js → messages-D0xT979U.js} +631 -68
- package/dist/messages-D0xT979U.js.map +1 -0
- package/dist/{presets-tvD28pCu.js → presets-h5i3kpOP.js} +29 -10
- package/dist/presets-h5i3kpOP.js.map +1 -0
- package/dist/presets.d.ts +2 -2
- package/dist/presets.js +1 -1
- package/dist/{providers-v1Rn2rqG.js → providers-x3LZByR5.js} +38 -6
- package/dist/providers-x3LZByR5.js.map +1 -0
- package/dist/providers.d.ts +2 -2
- package/dist/providers.js +3 -3
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/session/sqlite.js +1 -1
- package/dist/{session-DOJgRXvF.js → session-BHZwxmfr.js} +2 -2
- package/dist/{session-DOJgRXvF.js.map → session-BHZwxmfr.js.map} +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/session.js +2 -2
- package/dist/skills.d.ts +2 -2
- package/dist/skills.js +1 -1
- package/dist/{tools-CMVruxF0.js → tools-CWEDS2ZT.js} +380 -48
- package/dist/tools-CWEDS2ZT.js.map +1 -0
- package/dist/tools.d.ts +2 -2
- package/dist/tools.js +1 -1
- package/dist/{transcript-anchors-eyhlGeBI.d.ts → transcript-anchors-DOUqyvXR.d.ts} +28 -4
- package/dist/transcript-anchors-DOUqyvXR.d.ts.map +1 -0
- package/dist/tui.d.ts +29 -3
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +365 -80
- package/dist/tui.js.map +1 -1
- package/dist/{turn-operations-Y7e15gJf.js → turn-operations-D9HvatsR.js} +678 -33
- package/dist/turn-operations-D9HvatsR.js.map +1 -0
- package/dist/types-IcokUOyC.js.map +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/types.js +1 -1
- package/package.json +1 -1
- package/dist/agent-CYpPKn5Z.d.ts.map +0 -1
- package/dist/errors-COmsomd5.js.map +0 -1
- package/dist/index-D-cTScN3.d.ts.map +0 -1
- package/dist/messages-DsbMYNmt.js.map +0 -1
- package/dist/presets-tvD28pCu.js.map +0 -1
- package/dist/providers-v1Rn2rqG.js.map +0 -1
- package/dist/tools-CMVruxF0.js.map +0 -1
- package/dist/transcript-anchors-eyhlGeBI.d.ts.map +0 -1
- package/dist/turn-operations-Y7e15gJf.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-IcokUOyC.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/**\n * Shared types for the agent system.\n */\n\nimport type { ToolDef } from './tools/types'\nimport { Buffer } from 'node:buffer'\n\n// ---------------------------------------------------------------------------\n// Thinking / Reasoning\n// ---------------------------------------------------------------------------\n\n/**\n * Thinking / extended-reasoning configuration.\n *\n * - `'off'` — no thinking.\n * - `'minimal' | 'low' | 'medium' | 'high'` — explicit token budget. Maps to\n * provider-specific reasoning controls (Anthropic `thinking.type='enabled'`\n * with a budget; OpenAI `reasoning_effort`).\n * - `'adaptive'` — let the model decide per-turn whether and how much to think.\n * Anthropic-only (`thinking.type='adaptive'`). Other providers fall back to\n * no reasoning when this value is supplied.\n */\nexport type ThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'adaptive'\n\n// ---------------------------------------------------------------------------\n// MCP server configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Slim shape of an upstream MCP tool descriptor — what `client.listTools()`\n * returns per entry. Exposed publicly so hosts can persist the schemas\n * between runs and feed them back via {@link McpServerConfig.cachedTools}\n * to skip the `tools/list` round-trip on subsequent bootstraps.\n */\nexport interface McpToolSchema {\n name: string\n description?: string | null\n inputSchema?: unknown\n}\n\nexport interface McpServerConfig {\n /** Display name (used for tool namespacing) */\n name: string\n /** Transport type */\n transport: 'stdio' | 'sse' | 'streamable-http'\n /** For stdio: command to run */\n command?: string\n /** For stdio: command arguments */\n args?: string[]\n /**\n * For stdio: environment variables to pass to the server process.\n *\n * Merged on top of the MCP SDK's default inherited environment — a safety\n * whitelist (`PATH`, `HOME`, `LANG`, `SHELL`, `USER` on POSIX; `APPDATA`,\n * `PATH`, ... on Win32). Setting this to `{}` no longer strips `PATH` from\n * the child process. Set {@link McpServerConfig.strictEnv} to `true` to\n * pass `env` verbatim with no inherited defaults.\n */\n env?: Record<string, string>\n /**\n * When true, {@link McpServerConfig.env} is passed verbatim to the spawned\n * process — the MCP SDK's default inherited environment (`PATH`, `HOME`, ...)\n * is NOT merged in. Most consumers should leave this off; the default merge\n * prevents `spawn ENOENT` when a stdio server declares an `env` without\n * restating `PATH`.\n */\n strictEnv?: boolean\n /** For sse/streamable-http: server URL */\n url?: string\n /** Optional headers for HTTP transports */\n headers?: Record<string, string>\n /**\n * OAuth 2.1 authentication (sse / streamable-http only).\n *\n * - `'oauth'` — enables the SDK's OAuth flow with RFC 9728 protected-resource\n * metadata discovery, RFC 8414 / OIDC authorization-server metadata, RFC 7591\n * dynamic client registration, PKCE, and refresh-token rotation. Tokens persist\n * between runs via the host's credential store.\n * - `undefined` (default) — no OAuth. The host may still auto-promote a server\n * to OAuth on `UnauthorizedError` IF no static `Authorization` header is set\n * (the headers check stops us from second-guessing user-managed bearer tokens).\n *\n * Recognized aliases at parse time: Cursor's `authMethod: 'mcpOAuth'` maps to\n * `auth: 'oauth'` so `~/.cursor/mcp.json` pastes work unchanged.\n */\n auth?: 'oauth'\n /**\n * Timeout in milliseconds for MCP server bootstrap (connect + tool discovery).\n *\n * Zidane connects MCP servers lazily on the first `run()`. Without a\n * bootstrap timeout, a slow or hung server can delay the first provider call\n * for an arbitrarily long time even when that MCP server is never used.\n *\n * Default: `10000`.\n */\n bootstrapTimeout?: number\n /** Timeout in milliseconds for MCP tool calls (default: 30000) */\n toolTimeout?: number\n /**\n * Allow-list of tool names to expose. Names match the upstream tool name\n * (NOT the namespaced `mcp_{server}_{tool}` form). Tools not in the list are\n * dropped before registration — the model never sees them in its catalog and\n * the wire cost of advertising them is avoided.\n *\n * Mutually exclusive with {@link McpServerConfig.disabledTools} — passing both\n * throws at bootstrap time.\n *\n * Composes with {@link McpServerConfig.toolFilter}: allow-list applies first,\n * then the predicate. Composes with the `mcp:tools:filter` hook: config-side\n * filters apply first, then the hook can further narrow the list.\n */\n enabledTools?: string[]\n /**\n * Deny-list of tool names. Tools matching are dropped before registration.\n * Same matching semantics as {@link McpServerConfig.enabledTools}.\n */\n disabledTools?: string[]\n /**\n * Custom predicate run on each upstream tool. Return `true` to keep, `false`\n * to drop. Receives the raw `listTools()` payload — useful for filtering by\n * description, schema shape, or other metadata that an allow/deny list can't\n * express.\n *\n * Runs after the allow/deny filter but before the `mcp:tools:filter` hook.\n */\n toolFilter?: (tool: { name: string, description?: string | null, inputSchema?: unknown }) => boolean\n /**\n * Per-server override for {@link AgentBehavior.toolDisclosure}. When set,\n * this server's tools follow this disclosure mode regardless of the\n * agent-wide default. Useful when one big MCP server (200+ tools) should\n * stay lazy while smaller servers stay eager.\n *\n * Default: inherits from `behavior.toolDisclosure`.\n */\n disclosure?: 'eager' | 'lazy'\n /**\n * Pre-cached tool schemas to advertise without issuing `tools/list` at\n * bootstrap. The connection is still established (the SDK's `connect()`\n * is needed for `tools/call`) — only the discovery round-trip is\n * skipped. Schemas are trusted as-is; the host owns invalidation\n * (typical cache key: `(server identity, server version)`). If the\n * server later returns `MethodNotFound` for a cached tool, the host\n * should drop the entry from its cache so the next bootstrap re-lists.\n *\n * Compatible with every transport, every auth mode, and with\n * {@link McpServerConfig.lazyConnect}. Composes with the existing\n * `enabledTools` / `disabledTools` / `toolFilter` filters — those run\n * over the cached schemas exactly as they would over `listTools()`\n * output.\n */\n cachedTools?: McpToolSchema[]\n /**\n * Defer the `client.connect(transport)` call until the first\n * `tools/call` reaches this server. Bootstrap registers the server's\n * tools using {@link McpServerConfig.cachedTools} without touching\n * the network, taking MCP setup off the critical path of\n * `agent.run()`. The first invocation pays the connect cost\n * (~200-500ms typically); every subsequent call reuses the live\n * client.\n *\n * Requires {@link McpServerConfig.cachedTools} — without schemas in\n * hand there is nothing to advertise to the model, so deferring the\n * connection has no purpose. Bootstrap rejects the config otherwise.\n *\n * **Incompatible with `auth: 'oauth'`**: the OAuth handshake (token\n * refresh / RFC 9728 metadata discovery) can fail in ways that today\n * fire `mcp:auth:required` at bootstrap so the host can surface a\n * login affordance *before* the model commits to calling a tool.\n * Deferring that to first call means an auth failure surfaces mid-run\n * as a tool-result error, which the model can't recover from without\n * a fresh prompt. Bootstrap rejects the combination so the error is\n * loud and proximate to the misconfiguration. Use OAuth servers\n * without `lazyConnect` (with `cachedTools` alone, if you want to\n * skip the `tools/list` round-trip).\n *\n * On connect failure (network error, transport refused), the cached\n * promise is dropped so the next `tools/call` retries. The model\n * sees the failure as a normal tool error. Subsequent calls remain\n * eligible to succeed once the upstream is reachable again.\n */\n lazyConnect?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Tool execution\n// ---------------------------------------------------------------------------\n\nexport type ToolExecutionMode = 'sequential' | 'parallel'\n\nexport interface AgentBehavior {\n /** Tool execution mode (default: 'sequential') */\n toolExecution?: ToolExecutionMode\n /**\n * Max agent loop iterations.\n *\n * Default: unlimited (Infinity). The loop runs until the model signals\n * completion (no tool calls / `end_turn`), the abort signal fires, or this\n * cap is hit. Set a finite value as a safety net for runaway loops.\n */\n maxTurns?: number\n /** Max tokens per LLM response (default: 16384) */\n maxTokens?: number\n /** Thinking token budget — overrides the level-based default when set */\n thinkingBudget?: number\n /** JSON Schema for structured output enforcement */\n schema?: Record<string, unknown>\n /**\n * Enable provider prompt caching. When on (default), the provider marks the\n * system prompt, tools, and the last stable message with cache breakpoints so\n * the shared prefix is served from cache across turns.\n *\n * - Anthropic: `cache_control: { type: 'ephemeral' }` on the last `system`\n * content part, the last tool, and the last message content part.\n * - OpenAI-compatible / OpenRouter: same shape — honored by Anthropic-backed\n * OpenRouter routes and by Gemini; ignored (no-op) by providers that cache\n * automatically (OpenAI, DeepSeek, Grok, Groq, Moonshot).\n *\n * Usage is surfaced via `TurnUsage.cacheRead` / `TurnUsage.cacheCreation`.\n *\n * Default: `true`.\n */\n cache?: boolean\n /**\n * Soft per-turn cap on total tool-output bytes. When the sum of `outputBytes`\n * across a turn's tool results exceeds this value, the loop injects a\n * synthetic user message instructing the model to summarize before calling\n * more tools, and fires the `budget:exceeded` hook.\n *\n * Measured **post-`tool:transform`** so consumer truncation counts toward the\n * budget. Off by default (undefined / `0` disables the check). A reasonable\n * starting value for OSS-model integrations is `32768`.\n */\n toolOutputBudget?: number\n /**\n * Deduplicate identical re-reads of the same file in `read_file`. When the\n * model re-reads a file with the same slice and the bytes haven't changed\n * since the last read in this session, the tool returns a short stub\n * instead of re-emitting the full content. Pairs with the read-before-edit\n * guard in `edit` / `multi_edit`.\n *\n * Requires a session (set via `createSession()`); without one, the flag is\n * a no-op since per-session state has nowhere to live.\n *\n * Default: `true`.\n */\n dedupReads?: boolean\n /**\n * Taper the thinking budget over the course of a run. Late turns are\n * usually checkpoint / cleanup work where reasoning rarely pays for\n * itself; early turns benefit most. Two forms:\n *\n * - **Struct** — geometric decay starting after `afterTurn`, multiplying by\n * `factor` each subsequent turn, clamped to `floor`. Example\n * `{ afterTurn: 5, factor: 0.5, floor: 1024 }` with a base budget of 8192:\n * turns 1-5 = 8192, turn 6 = 4096, turn 7 = 2048, turn 8+ = 1024.\n * - **Function** — `(runTurn, baseBudget) => number`. Arbitrary curves;\n * `runTurn` is 1-indexed, run-relative (resumed sessions reset).\n *\n * No-op when `thinkingBudget` is unset. Honored by every provider that\n * respects `thinkingBudget` (anthropic explicit-budget `enabled` path,\n * adaptive `maxTokensCap`, openai-compat `max_tokens` padding).\n *\n * Default: `undefined` (no decay).\n */\n thinkingDecay?: { afterTurn: number, factor: number, floor: number } | ((runTurn: number, baseBudget: number) => number)\n /**\n * Per-tool soft call budget for this run. Keyed by **canonical** tool name.\n * On the first call after the run-cumulative dispatched count for that tool\n * reaches `max`, the framework fires `onExceed`:\n *\n * - `'steer'` (default) — let the call execute, but emit a synthetic user\n * message after the turn that nudges the model away from re-calling the\n * tool. Reuses the existing post-turn steer pathway used by\n * `toolOutputBudget`. Fires `tool-budget:exceeded` with `mode: 'steer'`.\n * - `'block'` — refuse the call via `tool:gate` `block`. The model sees a\n * `Blocked: <reason>` tool result. Fires `tool-budget:exceeded` with\n * `mode: 'block'`.\n * - **Function** — `(ctx) => { mode, message }`. The consumer supplies the\n * steering / refusal text and chooses the mode dynamically.\n *\n * Counts include both real dispatches and dedup substitutes (Z19 hits).\n * Excludes calls already blocked by an earlier gate (skill allow-list,\n * consumer hook). Tool dispatched by spawned subagents has its own per-run\n * counter — child counts never charge the parent.\n *\n * For MCP tools, key by the namespaced wire name (`mcp_<server>_<tool>`).\n *\n * Atomic in parallel mode: the middleware tracks its own per-tool\n * approval counter, incremented synchronously at gate-time. A\n * 4-call parallel batch against `max: 2` will let the first 2 through\n * and refuse the rest, even though the loop's `runToolCounts` only\n * propagates between calls (not within a single batch's gate fan-out).\n *\n * Default: `undefined` (no budget enforcement).\n */\n toolBudgets?: Record<string, {\n max: number\n onExceed?: 'steer' | 'block' | ((ctx: {\n tool: string\n count: number\n max: number\n }) => { mode: 'steer' | 'block', message: string })\n }>\n /**\n * Generic per-tool argument deduplication. Keyed by the tool's **canonical**\n * name (alias-stable). Each entry is a hasher: `(input) => string | undefined`.\n *\n * **Hasher contract** — three return values, three meanings:\n *\n * | Return | Meaning |\n * |-------------------------|------------------------------------------------------------------------|\n * | a non-empty string | Cache key for this call. Equal keys (most-recent-only, this session) |\n * | | replay the prior recorded result without re-dispatching the tool. |\n * | `undefined` | **Skip dedup for this call.** The tool runs normally; nothing recorded.|\n * | `''` / non-string | Treated identically to `undefined` (defensive: no dedup, no error). |\n *\n * The `undefined` opt-out is the way to say *\"this specific call is not\n * cacheable\"* (timestamps in input, randomness baked in, debug flags). It\n * is **not** the same as `JSON.stringify(input)` — that would dedup against\n * the verbatim input. Pick one explicitly:\n *\n * ```ts\n * // Always cache by full input — every identical re-call dedups.\n * dedupTools: { todowrite: input => JSON.stringify(input) }\n *\n * // Cache by a normalized subset; non-cacheable shapes opt out.\n * dedupTools: {\n * execute_sql: (input) => {\n * const q = typeof input.query === 'string' ? input.query.trim().toLowerCase() : undefined\n * if (!q || q.includes('now()') || q.includes('random()')) return undefined\n * return q\n * },\n * }\n * ```\n *\n * On a hit, the previously-recorded result is replayed as the tool_result\n * without dispatching the tool. The substitution flows through `tool:gate`\n * `result` (Z20), so `tool:after` and `tool:transform` still fire.\n *\n * Requires a session (`createSession()`); without one, the map is a silent\n * no-op since per-session state has nowhere to live. Tools with side\n * effects or non-deterministic outputs (network, time, randomness) MUST\n * NOT be listed — there is no safety net beyond the consumer's hasher.\n *\n * For MCP tools, key by the namespaced wire name (`mcp_<server>_<tool>`).\n * Parallel mode (`toolExecution: 'parallel'`, the default) sees calls in\n * the SAME assistant turn race against each other — none can dedup against\n * a sibling that started in the same batch. Sequential mode honors order\n * within a turn.\n *\n * **Cache policy**: only the most recent `(hash, result)` per tool is\n * retained. Interleaved patterns (input A, input B, input A) miss on the\n * second A because B overwrote it. Sufficient for the common spam-the-\n * same-call loop; consumers needing a richer cache should hook\n * `tool:gate` directly.\n *\n * Default: `undefined` (no per-tool dedup).\n */\n dedupTools?: Record<string, (input: Record<string, unknown>) => string | undefined>\n /**\n * Require `read_file` before `edit` / `multi_edit` on the same path, and\n * reject edits when the file has changed on disk since the last read in\n * this session. Eliminates the silent-corruption failure mode where a\n * model \"remembers\" stale content and applies a substring edit against\n * bytes that have moved.\n *\n * Requires a session. Off by default; turn it on for stricter eval-grade\n * runs where silent edit corruption would invalidate the result.\n *\n * Default: `false`.\n */\n requireReadBeforeEdit?: boolean\n /**\n * Client-side context compaction strategy. Use this for non-Anthropic\n * providers (OSS via cerebras / openai-compat / openrouter) that don't\n * have a server-side equivalent. Anthropic users should prefer the\n * server-side `context-management-2025-06-27` beta — see\n * `AnthropicParams.contextManagement`.\n *\n * - `'off'` (default) — no client-side compaction.\n * - `'tail'` — when total tool-output bytes in the persisted history\n * exceed `compactThreshold`, replace older `tool_result` outputs with a\n * short stub, keeping the newest `compactKeepTurns` turns intact. The\n * compaction is applied to the wire-level message list only; the\n * underlying session turns are not modified.\n *\n * Default: `'off'`.\n */\n compactStrategy?: 'off' | 'tail'\n /**\n * Soft byte threshold that triggers tail compaction when\n * `compactStrategy === 'tail'`. Counts the post-`context:transform` bytes\n * of `tool_result` outputs across all messages. Default: `131_072` (128\n * KiB). Ignored when compaction is off.\n */\n compactThreshold?: number\n /**\n * Number of trailing turns to leave untouched during tail compaction. The\n * most-recent `compactKeepTurns` user/assistant messages are not eligible\n * for elision so the model keeps the freshest tool context. Default: `4`.\n */\n compactKeepTurns?: number\n /**\n * Prefix every line of `read_file` output with its 1-indexed line number\n * followed by a tab (`<N>\\t<content>`) — the compact `cat -n`-style\n * format Claude Code emits. The `edit` tool strips the prefix from\n * `old_string` / `new_string` so the model can paste back a numbered\n * chunk verbatim without breaking the match.\n *\n * Set `false` to opt out — useful for callers piping `read_file` into\n * downstream parsers that don't recognize the prefix. Per-call\n * `read_file({ lineNumbers: false })` overrides this default.\n *\n * Default: `true`.\n */\n readLineNumbers?: boolean\n /**\n * Replace older `read_file` `tool_result` blocks with a short stub when\n * a successful `edit` / `multi_edit` / `write_file` later in the same\n * run modified the same path. The replacement is applied to the\n * wire-level message list only — persisted session turns keep the\n * original content.\n *\n * Eliminates the common waste pattern where the model carries the\n * pre-edit file body forward across many turns \"in case it needs it\".\n * Pairs cleanly with `compactStrategy: 'tail'`: stale reads shrink\n * first, then the byte-threshold compaction fires if anything's left.\n *\n * Detection is conservative — only triggers when the corresponding\n * tool_result confirms success (`Edited …`, `Created …`, `Updated …`).\n * Failed edits and `No change needed` write_file calls do NOT\n * invalidate prior reads.\n *\n * Default: `false`.\n */\n elideStaleReads?: boolean\n /**\n * Tool disclosure strategy. Controls whether the model sees every tool's\n * full `inputSchema` in its tool list every turn (\"eager\") or whether MCP\n * tools are advertised as a name+description catalog in the system prompt\n * and only get full schemas after being surfaced via the `tool_search`\n * native tool (\"lazy\" / progressive disclosure).\n *\n * Native tools (those passed to `createAgent({ tools })`) and skill tools\n * are always eager — they are core to the agent and cheap. Only MCP tools\n * are eligible for lazy disclosure.\n *\n * When `'lazy'`, the agent:\n * - Appends a `<searchable_tools>` section to the system prompt listing\n * every MCP tool by `name` + `description` only (no `inputSchema`).\n * - Auto-injects a `tool_search` native tool (opt out via\n * {@link AgentBehavior.toolSearch}) the model uses to load schemas on\n * demand. Surfaced tools persist for the rest of the run.\n * - Rebuilds the wire-level tool list each turn, appending newly-unlocked\n * tools at the end so the prefix-cache breakpoint advances cleanly.\n *\n * Trade-off: every `tool_search` invocation expands the tool list and\n * invalidates the tool-list cache breakpoint for one turn. With many\n * MCP servers, the savings on cold turns (fewer schemas in context) are\n * substantial; with one tiny MCP server, the overhead may not pay back.\n *\n * Default: `'eager'`.\n */\n toolDisclosure?: 'eager' | 'lazy'\n /**\n * Fine-grained config for the `tool_search` tool auto-injected when\n * {@link AgentBehavior.toolDisclosure} is `'lazy'`. No-op in eager mode.\n *\n * - `tool: false` — opt out of the auto-injection entirely. Use when the\n * host wants to ship a custom discovery tool. Note that the catalog\n * text drops the call-to-action prose in this case so the model isn't\n * pointed at a non-existent tool.\n * - `limit` — default cap on results returned per `tool_search` call when\n * the model omits the parameter. Default: `20`.\n *\n * Note on host-defined `tool_search`: a tool the host registers under the\n * name `tool_search` (or under any alias whose canonical is `tool_search`)\n * will shadow the auto-injected one — the catalog text will point at the\n * host's wire name, but driving the unlock flow requires either using\n * `createToolSearchTool({ catalog, unlocked })` from `tools/tool-search`\n * (which internally mutates the unlock set) or fully opting out via\n * `toolSearch.tool: false` and treating discovery as a host-side concern.\n * A bare host tool that doesn't touch the unlock set will not advance the\n * lazy disclosure state and the hard gate will keep refusing lazy calls.\n *\n * Default: `undefined` (auto-inject with the default limit).\n */\n toolSearch?: {\n tool?: false\n limit?: number\n }\n /**\n * Persist large `tool_result` outputs to disk and replace the in-message\n * content with a `<persisted-output>` stub (preview + filesystem path).\n * When the post-`tool:transform` byte size of a tool's result exceeds\n * this threshold, the framework writes the full payload to\n * `<persistDir>/<callId>.txt` and substitutes a fixed-format stub so the\n * model sees a 2 KiB preview plus the path it can `read_file`.\n *\n * The substitution happens at emit time (just after `tool:transform` runs)\n * and the stub flows into `session.turns` directly — so every subsequent\n * turn re-emits the same bytes, keeping the prompt-cache prefix stable.\n *\n * Set `0` / `undefined` to disable. Built-in chat profiles default to\n * `8192`. Tools listed in {@link AgentBehavior.persistExcludeTools} bypass\n * regardless of size — typically because their output is intentionally\n * short or persisting would be circular (e.g. `read_file`).\n *\n * Requires {@link AgentBehavior.persistDir} to be set; without a target\n * directory the framework silently skips persistence (no throw, no\n * substitution) since there's nowhere to write the blob.\n *\n * Default: `undefined` (off).\n */\n persistThreshold?: number\n /**\n * Canonical tool names to exclude from disk persistence regardless of\n * output size. The framework bypasses persistence for any tool whose\n * canonical name appears in this list — useful for tools whose results\n * are intentionally part of the prompt (`skills_use`), short envelopes\n * (`tool_search`, `present_plan`, `ask_user`), or where persistence\n * would be circular (`read_file`, whose pagination already serves the\n * same use case).\n *\n * Default: `undefined` (no exclusions). The chat-layer built-in profiles\n * set their own list — see `src/chat/agents.ts`.\n */\n persistExcludeTools?: readonly string[]\n /**\n * Directory under which persisted tool-result blobs land. Each call's\n * payload is written to `<persistDir>/<callId>.txt` (one file per\n * `tool_use` id, atomic via write-then-rename).\n *\n * The chat layer resolves this to `<userDir>/tool-results/<sessionId>/`\n * at session activation; SDK consumers pass an absolute path. Required\n * when {@link AgentBehavior.persistThreshold} is non-zero — when unset\n * the framework treats persistence as disabled.\n *\n * Default: `undefined`.\n */\n persistDir?: string\n}\n\n// ---------------------------------------------------------------------------\n// Prompt parts (multimodal input)\n// ---------------------------------------------------------------------------\n\n/**\n * One block of a multimodal user prompt.\n *\n * `agent.run({ prompt })` accepts either a plain string (treated as a single\n * text part) or an array of these parts for multimodal inputs.\n *\n * `document` parts are routed per provider: PDF-style mime types are sent as\n * native document blocks when the provider supports them; text documents are\n * inlined as text with an attachment header. Providers that cannot handle an\n * image or document throw early.\n */\nexport type PromptPart\n = | PromptTextPart\n | PromptImagePart\n | PromptDocumentPart\n\nexport interface PromptTextPart {\n type: 'text'\n text: string\n}\n\nexport interface PromptImagePart {\n type: 'image'\n /** IANA media type (e.g. `image/png`, `image/jpeg`) */\n mediaType: string\n /** Base64-encoded payload */\n data: string\n /** Optional display name */\n name?: string\n}\n\nexport interface PromptDocumentPart {\n type: 'document'\n /** IANA media type (e.g. `application/pdf`, `text/plain`) */\n mediaType: string\n /** Either a base64-encoded payload (`encoding: 'base64'`) or raw text (`encoding: 'text'`) */\n data: string\n encoding: 'base64' | 'text'\n /** Optional display name used in attachment headers */\n name?: string\n}\n\n// ---------------------------------------------------------------------------\n// Canonical message format (used throughout the agent system)\n// ---------------------------------------------------------------------------\n\n/**\n * A single block of structured tool-result content.\n *\n * MCP servers can return a mix of text, image, resource, and audio blocks. Tools\n * return `string` for the common text-only case or `ToolResultContent[]` when they\n * need to preserve non-text content (e.g. screenshots from a browser MCP).\n *\n * Providers that support native multi-part tool results (Anthropic, OpenAI Codex via\n * pi-ai) route image blocks into their wire format verbatim; OpenAI-compat providers\n * route them via a companion-user-message fallback when the underlying model/endpoint\n * does not accept images inside tool-role messages.\n */\nexport type ToolResultContent\n = | ToolResultTextContent\n | ToolResultImageContent\n\nexport interface ToolResultTextContent {\n type: 'text'\n text: string\n}\n\nexport interface ToolResultImageContent {\n type: 'image'\n /** IANA media type (e.g. `image/png`, `image/jpeg`) */\n mediaType: string\n /** Base64-encoded payload */\n data: string\n}\n\n/**\n * Lossy flattener — converts `ToolResultContent[]` (or a plain string) to a single\n * string. Image blocks are replaced with `[image: <media> — <n> b64 bytes]` markers.\n *\n * Use at UI boundaries where a string is required; providers that understand\n * structured content should route the array through without flattening.\n */\nexport function toolResultToText(content: string | ToolResultContent[]): string {\n if (typeof content === 'string')\n return content\n return content\n .map((block) => {\n if (block.type === 'text')\n return block.text\n return `[image: ${block.mediaType} — ${block.data.length} b64 bytes]`\n })\n .join('\\n')\n}\n\n/**\n * Approximate **wire payload size** of a tool output, in bytes.\n *\n * - Plain text: UTF-8 byte length.\n * - Structured content: text blocks contribute their UTF-8 byte length; image\n * blocks contribute their **base64 character length** — a proxy for the\n * serialized request-body footprint, NOT for tokens. Vision encoders\n * tokenize decoded pixels (geometry-dependent; e.g. Anthropic ≈ `w·h/750`,\n * OpenAI ≈ 85 + 170/tile), which has no meaningful relationship to base64\n * length.\n *\n * Used by the agent loop to populate `outputBytes` on `tool:after`,\n * `tool:transform`, `mcp:tool:after`, and `mcp:tool:transform` hooks so\n * consumers can size-budget tool output without re-counting bytes themselves.\n * Suitable for byte-budget heuristics (`toolOutputBudget`, tail compaction);\n * NOT a substitute for provider-side context-window accounting — defer to\n * server-side context management (e.g. Anthropic's `context-management-*`\n * beta) when token accuracy matters.\n */\nexport function toolOutputByteLength(content: string | ToolResultContent[]): number {\n if (typeof content === 'string')\n return Buffer.byteLength(content)\n let total = 0\n for (const block of content) {\n if (block.type === 'text')\n total += Buffer.byteLength(block.text)\n else\n total += block.data.length\n }\n return total\n}\n\nexport type SessionContentBlock\n = | { type: 'text', text: string }\n | { type: 'image', mediaType: string, data: string }\n | { type: 'tool_call', id: string, name: string, input: Record<string, unknown> }\n | {\n type: 'tool_result'\n callId: string\n /**\n * Tool output — either a plain string (text-only, the common case) or a structured\n * array of content blocks (text + image for multimodal tools such as screenshots).\n */\n output: string | ToolResultContent[]\n isError?: boolean\n }\n | {\n type: 'thinking'\n text: string\n signature?: string\n /**\n * Provider that minted `signature`. Signatures are provider-bound (Anthropic\n * HMAC vs. OpenAI `encrypted_content`) and are dropped on cross-provider\n * hops to avoid 400s. Unset means legacy/unknown — forwarded as-is.\n */\n signatureProducer?: 'anthropic' | 'openai'\n }\n | { type: 'redacted_thinking', data: string }\n | {\n /**\n * Opaque round-trip envelope for reasoning state minted by an OpenAI-compat\n * gateway (currently OpenRouter). The gateway expects its own\n * `reasoning_details` array echoed back verbatim on the next turn so the\n * upstream model can resume an extended-reasoning chain across tool calls.\n *\n * Stored opaquely because the items are provider-bound (Anthropic HMAC\n * signatures, OpenAI `encrypted_content`, model-specific summary formats\n * — all flowing through the gateway's normalized envelope).\n */\n type: 'provider_reasoning'\n producer: 'openrouter'\n details: unknown[]\n /**\n * Model id that produced the details. Reasoning is bound to a specific\n * upstream route — a model switch on the next turn invalidates the\n * embedded signatures, so the sender drops the block on mismatch.\n */\n model?: string\n }\n | {\n /**\n * Compaction marker. Inserted by `compactConversation()` to replace a\n * prefix of turns with an LLM-generated summary.\n *\n * The marker lives in `session.turns` and renders in the transcript —\n * the user can still scroll back to see the original turns. From the\n * agent loop's wire-level perspective, every turn whose id appears in\n * `replacesTurnIds` is dropped, and this block's `summary` text is\n * sent to the model as a single user message in their place.\n *\n * The marker turn carries `role: 'user'` so it sits naturally at a\n * conversational boundary. Only the latest `compact-summary` block in\n * the session is honored — earlier markers are subsumed by later\n * ones (their `replacesTurnIds` are a strict prefix).\n */\n type: 'compact-summary'\n /** Turn ids the summary replaces, in chronological order. */\n replacesTurnIds: readonly string[]\n /** The summary text sent to the model in place of the elided turns. */\n summary: string\n /** Model id used to produce the summary. */\n model: string\n /** Token usage from the summary call. */\n usage: TurnUsage\n /** Unix-ms when compaction completed. */\n compactedAt: number\n }\n\nexport interface SessionMessage {\n role: 'user' | 'assistant'\n content: SessionContentBlock[]\n}\n\nexport interface SessionTurn {\n /** UUID — generated by the store if it provides generateTurnId, else crypto.randomUUID() */\n id: string\n /** Run that produced this turn (e.g. 'run_1') */\n runId?: string\n role: 'user' | 'assistant' | 'system'\n content: SessionContentBlock[]\n /** Token usage — only present on assistant turns */\n usage?: TurnUsage\n /** Unix timestamp (Date.now()) when the turn was created */\n createdAt: number\n}\n\n// ---------------------------------------------------------------------------\n// Agent run options\n// ---------------------------------------------------------------------------\n\n/**\n * Per-run hook registrations. Each entry can be a single handler or an array of handlers.\n * Keys are `AgentHooks` event names (loose-typed here to avoid a circular import; agent.ts\n * narrows it to the strongly-typed map).\n */\nexport type RunHookMap = Record<string, ((ctx: any) => unknown) | ((ctx: any) => unknown)[]>\n\nexport interface AgentRunOptions {\n model?: string\n /**\n * User prompt. Optional when resuming a session with existing turns.\n *\n * Accepts either a plain string (single text part) or an array of `PromptPart`s for\n * multimodal inputs (text, images, documents). See {@link PromptPart}.\n */\n prompt?: string | PromptPart[]\n system?: string\n thinking?: ThinkingLevel\n /** Abort signal — when triggered, the agent stops after the current turn */\n signal?: AbortSignal\n /** Behavior overrides for this run (overrides agent defaults) */\n behavior?: AgentBehavior\n /** Tool overrides for this run. Pass {} for no tools. Omit to use agent tools. */\n tools?: Record<string, ToolDef>\n /**\n * Per-run hook registrations. Each hook is attached before the run starts and\n * detached in a finally block so handlers never leak across runs.\n *\n * Accepts either a single handler or an array (all handlers register).\n */\n hooks?: RunHookMap\n /**\n * Parent run id. Populated automatically by the `spawn` tool when the child\n * shares the parent's session; recorded on the resulting `SessionRun` so the\n * parent↔child run tree can be reconstructed from a persisted session.\n */\n parentRunId?: string\n /**\n * Zero-based subagent depth. 0 = top-level `agent.run()`, 1 = first-level\n * child spawned by a parent agent, and so on. Used by the spawn tool to\n * enforce `maxDepth` and to stamp `child:*` forwarded hook payloads.\n */\n depth?: number\n}\n\n// ---------------------------------------------------------------------------\n// Agent stats\n// ---------------------------------------------------------------------------\n\n/**\n * Reason the provider gave for stopping the turn.\n *\n * - `'stop'` — natural turn end (`end_turn` / `stop_sequence`).\n * - `'tool-calls'` — model emitted tool_use blocks.\n * - `'length'` — `max_tokens` reached, or (Anthropic 4.6+) the response bumped\n * against the model's context window mid-stream\n * (`model_context_window_exceeded`). The partial response is preserved; the\n * loop emits this reason so consumers can prune/retry.\n * - `'content-filter'` — model refused.\n * - `'pause'` — Anthropic `pause_turn`: a server-side mid-turn pause for very\n * long thinking. The loop continues with a synthetic \"Please continue.\"\n * user message rather than terminating; consumers see the pause via this\n * finish reason on the prior assistant turn.\n * - `'error'` — provider classified the turn as failed.\n * - `'other'` — unknown / unmapped.\n */\nexport type TurnFinishReason = 'stop' | 'tool-calls' | 'length' | 'content-filter' | 'pause' | 'error' | 'other'\n\nexport interface TurnUsage {\n input: number\n output: number\n /** Tokens written to cache (Anthropic) */\n cacheCreation?: number\n /** Tokens read from cache (Anthropic) */\n cacheRead?: number\n /** Thinking/reasoning tokens used */\n thinking?: number\n /**\n * Cost in USD for this turn. Provider-reported when available\n * (OpenRouter, OpenAI via pi-ai); otherwise estimated from `modelId` ×\n * pi-ai's bundled price registry by `fillEstimatedCost` in\n * `src/providers/cost.ts`. Absent only when neither path could resolve\n * a price (unknown / unbundled model).\n */\n cost?: number\n /**\n * Why the model stopped this turn. Providers normalize native stop reasons to this union.\n * Absent when the provider did not surface a reason (e.g. mock turns).\n */\n finishReason?: TurnFinishReason\n /**\n * The model ID the provider ultimately used. May differ from the requested model when the\n * provider remaps aliases. Absent for providers that do not echo a model ID.\n */\n modelId?: string\n}\n\nexport interface AgentStats {\n /**\n * Cumulative input tokens across the parent agent loop **and** every\n * recursively-spawned sub-agent. Use this for billing / token-ledger\n * consumption.\n */\n totalIn: number\n /** Cumulative output tokens. Same semantics as {@link AgentStats.totalIn}. */\n totalOut: number\n /**\n * Cumulative cache-read tokens across the parent agent loop and every\n * recursively-spawned sub-agent. Surfaced at the top level (rather than\n * only per-`TurnUsage`) because Anthropic prices cache reads at a separate\n * line-item rate from regular input — billing-correct cost computation\n * needs this number directly. Always `0` for providers that don't report\n * cache usage.\n */\n totalCacheRead: number\n /**\n * Cumulative cache-creation tokens across the parent agent loop and every\n * recursively-spawned sub-agent. Same rationale as\n * {@link AgentStats.totalCacheRead} — separate Anthropic billing rate.\n * Always `0` for providers that don't report cache usage.\n */\n totalCacheCreation: number\n /**\n * Number of parent agent-loop turns. Children's turn counts live under\n * `children[].stats.turns` and are NOT folded in here — a single \"turns\"\n * number for the whole tree would conflate two different measures\n * (parent-loop iterations vs. tree-wide tool-call rounds).\n *\n * Tree-wide turn count: `flattenTurns(stats).length`.\n */\n turns: number\n /**\n * Wall-clock duration of the top-level `agent.run()` call, in milliseconds.\n * Children run during parent tool calls so this naturally subsumes child\n * wall time — sequential children inflate it, parallel children compress\n * into the parent's window.\n */\n elapsed: number\n /**\n * Per-turn usage breakdown for the **parent loop only**. Children's per-turn\n * usages live under `children[].stats.turnUsage`. Use {@link flattenTurns}\n * to walk the full tree.\n */\n turnUsage?: TurnUsage[]\n /**\n * Cumulative cost in USD — parent loop plus every recursively-spawned\n * sub-agent. Sums per-turn `TurnUsage.cost` reported by the provider.\n * Absent when neither parent nor any descendant reported a non-zero cost.\n */\n cost?: number\n /** Stats from child agents spawned during this run, in completion order. Recursive. */\n children?: ChildRunStats[]\n /** Structured output from schema enforcement (only present when behavior.schema is set) */\n output?: Record<string, unknown>\n /**\n * Milliseconds from the start of `agent.run()` to the first observable signal from the\n * provider (first `stream:text`, `stream:thinking`, or `tool:before` event).\n *\n * Absent when the run produced no observable signals (e.g. aborted before any stream event).\n */\n timeTillFirstTokenMs?: number\n}\n\nexport interface ChildRunStats {\n id: string\n task: string\n /**\n * The child agent's full {@link AgentStats}. Cumulative for that child's\n * own subtree (child loop + its grandchildren). Do **not** sum\n * `ctx.stats.totalIn` across `spawn:complete` events to derive top-level\n * totals — `agent.run()`'s return value is the canonical cumulative root.\n */\n stats: AgentStats\n /**\n * Subagent depth when this child ran. 1 = direct child of the top-level\n * agent, 2 = grandchild, etc. Useful for telemetry that wants to group\n * runs by depth.\n */\n depth?: number\n /**\n * Terminal state of the child run. `'completed'` is the default. Exposed so\n * a parent reading `stats.children` can distinguish aborted/timed-out\n * children without re-parsing the returned string.\n */\n status?: 'completed' | 'aborted' | 'timeout' | 'error'\n /**\n * Final structured output when the child was run with `behavior.schema`.\n * Mirrors `AgentStats.output` but is surfaced here so the parent can read\n * it without peeking at the nested `stats` bag.\n */\n output?: Record<string, unknown>\n}\n\n// ---------------------------------------------------------------------------\n// Hook context types\n// ---------------------------------------------------------------------------\n\n/**\n * Base context for tool execution hooks.\n *\n * `name` is the canonical tool identity — the spec name registered on the agent (or the\n * `mcp_{server}_{tool}` name for MCP tools). Hooks should policy-match against `name`.\n *\n * `displayName` is the outward-facing name — the alias surfaced to the LLM when\n * `AgentOptions.toolAliases` maps the canonical name; otherwise equal to `name`.\n * UI/telemetry adapters should emit `displayName`.\n *\n * Canonical vs. alias matters on session resume: `session.turns` persists canonical\n * names only, so renaming an alias cannot desync history.\n */\nexport interface ToolHookContext {\n turnId: string\n callId: string\n /** Canonical tool name (spec name). Stable across alias-map changes. */\n name: string\n /** Aliased (wire) name — equal to `name` when no alias is defined. */\n displayName: string\n input: Record<string, unknown>\n}\n\n/**\n * Base context for MCP tool hooks.\n *\n * `tool` is the native tool name on the MCP server. `server` is the configured server\n * name. The canonical zidane-namespaced identity is `mcp_{server}_{tool}`.\n *\n * `displayName` equals the canonical namespaced name unless the agent has aliased\n * this MCP tool via `AgentOptions.toolAliases`; in which case `displayName` is the\n * alias that the LLM sees.\n */\nexport interface McpToolHookContext {\n turnId: string\n callId: string\n server: string\n tool: string\n /** Aliased wire name for this MCP tool, or the canonical `mcp_{server}_{tool}` name. */\n displayName: string\n input: Record<string, unknown>\n}\n\n/** Base context for session hooks */\nexport interface SessionHookContext {\n sessionId: string\n}\n\n/** Base context for spawn hooks */\nexport interface SpawnHookContext {\n id: string\n task: string\n /**\n * Subagent depth for the spawn. 1 = direct child of the top-level agent.\n * Present on spawn:before/complete/error. Absent for grandchild spawns that\n * bubble through `child:*` events (which carry their own `depth`).\n */\n depth?: number\n}\n\n/** Context for stream hooks */\nexport interface StreamHookContext {\n turnId: string\n}\n\n/** Context for OAuth refresh hooks */\nexport interface OAuthRefreshHookContext {\n provider: string\n providerId: string\n source: 'params' | 'file'\n previousCredentials: Record<string, unknown> & { access: string, refresh: string, expires: number }\n credentials: Record<string, unknown> & { access: string, refresh: string, expires: number }\n}\n\nexport type SessionEndStatus = 'completed' | 'aborted' | 'error'\n"],"mappings":";;;;;;;;;AAqnBA,SAAgB,iBAAiB,SAA+C;CAC9E,IAAI,OAAO,YAAY,UACrB,OAAO;CACT,OAAO,QACJ,KAAK,UAAU;EACd,IAAI,MAAM,SAAS,QACjB,OAAO,MAAM;EACf,OAAO,WAAW,MAAM,UAAU,KAAK,MAAM,KAAK,OAAO;GACzD,CACD,KAAK,KAAK;;;;;;;;;;;;;;;;;;;;;AAsBf,SAAgB,qBAAqB,SAA+C;CAClF,IAAI,OAAO,YAAY,UACrB,OAAO,OAAO,WAAW,QAAQ;CACnC,IAAI,QAAQ;CACZ,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,SAAS,QACjB,SAAS,OAAO,WAAW,MAAM,KAAK;MAEtC,SAAS,MAAM,KAAK;CAExB,OAAO"}
|
|
1
|
+
{"version":3,"file":"types-IcokUOyC.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/**\n * Shared types for the agent system.\n */\n\nimport type { ToolDef } from './tools/types'\nimport { Buffer } from 'node:buffer'\n\n// ---------------------------------------------------------------------------\n// Thinking / Reasoning\n// ---------------------------------------------------------------------------\n\n/**\n * Thinking / extended-reasoning configuration.\n *\n * - `'off'` — no thinking.\n * - `'minimal' | 'low' | 'medium' | 'high'` — explicit token budget. Maps to\n * provider-specific reasoning controls (Anthropic `thinking.type='enabled'`\n * with a budget; OpenAI `reasoning_effort`).\n * - `'adaptive'` — let the model decide per-turn whether and how much to think.\n * Anthropic-only (`thinking.type='adaptive'`). Other providers fall back to\n * no reasoning when this value is supplied.\n */\nexport type ThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'adaptive'\n\n// ---------------------------------------------------------------------------\n// MCP server configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Slim shape of an upstream MCP tool descriptor — what `client.listTools()`\n * returns per entry. Exposed publicly so hosts can persist the schemas\n * between runs and feed them back via {@link McpServerConfig.cachedTools}\n * to skip the `tools/list` round-trip on subsequent bootstraps.\n */\nexport interface McpToolSchema {\n name: string\n description?: string | null\n inputSchema?: unknown\n}\n\nexport interface McpServerConfig {\n /** Display name (used for tool namespacing) */\n name: string\n /** Transport type */\n transport: 'stdio' | 'sse' | 'streamable-http'\n /** For stdio: command to run */\n command?: string\n /** For stdio: command arguments */\n args?: string[]\n /**\n * For stdio: environment variables to pass to the server process.\n *\n * Merged on top of the MCP SDK's default inherited environment — a safety\n * whitelist (`PATH`, `HOME`, `LANG`, `SHELL`, `USER` on POSIX; `APPDATA`,\n * `PATH`, ... on Win32). Setting this to `{}` no longer strips `PATH` from\n * the child process. Set {@link McpServerConfig.strictEnv} to `true` to\n * pass `env` verbatim with no inherited defaults.\n */\n env?: Record<string, string>\n /**\n * When true, {@link McpServerConfig.env} is passed verbatim to the spawned\n * process — the MCP SDK's default inherited environment (`PATH`, `HOME`, ...)\n * is NOT merged in. Most consumers should leave this off; the default merge\n * prevents `spawn ENOENT` when a stdio server declares an `env` without\n * restating `PATH`.\n */\n strictEnv?: boolean\n /** For sse/streamable-http: server URL */\n url?: string\n /** Optional headers for HTTP transports */\n headers?: Record<string, string>\n /**\n * OAuth 2.1 authentication (sse / streamable-http only).\n *\n * - `'oauth'` — enables the SDK's OAuth flow with RFC 9728 protected-resource\n * metadata discovery, RFC 8414 / OIDC authorization-server metadata, RFC 7591\n * dynamic client registration, PKCE, and refresh-token rotation. Tokens persist\n * between runs via the host's credential store.\n * - `undefined` (default) — no OAuth. The host may still auto-promote a server\n * to OAuth on `UnauthorizedError` IF no static `Authorization` header is set\n * (the headers check stops us from second-guessing user-managed bearer tokens).\n *\n * Recognized aliases at parse time: Cursor's `authMethod: 'mcpOAuth'` maps to\n * `auth: 'oauth'` so `~/.cursor/mcp.json` pastes work unchanged.\n */\n auth?: 'oauth'\n /**\n * Timeout in milliseconds for MCP server bootstrap (connect + tool discovery).\n *\n * Zidane connects MCP servers lazily on the first `run()`. Without a\n * bootstrap timeout, a slow or hung server can delay the first provider call\n * for an arbitrarily long time even when that MCP server is never used.\n *\n * Default: `10000`.\n */\n bootstrapTimeout?: number\n /** Timeout in milliseconds for MCP tool calls (default: 30000) */\n toolTimeout?: number\n /**\n * Allow-list of tool names to expose. Names match the upstream tool name\n * (NOT the namespaced `mcp_{server}_{tool}` form). Tools not in the list are\n * dropped before registration — the model never sees them in its catalog and\n * the wire cost of advertising them is avoided.\n *\n * Mutually exclusive with {@link McpServerConfig.disabledTools} — passing both\n * throws at bootstrap time.\n *\n * Composes with {@link McpServerConfig.toolFilter}: allow-list applies first,\n * then the predicate. Composes with the `mcp:tools:filter` hook: config-side\n * filters apply first, then the hook can further narrow the list.\n */\n enabledTools?: string[]\n /**\n * Deny-list of tool names. Tools matching are dropped before registration.\n * Same matching semantics as {@link McpServerConfig.enabledTools}.\n */\n disabledTools?: string[]\n /**\n * Custom predicate run on each upstream tool. Return `true` to keep, `false`\n * to drop. Receives the raw `listTools()` payload — useful for filtering by\n * description, schema shape, or other metadata that an allow/deny list can't\n * express.\n *\n * Runs after the allow/deny filter but before the `mcp:tools:filter` hook.\n */\n toolFilter?: (tool: { name: string, description?: string | null, inputSchema?: unknown }) => boolean\n /**\n * Per-server override for {@link AgentBehavior.toolDisclosure}. When set,\n * this server's tools follow this disclosure mode regardless of the\n * agent-wide default. Useful when one big MCP server (200+ tools) should\n * stay lazy while smaller servers stay eager.\n *\n * Default: inherits from `behavior.toolDisclosure`.\n */\n disclosure?: 'eager' | 'lazy'\n /**\n * Pre-cached tool schemas to advertise without issuing `tools/list` at\n * bootstrap. The connection is still established (the SDK's `connect()`\n * is needed for `tools/call`) — only the discovery round-trip is\n * skipped. Schemas are trusted as-is; the host owns invalidation\n * (typical cache key: `(server identity, server version)`). If the\n * server later returns `MethodNotFound` for a cached tool, the host\n * should drop the entry from its cache so the next bootstrap re-lists.\n *\n * Compatible with every transport, every auth mode, and with\n * {@link McpServerConfig.lazyConnect}. Composes with the existing\n * `enabledTools` / `disabledTools` / `toolFilter` filters — those run\n * over the cached schemas exactly as they would over `listTools()`\n * output.\n */\n cachedTools?: McpToolSchema[]\n /**\n * Defer the `client.connect(transport)` call until the first\n * `tools/call` reaches this server. Bootstrap registers the server's\n * tools using {@link McpServerConfig.cachedTools} without touching\n * the network, taking MCP setup off the critical path of\n * `agent.run()`. The first invocation pays the connect cost\n * (~200-500ms typically); every subsequent call reuses the live\n * client.\n *\n * Requires {@link McpServerConfig.cachedTools} — without schemas in\n * hand there is nothing to advertise to the model, so deferring the\n * connection has no purpose. Bootstrap rejects the config otherwise.\n *\n * **Incompatible with `auth: 'oauth'`**: the OAuth handshake (token\n * refresh / RFC 9728 metadata discovery) can fail in ways that today\n * fire `mcp:auth:required` at bootstrap so the host can surface a\n * login affordance *before* the model commits to calling a tool.\n * Deferring that to first call means an auth failure surfaces mid-run\n * as a tool-result error, which the model can't recover from without\n * a fresh prompt. Bootstrap rejects the combination so the error is\n * loud and proximate to the misconfiguration. Use OAuth servers\n * without `lazyConnect` (with `cachedTools` alone, if you want to\n * skip the `tools/list` round-trip).\n *\n * On connect failure (network error, transport refused), the cached\n * promise is dropped so the next `tools/call` retries. The model\n * sees the failure as a normal tool error. Subsequent calls remain\n * eligible to succeed once the upstream is reachable again.\n */\n lazyConnect?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Tool execution\n// ---------------------------------------------------------------------------\n\nexport type ToolExecutionMode = 'sequential' | 'parallel'\n\nexport interface AgentBehavior {\n /** Tool execution mode (default: 'sequential') */\n toolExecution?: ToolExecutionMode\n /**\n * Max agent loop iterations.\n *\n * Default: unlimited (Infinity). The loop runs until the model signals\n * completion (no tool calls / `end_turn`), the abort signal fires, or this\n * cap is hit. Set a finite value as a safety net for runaway loops.\n */\n maxTurns?: number\n /** Max tokens per LLM response (default: 16384) */\n maxTokens?: number\n /** Thinking token budget — overrides the level-based default when set */\n thinkingBudget?: number\n /** JSON Schema for structured output enforcement */\n schema?: Record<string, unknown>\n /**\n * Enable provider prompt caching. When on (default), the provider marks the\n * system prompt, tools, and the last stable message with cache breakpoints so\n * the shared prefix is served from cache across turns.\n *\n * - Anthropic: `cache_control: { type: 'ephemeral' }` on the last `system`\n * content part, the last tool, and the last message content part.\n * - OpenAI-compatible / OpenRouter: same shape — honored by Anthropic-backed\n * OpenRouter routes and by Gemini; ignored (no-op) by providers that cache\n * automatically (OpenAI, DeepSeek, Grok, Groq, Moonshot).\n *\n * Usage is surfaced via `TurnUsage.cacheRead` / `TurnUsage.cacheCreation`.\n *\n * Default: `true`.\n */\n cache?: boolean\n /**\n * Soft per-turn cap on total tool-output bytes. When the sum of `outputBytes`\n * across a turn's tool results exceeds this value, the loop injects a\n * synthetic user message instructing the model to summarize before calling\n * more tools, and fires the `budget:exceeded` hook.\n *\n * Measured **post-`tool:transform`** so consumer truncation counts toward the\n * budget. Off by default (undefined / `0` disables the check). A reasonable\n * starting value for OSS-model integrations is `32768`.\n */\n toolOutputBudget?: number\n /**\n * Deduplicate identical re-reads of the same file in `read_file`. When the\n * model re-reads a file with the same slice and the bytes haven't changed\n * since the last read in this session, the tool returns a short stub\n * instead of re-emitting the full content. Pairs with the read-before-edit\n * guard in `edit` / `multi_edit`.\n *\n * Requires a session (set via `createSession()`); without one, the flag is\n * a no-op since per-session state has nowhere to live.\n *\n * Default: `true`.\n */\n dedupReads?: boolean\n /**\n * Taper the thinking budget over the course of a run. Late turns are\n * usually checkpoint / cleanup work where reasoning rarely pays for\n * itself; early turns benefit most. Two forms:\n *\n * - **Struct** — geometric decay starting after `afterTurn`, multiplying by\n * `factor` each subsequent turn, clamped to `floor`. Example\n * `{ afterTurn: 5, factor: 0.5, floor: 1024 }` with a base budget of 8192:\n * turns 1-5 = 8192, turn 6 = 4096, turn 7 = 2048, turn 8+ = 1024.\n * - **Function** — `(runTurn, baseBudget) => number`. Arbitrary curves;\n * `runTurn` is 1-indexed, run-relative (resumed sessions reset).\n *\n * No-op when `thinkingBudget` is unset. Honored by every provider that\n * respects `thinkingBudget` (anthropic explicit-budget `enabled` path,\n * adaptive `maxTokensCap`, openai-compat `max_tokens` padding).\n *\n * Default: `undefined` (no decay).\n */\n thinkingDecay?: { afterTurn: number, factor: number, floor: number } | ((runTurn: number, baseBudget: number) => number)\n /**\n * Per-tool soft call budget for this run. Keyed by **canonical** tool name.\n * On the first call after the run-cumulative dispatched count for that tool\n * reaches `max`, the framework fires `onExceed`:\n *\n * - `'steer'` (default) — let the call execute, but emit a synthetic user\n * message after the turn that nudges the model away from re-calling the\n * tool. Reuses the existing post-turn steer pathway used by\n * `toolOutputBudget`. Fires `tool-budget:exceeded` with `mode: 'steer'`.\n * - `'block'` — refuse the call via `tool:gate` `block`. The model sees a\n * `Blocked: <reason>` tool result. Fires `tool-budget:exceeded` with\n * `mode: 'block'`.\n * - **Function** — `(ctx) => { mode, message }`. The consumer supplies the\n * steering / refusal text and chooses the mode dynamically.\n *\n * Counts include both real dispatches and dedup substitutes (Z19 hits).\n * Excludes calls already blocked by an earlier gate (skill allow-list,\n * consumer hook). Tool dispatched by spawned subagents has its own per-run\n * counter — child counts never charge the parent.\n *\n * For MCP tools, key by the namespaced wire name (`mcp_<server>_<tool>`).\n *\n * Atomic in parallel mode: the middleware tracks its own per-tool\n * approval counter, incremented synchronously at gate-time. A\n * 4-call parallel batch against `max: 2` will let the first 2 through\n * and refuse the rest, even though the loop's `runToolCounts` only\n * propagates between calls (not within a single batch's gate fan-out).\n *\n * Default: `undefined` (no budget enforcement).\n */\n toolBudgets?: Record<string, {\n max: number\n onExceed?: 'steer' | 'block' | ((ctx: {\n tool: string\n count: number\n max: number\n }) => { mode: 'steer' | 'block', message: string })\n }>\n /**\n * Generic per-tool argument deduplication. Keyed by the tool's **canonical**\n * name (alias-stable). Each entry is a hasher: `(input) => string | undefined`.\n *\n * **Hasher contract** — three return values, three meanings:\n *\n * | Return | Meaning |\n * |-------------------------|------------------------------------------------------------------------|\n * | a non-empty string | Cache key for this call. Equal keys (most-recent-only, this session) |\n * | | replay the prior recorded result without re-dispatching the tool. |\n * | `undefined` | **Skip dedup for this call.** The tool runs normally; nothing recorded.|\n * | `''` / non-string | Treated identically to `undefined` (defensive: no dedup, no error). |\n *\n * The `undefined` opt-out is the way to say *\"this specific call is not\n * cacheable\"* (timestamps in input, randomness baked in, debug flags). It\n * is **not** the same as `JSON.stringify(input)` — that would dedup against\n * the verbatim input. Pick one explicitly:\n *\n * ```ts\n * // Always cache by full input — every identical re-call dedups.\n * dedupTools: { my_pure_tool: input => JSON.stringify(input) }\n *\n * // Cache by a normalized subset; non-cacheable shapes opt out.\n * dedupTools: {\n * execute_sql: (input) => {\n * const q = typeof input.query === 'string' ? input.query.trim().toLowerCase() : undefined\n * if (!q || q.includes('now()') || q.includes('random()')) return undefined\n * return q\n * },\n * }\n * ```\n *\n * On a hit, the previously-recorded result is replayed as the tool_result\n * without dispatching the tool. The substitution flows through `tool:gate`\n * `result` (Z20), so `tool:after` and `tool:transform` still fire.\n *\n * Requires a session (`createSession()`); without one, the map is a silent\n * no-op since per-session state has nowhere to live. Tools with side\n * effects or non-deterministic outputs (network, time, randomness) MUST\n * NOT be listed — there is no safety net beyond the consumer's hasher.\n *\n * For MCP tools, key by the namespaced wire name (`mcp_<server>_<tool>`).\n * Parallel mode (`toolExecution: 'parallel'`, the default) sees calls in\n * the SAME assistant turn race against each other — none can dedup against\n * a sibling that started in the same batch. Sequential mode honors order\n * within a turn.\n *\n * **Cache policy**: only the most recent `(hash, result)` per tool is\n * retained. Interleaved patterns (input A, input B, input A) miss on the\n * second A because B overwrote it. Sufficient for the common spam-the-\n * same-call loop; consumers needing a richer cache should hook\n * `tool:gate` directly.\n *\n * Default: `undefined` (no per-tool dedup).\n */\n dedupTools?: Record<string, (input: Record<string, unknown>) => string | undefined>\n /**\n * Require `read_file` before `edit` / `multi_edit` on the same path, and\n * reject edits when the file has changed on disk since the last read in\n * this session. Eliminates the silent-corruption failure mode where a\n * model \"remembers\" stale content and applies a substring edit against\n * bytes that have moved.\n *\n * Requires a session. Off by default; turn it on for stricter eval-grade\n * runs where silent edit corruption would invalidate the result.\n *\n * Default: `false`.\n */\n requireReadBeforeEdit?: boolean\n /**\n * Client-side context compaction strategy. Use this for non-Anthropic\n * providers (OSS via cerebras / openai-compat / openrouter) that don't\n * have a server-side equivalent. Anthropic users should prefer the\n * server-side `context-management-2025-06-27` beta — see\n * `AnthropicParams.contextManagement`.\n *\n * - `'off'` (default) — no client-side compaction.\n * - `'tail'` — when total tool-output bytes in the persisted history\n * exceed `compactThreshold`, replace older `tool_result` outputs with a\n * short stub, keeping the newest `compactKeepTurns` turns intact. The\n * compaction is applied to the wire-level message list only; the\n * underlying session turns are not modified.\n *\n * Default: `'off'`.\n */\n compactStrategy?: 'off' | 'tail'\n /**\n * Soft byte threshold that triggers tail compaction when\n * `compactStrategy === 'tail'`. Counts the post-`context:transform` bytes\n * of `tool_result` outputs across all messages. Default: `131_072` (128\n * KiB). Ignored when compaction is off.\n */\n compactThreshold?: number\n /**\n * Number of trailing turns to leave untouched during tail compaction. The\n * most-recent `compactKeepTurns` user/assistant messages are not eligible\n * for elision so the model keeps the freshest tool context. Default: `4`.\n */\n compactKeepTurns?: number\n /**\n * Prefix every line of `read_file` output with its 1-indexed line number\n * followed by a tab (`<N>\\t<content>`) — the compact `cat -n`-style\n * format Claude Code emits. The `edit` tool strips the prefix from\n * `old_string` / `new_string` so the model can paste back a numbered\n * chunk verbatim without breaking the match.\n *\n * Set `false` to opt out — useful for callers piping `read_file` into\n * downstream parsers that don't recognize the prefix. Per-call\n * `read_file({ lineNumbers: false })` overrides this default.\n *\n * Default: `true`.\n */\n readLineNumbers?: boolean\n /**\n * Replace older `read_file` `tool_result` blocks with a short stub when\n * a successful `edit` / `multi_edit` / `write_file` later in the same\n * run modified the same path. The replacement is applied to the\n * wire-level message list only — persisted session turns keep the\n * original content.\n *\n * Eliminates the common waste pattern where the model carries the\n * pre-edit file body forward across many turns \"in case it needs it\".\n * Pairs cleanly with `compactStrategy: 'tail'`: stale reads shrink\n * first, then the byte-threshold compaction fires if anything's left.\n *\n * Detection is conservative — only triggers when the corresponding\n * tool_result confirms success (`Edited …`, `Created …`, `Updated …`).\n * Failed edits and `No change needed` write_file calls do NOT\n * invalidate prior reads.\n *\n * Default: `false`.\n */\n elideStaleReads?: boolean\n /**\n * Tool disclosure strategy. Controls whether the model sees every tool's\n * full `inputSchema` in its tool list every turn (\"eager\") or whether MCP\n * tools are advertised as a name+description catalog in the system prompt\n * and only get full schemas after being surfaced via the `tool_search`\n * native tool (\"lazy\" / progressive disclosure).\n *\n * Native tools (those passed to `createAgent({ tools })`) and skill tools\n * are always eager — they are core to the agent and cheap. Only MCP tools\n * are eligible for lazy disclosure.\n *\n * When `'lazy'`, the agent:\n * - Appends a `<searchable_tools>` section to the system prompt listing\n * every MCP tool by `name` + `description` only (no `inputSchema`).\n * - Auto-injects a `tool_search` native tool (opt out via\n * {@link AgentBehavior.toolSearch}) the model uses to load schemas on\n * demand. Surfaced tools persist for the rest of the run.\n * - Rebuilds the wire-level tool list each turn, appending newly-unlocked\n * tools at the end so the prefix-cache breakpoint advances cleanly.\n *\n * Trade-off: every `tool_search` invocation expands the tool list and\n * invalidates the tool-list cache breakpoint for one turn. With many\n * MCP servers, the savings on cold turns (fewer schemas in context) are\n * substantial; with one tiny MCP server, the overhead may not pay back.\n *\n * Default: `'eager'`.\n */\n toolDisclosure?: 'eager' | 'lazy'\n /**\n * Fine-grained config for the `tool_search` tool auto-injected when\n * {@link AgentBehavior.toolDisclosure} is `'lazy'`. No-op in eager mode.\n *\n * - `tool: false` — opt out of the auto-injection entirely. Use when the\n * host wants to ship a custom discovery tool. Note that the catalog\n * text drops the call-to-action prose in this case so the model isn't\n * pointed at a non-existent tool.\n * - `limit` — default cap on results returned per `tool_search` call when\n * the model omits the parameter. Default: `20`.\n *\n * Note on host-defined `tool_search`: a tool the host registers under the\n * name `tool_search` (or under any alias whose canonical is `tool_search`)\n * will shadow the auto-injected one — the catalog text will point at the\n * host's wire name, but driving the unlock flow requires either using\n * `createToolSearchTool({ catalog, unlocked })` from `tools/tool-search`\n * (which internally mutates the unlock set) or fully opting out via\n * `toolSearch.tool: false` and treating discovery as a host-side concern.\n * A bare host tool that doesn't touch the unlock set will not advance the\n * lazy disclosure state and the hard gate will keep refusing lazy calls.\n *\n * Default: `undefined` (auto-inject with the default limit).\n */\n toolSearch?: {\n tool?: false\n limit?: number\n }\n /**\n * Persist large `tool_result` outputs to disk and replace the in-message\n * content with a `<persisted-output>` stub (preview + filesystem path).\n * When the post-`tool:transform` byte size of a tool's result exceeds\n * this threshold, the framework writes the full payload to\n * `<persistDir>/<callId>.txt` and substitutes a fixed-format stub so the\n * model sees a 2 KiB preview plus the path it can `read_file`.\n *\n * The substitution happens at emit time (just after `tool:transform` runs)\n * and the stub flows into `session.turns` directly — so every subsequent\n * turn re-emits the same bytes, keeping the prompt-cache prefix stable.\n *\n * Set `0` / `undefined` to disable. Built-in chat profiles default to\n * `8192`. Tools listed in {@link AgentBehavior.persistExcludeTools} bypass\n * regardless of size — typically because their output is intentionally\n * short or persisting would be circular (e.g. `read_file`).\n *\n * Requires {@link AgentBehavior.persistDir} to be set; without a target\n * directory the framework silently skips persistence (no throw, no\n * substitution) since there's nowhere to write the blob.\n *\n * Default: `undefined` (off).\n */\n persistThreshold?: number\n /**\n * Canonical tool names to exclude from disk persistence regardless of\n * output size. The framework bypasses persistence for any tool whose\n * canonical name appears in this list — useful for tools whose results\n * are intentionally part of the prompt (`skills_use`), short envelopes\n * (`tool_search`, `present_plan`, `ask_user`), or where persistence\n * would be circular (`read_file`, whose pagination already serves the\n * same use case).\n *\n * Default: `undefined` (no exclusions). The chat-layer built-in profiles\n * set their own list — see `src/chat/agents.ts`.\n */\n persistExcludeTools?: readonly string[]\n /**\n * Directory under which persisted tool-result blobs land. Each call's\n * payload is written to `<persistDir>/<callId>.txt` (one file per\n * `tool_use` id, atomic via write-then-rename).\n *\n * The chat layer resolves this to `<userDir>/tool-results/<sessionId>/`\n * at session activation; SDK consumers pass an absolute path. Required\n * when {@link AgentBehavior.persistThreshold} is non-zero — when unset\n * the framework treats persistence as disabled.\n *\n * Default: `undefined`.\n */\n persistDir?: string\n /**\n * Fail-fast instead of repair when the pre-send pairing pass detects\n * corruption (orphan `tool_use` / `tool_result`, duplicate ids,\n * compaction-stranded blocks). Throws {@link AgentToolPairingError} from\n * the next `agent.run()` turn carrying the structured repair list the\n * loop would have performed.\n *\n * Use case: training-data collectors that must reject any transcript\n * containing the synthetic `SYNTHETIC_TOOL_RESULT_PLACEHOLDER` rather\n * than ship poisoned data to the fine-tuning pipeline. User-facing chat\n * sessions should leave this off (the repair-on-the-fly behavior is the\n * point of the pass).\n *\n * Telemetry note: `pairing:repair` still fires for every repair before\n * the throw, so observability handlers see exactly what would have\n * happened.\n *\n * Default: `false`.\n */\n strictToolPairing?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Prompt parts (multimodal input)\n// ---------------------------------------------------------------------------\n\n/**\n * One block of a multimodal user prompt.\n *\n * `agent.run({ prompt })` accepts either a plain string (treated as a single\n * text part) or an array of these parts for multimodal inputs.\n *\n * `document` parts are routed per provider: PDF-style mime types are sent as\n * native document blocks when the provider supports them; text documents are\n * inlined as text with an attachment header. Providers that cannot handle an\n * image or document throw early.\n */\nexport type PromptPart\n = | PromptTextPart\n | PromptImagePart\n | PromptDocumentPart\n\nexport interface PromptTextPart {\n type: 'text'\n text: string\n}\n\nexport interface PromptImagePart {\n type: 'image'\n /** IANA media type (e.g. `image/png`, `image/jpeg`) */\n mediaType: string\n /** Base64-encoded payload */\n data: string\n /** Optional display name */\n name?: string\n}\n\nexport interface PromptDocumentPart {\n type: 'document'\n /** IANA media type (e.g. `application/pdf`, `text/plain`) */\n mediaType: string\n /** Either a base64-encoded payload (`encoding: 'base64'`) or raw text (`encoding: 'text'`) */\n data: string\n encoding: 'base64' | 'text'\n /** Optional display name used in attachment headers */\n name?: string\n}\n\n// ---------------------------------------------------------------------------\n// Canonical message format (used throughout the agent system)\n// ---------------------------------------------------------------------------\n\n/**\n * A single block of structured tool-result content.\n *\n * MCP servers can return a mix of text, image, resource, and audio blocks. Tools\n * return `string` for the common text-only case or `ToolResultContent[]` when they\n * need to preserve non-text content (e.g. screenshots from a browser MCP).\n *\n * Providers that support native multi-part tool results (Anthropic, OpenAI Codex via\n * pi-ai) route image blocks into their wire format verbatim; OpenAI-compat providers\n * route them via a companion-user-message fallback when the underlying model/endpoint\n * does not accept images inside tool-role messages.\n */\nexport type ToolResultContent\n = | ToolResultTextContent\n | ToolResultImageContent\n\nexport interface ToolResultTextContent {\n type: 'text'\n text: string\n}\n\nexport interface ToolResultImageContent {\n type: 'image'\n /** IANA media type (e.g. `image/png`, `image/jpeg`) */\n mediaType: string\n /** Base64-encoded payload */\n data: string\n}\n\n/**\n * Lossy flattener — converts `ToolResultContent[]` (or a plain string) to a single\n * string. Image blocks are replaced with `[image: <media> — <n> b64 bytes]` markers.\n *\n * Use at UI boundaries where a string is required; providers that understand\n * structured content should route the array through without flattening.\n */\nexport function toolResultToText(content: string | ToolResultContent[]): string {\n if (typeof content === 'string')\n return content\n return content\n .map((block) => {\n if (block.type === 'text')\n return block.text\n return `[image: ${block.mediaType} — ${block.data.length} b64 bytes]`\n })\n .join('\\n')\n}\n\n/**\n * Approximate **wire payload size** of a tool output, in bytes.\n *\n * - Plain text: UTF-8 byte length.\n * - Structured content: text blocks contribute their UTF-8 byte length; image\n * blocks contribute their **base64 character length** — a proxy for the\n * serialized request-body footprint, NOT for tokens. Vision encoders\n * tokenize decoded pixels (geometry-dependent; e.g. Anthropic ≈ `w·h/750`,\n * OpenAI ≈ 85 + 170/tile), which has no meaningful relationship to base64\n * length.\n *\n * Used by the agent loop to populate `outputBytes` on `tool:after`,\n * `tool:transform`, `mcp:tool:after`, and `mcp:tool:transform` hooks so\n * consumers can size-budget tool output without re-counting bytes themselves.\n * Suitable for byte-budget heuristics (`toolOutputBudget`, tail compaction);\n * NOT a substitute for provider-side context-window accounting — defer to\n * server-side context management (e.g. Anthropic's `context-management-*`\n * beta) when token accuracy matters.\n */\nexport function toolOutputByteLength(content: string | ToolResultContent[]): number {\n if (typeof content === 'string')\n return Buffer.byteLength(content)\n let total = 0\n for (const block of content) {\n if (block.type === 'text')\n total += Buffer.byteLength(block.text)\n else\n total += block.data.length\n }\n return total\n}\n\nexport type SessionContentBlock\n = | { type: 'text', text: string }\n | { type: 'image', mediaType: string, data: string }\n | { type: 'tool_call', id: string, name: string, input: Record<string, unknown> }\n | {\n type: 'tool_result'\n callId: string\n /**\n * Tool output — either a plain string (text-only, the common case) or a structured\n * array of content blocks (text + image for multimodal tools such as screenshots).\n */\n output: string | ToolResultContent[]\n isError?: boolean\n }\n | {\n type: 'thinking'\n text: string\n signature?: string\n /**\n * Provider that minted `signature`. Signatures are provider-bound (Anthropic\n * HMAC vs. OpenAI `encrypted_content`) and are dropped on cross-provider\n * hops to avoid 400s. Unset means legacy/unknown — forwarded as-is.\n */\n signatureProducer?: 'anthropic' | 'openai'\n }\n | { type: 'redacted_thinking', data: string }\n | {\n /**\n * Opaque round-trip envelope for reasoning state minted by an OpenAI-compat\n * gateway (currently OpenRouter). The gateway expects its own\n * `reasoning_details` array echoed back verbatim on the next turn so the\n * upstream model can resume an extended-reasoning chain across tool calls.\n *\n * Stored opaquely because the items are provider-bound (Anthropic HMAC\n * signatures, OpenAI `encrypted_content`, model-specific summary formats\n * — all flowing through the gateway's normalized envelope).\n */\n type: 'provider_reasoning'\n producer: 'openrouter'\n details: unknown[]\n /**\n * Model id that produced the details. Reasoning is bound to a specific\n * upstream route — a model switch on the next turn invalidates the\n * embedded signatures, so the sender drops the block on mismatch.\n */\n model?: string\n }\n | {\n /**\n * Compaction marker. Inserted by `compactConversation()` to replace a\n * prefix of turns with an LLM-generated summary.\n *\n * The marker lives in `session.turns` and renders in the transcript —\n * the user can still scroll back to see the original turns. From the\n * agent loop's wire-level perspective, every turn whose id appears in\n * `replacesTurnIds` is dropped, and this block's `summary` text is\n * sent to the model as a single user message in their place.\n *\n * The marker turn carries `role: 'user'` so it sits naturally at a\n * conversational boundary. Only the latest `compact-summary` block in\n * the session is honored — earlier markers are subsumed by later\n * ones (their `replacesTurnIds` are a strict prefix).\n */\n type: 'compact-summary'\n /** Turn ids the summary replaces, in chronological order. */\n replacesTurnIds: readonly string[]\n /** The summary text sent to the model in place of the elided turns. */\n summary: string\n /** Model id used to produce the summary. */\n model: string\n /** Token usage from the summary call. */\n usage: TurnUsage\n /** Unix-ms when compaction completed. */\n compactedAt: number\n }\n\nexport interface SessionMessage {\n role: 'user' | 'assistant'\n content: SessionContentBlock[]\n}\n\nexport interface SessionTurn {\n /** UUID — generated by the store if it provides generateTurnId, else crypto.randomUUID() */\n id: string\n /** Run that produced this turn (e.g. 'run_1') */\n runId?: string\n role: 'user' | 'assistant' | 'system'\n content: SessionContentBlock[]\n /** Token usage — only present on assistant turns */\n usage?: TurnUsage\n /** Unix timestamp (Date.now()) when the turn was created */\n createdAt: number\n}\n\n// ---------------------------------------------------------------------------\n// Agent run options\n// ---------------------------------------------------------------------------\n\n/**\n * Per-run hook registrations. Each entry can be a single handler or an array of handlers.\n * Keys are `AgentHooks` event names (loose-typed here to avoid a circular import; agent.ts\n * narrows it to the strongly-typed map).\n */\nexport type RunHookMap = Record<string, ((ctx: any) => unknown) | ((ctx: any) => unknown)[]>\n\nexport interface AgentRunOptions {\n model?: string\n /**\n * User prompt. Optional when resuming a session with existing turns.\n *\n * Accepts either a plain string (single text part) or an array of `PromptPart`s for\n * multimodal inputs (text, images, documents). See {@link PromptPart}.\n */\n prompt?: string | PromptPart[]\n system?: string\n thinking?: ThinkingLevel\n /** Abort signal — when triggered, the agent stops after the current turn */\n signal?: AbortSignal\n /** Behavior overrides for this run (overrides agent defaults) */\n behavior?: AgentBehavior\n /** Tool overrides for this run. Pass {} for no tools. Omit to use agent tools. */\n tools?: Record<string, ToolDef>\n /**\n * Per-run hook registrations. Each hook is attached before the run starts and\n * detached in a finally block so handlers never leak across runs.\n *\n * Accepts either a single handler or an array (all handlers register).\n */\n hooks?: RunHookMap\n /**\n * Parent run id. Populated automatically by the `spawn` tool when the child\n * shares the parent's session; recorded on the resulting `SessionRun` so the\n * parent↔child run tree can be reconstructed from a persisted session.\n */\n parentRunId?: string\n /**\n * Zero-based subagent depth. 0 = top-level `agent.run()`, 1 = first-level\n * child spawned by a parent agent, and so on. Used by the spawn tool to\n * enforce `maxDepth` and to stamp `child:*` forwarded hook payloads.\n */\n depth?: number\n}\n\n// ---------------------------------------------------------------------------\n// Agent stats\n// ---------------------------------------------------------------------------\n\n/**\n * Reason the provider gave for stopping the turn.\n *\n * - `'stop'` — natural turn end (`end_turn` / `stop_sequence`).\n * - `'tool-calls'` — model emitted tool_use blocks.\n * - `'length'` — `max_tokens` reached, or (Anthropic 4.6+) the response bumped\n * against the model's context window mid-stream\n * (`model_context_window_exceeded`). The partial response is preserved; the\n * loop emits this reason so consumers can prune/retry.\n * - `'content-filter'` — model refused.\n * - `'pause'` — Anthropic `pause_turn`: a server-side mid-turn pause for very\n * long thinking. The loop continues with a synthetic \"Please continue.\"\n * user message rather than terminating; consumers see the pause via this\n * finish reason on the prior assistant turn.\n * - `'error'` — provider classified the turn as failed.\n * - `'other'` — unknown / unmapped.\n */\nexport type TurnFinishReason = 'stop' | 'tool-calls' | 'length' | 'content-filter' | 'pause' | 'error' | 'other'\n\nexport interface TurnUsage {\n input: number\n output: number\n /** Tokens written to cache (Anthropic) */\n cacheCreation?: number\n /** Tokens read from cache (Anthropic) */\n cacheRead?: number\n /** Thinking/reasoning tokens used */\n thinking?: number\n /**\n * Cost in USD for this turn. Provider-reported when available\n * (OpenRouter, OpenAI via pi-ai); otherwise estimated from `modelId` ×\n * pi-ai's bundled price registry by `fillEstimatedCost` in\n * `src/providers/cost.ts`. Absent only when neither path could resolve\n * a price (unknown / unbundled model).\n */\n cost?: number\n /**\n * Why the model stopped this turn. Providers normalize native stop reasons to this union.\n * Absent when the provider did not surface a reason (e.g. mock turns).\n */\n finishReason?: TurnFinishReason\n /**\n * The model ID the provider ultimately used. May differ from the requested model when the\n * provider remaps aliases. Absent for providers that do not echo a model ID.\n */\n modelId?: string\n}\n\nexport interface AgentStats {\n /**\n * Cumulative input tokens across the parent agent loop **and** every\n * recursively-spawned sub-agent. Use this for billing / token-ledger\n * consumption.\n */\n totalIn: number\n /** Cumulative output tokens. Same semantics as {@link AgentStats.totalIn}. */\n totalOut: number\n /**\n * Cumulative cache-read tokens across the parent agent loop and every\n * recursively-spawned sub-agent. Surfaced at the top level (rather than\n * only per-`TurnUsage`) because Anthropic prices cache reads at a separate\n * line-item rate from regular input — billing-correct cost computation\n * needs this number directly. Always `0` for providers that don't report\n * cache usage.\n */\n totalCacheRead: number\n /**\n * Cumulative cache-creation tokens across the parent agent loop and every\n * recursively-spawned sub-agent. Same rationale as\n * {@link AgentStats.totalCacheRead} — separate Anthropic billing rate.\n * Always `0` for providers that don't report cache usage.\n */\n totalCacheCreation: number\n /**\n * Number of parent agent-loop turns. Children's turn counts live under\n * `children[].stats.turns` and are NOT folded in here — a single \"turns\"\n * number for the whole tree would conflate two different measures\n * (parent-loop iterations vs. tree-wide tool-call rounds).\n *\n * Tree-wide turn count: `flattenTurns(stats).length`.\n */\n turns: number\n /**\n * Wall-clock duration of the top-level `agent.run()` call, in milliseconds.\n * Children run during parent tool calls so this naturally subsumes child\n * wall time — sequential children inflate it, parallel children compress\n * into the parent's window.\n */\n elapsed: number\n /**\n * Per-turn usage breakdown for the **parent loop only**. Children's per-turn\n * usages live under `children[].stats.turnUsage`. Use {@link flattenTurns}\n * to walk the full tree.\n */\n turnUsage?: TurnUsage[]\n /**\n * Cumulative cost in USD — parent loop plus every recursively-spawned\n * sub-agent. Sums per-turn `TurnUsage.cost` reported by the provider.\n * Absent when neither parent nor any descendant reported a non-zero cost.\n */\n cost?: number\n /** Stats from child agents spawned during this run, in completion order. Recursive. */\n children?: ChildRunStats[]\n /** Structured output from schema enforcement (only present when behavior.schema is set) */\n output?: Record<string, unknown>\n /**\n * Milliseconds from the start of `agent.run()` to the first observable signal from the\n * provider (first `stream:text`, `stream:thinking`, or `tool:before` event).\n *\n * Absent when the run produced no observable signals (e.g. aborted before any stream event).\n */\n timeTillFirstTokenMs?: number\n}\n\nexport interface ChildRunStats {\n id: string\n task: string\n /**\n * The child agent's full {@link AgentStats}. Cumulative for that child's\n * own subtree (child loop + its grandchildren). Do **not** sum\n * `ctx.stats.totalIn` across `spawn:complete` events to derive top-level\n * totals — `agent.run()`'s return value is the canonical cumulative root.\n */\n stats: AgentStats\n /**\n * Subagent depth when this child ran. 1 = direct child of the top-level\n * agent, 2 = grandchild, etc. Useful for telemetry that wants to group\n * runs by depth.\n */\n depth?: number\n /**\n * Terminal state of the child run. `'completed'` is the default. Exposed so\n * a parent reading `stats.children` can distinguish aborted/timed-out\n * children without re-parsing the returned string.\n */\n status?: 'completed' | 'aborted' | 'timeout' | 'error'\n /**\n * Final structured output when the child was run with `behavior.schema`.\n * Mirrors `AgentStats.output` but is surfaced here so the parent can read\n * it without peeking at the nested `stats` bag.\n */\n output?: Record<string, unknown>\n}\n\n// ---------------------------------------------------------------------------\n// Hook context types\n// ---------------------------------------------------------------------------\n\n/**\n * Base context for tool execution hooks.\n *\n * `name` is the canonical tool identity — the spec name registered on the agent (or the\n * `mcp_{server}_{tool}` name for MCP tools). Hooks should policy-match against `name`.\n *\n * `displayName` is the outward-facing name — the alias surfaced to the LLM when\n * `AgentOptions.toolAliases` maps the canonical name; otherwise equal to `name`.\n * UI/telemetry adapters should emit `displayName`.\n *\n * Canonical vs. alias matters on session resume: `session.turns` persists canonical\n * names only, so renaming an alias cannot desync history.\n */\nexport interface ToolHookContext {\n turnId: string\n callId: string\n /** Canonical tool name (spec name). Stable across alias-map changes. */\n name: string\n /** Aliased (wire) name — equal to `name` when no alias is defined. */\n displayName: string\n input: Record<string, unknown>\n}\n\n/**\n * Base context for MCP tool hooks.\n *\n * `tool` is the native tool name on the MCP server. `server` is the configured server\n * name. The canonical zidane-namespaced identity is `mcp_{server}_{tool}`.\n *\n * `displayName` equals the canonical namespaced name unless the agent has aliased\n * this MCP tool via `AgentOptions.toolAliases`; in which case `displayName` is the\n * alias that the LLM sees.\n */\nexport interface McpToolHookContext {\n turnId: string\n callId: string\n server: string\n tool: string\n /** Aliased wire name for this MCP tool, or the canonical `mcp_{server}_{tool}` name. */\n displayName: string\n input: Record<string, unknown>\n}\n\n/** Base context for session hooks */\nexport interface SessionHookContext {\n sessionId: string\n}\n\n/** Base context for spawn hooks */\nexport interface SpawnHookContext {\n id: string\n task: string\n /**\n * Subagent depth for the spawn. 1 = direct child of the top-level agent.\n * Present on spawn:before/complete/error. Absent for grandchild spawns that\n * bubble through `child:*` events (which carry their own `depth`).\n */\n depth?: number\n}\n\n/** Context for stream hooks */\nexport interface StreamHookContext {\n turnId: string\n}\n\n/** Context for OAuth refresh hooks */\nexport interface OAuthRefreshHookContext {\n provider: string\n providerId: string\n source: 'params' | 'file'\n previousCredentials: Record<string, unknown> & { access: string, refresh: string, expires: number }\n credentials: Record<string, unknown> & { access: string, refresh: string, expires: number }\n}\n\nexport type SessionEndStatus = 'completed' | 'aborted' | 'error'\n"],"mappings":";;;;;;;;;AAyoBA,SAAgB,iBAAiB,SAA+C;CAC9E,IAAI,OAAO,YAAY,UACrB,OAAO;CACT,OAAO,QACJ,KAAK,UAAU;EACd,IAAI,MAAM,SAAS,QACjB,OAAO,MAAM;EACf,OAAO,WAAW,MAAM,UAAU,KAAK,MAAM,KAAK,OAAO;GACzD,CACD,KAAK,KAAK;;;;;;;;;;;;;;;;;;;;;AAsBf,SAAgB,qBAAqB,SAA+C;CAClF,IAAI,OAAO,YAAY,UACrB,OAAO,OAAO,WAAW,QAAQ;CACnC,IAAI,QAAQ;CACZ,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,SAAS,QACjB,SAAS,OAAO,WAAW,MAAM,KAAK;MAEtC,SAAS,MAAM,KAAK;CAExB,OAAO"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as ExecutionHandle, i as ExecutionContext, n as ContextType, o as SpawnConfig, r as ExecResult, t as ContextCapabilities } from "./types-Ce78ds4h.js";
|
|
2
2
|
import { t as SandboxProvider } from "./index-BiO_5Hm4.js";
|
|
3
|
-
import { A as SessionStore, At as
|
|
4
|
-
import { I as ModelUsage, L as flattenTurns, R as statsByModel, _ as ChildAgent, f as ValidationResult, j as InteractionToolOptions, t as Preset, v as SpawnToolOptions, y as SpawnToolState } from "./index-
|
|
3
|
+
import { $t as TurnFinishReason, A as SessionStore, At as ChildRunStats, Bt as SessionContentBlock, C as SkillResource, Ct as CerebrasParams, D as Session, Dt as AgentBehavior, E as CreateSessionOptions, Ft as PromptDocumentPart, Gt as SpawnHookContext, Ht as SessionHookContext, It as PromptImagePart, Jt as ToolExecutionMode, Kt as StreamHookContext, Lt as PromptPart, Mt as McpToolHookContext, N as RemoteStoreOptions, O as SessionData, Ot as AgentRunOptions, Pt as OAuthRefreshHookContext, Qt as ToolResultTextContent, Rt as PromptTextPart, T as SkillsConfig, Tt as AnthropicParams, Ut as SessionMessage, Vt as SessionEndStatus, Wt as SessionTurn, Xt as ToolResultContent, Yt as ToolHookContext, Zt as ToolResultImageContent, an as AgentProviderError, at as ToolResult, b as ToolMap, cn as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, en as TurnUsage, et as Provider, fn as matchesContextExceeded, i as AgentOptions, in as AgentContextExceededError, it as ToolCall, jt as McpServerConfig, k as SessionRun, kt as AgentStats, ln as ClassifiedError, nn as toolResultToText, nt as StreamCallbacks, on as AgentToolNotAllowedError, ot as ToolSpec, p as McpConnection, pt as OpenRouterParams, qt as ThinkingLevel, r as AgentHooks, rn as AgentAbortedError, rt as StreamOptions, st as TurnResult, t as Agent, tn as toolOutputByteLength, tt as ProviderCapabilities, un as ClassifiedErrorKind, v as ToolContext, x as SkillConfig, xt as OpenAIParams, y as ToolDef, zt as RunHookMap } from "./agent-bKs7MRT2.js";
|
|
4
|
+
import { I as ModelUsage, L as flattenTurns, R as statsByModel, _ as ChildAgent, f as ValidationResult, j as InteractionToolOptions, t as Preset, v as SpawnToolOptions, y as SpawnToolState } from "./index-BlMvPh9X.js";
|
|
5
5
|
export { type Agent, AgentAbortedError, type AgentBehavior, AgentContextExceededError, type AgentHooks, type AgentOptions, AgentProviderError, type AgentRunOptions, type AgentStats, AgentToolNotAllowedError, type AnthropicParams, CONTEXT_EXCEEDED_MESSAGE_PATTERNS, type CerebrasParams, type ChildAgent, type ChildRunStats, type ClassifiedError, type ClassifiedErrorKind, type ContextCapabilities, type ContextType, type CreateSessionOptions, type ExecResult, type ExecutionContext, type ExecutionHandle, type InteractionToolOptions, type McpConnection, type McpServerConfig, type McpToolHookContext, type ModelUsage, type OAuthRefreshHookContext, type OpenAIParams, type OpenRouterParams, type Preset, type PromptDocumentPart, type PromptImagePart, type PromptPart, type PromptTextPart, type Provider, type ProviderCapabilities, type RemoteStoreOptions, type RunHookMap, type SandboxProvider, type Session, type SessionContentBlock, type SessionData, type SessionEndStatus, type SessionHookContext, type SessionMessage, type SessionRun, type SessionStore, type SessionTurn, type SkillConfig, type SkillResource, type SkillsConfig, type SpawnConfig, type SpawnHookContext, type SpawnToolOptions, type SpawnToolState, type StreamCallbacks, type StreamHookContext, type StreamOptions, type ThinkingLevel, type ToolCall, type ToolContext, type ToolDef, type ToolExecutionMode, type ToolHookContext, type ToolMap, type ToolResult, type ToolResultContent, type ToolResultImageContent, type ToolResultTextContent, type ToolSpec, type TurnFinishReason, type TurnResult, type TurnUsage, type ValidationResult, flattenTurns, matchesContextExceeded, statsByModel, toolOutputByteLength, toolResultToText };
|
package/dist/types.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as matchesContextExceeded, i as AgentToolNotAllowedError, n as AgentContextExceededError, o as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, r as AgentProviderError, t as AgentAbortedError } from "./errors-Byb0F8B9.js";
|
|
2
2
|
import { n as toolResultToText, t as toolOutputByteLength } from "./types-IcokUOyC.js";
|
|
3
3
|
import { r as statsByModel, t as flattenTurns } from "./stats-DgOvY7wd.js";
|
|
4
4
|
export { AgentAbortedError, AgentContextExceededError, AgentProviderError, AgentToolNotAllowedError, CONTEXT_EXCEEDED_MESSAGE_PATTERNS, flattenTurns, matchesContextExceeded, statsByModel, toolOutputByteLength, toolResultToText };
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"agent-CYpPKn5Z.d.ts","names":[],"sources":["../src/errors.ts","../src/types.ts","../src/providers/anthropic.ts","../src/providers/cerebras.ts","../src/providers/openai.ts","../src/providers/openai-compat.ts","../src/providers/openrouter.ts","../src/providers/index.ts","../src/session/file-map.ts","../src/session/memory.ts","../src/session/messages.ts","../src/session/remote.ts","../src/session/index.ts","../src/skills/types.ts","../src/tools/types.ts","../src/mcp/index.ts","../src/skills/activation.ts","../src/agent.ts"],"mappings":";;;;;;;;;;;;AAYA;;;;KAAY,mBAAA;AAGZ;AAAA,UAAiB,eAAA;EACf,IAAA,EAAM,mBAAA;EAAmB;EAEzB,YAAA;EAFM;EAIN,OAAA;EAAA;;;;AAQD;;EADC,SAAA;AAAA;AAAA,UAGQ,iBAAA;EAIR;EAFA,QAAA;EAMA;EAJA,YAAA;EAIS;EAFT,KAAA;EASqC;EAPrC,SAAA;AAAA;;;;;cAOW,yBAAA,SAAkC,KAAA;EAAA,SACpC,IAAA;EAAA,SACA,QAAA;EAAA,SACA,YAAA;cAEG,OAAA,UAAiB,OAAA,EAAS,iBAAA;AAAA;AAYxC;;;;AAAA,cAAa,kBAAA,SAA2B,KAAA;EAAA,SAC7B,IAAA;EAAA,SACA,QAAA;EAAA,SACA,YAAA;EAMA;;;;;EAAA,SAAA,SAAA;cAEG,OAAA,UAAiB,OAAA,EAAS,iBAAA;AAAA;;;;cAY3B,iBAAA,SAA0B,KAAA;EAAA,SAC5B,IAAA;cAEG,OAAA,WAA+B,OAAA;IAAY,KAAA;EAAA;AAAA;;;AAczD;;;;;;cAAa,wBAAA,SAAiC,KAAA;EAAA,SACnC,IAAA;EAMA;EAAA,SAJA,QAAA;;WAEA,WAAA;EAQP;EAAA,SANO,YAAA;EAQP;EAAA,SANO,YAAA;cAEG,OAAA;IACV,QAAA;IACA,WAAA;IACA,YAAA;IACA,YAAA;IACA,KAAA;EAAA;AAAA;AAgCJ;;;;;AAYA;AAZA,cAXa,iCAAA,WAA4C,MAAA;;;;AAgCzD;iBArBgB,sBAAA,CAAuB,OAAA;;;;;;;iBAYvB,YAAA,CAAa,GAAA;;;;iBASb,YAAA,CACd,cAAA,EAAgB,eAAA,EAChB,QAAA,UACA,KAA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A,CAAQ,aAAA;Eb3ZnC;;;;;;;;;;;AC2UtB;EY6FE,KAAA;AAAA;AAAA,UAGe,KAAA;EACf,KAAA,EAAO,QAAA,CAAS,UAAA;EAChB,GAAA,GAAM,OAAA,EAAS,eAAA,KAAoB,OAAA,CAAQ,UAAA;EAC3C,KAAA;EACA,KAAA,GAAQ,OAAA;EACR,QAAA,GAAW,OAAA;EACX,WAAA,QAAmB,OAAA;EZjGS;;;AA+B9B;;EYwEE,KAAA,QAAa,OAAA;EZxE2B;;AA2D1C;;EYkBE,OAAA,QAAe,OAAA;EZlBkB;;AAgCnC;;;;EYPE,aAAA,GAAgB,IAAA,aAAiB,OAAA;EZYlB;;;;EYPf,eAAA,GAAkB,IAAA,aAAiB,OAAA;EZ8BpB;;;;;;;;;;EYnBf,MAAA,QAAc,OAAA;EAAA,SACL,SAAA;EAAA,SACA,KAAA,EAAO,WAAA;EAAA,SACP,SAAA,EAAW,gBAAA;EAAA,SACX,MAAA,EAAQ,eAAA;EAAA,SACR,OAAA,EAAS,OAAA;EZwDlB;EAAA,SYtDS,YAAA,WAAuB,WAAA;EZsDR;;AA6C1B;;;;EA7C0B,SY/Cf,IAAA,EAAM,QAAA,CAAS,MAAA;AAAA;AAAA,iBAoQV,WAAA,CAAA;EAAc,QAAA;EAAU,IAAA,EAAM,SAAA;EAAW,MAAA,EAAQ,WAAA;EAAa,KAAA,EAAO,UAAA;EAAY,WAAA;EAAa,QAAA,EAAU,aAAA;EAAe,SAAA;EAAW,UAAA;EAAY,OAAA;EAAS,MAAA,EAAQ,WAAA;EAAa,YAAA;EAAc,KAAA;EAAO,KAAA,EAAO;AAAA,GAAgB,YAAA,GAAe,KAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-COmsomd5.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Typed error classes for agent runs.\n *\n * Providers classify native errors into one of these so downstream consumers\n * can react without string-sniffing messages.\n *\n * Provider authors: implement `Provider.classifyError` to map native errors\n * (SDK exceptions, HTTP responses) to a `ClassifiedError`. The loop wraps\n * unclassified errors in `AgentProviderError` automatically.\n */\n\n/** Kind of classified provider error */\nexport type ClassifiedErrorKind = 'context_exceeded' | 'provider_error' | 'aborted'\n\n/** Structured classification returned by `Provider.classifyError` */\nexport interface ClassifiedError {\n kind: ClassifiedErrorKind\n /** Upstream error code as surfaced by the provider (e.g. `context_length_exceeded`). Optional. */\n providerCode?: string\n /** Optional human-readable message override. Falls back to the underlying error's message. */\n message?: string\n /**\n * Hint that the error is transient and a retry with backoff is reasonable\n * (e.g. 429, 5xx, truncated stream). Omitted when the provider can't decide;\n * callers should default to \"do not retry\" when absent to avoid hammering\n * terminal failures (auth, invalid request).\n */\n retryable?: boolean\n}\n\ninterface TypedErrorOptions {\n /** Provider name, always set (e.g. `anthropic`, `openrouter`) */\n provider: string\n /** Optional upstream error code */\n providerCode?: string\n /** Original error from the provider SDK/HTTP layer */\n cause?: unknown\n /** See {@link ClassifiedError.retryable}. */\n retryable?: boolean\n}\n\n/**\n * Thrown when the model or provider signals that the context window was exceeded.\n * Downstream consumers should catch this, prune history, and retry.\n */\nexport class AgentContextExceededError extends Error {\n readonly code = 'context_exceeded' as const\n readonly provider: string\n readonly providerCode?: string\n\n constructor(message: string, options: TypedErrorOptions) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined)\n this.name = 'AgentContextExceededError'\n this.provider = options.provider\n this.providerCode = options.providerCode\n }\n}\n\n/**\n * Thrown when the provider returns a non-context error (auth, rate limit, server error, etc.).\n * Catch-all for unclassified provider failures.\n */\nexport class AgentProviderError extends Error {\n readonly code = 'provider_error' as const\n readonly provider: string\n readonly providerCode?: string\n /**\n * Whether a retry with backoff is likely to succeed. See\n * {@link ClassifiedError.retryable}. Absent when the provider did not\n * classify the error — callers should treat absent as \"don't retry\".\n */\n readonly retryable?: boolean\n\n constructor(message: string, options: TypedErrorOptions) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined)\n this.name = 'AgentProviderError'\n this.provider = options.provider\n this.providerCode = options.providerCode\n this.retryable = options.retryable\n }\n}\n\n/**\n * Thrown when a run is aborted by the consumer via `agent.abort()` or an external `AbortSignal`.\n */\nexport class AgentAbortedError extends Error {\n readonly code = 'aborted' as const\n\n constructor(message = 'Agent run aborted', options?: { cause?: unknown }) {\n super(message, options?.cause !== undefined ? { cause: options.cause } : undefined)\n this.name = 'AgentAbortedError'\n }\n}\n\n/**\n * Thrown (well — constructed; attach via the `tool:gate` block signal) when the\n * union of `allowed-tools` across active skills does not permit a tool call.\n *\n * Produced by the allowed-tools middleware registered on `tool:gate` /\n * `mcp:tool:gate`. The gate's `block = true` + `reason` carry the same message\n * so consumers that don't look at this typed error still get a useful string.\n */\nexport class AgentToolNotAllowedError extends Error {\n readonly code = 'tool_not_allowed' as const\n /** Canonical tool name the agent tried to call. */\n readonly toolName: string\n /** Aliased / wire name the LLM saw. */\n readonly displayName: string\n /** Flattened union of `allowedTools` patterns across active skills. */\n readonly allowedUnion: readonly string[]\n /** Names of the skills currently active when the block fired. */\n readonly activeSkills: readonly string[]\n\n constructor(options: {\n toolName: string\n displayName: string\n allowedUnion: readonly string[]\n activeSkills: readonly string[]\n cause?: unknown\n }) {\n const msg = (\n `Tool \"${options.displayName}\" is not in the allowed-tools union of the active `\n + `skill(s) [${options.activeSkills.join(', ')}]. Union: [${options.allowedUnion.join(' ')}].`\n )\n super(msg, options.cause !== undefined ? { cause: options.cause } : undefined)\n this.name = 'AgentToolNotAllowedError'\n this.toolName = options.toolName\n this.displayName = options.displayName\n this.allowedUnion = options.allowedUnion\n this.activeSkills = options.activeSkills\n }\n}\n\n/**\n * Regex patterns matching common \"context window exceeded\" messages across providers.\n *\n * Use {@link matchesContextExceeded} to test a free-form error message against them.\n * Provider authors can also compose these into their own `classifyError` fallbacks.\n */\nexport const CONTEXT_EXCEEDED_MESSAGE_PATTERNS: readonly RegExp[] = [\n /context[_\\s]length[_\\s]exceeded/i,\n /maximum context length/i,\n /prompt is too long/i,\n /context window/i,\n]\n\n/**\n * Return true when `message` matches any of the known \"context window exceeded\"\n * phrasings. Safe for `''` / non-strings (returns false).\n */\nexport function matchesContextExceeded(message: unknown): boolean {\n if (typeof message !== 'string' || message.length === 0)\n return false\n return CONTEXT_EXCEEDED_MESSAGE_PATTERNS.some(re => re.test(message))\n}\n\n/**\n * Extract a printable message from an unknown thrown value.\n *\n * Standardizes the `err instanceof Error ? err.message : String(err)` idiom\n * that every `catch (err)` block was reaching for.\n */\nexport function errorMessage(err: unknown): string {\n if (err instanceof Error)\n return err.message\n return String(err)\n}\n\n/**\n * Convert a `ClassifiedError` + underlying cause into the matching typed error instance.\n */\nexport function toTypedError(\n classification: ClassifiedError,\n provider: string,\n cause: unknown,\n): AgentContextExceededError | AgentProviderError | AgentAbortedError {\n const message = classification.message ?? errorMessage(cause)\n\n if (classification.kind === 'context_exceeded') {\n return new AgentContextExceededError(message, {\n provider,\n providerCode: classification.providerCode,\n cause,\n })\n }\n\n if (classification.kind === 'aborted') {\n return new AgentAbortedError(message, { cause })\n }\n\n return new AgentProviderError(message, {\n provider,\n providerCode: classification.providerCode,\n retryable: classification.retryable,\n cause,\n })\n}\n"],"mappings":";;;;;AA6CA,IAAa,4BAAb,cAA+C,MAAM;CACnD,OAAgB;CAChB;CACA;CAEA,YAAY,SAAiB,SAA4B;EACvD,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,EAAE,OAAO,QAAQ,OAAO,GAAG,KAAA,EAAU;EAClF,KAAK,OAAO;EACZ,KAAK,WAAW,QAAQ;EACxB,KAAK,eAAe,QAAQ;;;;;;;AAQhC,IAAa,qBAAb,cAAwC,MAAM;CAC5C,OAAgB;CAChB;CACA;;;;;;CAMA;CAEA,YAAY,SAAiB,SAA4B;EACvD,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,EAAE,OAAO,QAAQ,OAAO,GAAG,KAAA,EAAU;EAClF,KAAK,OAAO;EACZ,KAAK,WAAW,QAAQ;EACxB,KA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AO,IAAI,mBAAmB,SAAS;EACrC;EACA,cAAc,eAAe;EAC7B,WAAW,eAAe;EAC1B;EACD,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-D-cTScN3.d.ts","names":[],"sources":["../src/compact/messages.ts","../src/compact/prompt.ts","../src/compact/errors.ts","../src/compact/compact.ts","../src/compact/restore.ts","../src/compact/utils.ts","../src/loop-persistence.ts","../src/mcp/oauth-provider.ts","../src/mcp/login.ts","../src/mcp/oauth-callback.ts","../src/stats.ts","../src/tools/edit.ts","../src/tools/glob.ts","../src/tools/grep.ts","../src/tools/interaction.ts","../src/tools/list-files.ts","../src/tools/multi-edit.ts","../src/tools/read-file.ts","../src/tools/shell.ts","../src/tools/skills-read.ts","../src/tools/skills-run-script.ts","../src/tools/skills-use.ts","../src/tools/spawn.ts","../src/tools/tool-search.ts","../src/tools/validation.ts","../src/tools/write-file.ts","../src/tracing.ts","../src/zod.ts","../src/presets/basic.ts","../src/presets/index.ts"],"mappings":";;;;;;;AAwBA;;;;;;;;AAAA,KAAY,YAAA;EAGJ,IAAA;EAAc,MAAA;AAAA;EACd,IAAA;EAAe,MAAA;AAAA;AAAA,UAEN,eAAA;EAIf;EAFA,WAAA,WAAsB,WAAA;EAES;EAA/B,SAAA,WAAoB,WAAA;AAAA;;;;;;;;;;;;;;;iBAiBN,kBAAA,CACd,KAAA,WAAgB,WAAA,IAChB,KAAA,EAAO,YAAA,EACP,SAAA,WACC,eAAA;AAuEH;;;;;;;;;AAmEA;;;;;;AAnEA,iBAAgB,oBAAA,CAAqB,KAAA,WAAgB,WAAA,KAAgB,WAAA;;;AAoLrE;;;;;AAOA;;;;;AAsBA;;;;;;;iBA9IgB,uBAAA,CAAwB,KAAA,WAAgB,WAAA,KAAgB,WAAA;;;;;AAiLxE;;cAhEa,wBAAA;;;;;;iBAOG,gBAAA,CAAiB,IAAA,EAAM,WAAA;;;;ACxSvC;;;;;AAEA;;UD4TiB,kBAAA;EC3TY;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UAIe,cAAA;E1BUf;;;;AAwEF;;E0B3EE,OAAA,GAAU,KAAA,EAAO,QAAA,CAAS,UAAA;AAAA;;;;;;A1B8I5B;;;;;;;;iB0B9HgB,kBAAA,CAAmB,OAAA,EAAS,mBAAA,GAAsB,cAAA;;;;;;;;;;;A1B3ClE;;;;;;;;;iB2BNgB,eAAA,CAAgB,UAAA,EAAY,MAAA,oBAA0B,MAAA;;;;;;;;;;;A3BMtE;c4BXa,UAAA;SAAuE,OAAA;;;;;;;cAAA,QAAA;;;;;;;;;A5BWpF;;;;;;;;;;AAMA;;;;;;;K6BHY,MAAA,GAAS,IAAA,CAAK,OAAA,CAAQ,YAAA;;;A7BwBlC;iB6BnBgB,YAAA,CAAa,MAAA,EAAQ,MAAA,GAAS,MAAA;;;;;;;;;;;;;;;A7B8F9C;;;;iB6BxEgB,cAAA,CAAA,GAAkB,OAAA,EAAS,MAAA,KAAW,MAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"messages-DsbMYNmt.js","names":[],"sources":["../src/providers/cost.ts","../src/providers/openai-compat.ts","../src/session/messages.ts"],"sourcesContent":["import type { TurnUsage } from '../types'\nimport { getModel } from '@mariozechner/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 `@mariozechner/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 * 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 { fillEstimatedCost } from './cost'\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 const out: OAIMessage[] = [{ role: 'system', content: system }]\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 */\nexport function applyOAICacheBreakpoints(messages: OAIMessage[]): void {\n if (messages.length === 0)\n return\n\n const first = messages[0]\n if (first.role === 'system')\n markLastContentPart(first)\n\n const lastIdx = messages.length - 1\n if (lastIdx > 0)\n markLastContentPart(messages[lastIdx])\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 return tools.map(t => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.inputSchema },\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 })),\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 applyOAICacheBreakpoints(messages)\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 { 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' }>\ntype ToolResultBlock = Extract<SessionContentBlock, { type: 'tool_result' }>\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// sanitizeOrphanedToolCalls\n// ---------------------------------------------------------------------------\n\n/**\n * Drop assistant `tool_call` blocks whose `id` has no matching\n * `tool_result.callId` in the immediately-following user message, and drop\n * user `tool_result` blocks whose `callId` has no match in the\n * immediately-preceding assistant message.\n *\n * Anthropic strictly requires every `tool_use` block to be paired with a\n * `tool_result` block in the next user message (`messages.N: 'tool_use' ids\n * were found without 'tool_result' blocks immediately after`). OpenAI is\n * looser but still rejects most mismatches. Orphans reach the wire layer from:\n *\n * 1. Interrupted runs (signal, crash, network drop) between persisting the\n * assistant turn (`turn:after`) and persisting its tool results turn\n * (`tool-results:after`).\n * 2. The schema-enforcement path — a synthetic `__output__` assistant\n * tool_call is appended without a matching tool_result. Any resume after\n * that turn would 400 without this pass.\n * 3. Consumer `context:transform` hooks that prune messages without\n * preserving the `tool_use ↔ tool_result` pairing.\n *\n * Strategy: drop the orphan blocks rather than synthesizing fake results —\n * the model never sees a half-done call, so it can't confabulate on phantom\n * outputs. Messages emptied by the cleanup are removed entirely (providers\n * reject empty `content` arrays).\n *\n * Adjacency rules:\n * - Assistant tool_calls are matched against the ORIGINAL next user message\n * (the wire still has to satisfy the per-message adjacency contract).\n * - User tool_results are matched against the previously-emitted message in\n * the cleaned output, so a tool_result whose entire assistant prefix was\n * dropped cascades and gets dropped too.\n *\n * Idempotent: returns the input reference when no orphans are found.\n */\nexport function sanitizeOrphanedToolCalls(messages: SessionMessage[]): SessionMessage[] {\n if (messages.length === 0)\n return messages\n\n const out: SessionMessage[] = []\n let changed = false\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i]\n\n if (msg.role === 'assistant') {\n const callIds = collectIds<ToolCallBlock>(msg.content, 'tool_call', b => b.id)\n if (callIds.size === 0) {\n out.push(msg)\n continue\n }\n const next = messages[i + 1]\n const matched = next && next.role === 'user'\n ? intersectIds<ToolResultBlock>(next.content, 'tool_result', b => b.callId, callIds)\n : new Set<string>()\n if (matched.size === callIds.size) {\n out.push(msg)\n continue\n }\n const cleaned = msg.content.filter(b => b.type !== 'tool_call' || matched.has(b.id))\n changed = true\n if (cleaned.length > 0)\n out.push({ ...msg, content: cleaned })\n continue\n }\n\n const hasResult = msg.content.some(b => b.type === 'tool_result')\n if (!hasResult) {\n out.push(msg)\n continue\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 const cleaned = msg.content.filter(b => b.type !== 'tool_result' || validIds.has(b.callId))\n if (cleaned.length === msg.content.length) {\n out.push(msg)\n continue\n }\n changed = true\n if (cleaned.length > 0)\n out.push({ ...msg, content: cleaned })\n }\n\n return changed ? out : messages\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\nfunction intersectIds<B extends SessionContentBlock>(\n content: SessionContentBlock[],\n type: B['type'],\n getId: (block: B) => string,\n candidates: Set<string>,\n): Set<string> {\n const matched = new Set<string>()\n for (const block of content) {\n if (block.type !== type)\n continue\n const id = getId(block as B)\n if (candidates.has(id))\n matched.add(id)\n }\n return matched\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":";;;;;;;;;;;;;;;;;;AAyBA,SAAgB,kBAAkB,OAAkB,UAA6B;CAC/E,IAAI,MAAM,SAAS,KAAA,GACjB,OAAO;CACT,IAAI,CAAC,MAAM,SACT,OAAO;CAMT,MAAM,SAAS;CACf,IAAI;CACJ,IAAI;EACF,QAAQ,OAA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,KAAa;CAC7B,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,SAAS,MACjB,IAAI,IAAI,MAAM,MAAW,CAAC;CAE9B,OAAO;;AAGT,SAAS,aACP,SACA,MACA,OACA,YACa;CACb,MAAM,0BAAU,IAAI,KAAa;CACjC,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,MAAM,SAAS,MACjB;EACF,MAAM,KAAK,MAAM,MAAW;EAC5B,IAAI,WAAW,IAAI,GAAG,EACpB,QAAQ,IAAI,GAAG;;CAEnB,OAAO;;AAGT,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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"presets-tvD28pCu.js","names":[],"sources":["../src/presets/basic.ts","../src/presets/index.ts"],"sourcesContent":["import { definePreset } from '.'\nimport { edit, listFiles, multiEdit, readFile, shell, 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, 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 * - `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 */\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 out.behavior = { ...out.behavior, ...p.behavior }\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 = h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