@providerkit/agents 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/LICENSE-APACHE-2.0 +202 -0
  2. package/README.md +2108 -52
  3. package/THIRD_PARTY_NOTICES.md +521 -0
  4. package/dist/a2a/auth.d.ts +10 -0
  5. package/dist/a2a/auth.d.ts.map +1 -0
  6. package/dist/a2a/auth.js +52 -0
  7. package/dist/a2a/auth.js.map +1 -0
  8. package/dist/a2a/client.d.ts +74 -0
  9. package/dist/a2a/client.d.ts.map +1 -0
  10. package/dist/a2a/client.js +601 -0
  11. package/dist/a2a/client.js.map +1 -0
  12. package/dist/a2a/index.d.ts +22 -0
  13. package/dist/a2a/index.d.ts.map +1 -0
  14. package/dist/a2a/index.js +11 -0
  15. package/dist/a2a/index.js.map +1 -0
  16. package/dist/a2a/memory-runs.d.ts +62 -0
  17. package/dist/a2a/memory-runs.d.ts.map +1 -0
  18. package/dist/a2a/memory-runs.js +349 -0
  19. package/dist/a2a/memory-runs.js.map +1 -0
  20. package/dist/a2a/policy.d.ts +15 -0
  21. package/dist/a2a/policy.d.ts.map +1 -0
  22. package/dist/a2a/policy.js +114 -0
  23. package/dist/a2a/policy.js.map +1 -0
  24. package/dist/a2a/push.d.ts +34 -0
  25. package/dist/a2a/push.d.ts.map +1 -0
  26. package/dist/a2a/push.js +180 -0
  27. package/dist/a2a/push.js.map +1 -0
  28. package/dist/a2a/remote.d.ts +155 -0
  29. package/dist/a2a/remote.d.ts.map +1 -0
  30. package/dist/a2a/remote.js +1196 -0
  31. package/dist/a2a/remote.js.map +1 -0
  32. package/dist/a2a/server.d.ts +110 -0
  33. package/dist/a2a/server.d.ts.map +1 -0
  34. package/dist/a2a/server.js +1139 -0
  35. package/dist/a2a/server.js.map +1 -0
  36. package/dist/a2a/signing.d.ts +21 -0
  37. package/dist/a2a/signing.d.ts.map +1 -0
  38. package/dist/a2a/signing.js +305 -0
  39. package/dist/a2a/signing.js.map +1 -0
  40. package/dist/a2a/tasks.d.ts +88 -0
  41. package/dist/a2a/tasks.d.ts.map +1 -0
  42. package/dist/a2a/tasks.js +170 -0
  43. package/dist/a2a/tasks.js.map +1 -0
  44. package/dist/a2a/wire.d.ts +267 -0
  45. package/dist/a2a/wire.d.ts.map +1 -0
  46. package/dist/a2a/wire.js +1202 -0
  47. package/dist/a2a/wire.js.map +1 -0
  48. package/dist/background-types.d.ts +76 -0
  49. package/dist/background-types.d.ts.map +1 -0
  50. package/dist/background-types.js +2 -0
  51. package/dist/background-types.js.map +1 -0
  52. package/dist/child.d.ts +25 -0
  53. package/dist/child.d.ts.map +1 -0
  54. package/dist/child.js +129 -0
  55. package/dist/child.js.map +1 -0
  56. package/dist/code-driver.d.ts +40 -0
  57. package/dist/code-driver.d.ts.map +1 -0
  58. package/dist/code-driver.js +2 -0
  59. package/dist/code-driver.js.map +1 -0
  60. package/dist/code-mode.d.ts +3 -0
  61. package/dist/code-mode.d.ts.map +1 -0
  62. package/dist/code-mode.js +2 -0
  63. package/dist/code-mode.js.map +1 -0
  64. package/dist/code-script.d.ts +3 -0
  65. package/dist/code-script.d.ts.map +1 -0
  66. package/dist/code-script.js +149 -0
  67. package/dist/code-script.js.map +1 -0
  68. package/dist/code.d.ts +75 -0
  69. package/dist/code.d.ts.map +1 -0
  70. package/dist/code.js +326 -0
  71. package/dist/code.js.map +1 -0
  72. package/dist/compaction.d.ts +15 -0
  73. package/dist/compaction.d.ts.map +1 -0
  74. package/dist/compaction.js +168 -0
  75. package/dist/compaction.js.map +1 -0
  76. package/dist/delegation.d.ts +85 -16
  77. package/dist/delegation.d.ts.map +1 -1
  78. package/dist/delegation.js +240 -106
  79. package/dist/delegation.js.map +1 -1
  80. package/dist/evals/driver.d.ts +10 -0
  81. package/dist/evals/driver.d.ts.map +1 -0
  82. package/dist/evals/driver.js +192 -0
  83. package/dist/evals/driver.js.map +1 -0
  84. package/dist/evals/journal.d.ts +26 -0
  85. package/dist/evals/journal.d.ts.map +1 -0
  86. package/dist/evals/journal.js +483 -0
  87. package/dist/evals/journal.js.map +1 -0
  88. package/dist/evals/judge.d.ts +31 -0
  89. package/dist/evals/judge.d.ts.map +1 -0
  90. package/dist/evals/judge.js +142 -0
  91. package/dist/evals/judge.js.map +1 -0
  92. package/dist/evals/report.d.ts +38 -0
  93. package/dist/evals/report.d.ts.map +1 -0
  94. package/dist/evals/report.js +241 -0
  95. package/dist/evals/report.js.map +1 -0
  96. package/dist/evals/runner.d.ts +24 -0
  97. package/dist/evals/runner.d.ts.map +1 -0
  98. package/dist/evals/runner.js +655 -0
  99. package/dist/evals/runner.js.map +1 -0
  100. package/dist/evals/scorers.d.ts +36 -0
  101. package/dist/evals/scorers.d.ts.map +1 -0
  102. package/dist/evals/scorers.js +259 -0
  103. package/dist/evals/scorers.js.map +1 -0
  104. package/dist/evals/simulation.d.ts +7 -0
  105. package/dist/evals/simulation.d.ts.map +1 -0
  106. package/dist/evals/simulation.js +38 -0
  107. package/dist/evals/simulation.js.map +1 -0
  108. package/dist/evals/testing.d.ts +36 -0
  109. package/dist/evals/testing.d.ts.map +1 -0
  110. package/dist/evals/testing.js +87 -0
  111. package/dist/evals/testing.js.map +1 -0
  112. package/dist/evals/trajectory.d.ts +11 -0
  113. package/dist/evals/trajectory.d.ts.map +1 -0
  114. package/dist/evals/trajectory.js +180 -0
  115. package/dist/evals/trajectory.js.map +1 -0
  116. package/dist/evals/types.d.ts +431 -0
  117. package/dist/evals/types.d.ts.map +1 -0
  118. package/dist/evals/types.js +4 -0
  119. package/dist/evals/types.js.map +1 -0
  120. package/dist/evals.d.ts +14 -0
  121. package/dist/evals.d.ts.map +1 -0
  122. package/dist/evals.js +9 -0
  123. package/dist/evals.js.map +1 -0
  124. package/dist/extensions.d.ts +33 -0
  125. package/dist/extensions.d.ts.map +1 -0
  126. package/dist/extensions.js +188 -0
  127. package/dist/extensions.js.map +1 -0
  128. package/dist/handoff.d.ts +58 -0
  129. package/dist/handoff.d.ts.map +1 -0
  130. package/dist/handoff.js +160 -0
  131. package/dist/handoff.js.map +1 -0
  132. package/dist/index.d.ts +14 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +8 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/input.d.ts +42 -0
  137. package/dist/input.d.ts.map +1 -0
  138. package/dist/input.js +266 -0
  139. package/dist/input.js.map +1 -0
  140. package/dist/mcp.d.ts +77 -0
  141. package/dist/mcp.d.ts.map +1 -0
  142. package/dist/mcp.js +505 -0
  143. package/dist/mcp.js.map +1 -0
  144. package/dist/memory-store.d.ts +11 -0
  145. package/dist/memory-store.d.ts.map +1 -0
  146. package/dist/memory-store.js +272 -0
  147. package/dist/memory-store.js.map +1 -0
  148. package/dist/memory.d.ts +212 -0
  149. package/dist/memory.d.ts.map +1 -0
  150. package/dist/memory.js +613 -0
  151. package/dist/memory.js.map +1 -0
  152. package/dist/otel.d.ts +74 -0
  153. package/dist/otel.d.ts.map +1 -0
  154. package/dist/otel.js +427 -0
  155. package/dist/otel.js.map +1 -0
  156. package/dist/progress.d.ts +17 -0
  157. package/dist/progress.d.ts.map +1 -0
  158. package/dist/progress.js +193 -0
  159. package/dist/progress.js.map +1 -0
  160. package/dist/quickjs.d.ts +19 -0
  161. package/dist/quickjs.d.ts.map +1 -0
  162. package/dist/quickjs.js +519 -0
  163. package/dist/quickjs.js.map +1 -0
  164. package/dist/recovery.d.ts +10 -0
  165. package/dist/recovery.d.ts.map +1 -0
  166. package/dist/recovery.js +62 -0
  167. package/dist/recovery.js.map +1 -0
  168. package/dist/request.d.ts +88 -0
  169. package/dist/request.d.ts.map +1 -0
  170. package/dist/request.js +422 -0
  171. package/dist/request.js.map +1 -0
  172. package/dist/run.d.ts +16 -4
  173. package/dist/run.d.ts.map +1 -1
  174. package/dist/run.js +2016 -245
  175. package/dist/run.js.map +1 -1
  176. package/dist/runs.d.ts +77 -34
  177. package/dist/runs.d.ts.map +1 -1
  178. package/dist/runs.js +267 -85
  179. package/dist/runs.js.map +1 -1
  180. package/dist/schema-to-ts.d.ts +4 -0
  181. package/dist/schema-to-ts.d.ts.map +1 -0
  182. package/dist/schema-to-ts.js +191 -0
  183. package/dist/schema-to-ts.js.map +1 -0
  184. package/dist/session.d.ts +23 -0
  185. package/dist/session.d.ts.map +1 -0
  186. package/dist/session.js +137 -0
  187. package/dist/session.js.map +1 -0
  188. package/dist/snapshot.d.ts +57 -8
  189. package/dist/snapshot.d.ts.map +1 -1
  190. package/dist/snapshot.js +1206 -109
  191. package/dist/snapshot.js.map +1 -1
  192. package/dist/steering.d.ts +75 -0
  193. package/dist/steering.d.ts.map +1 -0
  194. package/dist/steering.js +214 -0
  195. package/dist/steering.js.map +1 -0
  196. package/dist/subagents.d.ts +141 -0
  197. package/dist/subagents.d.ts.map +1 -0
  198. package/dist/subagents.js +746 -0
  199. package/dist/subagents.js.map +1 -0
  200. package/dist/tool-retry.d.ts +12 -0
  201. package/dist/tool-retry.d.ts.map +1 -0
  202. package/dist/tool-retry.js +53 -0
  203. package/dist/tool-retry.js.map +1 -0
  204. package/dist/tree.d.ts +62 -6
  205. package/dist/tree.d.ts.map +1 -1
  206. package/dist/tree.js +192 -23
  207. package/dist/tree.js.map +1 -1
  208. package/dist/types.d.ts +767 -52
  209. package/dist/types.d.ts.map +1 -1
  210. package/dist/workflow-snapshot.d.ts +8 -0
  211. package/dist/workflow-snapshot.d.ts.map +1 -0
  212. package/dist/workflow-snapshot.js +276 -0
  213. package/dist/workflow-snapshot.js.map +1 -0
  214. package/dist/workflow-types.d.ts +171 -0
  215. package/dist/workflow-types.d.ts.map +1 -0
  216. package/dist/workflow-types.js +2 -0
  217. package/dist/workflow-types.js.map +1 -0
  218. package/dist/workflow.d.ts +19 -0
  219. package/dist/workflow.d.ts.map +1 -0
  220. package/dist/workflow.js +1053 -0
  221. package/dist/workflow.js.map +1 -0
  222. package/examples/a2a-remote.ts +85 -0
  223. package/examples/a2a-server.ts +100 -0
  224. package/examples/background.ts +18 -4
  225. package/examples/code-mode.ts +76 -0
  226. package/examples/conversation.ts +57 -0
  227. package/examples/evals.ts +79 -0
  228. package/examples/guardrails.ts +56 -0
  229. package/examples/handoff.ts +79 -0
  230. package/examples/memory.ts +44 -0
  231. package/examples/otel.ts +99 -0
  232. package/examples/steering.ts +69 -0
  233. package/examples/structured-handoff.ts +92 -0
  234. package/examples/subagents.ts +127 -0
  235. package/examples/workflow.ts +74 -0
  236. package/package.json +58 -6
  237. package/src/a2a/auth.ts +62 -0
  238. package/src/a2a/client.ts +733 -0
  239. package/src/a2a/index.ts +74 -0
  240. package/src/a2a/memory-runs.ts +448 -0
  241. package/src/a2a/policy.ts +148 -0
  242. package/src/a2a/push.ts +251 -0
  243. package/src/a2a/remote.ts +1652 -0
  244. package/src/a2a/server.ts +1390 -0
  245. package/src/a2a/signing.ts +348 -0
  246. package/src/a2a/tasks.ts +260 -0
  247. package/src/a2a/wire.ts +1443 -0
  248. package/src/background-types.ts +86 -0
  249. package/src/child.ts +181 -0
  250. package/src/code-driver.ts +48 -0
  251. package/src/code-mode.ts +12 -0
  252. package/src/code-script.ts +149 -0
  253. package/src/code.ts +424 -0
  254. package/src/compaction.ts +212 -0
  255. package/src/delegation.ts +444 -155
  256. package/src/evals/driver.ts +222 -0
  257. package/src/evals/journal.ts +605 -0
  258. package/src/evals/judge.ts +188 -0
  259. package/src/evals/report.ts +295 -0
  260. package/src/evals/runner.ts +826 -0
  261. package/src/evals/scorers.ts +339 -0
  262. package/src/evals/simulation.ts +46 -0
  263. package/src/evals/testing.ts +126 -0
  264. package/src/evals/trajectory.ts +223 -0
  265. package/src/evals/types.ts +463 -0
  266. package/src/evals.ts +72 -0
  267. package/src/extensions.ts +247 -0
  268. package/src/handoff.ts +214 -0
  269. package/src/index.ts +51 -0
  270. package/src/input.ts +319 -0
  271. package/src/mcp.ts +690 -0
  272. package/src/memory-store.ts +366 -0
  273. package/src/memory.ts +893 -0
  274. package/src/otel.ts +568 -0
  275. package/src/progress.ts +214 -0
  276. package/src/quickjs.ts +524 -0
  277. package/src/recovery.ts +90 -0
  278. package/src/request.ts +513 -0
  279. package/src/run.ts +2678 -313
  280. package/src/runs.ts +464 -133
  281. package/src/schema-to-ts.ts +194 -0
  282. package/src/session.ts +178 -0
  283. package/src/snapshot.ts +1595 -124
  284. package/src/steering.ts +329 -0
  285. package/src/subagents.ts +1084 -0
  286. package/src/tool-retry.ts +86 -0
  287. package/src/tree.ts +223 -27
  288. package/src/types.ts +711 -52
  289. package/src/workflow-snapshot.ts +366 -0
  290. package/src/workflow-types.ts +213 -0
  291. package/src/workflow.ts +1316 -0
