zidane 4.0.2 → 4.1.4

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 (77) hide show
  1. package/README.md +196 -614
  2. package/dist/agent-BoV5Twdl.d.ts +2347 -0
  3. package/dist/agent-BoV5Twdl.d.ts.map +1 -0
  4. package/dist/contexts-3Arvn7yR.js +321 -0
  5. package/dist/contexts-3Arvn7yR.js.map +1 -0
  6. package/dist/contexts.d.ts +2 -25
  7. package/dist/contexts.js +2 -10
  8. package/dist/errors-D1lhd6mX.js +118 -0
  9. package/dist/errors-D1lhd6mX.js.map +1 -0
  10. package/dist/index-28otmfLX.d.ts +400 -0
  11. package/dist/index-28otmfLX.d.ts.map +1 -0
  12. package/dist/index-BfSdALzk.d.ts +113 -0
  13. package/dist/index-BfSdALzk.d.ts.map +1 -0
  14. package/dist/index-DPsd0qwm.d.ts +254 -0
  15. package/dist/index-DPsd0qwm.d.ts.map +1 -0
  16. package/dist/index.d.ts +5 -95
  17. package/dist/index.js +141 -271
  18. package/dist/index.js.map +1 -0
  19. package/dist/interpolate-CukJwP2G.js +887 -0
  20. package/dist/interpolate-CukJwP2G.js.map +1 -0
  21. package/dist/mcp-8wClKY-3.js +771 -0
  22. package/dist/mcp-8wClKY-3.js.map +1 -0
  23. package/dist/mcp.d.ts +2 -4
  24. package/dist/mcp.js +2 -13
  25. package/dist/messages-z5Pq20p7.js +1020 -0
  26. package/dist/messages-z5Pq20p7.js.map +1 -0
  27. package/dist/presets-Cs7_CsMk.js +39 -0
  28. package/dist/presets-Cs7_CsMk.js.map +1 -0
  29. package/dist/presets.d.ts +2 -43
  30. package/dist/presets.js +2 -17
  31. package/dist/providers-CX-R-Oy-.js +969 -0
  32. package/dist/providers-CX-R-Oy-.js.map +1 -0
  33. package/dist/providers.d.ts +2 -4
  34. package/dist/providers.js +3 -23
  35. package/dist/session/sqlite.d.ts +7 -12
  36. package/dist/session/sqlite.d.ts.map +1 -0
  37. package/dist/session/sqlite.js +67 -79
  38. package/dist/session/sqlite.js.map +1 -0
  39. package/dist/session-Cn68UASv.js +440 -0
  40. package/dist/session-Cn68UASv.js.map +1 -0
  41. package/dist/session.d.ts +2 -4
  42. package/dist/session.js +3 -27
  43. package/dist/skills.d.ts +3 -322
  44. package/dist/skills.js +24 -47
  45. package/dist/skills.js.map +1 -0
  46. package/dist/stats-DoKUtF5T.js +58 -0
  47. package/dist/stats-DoKUtF5T.js.map +1 -0
  48. package/dist/tools-DpeWKzP1.js +3941 -0
  49. package/dist/tools-DpeWKzP1.js.map +1 -0
  50. package/dist/tools.d.ts +3 -95
  51. package/dist/tools.js +2 -40
  52. package/dist/tui.d.ts +533 -0
  53. package/dist/tui.d.ts.map +1 -0
  54. package/dist/tui.js +2004 -0
  55. package/dist/tui.js.map +1 -0
  56. package/dist/types-Bx_F8jet.js +39 -0
  57. package/dist/types-Bx_F8jet.js.map +1 -0
  58. package/dist/types.d.ts +4 -55
  59. package/dist/types.js +4 -28
  60. package/package.json +38 -4
  61. package/dist/agent-BAHrGtqu.d.ts +0 -2425
  62. package/dist/chunk-4ILGBQ23.js +0 -803
  63. package/dist/chunk-4LPBN547.js +0 -3540
  64. package/dist/chunk-64LLNY7F.js +0 -28
  65. package/dist/chunk-6STZTA4N.js +0 -830
  66. package/dist/chunk-7GQ7P6DM.js +0 -566
  67. package/dist/chunk-IC7FT4OD.js +0 -37
  68. package/dist/chunk-JCOB6IYO.js +0 -22
  69. package/dist/chunk-JH6IAAFA.js +0 -28
  70. package/dist/chunk-LNN5UTS2.js +0 -97
  71. package/dist/chunk-PMCQOMV4.js +0 -490
  72. package/dist/chunk-UD25QF3H.js +0 -304
  73. package/dist/chunk-W57VY6DJ.js +0 -834
  74. package/dist/sandbox-D7v6Wy62.d.ts +0 -28
  75. package/dist/skills-use-DwZrNmcw.d.ts +0 -80
  76. package/dist/types-Bai5rKpa.d.ts +0 -89
  77. package/dist/validation-Pm--dQEU.d.ts +0 -185
