@providerkit/agents 0.0.0-stage → 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 (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/README.md +2328 -2
  4. package/THIRD_PARTY_NOTICES.md +521 -0
  5. package/dist/a2a/auth.d.ts +10 -0
  6. package/dist/a2a/auth.d.ts.map +1 -0
  7. package/dist/a2a/auth.js +52 -0
  8. package/dist/a2a/auth.js.map +1 -0
  9. package/dist/a2a/client.d.ts +74 -0
  10. package/dist/a2a/client.d.ts.map +1 -0
  11. package/dist/a2a/client.js +601 -0
  12. package/dist/a2a/client.js.map +1 -0
  13. package/dist/a2a/index.d.ts +22 -0
  14. package/dist/a2a/index.d.ts.map +1 -0
  15. package/dist/a2a/index.js +11 -0
  16. package/dist/a2a/index.js.map +1 -0
  17. package/dist/a2a/memory-runs.d.ts +62 -0
  18. package/dist/a2a/memory-runs.d.ts.map +1 -0
  19. package/dist/a2a/memory-runs.js +349 -0
  20. package/dist/a2a/memory-runs.js.map +1 -0
  21. package/dist/a2a/policy.d.ts +15 -0
  22. package/dist/a2a/policy.d.ts.map +1 -0
  23. package/dist/a2a/policy.js +114 -0
  24. package/dist/a2a/policy.js.map +1 -0
  25. package/dist/a2a/push.d.ts +34 -0
  26. package/dist/a2a/push.d.ts.map +1 -0
  27. package/dist/a2a/push.js +180 -0
  28. package/dist/a2a/push.js.map +1 -0
  29. package/dist/a2a/remote.d.ts +155 -0
  30. package/dist/a2a/remote.d.ts.map +1 -0
  31. package/dist/a2a/remote.js +1196 -0
  32. package/dist/a2a/remote.js.map +1 -0
  33. package/dist/a2a/server.d.ts +110 -0
  34. package/dist/a2a/server.d.ts.map +1 -0
  35. package/dist/a2a/server.js +1139 -0
  36. package/dist/a2a/server.js.map +1 -0
  37. package/dist/a2a/signing.d.ts +21 -0
  38. package/dist/a2a/signing.d.ts.map +1 -0
  39. package/dist/a2a/signing.js +305 -0
  40. package/dist/a2a/signing.js.map +1 -0
  41. package/dist/a2a/tasks.d.ts +88 -0
  42. package/dist/a2a/tasks.d.ts.map +1 -0
  43. package/dist/a2a/tasks.js +170 -0
  44. package/dist/a2a/tasks.js.map +1 -0
  45. package/dist/a2a/wire.d.ts +267 -0
  46. package/dist/a2a/wire.d.ts.map +1 -0
  47. package/dist/a2a/wire.js +1202 -0
  48. package/dist/a2a/wire.js.map +1 -0
  49. package/dist/background-types.d.ts +76 -0
  50. package/dist/background-types.d.ts.map +1 -0
  51. package/dist/background-types.js +2 -0
  52. package/dist/background-types.js.map +1 -0
  53. package/dist/child.d.ts +25 -0
  54. package/dist/child.d.ts.map +1 -0
  55. package/dist/child.js +129 -0
  56. package/dist/child.js.map +1 -0
  57. package/dist/code-driver.d.ts +40 -0
  58. package/dist/code-driver.d.ts.map +1 -0
  59. package/dist/code-driver.js +2 -0
  60. package/dist/code-driver.js.map +1 -0
  61. package/dist/code-mode.d.ts +3 -0
  62. package/dist/code-mode.d.ts.map +1 -0
  63. package/dist/code-mode.js +2 -0
  64. package/dist/code-mode.js.map +1 -0
  65. package/dist/code-script.d.ts +3 -0
  66. package/dist/code-script.d.ts.map +1 -0
  67. package/dist/code-script.js +149 -0
  68. package/dist/code-script.js.map +1 -0
  69. package/dist/code.d.ts +75 -0
  70. package/dist/code.d.ts.map +1 -0
  71. package/dist/code.js +326 -0
  72. package/dist/code.js.map +1 -0
  73. package/dist/compaction.d.ts +15 -0
  74. package/dist/compaction.d.ts.map +1 -0
  75. package/dist/compaction.js +168 -0
  76. package/dist/compaction.js.map +1 -0
  77. package/dist/delegation.d.ts +135 -0
  78. package/dist/delegation.d.ts.map +1 -0
  79. package/dist/delegation.js +401 -0
  80. package/dist/delegation.js.map +1 -0
  81. package/dist/evals/driver.d.ts +10 -0
  82. package/dist/evals/driver.d.ts.map +1 -0
  83. package/dist/evals/driver.js +192 -0
  84. package/dist/evals/driver.js.map +1 -0
  85. package/dist/evals/journal.d.ts +26 -0
  86. package/dist/evals/journal.d.ts.map +1 -0
  87. package/dist/evals/journal.js +483 -0
  88. package/dist/evals/journal.js.map +1 -0
  89. package/dist/evals/judge.d.ts +31 -0
  90. package/dist/evals/judge.d.ts.map +1 -0
  91. package/dist/evals/judge.js +142 -0
  92. package/dist/evals/judge.js.map +1 -0
  93. package/dist/evals/report.d.ts +38 -0
  94. package/dist/evals/report.d.ts.map +1 -0
  95. package/dist/evals/report.js +241 -0
  96. package/dist/evals/report.js.map +1 -0
  97. package/dist/evals/runner.d.ts +24 -0
  98. package/dist/evals/runner.d.ts.map +1 -0
  99. package/dist/evals/runner.js +655 -0
  100. package/dist/evals/runner.js.map +1 -0
  101. package/dist/evals/scorers.d.ts +36 -0
  102. package/dist/evals/scorers.d.ts.map +1 -0
  103. package/dist/evals/scorers.js +259 -0
  104. package/dist/evals/scorers.js.map +1 -0
  105. package/dist/evals/simulation.d.ts +7 -0
  106. package/dist/evals/simulation.d.ts.map +1 -0
  107. package/dist/evals/simulation.js +38 -0
  108. package/dist/evals/simulation.js.map +1 -0
  109. package/dist/evals/testing.d.ts +36 -0
  110. package/dist/evals/testing.d.ts.map +1 -0
  111. package/dist/evals/testing.js +87 -0
  112. package/dist/evals/testing.js.map +1 -0
  113. package/dist/evals/trajectory.d.ts +11 -0
  114. package/dist/evals/trajectory.d.ts.map +1 -0
  115. package/dist/evals/trajectory.js +180 -0
  116. package/dist/evals/trajectory.js.map +1 -0
  117. package/dist/evals/types.d.ts +431 -0
  118. package/dist/evals/types.d.ts.map +1 -0
  119. package/dist/evals/types.js +4 -0
  120. package/dist/evals/types.js.map +1 -0
  121. package/dist/evals.d.ts +14 -0
  122. package/dist/evals.d.ts.map +1 -0
  123. package/dist/evals.js +9 -0
  124. package/dist/evals.js.map +1 -0
  125. package/dist/extensions.d.ts +33 -0
  126. package/dist/extensions.d.ts.map +1 -0
  127. package/dist/extensions.js +188 -0
  128. package/dist/extensions.js.map +1 -0
  129. package/dist/handoff.d.ts +58 -0
  130. package/dist/handoff.d.ts.map +1 -0
  131. package/dist/handoff.js +160 -0
  132. package/dist/handoff.js.map +1 -0
  133. package/dist/index.d.ts +19 -0
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +11 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/input.d.ts +42 -0
  138. package/dist/input.d.ts.map +1 -0
  139. package/dist/input.js +266 -0
  140. package/dist/input.js.map +1 -0
  141. package/dist/mcp.d.ts +77 -0
  142. package/dist/mcp.d.ts.map +1 -0
  143. package/dist/mcp.js +505 -0
  144. package/dist/mcp.js.map +1 -0
  145. package/dist/memory-store.d.ts +11 -0
  146. package/dist/memory-store.d.ts.map +1 -0
  147. package/dist/memory-store.js +272 -0
  148. package/dist/memory-store.js.map +1 -0
  149. package/dist/memory.d.ts +212 -0
  150. package/dist/memory.d.ts.map +1 -0
  151. package/dist/memory.js +613 -0
  152. package/dist/memory.js.map +1 -0
  153. package/dist/otel.d.ts +74 -0
  154. package/dist/otel.d.ts.map +1 -0
  155. package/dist/otel.js +427 -0
  156. package/dist/otel.js.map +1 -0
  157. package/dist/progress.d.ts +17 -0
  158. package/dist/progress.d.ts.map +1 -0
  159. package/dist/progress.js +193 -0
  160. package/dist/progress.js.map +1 -0
  161. package/dist/quickjs.d.ts +19 -0
  162. package/dist/quickjs.d.ts.map +1 -0
  163. package/dist/quickjs.js +519 -0
  164. package/dist/quickjs.js.map +1 -0
  165. package/dist/recovery.d.ts +10 -0
  166. package/dist/recovery.d.ts.map +1 -0
  167. package/dist/recovery.js +62 -0
  168. package/dist/recovery.js.map +1 -0
  169. package/dist/request.d.ts +88 -0
  170. package/dist/request.d.ts.map +1 -0
  171. package/dist/request.js +422 -0
  172. package/dist/request.js.map +1 -0
  173. package/dist/run.d.ts +20 -0
  174. package/dist/run.d.ts.map +1 -0
  175. package/dist/run.js +2407 -0
  176. package/dist/run.js.map +1 -0
  177. package/dist/runs.d.ts +110 -0
  178. package/dist/runs.d.ts.map +1 -0
  179. package/dist/runs.js +438 -0
  180. package/dist/runs.js.map +1 -0
  181. package/dist/schema-to-ts.d.ts +4 -0
  182. package/dist/schema-to-ts.d.ts.map +1 -0
  183. package/dist/schema-to-ts.js +191 -0
  184. package/dist/schema-to-ts.js.map +1 -0
  185. package/dist/session.d.ts +23 -0
  186. package/dist/session.d.ts.map +1 -0
  187. package/dist/session.js +137 -0
  188. package/dist/session.js.map +1 -0
  189. package/dist/snapshot.d.ts +75 -0
  190. package/dist/snapshot.d.ts.map +1 -0
  191. package/dist/snapshot.js +1607 -0
  192. package/dist/snapshot.js.map +1 -0
  193. package/dist/steering.d.ts +75 -0
  194. package/dist/steering.d.ts.map +1 -0
  195. package/dist/steering.js +214 -0
  196. package/dist/steering.js.map +1 -0
  197. package/dist/subagents.d.ts +141 -0
  198. package/dist/subagents.d.ts.map +1 -0
  199. package/dist/subagents.js +746 -0
  200. package/dist/subagents.js.map +1 -0
  201. package/dist/tool-retry.d.ts +12 -0
  202. package/dist/tool-retry.d.ts.map +1 -0
  203. package/dist/tool-retry.js +53 -0
  204. package/dist/tool-retry.js.map +1 -0
  205. package/dist/tree.d.ts +98 -0
  206. package/dist/tree.d.ts.map +1 -0
  207. package/dist/tree.js +320 -0
  208. package/dist/tree.js.map +1 -0
  209. package/dist/types.d.ts +1007 -0
  210. package/dist/types.d.ts.map +1 -0
  211. package/dist/types.js +2 -0
  212. package/dist/types.js.map +1 -0
  213. package/dist/workflow-snapshot.d.ts +8 -0
  214. package/dist/workflow-snapshot.d.ts.map +1 -0
  215. package/dist/workflow-snapshot.js +276 -0
  216. package/dist/workflow-snapshot.js.map +1 -0
  217. package/dist/workflow-types.d.ts +171 -0
  218. package/dist/workflow-types.d.ts.map +1 -0
  219. package/dist/workflow-types.js +2 -0
  220. package/dist/workflow-types.js.map +1 -0
  221. package/dist/workflow.d.ts +19 -0
  222. package/dist/workflow.d.ts.map +1 -0
  223. package/dist/workflow.js +1053 -0
  224. package/dist/workflow.js.map +1 -0
  225. package/examples/a2a-remote.ts +85 -0
  226. package/examples/a2a-server.ts +100 -0
  227. package/examples/background.ts +59 -0
  228. package/examples/basic.ts +44 -0
  229. package/examples/code-mode.ts +76 -0
  230. package/examples/conversation.ts +57 -0
  231. package/examples/evals.ts +79 -0
  232. package/examples/guardrails.ts +56 -0
  233. package/examples/handoff.ts +79 -0
  234. package/examples/memory.ts +44 -0
  235. package/examples/otel.ts +99 -0
  236. package/examples/specialists.ts +99 -0
  237. package/examples/steering.ts +69 -0
  238. package/examples/structured-handoff.ts +92 -0
  239. package/examples/subagents.ts +127 -0
  240. package/examples/workflow.ts +74 -0
  241. package/package.json +114 -4
  242. package/src/a2a/auth.ts +62 -0
  243. package/src/a2a/client.ts +733 -0
  244. package/src/a2a/index.ts +74 -0
  245. package/src/a2a/memory-runs.ts +448 -0
  246. package/src/a2a/policy.ts +148 -0
  247. package/src/a2a/push.ts +251 -0
  248. package/src/a2a/remote.ts +1652 -0
  249. package/src/a2a/server.ts +1390 -0
  250. package/src/a2a/signing.ts +348 -0
  251. package/src/a2a/tasks.ts +260 -0
  252. package/src/a2a/wire.ts +1443 -0
  253. package/src/background-types.ts +86 -0
  254. package/src/child.ts +181 -0
  255. package/src/code-driver.ts +48 -0
  256. package/src/code-mode.ts +12 -0
  257. package/src/code-script.ts +149 -0
  258. package/src/code.ts +424 -0
  259. package/src/compaction.ts +212 -0
  260. package/src/delegation.ts +694 -0
  261. package/src/evals/driver.ts +222 -0
  262. package/src/evals/journal.ts +605 -0
  263. package/src/evals/judge.ts +188 -0
  264. package/src/evals/report.ts +295 -0
  265. package/src/evals/runner.ts +826 -0
  266. package/src/evals/scorers.ts +339 -0
  267. package/src/evals/simulation.ts +46 -0
  268. package/src/evals/testing.ts +126 -0
  269. package/src/evals/trajectory.ts +223 -0
  270. package/src/evals/types.ts +463 -0
  271. package/src/evals.ts +72 -0
  272. package/src/extensions.ts +247 -0
  273. package/src/handoff.ts +214 -0
  274. package/src/index.ts +62 -0
  275. package/src/input.ts +319 -0
  276. package/src/mcp.ts +690 -0
  277. package/src/memory-store.ts +366 -0
  278. package/src/memory.ts +893 -0
  279. package/src/otel.ts +568 -0
  280. package/src/progress.ts +214 -0
  281. package/src/quickjs.ts +524 -0
  282. package/src/recovery.ts +90 -0
  283. package/src/request.ts +513 -0
  284. package/src/run.ts +3199 -0
  285. package/src/runs.ts +696 -0
  286. package/src/schema-to-ts.ts +194 -0
  287. package/src/session.ts +178 -0
  288. package/src/snapshot.ts +2099 -0
  289. package/src/steering.ts +329 -0
  290. package/src/subagents.ts +1084 -0
  291. package/src/tool-retry.ts +86 -0
  292. package/src/tree.ts +366 -0
  293. package/src/types.ts +944 -0
  294. package/src/workflow-snapshot.ts +366 -0
  295. package/src/workflow-types.ts +213 -0
  296. 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 ADDED
@@ -0,0 +1,366 @@
1
+ import { EMPTY_USAGE, addUsage, createGate, messageOf, type TokenUsage } from "@providerkit/core";
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";
18
+
19
+ export type StopState = Exclude<RunState, { status: "running" | "completed" }>;
20
+
21
+ export class Halt extends Error {
22
+ constructor(readonly state: StopState) {
23
+ super(state.status);
24
+ }
25
+ }
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
+
55
+ export function fail(code: string, message: string, operationId?: string): never {
56
+ throw new Halt({ status: "failed", error: { code, message, operationId } });
57
+ }
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
+
71
+ /** Cancellation stops SDK work, not external effects which ignore their signal. */
72
+ export async function untilAbort<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
73
+ let onAbort = () => {};
74
+ try {
75
+ return await Promise.race([
76
+ work,
77
+ new Promise<never>((_resolve, reject) => {
78
+ onAbort = () => reject(signal.reason);
79
+ if (signal.aborted) onAbort();
80
+ else signal.addEventListener("abort", onAbort, { once: true });
81
+ }),
82
+ ]);
83
+ } finally {
84
+ signal.removeEventListener("abort", onAbort);
85
+ }
86
+ }
87
+
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> {
104
+ yield root;
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" };
189
+ }
190
+
191
+ /** Count local receipts once. Never add a child's already aggregated total. */
192
+ export function treeUsage(root: TreeNode): TokenUsage {
193
+ let usage = { ...EMPTY_USAGE };
194
+ const seen = new Set<string>();
195
+ for (const snapshot of snapshots(root)) {
196
+ if (snapshot.kind !== "agent") continue;
197
+ for (const model of allModels(snapshot)) {
198
+ if (seen.has(model.id)) continue;
199
+ seen.add(model.id);
200
+ usage = addUsage(usage, modelUsage(model));
201
+ }
202
+ }
203
+ return usage;
204
+ }
205
+
206
+ export async function authorizeTree(root: TreeNode, host: AgentHost): Promise<void> {
207
+ if (!host.authorizeResume)
208
+ throw new TypeError("Resume requires a trusted host.authorizeResume callback.");
209
+ // A parent's ownership is not authority over a descendant's tools or approvals.
210
+ for (const snapshot of snapshots(root)) await host.authorizeResume(immutableCopy(snapshot));
211
+ }
212
+
213
+ /** One root lease belongs to the host. This scope only coordinates its in-process tree. */
214
+ export class ExecutionTree {
215
+ readonly signal: AbortSignal;
216
+ readonly gate;
217
+ private readonly timeout = new AbortController();
218
+ private readonly broken = new AbortController();
219
+ private readonly timer;
220
+ private writes = Promise.resolve();
221
+ private toolBarrier = Promise.resolve();
222
+ private toolsSettled = Promise.resolve();
223
+ private checkpointFailure: Extract<RunState, { status: "failed" }> | undefined;
224
+
225
+ constructor(
226
+ readonly root: TreeNode,
227
+ private readonly options: RunOptions,
228
+ ) {
229
+ this.gate = createGate(root.tree.limits.maxParallel);
230
+ this.signal = AbortSignal.any([
231
+ this.timeout.signal,
232
+ this.broken.signal,
233
+ ...(options.signal ? [options.signal] : []),
234
+ ]);
235
+ this.timer = setTimeout(
236
+ () => this.timeout.abort(new Error("The agent tree reached its time limit.")),
237
+ Math.max(0, root.tree.startedAt + root.tree.limits.elapsedMs - Date.now()),
238
+ );
239
+ }
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
+
247
+ active(): void {
248
+ if (this.checkpointFailure) throw new Halt(this.checkpointFailure);
249
+ if (this.options.signal?.aborted || this.root.state.status === "cancelled")
250
+ throw new Halt({ status: "cancelled" });
251
+ if (
252
+ this.timeout.signal.aborted ||
253
+ Date.now() >= this.root.tree.startedAt + this.root.tree.limits.elapsedMs
254
+ )
255
+ throw new Halt({ status: "limited", limit: "treeElapsedMs" });
256
+ }
257
+
258
+ reserveModel(): void {
259
+ this.active();
260
+ // ponytail: a bounded tree is small. Deriving counters from the journal also
261
+ // preserves every reservation across resume without a second mutable ledger.
262
+ let models = 0;
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;
266
+ if (models >= this.root.tree.limits.modelCalls)
267
+ throw new Halt({ status: "limited", limit: "modelCalls" });
268
+ }
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
+
278
+ reserveChild(depth: number): void {
279
+ this.active();
280
+ if (depth > this.root.tree.limits.maxDepth)
281
+ throw new Halt({ status: "limited", limit: "maxDepth" });
282
+ if ([...snapshots(this.root)].length - 1 >= this.root.tree.limits.maxChildren)
283
+ throw new Halt({ status: "limited", limit: "maxChildren" });
284
+ }
285
+
286
+ async invokeTool<T>(
287
+ parallel: boolean,
288
+ signal: AbortSignal,
289
+ invoke: () => Promise<T>,
290
+ ): Promise<T> {
291
+ // Safe calls share a barrier. A serial call waits for all prior calls and
292
+ // becomes the barrier for later ones, across every specialist in this tree.
293
+ const previous = parallel ? this.toolBarrier : this.toolsSettled;
294
+ const work = previous.then(() => {
295
+ signal.throwIfAborted();
296
+ return untilAbort(invoke(), signal);
297
+ });
298
+ const settled = work.then(
299
+ () => {},
300
+ () => {},
301
+ );
302
+ this.toolsSettled = Promise.all([this.toolsSettled, settled]).then(() => {});
303
+ if (!parallel) this.toolBarrier = this.toolsSettled;
304
+ // Cancelling a queued call must return without waiting for another child.
305
+ // This cannot stop external effects that ignore their signal.
306
+ return untilAbort(work, signal);
307
+ }
308
+
309
+ async save(): Promise<void> {
310
+ const saved = immutableCopy(this.root);
311
+ // Every descendant writes the whole root through this one queue. Capturing at
312
+ // enqueue time keeps a slow earlier save from erasing a newer child's receipt.
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
+ }
340
+ });
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" }));
352
+ }
353
+
354
+ close(): void {
355
+ clearTimeout(this.timer);
356
+ }
357
+ }
358
+
359
+ export interface ExecutionScope {
360
+ tree: ExecutionTree;
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;
366
+ }