@@ -0,0 +1,86 @@
1
+ // Budget check adapted from PydanticAI (MIT), tool_manager.py, _check_max_retries.
2
+ // Copyright (c) Pydantic Services Inc. 2024 to present.
3
+ // Changed: default zero retries, exact operation attempts, no model-directed replay permission.
4
+ import type { Tool } from "@providerkit/core";
5
+ import { recoveryToolHash } from "./recovery.ts";
6
+ import { copyData, isId, isRecord } from "./snapshot.ts";
7
+ import { fail } from "./tree.ts";
8
+ import type { ToolExecution, ToolRetryDefinition, ToolRetryPolicy } from "./types.ts";
9
+
10
+ export function isToolRetryPolicy(value: unknown): value is ToolRetryPolicy {
11
+ return (
12
+ isRecord(value) &&
13
+ isId(value.identity) &&
14
+ isRecord(value.tools) &&
15
+ Object.entries(value.tools).every(
16
+ ([name, policy]) =>
17
+ isId(name) &&
18
+ isRecord(policy) &&
19
+ typeof policy.maxAttempts === "number" &&
20
+ Number.isSafeInteger(policy.maxAttempts) &&
21
+ policy.maxAttempts > 0 &&
22
+ ["read-only", "reconcile"].includes(String(policy.replay)),
23
+ )
24
+ );
25
+ }
26
+
27
+ export function readToolRetryPolicy(value: unknown): ToolRetryPolicy | null {
28
+ if (value === undefined) return null;
29
+ if (!isToolRetryPolicy(value))
30
+ throw new TypeError(
31
+ "toolRetries needs an identity and named tool budgets with maxAttempts and replay.",
32
+ );
33
+ return copyData(value);
34
+ }
35
+
36
+ export function isToolRetryDefinition(value: unknown): value is ToolRetryDefinition | null {
37
+ return (
38
+ value === null ||
39
+ (isRecord(value) &&
40
+ isToolRetryPolicy(value.policy) &&
41
+ isRecord(value.toolHashes) &&
42
+ Object.keys(value.toolHashes).length === Object.keys(value.policy.tools).length &&
43
+ Object.keys(value.policy.tools).every(
44
+ (name) =>
45
+ isRecord(value.toolHashes) &&
46
+ typeof value.toolHashes[name] === "string" &&
47
+ /^sha256:[a-f0-9]{64}$/.test(value.toolHashes[name]),
48
+ ))
49
+ );
50
+ }
51
+
52
+ export function retryBudget(definition: ToolRetryDefinition | null, name: string) {
53
+ return definition && Object.hasOwn(definition.policy.tools, name)
54
+ ? definition.policy.tools[name]
55
+ : undefined;
56
+ }
57
+
58
+ export function toolAttempts(tool: ToolExecution): number {
59
+ return (
60
+ tool.retries.length +
61
+ tool.interrupted.length +
62
+ (tool.status !== "pending" || tool.asks?.length ? 1 : 0)
63
+ );
64
+ }
65
+
66
+ export async function checkRetryTool(
67
+ tool: Tool | undefined,
68
+ definition: ToolRetryDefinition,
69
+ execution: ToolExecution,
70
+ ): Promise<void> {
71
+ const policy = tool && retryBudget(definition, tool.name);
72
+ if (
73
+ !tool ||
74
+ !policy ||
75
+ tool.isTerminal ||
76
+ tool.needsApproval ||
77
+ execution.asks?.length ||
78
+ (policy.replay === "read-only" && !tool.isReadOnly) ||
79
+ (await recoveryToolHash(tool)) !== definition.toolHashes[tool.name]
80
+ )
81
+ fail(
82
+ "tool_retry_unsafe",
83
+ "This tool cannot be retried under its saved policy. Reconcile the failed call with the host.",
84
+ execution.id,
85
+ );
86
+ }
package/src/tree.ts CHANGED
@@ -1,6 +1,20 @@
1
1
  import { EMPTY_USAGE, addUsage, createGate, messageOf, type TokenUsage } from "@providerkit/core";