@@ -0,0 +1,2347 @@
1
+ import { c as ExecutionContext, l as ExecutionHandle } from "./index-BfSdALzk.js";
2
+ import { Hookable } from "hookable";
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ //#region src/errors.d.ts
5
+ /**
6
+ * Typed error classes for agent runs.
7
+ *
8
+ * Providers classify native errors into one of these so downstream consumers
9
+ * can react without string-sniffing messages.
10
+ *
11
+ * Provider authors: implement `Provider.classifyError` to map native errors
12
+ * (SDK exceptions, HTTP responses) to a `ClassifiedError`. The loop wraps
13
+ * unclassified errors in `AgentProviderError` automatically.
14
+ */
15
+ /** Kind of classified provider error */
16
+ type ClassifiedErrorKind = 'context_exceeded' | 'provider_error' | 'aborted';
17
+ /** Structured classification returned by `Provider.classifyError` */
18
+ interface ClassifiedError {
19
+ kind: ClassifiedErrorKind;
20
+ /** Upstream error code as surfaced by the provider (e.g. `context_length_exceeded`). Optional. */
21
+ providerCode?: string;
22
+ /** Optional human-readable message override. Falls back to the underlying error's message. */
23
+ message?: string;
24
+ /**
25
+ * Hint that the error is transient and a retry with backoff is reasonable
26
+ * (e.g. 429, 5xx, truncated stream). Omitted when the provider can't decide;
27
+ * callers should default to "do not retry" when absent to avoid hammering
28
+ * terminal failures (auth, invalid request).
29
+ */
30
+ retryable?: boolean;
31
+ }
32
+ interface TypedErrorOptions {
33
+ /** Provider name, always set (e.g. `anthropic`, `openrouter`) */
34
+ provider: string;
35
+ /** Optional upstream error code */
36
+ providerCode?: string;
37
+ /** Original error from the provider SDK/HTTP layer */
38
+ cause?: unknown;
39
+ /** See {@link ClassifiedError.retryable}. */
40
+ retryable?: boolean;
41
+ }
42
+ /**
43
+ * Thrown when the model or provider signals that the context window was exceeded.
44
+ * Downstream consumers should catch this, prune history, and retry.
45
+ */
46
+ declare class AgentContextExceededError extends Error {
47
+ readonly code: "context_exceeded";
48
+ readonly provider: string;
49
+ readonly providerCode?: string;
50
+ constructor(message: string, options: TypedErrorOptions);
51
+ }
52
+ /**
53
+ * Thrown when the provider returns a non-context error (auth, rate limit, server error, etc.).
54
+ * Catch-all for unclassified provider failures.
55
+ */
56
+ declare class AgentProviderError extends Error {
57
+ readonly code: "provider_error";
58
+ readonly provider: string;
59
+ readonly providerCode?: string;
60
+ /**
61
+ * Whether a retry with backoff is likely to succeed. See
62
+ * {@link ClassifiedError.retryable}. Absent when the provider did not
63
+ * classify the error — callers should treat absent as "don't retry".
64
+ */
65
+ readonly retryable?: boolean;
66
+ constructor(message: string, options: TypedErrorOptions);
67
+ }
68
+ /**
69
+ * Thrown when a run is aborted by the consumer via `agent.abort()` or an external `AbortSignal`.
70
+ */
71
+ declare class AgentAbortedError extends Error {
72
+ readonly code: "aborted";
73
+ constructor(message?: string, options?: {
74
+ cause?: unknown;
75
+ });
76
+ }
77
+ /**
78
+ * Thrown (well — constructed; attach via the `tool:gate` block signal) when the
79
+ * union of `allowed-tools` across active skills does not permit a tool call.
80
+ *
81
+ * Produced by the allowed-tools middleware registered on `tool:gate` /
82
+ * `mcp:tool:gate`. The gate's `block = true` + `reason` carry the same message
83
+ * so consumers that don't look at this typed error still get a useful string.
84
+ */
85
+ declare class AgentToolNotAllowedError extends Error {
86
+ readonly code: "tool_not_allowed";
87
+ /** Canonical tool name the agent tried to call. */
88
+ readonly toolName: string;
89
+ /** Aliased / wire name the LLM saw. */
90
+ readonly displayName: string;
91
+ /** Flattened union of `allowedTools` patterns across active skills. */
92
+ readonly allowedUnion: readonly string[];
93
+ /** Names of the skills currently active when the block fired. */
94
+ readonly activeSkills: readonly string[];
95
+ constructor(options: {
96
+ toolName: string;
97
+ displayName: string;
98
+ allowedUnion: readonly string[];
99
+ activeSkills: readonly string[];
100
+ cause?: unknown;
101
+ });
102
+ }
103
+ /**
104
+ * Regex patterns matching common "context window exceeded" messages across providers.
105
+ *
106
+ * Use {@link matchesContextExceeded} to test a free-form error message against them.
107
+ * Provider authors can also compose these into their own `classifyError` fallbacks.
108
+ */
109
+ declare const CONTEXT_EXCEEDED_MESSAGE_PATTERNS: readonly RegExp[];
110
+ /**
111
+ * Return true when `message` matches any of the known "context window exceeded"
112
+ * phrasings. Safe for `''` / non-strings (returns false).
113
+ */
114
+ declare function matchesContextExceeded(message: unknown): boolean;
115
+ /**
116
+ * Convert a `ClassifiedError` + underlying cause into the matching typed error instance.
117
+ */
118
+ declare function toTypedError(classification: ClassifiedError, provider: string, cause: unknown): AgentContextExceededError | AgentProviderError | AgentAbortedError;
119
+ //#endregion
120
+ //#region src/types.d.ts
121
+ /**
122
+ * Thinking / extended-reasoning configuration.
123
+ *
124
+ * - `'off'` — no thinking.
125
+ * - `'minimal' | 'low' | 'medium' | 'high'` — explicit token budget. Maps to
126
+ * provider-specific reasoning controls (Anthropic `thinking.type='enabled'`
127
+ * with a budget; OpenAI `reasoning_effort`).
128
+ * - `'adaptive'` — let the model decide per-turn whether and how much to think.
129
+ * Anthropic-only (`thinking.type='adaptive'`). Other providers fall back to
130
+ * no reasoning when this value is supplied.
131
+ */
132
+ type ThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'adaptive';
133
+ interface McpServerConfig {
134
+ /** Display name (used for tool namespacing) */
135
+ name: string;
136
+ /** Transport type */
137
+ transport: 'stdio' | 'sse' | 'streamable-http';
138
+ /** For stdio: command to run */
139
+ command?: string;
140
+ /** For stdio: command arguments */
141
+ args?: string[];
142
+ /**
143
+ * For stdio: environment variables to pass to the server process.
144
+ *
145
+ * Merged on top of the MCP SDK's default inherited environment — a safety
146
+ * whitelist (`PATH`, `HOME`, `LANG`, `SHELL`, `USER` on POSIX; `APPDATA`,
147
+ * `PATH`, ... on Win32). Setting this to `{}` no longer strips `PATH` from
148
+ * the child process. Set {@link McpServerConfig.strictEnv} to `true` to
149
+ * pass `env` verbatim with no inherited defaults.
150
+ */
151
+ env?: Record<string, string>;
152
+ /**
153
+ * When true, {@link McpServerConfig.env} is passed verbatim to the spawned
154
+ * process — the MCP SDK's default inherited environment (`PATH`, `HOME`, ...)
155
+ * is NOT merged in. Most consumers should leave this off; the default merge
156
+ * prevents `spawn ENOENT` when a stdio server declares an `env` without
157
+ * restating `PATH`.
158
+ */
159
+ strictEnv?: boolean;
160
+ /** For sse/streamable-http: server URL */
161
+ url?: string;
162
+ /** Optional headers for HTTP transports */
163
+ headers?: Record<string, string>;
164
+ /**
165
+ * Timeout in milliseconds for MCP server bootstrap (connect + tool discovery).
166
+ *
167
+ * Zidane connects MCP servers lazily on the first `run()`. Without a
168
+ * bootstrap timeout, a slow or hung server can delay the first provider call
169
+ * for an arbitrarily long time even when that MCP server is never used.
170
+ *
171
+ * Default: `10000`.
172
+ */
173
+ bootstrapTimeout?: number;
174
+ /** Timeout in milliseconds for MCP tool calls (default: 30000) */
175
+ toolTimeout?: number;
176
+ /**
177
+ * Allow-list of tool names to expose. Names match the upstream tool name
178
+ * (NOT the namespaced `mcp_{server}_{tool}` form). Tools not in the list are
179
+ * dropped before registration — the model never sees them in its catalog and
180
+ * the wire cost of advertising them is avoided.
181
+ *
182
+ * Mutually exclusive with {@link McpServerConfig.disabledTools} — passing both
183
+ * throws at bootstrap time.
184
+ *
185
+ * Composes with {@link McpServerConfig.toolFilter}: allow-list applies first,
186
+ * then the predicate. Composes with the `mcp:tools:filter` hook: config-side
187
+ * filters apply first, then the hook can further narrow the list.
188
+ */
189
+ enabledTools?: string[];
190
+ /**
191
+ * Deny-list of tool names. Tools matching are dropped before registration.
192
+ * Same matching semantics as {@link McpServerConfig.enabledTools}.
193
+ */
194
+ disabledTools?: string[];
195
+ /**
196
+ * Custom predicate run on each upstream tool. Return `true` to keep, `false`
197
+ * to drop. Receives the raw `listTools()` payload — useful for filtering by
198
+ * description, schema shape, or other metadata that an allow/deny list can't
199
+ * express.
200
+ *
201
+ * Runs after the allow/deny filter but before the `mcp:tools:filter` hook.
202
+ */
203
+ toolFilter?: (tool: {
204
+ name: string;
205
+ description?: string | null;
206
+ inputSchema?: unknown;
207
+ }) => boolean;
208
+ /**
209
+ * Per-server override for {@link AgentBehavior.toolDisclosure}. When set,
210
+ * this server's tools follow this disclosure mode regardless of the
211
+ * agent-wide default. Useful when one big MCP server (200+ tools) should
212
+ * stay lazy while smaller servers stay eager.
213
+ *
214
+ * Default: inherits from `behavior.toolDisclosure`.
215
+ */
216
+ disclosure?: 'eager' | 'lazy';
217
+ }
218
+ type ToolExecutionMode = 'sequential' | 'parallel';
219
+ interface AgentBehavior {
220
+ /** Tool execution mode (default: 'sequential') */
221
+ toolExecution?: ToolExecutionMode;
222
+ /**
223
+ * Max agent loop iterations.
224
+ *
225
+ * Default: unlimited (Infinity). The loop runs until the model signals
226
+ * completion (no tool calls / `end_turn`), the abort signal fires, or this
227
+ * cap is hit. Set a finite value as a safety net for runaway loops.
228
+ */
229
+ maxTurns?: number;
230
+ /** Max tokens per LLM response (default: 16384) */
231
+ maxTokens?: number;
232
+ /** Thinking token budget — overrides the level-based default when set */
233
+ thinkingBudget?: number;
234
+ /** JSON Schema for structured output enforcement */
235
+ schema?: Record<string, unknown>;
236
+ /**
237
+ * Enable provider prompt caching. When on (default), the provider marks the
238
+ * system prompt, tools, and the last stable message with cache breakpoints so
239
+ * the shared prefix is served from cache across turns.
240
+ *
241
+ * - Anthropic: `cache_control: { type: 'ephemeral' }` on the last `system`
242
+ * content part, the last tool, and the last message content part.
243
+ * - OpenAI-compatible / OpenRouter: same shape — honored by Anthropic-backed
244
+ * OpenRouter routes and by Gemini; ignored (no-op) by providers that cache
245
+ * automatically (OpenAI, DeepSeek, Grok, Groq, Moonshot).
246
+ *
247
+ * Usage is surfaced via `TurnUsage.cacheRead` / `TurnUsage.cacheCreation`.
248
+ *
249
+ * Default: `true`.
250
+ */
251
+ cache?: boolean;
252
+ /**
253
+ * Soft per-turn cap on total tool-output bytes. When the sum of `outputBytes`
254
+ * across a turn's tool results exceeds this value, the loop injects a
255
+ * synthetic user message instructing the model to summarize before calling
256
+ * more tools, and fires the `budget:exceeded` hook.
257
+ *
258
+ * Measured **post-`tool:transform`** so consumer truncation counts toward the
259
+ * budget. Off by default (undefined / `0` disables the check). A reasonable
260
+ * starting value for OSS-model integrations is `32768`.
261
+ */
262
+ toolOutputBudget?: number;
263
+ /**
264
+ * Deduplicate identical re-reads of the same file in `read_file`. When the
265
+ * model re-reads a file with the same slice and the bytes haven't changed
266
+ * since the last read in this session, the tool returns a short stub
267
+ * instead of re-emitting the full content. Pairs with the read-before-edit
268
+ * guard in `edit` / `multi_edit`.
269
+ *
270
+ * Requires a session (set via `createSession()`); without one, the flag is
271
+ * a no-op since per-session state has nowhere to live.
272
+ *
273
+ * Default: `true`.
274
+ */
275
+ dedupReads?: boolean;
276
+ /**
277
+ * Taper the thinking budget over the course of a run. Late turns are
278
+ * usually checkpoint / cleanup work where reasoning rarely pays for
279
+ * itself; early turns benefit most. Two forms:
280
+ *
281
+ * - **Struct** — geometric decay starting after `afterTurn`, multiplying by
282
+ * `factor` each subsequent turn, clamped to `floor`. Example
283
+ * `{ afterTurn: 5, factor: 0.5, floor: 1024 }` with a base budget of 8192:
284
+ * turns 1-5 = 8192, turn 6 = 4096, turn 7 = 2048, turn 8+ = 1024.
285
+ * - **Function** — `(runTurn, baseBudget) => number`. Arbitrary curves;
286
+ * `runTurn` is 1-indexed, run-relative (resumed sessions reset).
287
+ *
288
+ * No-op when `thinkingBudget` is unset. Honored by every provider that
289
+ * respects `thinkingBudget` (anthropic explicit-budget `enabled` path,
290
+ * adaptive `maxTokensCap`, openai-compat `max_tokens` padding).
291
+ *
292
+ * Default: `undefined` (no decay).
293
+ */
294
+ thinkingDecay?: {
295
+ afterTurn: number;
296
+ factor: number;
297
+ floor: number;
298
+ } | ((runTurn: number, baseBudget: number) => number);
299
+ /**
300
+ * Per-tool soft call budget for this run. Keyed by **canonical** tool name.
301
+ * On the first call after the run-cumulative dispatched count for that tool
302
+ * reaches `max`, the framework fires `onExceed`:
303
+ *
304
+ * - `'steer'` (default) — let the call execute, but emit a synthetic user
305
+ * message after the turn that nudges the model away from re-calling the
306
+ * tool. Reuses the existing post-turn steer pathway used by
307
+ * `toolOutputBudget`. Fires `tool-budget:exceeded` with `mode: 'steer'`.
308
+ * - `'block'` — refuse the call via `tool:gate` `block`. The model sees a
309
+ * `Blocked: <reason>` tool result. Fires `tool-budget:exceeded` with
310
+ * `mode: 'block'`.
311
+ * - **Function** — `(ctx) => { mode, message }`. The consumer supplies the
312
+ * steering / refusal text and chooses the mode dynamically.
313
+ *
314
+ * Counts include both real dispatches and dedup substitutes (Z19 hits).
315
+ * Excludes calls already blocked by an earlier gate (skill allow-list,
316
+ * consumer hook). Tool dispatched by spawned subagents has its own per-run
317
+ * counter — child counts never charge the parent.
318
+ *
319
+ * For MCP tools, key by the namespaced wire name (`mcp_<server>_<tool>`).
320
+ *
321
+ * Atomic in parallel mode: the middleware tracks its own per-tool
322
+ * approval counter, incremented synchronously at gate-time. A
323
+ * 4-call parallel batch against `max: 2` will let the first 2 through
324
+ * and refuse the rest, even though the loop's `runToolCounts` only
325
+ * propagates between calls (not within a single batch's gate fan-out).
326
+ *
327
+ * Default: `undefined` (no budget enforcement).
328
+ */
329
+ toolBudgets?: Record<string, {
330
+ max: number;
331
+ onExceed?: 'steer' | 'block' | ((ctx: {
332
+ tool: string;
333
+ count: number;
334
+ max: number;
335
+ }) => {
336
+ mode: 'steer' | 'block';
337
+ message: string;
338
+ });
339
+ }>;
340
+ /**
341
+ * Generic per-tool argument deduplication. Keyed by the tool's **canonical**
342
+ * name (alias-stable). Each entry is a hasher: `(input) => string | undefined`.
343
+ *
344
+ * **Hasher contract** — three return values, three meanings:
345
+ *
346
+ * | Return | Meaning |
347
+ * |-------------------------|------------------------------------------------------------------------|
348
+ * | a non-empty string | Cache key for this call. Equal keys (most-recent-only, this session) |
349
+ * | | replay the prior recorded result without re-dispatching the tool. |
350
+ * | `undefined` | **Skip dedup for this call.** The tool runs normally; nothing recorded.|
351
+ * | `''` / non-string | Treated identically to `undefined` (defensive: no dedup, no error). |
352
+ *
353
+ * The `undefined` opt-out is the way to say *"this specific call is not
354
+ * cacheable"* (timestamps in input, randomness baked in, debug flags). It
355
+ * is **not** the same as `JSON.stringify(input)` — that would dedup against
356
+ * the verbatim input. Pick one explicitly:
357
+ *
358
+ * ```ts
359
+ * // Always cache by full input — every identical re-call dedups.
360
+ * dedupTools: { todowrite: input => JSON.stringify(input) }
361
+ *
362
+ * // Cache by a normalized subset; non-cacheable shapes opt out.
363
+ * dedupTools: {
364
+ * execute_sql: (input) => {
365
+ * const q = typeof input.query === 'string' ? input.query.trim().toLowerCase() : undefined
366
+ * if (!q || q.includes('now()') || q.includes('random()')) return undefined
367
+ * return q
368
+ * },
369
+ * }
370
+ * ```
371
+ *
372
+ * On a hit, the previously-recorded result is replayed as the tool_result
373
+ * without dispatching the tool. The substitution flows through `tool:gate`
374
+ * `result` (Z20), so `tool:after` and `tool:transform` still fire.
375
+ *
376
+ * Requires a session (`createSession()`); without one, the map is a silent
377
+ * no-op since per-session state has nowhere to live. Tools with side
378
+ * effects or non-deterministic outputs (network, time, randomness) MUST
379
+ * NOT be listed — there is no safety net beyond the consumer's hasher.
380
+ *
381
+ * For MCP tools, key by the namespaced wire name (`mcp_<server>_<tool>`).
382
+ * Parallel mode (`toolExecution: 'parallel'`, the default) sees calls in
383
+ * the SAME assistant turn race against each other — none can dedup against
384
+ * a sibling that started in the same batch. Sequential mode honors order
385
+ * within a turn.
386
+ *
387
+ * **Cache policy**: only the most recent `(hash, result)` per tool is
388
+ * retained. Interleaved patterns (input A, input B, input A) miss on the
389
+ * second A because B overwrote it. Sufficient for the common spam-the-
390
+ * same-call loop; consumers needing a richer cache should hook
391
+ * `tool:gate` directly.
392
+ *
393
+ * Default: `undefined` (no per-tool dedup).
394
+ */
395
+ dedupTools?: Record<string, (input: Record<string, unknown>) => string | undefined>;
396
+ /**
397
+ * Require `read_file` before `edit` / `multi_edit` on the same path, and
398
+ * reject edits when the file has changed on disk since the last read in
399
+ * this session. Eliminates the silent-corruption failure mode where a
400
+ * model "remembers" stale content and applies a substring edit against
401
+ * bytes that have moved.
402
+ *
403
+ * Requires a session. Off by default; turn it on for stricter eval-grade
404
+ * runs where silent edit corruption would invalidate the result.
405
+ *
406
+ * Default: `false`.
407
+ */
408
+ requireReadBeforeEdit?: boolean;
409
+ /**
410
+ * Client-side context compaction strategy. Use this for non-Anthropic
411
+ * providers (OSS via cerebras / openai-compat / openrouter) that don't
412
+ * have a server-side equivalent. Anthropic users should prefer the
413
+ * server-side `context-management-2025-06-27` beta — see
414
+ * `AnthropicParams.contextManagement`.
415
+ *
416
+ * - `'off'` (default) — no client-side compaction.
417
+ * - `'tail'` — when total tool-output bytes in the persisted history
418
+ * exceed `compactThreshold`, replace older `tool_result` outputs with a
419
+ * short stub, keeping the newest `compactKeepTurns` turns intact. The
420
+ * compaction is applied to the wire-level message list only; the
421
+ * underlying session turns are not modified.
422
+ *
423
+ * Default: `'off'`.
424
+ */
425
+ compactStrategy?: 'off' | 'tail';
426
+ /**
427
+ * Soft byte threshold that triggers tail compaction when
428
+ * `compactStrategy === 'tail'`. Counts the post-`context:transform` bytes
429
+ * of `tool_result` outputs across all messages. Default: `131_072` (128
430
+ * KiB). Ignored when compaction is off.
431
+ */
432
+ compactThreshold?: number;
433
+ /**
434
+ * Number of trailing turns to leave untouched during tail compaction. The
435
+ * most-recent `compactKeepTurns` user/assistant messages are not eligible
436
+ * for elision so the model keeps the freshest tool context. Default: `4`.
437
+ */
438
+ compactKeepTurns?: number;
439
+ /**
440
+ * Prefix every line of `read_file` output with its 1-indexed line number
441
+ * followed by a tab (`<N>\t<content>`) — the compact `cat -n`-style
442
+ * format Claude Code emits. The `edit` tool strips the prefix from
443
+ * `old_string` / `new_string` so the model can paste back a numbered
444
+ * chunk verbatim without breaking the match.
445
+ *
446
+ * Set `false` to opt out — useful for callers piping `read_file` into
447
+ * downstream parsers that don't recognize the prefix. Per-call
448
+ * `read_file({ lineNumbers: false })` overrides this default.
449
+ *
450
+ * Default: `true`.
451
+ */
452
+ readLineNumbers?: boolean;
453
+ /**
454
+ * Replace older `read_file` `tool_result` blocks with a short stub when
455
+ * a successful `edit` / `multi_edit` / `write_file` later in the same
456
+ * run modified the same path. The replacement is applied to the
457
+ * wire-level message list only — persisted session turns keep the
458
+ * original content.
459
+ *
460
+ * Eliminates the common waste pattern where the model carries the
461
+ * pre-edit file body forward across many turns "in case it needs it".
462
+ * Pairs cleanly with `compactStrategy: 'tail'`: stale reads shrink
463
+ * first, then the byte-threshold compaction fires if anything's left.
464
+ *
465
+ * Detection is conservative — only triggers when the corresponding
466
+ * tool_result confirms success (`Edited …`, `Created …`, `Updated …`).
467
+ * Failed edits and `No change needed` write_file calls do NOT
468
+ * invalidate prior reads.
469
+ *
470
+ * Default: `false`.
471
+ */
472
+ elideStaleReads?: boolean;
473
+ /**
474
+ * Tool disclosure strategy. Controls whether the model sees every tool's
475
+ * full `inputSchema` in its tool list every turn ("eager") or whether MCP
476
+ * tools are advertised as a name+description catalog in the system prompt
477
+ * and only get full schemas after being surfaced via the `tool_search`
478
+ * native tool ("lazy" / progressive disclosure).
479
+ *
480
+ * Native tools (those passed to `createAgent({ tools })`) and skill tools
481
+ * are always eager — they are core to the agent and cheap. Only MCP tools
482
+ * are eligible for lazy disclosure.
483
+ *
484
+ * When `'lazy'`, the agent:
485
+ * - Appends a `<searchable_tools>` section to the system prompt listing
486
+ * every MCP tool by `name` + `description` only (no `inputSchema`).
487
+ * - Auto-injects a `tool_search` native tool (opt out via
488
+ * {@link AgentBehavior.toolSearch}) the model uses to load schemas on
489
+ * demand. Surfaced tools persist for the rest of the run.
490
+ * - Rebuilds the wire-level tool list each turn, appending newly-unlocked
491
+ * tools at the end so the prefix-cache breakpoint advances cleanly.
492
+ *
493
+ * Trade-off: every `tool_search` invocation expands the tool list and
494
+ * invalidates the tool-list cache breakpoint for one turn. With many
495
+ * MCP servers, the savings on cold turns (fewer schemas in context) are
496
+ * substantial; with one tiny MCP server, the overhead may not pay back.
497
+ *
498
+ * Default: `'eager'`.
499
+ */
500
+ toolDisclosure?: 'eager' | 'lazy';
501
+ /**
502
+ * Fine-grained config for the `tool_search` tool auto-injected when
503
+ * {@link AgentBehavior.toolDisclosure} is `'lazy'`. No-op in eager mode.
504
+ *
505
+ * - `tool: false` — opt out of the auto-injection entirely. Use when the
506
+ * host wants to ship a custom discovery tool. Note that the catalog
507
+ * text drops the call-to-action prose in this case so the model isn't
508
+ * pointed at a non-existent tool.
509
+ * - `limit` — default cap on results returned per `tool_search` call when
510
+ * the model omits the parameter. Default: `20`.
511
+ *
512
+ * Note on host-defined `tool_search`: a tool the host registers under the
513
+ * name `tool_search` (or under any alias whose canonical is `tool_search`)
514
+ * will shadow the auto-injected one — the catalog text will point at the
515
+ * host's wire name, but driving the unlock flow requires either using
516
+ * `createToolSearchTool({ catalog, unlocked })` from `tools/tool-search`
517
+ * (which internally mutates the unlock set) or fully opting out via
518
+ * `toolSearch.tool: false` and treating discovery as a host-side concern.
519
+ * A bare host tool that doesn't touch the unlock set will not advance the
520
+ * lazy disclosure state and the hard gate will keep refusing lazy calls.
521
+ *
522
+ * Default: `undefined` (auto-inject with the default limit).
523
+ */
524
+ toolSearch?: {
525
+ tool?: false;
526
+ limit?: number;
527
+ };
528
+ }
529
+ /**
530
+ * One block of a multimodal user prompt.
531
+ *
532
+ * `agent.run({ prompt })` accepts either a plain string (treated as a single
533
+ * text part) or an array of these parts for multimodal inputs.
534
+ *
535
+ * `document` parts are routed per provider: PDF-style mime types are sent as
536
+ * native document blocks when the provider supports them; text documents are
537
+ * inlined as text with an attachment header. Providers that cannot handle an
538
+ * image or document throw early.
539
+ */
540
+ type PromptPart = PromptTextPart | PromptImagePart | PromptDocumentPart;
541
+ interface PromptTextPart {
542
+ type: 'text';
543
+ text: string;
544
+ }
545
+ interface PromptImagePart {
546
+ type: 'image';
547
+ /** IANA media type (e.g. `image/png`, `image/jpeg`) */
548
+ mediaType: string;
549
+ /** Base64-encoded payload */
550
+ data: string;
551
+ /** Optional display name */
552
+ name?: string;
553
+ }
554
+ interface PromptDocumentPart {
555
+ type: 'document';
556
+ /** IANA media type (e.g. `application/pdf`, `text/plain`) */
557
+ mediaType: string;
558
+ /** Either a base64-encoded payload (`encoding: 'base64'`) or raw text (`encoding: 'text'`) */
559
+ data: string;
560
+ encoding: 'base64' | 'text';
561
+ /** Optional display name used in attachment headers */
562
+ name?: string;
563
+ }
564
+ /**
565
+ * A single block of structured tool-result content.
566
+ *
567
+ * MCP servers can return a mix of text, image, resource, and audio blocks. Tools
568
+ * return `string` for the common text-only case or `ToolResultContent[]` when they
569
+ * need to preserve non-text content (e.g. screenshots from a browser MCP).
570
+ *
571
+ * Providers that support native multi-part tool results (Anthropic, OpenAI Codex via
572
+ * pi-ai) route image blocks into their wire format verbatim; OpenAI-compat providers
573
+ * route them via a companion-user-message fallback when the underlying model/endpoint
574
+ * does not accept images inside tool-role messages.
575
+ */
576
+ type ToolResultContent = ToolResultTextContent | ToolResultImageContent;
577
+ interface ToolResultTextContent {
578
+ type: 'text';
579
+ text: string;
580
+ }
581
+ interface ToolResultImageContent {
582
+ type: 'image';
583
+ /** IANA media type (e.g. `image/png`, `image/jpeg`) */
584
+ mediaType: string;
585
+ /** Base64-encoded payload */
586
+ data: string;
587
+ }
588
+ /**
589
+ * Lossy flattener — converts `ToolResultContent[]` (or a plain string) to a single
590
+ * string. Image blocks are replaced with `[image: <media> — <n> b64 bytes]` markers.
591
+ *
592
+ * Use at UI boundaries where a string is required; providers that understand
593
+ * structured content should route the array through without flattening.
594
+ */
595
+ declare function toolResultToText(content: string | ToolResultContent[]): string;
596
+ /**
597
+ * Approximate byte length of a tool output as it goes back to the model.
598
+ *
599
+ * - Plain text: UTF-8 byte length.
600
+ * - Structured content: text blocks contribute their UTF-8 byte length; image
601
+ * blocks contribute their **base64 character length**, since that is what
602
+ * the model tokenizes (the wire-encoded payload, not the decoded image).
603
+ *
604
+ * Used by the agent loop to populate `outputBytes` on `tool:after`,
605
+ * `tool:transform`, `mcp:tool:after`, and `mcp:tool:transform` hooks so
606
+ * consumers can size-budget tool output without re-counting bytes themselves.
607
+ */
608
+ declare function toolOutputByteLength(content: string | ToolResultContent[]): number;
609
+ type SessionContentBlock = {
610
+ type: 'text';
611
+ text: string;
612
+ } | {
613
+ type: 'image';
614
+ mediaType: string;
615
+ data: string;
616
+ } | {
617
+ type: 'tool_call';
618
+ id: string;
619
+ name: string;
620
+ input: Record<string, unknown>;
621
+ } | {
622
+ type: 'tool_result';
623
+ callId: string;
624
+ /**
625
+ * Tool output — either a plain string (text-only, the common case) or a structured
626
+ * array of content blocks (text + image for multimodal tools such as screenshots).
627
+ */
628
+ output: string | ToolResultContent[];
629
+ isError?: boolean;
630
+ } | {
631
+ type: 'thinking';
632
+ text: string;
633
+ signature?: string;
634
+ /**
635
+ * Provider that minted `signature`. Signatures are provider-bound (Anthropic
636
+ * HMAC vs. OpenAI `encrypted_content`) and are dropped on cross-provider
637
+ * hops to avoid 400s. Unset means legacy/unknown — forwarded as-is.
638
+ */
639
+ signatureProducer?: 'anthropic' | 'openai';
640
+ } | {
641
+ type: 'redacted_thinking';
642
+ data: string;
643
+ } | {
644
+ /**
645
+ * Opaque round-trip envelope for reasoning state minted by an OpenAI-compat
646
+ * gateway (currently OpenRouter). The gateway expects its own
647
+ * `reasoning_details` array echoed back verbatim on the next turn so the
648
+ * upstream model can resume an extended-reasoning chain across tool calls.
649
+ *
650
+ * Stored opaquely because the items are provider-bound (Anthropic HMAC
651
+ * signatures, OpenAI `encrypted_content`, model-specific summary formats
652
+ * — all flowing through the gateway's normalized envelope).
653
+ */
654
+ type: 'provider_reasoning';
655
+ producer: 'openrouter';
656
+ details: unknown[];
657
+ /**
658
+ * Model id that produced the details. Reasoning is bound to a specific
659
+ * upstream route — a model switch on the next turn invalidates the
660
+ * embedded signatures, so the sender drops the block on mismatch.
661
+ */
662
+ model?: string;
663
+ };
664
+ interface SessionMessage {
665
+ role: 'user' | 'assistant';
666
+ content: SessionContentBlock[];
667
+ }
668
+ interface SessionTurn {
669
+ /** UUID — generated by the store if it provides generateTurnId, else crypto.randomUUID() */
670
+ id: string;
671
+ /** Run that produced this turn (e.g. 'run_1') */
672
+ runId?: string;
673
+ role: 'user' | 'assistant' | 'system';
674
+ content: SessionContentBlock[];
675
+ /** Token usage — only present on assistant turns */
676
+ usage?: TurnUsage;
677
+ /** Unix timestamp (Date.now()) when the turn was created */
678
+ createdAt: number;
679
+ }
680
+ /**
681
+ * Per-run hook registrations. Each entry can be a single handler or an array of handlers.
682
+ * Keys are `AgentHooks` event names (loose-typed here to avoid a circular import; agent.ts
683
+ * narrows it to the strongly-typed map).
684
+ */
685
+ type RunHookMap = Record<string, ((ctx: any) => unknown) | ((ctx: any) => unknown)[]>;
686
+ interface AgentRunOptions {
687
+ model?: string;
688
+ /**
689
+ * User prompt. Optional when resuming a session with existing turns.
690
+ *
691
+ * Accepts either a plain string (single text part) or an array of `PromptPart`s for
692
+ * multimodal inputs (text, images, documents). See {@link PromptPart}.
693
+ */
694
+ prompt?: string | PromptPart[];
695
+ system?: string;
696
+ thinking?: ThinkingLevel;
697
+ /** Abort signal — when triggered, the agent stops after the current turn */
698
+ signal?: AbortSignal;
699
+ /** Behavior overrides for this run (overrides agent defaults) */
700
+ behavior?: AgentBehavior;
701
+ /** Tool overrides for this run. Pass {} for no tools. Omit to use agent tools. */
702
+ tools?: Record<string, ToolDef>;
703
+ /**
704
+ * Per-run hook registrations. Each hook is attached before the run starts and
705
+ * detached in a finally block so handlers never leak across runs.
706
+ *
707
+ * Accepts either a single handler or an array (all handlers register).
708
+ */
709
+ hooks?: RunHookMap;
710
+ /**
711
+ * Parent run id. Populated automatically by the `spawn` tool when the child
712
+ * shares the parent's session; recorded on the resulting `SessionRun` so the
713
+ * parent↔child run tree can be reconstructed from a persisted session.
714
+ */
715
+ parentRunId?: string;
716
+ /**
717
+ * Zero-based subagent depth. 0 = top-level `agent.run()`, 1 = first-level
718
+ * child spawned by a parent agent, and so on. Used by the spawn tool to
719
+ * enforce `maxDepth` and to stamp `child:*` forwarded hook payloads.
720
+ */
721
+ depth?: number;
722
+ }
723
+ /**
724
+ * Reason the provider gave for stopping the turn.
725
+ *
726
+ * - `'stop'` — natural turn end (`end_turn` / `stop_sequence`).
727
+ * - `'tool-calls'` — model emitted tool_use blocks.
728
+ * - `'length'` — `max_tokens` reached, or (Anthropic 4.6+) the response bumped
729
+ * against the model's context window mid-stream
730
+ * (`model_context_window_exceeded`). The partial response is preserved; the
731
+ * loop emits this reason so consumers can prune/retry.
732
+ * - `'content-filter'` — model refused.
733
+ * - `'pause'` — Anthropic `pause_turn`: a server-side mid-turn pause for very
734
+ * long thinking. The loop continues with a synthetic "Please continue."
735
+ * user message rather than terminating; consumers see the pause via this
736
+ * finish reason on the prior assistant turn.
737
+ * - `'error'` — provider classified the turn as failed.
738
+ * - `'other'` — unknown / unmapped.
739
+ */
740
+ type TurnFinishReason = 'stop' | 'tool-calls' | 'length' | 'content-filter' | 'pause' | 'error' | 'other';
741
+ interface TurnUsage {
742
+ input: number;
743
+ output: number;
744
+ /** Tokens written to cache (Anthropic) */
745
+ cacheCreation?: number;
746
+ /** Tokens read from cache (Anthropic) */
747
+ cacheRead?: number;
748
+ /** Thinking/reasoning tokens used */
749
+ thinking?: number;
750
+ /** Cost in USD as reported by the provider (OpenRouter) */
751
+ cost?: number;
752
+ /**
753
+ * Why the model stopped this turn. Providers normalize native stop reasons to this union.
754
+ * Absent when the provider did not surface a reason (e.g. mock turns).
755
+ */
756
+ finishReason?: TurnFinishReason;
757
+ /**
758
+ * The model ID the provider ultimately used. May differ from the requested model when the
759
+ * provider remaps aliases. Absent for providers that do not echo a model ID.
760
+ */
761
+ modelId?: string;
762
+ }
763
+ interface AgentStats {
764
+ /**
765
+ * Cumulative input tokens across the parent agent loop **and** every
766
+ * recursively-spawned sub-agent. Use this for billing / token-ledger
767
+ * consumption.
768
+ */
769
+ totalIn: number;
770
+ /** Cumulative output tokens. Same semantics as {@link AgentStats.totalIn}. */
771
+ totalOut: number;
772
+ /**
773
+ * Cumulative cache-read tokens across the parent agent loop and every
774
+ * recursively-spawned sub-agent. Surfaced at the top level (rather than
775
+ * only per-`TurnUsage`) because Anthropic prices cache reads at a separate
776
+ * line-item rate from regular input — billing-correct cost computation
777
+ * needs this number directly. Always `0` for providers that don't report
778
+ * cache usage.
779
+ */
780
+ totalCacheRead: number;
781
+ /**
782
+ * Cumulative cache-creation tokens across the parent agent loop and every
783
+ * recursively-spawned sub-agent. Same rationale as
784
+ * {@link AgentStats.totalCacheRead} — separate Anthropic billing rate.
785
+ * Always `0` for providers that don't report cache usage.
786
+ */
787
+ totalCacheCreation: number;
788
+ /**
789
+ * Number of parent agent-loop turns. Children's turn counts live under
790
+ * `children[].stats.turns` and are NOT folded in here — a single "turns"
791
+ * number for the whole tree would conflate two different measures
792
+ * (parent-loop iterations vs. tree-wide tool-call rounds).
793
+ *
794
+ * Tree-wide turn count: `flattenTurns(stats).length`.
795
+ */
796
+ turns: number;
797
+ /**
798
+ * Wall-clock duration of the top-level `agent.run()` call, in milliseconds.
799
+ * Children run during parent tool calls so this naturally subsumes child
800
+ * wall time — sequential children inflate it, parallel children compress
801
+ * into the parent's window.
802
+ */
803
+ elapsed: number;
804
+ /**
805
+ * Per-turn usage breakdown for the **parent loop only**. Children's per-turn
806
+ * usages live under `children[].stats.turnUsage`. Use {@link flattenTurns}
807
+ * to walk the full tree.
808
+ */
809
+ turnUsage?: TurnUsage[];
810
+ /**
811
+ * Cumulative cost in USD — parent loop plus every recursively-spawned
812
+ * sub-agent. Sums per-turn `TurnUsage.cost` reported by the provider.
813
+ * Absent when neither parent nor any descendant reported a non-zero cost.
814
+ */
815
+ cost?: number;
816
+ /** Stats from child agents spawned during this run, in completion order. Recursive. */
817
+ children?: ChildRunStats[];
818
+ /** Structured output from schema enforcement (only present when behavior.schema is set) */
819
+ output?: Record<string, unknown>;
820
+ /**
821
+ * Milliseconds from the start of `agent.run()` to the first observable signal from the
822
+ * provider (first `stream:text`, `stream:thinking`, or `tool:before` event).
823
+ *
824
+ * Absent when the run produced no observable signals (e.g. aborted before any stream event).
825
+ */
826
+ timeTillFirstTokenMs?: number;
827
+ }
828
+ interface ChildRunStats {
829
+ id: string;
830
+ task: string;
831
+ /**
832
+ * The child agent's full {@link AgentStats}. Cumulative for that child's
833
+ * own subtree (child loop + its grandchildren). Do **not** sum
834
+ * `ctx.stats.totalIn` across `spawn:complete` events to derive top-level
835
+ * totals — `agent.run()`'s return value is the canonical cumulative root.
836
+ */
837
+ stats: AgentStats;
838
+ /**
839
+ * Subagent depth when this child ran. 1 = direct child of the top-level
840
+ * agent, 2 = grandchild, etc. Useful for telemetry that wants to group
841
+ * runs by depth.
842
+ */
843
+ depth?: number;
844
+ /**
845
+ * Terminal state of the child run. `'completed'` is the default. Exposed so
846
+ * a parent reading `stats.children` can distinguish aborted/timed-out
847
+ * children without re-parsing the returned string.
848
+ */
849
+ status?: 'completed' | 'aborted' | 'timeout' | 'error';
850
+ /**
851
+ * Final structured output when the child was run with `behavior.schema`.
852
+ * Mirrors `AgentStats.output` but is surfaced here so the parent can read
853
+ * it without peeking at the nested `stats` bag.
854
+ */
855
+ output?: Record<string, unknown>;
856
+ }
857
+ /**
858
+ * Base context for tool execution hooks.
859
+ *
860
+ * `name` is the canonical tool identity — the spec name registered on the agent (or the
861
+ * `mcp_{server}_{tool}` name for MCP tools). Hooks should policy-match against `name`.
862
+ *
863
+ * `displayName` is the outward-facing name — the alias surfaced to the LLM when
864
+ * `AgentOptions.toolAliases` maps the canonical name; otherwise equal to `name`.
865
+ * UI/telemetry adapters should emit `displayName`.
866
+ *
867
+ * Canonical vs. alias matters on session resume: `session.turns` persists canonical
868
+ * names only, so renaming an alias cannot desync history.
869
+ */
870
+ interface ToolHookContext {
871
+ turnId: string;
872
+ callId: string;
873
+ /** Canonical tool name (spec name). Stable across alias-map changes. */
874
+ name: string;
875
+ /** Aliased (wire) name — equal to `name` when no alias is defined. */
876
+ displayName: string;
877
+ input: Record<string, unknown>;
878
+ }
879
+ /**
880
+ * Base context for MCP tool hooks.
881
+ *
882
+ * `tool` is the native tool name on the MCP server. `server` is the configured server
883
+ * name. The canonical zidane-namespaced identity is `mcp_{server}_{tool}`.
884
+ *
885
+ * `displayName` equals the canonical namespaced name unless the agent has aliased
886
+ * this MCP tool via `AgentOptions.toolAliases`; in which case `displayName` is the
887
+ * alias that the LLM sees.
888
+ */
889
+ interface McpToolHookContext {
890
+ turnId: string;
891
+ callId: string;
892
+ server: string;
893
+ tool: string;
894
+ /** Aliased wire name for this MCP tool, or the canonical `mcp_{server}_{tool}` name. */
895
+ displayName: string;
896
+ input: Record<string, unknown>;
897
+ }
898
+ /** Base context for session hooks */
899
+ interface SessionHookContext {
900
+ sessionId: string;
901
+ }
902
+ /** Base context for spawn hooks */
903
+ interface SpawnHookContext {
904
+ id: string;
905
+ task: string;
906
+ /**
907
+ * Subagent depth for the spawn. 1 = direct child of the top-level agent.
908
+ * Present on spawn:before/complete/error. Absent for grandchild spawns that
909
+ * bubble through `child:*` events (which carry their own `depth`).
910
+ */
911
+ depth?: number;
912
+ }
913
+ /** Context for stream hooks */
914
+ interface StreamHookContext {
915
+ turnId: string;
916
+ }
917
+ /** Context for OAuth refresh hooks */
918
+ interface OAuthRefreshHookContext {
919
+ provider: string;
920
+ providerId: string;
921
+ source: 'params' | 'file';
922
+ previousCredentials: Record<string, unknown> & {
923
+ access: string;
924
+ refresh: string;
925
+ expires: number;
926
+ };
927
+ credentials: Record<string, unknown> & {
928
+ access: string;
929
+ refresh: string;
930
+ expires: number;
931
+ };
932
+ }
933
+ type SessionEndStatus = 'completed' | 'aborted' | 'error';
934
+ //#endregion
935
+ //#region src/providers/anthropic.d.ts
936
+ /**
937
+ * Server-side context-management config — the body of `context_management` on
938
+ * the Messages API. Typed loosely (Record-of-unknown) so we don't pin a specific
939
+ * SDK schema version: the v0.90 SDK does not yet type this field, but the wire
940
+ * format is stable behind the `context-management-2025-06-27` beta.
941
+ *
942
+ * See: https://docs.anthropic.com/en/docs/build-with-claude/context-management
943
+ */
944
+ interface AnthropicContextManagement {
945
+ edits?: Array<Record<string, unknown>>;
946
+ [key: string]: unknown;
947
+ }
948
+ interface AnthropicParams {
949
+ apiKey?: string;
950
+ access?: string;
951
+ refresh?: string;
952
+ expires?: number;
953
+ defaultModel?: string;
954
+ /**
955
+ * Optional override for the Anthropic SDK base URL. Honored end-to-end — headers and
956
+ * routing pass through to the forwarded host. Useful for proxies (e.g. corporate
957
+ * gateways, internal router).
958
+ */
959
+ baseURL?: string;
960
+ /**
961
+ * Additional `anthropic-beta` flags to opt into. Merged with the OAuth-path
962
+ * defaults (`claude-code-20250219`, `oauth-2025-04-20`); duplicates are
963
+ * de-duped. Examples:
964
+ *
965
+ * - `'context-management-2025-06-27'` — server-side context compaction
966
+ * (token-accurate; pair with {@link AnthropicParams.contextManagement}).
967
+ * - `'token-efficient-tools-2026-03-28'` — terser tool_use wire format.
968
+ * - `'interleaved-thinking-2025-05-14'` — think between tool calls within
969
+ * one turn.
970
+ * - `'redact-thinking-2026-02-12'` — replace large thinking blocks with
971
+ * stubs server-side.
972
+ * - `'prompt-caching-scope-2026-01-05'` — extended prompt-cache scope.
973
+ *
974
+ * Honored on both the OAuth and API-key paths.
975
+ */
976
+ extraBetas?: readonly string[];
977
+ /**
978
+ * Server-side context-management directive. Sent on the request body as
979
+ * `context_management`. Requires the `context-management-2025-06-27` beta —
980
+ * add it to {@link AnthropicParams.extraBetas}.
981
+ *
982
+ * Typed loosely so future Anthropic schema additions land without an SDK
983
+ * bump. A typical compaction edit:
984
+ *
985
+ * ```ts
986
+ * contextManagement: {
987
+ * edits: [{
988
+ * type: 'clear_tool_uses_20250919',
989
+ * trigger: { type: 'input_tokens', value: 180_000 },
990
+ * clear_at_least: { type: 'input_tokens', value: 140_000 },
991
+ * clear_tool_inputs: ['Read', 'Bash', 'Grep'],
992
+ * }],
993
+ * }
994
+ * ```
995
+ */
996
+ contextManagement?: AnthropicContextManagement;
997
+ /**
998
+ * Generic pass-through for fields on the Messages API request body that the
999
+ * SDK does not yet type. Spread into the request before the typed fields,
1000
+ * so explicit options ({@link AnthropicParams.contextManagement} and the
1001
+ * built-in fields like `model` / `tools` / `messages`) win on collision.
1002
+ *
1003
+ * Forward-compat escape hatch for new Anthropic betas — when a future flag
1004
+ * ships before zidane has a dedicated typed knob, set it here without
1005
+ * waiting on a release. Most fields will still need the matching beta in
1006
+ * {@link AnthropicParams.extraBetas}.
1007
+ */
1008
+ extraBodyParams?: Record<string, unknown>;
1009
+ }
1010
+ declare function anthropic(anthropicParams?: AnthropicParams): Provider;
1011
+ //#endregion
1012
+ //#region src/providers/cerebras.d.ts
1013
+ interface CerebrasParams {
1014
+ apiKey?: string;
1015
+ defaultModel?: string;
1016
+ /**
1017
+ * Provider capability flags. Cerebras currently serves text-only OSS models
1018
+ * (GLM, Llama-family, Qwen-family) — default: `{ vision: false, imageInToolResult: false }`.
1019
+ * Override when routing to a vision-capable deployment.
1020
+ */
1021
+ capabilities?: ProviderCapabilities;
1022
+ }
1023
+ /**
1024
+ * Cerebras provider.
1025
+ *
1026
+ * Thin wrapper around {@link openaiCompat} with Cerebras-specific defaults
1027
+ * (base URL, default model).
1028
+ */
1029
+ declare function cerebras(params?: CerebrasParams): Provider;
1030
+ //#endregion
1031
+ //#region src/providers/openai.d.ts
1032
+ interface OpenAIParams {
1033
+ /** OpenAI Codex OAuth access token. Falls back to OPENAI_CODEX_API_KEY and .credentials.json. */
1034
+ apiKey?: string;
1035
+ /** Alias for apiKey, matching the OAuth credential field. */
1036
+ access?: string;
1037
+ refresh?: string;
1038
+ expires?: number;
1039
+ accountId?: string;
1040
+ defaultModel?: string;
1041
+ transport?: 'sse' | 'websocket' | 'auto';
1042
+ }
1043
+ declare function openai(params?: OpenAIParams): Provider;
1044
+ //#endregion
1045
+ //#region src/providers/openai-compat.d.ts
1046
+ /**
1047
+ * HTTP error thrown when an OpenAI-compatible endpoint returns a non-OK response.
1048
+ *
1049
+ * The body is best-effort JSON-parsed; `error.message` / `error.code` / `error.type`
1050
+ * are extracted for clean downstream classification.
1051
+ */
1052
+ declare class OpenAICompatHttpError extends Error {
1053
+ readonly status: number;
1054
+ readonly providerCode?: string;
1055
+ readonly bodyText: string;
1056
+ constructor(status: number, bodyText: string);
1057
+ }
1058
+ /**
1059
+ * Classify an OpenAI-compatible error into `ClassifiedError`.
1060
+ *
1061
+ * Recognizes:
1062
+ * - `AbortError` (from fetch) → `aborted`.
1063
+ * - `OpenAICompatHttpError` with a context-exceeded code or message → `context_exceeded`.
1064
+ * - Any other `OpenAICompatHttpError` → `provider_error`.
1065
+ *
1066
+ * Returns `null` for unrecognized error shapes (the loop falls back to `AgentProviderError`).
1067
+ */
1068
+ declare function classifyOpenAICompatError(err: unknown): ClassifiedError | null;
1069
+ /**
1070
+ * Map an OpenAI-compatible `finish_reason` string to the zidane `TurnFinishReason` union.
1071
+ */
1072
+ declare function mapOAIFinishReason(reason: string | null | undefined): TurnFinishReason | undefined;
1073
+ /**
1074
+ * Auth header config. `scheme` is prepended to the api key with a space, e.g.
1075
+ * `{ name: 'Authorization', scheme: 'Bearer' }` → `Authorization: Bearer <key>`.
1076
+ * Omit `scheme` for raw header values (e.g. `{ name: 'X-Api-Key' }` → `X-Api-Key: <key>`).
1077
+ *
1078
+ * Real-world examples:
1079
+ * - Default OpenAI / OpenRouter / Cerebras: `{ name: 'Authorization', scheme: 'Bearer' }`.
1080
+ * - Baseten: `{ name: 'Authorization', scheme: 'Api-Key' }`.
1081
+ * - Some gateways: `{ name: 'X-Api-Key' }`.
1082
+ */
1083
+ interface OpenAICompatAuthHeader {
1084
+ name: string;
1085
+ scheme?: string;
1086
+ }
1087
+ interface OpenAICompatParams {
1088
+ /** Bearer-style API key. */
1089
+ apiKey: string;
1090
+ /** Base URL — `/chat/completions` is appended. */
1091
+ baseURL: string;
1092
+ /** Default model id when `run({ model })` is omitted. */
1093
+ defaultModel?: string;
1094
+ /** Provider name exposed as `Provider.name`. Defaults to `'openai-compat'`. */
1095
+ name?: string;
1096
+ /** Auth header shape. Defaults to `{ name: 'Authorization', scheme: 'Bearer' }`. */
1097
+ authHeader?: OpenAICompatAuthHeader;
1098
+ /** Extra headers sent with every request (e.g. referer, user-agent). */
1099
+ extraHeaders?: Record<string, string>;
1100
+ /**
1101
+ * Provider-level capability flags. Routed into the message shaper and the
1102
+ * agent loop so images in tool results + user messages are handled correctly
1103
+ * for the underlying model.
1104
+ *
1105
+ * Defaults when omitted: `vision: false`, `imageInToolResult: false` — a
1106
+ * conservative assumption matching most OSS text-only OpenAI-compat
1107
+ * endpoints. Override when routing to a known vision-capable endpoint
1108
+ * (e.g. OpenRouter vision models, Baseten image-capable deployments).
1109
+ */
1110
+ capabilities?: ProviderCapabilities;
1111
+ /**
1112
+ * Whether this endpoint honors `cache_control: { type: 'ephemeral' }` markers
1113
+ * on message content parts and tool definitions.
1114
+ *
1115
+ * - `true` — inject markers when the caller asks for caching. OpenRouter routes
1116
+ * to Anthropic/Gemini forward the markers; routes to OpenAI/DeepSeek/
1117
+ * Grok/Groq/Moonshot ignore them (those backends cache automatically).
1118
+ * - `false` — never inject markers. Safe default for endpoints that strictly
1119
+ * validate the request schema (OpenAI direct, most OSS inference
1120
+ * servers) and would reject unknown fields.
1121
+ *
1122
+ * Default: `false`. The `openrouter` wrapper sets this to `true`.
1123
+ */
1124
+ cacheBreakpoints?: boolean;
1125
+ /**
1126
+ * Whether this endpoint speaks OpenRouter's normalized reasoning envelope —
1127
+ * `reasoning: { effort | max_tokens | exclude }` on requests and structured
1128
+ * `reasoning_details[]` on assistant messages, round-tripped to preserve
1129
+ * extended-reasoning state across turns.
1130
+ *
1131
+ * - `true` — map zidane's `behavior.thinking` / `behavior.thinkingBudget` to
1132
+ * the request's `reasoning` field, capture `reasoning_details`
1133
+ * from streaming responses into `provider_reasoning` blocks, and
1134
+ * echo them back on subsequent assistant messages.
1135
+ * - `false` — never set the field; drop any stored `provider_reasoning`
1136
+ * blocks before sending. Safe default for hosts that strict-
1137
+ * validate the request schema.
1138
+ *
1139
+ * Default: `false`. The `openrouter` wrapper sets this to `true`.
1140
+ */
1141
+ supportsReasoning?: boolean;
1142
+ /**
1143
+ * Generic pass-through for fields on the Chat Completions request body that
1144
+ * zidane does not yet type. Spread into the request before the typed core
1145
+ * (model / messages / tools / max_tokens / stream / tool_choice), so
1146
+ * explicit options always win on collision.
1147
+ *
1148
+ * Forward-compat escape hatch for endpoints that ship one-off fields ahead
1149
+ * of zidane (e.g. OpenAI `reasoning_effort`, OpenRouter `provider` routing,
1150
+ * vendor-specific `safety_level` knobs).
1151
+ */
1152
+ extraBodyParams?: Record<string, unknown>;
1153
+ }
1154
+ /**
1155
+ * Factory for any OpenAI-compatible HTTP endpoint.
1156
+ *
1157
+ * Speaks the standard `POST /chat/completions` + `stream: true` + SSE dialect.
1158
+ * Thin wrappers (`openrouter`, `cerebras`) call this with pinned defaults.
1159
+ *
1160
+ * @example Baseten (non-standard auth scheme)
1161
+ * ```ts
1162
+ * openaiCompat({
1163
+ * name: 'baseten',
1164
+ * apiKey: process.env.BASETEN_API_KEY!,
1165
+ * baseURL: process.env.BASETEN_PROXY_URL!,
1166
+ * authHeader: { name: 'Authorization', scheme: 'Api-Key' },
1167
+ * })
1168
+ * ```
1169
+ */
1170
+ declare function openaiCompat(params: OpenAICompatParams): Provider;
1171
+ //#endregion
1172
+ //#region src/providers/openrouter.d.ts
1173
+ interface OpenRouterParams {
1174
+ apiKey?: string;
1175
+ defaultModel?: string;
1176
+ /**
1177
+ * Provider capability flags. OpenRouter itself is a router — whether vision or
1178
+ * native image-in-tool-result are supported depends on the downstream model.
1179
+ * Default: `{ vision: true, imageInToolResult: false }` — matches the default
1180
+ * `anthropic/claude-sonnet-4-6` model (vision-capable via companion user-message
1181
+ * fallback since OpenRouter exposes Claude over the Chat Completions dialect).
1182
+ *
1183
+ * Override when routing to a known-text-only model (e.g. `meta-llama/llama-3-8b-instruct`).
1184
+ */
1185
+ capabilities?: ProviderCapabilities;
1186
+ }
1187
+ /**
1188
+ * OpenRouter provider.
1189
+ *
1190
+ * Thin wrapper around {@link openaiCompat} with OpenRouter-specific defaults
1191
+ * (base URL, default model) and required attribution headers.
1192
+ */
1193
+ declare function openrouter(params?: OpenRouterParams): Provider;
1194
+ //#endregion
1195
+ //#region src/providers/index.d.ts
1196
+ interface ToolSpec {
1197
+ name: string;
1198
+ description: string;
1199
+ inputSchema: Record<string, unknown>;
1200
+ }
1201
+ interface ToolCall {
1202
+ id: string;
1203
+ name: string;
1204
+ input: Record<string, unknown>;
1205
+ }
1206
+ interface ToolResult {
1207
+ id: string;
1208
+ /**
1209
+ * Tool output — plain string for text-only tools (the common case) or a structured
1210
+ * array of content blocks for tools that return images or mixed content (e.g. an
1211
+ * MCP browser server returning a screenshot).
1212
+ *
1213
+ * Use `toolResultToText(content)` when a downstream consumer only handles strings.
1214
+ */
1215
+ content: string | ToolResultContent[];
1216
+ }
1217
+ /**
1218
+ * Provider-level capability flags used by the agent loop to route tool results
1219
+ * and user messages appropriately.
1220
+ *
1221
+ * When a flag is `undefined` (omitted), the loop applies the conservative
1222
+ * text-only default — images are stripped and replaced with a text marker so
1223
+ * non-vision models do not confabulate about content they cannot see.
1224
+ */
1225
+ interface ProviderCapabilities {
1226
+ /**
1227
+ * Model accepts image input anywhere (user messages and tool results).
1228
+ *
1229
+ * When `false`, the loop replaces image blocks with
1230
+ * `"[image omitted — model does not support vision]"` before they reach the provider.
1231
+ * Gives the model an honest marker instead of letting JSON-stringified base64 slip
1232
+ * through and get confabulated over.
1233
+ */
1234
+ vision?: boolean;
1235
+ /**
1236
+ * Provider wire format embeds images inside tool-role messages natively
1237
+ * (Anthropic `tool_result.content` arrays, OpenAI Codex pi-ai `toolResult` blocks).
1238
+ *
1239
+ * When `false`, a vision-capable provider still gets images — but via a
1240
+ * companion `user` message emitted immediately after the flattened
1241
+ * `tool`/`tool_result` marker. This is the Claude Desktop / Cline pattern
1242
+ * and works on any OpenAI Chat Completions endpoint that accepts image
1243
+ * URLs in user messages.
1244
+ */
1245
+ imageInToolResult?: boolean;
1246
+ }
1247
+ interface StreamCallbacks {
1248
+ onText: (delta: string) => void;
1249
+ onThinking?: (delta: string) => void;
1250
+ onOAuthRefresh?: (ctx: OAuthRefreshHookContext) => void | Promise<void>;
1251
+ }
1252
+ interface TurnResult {
1253
+ /** Full assistant turn as a SessionMessage */
1254
+ assistantMessage: SessionMessage;
1255
+ /** Text content blocks concatenated */
1256
+ text: string;
1257
+ /** Tool calls requested by the model */
1258
+ toolCalls: ToolCall[];
1259
+ /** Whether the model wants to stop */
1260
+ done: boolean;
1261
+ usage: TurnUsage;
1262
+ }
1263
+ interface StreamOptions {
1264
+ model: string;
1265
+ system: string;
1266
+ tools: unknown[];
1267
+ messages: SessionMessage[];
1268
+ maxTokens: number;
1269
+ /** Thinking/reasoning level (optional, default: off) */
1270
+ thinking?: ThinkingLevel;
1271
+ /** Exact thinking token budget — overrides the level-based default when set */
1272
+ thinkingBudget?: number;
1273
+ /** Force tool selection behavior */
1274
+ toolChoice?: {
1275
+ type: 'auto' | 'required' | 'tool';
1276
+ name?: string;
1277
+ };
1278
+ /**
1279
+ * Enable prompt caching on this call. When `true`, providers that support it
1280
+ * insert `cache_control` breakpoints on the system prompt, last tool, and
1281
+ * last stable message so the shared prefix is cached across turns.
1282
+ *
1283
+ * Default: `false` (providers opt callers in — the agent loop passes `true`).
1284
+ */
1285
+ cache?: boolean;
1286
+ /** Abort signal for cancellation */
1287
+ signal?: AbortSignal;
1288
+ }
1289
+ interface Provider {
1290
+ readonly name: string;
1291
+ readonly meta: {
1292
+ defaultModel: string; /** Provider-level capability flags. See {@link ProviderCapabilities}. */
1293
+ capabilities?: ProviderCapabilities;
1294
+ } & Record<string, unknown>;
1295
+ /** Format tool specs for this provider */
1296
+ formatTools: (tools: ToolSpec[]) => unknown[];
1297
+ /** Create a text-only user message. Multimodal content goes through `promptMessage`. */
1298
+ userMessage: (content: string) => SessionMessage;
1299
+ /** Create an assistant message (for priming) */
1300
+ assistantMessage: (content: string) => SessionMessage;
1301
+ /** Create a tool results message to send back */
1302
+ toolResultsMessage: (results: ToolResult[]) => SessionMessage;
1303
+ /** Stream a turn, calling onText for each text delta */
1304
+ stream: (options: StreamOptions, callbacks: StreamCallbacks) => Promise<TurnResult>;
1305
+ /**
1306
+ * Build a user `SessionMessage` from multimodal prompt parts.
1307
+ *
1308
+ * Providers that cannot handle a particular part type (e.g. document) should throw.
1309
+ * The agent loop always canonicalizes the run-level prompt into parts before calling
1310
+ * this method; providers may fall back to `userMessage` for the text-only path if
1311
+ * they do not implement this.
1312
+ */
1313
+ promptMessage?: (parts: PromptPart[]) => SessionMessage;
1314
+ /**
1315
+ * Classify a native provider error for downstream typed-error wrapping.
1316
+ *
1317
+ * Return `null` when the error is not recognized — the loop will wrap it in
1318
+ * `AgentProviderError` with the provider's name. Return a `ClassifiedError` to
1319
+ * route it to one of the typed error classes.
1320
+ */
1321
+ classifyError?: (err: unknown) => ClassifiedError | null;
1322
+ }
1323
+ //#endregion
1324
+ //#region src/session/file-map.d.ts
1325
+ /**
1326
+ * Host-provided file-map adapter. Three methods exchanging `Record<string, string>`
1327
+ * payloads — the whole persistence surface the wrapper needs.
1328
+ */
1329
+ interface FileMapAdapter {
1330
+ /** Load the current file map. Returns an empty `files` record when nothing is persisted. */
1331
+ get: () => Promise<{
1332
+ files: Record<string, string>;
1333
+ }>;
1334
+ /** Replace the persisted file map. Full-rewrite semantics. */
1335
+ save: (files: Record<string, string>) => Promise<void>;
1336
+ /** Delete all persisted state. */
1337
+ delete: () => Promise<void>;
1338
+ }
1339
+ interface FileMapStoreOptions {
1340
+ /** Filename for the JSONL turns log. Default: `turns.jsonl`. */
1341
+ turnsFile?: string;
1342
+ /** Filename for the metadata JSON. Default: `meta.json`. */
1343
+ metaFile?: string;
1344
+ }
1345
+ /**
1346
+ * Create a single-session `SessionStore` backed by a file-map adapter.
1347
+ *
1348
+ * @example
1349
+ * ```ts
1350
+ * const session = await createSession({
1351
+ * store: createFileMapStore(hostSessionStore),
1352
+ * })
1353
+ * ```
1354
+ */
1355
+ declare function createFileMapStore(adapter: FileMapAdapter, options?: FileMapStoreOptions): SessionStore;
1356
+ //#endregion
1357
+ //#region src/session/memory.d.ts
1358
+ declare function createMemoryStore(): SessionStore;
1359
+ //#endregion
1360
+ //#region src/session/messages.d.ts
1361
+ declare function fromAnthropic(msg: {
1362
+ role: string;
1363
+ content: unknown;
1364
+ }): SessionMessage;
1365
+ declare function fromOpenAI(msg: {
1366
+ role: string;
1367
+ content: unknown;
1368
+ }): SessionMessage;
1369
+ declare function toAnthropic(msg: SessionMessage): {
1370
+ role: string;
1371
+ content: unknown;
1372
+ };
1373
+ declare function toOpenAI(msg: SessionMessage): {
1374
+ role: string;
1375
+ content: unknown;
1376
+ };
1377
+ declare function autoDetectAndConvert(msg: {
1378
+ role: string;
1379
+ content: unknown;
1380
+ }): SessionMessage;
1381
+ //#endregion
1382
+ //#region src/session/remote.d.ts
1383
+ interface RemoteStoreOptions {
1384
+ /** Base URL of the session API */
1385
+ url: string;
1386
+ /** Optional headers (e.g. for authentication) */
1387
+ headers?: Record<string, string>;
1388
+ }
1389
+ declare function createRemoteStore(options: RemoteStoreOptions): SessionStore;
1390
+ //#endregion
1391
+ //#region src/session/index.d.ts
1392
+ interface SessionRun {
1393
+ id: string;
1394
+ startedAt: number;
1395
+ endedAt?: number;
1396
+ prompt: string;
1397
+ status: 'running' | 'completed' | 'aborted' | 'error';
1398
+ turns?: number;
1399
+ tokensIn?: number;
1400
+ tokensOut?: number;
1401
+ error?: string;
1402
+ /** Per-turn usage breakdown */
1403
+ turnUsage?: TurnUsage[];
1404
+ /** Total usage across all turns */
1405
+ totalUsage?: TurnUsage;
1406
+ /** Estimated cost in USD */
1407
+ cost?: number;
1408
+ /**
1409
+ * The run that spawned this one, when the agent is a subagent sharing its
1410
+ * parent's session. Undefined on top-level `agent.run()`. Consumers can walk
1411
+ * `runs` by `parentRunId` to reconstruct the subagent tree.
1412
+ */
1413
+ parentRunId?: string;
1414
+ /**
1415
+ * Zero-based subagent depth. 0 = top-level run, 1 = direct child, …
1416
+ * Recorded here so hosts can query/filter by level without walking the tree.
1417
+ */
1418
+ depth?: number;
1419
+ }
1420
+ interface SessionData {
1421
+ id: string;
1422
+ agentId?: string;
1423
+ turns: SessionTurn[];
1424
+ runs: SessionRun[];
1425
+ status: 'idle' | 'running' | 'completed' | 'error';
1426
+ metadata: Record<string, unknown>;
1427
+ createdAt: number;
1428
+ updatedAt: number;
1429
+ }
1430
+ interface SessionStore {
1431
+ /** Optional: generate a session ID server-side (e.g. Supabase UUID). */
1432
+ generateSessionId?: () => string | Promise<string>;
1433
+ /** Optional: generate a turn ID server-side. */
1434
+ generateTurnId?: () => string | Promise<string>;
1435
+ /** Load a session by ID. Returns null if not found. */
1436
+ load: (sessionId: string) => Promise<SessionData | null>;
1437
+ /** Save a session (create or update, full document). */
1438
+ save: (session: SessionData) => Promise<void>;
1439
+ /** Delete a session. */
1440
+ delete: (sessionId: string) => Promise<void>;
1441
+ /** List session IDs, optionally filtered. */
1442
+ list: (filter?: {
1443
+ agentId?: string;
1444
+ limit?: number;
1445
+ }) => Promise<string[]>;
1446
+ /** Append new turns to a session (incremental, avoids full re-save). */
1447
+ appendTurns: (sessionId: string, turns: SessionTurn[]) => Promise<void>;
1448
+ /** Return a slice of turns for a session. */
1449
+ getTurns: (sessionId: string, from?: number, limit?: number) => Promise<SessionTurn[]>;
1450
+ /** Persist an updated run record (called after completeRun / abortRun / errorRun). */
1451
+ updateRun: (sessionId: string, run: SessionRun) => Promise<void>;
1452
+ /** Update the top-level status of a session. */
1453
+ updateStatus: (sessionId: string, status: SessionData['status']) => Promise<void>;
1454
+ }
1455
+ interface Session {
1456
+ /** Session ID */
1457
+ readonly id: string;
1458
+ /** Agent ID (optional label) */
1459
+ readonly agentId?: string;
1460
+ /** Current turn history */
1461
+ readonly turns: SessionTurn[];
1462
+ /**
1463
+ * True when this session has no turns yet.
1464
+ *
1465
+ * Use this as a first-prompt signal when setting up a run — e.g. writing initial
1466
+ * configuration only on fresh sessions. Equivalent to `turns.length === 0`.
1467
+ */
1468
+ readonly isEmpty: boolean;
1469
+ /** Top-level session status */
1470
+ readonly status: SessionData['status'];
1471
+ /** All runs in this session */
1472
+ readonly runs: SessionRun[];
1473
+ /** Arbitrary metadata */
1474
+ readonly metadata: Record<string, unknown>;
1475
+ /**
1476
+ * Start tracking a new run. `extras.parentRunId` + `extras.depth` are
1477
+ * populated by the spawn tool when a child agent shares its parent's
1478
+ * session; regular top-level `agent.run()` calls omit them.
1479
+ */
1480
+ startRun: (runId: string, prompt?: string, extras?: {
1481
+ parentRunId?: string;
1482
+ depth?: number;
1483
+ }) => void;
1484
+ /** Mark a run as completed */
1485
+ completeRun: (runId: string, stats: {
1486
+ turns: number;
1487
+ tokensIn: number;
1488
+ tokensOut: number;
1489
+ turnUsage?: TurnUsage[];
1490
+ cost?: number;
1491
+ }) => void;
1492
+ /** Mark a run as aborted */
1493
+ abortRun: (runId: string) => void;
1494
+ /** Mark a run as errored */
1495
+ errorRun: (runId: string, error: string) => void;
1496
+ /** Append turns to in-memory history AND persist via store.appendTurns (if store present) */
1497
+ appendTurns: (turns: SessionTurn[]) => Promise<void>;
1498
+ /** Replace all turns in-memory (does not persist — use save() for that) */
1499
+ setTurns: (turns: SessionTurn[]) => void;
1500
+ /** Update the session status in memory AND via store.updateStatus (if store present) */
1501
+ updateStatus: (status: SessionData['status']) => Promise<void>;
1502
+ /** Persist an updated run record via store.updateRun (if store present) */
1503
+ updateRun: (run: SessionRun) => Promise<void>;
1504
+ /** Generate a turn ID using store.generateTurnId if available, else crypto.randomUUID() */
1505
+ generateTurnId: () => string | Promise<string>;
1506
+ /** Set metadata key */
1507
+ setMeta: (key: string, value: unknown) => void;
1508
+ /** Persist the full session document to the store */
1509
+ save: () => Promise<void>;
1510
+ /** Serialize to SessionData */
1511
+ toJSON: () => SessionData;
1512
+ }
1513
+ interface CreateSessionOptions {
1514
+ /** Session ID. If omitted and store provides generateSessionId, that is used. */
1515
+ id?: string;
1516
+ /** Agent ID label */
1517
+ agentId?: string;
1518
+ /** Initial metadata */
1519
+ metadata?: Record<string, unknown>;
1520
+ /** Storage backend (optional, enables save/load) */
1521
+ store?: SessionStore;
1522
+ _data?: SessionData;
1523
+ }
1524
+ /**
1525
+ * Create a new session.
1526
+ * Async so stores that generate IDs server-side (e.g. Supabase) can be supported.
1527
+ */
1528
+ declare function createSession(options?: CreateSessionOptions): Promise<Session>;
1529
+ /**
1530
+ * Load an existing session from a store.
1531
+ */
1532
+ declare function loadSession(store: SessionStore, sessionId: string): Promise<Session | null>;
1533
+ //#endregion
1534
+ //#region src/skills/types.d.ts
1535
+ /**
1536
+ * Types for the Agent Skills system.
1537
+ *
1538
+ * Follows the Agent Skills open standard (agentskills.io/specification).
1539
+ * Zidane-specific metadata conventionally uses the `zidane.` key prefix
1540
+ * (e.g. `metadata['zidane.paths']`) to stay spec-compliant.
1541
+ */
1542
+ interface SkillResource {
1543
+ /** Relative path from skill directory */
1544
+ path: string;
1545
+ /** Resource type inferred from directory */
1546
+ type: 'script' | 'reference' | 'asset' | 'other';
1547
+ }
1548
+ /**
1549
+ * Where the skill came from. Used for collision precedence (project beats user)
1550
+ * and for host SDKs to gate project-level skills on a trust check.
1551
+ */
1552
+ type SkillSource = 'project' | 'user' | 'inline' | 'builtin';
1553
+ /** Severity + code for lenient-load warnings surfaced to host UIs. */
1554
+ interface SkillDiagnostic {
1555
+ severity: 'warning' | 'error';
1556
+ /** Stable machine-readable code (e.g. `name-mismatch-directory`). */
1557
+ code: string;
1558
+ /** Human-readable description. */
1559
+ message: string;
1560
+ /** Optional frontmatter field name the diagnostic relates to. */
1561
+ field?: string;
1562
+ }
1563
+ interface SkillConfig {
1564
+ /** Skill name: 1-64 chars, lowercase alphanumeric + hyphens */
1565
+ name: string;
1566
+ /** What the skill does and when to use it (1-1024 chars) */
1567
+ description: string;
1568
+ /** The SKILL.md body content (after YAML frontmatter) */
1569
+ instructions: string;
1570
+ /**
1571
+ * Where this skill was loaded from. Drives collision precedence and the
1572
+ * `trustProjectSkills` gate. Optional — `parseSkillFile` stamps it; raw
1573
+ * fixtures that omit it are treated as `'project'` by downstream readers.
1574
+ */
1575
+ source?: SkillSource;
1576
+ /** Absolute path to SKILL.md (undefined for inline skills) */
1577
+ location?: string;
1578
+ /** Skill directory path for resolving relative references */
1579
+ baseDir?: string;
1580
+ /** License identifier or reference */
1581
+ license?: string;
1582
+ /** Environment requirements */
1583
+ compatibility?: string;
1584
+ /**
1585
+ * Flat key-value metadata bag per the spec. For Zidane-specific hints,
1586
+ * use the `zidane.` key prefix (e.g. `metadata['zidane.paths']`).
1587
+ */
1588
+ metadata?: Record<string, string>;
1589
+ /** Pre-approved tool names (experimental per spec) */
1590
+ allowedTools?: string[];
1591
+ /** Bundled resource files discovered in the skill directory */
1592
+ resources?: SkillResource[];
1593
+ /**
1594
+ * Lenient-load warnings recorded during parsing. Host SDKs can surface these
1595
+ * as inline UI hints. Absent when no issues were found.
1596
+ */
1597
+ diagnostics?: SkillDiagnostic[];
1598
+ }
1599
+ interface SkillsConfig {
1600
+ /**
1601
+ * Control which skills are active.
1602
+ * - `true` (default): all discovered skills are enabled
1603
+ * - `false` or `[]`: fully disable the skills system (no resolution, no catalog, no hooks)
1604
+ * - `string[]`: allowlist — only skills with matching names are enabled
1605
+ */
1606
+ enabled?: boolean | string[];
1607
+ /** Directories to scan for SKILL.md files */
1608
+ scan?: string[];
1609
+ /** Dynamic skills written to disk at agent start, then loaded normally */
1610
+ write?: SkillConfig[];
1611
+ /** Skill names to exclude from the catalog */
1612
+ exclude?: string[];
1613
+ /** Skip default scan paths (~/.agents/skills, .zidane/skills, etc.) */
1614
+ skipDefaultPaths?: boolean;
1615
+ /**
1616
+ * Auto-inject `skills_use` / `skills_read` / `skills_run_script` tools
1617
+ * when the catalog is non-empty. Default `true`. Set `false` to opt out
1618
+ * (the system prompt will then instruct the model to use its file-read
1619
+ * tool instead).
1620
+ */
1621
+ tool?: boolean;
1622
+ /**
1623
+ * Cap on concurrently active skills per run. Default `undefined` (unlimited).
1624
+ * Attempts to activate past the cap throw from `skills_use`.
1625
+ */
1626
+ maxActive?: number;
1627
+ /** Script timeout for `skills_run_script`, in milliseconds. Default `60000`. */
1628
+ scriptTimeoutMs?: number;
1629
+ /**
1630
+ * When `false`, skills with `source: 'project'` are skipped during
1631
+ * resolution with a diagnostic. Default `true` (preserves existing behavior).
1632
+ * Useful for host SDKs handling untrusted repositories.
1633
+ */
1634
+ trustProjectSkills?: boolean;
1635
+ }
1636
+ //#endregion
1637
+ //#region src/tools/types.d.ts
1638
+ /**
1639
+ * Runtime context passed to every tool execution.
1640
+ * Provides access to the agent's provider, abort signal, execution environment, and hooks.
1641
+ *
1642
+ * The preset-y fields (`name`, `system`, `tools`, `toolAliases`, `mcpServers`, `skills`,
1643
+ * `behavior`) mirror the agent's own options so child-spawning tools can inherit them.
1644
+ */
1645
+ interface ToolContext {
1646
+ /** The LLM provider for this agent run */
1647
+ provider: Provider;
1648
+ /** Abort signal — tools should check this for early termination */
1649
+ signal: AbortSignal;
1650
+ /** The execution context (shell, filesystem, etc.) */
1651
+ execution: ExecutionContext;
1652
+ /** The active execution handle for the current agent run */
1653
+ handle: ExecutionHandle;
1654
+ /** Agent hooks for emitting events (e.g. spawn:complete) */
1655
+ hooks: Hookable<AgentHooks>;
1656
+ /** Agent display name (preset or user-supplied) */
1657
+ name?: string;
1658
+ /** Agent default system prompt */
1659
+ system?: string;
1660
+ /** Source tool map the agent was created with (pre-MCP-merge, pre-skills-injection) */
1661
+ tools: Record<string, ToolDef>;
1662
+ /**
1663
+ * Map canonical tool names to LLM-facing (aliased) names.
1664
+ *
1665
+ * Aliasing is **LLM-boundary-only**:
1666
+ * - The alias is what the provider's tool spec carries, what the model calls it, and
1667
+ * what appears in `ToolHookContext.displayName` / `McpToolHookContext.displayName`.
1668
+ * - The canonical name is what lives in `session.turns`, `ToolHookContext.name`, and
1669
+ * what the agent uses to look up the tool implementation. Alias changes never
1670
+ * desync persisted history.
1671
+ */
1672
+ toolAliases?: Record<string, string>;
1673
+ /** MCP servers configured on the agent (for child inheritance) */
1674
+ mcpServers?: McpServerConfig[];
1675
+ /** Skills configuration (for child inheritance) */
1676
+ skills?: SkillsConfig;
1677
+ /** Behavior defaults (for child inheritance) */
1678
+ behavior?: AgentBehavior;
1679
+ /** Turn ID that requested this tool call */
1680
+ turnId: string;
1681
+ /** Tool call ID from the model */
1682
+ callId: string;
1683
+ /**
1684
+ * The run id this tool call is part of. Populated by the agent loop when
1685
+ * invoking tools. Optional on the type so host code constructing contexts
1686
+ * by hand (tests, direct tool invocations) doesn't have to synthesize one.
1687
+ *
1688
+ * Spawn-style tools rely on this to tag child runs with `parentRunId` so
1689
+ * the subagent tree can be reconstructed from a persisted session.
1690
+ */
1691
+ runId?: string;
1692
+ /**
1693
+ * The agent's session, when one was provided to `createAgent`. Tools that
1694
+ * want to persist their own state (or, in the case of `spawn`, inherit the
1695
+ * parent's session for child persistence) can read from here.
1696
+ */
1697
+ session?: Session;
1698
+ /**
1699
+ * Subagent depth for the agent owning this tool call. 0 = top-level,
1700
+ * 1 = first-level child, … Used by spawn to enforce a `maxDepth` cap.
1701
+ * Undefined is treated as 0 by spawn.
1702
+ */
1703
+ depth?: number;
1704
+ }
1705
+ interface ToolDef {
1706
+ spec: ToolSpec;
1707
+ /**
1708
+ * Execute the tool and return its output.
1709
+ *
1710
+ * Return a plain string for text-only tools (the common case). Return a
1711
+ * `ToolResultContent[]` when the tool produces non-text content (images, mixed
1712
+ * text+image) that the provider can route through natively (Anthropic
1713
+ * `tool_result.content` arrays, OpenAI Codex pi-ai) or through the
1714
+ * companion-user-message fallback (OpenAI Chat Completions).
1715
+ */
1716
+ execute: (input: Record<string, unknown>, ctx: ToolContext) => Promise<string | ToolResultContent[]>;
1717
+ }
1718
+ type ToolMap = Map<string, ToolDef>;
1719
+ //#endregion
1720
+ //#region src/mcp/index.d.ts
1721
+ interface McpConnection {
1722
+ tools: Record<string, ToolDef>;
1723
+ close: () => Promise<void>;
1724
+ }
1725
+ /**
1726
+ * Normalize MCP server configs from any common shape to `McpServerConfig[]`.
1727
+ *
1728
+ * Accepts:
1729
+ * - `McpServerConfig[]` — zidane native (pass-through).
1730
+ * - `McpServerConfig` — a single config object (wrapped to a 1-element array).
1731
+ * - `Record<string, RawShape>` — name-keyed map (common in host-SDK configs), where the key is the server name.
1732
+ * - Mixed shapes with `type` vs `transport`, `httpUrl`/`sseUrl` vs `url`.
1733
+ *
1734
+ * Returns `[]` when `input` is nullish. Throws a descriptive error when the transport
1735
+ * cannot be inferred from a given entry, or when the input shape is unsupported.
1736
+ */
1737
+ declare function normalizeMcpServers(input: unknown): McpServerConfig[];
1738
+ /**
1739
+ * Lossy flattener — converts MCP `CallToolResult.content` blocks to a single
1740
+ * string. Text blocks are extracted; non-text blocks are JSON-stringified.
1741
+ *
1742
+ * Use this only at UI / log boundaries that require a string. The agent
1743
+ * loop itself routes through {@link normalizeMcpBlocks} so image blocks
1744
+ * survive into provider-native tool_result content (Anthropic blocks,
1745
+ * OpenAI companion-user-message).
1746
+ */
1747
+ declare function resultToString(content: unknown[]): string;
1748
+ /**
1749
+ * Normalize MCP `CallToolResult.content` to zidane's {@link ToolResultContent[]} shape.
1750
+ *
1751
+ * Handles the four MCP content block types:
1752
+ * - `text` → preserved as `{type:'text', text}`
1753
+ * - `image` → preserved as `{type:'image', mediaType, data}` (MCP uses `mimeType`)
1754
+ * - `resource` with embedded text → flattened to a text block
1755
+ * - `resource` with embedded blob whose `mimeType` is `image/*` → flattened to an image block
1756
+ * - Any unrecognized block → JSON-stringified fallback text block (lossy but safe)
1757
+ *
1758
+ * Returns `null` when the input is not an array — callers should fall back to an empty
1759
+ * result in that case.
1760
+ */
1761
+ declare function normalizeMcpBlocks(content: unknown): ToolResultContent[] | null;
1762
+ /**
1763
+ * Connect to MCP servers and discover their tools.
1764
+ *
1765
+ * Each tool is namespaced as `mcp_{serverName}_{toolName}` to avoid
1766
+ * collisions with agent tools or tools from other servers.
1767
+ *
1768
+ * @param configs - Array of MCP server configurations
1769
+ * @param _clientFactory - Internal: override client construction for testing
1770
+ * @param hooks - Optional agent hooks for firing mcp:connect, mcp:error, mcp:close events
1771
+ */
1772
+ declare function connectMcpServers(configs: McpServerConfig[], _clientFactory?: () => Client, hooks?: Hookable<AgentHooks>): Promise<McpConnection>;
1773
+ //#endregion
1774
+ //#region src/skills/activation.d.ts
1775
+ /** How a skill was activated. Surfaced in `skills:activate` hook ctx. */
1776
+ type ActivationVia = 'model' | 'explicit' | 'resume';
1777
+ /** Reason a skill was deactivated. Surfaced in `skills:deactivate` hook ctx. */
1778
+ type DeactivationReason = 'run-end' | 'explicit' | 'reset';
1779
+ /** A skill currently active in the state machine. */
1780
+ interface ActiveSkill {
1781
+ skill: SkillConfig;
1782
+ activatedAt: number;
1783
+ activatedVia: ActivationVia;
1784
+ }
1785
+ /**
1786
+ * Per-agent skill activation state. Public read-surface is the `active()` list
1787
+ * and `isActive(name)` predicate; writes go through `activate()` / `deactivate()`.
1788
+ */
1789
+ interface SkillActivationState {
1790
+ /** List of currently active skills in activation order. Returns a snapshot. */
1791
+ active: () => readonly ActiveSkill[];
1792
+ /** Is the skill with this canonical name currently active? */
1793
+ isActive: (name: string) => boolean;
1794
+ /** Retrieve the `ActiveSkill` record by name, or `undefined`. */
1795
+ get: (name: string) => ActiveSkill | undefined;
1796
+ /**
1797
+ * Mark a skill as active.
1798
+ * - Returns `'ok'` on a fresh activation (caller should fire `skills:activate`).
1799
+ * - Returns `'already-active'` if the skill was already in the set (idempotent).
1800
+ * - Returns `'cap-reached'` if the `maxActive` cap would be exceeded. State is unchanged.
1801
+ */
1802
+ activate: (skill: SkillConfig, via: ActivationVia) => 'ok' | 'already-active' | 'cap-reached';
1803
+ /**
1804
+ * Mark a skill as inactive. Returns the removed `ActiveSkill` record or `undefined`
1805
+ * if it wasn't active. Callers fire `skills:deactivate` on removal.
1806
+ */
1807
+ deactivate: (name: string) => ActiveSkill | undefined;
1808
+ /** Remove every active skill. Returns the list of removed records. */
1809
+ clear: () => readonly ActiveSkill[];
1810
+ }
1811
+ interface SkillActivationStateOptions {
1812
+ /**
1813
+ * Cap on concurrent activations. `undefined` (the default) disables the cap.
1814
+ * When set, `activate()` returns `'cap-reached'` once the set is at size `maxActive`.
1815
+ */
1816
+ maxActive?: number;
1817
+ }
1818
+ declare function createSkillActivationState(options?: SkillActivationStateOptions): SkillActivationState;
1819
+ //#endregion
1820
+ //#region src/agent.d.ts
1821
+ interface AgentHooks {
1822
+ 'system:before': (ctx: {
1823
+ system: string;
1824
+ }) => void;
1825
+ 'turn:before': (ctx: {
1826
+ turn: number;
1827
+ turnId: string;
1828
+ options: StreamOptions;
1829
+ }) => void;
1830
+ /**
1831
+ * Fires after each assistant turn (before its tool-result follow-up
1832
+ * dispatches; the loop iterates back to a fresh `turn:before` once the
1833
+ * tool results are produced).
1834
+ *
1835
+ * `toolCounts.turn` — calls **emitted** by the model in this assistant
1836
+ * turn, keyed by canonical tool name. Reflects what the model asked for,
1837
+ * regardless of downstream gate outcome. Most useful for spotting per-turn
1838
+ * spikes ("the model called todowrite 4 times in one turn").
1839
+ *
1840
+ * `toolCounts.run` — cumulative running counter of **dispatched** calls
1841
+ * scoped to this `runId`, captured at fire time. Excludes calls that were
1842
+ * `block`ed by `tool:gate` handlers. Includes calls short-circuited via
1843
+ * `tool:gate` `result` substitution (the model still asked, the framework
1844
+ * just answered without the tool running). Resumed sessions start a fresh
1845
+ * run with empty counts.
1846
+ *
1847
+ * Both fields are frozen snapshots; mutate-safe.
1848
+ */
1849
+ 'turn:after': (ctx: {
1850
+ turn: number;
1851
+ turnId: string;
1852
+ usage: TurnUsage;
1853
+ message: SessionTurn;
1854
+ toolCounts: {
1855
+ turn: Readonly<Record<string, number>>;
1856
+ run: Readonly<Record<string, number>>;
1857
+ };
1858
+ }) => void;
1859
+ 'stream:text': (ctx: StreamHookContext & {
1860
+ delta: string;
1861
+ text: string;
1862
+ }) => void;
1863
+ 'stream:end': (ctx: StreamHookContext & {
1864
+ text: string;
1865
+ }) => void;
1866
+ 'stream:thinking': (ctx: StreamHookContext & {
1867
+ delta: string;
1868
+ thinking: string;
1869
+ }) => void;
1870
+ 'oauth:refresh': (ctx: OAuthRefreshHookContext) => void;
1871
+ /**
1872
+ * Fires before validation, `tool:before`, and `execute`. Two ways to
1873
+ * intercept:
1874
+ *
1875
+ * - Set `block = true` (with a `reason`) to refuse the call. The model
1876
+ * sees a `Blocked: <reason>` tool result; `tool:before` / `tool:after`
1877
+ * do **not** fire.
1878
+ * - Set `result` to substitute a successful tool_result and skip
1879
+ * execution. The model sees the substitute as a normal tool_result;
1880
+ * `tool:before` does not fire, but `tool:after` and `tool:transform`
1881
+ * do — so byte budgets, telemetry, and post-mutation hooks see the
1882
+ * substitute. Useful for cache hits, dedup, idempotency guards,
1883
+ * plan-mode synthetic acks.
1884
+ *
1885
+ * If multiple handlers along the chain set both `block` and `result`,
1886
+ * `block` wins — refusal beats substitution, so a policy gate
1887
+ * (skills allow-list, custom security) can always override an upstream
1888
+ * consumer's cache substitute. Mirrors the writable-`result` shape on
1889
+ * `tool:unknown` and `tool:error` so consumers learn one pattern.
1890
+ *
1891
+ * `runToolCounts` — frozen pre-call snapshot of per-tool dispatched
1892
+ * counts in this run. Use it to self-throttle, drive observability, or
1893
+ * implement budget guards. Counts every call that passed gate, including
1894
+ * dedup substitutes (Z19); excludes `block`ed calls.
1895
+ *
1896
+ * **Parallel mode** (`toolExecution: 'parallel'`, the default): the
1897
+ * snapshot is taken before any dispatches in the batch, so consumer
1898
+ * hooks reading `runToolCounts` see the pre-batch view. Built-in
1899
+ * budget / dedup middleware uses internal per-call reservation, so
1900
+ * `behavior.toolBudgets` enforces atomically even within a parallel
1901
+ * batch.
1902
+ */
1903
+ 'tool:gate': (ctx: ToolHookContext & {
1904
+ block: boolean;
1905
+ reason: string;
1906
+ result?: string | ToolResultContent[];
1907
+ runToolCounts: Readonly<Record<string, number>>;
1908
+ }) => void;
1909
+ 'tool:before': (ctx: ToolHookContext & {
1910
+ coercions?: readonly string[];
1911
+ runToolCounts: Readonly<Record<string, number>>;
1912
+ }) => void;
1913
+ 'tool:after': (ctx: ToolHookContext & {
1914
+ result: string | ToolResultContent[];
1915
+ outputBytes: number;
1916
+ coercions?: readonly string[];
1917
+ runToolCounts: Readonly<Record<string, number>>;
1918
+ }) => void;
1919
+ /**
1920
+ * Fires when a tool throws during execution. Mutate `result` to substitute a
1921
+ * tool-output payload that gets sent back to the model in place of the
1922
+ * default `Tool error: <msg>` string — useful for OSS-model error rewriting
1923
+ * (collapse stack traces, hide internal paths, prepend recovery hints).
1924
+ *
1925
+ * The post-hook value flows through `tool:transform` like a normal output, so
1926
+ * downstream byte-budgeting and image-stripping still apply.
1927
+ */
1928
+ 'tool:error': (ctx: ToolHookContext & {
1929
+ error: Error;
1930
+ result?: string | ToolResultContent[];
1931
+ }) => void;
1932
+ 'tool:transform': (ctx: ToolHookContext & {
1933
+ result: string | ToolResultContent[];
1934
+ isError: boolean;
1935
+ outputBytes: number;
1936
+ coercions?: readonly string[];
1937
+ }) => void;
1938
+ /**
1939
+ * Fires before the generic "Unknown tool" error when the model invokes a tool
1940
+ * that isn't registered (hallucinated names, dropped MCP servers, dangling
1941
+ * aliases). Mutate `result` to substitute a friendly response or set
1942
+ * `suppressError: true` to skip the companion `tool:error` emission.
1943
+ *
1944
+ * Fires for any unknown tool name — including hallucinated MCP-style names
1945
+ * (`mcp_supabase_xxx`); branch on `name.startsWith('mcp_')` to differentiate.
1946
+ */
1947
+ 'tool:unknown': (ctx: ToolHookContext & {
1948
+ result?: string | ToolResultContent[];
1949
+ suppressError: boolean;
1950
+ }) => void;
1951
+ /**
1952
+ * Fires when `validateToolArgs` rejects an input that could not be auto-coerced
1953
+ * to satisfy the tool's `inputSchema`. Observational — the tool call still
1954
+ * surfaces a `Validation error: …` string back to the model. Useful for
1955
+ * counting validation failures separately from runtime tool errors.
1956
+ */
1957
+ 'validation:reject': (ctx: ToolHookContext & {
1958
+ reason: string;
1959
+ schema: Record<string, unknown>;
1960
+ }) => void;
1961
+ /**
1962
+ * Fires when `validateToolArgs` successfully auto-coerced one or more input
1963
+ * fields to satisfy the tool's `inputSchema`. **Only fires when at least one
1964
+ * coercion happened** — never on perfectly-shaped inputs. Useful for counting
1965
+ * model "wrongness rate" without re-running validation downstream.
1966
+ *
1967
+ * `coercions` lists the field names that were coerced. The values landed in
1968
+ * the input that the tool actually received; consumers wanting before/after
1969
+ * comparison can re-run `validateToolArgs(ctx.input, ctx.schema)`.
1970
+ */
1971
+ 'validation:coerce': (ctx: ToolHookContext & {
1972
+ coercions: readonly string[];
1973
+ schema: Record<string, unknown>;
1974
+ }) => void;
1975
+ 'context:transform': (ctx: {
1976
+ messages: SessionMessage[];
1977
+ }) => void;
1978
+ /**
1979
+ * Fires per request, after `context:transform` and before the request goes
1980
+ * out. Mutating `ctx.system` updates the system prompt the provider sends
1981
+ * for this turn — useful for runtime-derived sections (e.g. listing files
1982
+ * already read in the session, surfacing live tool budgets, injecting
1983
+ * skill activation reminders).
1984
+ *
1985
+ * Cache breakpoints are applied inside the provider after this hook, so
1986
+ * mutations land in the cache key naturally — repeated turns with the
1987
+ * same derived system text still hit the cache.
1988
+ *
1989
+ * `messages` is read-only here; use `context:transform` for message
1990
+ * surgery. `session` is `undefined` when the run is sessionless.
1991
+ */
1992
+ 'system:transform': (ctx: {
1993
+ system: string;
1994
+ messages: readonly SessionMessage[];
1995
+ turn: number;
1996
+ turnId: string;
1997
+ session?: Session;
1998
+ }) => void;
1999
+ 'steer:inject': (ctx: {
2000
+ message: string;
2001
+ }) => void;
2002
+ 'spawn:before': (ctx: SpawnHookContext) => void;
2003
+ 'spawn:complete': (ctx: ChildRunStats) => void;
2004
+ 'spawn:error': (ctx: SpawnHookContext & {
2005
+ error: Error;
2006
+ }) => void;
2007
+ 'child:stream:text': (ctx: StreamHookContext & {
2008
+ delta: string;
2009
+ text: string;
2010
+ childId: string;
2011
+ depth: number;
2012
+ }) => void;
2013
+ 'child:stream:thinking': (ctx: StreamHookContext & {
2014
+ delta: string;
2015
+ thinking: string;
2016
+ childId: string;
2017
+ depth: number;
2018
+ }) => void;
2019
+ 'child:stream:end': (ctx: StreamHookContext & {
2020
+ text: string;
2021
+ childId: string;
2022
+ depth: number;
2023
+ }) => void;
2024
+ 'child:tool:before': (ctx: ToolHookContext & {
2025
+ coercions?: readonly string[];
2026
+ runToolCounts: Readonly<Record<string, number>>;
2027
+ childId: string;
2028
+ depth: number;
2029
+ }) => void;
2030
+ 'child:tool:after': (ctx: ToolHookContext & {
2031
+ result: string | ToolResultContent[];
2032
+ outputBytes: number;
2033
+ coercions?: readonly string[];
2034
+ runToolCounts: Readonly<Record<string, number>>;
2035
+ childId: string;
2036
+ depth: number;
2037
+ }) => void;
2038
+ 'child:tool:error': (ctx: ToolHookContext & {
2039
+ error: Error;
2040
+ childId: string;
2041
+ depth: number;
2042
+ }) => void;
2043
+ 'child:turn:after': (ctx: {
2044
+ turn: number;
2045
+ turnId: string;
2046
+ usage: TurnUsage;
2047
+ message: SessionTurn;
2048
+ toolCounts: {
2049
+ turn: Readonly<Record<string, number>>;
2050
+ run: Readonly<Record<string, number>>;
2051
+ };
2052
+ childId: string;
2053
+ depth: number;
2054
+ }) => void;
2055
+ 'mcp:connect': (ctx: {
2056
+ name: string;
2057
+ transport: string;
2058
+ tools: string[];
2059
+ }) => void;
2060
+ 'mcp:error': (ctx: {
2061
+ name: string;
2062
+ error: Error;
2063
+ }) => void;
2064
+ 'mcp:close': (ctx: {
2065
+ name: string;
2066
+ }) => void;
2067
+ /**
2068
+ * Fires at the start of a per-server bootstrap attempt, before any network I/O.
2069
+ * Pairs with `mcp:bootstrap:end` and is always emitted, regardless of outcome.
2070
+ */
2071
+ 'mcp:bootstrap:start': (ctx: {
2072
+ name: string;
2073
+ transport: string;
2074
+ }) => void;
2075
+ /**
2076
+ * Fires at the end of a per-server bootstrap attempt. `durationMs` spans from
2077
+ * the matching `mcp:bootstrap:start`. On `ok: false` carries the originating
2078
+ * error so consumers can log / trace without relying on a separate `mcp:error`.
2079
+ */
2080
+ 'mcp:bootstrap:end': (ctx: {
2081
+ name: string;
2082
+ transport: string;
2083
+ durationMs: number;
2084
+ } & ({
2085
+ ok: true;
2086
+ toolCount: number;
2087
+ } | {
2088
+ ok: false;
2089
+ error: Error;
2090
+ })) => void;
2091
+ /**
2092
+ * Fires once per server after `listTools()` and after the config-side filters
2093
+ * (`enabledTools` / `disabledTools` / `toolFilter`) have applied, but BEFORE
2094
+ * tools are registered. Handlers may mutate `ctx.tools` in place — splicing,
2095
+ * reordering, or replacing entries — to further narrow what the model sees.
2096
+ *
2097
+ * Composes with config-side filters: config drops tools the host's static
2098
+ * policy excludes; this hook is the runtime escape hatch for per-user, per-
2099
+ * environment, or capability-driven decisions that the config can't express.
2100
+ *
2101
+ * Items are upstream tool descriptors (NOT yet namespaced as `mcp_<server>_<tool>`).
2102
+ */
2103
+ 'mcp:tools:filter': (ctx: {
2104
+ server: string;
2105
+ transport: 'stdio' | 'sse' | 'streamable-http';
2106
+ tools: Array<{
2107
+ name: string;
2108
+ description?: string | null;
2109
+ inputSchema?: unknown;
2110
+ }>;
2111
+ }) => void;
2112
+ /**
2113
+ * MCP-side counterpart of `tool:gate`. Same shape: set `block` to refuse,
2114
+ * set `result` to substitute a successful payload and skip the upstream
2115
+ * MCP `callTool`. When both are set across the handler chain, `block` wins.
2116
+ *
2117
+ * Fires INSIDE the MCP wrapper's `execute`, after the loop's `tool:gate`
2118
+ * already ran. Does **not** carry `runToolCounts` — those are loop-level
2119
+ * and already exposed on `tool:gate` for MCP tools (which are registered
2120
+ * as agent tools under their namespaced name `mcp_<server>_<tool>`). Use
2121
+ * `tool:gate` for budget / dedup logic; reserve `mcp:tool:gate` for
2122
+ * MCP-specific concerns (per-server routing, transport-aware refusals).
2123
+ */
2124
+ 'mcp:tool:gate': (ctx: McpToolHookContext & {
2125
+ block: boolean;
2126
+ reason: string;
2127
+ result?: string | ToolResultContent[];
2128
+ }) => void;
2129
+ 'mcp:tool:before': (ctx: McpToolHookContext) => void;
2130
+ 'mcp:tool:after': (ctx: McpToolHookContext & {
2131
+ result: string | ToolResultContent[];
2132
+ outputBytes: number;
2133
+ }) => void;
2134
+ 'mcp:tool:transform': (ctx: McpToolHookContext & {
2135
+ result: string | ToolResultContent[];
2136
+ outputBytes: number;
2137
+ }) => void;
2138
+ 'mcp:tool:error': (ctx: McpToolHookContext & {
2139
+ error: Error;
2140
+ }) => void;
2141
+ 'skills:resolve': (ctx: {
2142
+ skills: SkillConfig[];
2143
+ }) => void;
2144
+ 'skills:catalog': (ctx: {
2145
+ catalog: string;
2146
+ skills: SkillConfig[];
2147
+ }) => void;
2148
+ 'skills:activate': (ctx: {
2149
+ skill: SkillConfig;
2150
+ via: ActivationVia;
2151
+ }) => void;
2152
+ 'skills:deactivate': (ctx: {
2153
+ skill: SkillConfig;
2154
+ reason: DeactivationReason;
2155
+ }) => void;
2156
+ 'usage': (ctx: {
2157
+ turn: number;
2158
+ turnId: string;
2159
+ usage: TurnUsage;
2160
+ totalIn: number;
2161
+ totalOut: number;
2162
+ }) => void;
2163
+ 'output': (ctx: {
2164
+ output: Record<string, unknown>;
2165
+ schema: Record<string, unknown>;
2166
+ }) => void;
2167
+ /**
2168
+ * Fires when a turn's total tool-output bytes exceed `behavior.toolOutputBudget`.
2169
+ * Measured post-`tool:transform`. Loop injects a synthetic user message after
2170
+ * the tool-results turn instructing the model to summarize.
2171
+ */
2172
+ 'budget:exceeded': (ctx: {
2173
+ turn: number;
2174
+ turnId: string;
2175
+ bytes: number;
2176
+ budget: number;
2177
+ }) => void;
2178
+ /**
2179
+ * Fires when a per-tool budget configured via `behavior.toolBudgets` is
2180
+ * exceeded for a specific tool. `mode` reflects how the framework reacted:
2181
+ * `'steer'` lets the call run and queues a post-turn nudge; `'block'`
2182
+ * refuses the call outright with `Blocked: <message>`.
2183
+ *
2184
+ * `count` is the run-cumulative dispatched count just before this call.
2185
+ * Use `turnId` to correlate with `turn:after` if you need the integer turn
2186
+ * index. Distinct from `budget:exceeded` (byte-level) so consumers can
2187
+ * subscribe specifically; both can fire in the same turn.
2188
+ */
2189
+ 'tool-budget:exceeded': (ctx: {
2190
+ tool: string;
2191
+ count: number;
2192
+ max: number;
2193
+ turnId: string;
2194
+ mode: 'steer' | 'block';
2195
+ }) => void;
2196
+ 'agent:abort': (ctx: object) => void;
2197
+ /**
2198
+ * Run finished — fires on all exit paths (completion, maxTurns, abort).
2199
+ *
2200
+ * Since 4.0 the `AgentStats` carried here is **cumulative** across the
2201
+ * parent agent loop and every recursively-spawned sub-agent
2202
+ * (`totalIn` / `totalOut` / `cost` / `totalCacheRead` / `totalCacheCreation`).
2203
+ * For parent-loop-only counts use `ctx.turnUsage` (parent-only array);
2204
+ * for tree-wide turn counts use `flattenTurns(ctx).length`.
2205
+ */
2206
+ 'agent:done': (ctx: AgentStats) => void;
2207
+ 'session:start': (ctx: SessionHookContext & {
2208
+ runId: string;
2209
+ prompt: string;
2210
+ }) => void;
2211
+ 'session:end': (ctx: SessionHookContext & {
2212
+ runId: string;
2213
+ status: SessionEndStatus;
2214
+ turnRange: [number, number];
2215
+ }) => void;
2216
+ 'session:turns': (ctx: SessionHookContext & {
2217
+ turns: SessionTurn[];
2218
+ count: number;
2219
+ }) => void;
2220
+ 'session:meta': (ctx: SessionHookContext & {
2221
+ key: string;
2222
+ value: unknown;
2223
+ }) => void;
2224
+ 'session:save': (ctx: SessionHookContext) => void;
2225
+ }
2226
+ interface AgentOptions {
2227
+ provider: Provider;
2228
+ /** Display name for the agent (used in traces/logs). */
2229
+ name?: string;
2230
+ /** Default system prompt injected when no system is provided at run time. */
2231
+ system?: string;
2232
+ /** Tool definitions available to the agent. Defaults to no tools. */
2233
+ tools?: Record<string, ToolDef>;
2234
+ /**
2235
+ * Map canonical tool names to LLM-facing (aliased) names.
2236
+ *
2237
+ * Aliasing is **LLM-boundary-only**: the alias is what the provider's tool spec
2238
+ * carries and what the model calls the tool; the canonical name is what lives in
2239
+ * `session.turns` and what the agent uses to look up the tool implementation.
2240
+ */
2241
+ toolAliases?: Record<string, string>;
2242
+ /** Agent-level behavior defaults (overridden by run-level behavior) */
2243
+ behavior?: AgentBehavior;
2244
+ /** Execution context: where tools run. Defaults to in-process. */
2245
+ execution?: ExecutionContext;
2246
+ /** MCP servers to connect and expose as tools */
2247
+ mcpServers?: McpServerConfig[];
2248
+ /** Session for identity, turn persistence, and run tracking */
2249
+ session?: Session;
2250
+ /** Skills configuration */
2251
+ skills?: SkillsConfig;
2252
+ /**
2253
+ * Test seam — replaces the default MCP connector with a custom
2254
+ * implementation. Bypasses the `mcpServers` normalization layer entirely
2255
+ * and is **not** part of the supported public API. Subject to change or
2256
+ * removal in any release.
2257
+ *
2258
+ * @internal
2259
+ */
2260
+ mcpConnector?: (configs: McpServerConfig[]) => Promise<McpConnection>;
2261
+ /**
2262
+ * Pre-connect MCP servers in the background as soon as `createAgent` returns,
2263
+ * instead of deferring the bootstrap to the first `agent.run()`.
2264
+ *
2265
+ * Useful when MCP latency is the dominant cost of a cold start: callers that
2266
+ * construct the agent early (e.g. at process init) can hide the bootstrap
2267
+ * behind other setup work. If bootstrap fails, the error is stored and
2268
+ * surfaced on the first `agent.run()` / `agent.warmup()`; the in-flight
2269
+ * promise is `await`ed by both paths so the error is never silently lost.
2270
+ *
2271
+ * No-op when `mcpServers` is empty. Default: `false`.
2272
+ */
2273
+ eager?: boolean;
2274
+ }
2275
+ interface Agent {
2276
+ hooks: Hookable<AgentHooks>;
2277
+ run: (options: AgentRunOptions) => Promise<AgentStats>;
2278
+ abort: () => void;
2279
+ steer: (message: string) => void;
2280
+ followUp: (message: string) => void;
2281
+ waitForIdle: () => Promise<void>;
2282
+ /**
2283
+ * Clear the agent's in-memory state (turns, queues, skill activations).
2284
+ * Fires `skills:deactivate` with `reason: 'reset'` for each previously active
2285
+ * skill. Awaiting lets host apps observe listener rejections.
2286
+ */
2287
+ reset: () => Promise<void>;
2288
+ /**
2289
+ * Destroy the execution context and clean up resources.
2290
+ * Idempotent — safe to call from both a `finally` block and a signal handler.
2291
+ */
2292
+ destroy: () => Promise<void>;
2293
+ /**
2294
+ * Explicitly activate a skill by name. Fires `skills:activate` with
2295
+ * `via: 'explicit'`. Throws if the skill isn't in the resolved catalog or
2296
+ * if the `maxActive` cap is reached. Idempotent — activating an already-active
2297
+ * skill is a no-op.
2298
+ */
2299
+ activateSkill: (name: string) => Promise<void>;
2300
+ /**
2301
+ * Deactivate a skill by name. Fires `skills:deactivate` with `reason: 'explicit'`.
2302
+ * No-op when the skill wasn't active.
2303
+ */
2304
+ deactivateSkill: (name: string) => Promise<void>;
2305
+ /**
2306
+ * Pre-connect MCP servers without running a turn. Idempotent and concurrency-safe:
2307
+ * - No MCP servers configured → resolves immediately.
2308
+ * - Connection already established → resolves immediately.
2309
+ * - Another `warmup()` / `run()` is bootstrapping → awaits the in-flight promise.
2310
+ *
2311
+ * Use from host code that wants to hide MCP bootstrap latency behind other
2312
+ * startup work (UI init, auth, etc.). Safe to call multiple times and from
2313
+ * multiple callers concurrently.
2314
+ */
2315
+ warmup: () => Promise<void>;
2316
+ readonly isRunning: boolean;
2317
+ readonly turns: SessionTurn[];
2318
+ readonly execution: ExecutionContext;
2319
+ readonly handle: ExecutionHandle | null;
2320
+ readonly session: Session | null;
2321
+ /** Snapshot of currently active skills. */
2322
+ readonly activeSkills: readonly ActiveSkill[];
2323
+ /**
2324
+ * Frozen view of the underlying `provider.meta`. Read-only to prevent
2325
+ * accidental cross-agent contamination — writes are rejected at runtime
2326
+ * (via `Object.freeze`) and at compile time (via `Readonly`). To override
2327
+ * model / capability defaults, construct a new provider.
2328
+ */
2329
+ readonly meta: Readonly<Record<string, unknown>>;
2330
+ }
2331
+ declare function createAgent({
2332
+ provider,
2333
+ name: agentName,
2334
+ system: agentSystem,
2335
+ tools: agentTools,
2336
+ toolAliases,
2337
+ behavior: agentBehavior,
2338
+ execution,
2339
+ mcpServers,
2340
+ session,
2341
+ skills: agentSkills,
2342
+ mcpConnector,
2343
+ eager
2344
+ }: AgentOptions): Agent;
2345
+ //#endregion
2346
+ export { OpenAICompatHttpError as $, loadSession as A, ToolExecutionMode as At, FileMapStoreOptions as B, AgentContextExceededError as Bt, SkillsConfig as C, SessionEndStatus as Ct, SessionRun as D, SpawnHookContext as Dt, SessionData as E, SessionTurn as Et, fromOpenAI as F, TurnFinishReason as Ft, StreamOptions as G, ClassifiedErrorKind as Gt, Provider as H, AgentToolNotAllowedError as Ht, toAnthropic as I, TurnUsage as It, ToolSpec as J, ToolCall as K, matchesContextExceeded as Kt, toOpenAI as L, toolOutputByteLength as Lt, createRemoteStore as M, ToolResultContent as Mt, autoDetectAndConvert as N, ToolResultImageContent as Nt, SessionStore as O, StreamHookContext as Ot, fromAnthropic as P, ToolResultTextContent as Pt, OpenAICompatAuthHeader as Q, createMemoryStore as R, toolResultToText as Rt, SkillSource as S, SessionContentBlock as St, Session as T, SessionMessage as Tt, ProviderCapabilities as U, CONTEXT_EXCEEDED_MESSAGE_PATTERNS as Ut, createFileMapStore as V, AgentProviderError as Vt, StreamCallbacks as W, ClassifiedError as Wt, OpenRouterParams as X, TurnResult as Y, openrouter as Z, ToolDef as _, PromptDocumentPart as _t, ActivationVia as a, openai as at, SkillDiagnostic as b, PromptTextPart as bt, SkillActivationState as c, AnthropicParams as ct, McpConnection as d, AgentRunOptions as dt, OpenAICompatParams as et, connectMcpServers as f, AgentStats as ft, ToolContext as g, OAuthRefreshHookContext as gt, resultToString as h, McpToolHookContext as ht, createAgent as i, OpenAIParams as it, RemoteStoreOptions as j, ToolHookContext as jt, createSession as k, ThinkingLevel as kt, SkillActivationStateOptions as l, anthropic as lt, normalizeMcpServers as m, McpServerConfig as mt, AgentHooks as n, mapOAIFinishReason as nt, ActiveSkill as o, CerebrasParams as ot, normalizeMcpBlocks as p, ChildRunStats as pt, ToolResult as q, toTypedError as qt, AgentOptions as r, openaiCompat as rt, DeactivationReason as s, cerebras as st, Agent as t, classifyOpenAICompatError as tt, createSkillActivationState as u, AgentBehavior as ut, ToolMap as v, PromptImagePart as vt, CreateSessionOptions as w, SessionHookContext as wt, SkillResource as x, RunHookMap as xt, SkillConfig as y, PromptPart as yt, FileMapAdapter as z, AgentAbortedError as zt };
2347
+ //# sourceMappingURL=agent-BoV5Twdl.d.ts.map