zidane 5.3.1 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +18 -1
  2. package/dist/{agent-bKs7MRT2.d.ts → agent-DHQAsdj6.d.ts} +174 -15
  3. package/dist/agent-DHQAsdj6.d.ts.map +1 -0
  4. package/dist/chat.d.ts +4 -4
  5. package/dist/chat.d.ts.map +1 -1
  6. package/dist/chat.js +1 -1
  7. package/dist/{index-CTmNaIDb.d.ts → index-CHSaLab5.d.ts} +2 -2
  8. package/dist/{index-CTmNaIDb.d.ts.map → index-CHSaLab5.d.ts.map} +1 -1
  9. package/dist/{index-BlMvPh9X.d.ts → index-CrqFoaQA.d.ts} +36 -11
  10. package/dist/index-CrqFoaQA.d.ts.map +1 -0
  11. package/dist/index.d.ts +4 -4
  12. package/dist/index.js +5 -5
  13. package/dist/{login-CNS9_8Ue.js → login-bK0EP8La.js} +3 -3
  14. package/dist/{login-CNS9_8Ue.js.map → login-bK0EP8La.js.map} +1 -1
  15. package/dist/{mcp-ZsSFo4Dp.js → mcp-DhmmJfxK.js} +15 -2
  16. package/dist/mcp-DhmmJfxK.js.map +1 -0
  17. package/dist/mcp.d.ts +1 -1
  18. package/dist/mcp.js +1 -1
  19. package/dist/{presets-h5i3kpOP.js → presets-M8f6lDnW.js} +2 -2
  20. package/dist/{presets-h5i3kpOP.js.map → presets-M8f6lDnW.js.map} +1 -1
  21. package/dist/presets.d.ts +2 -2
  22. package/dist/presets.js +1 -1
  23. package/dist/providers.d.ts +1 -1
  24. package/dist/session/sqlite.d.ts +1 -1
  25. package/dist/session.d.ts +1 -1
  26. package/dist/skills.d.ts +2 -2
  27. package/dist/{tools-CWEDS2ZT.js → tools-DKdyPoUf.js} +425 -165
  28. package/dist/tools-DKdyPoUf.js.map +1 -0
  29. package/dist/tools.d.ts +3 -3
  30. package/dist/tools.js +2 -2
  31. package/dist/{transcript-anchors-DOUqyvXR.d.ts → transcript-anchors-Fgh_rZ04.d.ts} +3 -3
  32. package/dist/{transcript-anchors-DOUqyvXR.d.ts.map → transcript-anchors-Fgh_rZ04.d.ts.map} +1 -1
  33. package/dist/tui.d.ts +2 -2
  34. package/dist/tui.js +4 -4
  35. package/dist/tui.js.map +1 -1
  36. package/dist/{turn-operations-D9HvatsR.js → turn-operations-DDokWR8p.js} +5 -4
  37. package/dist/turn-operations-DDokWR8p.js.map +1 -0
  38. package/dist/types-IcokUOyC.js.map +1 -1
  39. package/dist/types.d.ts +3 -3
  40. package/docs/ARCHITECTURE.md +18 -7
  41. package/docs/SKILL.md +56 -3
  42. package/package.json +1 -1
  43. package/dist/agent-bKs7MRT2.d.ts.map +0 -1
  44. package/dist/index-BlMvPh9X.d.ts.map +0 -1
  45. package/dist/mcp-ZsSFo4Dp.js.map +0 -1
  46. package/dist/tools-CWEDS2ZT.js.map +0 -1
  47. package/dist/turn-operations-D9HvatsR.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: { 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"}
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 interface AgentBehavior {\n /**\n * Maximum number of tools that may be in flight concurrently within a\n * single assistant turn. The scheduler dispatches concurrency-safe tools\n * (`ToolDef.isConcurrencySafe`) in parallel up to this cap; unsafe tools\n * act as barriers (wait for the fleet to drain, then run alone).\n *\n * Default: `10`. Set to `1` to force fully sequential dispatch regardless\n * of per-tool flags — useful for deterministic debugging / eval-grade\n * runs. Values `< 1` are clamped to `1`.\n */\n maxConcurrentTools?: number\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 * Concurrency-safe siblings ({@link ToolDef.isConcurrencySafe}) in the\n * SAME assistant turn race against each other — none can dedup against\n * a sibling that started in the same batch. Unsafe tools act as barriers\n * and honor submission order within a turn, so an unsafe-but-listed tool\n * follows the cache cleanly.\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 * The run this tool call belongs to (the `SessionRun.id`). Lets a single\n * `tool:*` listener disambiguate calls across parallel runs / subagent\n * trees without subscribing to the `child:tool:*` bubble events.\n */\n runId?: string\n /**\n * Parent run id when this tool call's agent is a subagent — i.e. the\n * `SessionRun.parentRunId` of the run that owns the call. Absent on\n * top-level runs. Useful for observability stitching: a UI grouping\n * subagent-scoped state (e.g. todowrite, edit batches) by parent\n * run can read this directly off `tool:before` / `tool:after`\n * without resolving the run row.\n */\n parentRunId?: string\n /**\n * Subagent depth for this tool call. 0 = top-level, 1 = first-level\n * child, etc. Mirrors `ToolContext.depth` so hook consumers don't\n * have to cross-reference the tool context. Omitted on top-level\n * runs (treated as 0).\n */\n depth?: number\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 /** Owning run id — same semantics as `ToolHookContext.runId`. */\n runId?: string\n /** Parent run id when this tool call's agent is a subagent — see `ToolHookContext.parentRunId`. */\n parentRunId?: string\n /** Subagent depth — see `ToolHookContext.depth`. */\n depth?: number\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":";;;;;;;;;AAipBA,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 { $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
- 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 };
3
+ import { $t as ThinkingLevel, Bt as OAuthRefreshHookContext, D as SkillConfig, Dt as OpenAIParams, F as SessionRun, Ft as AgentStats, Gt as RunHookMap, Ht as PromptImagePart, I as SessionStore, It as ChildRunStats, Jt as SessionHookContext, Kt as SessionContentBlock, Lt as McpServerConfig, M as CreateSessionOptions, N as Session, Nt as AgentBehavior, P as SessionData, Pt as AgentRunOptions, Qt as StreamHookContext, Rt as McpToolHookContext, S as ReadStateMap, Ut as PromptPart, Vt as PromptDocumentPart, Wt as PromptTextPart, Xt as SessionTurn, Yt as SessionMessage, Zt as SpawnHookContext, _n as matchesContextExceeded, an as TurnUsage, b as ToolMap, cn as AgentAbortedError, ct as StreamCallbacks, dn as AgentToolNotAllowedError, dt as ToolResult, en as ToolHookContext, ft as ToolSpec, hn as ClassifiedErrorKind, i as AgentOptions, in as TurnFinishReason, j as SkillsConfig, jt as AnthropicParams, k as SkillResource, kt as CerebrasParams, ln as AgentContextExceededError, lt as StreamOptions, mn as ClassifiedError, nn as ToolResultImageContent, on as toolOutputByteLength, ot as Provider, p as McpConnection, pn as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, pt as TurnResult, qt as SessionEndStatus, r as AgentHooks, rn as ToolResultTextContent, sn as toolResultToText, st as ProviderCapabilities, t as Agent, tn as ToolResultContent, un as AgentProviderError, ut as ToolCall, v as ToolContext, x as ReadStateEntry, y as ToolDef, yt as OpenRouterParams, z as RemoteStoreOptions } from "./agent-DHQAsdj6.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-CrqFoaQA.js";
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 ReadStateEntry, type ReadStateMap, 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 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 };
@@ -106,9 +106,7 @@ flowchart TB
106
106
 
107
107
  subgraph TOOLS ["Tool Execution"]
108
108
  direction TB
109
- TE1["Push assistant turn\n(with tool calls)"] --> TE2{Parallel\nmode?}
110
- TE2 -->|sequential| SEQ["For each tool:\n1. Check abort + steering queue\n (on hit: synthesize Aborted/Skipped\n tool_results for remaining calls)\n2. executeSingleTool()"]
111
- TE2 -->|parallel| PAR["Promise.allSettled(\nexecuteSingleTool)"]
109
+ TE1["Push assistant turn\n(with tool calls)"] --> TE2["executeToolBatch:\nWalk calls in submission order.\nSafe tools fan out as a fleet\n(cap = maxConcurrentTools);\nunsafe tools barrier (drain → run alone → unblock).\nAbort/steer between dispatches → synthesize\nInterrupt/Skipped results for unstarted calls.\nshell error cascades a sibling abort."]
112
110
  SEQ --> TE3["Push tool results turn\n+ fire tool-results:after"]
113
111
  PAR --> TE3
114
112
  end
@@ -160,12 +158,25 @@ flowchart TB
160
158
 
161
159
  **`tool:gate` mutations.** Set `block` to refuse (`Blocked: reason`), `result` to substitute and skip execute, or neither to run normally. `block` wins over `result` so a policy gate always beats a consumer cache. The substitute path skips `tool:before` + validate + execute but fires `tool:transform` + `tool:after` — budgets and telemetry stay consistent with executed calls.
162
160
 
163
- **`runToolCounts`** is a frozen pre-call snapshot, scoped to `runId`. Includes dedup + gate-`result` substitutes; excludes blocked calls. Resumed sessions reset the counter. In parallel mode, consumer hooks see the pre-batch snapshot — built-in budget/dedup middleware uses its own gate-time reservation counter so `behavior.toolBudgets` stays atomic mid-batch.
161
+ **`runToolCounts`** is a frozen pre-call snapshot, scoped to `runId`. Includes dedup + gate-`result` substitutes; excludes blocked calls. Resumed sessions reset the counter. Concurrent fleets see the same pre-batch snapshot — built-in budget/dedup middleware uses its own gate-time reservation counter so `behavior.toolBudgets` stays atomic across the fleet.
164
162
 
165
163
  **Output shape.** `string | ToolResultContent[]`. Text tools return strings; multimodal tools (MCP browsers, screenshots) return `[{ type: 'text' }, { type: 'image', mediaType, data }]`. Providers with `capabilities.imageInToolResult: true` (Anthropic, OpenAI Codex) route arrays natively; OpenAI-compat emits a companion `user` message with `image_url` parts. Non-vision providers swap image blocks for a text marker before the hook fires.
166
164
 
167
165
  **`outputBytes`** populates `tool:after`, `tool:transform`, `mcp:tool:after`, `mcp:tool:transform` — UTF-8 byte length for text, base64 char length for images. This is a **wire-payload-size proxy**, not a token count (vision encoders tokenize decoded pixels, geometry-dependent). Use it for byte-budget heuristics; defer to provider-side context management for token-accurate accounting. Reproduce via `toolOutputByteLength(content)`.
168
166
 
167
+ ### Concurrency scheduler
168
+
169
+ `executeToolBatch` (`src/loop.ts`) walks the assistant turn's tool calls in submission order and decides per-call whether to fan out:
170
+
171
+ - **Per-tool flag.** Every `ToolDef.isConcurrencySafe` (`boolean | ((input) => boolean)`) declares the safety verdict. Default `false` — fail-closed. Resolved once per call before dispatch begins.
172
+ - **Fleet vs. barrier.** Safe calls join a running concurrent fleet up to `behavior.maxConcurrentTools` (default `10`). Unsafe calls (and any call when the fleet already contains an unsafe sibling or is at the cap) **barrier**: drain the in-flight fleet, run alone, then unblock the queue.
173
+ - **Order preserved at yield time.** Results are written to `results[i]` slots in submission order; concurrent completion order is invisible to the model.
174
+ - **Sibling abort controller.** One `AbortController` per batch carries both the parent abort (forwarded so a user-issued abort still tears in-flight tools down) and the `shell`-cascade signal. Cancelled siblings get a `Cancelled: a sibling \`shell\` call …` tool_result; non-shell errors are isolated.
175
+ - **Abort + steer between dispatches.** Re-checked after each in-iteration drain so a tool that aborts mid-batch doesn't dispatch one extra call. Unstarted slots are filled with `INTERRUPT_MESSAGE_FOR_TOOL_USE` / `TOOL_USE_SKIPPED_MESSAGE` (both `isError: true`) so the assistant turn's `tool_use` ids never go orphan.
176
+ - **`shell` is conditional.** `shell.isConcurrencySafe(input)` parses the command via `isReadOnlyShellCommand` — strict allow-list of read-only command bases (`ls`, `cat`, `git status`, `rg`, …) plus a `git` subcommand allow-list. Rejects pipes, redirects, command chains, and subshell expansions.
177
+
178
+ Forcing fully sequential dispatch (for deterministic debugging / eval-grade runs) is one knob: `behavior.maxConcurrentTools: 1`. Every call then barriers regardless of its `isConcurrencySafe` flag.
179
+
169
180
  ## Tool ergonomics defaults
170
181
 
171
182
  Built-in tools are opinionated about output sizes — drop your v2 `tool:transform` truncation polyfills.
@@ -447,7 +458,7 @@ output ← when behavior.schema set
447
458
  budget:exceeded / tool-budget:exceeded ← byte / per-tool caps tripped
448
459
  ```
449
460
 
450
- **`tool-results:after`** is the durable-persistence seam. The assistant turn carrying `tool_use` blocks and the user turn carrying matching `tool_result` blocks must be persisted as a pair — otherwise a process death between turns leaves an orphan `tool_use` that Anthropic rejects on resume. Subscribe here to write the pair atomically. The loop also synthesizes `Aborted: …` / `Skipped: …` tool_results for any remaining calls when abort / steering interrupts a sequential batch (`synthesizeMissingToolResults` in `src/agent.ts`), so the assistant turn's `tool_use` ids always stay matched.
461
+ **`tool-results:after`** is the durable-persistence seam. The assistant turn carrying `tool_use` blocks and the user turn carrying matching `tool_result` blocks must be persisted as a pair — otherwise a process death between turns leaves an orphan `tool_use` that Anthropic rejects on resume. Subscribe here to write the pair atomically. The scheduler also synthesizes `Interrupt: …` / `Skipped: …` tool_results for any unstarted calls when abort / steering interrupts a batch (and `synthesizeMissingToolResults` in `src/agent.ts` covers the `turn:after` throw path), so the assistant turn's `tool_use` ids always stay matched.
451
462
 
452
463
  `tool:unknown` replaces `tool:before` when no `toolDef` exists; `validation:reject` fires after coercion attempts fail. The model receives a result string in both cases (substituted or `Validation error: …`) so it can recover.
453
464
 
@@ -590,7 +601,7 @@ Merge rules:
590
601
 
591
602
  `run.behavior` > `agent.behavior` > defaults (field-by-field merge).
592
603
 
593
- Defaults: unlimited turns (set `maxTurns` as a safety net), `maxTokens: 16384`, level-based thinking; `cache: true`, `dedupReads: true`, `requireReadBeforeEdit: false`, `compactStrategy: 'off'`, `compactThreshold: 128 KiB`, `compactKeepTurns: 4`, `toolDisclosure: 'eager'`, `readLineNumbers: true`, `elideStaleReads: false`. All other knobs (`toolOutputBudget`, `dedupTools`, `toolBudgets`, `thinkingDecay`, `toolSearch`, `persistThreshold`, `persistDir`, `persistExcludeTools`) are `undefined`. The chat-layer profiles (`BUILD_AGENT` / `PLAN_AGENT`) override several of these — see CHAT.md → Agents.
604
+ Defaults: unlimited turns (set `maxTurns` as a safety net), `maxTokens: 16384`, level-based thinking; `cache: true`, `dedupReads: true`, `requireReadBeforeEdit: false`, `maxConcurrentTools: 10`, `compactStrategy: 'off'`, `compactThreshold: 128 KiB`, `compactKeepTurns: 4`, `toolDisclosure: 'eager'`, `readLineNumbers: true`, `elideStaleReads: false`. All other knobs (`toolOutputBudget`, `dedupTools`, `toolBudgets`, `thinkingDecay`, `toolSearch`, `persistThreshold`, `persistDir`, `persistExcludeTools`) are `undefined`. The chat-layer profiles (`BUILD_AGENT` / `PLAN_AGENT`) override several of these — see CHAT.md → Agents.
594
605
 
595
606
  **`toolOutputBudget`** (off by default). The loop sums every tool result's `outputBytes` after `tool:transform`, so consumer truncation counts. On overshoot, a synthetic user message is appended:
596
607
 
@@ -600,7 +611,7 @@ Defaults: unlimited turns (set `maxTurns` as a safety net), `maxTokens: 16384`,
600
611
 
601
612
  **`compactStrategy: 'tail'`** — client-side companion for non-Anthropic providers. After `sanitizeStoredToolResults` and before `context:transform`, the loop sums tool-result bytes; on overshoot, `tool_result` blocks older than `compactKeepTurns` are replaced with a stub. Text and image blocks pass through; `session.turns` is untouched. Anthropic users should prefer the server-side `context-management-2025-06-27` beta (token-accurate) via `anthropic({ extraBetas, contextManagement })`.
602
613
 
603
- **`dedupReads` + `requireReadBeforeEdit`** share a per-session `WeakMap<Session, Map<path, { contentHash, offset, limit, maxBytes, mtimeMs }>>` (keyed `${handle.cwd}::${path}`). `read_file` returns a stub on identical (hash + slice) re-reads. `edit` / `multi_edit` reject when no entry exists or the on-disk hash drifted. Edits update the hash on success so chained edits don't need re-reads. GC'd with the session.
614
+ **`dedupReads` + `requireReadBeforeEdit`** share the same per-session `WeakMap<Session, Map<canonicalAbsPath, { contentHash, offset, limit, maxBytes, mtimeMs }>>`. The key is the canonical absolute path (via `node:path.resolve(handle.cwd, modelProvidedPath)`) so all path shapes the model can write — `src/x`, `./src/x`, `/abs/cwd/src/x` converge on one entry. Map population happens whenever **either** feature is enabled; the dedup *short-circuit* (returning the "unchanged since the previous read" stub) is what `dedupReads` actually gates. This decoupling means `dedupReads: false` no longer breaks the `requireReadBeforeEdit` guard. `edit` / `multi_edit` reject when no entry exists or the on-disk hash drifted; both update the hash on success so chained edits don't need re-reads. Optional `AgentOptions.readState` (also exposed on `ToolContext.readState`) forwards an explicit map — used by `createSpawnTool({ shareReadState: true })` so a sessionless child still feeds the parent's tracking without sharing turn persistence. GC'd with the session when no explicit map is in play.
604
615
 
605
616
  **`dedupTools`** generalizes the same pattern via a consumer hasher per tool. Parallel `WeakMap<Session, Map<toolName, { hash, result }>>` keeps only the most recent hash. On hit, the prior result replays verbatim — substitute path fires `tool:transform` + `tool:after` so budgets stay coherent. Tools with side effects or non-deterministic outputs MUST NOT be listed.
606
617
 
package/docs/SKILL.md CHANGED
@@ -25,7 +25,7 @@ const agent = createAgent({
25
25
  ...basic,
26
26
  provider: anthropic({ apiKey: '...' }),
27
27
  behavior: {
28
- toolExecution: 'sequential', // 'sequential' | 'parallel' (default: parallel)
28
+ maxConcurrentTools: 10, // cap on in-flight tools per turn (default: 10; set 1 for fully sequential)
29
29
  maxTurns: 50,
30
30
  maxTokens: 16384,
31
31
  thinkingBudget: 10240,
@@ -235,13 +235,42 @@ interface ToolDef {
235
235
  input: Record<string, unknown>,
236
236
  ctx: ToolContext,
237
237
  ) => Promise<string | ToolResultContent[]>
238
+ /** Default `false`. See "Per-tool concurrency" below. */
239
+ isConcurrencySafe?: boolean | ((input: Record<string, unknown>) => boolean)
238
240
  }
239
241
  ```
240
242
 
241
- `ToolContext` exposes `provider`, `signal`, `execution`, `handle`, `hooks`, `turnId`, `callId`, `runId?`, `session?`, `depth?`, plus preset fields (`name`, `system`, `tools`, `toolAliases`, `mcpServers`, `skills`, `behavior`) so `spawn` can inherit.
243
+ `ToolContext` exposes `provider`, `signal`, `execution`, `handle`, `hooks`, `turnId`, `callId`, `runId?`, `parentRunId?`, `session?`, `readState?`, `depth?`, plus preset fields (`name`, `system`, `tools`, `toolAliases`, `mcpServers`, `skills`, `behavior`) so `spawn` can inherit.
242
244
 
243
245
  Returns `string` (common) or `ToolResultContent[]` (images / mixed content). Routed natively via `tool_result.content` when supported, or via companion user message on plain Chat Completions. Flatten via `toolResultToText(result)`.
244
246
 
247
+ ### Per-tool concurrency
248
+
249
+ The unified dispatcher walks tool calls in submission order and decides per-call whether to fan out:
250
+
251
+ - **Safe siblings fan out** — concurrent-safe tools form a fleet that runs in parallel up to `behavior.maxConcurrentTools` (default `10`).
252
+ - **Unsafe tools act as barriers** — the dispatcher drains the in-flight fleet, runs the unsafe call alone, then unblocks the queue. Subsequent safe calls re-form a new fleet behind it.
253
+ - **Results yield in submission order** regardless of completion order — the model sees a deterministic transcript.
254
+
255
+ Built-in annotations (mirrors the convention that reads parallelize, writes serialize):
256
+
257
+ | Concurrency-safe | Barrier (default) |
258
+ |---|---|
259
+ | `readFile`, `glob`, `grep`, `listFiles`, `tool_search`, `todoread`, `spawn`, `skills_read` | `edit`, `multiEdit`, `writeFile`, `todowrite`, `interaction`, custom tools, MCP tools |
260
+ | `shell` (conditional — see below) | |
261
+
262
+ `shell.isConcurrencySafe` parses `input.command`: `ls`, `cat`, `pwd`, `git status`, `rg`, `echo`, etc. fan out (full allow-list in `tools/shell.ts → SHELL_READ_ONLY_COMMANDS` + `GIT_READ_ONLY_SUBCOMMANDS`). Anything mutating, any redirect (`>`, `>>`, `|`), any command chain (`&&`, `||`, `;`), and any subshell (`$(…)`, `` `…` ``) barriers.
263
+
264
+ **Cascade-cancel**. A `shell` error inside a concurrent fleet cancels its in-flight siblings via the per-batch `siblingAbort` controller. Other tool errors are isolated (one read's failure doesn't kill another read). Cancelled siblings get a `Cancelled: a sibling \`shell\` call …` tool_result so the model can decide whether to retry independently.
265
+
266
+ **Authoring custom tools**. Default is fail-closed (`false`) — any custom tool you author serializes unless you opt in. Opt in via `isConcurrencySafe: true` when:
267
+
268
+ - The tool only reads from disk / network / catalog.
269
+ - The tool doesn't mutate any shared state (session metadata, files, in-memory caches your other tools read).
270
+ - Parallel invocations against different inputs produce the same outputs as sequential invocations.
271
+
272
+ Use `isConcurrencySafe: (input) => …` when safety depends on the call's arguments (the `shell` pattern).
273
+
245
274
  ### Tool argument validation (auto-coerce)
246
275
 
247
276
  `validateToolArgs(input, schema)` runs between `tool:gate` and `tool:before`. Missing/null required fields fail. Top-level coercions normalize the common OSS-model mistakes (`"true"`/`"yes"`/`"1"` → `true`, numeric strings → numbers, JSON strings → arrays/objects). `execute` always receives the **coerced** input. `validation:reject` fires only when no type reconciles — distinct from `tool:error`.
@@ -319,6 +348,16 @@ Mutable ctx fields: `tool:gate` (`block`, `reason`, `result`), `tool:transform`
319
348
 
320
349
  `outputBytes` is the wire size — **pre-mutation** on `*:transform` (truncation handlers decide), **post-mutation** on `*:after` (what the model sees). Reproduce via `toolOutputByteLength(content)`. `ctx.coercions` is **omitted** on `tool:before` / `tool:after` / `tool:transform` when no coercion happened; guard with `if (ctx.coercions)`.
321
350
 
351
+ ### Identity fields on tool hook contexts
352
+
353
+ Every `tool:*` and `mcp:tool:*` hook ctx additionally carries three optional identity fields (omitted from the per-row "key ctx fields" column above to keep the table readable):
354
+
355
+ - `runId?: string` — the `SessionRun.id` this call belongs to. Lets one listener disambiguate calls across parallel runs / subagent trees without subscribing to `child:tool:*`.
356
+ - `parentRunId?: string` — set when the call's agent is a subagent (mirrors `SessionRun.parentRunId`); absent on top-level runs. Drives UI grouping for subagent-scoped state (todowrite batches, edit groups, etc.) without resolving the run row.
357
+ - `depth?: number` — subagent depth, 0 = top-level. Mirrors `ToolContext.depth`.
358
+
359
+ Same three fields land on `ToolContext` (visible to the tool body via `ctx.runId` / `ctx.parentRunId` / `ctx.depth`). The loop centralizes their construction in `buildToolHookBase`, so a new tool-related hook event automatically inherits them.
360
+
322
361
  ### Child (sub-agent) bubble events
323
362
 
324
363
  `spawn`'s stream/tool/turn events bubble to the parent with `childId` + `depth`:
@@ -425,6 +464,17 @@ definePreset({
425
464
  })
426
465
  ```
427
466
 
467
+ ### Parent/child boundaries — `persist` and `shareReadState`
468
+
469
+ Two **independent** flags control what crosses the parent/child boundary:
470
+
471
+ | Flag | Default | What it shares |
472
+ |---|---|---|
473
+ | `persist` | `false` | The parent's `Session`. Child turns get appended to the same `session.turns` stream with the child's `runId`; the child's `SessionRun` carries `parentRunId` so the tree is reconstructible. As a side-effect the read-state map (Session-keyed) is also shared. |
474
+ | `shareReadState` | `false` | Only the read-state map. The child gets `AgentOptions.readState` populated with the parent's resolved map but **no session** — `read_file` populations land in the parent's tracking, but child turns stay in-memory. |
475
+
476
+ Use `shareReadState: true` (without `persist`) when you want the parent's `requireReadBeforeEdit` gate to honor reads the child performed, without polluting the parent's session with child turns. The gate's error message now hints at this when the entry is missing — re-read in the calling context OR opt into one of the sharing flags.
477
+
428
478
  ## Interaction Tool
429
479
 
430
480
  Lets the agent request structured input. Not in any preset by default. `onRequest` can be async — the agent waits.
@@ -663,7 +713,10 @@ createSandboxContext(myProvider) // implement SandboxProvider (E2B, Rivet, …)
663
713
  | `InteractionToolOptions` | `createInteractionTool` config (`schema, onRequest`). |
664
714
  | `PromptPart` | `{ type: 'text' \| 'image' \| 'document', ... }`. |
665
715
  | `RunHookMap` | `run({ hooks })` shape. |
666
- | `ToolHookContext` / `McpToolHookContext` / `SessionHookContext` / `StreamHookContext` / `SpawnHookContext` | Hook ctx base types. |
716
+ | `AgentBehavior.maxConcurrentTools` | Cap on in-flight tools per turn (default `10`, clamped at `1`). See "Per-tool concurrency" above. |
717
+ | `ToolDef.isConcurrencySafe` | `boolean \| ((input) => boolean)`. Defaults to `false`. See "Per-tool concurrency" above. |
718
+ | `ToolHookContext` / `McpToolHookContext` / `SessionHookContext` / `StreamHookContext` / `SpawnHookContext` | Hook ctx base types. `ToolHookContext` / `McpToolHookContext` carry `runId? / parentRunId? / depth?` identity fields on every `tool:*` / `mcp:tool:*` event — see Identity fields above. |
719
+ | `ReadStateMap` / `ReadStateEntry` | Per-file read-tracking map (`Map<canonicalAbsPath, { contentHash, offset, limit, maxBytes, lineNumbers?, mtimeMs }>`). Construct one manually for `AgentOptions.readState` to share across an agent tree; or get the session-bound one via `getReadState(session)` / the lookup-aware `resolveReadStateMap(ctx)`. Canonical keys come from `readStateKey(cwd, path)`. |
667
720
  | `ClassifiedError` | `{ kind, providerCode?, message? }` from `Provider.classifyError`. |
668
721
  | `AgentContextExceededError` / `AgentProviderError` / `AgentAbortedError` / `AgentToolNotAllowedError` | Typed errors. `toTypedError(err)` wraps native errors. |
669
722
  | `FileMapAdapter` | `{ get, save, delete }` — host-SDK seam for `createFileMapStore`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zidane",
3
- "version": "5.3.1",
3
+ "version": "5.4.0",
4
4
  "description": "an agent that goes straight to the goal",
5
5
  "type": "module",
6
6
  "private": false,
@@ -1 +0,0 @@
1
- {"version":3,"file":"agent-bKs7MRT2.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/schema-sanitize.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;;;AAoBzD;;;;;;;;;;;;cAAa,qBAAA,SAA8B,KAAA;EAAA,SAChC,IAAA;EAYP;EAAA,SAVO,QAAA;EAYP;EAAA,SAVO,YAAA;EAcP;;;;;;EAAA,SAPO,OAAA,EAAS,aAAA;IAChB,IAAA;IACA,MAAA;IACA,YA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8CS;;;;ACt0BlE;;;;;;;;EYqyBE,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;EZ7wB0C;;;;;EYmxB7D,KAAA,QAAa,OAAA;EX5wBkB;;;;EWixB/B,OAAA,QAAe,OAAA;EX/wBqB;;;;;;EWsxBpC,aAAA,GAAgB,IAAA,aAAiB,OAAA;EX/wBzB;AAGV;;;EWixBE,eAAA,GAAkB,IAAA,aAAiB,OAAA;EX/wBnC;;;;;AA4TF;;;;;EW8dE,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;EXzba;EAAA,SW2btB,YAAA,WAAuB,WAAA;EX1bhB;;;;;;EAAA,SWicP,IAAA,EAAM,QAAA,CAAS,MAAA;AAAA;AAAA,iBA4QV,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":"index-BlMvPh9X.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.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;ED6T3B,OAAA;EC7TW;ED+TX,eAAA;ECxTa;ED0Tb,KAAA;EClTU;EDoTV,KAAA,EAAO,SAAA;;EAEP,WAAA;AAAA;ACzSF;;;;;AAYA;;;;;AA4BA;;;;;AAmCA;;;;;AAIA;;AA/EA,iBDkUgB,aAAA,CAAc,KAAA,EAAO,kBAAA,GAAqB,WAAA;;;;;;;;;;;AA1V1D;;;;;;;;KCPY,gBAAA;AAAA,UAEK,oBAAA;EACf,SAAA,EAAW,gBA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