zidane 3.4.1 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -342,11 +342,16 @@ agent.hooks.hook('turn:after', (ctx) => {
342
342
 
343
343
  agent.hooks.hook('usage', (ctx) => {
344
344
  // ctx.turn, ctx.turnId, ctx.usage (per-turn)
345
- // ctx.totalIn, ctx.totalOut (running totals)
345
+ // ctx.totalIn, ctx.totalOut (running parent-loop totals — children fold in
346
+ // post-loop and are visible on `agent:done`)
346
347
  })
347
348
 
348
349
  agent.hooks.hook('agent:done', (ctx) => {
349
- // ctx.totalIn, ctx.totalOut, ctx.turns, ctx.elapsed, ctx.children?
350
+ // ctx.totalIn / ctx.totalOut / ctx.cost — cumulative across parent loop +
351
+ // every recursively-spawned sub-agent
352
+ // ctx.turns, ctx.elapsed — parent-loop view (use `flattenTurns(ctx).length`
353
+ // for tree-wide turn counts, `statsByModel(ctx)` for per-model breakdown)
354
+ // ctx.children? — per-child stats in completion order
350
355
  // ctx.output — structured output (when behavior.schema is set)
351
356
  // Fires on all exit paths: completion, maxTurns, and abort
352
357
  })
@@ -1030,11 +1035,24 @@ const schema = zodToJsonSchema(z.toJsonSchema(z.object({ name: z.string() })))
1030
1035
 
1031
1036
  ## Usage Tracking
1032
1037
 
1038
+ `stats.totalIn` / `stats.totalOut` / `stats.cost` are **cumulative** — parent
1039
+ loop plus every recursively-spawned sub-agent. `stats.turns` and
1040
+ `stats.turnUsage` cover the parent loop only; reach for the helpers below for
1041
+ tree-wide breakdowns.
1042
+
1033
1043
  ```ts
1044
+ import { flattenTurns, statsByModel } from 'zidane'
1045
+
1034
1046
  const stats = await agent.run({ prompt: 'hello' })
1035
- stats.turnUsage // TurnUsage[] — per-turn { input, output, cacheCreation?, cacheRead?, thinking?, cost?, finishReason?, modelId? }
1036
- stats.cost // total USD cost (if reported by provider)
1047
+ stats.totalIn // cumulative input tokens (parent + recursive children)
1048
+ stats.totalOut // cumulative output tokens
1049
+ stats.cost // cumulative USD cost (when reported by provider)
1050
+ stats.turnUsage // TurnUsage[] — parent loop only
1051
+ stats.children // ChildRunStats[] — recursive subtree, completion order
1037
1052
  stats.timeTillFirstTokenMs // ms from run() start to the first stream/tool event
1053
+
1054
+ flattenTurns(stats) // every TurnUsage in the tree, parent first then DFS children
1055
+ statsByModel(stats) // Map<modelId, { input, output, cost, cacheRead, cacheCreation, turns }>
1038
1056
  ```
1039
1057
 
1040
1058
  ## Types
@@ -1,5 +1,5 @@
1
1
  import { Hookable } from 'hookable';
2
- import { b as ExecutionContext, c as ExecutionHandle } from './types-vA1a_ZX7.js';
2
+ import { a as ExecutionContext, c as ExecutionHandle } from './types-Bai5rKpa.js';
3
3
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
4
4
 
5
5
  /**
@@ -764,15 +764,59 @@ interface TurnUsage {
764
764
  modelId?: string;
765
765
  }
766
766
  interface AgentStats {
767
+ /**
768
+ * Cumulative input tokens across the parent agent loop **and** every
769
+ * recursively-spawned sub-agent. Use this for billing / token-ledger
770
+ * consumption.
771
+ */
767
772
  totalIn: number;
773
+ /** Cumulative output tokens. Same semantics as {@link AgentStats.totalIn}. */
768
774
  totalOut: number;
775
+ /**
776
+ * Cumulative cache-read tokens across the parent agent loop and every
777
+ * recursively-spawned sub-agent. Surfaced at the top level (rather than
778
+ * only per-`TurnUsage`) because Anthropic prices cache reads at a separate
779
+ * line-item rate from regular input — billing-correct cost computation
780
+ * needs this number directly. Always `0` for providers that don't report
781
+ * cache usage.
782
+ */
783
+ totalCacheRead: number;
784
+ /**
785
+ * Cumulative cache-creation tokens across the parent agent loop and every
786
+ * recursively-spawned sub-agent. Same rationale as
787
+ * {@link AgentStats.totalCacheRead} — separate Anthropic billing rate.
788
+ * Always `0` for providers that don't report cache usage.
789
+ */
790
+ totalCacheCreation: number;
791
+ /**
792
+ * Number of parent agent-loop turns. Children's turn counts live under
793
+ * `children[].stats.turns` and are NOT folded in here — a single "turns"
794
+ * number for the whole tree would conflate two different measures
795
+ * (parent-loop iterations vs. tree-wide tool-call rounds).
796
+ *
797
+ * Tree-wide turn count: `flattenTurns(stats).length`.
798
+ */
769
799
  turns: number;
800
+ /**
801
+ * Wall-clock duration of the top-level `agent.run()` call, in milliseconds.
802
+ * Children run during parent tool calls so this naturally subsumes child
803
+ * wall time — sequential children inflate it, parallel children compress
804
+ * into the parent's window.
805
+ */
770
806
  elapsed: number;
771
- /** Per-turn usage breakdown */
807
+ /**
808
+ * Per-turn usage breakdown for the **parent loop only**. Children's per-turn
809
+ * usages live under `children[].stats.turnUsage`. Use {@link flattenTurns}
810
+ * to walk the full tree.
811
+ */
772
812
  turnUsage?: TurnUsage[];
773
- /** Total cost in USD (sum of per-turn costs reported by provider) */
813
+ /**
814
+ * Cumulative cost in USD — parent loop plus every recursively-spawned
815
+ * sub-agent. Sums per-turn `TurnUsage.cost` reported by the provider.
816
+ * Absent when neither parent nor any descendant reported a non-zero cost.
817
+ */
774
818
  cost?: number;
775
- /** Stats from child agents spawned during this run */
819
+ /** Stats from child agents spawned during this run, in completion order. Recursive. */
776
820
  children?: ChildRunStats[];
777
821
  /** Structured output from schema enforcement (only present when behavior.schema is set) */
778
822
  output?: Record<string, unknown>;
@@ -787,6 +831,12 @@ interface AgentStats {
787
831
  interface ChildRunStats {
788
832
  id: string;
789
833
  task: string;
834
+ /**
835
+ * The child agent's full {@link AgentStats}. Cumulative for that child's
836
+ * own subtree (child loop + its grandchildren). Do **not** sum
837
+ * `ctx.stats.totalIn` across `spawn:complete` events to derive top-level
838
+ * totals — `agent.run()`'s return value is the canonical cumulative root.
839
+ */
790
840
  stats: AgentStats;
791
841
  /**
792
842
  * Subagent depth when this child ran. 1 = direct child of the top-level
@@ -2236,6 +2286,15 @@ interface AgentHooks {
2236
2286
  mode: 'steer' | 'block';
2237
2287
  }) => void;
2238
2288
  'agent:abort': (ctx: object) => void;
2289
+ /**
2290
+ * Run finished — fires on all exit paths (completion, maxTurns, abort).
2291
+ *
2292
+ * Since 4.0 the `AgentStats` carried here is **cumulative** across the
2293
+ * parent agent loop and every recursively-spawned sub-agent
2294
+ * (`totalIn` / `totalOut` / `cost` / `totalCacheRead` / `totalCacheCreation`).
2295
+ * For parent-loop-only counts use `ctx.turnUsage` (parent-only array);
2296
+ * for tree-wide turn counts use `flattenTurns(ctx).length`.
2297
+ */
2239
2298
  'agent:done': (ctx: AgentStats) => void;
2240
2299
  'session:start': (ctx: SessionHookContext & {
2241
2300
  runId: string;
@@ -2363,4 +2422,4 @@ interface Agent {
2363
2422
  }
2364
2423
  declare function createAgent({ provider, name: agentName, system: agentSystem, tools: agentTools, toolAliases, behavior: agentBehavior, execution, mcpServers, session, skills: agentSkills, mcpConnector, eager }: AgentOptions): Agent;
2365
2424
 
2366
- export { type ToolMap as $, type Agent as A, type SessionData as B, CONTEXT_EXCEEDED_MESSAGE_PATTERNS as C, type SessionEndStatus as D, type SessionHookContext as E, type SessionMessage as F, type SessionRun as G, type SessionStore as H, type SessionTurn as I, type SkillConfig as J, type SkillResource as K, type SkillsConfig as L, type McpConnection as M, type SpawnHookContext as N, type OAuthRefreshHookContext as O, type PromptDocumentPart as P, type StreamCallbacks as Q, type RemoteStoreOptions as R, type Session as S, type StreamHookContext as T, type StreamOptions as U, type ThinkingLevel as V, type ToolCall as W, type ToolContext as X, type ToolDef as Y, type ToolExecutionMode as Z, type ToolHookContext as _, AgentAbortedError as a, type ToolResult as a0, type ToolResultContent as a1, type ToolResultImageContent as a2, type ToolResultTextContent as a3, type ToolSpec as a4, type TurnFinishReason as a5, type TurnResult as a6, type TurnUsage as a7, matchesContextExceeded as a8, toolOutputByteLength as a9, loadSession as aA, mapOAIFinishReason as aB, normalizeMcpBlocks as aC, normalizeMcpServers as aD, openai as aE, openaiCompat as aF, openrouter as aG, resultToString as aH, toAnthropic as aI, toOpenAI as aJ, toTypedError as aK, toolResultToText as aa, type ActivationVia as ab, type ActiveSkill as ac, type DeactivationReason as ad, type FileMapAdapter as ae, type FileMapStoreOptions as af, type OpenAICompatAuthHeader as ag, OpenAICompatHttpError as ah, type OpenAICompatParams as ai, type SkillActivationState as aj, type SkillActivationStateOptions as ak, type SkillDiagnostic as al, type SkillSource as am, anthropic as an, autoDetectAndConvert as ao, cerebras as ap, classifyOpenAICompatError as aq, connectMcpServers as ar, createAgent as as, createFileMapStore as at, createMemoryStore as au, createRemoteStore as av, createSession as aw, createSkillActivationState as ax, fromAnthropic as ay, fromOpenAI as az, type AgentBehavior as b, AgentContextExceededError as c, type AgentHooks as d, type AgentOptions as e, AgentProviderError as f, type AgentRunOptions as g, type AgentStats as h, AgentToolNotAllowedError as i, type AnthropicParams as j, type CerebrasParams as k, type ChildRunStats as l, type ClassifiedError as m, type ClassifiedErrorKind as n, type CreateSessionOptions as o, type McpServerConfig as p, type McpToolHookContext as q, type OpenAIParams as r, type OpenRouterParams as s, type PromptImagePart as t, type PromptPart as u, type PromptTextPart as v, type Provider as w, type ProviderCapabilities as x, type RunHookMap as y, type SessionContentBlock as z };
2425
+ export { type SkillsConfig as $, type AgentHooks as A, type PromptTextPart as B, CONTEXT_EXCEEDED_MESSAGE_PATTERNS as C, type DeactivationReason as D, type Provider as E, type FileMapAdapter as F, type ProviderCapabilities as G, type RunHookMap as H, type Session as I, type SessionContentBlock as J, type SessionData as K, type SessionEndStatus as L, type McpConnection as M, type SessionHookContext as N, type OAuthRefreshHookContext as O, type PromptDocumentPart as P, type SessionMessage as Q, type RemoteStoreOptions as R, type SessionStore as S, type SessionRun as T, type SessionTurn as U, type SkillActivationState as V, type SkillActivationStateOptions as W, type SkillConfig as X, type SkillDiagnostic as Y, type SkillResource as Z, type SkillSource as _, type ActivationVia as a, type SpawnHookContext as a0, type StreamCallbacks as a1, type StreamHookContext as a2, type StreamOptions as a3, type ThinkingLevel as a4, type ToolCall as a5, type ToolContext as a6, type ToolDef as a7, type ToolExecutionMode as a8, type ToolHookContext as a9, normalizeMcpServers as aA, openai as aB, openaiCompat as aC, openrouter as aD, resultToString as aE, toAnthropic as aF, toOpenAI as aG, toTypedError as aH, toolOutputByteLength as aI, toolResultToText as aJ, type ChildRunStats as aK, type ToolMap as aa, type ToolResult as ab, type ToolResultContent as ac, type ToolResultImageContent as ad, type ToolResultTextContent as ae, type ToolSpec as af, type TurnFinishReason as ag, type TurnResult as ah, type TurnUsage as ai, anthropic as aj, autoDetectAndConvert as ak, cerebras as al, classifyOpenAICompatError as am, connectMcpServers as an, createAgent as ao, createFileMapStore as ap, createMemoryStore as aq, createRemoteStore as ar, createSession as as, createSkillActivationState as at, fromAnthropic as au, fromOpenAI as av, loadSession as aw, mapOAIFinishReason as ax, matchesContextExceeded as ay, normalizeMcpBlocks as az, type ActiveSkill as b, type Agent as c, AgentAbortedError as d, type AgentBehavior as e, AgentContextExceededError as f, type AgentOptions as g, AgentProviderError as h, type AgentRunOptions as i, type AgentStats as j, AgentToolNotAllowedError as k, type AnthropicParams as l, type CerebrasParams as m, type ClassifiedError as n, type ClassifiedErrorKind as o, type CreateSessionOptions as p, type FileMapStoreOptions as q, type McpServerConfig as r, type McpToolHookContext as s, type OpenAICompatAuthHeader as t, OpenAICompatHttpError as u, type OpenAICompatParams as v, type OpenAIParams as w, type OpenRouterParams as x, type PromptImagePart as y, type PromptPart as z };
@@ -7,6 +7,9 @@ import {
7
7
  resolveSkills,
8
8
  validateResourcePath
9
9
  } from "./chunk-6STZTA4N.js";
10
+ import {
11
+ flattenTurns
12
+ } from "./chunk-IC7FT4OD.js";
10
13
  import {
11
14
  createProcessContext
12
15
  } from "./chunk-UD25QF3H.js";
@@ -1704,6 +1707,8 @@ function sanitizeStoredToolResults(provider, messages) {
1704
1707
  async function runLoop(ctx) {
1705
1708
  let totalIn = 0;
1706
1709
  let totalOut = 0;
1710
+ let totalCacheRead = 0;
1711
+ let totalCacheCreation = 0;
1707
1712
  const turnUsages = [];
1708
1713
  const startTime = Date.now();
1709
1714
  const maxTurns = ctx.maxTurns ?? Number.POSITIVE_INFINITY;
@@ -1726,6 +1731,8 @@ async function runLoop(ctx) {
1726
1731
  turnsCompleted = turn + 1;
1727
1732
  totalIn += result.usage.input;
1728
1733
  totalOut += result.usage.output;
1734
+ totalCacheRead += result.usage.cacheRead ?? 0;
1735
+ totalCacheCreation += result.usage.cacheCreation ?? 0;
1729
1736
  turnUsages.push(result.usage);
1730
1737
  await ctx.hooks.callHook("usage", { turn, turnId: result.turnId, usage: result.usage, totalIn, totalOut });
1731
1738
  if (ctx.signal.aborted) {
@@ -1762,6 +1769,8 @@ async function runLoop(ctx) {
1762
1769
  return {
1763
1770
  totalIn,
1764
1771
  totalOut,
1772
+ totalCacheRead,
1773
+ totalCacheCreation,
1765
1774
  turns: turn + 1,
1766
1775
  elapsed: Date.now() - startTime,
1767
1776
  turnUsage: turnUsages,
@@ -1773,6 +1782,8 @@ async function runLoop(ctx) {
1773
1782
  return {
1774
1783
  totalIn,
1775
1784
  totalOut,
1785
+ totalCacheRead,
1786
+ totalCacheCreation,
1776
1787
  turns: turnsCompleted,
1777
1788
  elapsed: Date.now() - startTime,
1778
1789
  turnUsage: turnUsages,
@@ -2985,8 +2996,27 @@ ${buildSearchableCatalog(disclosure.lazyEntries, { discoveryToolName })}`;
2985
2996
  runStartMs,
2986
2997
  runToolCounts: {}
2987
2998
  });
2999
+ const parentTurnCost = stats.turnUsage?.reduce((sum, t) => sum + (t.cost ?? 0), 0) ?? 0;
3000
+ let childrenIn = 0;
3001
+ let childrenOut = 0;
3002
+ let childrenCost = 0;
3003
+ let childrenCacheRead = 0;
3004
+ let childrenCacheCreation = 0;
3005
+ for (const c of childrenStats) {
3006
+ childrenIn += c.stats.totalIn;
3007
+ childrenOut += c.stats.totalOut;
3008
+ childrenCost += c.stats.cost ?? 0;
3009
+ childrenCacheRead += c.stats.totalCacheRead;
3010
+ childrenCacheCreation += c.stats.totalCacheCreation;
3011
+ }
3012
+ const cumulativeCost = parentTurnCost + childrenCost;
2988
3013
  const finalStats = {
2989
3014
  ...stats,
3015
+ totalIn: stats.totalIn + childrenIn,
3016
+ totalOut: stats.totalOut + childrenOut,
3017
+ totalCacheRead: stats.totalCacheRead + childrenCacheRead,
3018
+ totalCacheCreation: stats.totalCacheCreation + childrenCacheCreation,
3019
+ ...cumulativeCost > 0 ? { cost: cumulativeCost } : {},
2990
3020
  children: childrenStats.length > 0 ? childrenStats : void 0
2991
3021
  };
2992
3022
  await flushTurns();
@@ -2996,15 +3026,12 @@ ${buildSearchableCatalog(disclosure.lazyEntries, { discoveryToolName })}`;
2996
3026
  await hooks.callHook("agent:done", finalStats);
2997
3027
  return finalStats;
2998
3028
  }
2999
- const totalCost = finalStats.turnUsage?.reduce((sum, t) => sum + (t.cost ?? 0), 0);
3000
- if (totalCost)
3001
- finalStats.cost = totalCost;
3002
3029
  session?.completeRun(runId, {
3003
- turns: finalStats.turns,
3004
- tokensIn: finalStats.totalIn,
3005
- tokensOut: finalStats.totalOut,
3006
- turnUsage: finalStats.turnUsage,
3007
- cost: totalCost
3030
+ turns: stats.turns,
3031
+ tokensIn: stats.totalIn,
3032
+ tokensOut: stats.totalOut,
3033
+ turnUsage: stats.turnUsage,
3034
+ cost: parentTurnCost > 0 ? parentTurnCost : void 0
3008
3035
  });
3009
3036
  await finalizeSession("completed");
3010
3037
  await hooks.callHook("agent:done", finalStats);
@@ -3014,7 +3041,14 @@ ${buildSearchableCatalog(disclosure.lazyEntries, { discoveryToolName })}`;
3014
3041
  if (abortController.signal.aborted) {
3015
3042
  session?.abortRun(runId);
3016
3043
  await finalizeSession("aborted");
3017
- const stats = { totalIn: 0, totalOut: 0, turns: 0, elapsed: 0 };
3044
+ const stats = {
3045
+ totalIn: 0,
3046
+ totalOut: 0,
3047
+ totalCacheRead: 0,
3048
+ totalCacheCreation: 0,
3049
+ turns: 0,
3050
+ elapsed: 0
3051
+ };
3018
3052
  await hooks.callHook("agent:done", stats);
3019
3053
  return stats;
3020
3054
  }
@@ -3277,6 +3311,8 @@ function createSpawnTool(options = {}) {
3277
3311
  const localStats = {
3278
3312
  totalIn: 0,
3279
3313
  totalOut: 0,
3314
+ totalCacheRead: 0,
3315
+ totalCacheCreation: 0,
3280
3316
  turns: 0,
3281
3317
  elapsed: 0
3282
3318
  };
@@ -3363,16 +3399,17 @@ function createSpawnTool(options = {}) {
3363
3399
  });
3364
3400
  try {
3365
3401
  finalStats = await raceWithTimeout(runPromise, options.timeoutMs);
3402
+ const treeTurns = flattenTurns(finalStats).length;
3366
3403
  if (ctx.signal.aborted) {
3367
3404
  childRunStatus = "aborted";
3368
3405
  result = [
3369
- `[sub-agent ${id}] Aborted after ${finalStats.turns} turns (${finalStats.elapsed}ms)`,
3406
+ `[sub-agent ${id}] Aborted after ${treeTurns} turns (${finalStats.elapsed}ms)`,
3370
3407
  `Tokens: ${finalStats.totalIn} in / ${finalStats.totalOut} out`
3371
3408
  ].join("\n");
3372
3409
  } else {
3373
3410
  const response = extractText(agent.turns.at(-1));
3374
3411
  result = [
3375
- `[sub-agent ${id}] Completed in ${finalStats.turns} turns (${finalStats.elapsed}ms)`,
3412
+ `[sub-agent ${id}] Completed in ${treeTurns} turns (${finalStats.elapsed}ms)`,
3376
3413
  `Tokens: ${finalStats.totalIn} in / ${finalStats.totalOut} out`,
3377
3414
  "",
3378
3415
  response || "(no text response)"
@@ -3385,13 +3422,27 @@ function createSpawnTool(options = {}) {
3385
3422
  try {
3386
3423
  finalStats = await runPromise;
3387
3424
  } catch {
3388
- finalStats = { totalIn: 0, totalOut: 0, turns: 0, elapsed: err.timeoutMs };
3425
+ finalStats = {
3426
+ totalIn: 0,
3427
+ totalOut: 0,
3428
+ totalCacheRead: 0,
3429
+ totalCacheCreation: 0,
3430
+ turns: 0,
3431
+ elapsed: err.timeoutMs
3432
+ };
3389
3433
  }
3390
3434
  result = `[sub-agent ${id}] Timed out after ${err.timeoutMs}ms`;
3391
3435
  } else {
3392
3436
  const error = err instanceof Error ? err : new Error(String(err));
3393
3437
  childRunStatus = "error";
3394
- finalStats = { totalIn: 0, totalOut: 0, turns: 0, elapsed: 0 };
3438
+ finalStats = {
3439
+ totalIn: 0,
3440
+ totalOut: 0,
3441
+ totalCacheRead: 0,
3442
+ totalCacheCreation: 0,
3443
+ turns: 0,
3444
+ elapsed: 0
3445
+ };
3395
3446
  result = `[sub-agent ${id}] Error: ${error.message}`;
3396
3447
  await ctx.hooks.callHook("spawn:error", { id, task, depth: childDepth, error });
3397
3448
  }
@@ -3405,6 +3456,8 @@ function createSpawnTool(options = {}) {
3405
3456
  if (finalStats) {
3406
3457
  localStats.totalIn += finalStats.totalIn;
3407
3458
  localStats.totalOut += finalStats.totalOut;
3459
+ localStats.totalCacheRead += finalStats.totalCacheRead;
3460
+ localStats.totalCacheCreation += finalStats.totalCacheCreation;
3408
3461
  localStats.turns += finalStats.turns;
3409
3462
  localStats.elapsed += finalStats.elapsed;
3410
3463
  }
@@ -6,7 +6,7 @@ import {
6
6
  readFile,
7
7
  shell,
8
8
  writeFile
9
- } from "./chunk-VTLEPYND.js";
9
+ } from "./chunk-4LPBN547.js";
10
10
 
11
11
  // src/presets/basic.ts
12
12
  var basicTools = { shell, readFile, writeFile, listFiles, edit, multiEdit };
@@ -0,0 +1,37 @@
1
+ // src/stats.ts
2
+ function flattenTurns(stats) {
3
+ const out = [];
4
+ collectTurns(stats, out);
5
+ return out;
6
+ }
7
+ function collectTurns(stats, out) {
8
+ if (stats.turnUsage)
9
+ out.push(...stats.turnUsage);
10
+ if (stats.children) {
11
+ for (const child of stats.children)
12
+ collectTurns(child.stats, out);
13
+ }
14
+ }
15
+ function statsByModel(stats) {
16
+ const out = /* @__PURE__ */ new Map();
17
+ for (const turn of flattenTurns(stats)) {
18
+ const key = turn.modelId ?? "(unknown)";
19
+ let entry = out.get(key);
20
+ if (!entry) {
21
+ entry = { input: 0, output: 0, cost: 0, cacheRead: 0, cacheCreation: 0, turns: 0 };
22
+ out.set(key, entry);
23
+ }
24
+ entry.input += turn.input;
25
+ entry.output += turn.output;
26
+ entry.cost += turn.cost ?? 0;
27
+ entry.cacheRead += turn.cacheRead ?? 0;
28
+ entry.cacheCreation += turn.cacheCreation ?? 0;
29
+ entry.turns += 1;
30
+ }
31
+ return out;
32
+ }
33
+
34
+ export {
35
+ flattenTurns,
36
+ statsByModel
37
+ };
@@ -1,6 +1,6 @@
1
- import { S as SpawnConfig, b as ExecutionContext } from './types-vA1a_ZX7.js';
2
- export { C as ContextCapabilities, a as ContextType, E as ExecResult, c as ExecutionHandle } from './types-vA1a_ZX7.js';
3
- export { S as SandboxProvider, c as createSandboxContext } from './sandbox-CLghrTLi.js';
1
+ import { S as SpawnConfig, a as ExecutionContext } from './types-Bai5rKpa.js';
2
+ export { C as ContextCapabilities, b as ContextType, E as ExecResult, c as ExecutionHandle } from './types-Bai5rKpa.js';
3
+ export { S as SandboxProvider, c as createSandboxContext } from './sandbox-D7v6Wy62.js';
4
4
 
5
5
  /**
6
6
  * Docker execution context.
package/dist/index.d.ts CHANGED
@@ -1,12 +1,13 @@
1
- import { d as AgentHooks } from './agent-CMjWCUPr.js';
2
- export { ab as ActivationVia, ac as ActiveSkill, A as Agent, a as AgentAbortedError, b as AgentBehavior, c as AgentContextExceededError, e as AgentOptions, f as AgentProviderError, g as AgentRunOptions, h as AgentStats, i as AgentToolNotAllowedError, j as AnthropicParams, C as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, k as CerebrasParams, m as ClassifiedError, n as ClassifiedErrorKind, o as CreateSessionOptions, ad as DeactivationReason, ae as FileMapAdapter, af as FileMapStoreOptions, M as McpConnection, p as McpServerConfig, q as McpToolHookContext, O as OAuthRefreshHookContext, ag as OpenAICompatAuthHeader, ah as OpenAICompatHttpError, ai as OpenAICompatParams, r as OpenAIParams, s as OpenRouterParams, P as PromptDocumentPart, t as PromptImagePart, u as PromptPart, v as PromptTextPart, w as Provider, x as ProviderCapabilities, R as RemoteStoreOptions, y as RunHookMap, S as Session, z as SessionContentBlock, B as SessionData, D as SessionEndStatus, E as SessionHookContext, F as SessionMessage, G as SessionRun, H as SessionStore, I as SessionTurn, aj as SkillActivationState, ak as SkillActivationStateOptions, J as SkillConfig, al as SkillDiagnostic, K as SkillResource, am as SkillSource, L as SkillsConfig, N as SpawnHookContext, Q as StreamCallbacks, T as StreamHookContext, U as StreamOptions, V as ThinkingLevel, W as ToolCall, X as ToolContext, Y as ToolDef, Z as ToolExecutionMode, _ as ToolHookContext, $ as ToolMap, a0 as ToolResult, a1 as ToolResultContent, a2 as ToolResultImageContent, a3 as ToolResultTextContent, a4 as ToolSpec, a5 as TurnFinishReason, a6 as TurnResult, a7 as TurnUsage, an as anthropic, ao as autoDetectAndConvert, ap as cerebras, aq as classifyOpenAICompatError, ar as connectMcpServers, as as createAgent, at as createFileMapStore, au as createMemoryStore, av as createRemoteStore, aw as createSession, ax as createSkillActivationState, ay as fromAnthropic, az as fromOpenAI, aA as loadSession, aB as mapOAIFinishReason, a8 as matchesContextExceeded, aC as normalizeMcpBlocks, aD as normalizeMcpServers, aE as openai, aF as openaiCompat, aG as openrouter, aH as resultToString, aI as toAnthropic, aJ as toOpenAI, aK as toTypedError, a9 as toolOutputByteLength, aa as toolResultToText } from './agent-CMjWCUPr.js';
1
+ import { A as AgentHooks } from './agent-BAHrGtqu.js';
2
+ export { a as ActivationVia, b as ActiveSkill, c as Agent, d as AgentAbortedError, e as AgentBehavior, f as AgentContextExceededError, g as AgentOptions, h as AgentProviderError, i as AgentRunOptions, j as AgentStats, k as AgentToolNotAllowedError, l as AnthropicParams, C as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, m as CerebrasParams, n as ClassifiedError, o as ClassifiedErrorKind, p as CreateSessionOptions, D as DeactivationReason, F as FileMapAdapter, q as FileMapStoreOptions, M as McpConnection, r as McpServerConfig, s as McpToolHookContext, O as OAuthRefreshHookContext, t as OpenAICompatAuthHeader, u as OpenAICompatHttpError, v as OpenAICompatParams, w as OpenAIParams, x as OpenRouterParams, P as PromptDocumentPart, y as PromptImagePart, z as PromptPart, B as PromptTextPart, E as Provider, G as ProviderCapabilities, R as RemoteStoreOptions, H as RunHookMap, I as Session, J as SessionContentBlock, K as SessionData, L as SessionEndStatus, N as SessionHookContext, Q as SessionMessage, T as SessionRun, S as SessionStore, U as SessionTurn, V as SkillActivationState, W as SkillActivationStateOptions, X as SkillConfig, Y as SkillDiagnostic, Z as SkillResource, _ as SkillSource, $ as SkillsConfig, a0 as SpawnHookContext, a1 as StreamCallbacks, a2 as StreamHookContext, a3 as StreamOptions, a4 as ThinkingLevel, a5 as ToolCall, a6 as ToolContext, a7 as ToolDef, a8 as ToolExecutionMode, a9 as ToolHookContext, aa as ToolMap, ab as ToolResult, ac as ToolResultContent, ad as ToolResultImageContent, ae as ToolResultTextContent, af as ToolSpec, ag as TurnFinishReason, ah as TurnResult, ai as TurnUsage, aj as anthropic, ak as autoDetectAndConvert, al as cerebras, am as classifyOpenAICompatError, an as connectMcpServers, ao as createAgent, ap as createFileMapStore, aq as createMemoryStore, ar as createRemoteStore, as as createSession, at as createSkillActivationState, au as fromAnthropic, av as fromOpenAI, aw as loadSession, ax as mapOAIFinishReason, ay as matchesContextExceeded, az as normalizeMcpBlocks, aA as normalizeMcpServers, aB as openai, aC as openaiCompat, aD as openrouter, aE as resultToString, aF as toAnthropic, aG as toOpenAI, aH as toTypedError, aI as toolOutputByteLength, aJ as toolResultToText } from './agent-BAHrGtqu.js';
3
3
  export { createDockerContext, createProcessContext } from './contexts.js';
4
- export { S as SandboxProvider, c as createSandboxContext } from './sandbox-CLghrTLi.js';
5
- export { C as ContextCapabilities, a as ContextType, E as ExecResult, b as ExecutionContext, c as ExecutionHandle, S as SpawnConfig } from './types-vA1a_ZX7.js';
4
+ export { S as SandboxProvider, c as createSandboxContext } from './sandbox-D7v6Wy62.js';
5
+ export { C as ContextCapabilities, b as ContextType, E as ExecResult, a as ExecutionContext, c as ExecutionHandle, S as SpawnConfig } from './types-Bai5rKpa.js';
6
6
  export { Preset, basic, basicTools, definePreset } from './presets.js';
7
7
  export { IMPLICITLY_ALLOWED_SKILL_TOOLS, SkillValidationIssue, SkillValidationResult, SourcedScanPath, buildCatalog, defineSkill, discoverSkills, installAllowedToolsGate, interpolateShellCommands, isToolAllowedByUnion, matchesAllowedTool, parseAllowedToolPattern, parseSkillFile, resolveSkills, validateResourcePath, validateSkillForWrite, validateSkillName, writeSkillToDisk, writeSkillsToDisk } from './skills.js';
8
- export { S as SkillsReadToolOptions, a as SkillsRunScriptToolOptions, b as SkillsUseToolOptions, c as createSkillsReadTool, d as createSkillsRunScriptTool, e as createSkillsUseTool, f as edit, g as glob, h as grep, m as multiEdit } from './skills-use-6oJKUjk_.js';
9
- export { C as ChildAgent, I as InteractionToolOptions, S as SpawnToolOptions, a as SpawnToolState, V as ValidationResult, c as createInteractionTool, b as createSpawnTool, v as validateToolArgs } from './validation-BWV_pCdO.js';
8
+ export { ModelUsage, flattenTurns, statsByModel } from './types.js';
9
+ export { S as SkillsReadToolOptions, a as SkillsRunScriptToolOptions, b as SkillsUseToolOptions, c as createSkillsReadTool, d as createSkillsRunScriptTool, e as createSkillsUseTool, f as edit, g as glob, h as grep, m as multiEdit } from './skills-use-DwZrNmcw.js';
10
+ export { C as ChildAgent, I as InteractionToolOptions, S as SpawnToolOptions, a as SpawnToolState, V as ValidationResult, c as createInteractionTool, b as createSpawnTool, v as validateToolArgs } from './validation-Pm--dQEU.js';
10
11
  import { Hookable } from 'hookable';
11
12
  import '@modelcontextprotocol/sdk/client/index.js';
12
13
 
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  basicTools,
12
12
  basic_default,
13
13
  definePreset
14
- } from "./chunk-WE4C6AQE.js";
14
+ } from "./chunk-64LLNY7F.js";
15
15
  import {
16
16
  createAgent,
17
17
  createInteractionTool,
@@ -24,7 +24,7 @@ import {
24
24
  grep,
25
25
  multiEdit,
26
26
  validateToolArgs
27
- } from "./chunk-VTLEPYND.js";
27
+ } from "./chunk-4LPBN547.js";
28
28
  import {
29
29
  IMPLICITLY_ALLOWED_SKILL_TOOLS,
30
30
  buildCatalog,
@@ -43,6 +43,10 @@ import {
43
43
  writeSkillToDisk,
44
44
  writeSkillsToDisk
45
45
  } from "./chunk-6STZTA4N.js";
46
+ import {
47
+ flattenTurns,
48
+ statsByModel
49
+ } from "./chunk-IC7FT4OD.js";
46
50
  import {
47
51
  createDockerContext,
48
52
  createProcessContext,
@@ -233,6 +237,7 @@ export {
233
237
  defineSkill,
234
238
  discoverSkills,
235
239
  edit,
240
+ flattenTurns,
236
241
  fromAnthropic,
237
242
  fromOpenAI,
238
243
  glob,
@@ -254,6 +259,7 @@ export {
254
259
  parseSkillFile,
255
260
  resolveSkills,
256
261
  resultToString,
262
+ statsByModel,
257
263
  toAnthropic,
258
264
  toOpenAI,
259
265
  toTypedError,
package/dist/mcp.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import '@modelcontextprotocol/sdk/client/index.js';
2
2
  import 'hookable';
3
- export { M as McpConnection, p as McpServerConfig, ar as connectMcpServers, aC as normalizeMcpBlocks, aD as normalizeMcpServers, aH as resultToString } from './agent-CMjWCUPr.js';
4
- import './types-vA1a_ZX7.js';
3
+ export { M as McpConnection, r as McpServerConfig, an as connectMcpServers, az as normalizeMcpBlocks, aA as normalizeMcpServers, aE as resultToString } from './agent-BAHrGtqu.js';
4
+ import './types-Bai5rKpa.js';
package/dist/presets.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Y as ToolDef, e as AgentOptions } from './agent-CMjWCUPr.js';
1
+ import { a7 as ToolDef, g as AgentOptions } from './agent-BAHrGtqu.js';
2
2
  import 'hookable';
3
- import './types-vA1a_ZX7.js';
3
+ import './types-Bai5rKpa.js';
4
4
  import '@modelcontextprotocol/sdk/client/index.js';
5
5
 
6
6
  /**
package/dist/presets.js CHANGED
@@ -2,9 +2,10 @@ import {
2
2
  basicTools,
3
3
  basic_default,
4
4
  definePreset
5
- } from "./chunk-WE4C6AQE.js";
6
- import "./chunk-VTLEPYND.js";
5
+ } from "./chunk-64LLNY7F.js";
6
+ import "./chunk-4LPBN547.js";
7
7
  import "./chunk-6STZTA4N.js";
8
+ import "./chunk-IC7FT4OD.js";
8
9
  import "./chunk-UD25QF3H.js";
9
10
  import "./chunk-7GQ7P6DM.js";
10
11
  import "./chunk-JH6IAAFA.js";
@@ -1,4 +1,4 @@
1
- export { j as AnthropicParams, k as CerebrasParams, ag as OpenAICompatAuthHeader, ah as OpenAICompatHttpError, ai as OpenAICompatParams, r as OpenAIParams, s as OpenRouterParams, w as Provider, x as ProviderCapabilities, Q as StreamCallbacks, U as StreamOptions, W as ToolCall, a0 as ToolResult, a4 as ToolSpec, a6 as TurnResult, an as anthropic, ap as cerebras, aq as classifyOpenAICompatError, aB as mapOAIFinishReason, aE as openai, aF as openaiCompat, aG as openrouter } from './agent-CMjWCUPr.js';
1
+ export { l as AnthropicParams, m as CerebrasParams, t as OpenAICompatAuthHeader, u as OpenAICompatHttpError, v as OpenAICompatParams, w as OpenAIParams, x as OpenRouterParams, E as Provider, G as ProviderCapabilities, a1 as StreamCallbacks, a3 as StreamOptions, a5 as ToolCall, ab as ToolResult, af as ToolSpec, ah as TurnResult, aj as anthropic, al as cerebras, am as classifyOpenAICompatError, ax as mapOAIFinishReason, aB as openai, aC as openaiCompat, aD as openrouter } from './agent-BAHrGtqu.js';
2
2
  import 'hookable';
3
- import './types-vA1a_ZX7.js';
3
+ import './types-Bai5rKpa.js';
4
4
  import '@modelcontextprotocol/sdk/client/index.js';
@@ -1,4 +1,4 @@
1
- import { S as SpawnConfig, E as ExecResult, b as ExecutionContext } from './types-vA1a_ZX7.js';
1
+ import { S as SpawnConfig, E as ExecResult, a as ExecutionContext } from './types-Bai5rKpa.js';
2
2
 
3
3
  /**
4
4
  * Remote sandbox execution context.
@@ -1,6 +1,6 @@
1
- import { H as SessionStore } from '../agent-CMjWCUPr.js';
1
+ import { S as SessionStore } from '../agent-BAHrGtqu.js';
2
2
  import 'hookable';
3
- import '../types-vA1a_ZX7.js';
3
+ import '../types-Bai5rKpa.js';
4
4
  import '@modelcontextprotocol/sdk/client/index.js';
5
5
 
6
6
  /**
package/dist/session.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { o as CreateSessionOptions, ae as FileMapAdapter, af as FileMapStoreOptions, R as RemoteStoreOptions, S as Session, z as SessionContentBlock, B as SessionData, F as SessionMessage, G as SessionRun, H as SessionStore, I as SessionTurn, ao as autoDetectAndConvert, at as createFileMapStore, au as createMemoryStore, av as createRemoteStore, aw as createSession, ay as fromAnthropic, az as fromOpenAI, aA as loadSession, aI as toAnthropic, aJ as toOpenAI } from './agent-CMjWCUPr.js';
1
+ export { p as CreateSessionOptions, F as FileMapAdapter, q as FileMapStoreOptions, R as RemoteStoreOptions, I as Session, J as SessionContentBlock, K as SessionData, Q as SessionMessage, T as SessionRun, S as SessionStore, U as SessionTurn, ak as autoDetectAndConvert, ap as createFileMapStore, aq as createMemoryStore, ar as createRemoteStore, as as createSession, au as fromAnthropic, av as fromOpenAI, aw as loadSession, aF as toAnthropic, aG as toOpenAI } from './agent-BAHrGtqu.js';
2
2
  import 'hookable';
3
- import './types-vA1a_ZX7.js';
3
+ import './types-Bai5rKpa.js';
4
4
  import '@modelcontextprotocol/sdk/client/index.js';
@@ -1,4 +1,4 @@
1
- import { Y as ToolDef, J as SkillConfig, aj as SkillActivationState, d as AgentHooks } from './agent-CMjWCUPr.js';
1
+ import { a7 as ToolDef, X as SkillConfig, V as SkillActivationState, A as AgentHooks } from './agent-BAHrGtqu.js';
2
2
  import { Hookable } from 'hookable';
3
3
 
4
4
  /**
package/dist/skills.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { d as AgentHooks, aj as SkillActivationState, J as SkillConfig, am as SkillSource, al as SkillDiagnostic, L as SkillsConfig } from './agent-CMjWCUPr.js';
2
- export { ab as ActivationVia, ac as ActiveSkill, ad as DeactivationReason, ak as SkillActivationStateOptions, K as SkillResource, ax as createSkillActivationState } from './agent-CMjWCUPr.js';
1
+ import { A as AgentHooks, V as SkillActivationState, X as SkillConfig, _ as SkillSource, Y as SkillDiagnostic, $ as SkillsConfig } from './agent-BAHrGtqu.js';
2
+ export { a as ActivationVia, b as ActiveSkill, D as DeactivationReason, W as SkillActivationStateOptions, Z as SkillResource, at as createSkillActivationState } from './agent-BAHrGtqu.js';
3
3
  import { Hookable } from 'hookable';
4
- import { b as ExecutionContext, c as ExecutionHandle } from './types-vA1a_ZX7.js';
4
+ import { a as ExecutionContext, c as ExecutionHandle } from './types-Bai5rKpa.js';
5
5
  import '@modelcontextprotocol/sdk/client/index.js';
6
6
 
7
7
  /**
package/dist/tools.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- export { S as SkillsReadToolOptions, a as SkillsRunScriptToolOptions, b as SkillsUseToolOptions, c as createSkillsReadTool, d as createSkillsRunScriptTool, e as createSkillsUseTool, f as edit, g as glob, h as grep, m as multiEdit } from './skills-use-6oJKUjk_.js';
2
- export { C as ChildAgent, I as InteractionToolOptions, S as SpawnToolOptions, a as SpawnToolState, V as ValidationResult, c as createInteractionTool, b as createSpawnTool, v as validateToolArgs } from './validation-BWV_pCdO.js';
3
- import { Y as ToolDef } from './agent-CMjWCUPr.js';
4
- export { X as ToolContext, $ as ToolMap } from './agent-CMjWCUPr.js';
1
+ export { S as SkillsReadToolOptions, a as SkillsRunScriptToolOptions, b as SkillsUseToolOptions, c as createSkillsReadTool, d as createSkillsRunScriptTool, e as createSkillsUseTool, f as edit, g as glob, h as grep, m as multiEdit } from './skills-use-DwZrNmcw.js';
2
+ export { C as ChildAgent, I as InteractionToolOptions, S as SpawnToolOptions, a as SpawnToolState, V as ValidationResult, c as createInteractionTool, b as createSpawnTool, v as validateToolArgs } from './validation-Pm--dQEU.js';
3
+ import { a7 as ToolDef } from './agent-BAHrGtqu.js';
4
+ export { a6 as ToolContext, aa as ToolMap } from './agent-BAHrGtqu.js';
5
5
  import 'hookable';
6
6
  import './presets.js';
7
- import './types-vA1a_ZX7.js';
7
+ import './types-Bai5rKpa.js';
8
8
  import '@modelcontextprotocol/sdk/client/index.js';
9
9
 
10
10
  declare const listFiles: ToolDef;
package/dist/tools.js CHANGED
@@ -14,8 +14,9 @@ import {
14
14
  shell,
15
15
  validateToolArgs,
16
16
  writeFile
17
- } from "./chunk-VTLEPYND.js";
17
+ } from "./chunk-4LPBN547.js";
18
18
  import "./chunk-6STZTA4N.js";
19
+ import "./chunk-IC7FT4OD.js";
19
20
  import "./chunk-UD25QF3H.js";
20
21
  import "./chunk-7GQ7P6DM.js";
21
22
  import "./chunk-JH6IAAFA.js";
@@ -86,4 +86,4 @@ interface ExecutionContext {
86
86
  destroy: (handle: ExecutionHandle) => Promise<void>;
87
87
  }
88
88
 
89
- export type { ContextCapabilities as C, ExecResult as E, SpawnConfig as S, ContextType as a, ExecutionContext as b, ExecutionHandle as c };
89
+ export type { ContextCapabilities as C, ExecResult as E, SpawnConfig as S, ExecutionContext as a, ContextType as b, ExecutionHandle as c };
package/dist/types.d.ts CHANGED
@@ -1,7 +1,55 @@
1
- export { A as Agent, a as AgentAbortedError, b as AgentBehavior, c as AgentContextExceededError, d as AgentHooks, e as AgentOptions, f as AgentProviderError, g as AgentRunOptions, h as AgentStats, i as AgentToolNotAllowedError, j as AnthropicParams, C as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, k as CerebrasParams, l as ChildRunStats, m as ClassifiedError, n as ClassifiedErrorKind, o as CreateSessionOptions, M as McpConnection, p as McpServerConfig, q as McpToolHookContext, O as OAuthRefreshHookContext, r as OpenAIParams, s as OpenRouterParams, P as PromptDocumentPart, t as PromptImagePart, u as PromptPart, v as PromptTextPart, w as Provider, x as ProviderCapabilities, R as RemoteStoreOptions, y as RunHookMap, S as Session, z as SessionContentBlock, B as SessionData, D as SessionEndStatus, E as SessionHookContext, F as SessionMessage, G as SessionRun, H as SessionStore, I as SessionTurn, J as SkillConfig, K as SkillResource, L as SkillsConfig, N as SpawnHookContext, Q as StreamCallbacks, T as StreamHookContext, U as StreamOptions, V as ThinkingLevel, W as ToolCall, X as ToolContext, Y as ToolDef, Z as ToolExecutionMode, _ as ToolHookContext, $ as ToolMap, a0 as ToolResult, a1 as ToolResultContent, a2 as ToolResultImageContent, a3 as ToolResultTextContent, a4 as ToolSpec, a5 as TurnFinishReason, a6 as TurnResult, a7 as TurnUsage, a8 as matchesContextExceeded, a9 as toolOutputByteLength, aa as toolResultToText } from './agent-CMjWCUPr.js';
2
- export { C as ContextCapabilities, a as ContextType, E as ExecResult, b as ExecutionContext, c as ExecutionHandle, S as SpawnConfig } from './types-vA1a_ZX7.js';
3
- export { S as SandboxProvider } from './sandbox-CLghrTLi.js';
1
+ import { j as AgentStats, ai as TurnUsage } from './agent-BAHrGtqu.js';
2
+ export { c as Agent, d as AgentAbortedError, e as AgentBehavior, f as AgentContextExceededError, A as AgentHooks, g as AgentOptions, h as AgentProviderError, i as AgentRunOptions, k as AgentToolNotAllowedError, l as AnthropicParams, C as CONTEXT_EXCEEDED_MESSAGE_PATTERNS, m as CerebrasParams, aK as ChildRunStats, n as ClassifiedError, o as ClassifiedErrorKind, p as CreateSessionOptions, M as McpConnection, r as McpServerConfig, s as McpToolHookContext, O as OAuthRefreshHookContext, w as OpenAIParams, x as OpenRouterParams, P as PromptDocumentPart, y as PromptImagePart, z as PromptPart, B as PromptTextPart, E as Provider, G as ProviderCapabilities, R as RemoteStoreOptions, H as RunHookMap, I as Session, J as SessionContentBlock, K as SessionData, L as SessionEndStatus, N as SessionHookContext, Q as SessionMessage, T as SessionRun, S as SessionStore, U as SessionTurn, X as SkillConfig, Z as SkillResource, $ as SkillsConfig, a0 as SpawnHookContext, a1 as StreamCallbacks, a2 as StreamHookContext, a3 as StreamOptions, a4 as ThinkingLevel, a5 as ToolCall, a6 as ToolContext, a7 as ToolDef, a8 as ToolExecutionMode, a9 as ToolHookContext, aa as ToolMap, ab as ToolResult, ac as ToolResultContent, ad as ToolResultImageContent, ae as ToolResultTextContent, af as ToolSpec, ag as TurnFinishReason, ah as TurnResult, ay as matchesContextExceeded, aI as toolOutputByteLength, aJ as toolResultToText } from './agent-BAHrGtqu.js';
3
+ export { C as ContextCapabilities, b as ContextType, E as ExecResult, a as ExecutionContext, c as ExecutionHandle, S as SpawnConfig } from './types-Bai5rKpa.js';
4
+ export { S as SandboxProvider } from './sandbox-D7v6Wy62.js';
4
5
  export { Preset } from './presets.js';
5
- export { C as ChildAgent, I as InteractionToolOptions, S as SpawnToolOptions, a as SpawnToolState, V as ValidationResult } from './validation-BWV_pCdO.js';
6
+ export { C as ChildAgent, I as InteractionToolOptions, S as SpawnToolOptions, a as SpawnToolState, V as ValidationResult } from './validation-Pm--dQEU.js';
6
7
  import 'hookable';
7
8
  import '@modelcontextprotocol/sdk/client/index.js';
9
+
10
+ /**
11
+ * Pure derivations over `AgentStats`.
12
+ *
13
+ * Both helpers are tree-shakeable — import only what you need. They never
14
+ * touch agent state, never do I/O, and always operate on the recursive
15
+ * `AgentStats` tree returned by `agent.run()`.
16
+ */
17
+
18
+ /**
19
+ * Per-model usage rollup produced by {@link statsByModel}.
20
+ *
21
+ * `turns` counts the number of `TurnUsage` entries attributed to the model
22
+ * across the whole tree (parent loop + every recursively-spawned child).
23
+ * Cache and cost numbers are summed from the same set of turns.
24
+ */
25
+ interface ModelUsage {
26
+ input: number;
27
+ output: number;
28
+ cost: number;
29
+ cacheRead: number;
30
+ cacheCreation: number;
31
+ turns: number;
32
+ }
33
+ /**
34
+ * Depth-first walk over the stats tree, returning every `TurnUsage` entry
35
+ * — parent loop first, then each child subtree in completion order.
36
+ *
37
+ * Closes the cache-token aggregation gap: `TurnUsage.cacheRead` /
38
+ * `cacheCreation` live only on per-turn entries, and the top-level
39
+ * `AgentStats` deliberately doesn't carry cumulative forms (one source of
40
+ * truth, no risk of drift). Anything that needs a tree-wide sum walks
41
+ * through this.
42
+ */
43
+ declare function flattenTurns(stats: AgentStats): TurnUsage[];
44
+ /**
45
+ * Group cumulative usage by `TurnUsage.modelId`. Each entry sums the input,
46
+ * output, cache, cost, and turn-count across every turn the tree attributed
47
+ * to that model — naturally handling cross-model runs (vision-fallback,
48
+ * model-shifted subagents, mixed-provider workflows).
49
+ *
50
+ * Turns missing `modelId` (mock providers, providers that don't echo a model
51
+ * id) are bucketed under the literal string `'(unknown)'`.
52
+ */
53
+ declare function statsByModel(stats: AgentStats): Map<string, ModelUsage>;
54
+
55
+ export { AgentStats, type ModelUsage, TurnUsage, flattenTurns, statsByModel };
package/dist/types.js CHANGED
@@ -1,3 +1,7 @@
1
+ import {
2
+ flattenTurns,
3
+ statsByModel
4
+ } from "./chunk-IC7FT4OD.js";
1
5
  import {
2
6
  toolOutputByteLength,
3
7
  toolResultToText
@@ -16,7 +20,9 @@ export {
16
20
  AgentProviderError,
17
21
  AgentToolNotAllowedError,
18
22
  CONTEXT_EXCEEDED_MESSAGE_PATTERNS,
23
+ flattenTurns,
19
24
  matchesContextExceeded,
25
+ statsByModel,
20
26
  toolOutputByteLength,
21
27
  toolResultToText
22
28
  };
@@ -1,4 +1,4 @@
1
- import { X as ToolContext, Y as ToolDef, h as AgentStats, l as ChildRunStats } from './agent-CMjWCUPr.js';
1
+ import { a6 as ToolContext, a7 as ToolDef, j as AgentStats, aK as ChildRunStats } from './agent-BAHrGtqu.js';
2
2
  import { Preset } from './presets.js';
3
3
 
4
4
  /**
@@ -84,7 +84,17 @@ interface ChildAgent {
84
84
  interface SpawnToolState {
85
85
  /** Currently running children. */
86
86
  readonly children: ReadonlyMap<string, ChildAgent>;
87
- /** Aggregated stats from all completed children (returns a copy). */
87
+ /**
88
+ * Cumulative stats across every completed direct child of this spawn-tool
89
+ * instance (returns a copy). Each child's contribution is the cumulative
90
+ * `AgentStats` returned by its `agent.run()` — so
91
+ * `totalIn`/`totalOut`/`totalCacheRead`/`totalCacheCreation` cover the
92
+ * entire subtree (children + grandchildren + …), while `turns` and
93
+ * `elapsed` stay parent-loop-only per child and are summed across direct
94
+ * children. `elapsed` over-counts when children ran in parallel.
95
+ *
96
+ * Lives across multiple parent runs that share this instance.
97
+ */
88
98
  readonly totalChildStats: Readonly<AgentStats>;
89
99
  }
90
100
  interface SpawnToolOptions {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zidane",
3
- "version": "3.4.1",
3
+ "version": "4.0.1",
4
4
  "description": "an agent that goes straight to the goal",
5
5
  "type": "module",
6
6
  "private": false,