2
- import { immutableCopy } from "./snapshot.ts";
3
- import type { AgentHost, RunOptions, RunSnapshot, RunState } from "./types.ts";
2
+ import type { RemoteSend } from "./a2a/remote.ts";
3
+ import { allModels } from "./compaction.ts";
4
+ import { modelUsage } from "./recovery.ts";
5
+ import { copyData, immutableCopy, isRecord } from "./snapshot.ts";
6
+ import type { StepExecution } from "./workflow-types.ts";
7
+ import type {
8
+ AgentEvent,
9
+ AgentHost,
10
+ AskRecord,
11
+ ChildPathStep,
12
+ RunOptions,
13
+ TreeNode,
14
+ RunState,
15
+ ToolExecution,
16
+ UserContent,
17
+ } from "./types.ts";
4
18
 
5
19
  export type StopState = Exclude<RunState, { status: "running" | "completed" }>;
6
20
 
@@ -10,10 +24,50 @@ export class Halt extends Error {
10
24
  }
11
25
  }
12
26
 
27
+ /** Only known specialist-local outcomes can become tool data. Unknown codes fail closed. */
28
+ export function isLocalStop(state: RunState): boolean {
29
+ return (
30
+ (state.status === "limited" &&
31
+ ["turns", "toolCalls", "elapsedMs", "outputTokens", "steps"].includes(state.limit)) ||
32
+ (state.status === "failed" &&
33
+ [
34
+ "model_failed",
35
+ "step_failed",
36
+ "workflow_failed",
37
+ "invalid_model_output",
38
+ "content_filtered",
39
+ "incomplete_turn",
40
+ "missing_result",
41
+ "empty_output",
42
+ "memory_missing",
43
+ "memory_unavailable",
44
+ "remote_failed",
45
+ "remote_invalid_output",
46
+ "remote_auth_required",
47
+ "remote_input_required",
48
+ "remote_request_unsupported",
49
+ "remote_result_too_large",
50
+ "remote_cancelled",
51
+ ].includes(state.error.code))
52
+ );
53
+ }
54
+
13
55
  export function fail(code: string, message: string, operationId?: string): never {
14
56
  throw new Halt({ status: "failed", error: { code, message, operationId } });
15
57
  }
16
58
 
59
+ /** Progress is not the durable journal, and an observer cannot stop execution. It gets a
60
+ * frozen copy, is never awaited, and whatever it throws or rejects with is dropped. */
61
+ export function emitEvent(options: RunOptions, event: AgentEvent): void {
62
+ // Storage is not an observer. Its failures must reach execution and the checkpoint barrier.
63
+ options.host?.progress?.push(immutableCopy(event));
64
+ try {
65
+ void Promise.resolve(options.onEvent?.(immutableCopy(event))).catch(() => {});
66
+ } catch {
67
+ // Dropped on purpose: see above.
68
+ }
69
+ }
70
+
17
71
  /** Cancellation stops SDK work, not external effects which ignore their signal. */
18
72
  export async function untilAbort<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
19
73
  let onAbort = () => {};
@@ -31,27 +85,125 @@ export async function untilAbort<T>(work: Promise<T>, signal: AbortSignal): Prom
31
85
  }
32
86
  }
33
87
 
34
- export function* snapshots(root: RunSnapshot): Generator<RunSnapshot> {
88
+ export function childJournals(root: TreeNode) {
89
+ return root.kind === "agent"
90
+ ? root.delegations
91
+ : root.kind === "remote"
92
+ ? []
93
+ : root.steps.map((step) => ({
94
+ operationId: step.id,
95
+ children: step.children,
96
+ }));
97
+ }
98
+
99
+ export function nodeId(node: TreeNode): string {
100
+ return node.kind === "workflow" ? node.workflowId : node.agentId;
101
+ }
102
+
103
+ export function* snapshots(root: TreeNode): Generator<TreeNode> {
35
104
  yield root;
36
- for (const delegation of root.delegations)
37
- for (const child of delegation.children) yield* snapshots(child.snapshot);
105
+ for (const journal of childJournals(root))
106
+ for (const child of journal.children) yield* snapshots(child.snapshot);
107
+ }
108
+
109
+ export function wakeAt(root: TreeNode): number | undefined {
110
+ const wakes = [...snapshots(root)].flatMap((node) => {
111
+ if (node.state.status !== "running" && node.state.status !== "suspended") return [];
112
+ if (node.kind === "remote") return node.remote.wakeAt === undefined ? [] : [node.remote.wakeAt];
113
+ return node.kind === "workflow"
114
+ ? node.steps.flatMap((step) =>
115
+ (step.status === "waiting" || step.status === "retrying") && step.wakeAt !== undefined
116
+ ? [step.wakeAt]
117
+ : [],
118
+ )
119
+ : [];
120
+ });
121
+ return wakes.length ? Math.min(...wakes) : undefined;
122
+ }
123
+
124
+ /** Requests come from the effect journal, in tool and child admission order. */
125
+ export function* requestRecords(root: TreeNode): Generator<{
126
+ record: AskRecord;
127
+ execution: ToolExecution | StepExecution | RemoteSend;
128
+ snapshot: TreeNode;
129
+ }> {
130
+ if (root.kind === "remote") {
131
+ for (const execution of root.remote.sends)
132
+ for (const record of execution.asks ?? []) yield { record, execution, snapshot: root };
133
+ return;
134
+ }
135
+ if (root.kind === "workflow") {
136
+ for (const execution of root.steps) {
137
+ for (const record of execution.asks ?? []) yield { record, execution, snapshot: root };
138
+ for (const child of execution.children) yield* requestRecords(child.snapshot);
139
+ }
140
+ return;
141
+ }
142
+ for (const model of root.models) {
143
+ if (model.status !== "completed") continue;
144
+ for (const execution of model.tools) {
145
+ for (const record of execution.asks ?? []) yield { record, execution, snapshot: root };
146
+ for (const call of execution.calls ?? [])
147
+ for (const record of call.asks ?? []) yield { record, execution: call, snapshot: root };
148
+ const delegation = root.delegations.find((journal) => journal.operationId === execution.id);
149
+ for (const child of delegation?.children ?? []) yield* requestRecords(child.snapshot);
150
+ }
151
+ }
152
+ }
153
+
154
+ export function openRequests(root: TreeNode) {
155
+ if (root.state.status !== "running" && root.state.status !== "suspended") return [];
156
+ return [...requestRecords(root)]
157
+ .filter(
158
+ ({ record, execution, snapshot }) =>
159
+ (snapshot.state.status === "running" || snapshot.state.status === "suspended") &&
160
+ execution.status !== "completed" &&
161
+ !record.request.call?.parentOperationId &&
162
+ !record.decision &&
163
+ !record.closed,
164
+ )
165
+ .map(({ record }) => ({
166
+ ...copyData(record.request),
167
+ ...(record.problem ? { problem: copyData(record.problem) } : {}),
168
+ }));
169
+ }
170
+
171
+ /** Do this before authorization callbacks. A JSON object cannot contain duplicate keys after
172
+ * parsing; HTTP hosts must reject duplicate raw JSON members before constructing this map. */
173
+ export function readAnswers(root: TreeNode, value: unknown): Record<string, unknown> {
174
+ if (!isRecord(value) || Object.values(value).some((evidence) => evidence === undefined))
175
+ throw new TypeError("Provide JSON evidence by request id.");
176
+ const pending = new Set(openRequests(root).map((request) => request.id));
177
+ for (const id of Object.keys(value))
178
+ if (!pending.has(id))
179
+ throw new TypeError("An answer names an unknown, closed or already-decided request.");
180
+ return copyData(value);
181
+ }
182
+
183
+ export function stopRequests(root: TreeNode): void {
184
+ for (const { record } of requestRecords(root))
185
+ if (!record.closed && !record.decision) record.closed = "stopped";
186
+ for (const snapshot of snapshots(root))
187
+ if (snapshot.state.status === "running" || snapshot.state.status === "suspended")
188
+ snapshot.state = { status: "cancelled" };
38
189
  }
39
190
 
40
191
  /** Count local receipts once. Never add a child's already aggregated total. */
41
- export function treeUsage(root: RunSnapshot): TokenUsage {
192
+ export function treeUsage(root: TreeNode): TokenUsage {
42
193
  let usage = { ...EMPTY_USAGE };
43
194
  const seen = new Set<string>();
44
195
  for (const snapshot of snapshots(root)) {
45
- for (const model of snapshot.models) {
196
+ if (snapshot.kind !== "agent") continue;
197
+ for (const model of allModels(snapshot)) {
46
198
  if (seen.has(model.id)) continue;
47
199
  seen.add(model.id);
48
- usage = addUsage(usage, model.usage);
200
+ usage = addUsage(usage, modelUsage(model));
49
201
  }
50
202
  }
51
203
  return usage;
52
204
  }
53
205
 
54
- export async function authorizeTree(root: RunSnapshot, host: AgentHost): Promise<void> {
206
+ export async function authorizeTree(root: TreeNode, host: AgentHost): Promise<void> {
55
207
  if (!host.authorizeResume)
56
208
  throw new TypeError("Resume requires a trusted host.authorizeResume callback.");
57
209
  // A parent's ownership is not authority over a descendant's tools or approvals.
@@ -71,7 +223,7 @@ export class ExecutionTree {
71
223
  private checkpointFailure: Extract<RunState, { status: "failed" }> | undefined;
72
224
 
73
225
  constructor(
74
- readonly root: RunSnapshot,
226
+ readonly root: TreeNode,
75
227
  private readonly options: RunOptions,
76
228
  ) {
77
229
  this.gate = createGate(root.tree.limits.maxParallel);
@@ -86,9 +238,16 @@ export class ExecutionTree {
86
238
  );
87
239
  }
88
240
 
241
+ /** A failed checkpoint fails every later one, so the host's saved journal stops at the last
242
+ * write that succeeded and the returned state was never stored. */
243
+ get checkpointFailed(): boolean {
244
+ return this.checkpointFailure !== undefined;
245
+ }
246
+
89
247
  active(): void {
90
248
  if (this.checkpointFailure) throw new Halt(this.checkpointFailure);
91
- if (this.options.signal?.aborted) throw new Halt({ status: "cancelled" });
249
+ if (this.options.signal?.aborted || this.root.state.status === "cancelled")
250
+ throw new Halt({ status: "cancelled" });
92
251
  if (
93
252
  this.timeout.signal.aborted ||
94
253
  Date.now() >= this.root.tree.startedAt + this.root.tree.limits.elapsedMs
@@ -101,11 +260,21 @@ export class ExecutionTree {
101
260
  // ponytail: a bounded tree is small. Deriving counters from the journal also
102
261
  // preserves every reservation across resume without a second mutable ledger.
103
262
  let models = 0;
104
- for (const snapshot of snapshots(this.root)) models += snapshot.models.length;
263
+ for (const snapshot of snapshots(this.root))
264
+ if (snapshot.kind === "agent")
265
+ for (const model of allModels(snapshot)) models += 1 + model.interrupted.length;
105
266
  if (models >= this.root.tree.limits.modelCalls)
106
267
  throw new Halt({ status: "limited", limit: "modelCalls" });
107
268
  }
108
269
 
270
+ /** Preflight only. reserveChild rechecks against the live journal at each admission. */
271
+ childRoom(depth: number): number {
272
+ this.active();
273
+ return depth > this.root.tree.limits.maxDepth
274
+ ? 0
275
+ : this.root.tree.limits.maxChildren - ([...snapshots(this.root)].length - 1);
276
+ }
277
+
109
278
  reserveChild(depth: number): void {
110
279
  this.active();
111
280
  if (depth > this.root.tree.limits.maxDepth)
@@ -141,22 +310,45 @@ export class ExecutionTree {
141
310
  const saved = immutableCopy(this.root);
142
311
  // Every descendant writes the whole root through this one queue. Capturing at
143
312
  // enqueue time keeps a slow earlier save from erasing a newer child's receipt.
144
- this.writes = this.writes.then(async () => {
145
- await this.options.host?.checkpoint?.(saved);
313
+ // Seal progress at the same boundary as the snapshot, not when a queued write eventually
314
+ // runs. Handle its rejection now even if an older checkpoint is still pending.
315
+ const progress = (async () => {
316
+ try {
317
+ await this.options.host?.progress?.flush();
318
+ return { ok: true as const };
319
+ } catch (cause) {
320
+ return { ok: false as const, cause };
321
+ }
322
+ })();
323
+ const write = this.writes.then(async () => {
324
+ if (this.checkpointFailure) throw new Halt(this.checkpointFailure);
325
+ try {
326
+ const flushed = await progress;
327
+ if (!flushed.ok) throw flushed.cause;
328
+ await this.options.host?.checkpoint?.(saved);
329
+ } catch (error) {
330
+ this.checkpointFailure = {
331
+ status: "failed",
332
+ error: {
333
+ code: "checkpoint_failed",
334
+ message: `Checkpoint failed: ${messageOf(error)}. Reconcile stored state before resuming.`,
335
+ },
336
+ };
337
+ this.broken.abort(error);
338
+ throw new Halt(this.checkpointFailure);
339
+ }
146
340
  });
147
- try {
148
- await this.writes;
149
- } catch (error) {
150
- this.checkpointFailure ??= {
151
- status: "failed",
152
- error: {
153
- code: "checkpoint_failed",
154
- message: `Checkpoint failed: ${messageOf(error)}. Reconcile stored state before resuming.`,
155
- },
156
- };
157
- this.broken.abort(error);
158
- throw new Halt(this.checkpointFailure);
159
- }
341
+ // Fail closed through checkpointFailure, not a poisoned promise chain.
342
+ this.writes = write.then(
343
+ () => {},
344
+ () => {},
345
+ );
346
+ await write;
347
+ }
348
+
349
+ stop(): void {
350
+ stopRequests(this.root);
351
+ this.broken.abort(new Halt({ status: "cancelled" }));
160
352
  }
161
353
 
162
354
  close(): void {
@@ -167,4 +359,8 @@ export class ExecutionTree {
167
359
  export interface ExecutionScope {
168
360
  tree: ExecutionTree;
169
361
  depth: number;
362
+ path: ChildPathStep[];
363
+ /** Latest real user input along this handoff chain, rebuilt from the source journals.
364
+ * A handoff's own input is an SDK transfer notice, not a recall query. */
365
+ handoffInput?: UserContent;
170
366
  }