@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,1607 @@
1
+ import { isRemoteSnapshot, checkRemoteSnapshot, checkRemoteProgress } from "./a2a/remote.js";
2
+ import { isWorkflowSnapshot, checkWorkflowSnapshot, checkWorkflowProgress, } from "./workflow-snapshot.js";
3
+ import { CODE_LIMITS, programJson, textBytes } from "./code.js";
4
+ import { HOSTED_TOOL_TYPES, isEffort, parseToolArgs, } from "@providerkit/core";
5
+ import { checkMemorySnapshot, isMemoryPolicy, isMemoryRecall, isMemoryScopes, readMemoryBinding, } from "./memory.js";
6
+ import { allModels, checkCompactions, isCompactionDefinition } from "./compaction.js";
7
+ import { isSubagentRecord } from "./subagents.js";
8
+ import { isToolRetryDefinition, retryBudget, toolAttempts } from "./tool-retry.js";
9
+ import { GUARD_STAGES } from "./extensions.js";
10
+ import { INPUT_LIMITS, inputBytes, readQueuedInput } from "./steering.js";
11
+ import { isRecoveryDefinition } from "./recovery.js";
12
+ import { checkDecision, isAsk } from "./request.js";
13
+ export function isRecord(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ export function isId(value) {
17
+ return typeof value === "string" && value.trim().length > 0;
18
+ }
19
+ function finite(value) {
20
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
21
+ }
22
+ function positive(value) {
23
+ return finite(value) && Number.isSafeInteger(value) && value > 0;
24
+ }
25
+ function optional(value, guard) {
26
+ return value === undefined || guard(value);
27
+ }
28
+ /** JSON cannot preserve cycles, class instances, non-finite numbers or functions. */
29
+ function serializable(value, parents = new Set()) {
30
+ if (value === null || typeof value === "string" || typeof value === "boolean")
31
+ return true;
32
+ if (typeof value === "number")
33
+ return Number.isFinite(value);
34
+ if (typeof value !== "object" || parents.has(value))
35
+ return false;
36
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype)
37
+ return false;
38
+ parents.add(value);
39
+ const valid = Array.isArray(value)
40
+ ? value.every((item) => serializable(item, parents))
41
+ : Object.values(value).every((item) => item === undefined || serializable(item, parents));
42
+ parents.delete(value);
43
+ return valid;
44
+ }
45
+ export function copyData(value) {
46
+ if (value !== undefined && !serializable(value)) {
47
+ throw new TypeError("Run data must use plain JSON values so a checkpoint can save it.");
48
+ }
49
+ return structuredClone(value);
50
+ }
51
+ /** A callback cannot edit the live journal, even by retaining a nested reference. */
52
+ export function immutableCopy(value) {
53
+ const copy = copyData(value);
54
+ function freeze(item) {
55
+ if (typeof item !== "object" || item === null)
56
+ return;
57
+ for (const child of Object.values(item))
58
+ freeze(child);
59
+ Object.freeze(item);
60
+ }
61
+ freeze(copy);
62
+ return copy;
63
+ }
64
+ /** Object key order can change when a host stores JSON; array order cannot. */
65
+ export function equalData(left, right) {
66
+ if (left === right)
67
+ return true;
68
+ if (Array.isArray(left) && Array.isArray(right)) {
69
+ return (left.length === right.length && left.every((item, index) => equalData(item, right[index])));
70
+ }
71
+ if (!isRecord(left) || !isRecord(right))
72
+ return false;
73
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
74
+ return [...keys].every((key) => equalData(left[key], right[key]));
75
+ }
76
+ export function readLimits(value = {}) {
77
+ if (!isRecord(value))
78
+ throw new TypeError("Agent limits must be an object.");
79
+ const limits = {
80
+ turns: value.turns ?? 12,
81
+ toolCalls: value.toolCalls ?? 32,
82
+ elapsedMs: value.elapsedMs ?? 300_000,
83
+ parallelTools: value.parallelTools ?? 3,
84
+ inlineBytes: value.inlineBytes ?? 5_000_000,
85
+ };
86
+ if (!isLimits(limits)) {
87
+ throw new TypeError("Agent limits must be positive finite integers (inlineBytes may be 0); elapsedMs must fit a timer.");
88
+ }
89
+ return limits;
90
+ }
91
+ function isLimits(value) {
92
+ return (isRecord(value) &&
93
+ positive(value.turns) &&
94
+ positive(value.toolCalls) &&
95
+ positive(value.elapsedMs) &&
96
+ value.elapsedMs <= 2_147_483_647 &&
97
+ positive(value.parallelTools) &&
98
+ finite(value.inlineBytes) &&
99
+ Number.isSafeInteger(value.inlineBytes));
100
+ }
101
+ const IMAGE_TYPES = [
102
+ "image/jpeg",
103
+ "image/png",
104
+ "image/webp",
105
+ "image/gif",
106
+ ];
107
+ export function isImageMime(value) {
108
+ return IMAGE_TYPES.some((type) => type === value);
109
+ }
110
+ /** Core's file types, with an RFC 6838 subtype and no parameters, so the value a provider
111
+ * receives is the plain media type it documents. */
112
+ export function isFileMime(value) {
113
+ return (typeof value === "string" &&
114
+ /^(?:application|audio|video|text)\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}$/.test(value));
115
+ }
116
+ // Ported from TanStack AI (MIT), packages/ai-harness/src/inline-media.ts: check base64 and
117
+ // count its bytes from the length, without decoding. Stricter here: no whitespace and padded
118
+ // to a multiple of four, because the text goes to the provider exactly as given.
119
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
120
+ export function isBase64(value) {
121
+ return (typeof value === "string" && value.length > 0 && value.length % 4 === 0 && BASE64.test(value));
122
+ }
123
+ function decodedBytes(base64) {
124
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
125
+ return (base64.length / 4) * 3 - padding;
126
+ }
127
+ /** Decoded bytes of every inline image and file: user parts and tool images alike. */
128
+ export function inlineBytes(history, input) {
129
+ let total = 0;
130
+ const count = (parts) => {
131
+ for (const part of parts)
132
+ if (part.type === "image" || part.type === "file")
133
+ total += decodedBytes(part.data);
134
+ };
135
+ for (const message of history) {
136
+ if (message.role === "user" && typeof message.content !== "string")
137
+ count(message.content);
138
+ if (message.role === "tool" && message.images)
139
+ count(message.images);
140
+ }
141
+ if (typeof input !== "string")
142
+ count(input);
143
+ return total;
144
+ }
145
+ /** All retained inline media, including results of a partially settled tool batch. */
146
+ export function snapshotInlineBytes(snapshot) {
147
+ return inlineBytes([
148
+ ...snapshot.history,
149
+ ...snapshot.inputs.map((input) => ({ role: "user", content: input.content })),
150
+ ...snapshot.models.flatMap((model) => model.status === "completed"
151
+ ? model.tools.flatMap((tool) => tool.status === "completed" && tool.result.ok && tool.result.images
152
+ ? [
153
+ {
154
+ role: "tool",
155
+ name: "",
156
+ toolCallId: "",
157
+ content: "",
158
+ images: tool.result.images,
159
+ },
160
+ ]
161
+ : [])
162
+ : []),
163
+ ], snapshot.input);
164
+ }
165
+ function isImage(value) {
166
+ return (isRecord(value) && value.type === "image" && isImageMime(value.mimeType) && isBase64(value.data));
167
+ }
168
+ export function isPart(value) {
169
+ if (!isRecord(value))
170
+ return false;
171
+ switch (value.type) {
172
+ case "text":
173
+ return typeof value.text === "string";
174
+ case "image":
175
+ return isImage(value);
176
+ case "file":
177
+ return isFileMime(value.mimeType) && isBase64(value.data);
178
+ case "media":
179
+ return isId(value.id) && (isImageMime(value.mimeType) || isFileMime(value.mimeType));
180
+ default:
181
+ return false;
182
+ }
183
+ }
184
+ /** A frozen new turn: non-empty text, or at least one part. */
185
+ export function isTurnContent(value) {
186
+ return isId(value) || (Array.isArray(value) && value.length > 0 && value.every(isPart));
187
+ }
188
+ function isAssistant(value) {
189
+ return (isRecord(value) &&
190
+ value.role === "assistant" &&
191
+ typeof value.content === "string" &&
192
+ optional(value.reasoning, (v) => typeof v === "string") &&
193
+ optional(value.reasoningDetails, Array.isArray) &&
194
+ optional(value.reasoningItems, (v) => isRecord(v) && typeof v.provider === "string" && Array.isArray(v.items)) &&
195
+ optional(value.toolCalls, (v) => Array.isArray(v) && v.every(isCall)));
196
+ }
197
+ /** Shape only. Who may send which message is the input normalizer's rule, not this one. */
198
+ export function isAgentMessage(value) {
199
+ if (!isRecord(value))
200
+ return false;
201
+ switch (value.role) {
202
+ case "user":
203
+ return (typeof value.content === "string" ||
204
+ (Array.isArray(value.content) && value.content.every(isPart)));
205
+ case "assistant":
206
+ return isAssistant(value);
207
+ case "tool":
208
+ return (isId(value.toolCallId) &&
209
+ isId(value.name) &&
210
+ typeof value.content === "string" &&
211
+ optional(value.images, (v) => Array.isArray(v) && v.every(isImage)));
212
+ default:
213
+ return false;
214
+ }
215
+ }
216
+ function isFailure(value) {
217
+ return (isRecord(value) && isId(value.code) && isId(value.message) && optional(value.operationId, isId));
218
+ }
219
+ export function isRevision(value) {
220
+ return value === null || isId(value);
221
+ }
222
+ function isSessionRef(value) {
223
+ return isRecord(value) && isId(value.id) && isRevision(value.revision);
224
+ }
225
+ export function isSessionStatus(value) {
226
+ if (!isRecord(value) ||
227
+ !isId(value.id) ||
228
+ !optional(value.asks, (v) => Array.isArray(v) && v.every(isAskRecord)))
229
+ return false;
230
+ return (value.status === "pending" ||
231
+ (value.status === "saved" && isId(value.revision)) ||
232
+ (value.status === "unsaved" && isFailure(value.error)));
233
+ }
234
+ export function isSession(value) {
235
+ return (isRecord(value) &&
236
+ isId(value.id) &&
237
+ typeof value.load === "function" &&
238
+ typeof value.append === "function");
239
+ }
240
+ export function readTreeLimits(value = {}) {
241
+ if (!isRecord(value))
242
+ throw new TypeError("Tree limits must be an object.");
243
+ const limits = {
244
+ maxParallel: value.maxParallel ?? 4,
245
+ maxChildren: value.maxChildren ?? 32,
246
+ maxDepth: value.maxDepth ?? 4,
247
+ modelCalls: value.modelCalls ?? 128,
248
+ elapsedMs: value.elapsedMs ?? 300_000,
249
+ };
250
+ if (!isTreeLimits(limits))
251
+ throw new TypeError("Tree limits must be finite integers; elapsedMs must fit a timer.");
252
+ return limits;
253
+ }
254
+ function isTreeLimits(value) {
255
+ return (isRecord(value) &&
256
+ positive(value.maxParallel) &&
257
+ finite(value.maxChildren) &&
258
+ Number.isSafeInteger(value.maxChildren) &&
259
+ finite(value.maxDepth) &&
260
+ Number.isSafeInteger(value.maxDepth) &&
261
+ positive(value.modelCalls) &&
262
+ positive(value.elapsedMs) &&
263
+ value.elapsedMs <= 2_147_483_647);
264
+ }
265
+ function isPath(value) {
266
+ return (Array.isArray(value) &&
267
+ value.every((step) => isRecord(step) && [step.operationId, step.key, step.runId].every(isId)));
268
+ }
269
+ export function isNames(value) {
270
+ return Array.isArray(value) && value.every(isId) && new Set(value).size === value.length;
271
+ }
272
+ export function isEnabledTools(value) {
273
+ return typeof value === "function" || isNames(value);
274
+ }
275
+ function isStringList(value) {
276
+ // Iteration visits sparse entries too: JSON would turn those holes into null.
277
+ return Array.isArray(value) && [...value].every(isId);
278
+ }
279
+ // Snapshot shapes only. Core still decides which tools and fields a provider can send.
280
+ const HOSTED_SETTINGS = {
281
+ web_search: {
282
+ allowedDomains: (value) => optional(value, isStringList),
283
+ blockedDomains: (value) => optional(value, isStringList),
284
+ maxUses: (value) => value === 0 || optional(value, positive),
285
+ userLocation: (value) => optional(value, (location) => isRecord(location) &&
286
+ Object.keys(location).every((key) => ["city", "region", "country", "timezone"].includes(key)) &&
287
+ Object.values(location).every((item) => optional(item, isId))),
288
+ },
289
+ web_fetch: {
290
+ allowedDomains: (value) => optional(value, isStringList),
291
+ blockedDomains: (value) => optional(value, isStringList),
292
+ maxUses: (value) => value === 0 || optional(value, positive),
293
+ maxContentTokens: (value) => optional(value, positive),
294
+ },
295
+ code_execution: {
296
+ fileIds: (value) => optional(value, isStringList),
297
+ },
298
+ file_search: {
299
+ storeIds: isStringList,
300
+ maxResults: (value) => optional(value, positive),
301
+ },
302
+ image_generation: {
303
+ size: (value) => optional(value, (item) => ["auto", "1024x1024", "1024x1536", "1536x1024"].some((size) => size === item)),
304
+ quality: (value) => optional(value, (item) => ["auto", "low", "medium", "high"].some((quality) => quality === item)),
305
+ format: (value) => optional(value, (item) => ["png", "jpeg", "webp"].some((format) => format === item)),
306
+ background: (value) => optional(value, (item) => ["auto", "opaque", "transparent"].some((background) => background === item)),
307
+ },
308
+ };
309
+ function isHostedTools(value) {
310
+ if (!Array.isArray(value) || !serializable(value))
311
+ return false;
312
+ const seen = new Set();
313
+ for (const tool of value) {
314
+ if (!isRecord(tool) || !optional(tool.optional, (item) => typeof item === "boolean"))
315
+ return false;
316
+ const type = HOSTED_TOOL_TYPES.find((type) => type === tool.type);
317
+ if (!type || seen.has(type))
318
+ return false;
319
+ seen.add(type);
320
+ const guards = HOSTED_SETTINGS[type];
321
+ if (!Object.keys(tool).every((key) => key === "type" || key === "optional" || Object.hasOwn(guards, key)) ||
322
+ !Object.entries(guards).every(([key, guard]) => guard(tool[key])))
323
+ return false;
324
+ }
325
+ return true;
326
+ }
327
+ const MODEL_SETTINGS = {
328
+ model: isId,
329
+ maxAttempts: positive,
330
+ effort: (value) => typeof value === "string" && isEffort(value),
331
+ maxTokens: positive,
332
+ temperature: finite,
333
+ topP: (value) => finite(value) && value <= 1,
334
+ stopSequences: (value) => Array.isArray(value) && value.every(isId),
335
+ toolChoice: (value) => ["auto", "none", "required"].some((choice) => choice === value) ||
336
+ (isRecord(value) && isId(value.name) && Object.keys(value).length === 1),
337
+ jsonWithTools: (value) => value === "prompt" || value === "response_format",
338
+ hostedTools: isHostedTools,
339
+ parallelToolCalls: (value) => typeof value === "boolean",
340
+ serviceTier: (value) => value === "priority" || value === "flex",
341
+ onActivity: (value) => typeof value === "function",
342
+ onRateLimit: (value) => typeof value === "function",
343
+ };
344
+ function isModelSettings(value) {
345
+ return (isRecord(value) &&
346
+ Object.keys(value).every((key) => Object.hasOwn(MODEL_SETTINGS, key)) &&
347
+ Object.entries(MODEL_SETTINGS).every(([key, guard]) => optional(value[key], guard)));
348
+ }
349
+ export function isRecordedModelSettings(value) {
350
+ return (isModelSettings(value) && value.onActivity === undefined && value.onRateLimit === undefined);
351
+ }
352
+ export function readModelSettings(value = {}) {
353
+ if (!isModelSettings(value))
354
+ throw new TypeError("Invalid modelSettings. Use core StreamOptions without signal, sessionId or json; the agent owns those fields.");
355
+ // Undefined means inherit, not erase a lower-precedence value. Keep observers outside the
356
+ // JSON copy: they do not change the request and may close over process-local services.
357
+ const defined = Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
358
+ if (!isModelSettings(defined))
359
+ throw new TypeError("Invalid modelSettings.");
360
+ const { onActivity, onRateLimit, ...data } = defined;
361
+ return {
362
+ ...copyData(data),
363
+ ...(onActivity ? { onActivity } : {}),
364
+ ...(onRateLimit ? { onRateLimit } : {}),
365
+ };
366
+ }
367
+ function isGuardDefinition(value) {
368
+ return (value === null ||
369
+ (isRecord(value) &&
370
+ isId(value.identity) &&
371
+ positive(value.maxOutputBytes) &&
372
+ isNames(value.stages) &&
373
+ value.stages.length > 0 &&
374
+ value.stages.every((stage) => GUARD_STAGES.some((name) => name === stage))));
375
+ }
376
+ function isGuardRecord(value) {
377
+ return (isRecord(value) &&
378
+ GUARD_STAGES.some((stage) => stage === value.stage) &&
379
+ isId(value.operationId) &&
380
+ isId(value.attemptId) &&
381
+ typeof value.inputHash === "string" &&
382
+ /^sha256:[a-f0-9]{64}$/.test(value.inputHash) &&
383
+ ["running", "allowed", "rejected", "failed"].some((status) => status === value.status));
384
+ }
385
+ /** Record only validation data. Reading an archive must not construct executable tools. */
386
+ export function recordCodeTools(tools) {
387
+ return Object.fromEntries([...tools].map(([name, code]) => [
388
+ name,
389
+ {
390
+ name,
391
+ limits: { ...code.limits },
392
+ tools: code.tools.map((tool) => ({ name: tool.name, isReadOnly: tool.isReadOnly })),
393
+ },
394
+ ]));
395
+ }
396
+ function isRecordedCodeTools(value) {
397
+ if (!isRecord(value))
398
+ return false;
399
+ for (const [name, code] of Object.entries(value)) {
400
+ if (!isId(name) ||
401
+ !isRecord(code) ||
402
+ code.name !== name ||
403
+ Object.keys(code).some((key) => !["name", "limits", "tools"].includes(key)) ||
404
+ !isRecord(code.limits) ||
405
+ !Array.isArray(code.tools) ||
406
+ !code.tools.length)
407
+ return false;
408
+ const limits = code.limits;
409
+ if (Object.keys(limits).length !== Object.keys(CODE_LIMITS).length ||
410
+ !Object.keys(CODE_LIMITS).every((key) => positive(limits[key])) ||
411
+ typeof limits.timeoutMs !== "number" ||
412
+ limits.timeoutMs > 2_147_483_647)
413
+ return false;
414
+ const names = new Set();
415
+ for (const tool of code.tools) {
416
+ if (!isRecord(tool) ||
417
+ !isId(tool.name) ||
418
+ typeof tool.isReadOnly !== "boolean" ||
419
+ Object.keys(tool).some((key) => key !== "name" && key !== "isReadOnly") ||
420
+ names.has(tool.name))
421
+ return false;
422
+ names.add(tool.name);
423
+ }
424
+ }
425
+ return true;
426
+ }
427
+ function isRunDefinition(value) {
428
+ return (isRecord(value) &&
429
+ typeof value.instructions === "string" &&
430
+ isRecordedModelSettings(value.modelSettings) &&
431
+ isNames(value.enabledTools) &&
432
+ isNames(value.stopAtTools) &&
433
+ optional(value.codeTools, isRecordedCodeTools) &&
434
+ isGuardDefinition(value.guardrails) &&
435
+ isCompactionDefinition(value.compaction) &&
436
+ isToolRetryDefinition(value.toolRetries) &&
437
+ optional(value.memory, isMemoryPolicy) &&
438
+ isRecoveryDefinition(value.recovery));
439
+ }
440
+ export function checkOptions(value, use = "run") {
441
+ if (!isRecord(value) ||
442
+ !optional(value.runId, isId) ||
443
+ !optional(value.signal, (signal) => signal instanceof AbortSignal) ||
444
+ !optional(value.context, isRecord) ||
445
+ !optional(value.onEvent, (fn) => typeof fn === "function") ||
446
+ !optional(value.onLifecycle, (fn) => typeof fn === "function") ||
447
+ !optional(value.answers, isRecord)) {
448
+ throw new TypeError("Invalid run options.");
449
+ }
450
+ readMemoryBinding(value.memory);
451
+ if (!optional(value.session, isSession))
452
+ throw new TypeError("A session needs an id and load and append functions.");
453
+ if (!optional(value.historyLimit, positive))
454
+ throw new TypeError("historyLimit must be a positive whole number.");
455
+ if (!optional(value.prepareHistory, (fn) => typeof fn === "function"))
456
+ throw new TypeError("prepareHistory must be a function.");
457
+ if (!optional(value.enabledTools, isEnabledTools))
458
+ throw new TypeError("enabledTools must be an allow-list of unique tool names, or a function returning one.");
459
+ if (value.modelSettings !== undefined)
460
+ readModelSettings(value.modelSettings);
461
+ // ResumeOptions leaves these out, but a JavaScript caller can still pass them. Say so,
462
+ // rather than ignore a value someone set.
463
+ if (use === "resume" &&
464
+ [value.historyLimit, value.prepareHistory, value.modelSettings, value.enabledTools].some((item) => item !== undefined))
465
+ throw new TypeError("historyLimit, prepareHistory, modelSettings and enabledTools apply when a run starts. A resumed run keeps its recorded history and definition.");
466
+ if (value.host !== undefined) {
467
+ if (!isRecord(value.host))
468
+ throw new TypeError("The run host must be an object.");
469
+ if (value.host.inbox !== undefined &&
470
+ (!isRecord(value.host.inbox) ||
471
+ typeof value.host.inbox.poll !== "function" ||
472
+ typeof value.host.inbox.acknowledge !== "function"))
473
+ throw new TypeError("host.inbox needs poll and acknowledge functions.");
474
+ for (const key of [
475
+ "checkpoint",
476
+ "authorizeResume",
477
+ "prepareRequest",
478
+ "resolveRequest",
479
+ "needsApproval",
480
+ "answerNow",
481
+ "beforeStep",
482
+ "reconcileStep",
483
+ "beforeTool",
484
+ "reconcileToolRetry",
485
+ "canRunConcurrently",
486
+ "child",
487
+ "loadMedia",
488
+ ]) {
489
+ if (!optional(value.host[key], (fn) => typeof fn === "function")) {
490
+ throw new TypeError(`host.${key} must be a function.`);
491
+ }
492
+ }
493
+ }
494
+ }
495
+ export function isScope(value) {
496
+ return (isRecord(value) &&
497
+ isId(value.actorId) &&
498
+ isRecord(value.resource) &&
499
+ isId(value.resource.id) &&
500
+ isId(value.resource.version) &&
501
+ positive(value.expiresAt));
502
+ }
503
+ /** Code and guest inputs are exact JSON, not prose whose escapes may be repaired. */
504
+ export function jsonArguments(raw) {
505
+ try {
506
+ const value = JSON.parse(raw);
507
+ return isRecord(value) ? value : undefined;
508
+ }
509
+ catch {
510
+ return undefined;
511
+ }
512
+ }
513
+ export function completeArguments(raw) {
514
+ return jsonArguments(raw) !== undefined;
515
+ }
516
+ function isCall(value) {
517
+ return (isRecord(value) &&
518
+ isId(value.id) &&
519
+ isId(value.name) &&
520
+ typeof value.arguments === "string" &&
521
+ optional(value.thoughtSignature, (v) => typeof v === "string"));
522
+ }
523
+ function isRequest(value) {
524
+ return (isRecord(value) &&
525
+ [value.agentId, value.version, value.runId, value.attemptId, value.operationId].every(isId) &&
526
+ isCall(value.call) &&
527
+ optional(value.subagent, isId) &&
528
+ optional(value.parentOperationId, isId) &&
529
+ isRecord(value.arguments));
530
+ }
531
+ function isStepRequest(value) {
532
+ return (isRecord(value) &&
533
+ [
534
+ value.workflowId,
535
+ value.version,
536
+ value.runId,
537
+ value.attemptId,
538
+ value.operationId,
539
+ value.key,
540
+ ].every(isId) &&
541
+ ["step", "ask", "agent", "remote", "workflow", "sleep"].includes(String(value.kind)));
542
+ }
543
+ function isPendingRequest(value) {
544
+ return (isRecord(value) &&
545
+ isId(value.id) &&
546
+ isPath(value.path) &&
547
+ ((value.step === undefined && isRequest(value.call)) ||
548
+ (value.call === undefined && isStepRequest(value.step))) &&
549
+ isScope(value.scope) &&
550
+ isAsk(value.ask) &&
551
+ positive(value.createdAt) &&
552
+ typeof value.definitionHash === "string" &&
553
+ /^sha256:[a-f0-9]{64}$/.test(value.definitionHash));
554
+ }
555
+ export function isAskRecord(value) {
556
+ if (!isRecord(value) ||
557
+ !isPendingRequest(value.request) ||
558
+ !optional(value.closed, (v) => ["expired", "stale", "invalid", "stopped"].includes(String(v))) ||
559
+ !optional(value.problem, (v) => isRecord(v) &&
560
+ ["expired", "stale", "invalid_answer", "refused"].includes(String(v.code)) &&
561
+ isId(v.message)))
562
+ return false;
563
+ if (value.decision !== undefined) {
564
+ try {
565
+ checkDecision(value.request.ask, value.decision);
566
+ }
567
+ catch {
568
+ return false;
569
+ }
570
+ }
571
+ return true;
572
+ }
573
+ export function isUsage(value) {
574
+ return (isRecord(value) &&
575
+ finite(value.inputTokens) &&
576
+ finite(value.outputTokens) &&
577
+ finite(value.cachedInputTokens) &&
578
+ [value.cacheWriteTokens, value.reasoningTokens, value.reportedCostUsd].every((v) => optional(v, finite)));
579
+ }
580
+ function isTurn(value) {
581
+ if (!isRecord(value) || !isUsage(value.usage))
582
+ return false;
583
+ return (isAssistant(value.message) &&
584
+ [null, "stop", "length", "tool_calls", "content_filter"].some((v) => v === value.finishReason) &&
585
+ optional(value.source, (v) => isRecord(v) && typeof v.provider === "string" && typeof v.model === "string"));
586
+ }
587
+ export function readTurn(value) {
588
+ if (!serializable(value) || !isTurn(value))
589
+ throw new TypeError("The provider returned an invalid or unsavable turn.");
590
+ const ids = value.message.toolCalls?.map((call) => call.id) ?? [];
591
+ if (new Set(ids).size !== ids.length)
592
+ throw new TypeError("The provider reused a tool-call ID within one turn.");
593
+ return copyData(value);
594
+ }
595
+ function isToolResult(value) {
596
+ return (isRecord(value) &&
597
+ typeof value.content === "string" &&
598
+ (value.ok === true
599
+ ? value.kind === undefined &&
600
+ optional(value.images, (images) => Array.isArray(images) && images.every(isImage)) &&
601
+ optional(value.output, serializable) &&
602
+ optional(value.final, (final) => isRecord(final) && serializable(final.candidate))
603
+ : value.ok === false &&
604
+ value.images === undefined &&
605
+ value.output === undefined &&
606
+ value.final === undefined &&
607
+ [
608
+ "invalid_input",
609
+ "timeout",
610
+ "aborted",
611
+ "failed",
612
+ "denied",
613
+ "cancelled",
614
+ "unknown_tool",
615
+ "disabled_tool",
616
+ "invalid_output",
617
+ "interrupted",
618
+ ].some((kind) => kind === value.kind)));
619
+ }
620
+ function isInterrupted(value) {
621
+ return (Array.isArray(value) &&
622
+ value.every((attempt) => isRecord(attempt) && isId(attempt.attemptId)) &&
623
+ new Set(value.map((attempt) => attempt.attemptId)).size === value.length);
624
+ }
625
+ function isRetriedAttempt(value) {
626
+ return (isRecord(value) &&
627
+ isId(value.attemptId) &&
628
+ isRecord(value.arguments) &&
629
+ isToolResult(value.result) &&
630
+ !value.result.ok &&
631
+ ["failed", "timeout"].includes(value.result.kind) &&
632
+ optional(value.reconciliation, isId));
633
+ }
634
+ function isProgramCall(value) {
635
+ return (isRecord(value) &&
636
+ value.calls === undefined &&
637
+ isToolExecution(value) &&
638
+ value.status !== "delegating" &&
639
+ (value.status === "completed" || !("result" in value)) &&
640
+ "attemptId" in value &&
641
+ isId(value.attemptId) &&
642
+ "programAttemptId" in value &&
643
+ isId(value.programAttemptId) &&
644
+ "name" in value &&
645
+ isId(value.name) &&
646
+ "arguments" in value &&
647
+ isRecord(value.arguments) &&
648
+ "started" in value &&
649
+ typeof value.started === "boolean" &&
650
+ (!("bytes" in value) ||
651
+ optional(value.bytes, (bytes) => finite(bytes) && Number.isSafeInteger(bytes))));
652
+ }
653
+ function isToolExecution(value) {
654
+ if (!isRecord(value) ||
655
+ !isId(value.id) ||
656
+ !isInterrupted(value.interrupted) ||
657
+ !Array.isArray(value.retries) ||
658
+ !value.retries.every(isRetriedAttempt) ||
659
+ !isInterrupted([...value.interrupted, ...value.retries]) ||
660
+ [...value.interrupted, ...value.retries].some((attempt) => attempt.attemptId === value.attemptId) ||
661
+ !optional(value.calls, (calls) => Array.isArray(calls) && calls.every(isProgramCall)) ||
662
+ !optional(value.asks, (v) => Array.isArray(v) && v.every(isAskRecord)))
663
+ return false;
664
+ if (value.status === "pending")
665
+ return value.previousAttemptId === undefined
666
+ ? (value.interrupted.length === 0 && value.retries.length === 0) ||
667
+ (Array.isArray(value.asks) && value.asks.length > 0)
668
+ : isId(value.previousAttemptId) &&
669
+ [value.interrupted.at(-1), value.retries.at(-1)].some((attempt) => attempt?.attemptId === value.previousAttemptId);
670
+ return (value.previousAttemptId === undefined &&
671
+ isId(value.attemptId) &&
672
+ (value.status === "running" ||
673
+ value.status === "delegating" ||
674
+ (value.status === "completed" && isToolResult(value.result))));
675
+ }
676
+ function isModel(value) {
677
+ if (!isRecord(value) ||
678
+ !isId(value.id) ||
679
+ !isId(value.attemptId) ||
680
+ !isUsage(value.usage) ||
681
+ (value.billing !== "unknown" && value.billing !== "reported") ||
682
+ (value.status === "running" && value.billing !== "unknown") ||
683
+ !isInterrupted(value.interrupted) ||
684
+ value.interrupted.some((attempt) => attempt.attemptId === value.attemptId || !("usage" in attempt) || !isUsage(attempt.usage)))
685
+ return false;
686
+ return (value.status === "running" ||
687
+ (value.status === "completed" &&
688
+ isTurn(value.turn) &&
689
+ Array.isArray(value.tools) &&
690
+ value.tools.every(isToolExecution)));
691
+ }
692
+ function isCompaction(value) {
693
+ return (isRecord(value) &&
694
+ isId(value.id) &&
695
+ finite(value.beforeModel) &&
696
+ Number.isSafeInteger(value.beforeModel) &&
697
+ positive(value.sourceCount) &&
698
+ positive(value.cut) &&
699
+ optional(value.model, isModel) &&
700
+ (value.status === "running" || (value.status === "completed" && isId(value.summary))));
701
+ }
702
+ export function isState(value) {
703
+ if (!isRecord(value))
704
+ return false;
705
+ switch (value.status) {
706
+ case "running":
707
+ case "cancelled":
708
+ return true;
709
+ case "completed":
710
+ return serializable(value.candidate);
711
+ case "suspended":
712
+ return Object.keys(value).length === 1;
713
+ case "limited":
714
+ return [
715
+ "turns",
716
+ "toolCalls",
717
+ "elapsedMs",
718
+ "outputTokens",
719
+ "maxChildren",
720
+ "maxDepth",
721
+ "modelCalls",
722
+ "steps",
723
+ "treeElapsedMs",
724
+ ].some((v) => v === value.limit);
725
+ case "failed":
726
+ return isFailure(value.error);
727
+ default:
728
+ return false;
729
+ }
730
+ }
731
+ function isDelegationJournal(value) {
732
+ return (isRecord(value) &&
733
+ isId(value.operationId) &&
734
+ (value.kind === "delegation"
735
+ ? value.target === undefined && value.note === undefined
736
+ : value.kind === "handoff" &&
737
+ isRecord(value.target) &&
738
+ isId(value.target.id) &&
739
+ isId(value.target.version) &&
740
+ optional(value.note, (note) => typeof note === "string")) &&
741
+ Array.isArray(value.children) &&
742
+ value.children.every((child) => isRecord(child) &&
743
+ isId(child.key) &&
744
+ optional(child.reference, isId) &&
745
+ isTreeNode(child.snapshot)));
746
+ }
747
+ function isRunInput(value) {
748
+ if (!isRecord(value) || !finite(value.beforeModel) || !Number.isSafeInteger(value.beforeModel))
749
+ return false;
750
+ try {
751
+ return equalData(value.content, readQueuedInput({ id: value.id, content: value.content }).content);
752
+ }
753
+ catch {
754
+ return false;
755
+ }
756
+ }
757
+ /** Format 3 only. A format 2 snapshot from 0.1.0 has no reader: it is refused, not migrated. */
758
+ function isSnapshot(value) {
759
+ return (isRecord(value) &&
760
+ value.format === 3 &&
761
+ value.kind === "agent" &&
762
+ [value.agentId, value.version, value.runId, value.attemptId].every(isId) &&
763
+ positive(value.startedAt) &&
764
+ isRunDefinition(value.definition) &&
765
+ optional(value.recall, isMemoryRecall) &&
766
+ optional(value.subagent, (record) => isSubagentRecord(record) && isRunDefinition(record.base)) &&
767
+ Array.isArray(value.history) &&
768
+ value.history.every(isAgentMessage) &&
769
+ isTurnContent(value.input) &&
770
+ Array.isArray(value.inputs) &&
771
+ value.inputs.every(isRunInput) &&
772
+ Array.isArray(value.guards) &&
773
+ value.guards.every(isGuardRecord) &&
774
+ Array.isArray(value.compactions) &&
775
+ value.compactions.every(isCompaction) &&
776
+ optional(value.session, isSessionRef) &&
777
+ isLimits(value.limits) &&
778
+ Array.isArray(value.models) &&
779
+ value.models.every(isModel) &&
780
+ Array.isArray(value.delegations) &&
781
+ value.delegations.every(isDelegationJournal) &&
782
+ isRecord(value.tree) &&
783
+ isId(value.tree.runId) &&
784
+ positive(value.tree.startedAt) &&
785
+ isTreeLimits(value.tree.limits) &&
786
+ optional(value.tree.memory, isMemoryScopes) &&
787
+ isState(value.state));
788
+ }
789
+ export function isTreeInfo(value) {
790
+ return (isRecord(value) &&
791
+ isId(value.runId) &&
792
+ positive(value.startedAt) &&
793
+ isTreeLimits(value.limits) &&
794
+ optional(value.memory, isMemoryScopes));
795
+ }
796
+ export function isTreeNode(value) {
797
+ return isSnapshot(value) || isWorkflowSnapshot(value) || isRemoteSnapshot(value);
798
+ }
799
+ export function agentSnapshot(node) {
800
+ if (node.kind !== "agent")
801
+ throw new TypeError("Expected an agent node, not a workflow.");
802
+ return node;
803
+ }
804
+ export function readWorkflowSnapshot(raw) {
805
+ if (!serializable(raw) || !isWorkflowSnapshot(raw))
806
+ throw new TypeError("Invalid workflow snapshot.");
807
+ checkWorkflowSnapshot(raw);
808
+ checkTree(raw);
809
+ return copyData(raw);
810
+ }
811
+ export function modelId(runId, index) {
812
+ return `${runId}/model/${index + 1}`;
813
+ }
814
+ export function toolId(model, index) {
815
+ return `${model}/tool/${index + 1}`;
816
+ }
817
+ export function childRunId(operationId, key) {
818
+ return `${operationId}/child/${encodeURIComponent(key)}`;
819
+ }
820
+ /** Check global reservations from saved local journals, including work not yet sent. */
821
+ export function checkTree(root) {
822
+ let children = 0;
823
+ let models = 0;
824
+ const inputIds = new Set();
825
+ const remoteNodes = new Map();
826
+ const continued = new Set();
827
+ let inputSize = 0;
828
+ function visit(node, depth, path, conversation, createdLevel, createdCeiling) {
829
+ if (!equalData(node.tree, root.tree) || node.startedAt < root.tree.startedAt)
830
+ throw new TypeError("The child belongs to a different tree or deadline.");
831
+ if (depth > root.tree.limits.maxDepth)
832
+ throw new TypeError("The tree exceeds its depth limit.");
833
+ if (node.kind === "remote") {
834
+ checkRemoteSnapshot(node);
835
+ if (root.runId === root.tree.runId &&
836
+ node.remote.sends.some((send) => send.asks?.some((record) => !equalData(record.request.path, path))))
837
+ throw new TypeError("The remote request path is invalid.");
838
+ if (node.input.continue && root.runId === root.tree.runId) {
839
+ const source = remoteNodes.get(node.input.continue);
840
+ if (!source ||
841
+ source.agentId !== node.agentId ||
842
+ source.version !== node.version ||
843
+ !equalData(source.definition, node.definition) ||
844
+ source.state.status !== "completed" ||
845
+ source.remote.state !== "input_required" ||
846
+ source.remote.cancel ||
847
+ !equalData(source.remote.endpoint, node.remote.endpoint) ||
848
+ source.remote.taskId !== node.remote.taskId ||
849
+ source.remote.contextId !== node.remote.contextId ||
850
+ node.remote.priorTurns !== source.remote.priorTurns + source.remote.sends.length ||
851
+ continued.has(source.runId))
852
+ throw new TypeError("The remote continuation does not match an open task in this tree.");
853
+ continued.add(source.runId);
854
+ }
855
+ remoteNodes.set(node.runId, node);
856
+ return;
857
+ }
858
+ if (node.kind === "workflow") {
859
+ checkWorkflowSnapshot(node);
860
+ for (const step of node.steps) {
861
+ if (root.runId === root.tree.runId &&
862
+ step.asks?.some((record) => !equalData(record.request.path, path)))
863
+ throw new TypeError("The workflow request path is invalid.");
864
+ for (const child of step.children) {
865
+ children++;
866
+ visit(child.snapshot, depth + 1, [...path, { operationId: step.id, key: child.key, runId: child.snapshot.runId }], false, createdLevel, createdCeiling);
867
+ }
868
+ }
869
+ return;
870
+ }
871
+ if (node.subagent) {
872
+ createdLevel++;
873
+ createdCeiling = Math.min(createdCeiling, node.subagent.policy.maxLevels);
874
+ if (createdLevel > createdCeiling || node.session)
875
+ throw new TypeError("A helper exceeds its recursive creation permission or carries a session.");
876
+ }
877
+ if (!conversation && node.inputs.length)
878
+ throw new TypeError("A delegated specialist cannot receive the root conversation's inbox.");
879
+ for (const input of node.inputs) {
880
+ if (inputIds.has(input.id))
881
+ throw new TypeError("Duplicate input id in the run tree.");
882
+ inputIds.add(input.id);
883
+ inputSize += inputBytes(input);
884
+ }
885
+ if (!equalData(node.tree, root.tree) || node.startedAt < root.tree.startedAt)
886
+ throw new TypeError("The child belongs to a different tree or deadline.");
887
+ if (depth > root.tree.limits.maxDepth)
888
+ throw new TypeError("The tree exceeds its depth limit.");
889
+ models += allModels(node).reduce((total, model) => total + 1 + model.interrupted.length, 0);
890
+ if (new Set(node.delegations.map((journal) => journal.operationId)).size !==
891
+ node.delegations.length)
892
+ throw new TypeError("Duplicate delegation journal.");
893
+ for (const journal of node.delegations) {
894
+ const tool = node.models
895
+ .flatMap((model) => (model.status === "completed" ? model.tools : []))
896
+ .find((tool) => tool.id === journal.operationId);
897
+ if (!tool || (tool.status !== "delegating" && tool.status !== "completed"))
898
+ throw new TypeError("The delegation journal does not match its tool call.");
899
+ if (journal.kind === "handoff") {
900
+ const child = journal.children[0];
901
+ const model = node.models.find((entry) => entry.status === "completed" && entry.tools.some((entry) => entry.id === tool.id));
902
+ if (journal.target.id === node.agentId ||
903
+ journal.children.length > 1 ||
904
+ model?.status !== "completed" ||
905
+ model.tools.length !== 1 ||
906
+ (child &&
907
+ (child.key !== "handoff" ||
908
+ child.snapshot.kind !== "agent" ||
909
+ child.snapshot.session !== undefined ||
910
+ child.snapshot.agentId !== journal.target.id ||
911
+ child.snapshot.version !== journal.target.version)) ||
912
+ (child && model !== node.models.at(-1)) ||
913
+ (tool.status === "completed" &&
914
+ tool.result.ok &&
915
+ child?.snapshot.state.status !== "completed"))
916
+ throw new TypeError("The handoff must have one fixed target, one call and no later source turn.");
917
+ }
918
+ if (new Set(journal.children.map((child) => child.key)).size !== journal.children.length)
919
+ throw new TypeError("Duplicate child key.");
920
+ for (const child of journal.children) {
921
+ if (child.snapshot.runId !== childRunId(journal.operationId, child.key) ||
922
+ child.snapshot.startedAt < node.startedAt)
923
+ throw new TypeError("Invalid child identity or start time.");
924
+ if ((tool.status === "completed" || node.state.status === "completed") &&
925
+ (child.snapshot.state.status === "running" || child.snapshot.state.status === "suspended"))
926
+ throw new TypeError("A completed delegation cannot contain unfinished children.");
927
+ children++;
928
+ visit(child.snapshot, depth + 1, [
929
+ ...path,
930
+ { operationId: journal.operationId, key: child.key, runId: child.snapshot.runId },
931
+ ], conversation && journal.kind === "handoff", createdLevel, createdCeiling);
932
+ }
933
+ }
934
+ for (const model of node.models) {
935
+ if (model.status === "completed" && root.runId === root.tree.runId)
936
+ for (const tool of model.tools)
937
+ for (const record of [
938
+ ...(tool.asks ?? []),
939
+ ...(tool.calls ?? []).flatMap((call) => call.asks ?? []),
940
+ ])
941
+ if (!equalData(record.request.path, path))
942
+ throw new TypeError("The request path does not match its owning call.");
943
+ if (model.status === "completed" &&
944
+ model.tools.some((tool) => tool.status === "delegating" &&
945
+ !node.delegations.some((journal) => journal.operationId === tool.id)))
946
+ throw new TypeError("A delegation is missing its child journal.");
947
+ }
948
+ }
949
+ if (root.runId === root.tree.runId && root.startedAt !== root.tree.startedAt)
950
+ throw new TypeError("The root start time does not match its tree.");
951
+ visit(root, 0, [], true, 0, Infinity);
952
+ if (inputIds.size > INPUT_LIMITS.count || inputSize > INPUT_LIMITS.bytes)
953
+ throw new TypeError("The snapshot exceeds its input count or byte limit.");
954
+ if (children > root.tree.limits.maxChildren || models > root.tree.limits.modelCalls)
955
+ throw new TypeError("The snapshot exceeds its tree limits.");
956
+ }
957
+ /** A later attempt must retain the exact measurements and identity of every lost attempt. */
958
+ function checkAttemptProgress(previous, next) {
959
+ if (previous.interrupted.some((attempt, index) => !equalData(attempt, next.interrupted[index])))
960
+ throw new TypeError("The host erased or replaced interrupted attempts.");
961
+ if (!previous.attemptId)
962
+ return;
963
+ if (previous.attemptId === next.attemptId) {
964
+ if (previous.interrupted.length !== next.interrupted.length)
965
+ throw new TypeError("The host changed a current attempt's history.");
966
+ }
967
+ else if (!equalData(next.interrupted[previous.interrupted.length], {
968
+ attemptId: previous.attemptId,
969
+ ...(previous.usage ? { usage: previous.usage } : {}),
970
+ }))
971
+ throw new TypeError("The host changed an attempt without retaining its receipt.");
972
+ }
973
+ /** A host cache may fill a missing receipt, never erase or replace a known effect. */
974
+ export function checkChildProgress(previous, next) {
975
+ if (previous.kind !== next.kind ||
976
+ previous.runId !== next.runId ||
977
+ previous.version !== next.version ||
978
+ previous.startedAt !== next.startedAt ||
979
+ !equalData(previous.definition, next.definition) ||
980
+ !equalData(previous.input, next.input) ||
981
+ !equalData(previous.limits, next.limits) ||
982
+ !equalData(previous.tree, next.tree) ||
983
+ (previous.state.status !== "running" &&
984
+ previous.state.status !== "suspended" &&
985
+ !equalData(previous.state, next.state)))
986
+ throw new TypeError("The child host returned a different or regressed node.");
987
+ if (previous.kind === "remote" && next.kind === "remote") {
988
+ checkRemoteProgress(previous, next);
989
+ return;
990
+ }
991
+ if (previous.kind === "workflow" && next.kind === "workflow") {
992
+ if (previous.workflowId !== next.workflowId)
993
+ throw new TypeError("The child host changed the workflow.");
994
+ checkWorkflowProgress(previous, next);
995
+ return;
996
+ }
997
+ if (previous.kind !== "agent" || next.kind !== "agent")
998
+ throw new TypeError("The child kind changed.");
999
+ if (previous.runId !== next.runId ||
1000
+ !equalData(previous.definition, next.definition) ||
1001
+ !equalData(previous.subagent, next.subagent) ||
1002
+ (previous.recall !== undefined && !equalData(previous.recall, next.recall)) ||
1003
+ !equalData(previous.limits, next.limits) ||
1004
+ !equalData(previous.history, next.history) ||
1005
+ !equalData(previous.input, next.input) ||
1006
+ !equalData(previous.session, next.session) ||
1007
+ previous.startedAt !== next.startedAt ||
1008
+ previous.agentId !== next.agentId ||
1009
+ previous.version !== next.version ||
1010
+ !equalData(previous.tree, next.tree))
1011
+ throw new TypeError("The child host returned a different child.");
1012
+ if (previous.inputs.some((input, index) => !equalData(input, next.inputs[index])) ||
1013
+ next.inputs
1014
+ .slice(previous.inputs.length)
1015
+ .some((input) => input.beforeModel < previous.models.length))
1016
+ throw new TypeError("The child host erased an input or changed an admitted model's input.");
1017
+ for (const [index, guard] of previous.guards.entries()) {
1018
+ const saved = next.guards[index];
1019
+ if (!saved ||
1020
+ !equalData({ ...guard, status: saved.status }, saved) ||
1021
+ (guard.status !== "running" && guard.status !== saved.status))
1022
+ throw new TypeError("The child host erased or replaced a guard verdict.");
1023
+ }
1024
+ if (previous.compactions.length > next.compactions.length)
1025
+ throw new TypeError("The child host dropped compaction receipts.");
1026
+ for (const [index, entry] of previous.compactions.entries()) {
1027
+ const saved = next.compactions[index];
1028
+ if (!saved ||
1029
+ entry.id !== saved.id ||
1030
+ entry.cut !== saved.cut ||
1031
+ entry.sourceCount !== saved.sourceCount ||
1032
+ entry.beforeModel !== saved.beforeModel ||
1033
+ (entry.status === "completed" && !equalData(entry, saved)) ||
1034
+ (entry.model && (!saved.model || entry.model.attemptId !== saved.model.attemptId)))
1035
+ throw new TypeError("The child host erased or replaced a compaction.");
1036
+ }
1037
+ if (next.compactions
1038
+ .slice(previous.compactions.length)
1039
+ .some((entry) => entry.beforeModel < previous.models.length))
1040
+ throw new TypeError("The child host changed an admitted model's context.");
1041
+ if (previous.models.length > next.models.length)
1042
+ throw new TypeError("The child host dropped saved model receipts.");
1043
+ if (previous.state.status !== "running" &&
1044
+ previous.state.status !== "suspended" &&
1045
+ !equalData(previous.state, next.state))
1046
+ throw new TypeError("The child host replaced a settled outcome.");
1047
+ for (const [index, model] of previous.models.entries()) {
1048
+ const saved = next.models[index];
1049
+ if (!saved || saved.id !== model.id)
1050
+ throw new TypeError("The child host changed a model operation.");
1051
+ checkAttemptProgress(model, saved);
1052
+ if (model.status !== "completed")
1053
+ continue;
1054
+ if (saved.status !== "completed" ||
1055
+ saved.attemptId !== model.attemptId ||
1056
+ saved.billing !== model.billing ||
1057
+ !equalData(model.turn, saved.turn))
1058
+ throw new TypeError("The child host replaced a completed model receipt.");
1059
+ for (const [position, tool] of model.tools.entries()) {
1060
+ const restored = saved.tools[position];
1061
+ for (const [index, ask] of (tool.asks ?? []).entries()) {
1062
+ const nextAsk = restored?.asks?.[index];
1063
+ if (!nextAsk ||
1064
+ !equalData(ask.request, nextAsk.request) ||
1065
+ (ask.decision && !equalData(ask.decision, nextAsk.decision)) ||
1066
+ (ask.closed && ask.closed !== nextAsk.closed))
1067
+ throw new TypeError("The child host erased or replaced a request receipt.");
1068
+ }
1069
+ if (!restored ||
1070
+ tool.id !== restored.id ||
1071
+ tool.retries.some((attempt, index) => !equalData(attempt, restored.retries[index])) ||
1072
+ tool.interrupted.some((attempt, index) => !equalData(attempt, restored.interrupted[index])) ||
1073
+ (tool.status === "running" && restored.status === "delegating"))
1074
+ throw new TypeError("The child host replaced a tool receipt.");
1075
+ for (const [callIndex, call] of (tool.calls ?? []).entries()) {
1076
+ const nextCall = restored?.calls?.[callIndex];
1077
+ if (!nextCall ||
1078
+ call.id !== nextCall.id ||
1079
+ call.programAttemptId !== nextCall.programAttemptId ||
1080
+ call.name !== nextCall.name ||
1081
+ !equalData(call.arguments, nextCall.arguments) ||
1082
+ (call.started && !nextCall.started) ||
1083
+ (call.attemptId === nextCall.attemptId &&
1084
+ call.bytes !== undefined &&
1085
+ call.bytes !== nextCall.bytes) ||
1086
+ call.interrupted.some((entry, i) => !equalData(entry, nextCall.interrupted[i])) ||
1087
+ call.retries.some((entry, i) => !equalData(entry, nextCall.retries[i])) ||
1088
+ (call.status === "running" &&
1089
+ nextCall.status === "pending" &&
1090
+ nextCall.retries.length === call.retries.length) ||
1091
+ (call.status === "completed" &&
1092
+ !equalData(call, nextCall) &&
1093
+ !nextCall.retries
1094
+ .slice(call.retries.length)
1095
+ .some((entry) => entry.attemptId === call.attemptId && equalData(entry.result, call.result))) ||
1096
+ (call.attemptId !== nextCall.attemptId &&
1097
+ !nextCall.retries.some((entry) => entry.attemptId === call.attemptId)))
1098
+ throw new TypeError("The child host erased, replaced or rolled back a program call.");
1099
+ for (const [askIndex, ask] of (call.asks ?? []).entries()) {
1100
+ const nextAsk = nextCall.asks?.[askIndex];
1101
+ if (!nextAsk ||
1102
+ !equalData(ask.request, nextAsk.request) ||
1103
+ (ask.decision && !equalData(ask.decision, nextAsk.decision)) ||
1104
+ (ask.closed && ask.closed !== nextAsk.closed))
1105
+ throw new TypeError("The child host replaced an inner request receipt.");
1106
+ }
1107
+ }
1108
+ const retained = tool.status === "pending"
1109
+ ? undefined
1110
+ : restored.retries
1111
+ .slice(tool.retries.length)
1112
+ .find((attempt) => attempt.attemptId === tool.attemptId);
1113
+ if (tool.status === "completed" &&
1114
+ !equalData(tool, restored) &&
1115
+ (!retained || tool.result.ok || !equalData(retained.result, tool.result)))
1116
+ throw new TypeError("The child host replaced a completed tool receipt.");
1117
+ // A settled failed attempt can move to retries. An interrupted attempt stays in its
1118
+ // existing history; pure coordinators still carry no external attempt of their own.
1119
+ if (tool.status !== "delegating" && !retained)
1120
+ checkAttemptProgress(tool, restored);
1121
+ }
1122
+ }
1123
+ for (const journal of previous.delegations) {
1124
+ const saved = next.delegations.find((entry) => entry.operationId === journal.operationId);
1125
+ if (!saved || saved.children.length < journal.children.length)
1126
+ throw new TypeError("The child host dropped a delegation receipt.");
1127
+ if (saved.kind !== journal.kind ||
1128
+ (journal.kind === "handoff" &&
1129
+ (saved.kind !== "handoff" ||
1130
+ !equalData(saved.target, journal.target) ||
1131
+ (journal.children.length > 0 && saved.note !== journal.note))))
1132
+ throw new TypeError("The child host changed a handoff identity or admitted note.");
1133
+ for (const [index, child] of journal.children.entries()) {
1134
+ const restored = saved.children[index];
1135
+ if (!restored || restored.key !== child.key)
1136
+ throw new TypeError("The child host changed child admission order.");
1137
+ checkChildProgress(child.snapshot, restored.snapshot);
1138
+ }
1139
+ }
1140
+ }
1141
+ /** The selected result is journal data, not a second invocation of the tool. Model order
1142
+ * wins even when a later tool in a parallel batch finishes first. */
1143
+ export function finalToolResult(model, stopAtTools, resultTool) {
1144
+ const calls = model.turn.message.toolCalls ?? [];
1145
+ for (const [index, call] of calls.entries()) {
1146
+ const tool = model.tools[index];
1147
+ if (tool?.status !== "completed" || !tool.result.ok)
1148
+ continue;
1149
+ if ((calls.length === 1 && call.name === resultTool) || stopAtTools.includes(call.name))
1150
+ if (tool.result.final)
1151
+ return tool.result.final;
1152
+ }
1153
+ return undefined;
1154
+ }
1155
+ /** A successful handoff keeps the target's raw candidate, not its transformed output. The
1156
+ * target runtime owns validation, even when the source has a different output contract. */
1157
+ export function finalHandoffResult(snapshot, model) {
1158
+ const tool = model.tools[0];
1159
+ if (model.tools.length !== 1 || tool?.status !== "completed" || !tool.result.ok)
1160
+ return undefined;
1161
+ const journal = snapshot.delegations.find((entry) => entry.operationId === tool.id);
1162
+ const child = journal?.kind === "handoff" ? journal.children[0]?.snapshot : undefined;
1163
+ return child?.kind === "agent" && child.state.status === "completed"
1164
+ ? { candidate: child.state.candidate, child }
1165
+ : undefined;
1166
+ }
1167
+ /** Saved verdicts cannot be dropped to turn a withheld response into a completed one. This
1168
+ * checks journal structure, not authenticity: the host still supplies authoritative state. */
1169
+ function checkGuards(snapshot) {
1170
+ const stages = snapshot.definition.guardrails?.stages ?? [];
1171
+ for (const guard of snapshot.guards) {
1172
+ if (!stages.includes(guard.stage))
1173
+ throw new TypeError("A guard is not in the recorded policy.");
1174
+ const model = allModels(snapshot).find((model) => model.id === guard.operationId ||
1175
+ (model.status === "completed" &&
1176
+ model.tools.some((tool) => tool.id === guard.operationId ||
1177
+ tool.calls?.some((call) => call.id === guard.operationId))));
1178
+ if (!model &&
1179
+ !(guard.stage === "modelInput" &&
1180
+ (guard.operationId === modelId(snapshot.runId, snapshot.models.length) ||
1181
+ snapshot.compactions.some((entry) => entry.id === guard.operationId))))
1182
+ throw new TypeError("A guard does not match a journaled operation.");
1183
+ if (snapshot.state.status === "completed" && guard.status !== "allowed")
1184
+ throw new TypeError("A completed run cannot have an unfinished or rejected guard.");
1185
+ }
1186
+ function requireGuardVerdict(stage, id, attemptId) {
1187
+ if (stages.includes(stage) &&
1188
+ !snapshot.guards.some((guard) => guard.stage === stage &&
1189
+ guard.operationId === id &&
1190
+ guard.attemptId === attemptId &&
1191
+ guard.status === "allowed"))
1192
+ throw new TypeError("A completed operation is missing its allowed guard verdict.");
1193
+ }
1194
+ for (const model of allModels(snapshot)) {
1195
+ // Input checks precede admission; even running work must have passed them.
1196
+ requireGuardVerdict("modelInput", model.id, model.attemptId);
1197
+ if (model.status !== "completed")
1198
+ continue;
1199
+ requireGuardVerdict("modelOutput", model.id, model.attemptId);
1200
+ for (const tool of model.tools) {
1201
+ for (const call of tool.calls ?? []) {
1202
+ for (const attempt of call.retries) {
1203
+ requireGuardVerdict("toolInput", call.id, attempt.attemptId);
1204
+ requireGuardVerdict("toolOutput", call.id, attempt.attemptId);
1205
+ }
1206
+ if (call.status !== "completed")
1207
+ continue;
1208
+ if (call.result.ok)
1209
+ requireGuardVerdict("toolInput", call.id, call.attemptId);
1210
+ if (call.result.ok || !["aborted", "interrupted"].includes(call.result.kind))
1211
+ requireGuardVerdict("toolOutput", call.id, call.attemptId);
1212
+ }
1213
+ for (const attempt of tool.retries) {
1214
+ requireGuardVerdict("toolInput", tool.id, attempt.attemptId);
1215
+ requireGuardVerdict("toolOutput", tool.id, attempt.attemptId);
1216
+ }
1217
+ if (tool.status !== "completed")
1218
+ continue;
1219
+ if (tool.result.ok)
1220
+ requireGuardVerdict("toolInput", tool.id, tool.attemptId);
1221
+ requireGuardVerdict("toolOutput", tool.id, tool.attemptId);
1222
+ }
1223
+ }
1224
+ }
1225
+ /** Program receipts are private evidence, never a continuation of the guest VM. */
1226
+ function checkProgramJournal(snapshot, tool, code) {
1227
+ if (tool.calls === undefined) {
1228
+ if (code &&
1229
+ (tool.status === "running" ||
1230
+ tool.interrupted.length ||
1231
+ (tool.status === "completed" && tool.result.ok)))
1232
+ throw new TypeError("An admitted code program is missing its call journal.");
1233
+ return 0;
1234
+ }
1235
+ if (!code ||
1236
+ !snapshot.definition.enabledTools.includes(code.name) ||
1237
+ tool.status === "delegating" ||
1238
+ (tool.status === "pending" && !tool.interrupted.length))
1239
+ throw new TypeError("Only an admitted code tool can contain program calls.");
1240
+ if (tool.status === "completed") {
1241
+ let envelope;
1242
+ try {
1243
+ envelope = JSON.parse(tool.result.content);
1244
+ }
1245
+ catch {
1246
+ throw new TypeError("A code result must be a JSON envelope.");
1247
+ }
1248
+ if (!isRecord(envelope) ||
1249
+ envelope.toolCalls !== tool.calls.length ||
1250
+ (tool.result.ok
1251
+ ? envelope.error !== undefined || envelope.calls !== undefined
1252
+ : envelope.error === undefined || envelope.result !== undefined) ||
1253
+ (envelope.result !== undefined &&
1254
+ textBytes(programJson(envelope.result)) > code.limits.resultBytes) ||
1255
+ (envelope.logs !== undefined &&
1256
+ (typeof envelope.logs !== "string" || textBytes(envelope.logs) > code.limits.logBytes)) ||
1257
+ (envelope.droppedLogBytes !== undefined &&
1258
+ (!finite(envelope.droppedLogBytes) || !Number.isSafeInteger(envelope.droppedLogBytes))) ||
1259
+ (envelope.toolCallsLeft !== undefined &&
1260
+ (!finite(envelope.toolCallsLeft) ||
1261
+ !Number.isSafeInteger(envelope.toolCallsLeft) ||
1262
+ envelope.toolCallsLeft > code.limits.calls)) ||
1263
+ (envelope.error !== undefined &&
1264
+ (!isRecord(envelope.error) ||
1265
+ !isId(envelope.error.name) ||
1266
+ envelope.error.name.length > 64 ||
1267
+ typeof envelope.error.message !== "string" ||
1268
+ textBytes(envelope.error.message) > 2048 ||
1269
+ !optional(envelope.error.line, positive))) ||
1270
+ (envelope.calls !== undefined &&
1271
+ (!Array.isArray(envelope.calls) ||
1272
+ envelope.calls.length > 20 ||
1273
+ envelope.calls.some((note) => !isRecord(note) ||
1274
+ !isId(note.tool) ||
1275
+ !code.tools.some((tool) => tool.name === note.tool) ||
1276
+ typeof note.note !== "string" ||
1277
+ note.note.length > 200 ||
1278
+ !["returned", "failed", "refused", "stopped", "not started"].includes(String(note.status))))) ||
1279
+ Object.keys(envelope).some((key) => ![
1280
+ "result",
1281
+ "logs",
1282
+ "droppedLogBytes",
1283
+ "toolCalls",
1284
+ "toolCallsLeft",
1285
+ "error",
1286
+ "calls",
1287
+ ].includes(key)))
1288
+ throw new TypeError("The code result exceeds its recorded count or byte limits.");
1289
+ }
1290
+ const attempts = [
1291
+ ...tool.interrupted.map((entry) => entry.attemptId),
1292
+ ...(tool.status !== "pending" ? [tool.attemptId] : []),
1293
+ ];
1294
+ let previousAttempt = -1;
1295
+ let total = 0;
1296
+ const counts = new Map();
1297
+ for (const [position, call] of tool.calls.entries()) {
1298
+ const bound = code.tools.find((bound) => bound.name === call.name);
1299
+ const attempt = attempts.indexOf(call.programAttemptId);
1300
+ if (!bound ||
1301
+ !snapshot.definition.enabledTools.includes(call.name) ||
1302
+ call.id !== `${tool.id}/call/${position + 1}` ||
1303
+ call.interrupted.length ||
1304
+ attempt < previousAttempt ||
1305
+ attempt < 0 ||
1306
+ textBytes(programJson(call.arguments)) > code.limits.callInputBytes ||
1307
+ ((call.status === "running" || call.retries.length > 0) && !call.started) ||
1308
+ (call.status === "completed" && call.result.ok && !call.started) ||
1309
+ ((tool.status === "completed" ||
1310
+ attempt < attempts.length - 1 ||
1311
+ tool.status === "pending") &&
1312
+ call.status !== "completed"))
1313
+ throw new TypeError("Invalid code call identity, binding, input, attempt or settlement.");
1314
+ previousAttempt = attempt;
1315
+ const expectedAttempt = (n) => n === 0
1316
+ ? call.programAttemptId
1317
+ : `${call.programAttemptId}/call/${position + 1}/attempt/${n + 1}`;
1318
+ if (call.attemptId !== expectedAttempt(call.retries.length) ||
1319
+ call.retries.some((retry, index) => retry.attemptId !== expectedAttempt(index)))
1320
+ throw new TypeError("Code tool attempts must keep their original identity and increase in order.");
1321
+ const retry = retryBudget(snapshot.definition.toolRetries, call.name);
1322
+ if (call.retries.length &&
1323
+ (!retry ||
1324
+ call.asks?.length ||
1325
+ call.retries.length + 1 > retry.maxAttempts ||
1326
+ call.retries.some((entry) => !equalData(entry.arguments, call.arguments) ||
1327
+ (retry.replay === "reconcile"
1328
+ ? !isId(entry.reconciliation)
1329
+ : entry.reconciliation !== undefined))))
1330
+ throw new TypeError("Code retries do not match the saved retry policy.");
1331
+ const results = [
1332
+ ...call.retries.map((entry) => entry.result),
1333
+ ...(call.status === "completed" ? [call.result] : []),
1334
+ ];
1335
+ if (results.some((result) => textBytes(result.content) > 1024 ||
1336
+ (result.ok &&
1337
+ (result.output !== undefined ||
1338
+ result.images !== undefined ||
1339
+ result.final !== undefined))))
1340
+ throw new TypeError("Code receipts may retain only bounded result previews.");
1341
+ for (const [index, ask] of (call.asks ?? []).entries()) {
1342
+ const request = ask.request;
1343
+ if (request.ask.type !== "approval" ||
1344
+ !request.call ||
1345
+ request.step !== undefined ||
1346
+ request.id !== `${call.id}/ask/${index + 1}` ||
1347
+ request.call.parentOperationId !== tool.id ||
1348
+ request.call.operationId !== call.id ||
1349
+ request.call.call.id !== call.id ||
1350
+ request.call.call.name !== call.name ||
1351
+ request.call.agentId !== snapshot.agentId ||
1352
+ request.call.runId !== snapshot.runId ||
1353
+ request.call.version !== snapshot.version ||
1354
+ request.call.subagent !== snapshot.subagent?.spec.name ||
1355
+ ![call.attemptId, ...call.retries.map((entry) => entry.attemptId)].includes(request.call.attemptId) ||
1356
+ !equalData(jsonArguments(request.call.call.arguments), call.arguments) ||
1357
+ !equalData(request.call.arguments, call.arguments) ||
1358
+ request.createdAt < snapshot.startedAt ||
1359
+ (call.status === "completed" && !ask.closed && !ask.decision) ||
1360
+ (ask.decision?.type === "approve" &&
1361
+ ask.decision.arguments !== undefined &&
1362
+ textBytes(programJson(ask.decision.arguments)) > code.limits.callInputBytes &&
1363
+ call.started))
1364
+ throw new TypeError("An inner approval does not match its owning code call.");
1365
+ }
1366
+ const count = (counts.get(call.programAttemptId) ?? 0) + 1 + call.retries.length;
1367
+ if (count > code.limits.calls)
1368
+ throw new TypeError("The program exceeds its call limit.");
1369
+ counts.set(call.programAttemptId, count);
1370
+ total += 1 + call.retries.length;
1371
+ }
1372
+ if (tool.interrupted.length &&
1373
+ tool.calls.some((call) => call.programAttemptId !== (tool.status !== "pending" ? tool.attemptId : undefined) &&
1374
+ (!code.tools.find((bound) => bound.name === call.name)?.isReadOnly || call.asks?.length)))
1375
+ throw new TypeError("A restarted program cannot contain an earlier effect or approval.");
1376
+ return total;
1377
+ }
1378
+ /** Validate data-only journals without live tools. Execution callers supply their actual code
1379
+ * registry, which must match the saved policy. Recorded data never replaces host authorization. */
1380
+ export function readSnapshot(raw, agentId, version, limits, resultTool, codeTools) {
1381
+ if (!serializable(raw) || !isSnapshot(raw))
1382
+ throw new TypeError("Invalid agent snapshot.");
1383
+ const recordedCode = raw.definition.codeTools ?? {};
1384
+ if (codeTools !== undefined && !equalData(recordedCode, recordCodeTools(codeTools))) {
1385
+ throw new TypeError("The recorded code bindings or limits changed. Restore the same code tools before resuming.");
1386
+ }
1387
+ if (raw.agentId !== agentId || raw.version !== version)
1388
+ throw new TypeError("The snapshot belongs to a different agent definition or version.");
1389
+ if (!equalData(raw.limits, limits))
1390
+ throw new TypeError("The snapshot limits do not match this agent version.");
1391
+ let calls = 0;
1392
+ for (const [index, model] of raw.models.entries()) {
1393
+ if (model.id !== modelId(raw.runId, index))
1394
+ throw new TypeError("Invalid model operation identity.");
1395
+ if (model.interrupted.length &&
1396
+ (!raw.definition.recovery?.policy.inferenceOnly ||
1397
+ !!raw.definition.modelSettings.hostedTools?.length ||
1398
+ model.interrupted.length >= raw.definition.recovery.policy.maxAttempts))
1399
+ throw new TypeError("Model attempts exceed the recorded recovery policy.");
1400
+ const last = index === raw.models.length - 1;
1401
+ // A plain-text run gets one last answer with no tools. It is still a model operation
1402
+ // counted by the tree. No receipt on that extra turn may claim a tool was executed.
1403
+ if (index >= limits.turns &&
1404
+ (resultTool ||
1405
+ index !== limits.turns ||
1406
+ (model.status === "completed" && model.tools.some((tool) => tool.status !== "pending"))))
1407
+ throw new TypeError("The final tool-free turn cannot execute tools or exceed the turn allowance.");
1408
+ if (model.status === "running") {
1409
+ if (!last)
1410
+ throw new TypeError("A model operation has an unknown outcome before later work.");
1411
+ continue;
1412
+ }
1413
+ readTurn(model.turn);
1414
+ const tools = model.turn.message.toolCalls ?? [];
1415
+ if (tools.length !== model.tools.length)
1416
+ throw new TypeError("The tool journal does not match the model turn.");
1417
+ if (!equalData(model.usage, model.turn.usage))
1418
+ throw new TypeError("The model usage does not match its completed turn.");
1419
+ let pending = false;
1420
+ for (const [position, tool] of model.tools.entries()) {
1421
+ if (tool.id !== toolId(model.id, position) ||
1422
+ (!last && tool.status !== "completed") ||
1423
+ (pending &&
1424
+ tool.status !== "pending" &&
1425
+ !tool.asks?.length &&
1426
+ !tool.interrupted.length &&
1427
+ !tool.retries.length)) {
1428
+ throw new TypeError("Invalid tool operation position.");
1429
+ }
1430
+ const call = tools[position];
1431
+ if (!call ||
1432
+ (tool.status === "completed" && tool.result.ok && !completeArguments(call.arguments))) {
1433
+ throw new TypeError("A successful tool result must have complete arguments.");
1434
+ }
1435
+ if (tool.status !== "pending" &&
1436
+ model.turn.finishReason !== "stop" &&
1437
+ model.turn.finishReason !== "tool_calls") {
1438
+ throw new TypeError("An unfinished model turn cannot have executed tools.");
1439
+ }
1440
+ if (tool.status === "completed" && tool.result.ok) {
1441
+ if (!raw.definition.enabledTools.includes(call.name) ||
1442
+ raw.definition.modelSettings.toolChoice === "none")
1443
+ throw new TypeError("A disabled tool cannot have a successful result.");
1444
+ const stopping = raw.definition.stopAtTools.includes(call.name) || call.name === resultTool;
1445
+ if (tool.result.final && !stopping)
1446
+ throw new TypeError("This tool is not configured to produce a final result.");
1447
+ if (stopping && !tool.result.final)
1448
+ throw new TypeError("A successful stopping tool must record its final result.");
1449
+ }
1450
+ const keys = new Set();
1451
+ const code = Object.hasOwn(recordedCode, call.name) ? recordedCode[call.name] : undefined;
1452
+ const originalArguments = code
1453
+ ? (jsonArguments(call.arguments) ?? {})
1454
+ : parseToolArgs(call.arguments);
1455
+ let clientArguments = originalArguments;
1456
+ for (const [askIndex, record] of (tool.asks ?? []).entries()) {
1457
+ const request = record.request;
1458
+ if (!request.call ||
1459
+ request.step !== undefined ||
1460
+ request.id !== `${tool.id}/ask/${askIndex + 1}` ||
1461
+ request.call.operationId !== tool.id ||
1462
+ request.call.parentOperationId !== undefined ||
1463
+ request.call.runId !== raw.runId ||
1464
+ request.call.agentId !== raw.agentId ||
1465
+ request.call.version !== raw.version ||
1466
+ request.call.subagent !== raw.subagent?.spec.name ||
1467
+ !equalData(request.call.call, call) ||
1468
+ !completeArguments(call.arguments) ||
1469
+ !equalData(request.call.arguments, request.ask.type === "client" ? clientArguments : originalArguments) ||
1470
+ request.createdAt < raw.startedAt ||
1471
+ (tool.status === "completed" && !record.closed && !record.decision))
1472
+ throw new TypeError("The request does not match its journaled tool call.");
1473
+ // A dispatch keeps the approval that preceded it, even if that approval later expired.
1474
+ if (request.ask.type === "approval")
1475
+ clientArguments =
1476
+ record.decision?.type === "approve"
1477
+ ? (record.decision.arguments ?? originalArguments)
1478
+ : originalArguments;
1479
+ if (!record.closed) {
1480
+ const key = request.ask.type === "question" ? `question:${request.ask.key}` : request.ask.type;
1481
+ if (keys.has(key))
1482
+ throw new TypeError("A call has duplicate open request keys.");
1483
+ keys.add(key);
1484
+ }
1485
+ }
1486
+ if (call.name === resultTool &&
1487
+ tool.status === "completed" &&
1488
+ tool.result.ok &&
1489
+ (tools.length !== 1 || !equalData(tool.result.final?.candidate, clientArguments)))
1490
+ throw new TypeError("The submitted result does not match its effective arguments.");
1491
+ if (tool.interrupted.length &&
1492
+ (!raw.definition.recovery?.policy.readOnlyTools?.includes(call.name) ||
1493
+ toolAttempts(tool) > raw.definition.recovery.policy.maxAttempts ||
1494
+ tool.status === "delegating"))
1495
+ throw new TypeError("Tool attempts exceed the recorded recovery policy.");
1496
+ const retry = retryBudget(raw.definition.toolRetries, call.name);
1497
+ if ((retry && toolAttempts(tool) > retry.maxAttempts) ||
1498
+ (tool.retries.length &&
1499
+ (!retry ||
1500
+ tool.asks?.length ||
1501
+ tool.status === "delegating" ||
1502
+ raw.definition.stopAtTools.includes(call.name) ||
1503
+ call.name === resultTool ||
1504
+ !raw.definition.enabledTools.includes(call.name) ||
1505
+ raw.definition.modelSettings.toolChoice === "none" ||
1506
+ !completeArguments(call.arguments) ||
1507
+ tool.retries.some((attempt) => !equalData(attempt.arguments, originalArguments) ||
1508
+ (retry.replay === "reconcile"
1509
+ ? !isId(attempt.reconciliation)
1510
+ : attempt.reconciliation !== undefined)))))
1511
+ throw new TypeError("Tool retries do not match the recorded policy or call.");
1512
+ pending ||=
1513
+ tool.status === "pending" &&
1514
+ !tool.asks?.length &&
1515
+ !tool.interrupted.length &&
1516
+ !tool.retries.length;
1517
+ const approved = [...(tool.asks ?? [])]
1518
+ .reverse()
1519
+ .find((record) => !record.closed && record.decision?.type === "approve")?.decision;
1520
+ const effectiveCode = approved?.type === "approve" && approved.arguments !== undefined
1521
+ ? approved.arguments
1522
+ : originalArguments;
1523
+ if (code &&
1524
+ (tool.calls?.length || (tool.status === "completed" && tool.result.ok)) &&
1525
+ (!completeArguments(call.arguments) ||
1526
+ typeof effectiveCode.code !== "string" ||
1527
+ Object.keys(effectiveCode).length !== 1 ||
1528
+ textBytes(effectiveCode.code) > code.limits.sourceBytes))
1529
+ throw new TypeError("The admitted code source does not fit its saved limit or input schema.");
1530
+ calls += toolAttempts(tool) + checkProgramJournal(raw, tool, code);
1531
+ }
1532
+ if (!last &&
1533
+ (tools.length === 0 ||
1534
+ model.turn.finishReason === null ||
1535
+ model.turn.finishReason === "length" ||
1536
+ model.turn.finishReason === "content_filter" ||
1537
+ finalToolResult(model, raw.definition.stopAtTools, resultTool))) {
1538
+ throw new TypeError("A finished model turn cannot have later work.");
1539
+ }
1540
+ }
1541
+ for (const [index, input] of raw.inputs.entries()) {
1542
+ if (input.beforeModel > raw.models.length ||
1543
+ input.beforeModel < (raw.inputs[index - 1]?.beforeModel ?? 0) ||
1544
+ raw.models
1545
+ .slice(0, input.beforeModel)
1546
+ .some((model) => model.status !== "completed" ||
1547
+ model.tools.some((tool) => tool.status !== "completed") ||
1548
+ !model.tools.length ||
1549
+ model.turn.finishReason === null ||
1550
+ model.turn.finishReason === "length" ||
1551
+ model.turn.finishReason === "content_filter" ||
1552
+ finalToolResult(model, raw.definition.stopAtTools, resultTool) ||
1553
+ finalHandoffResult(raw, model)))
1554
+ throw new TypeError("An input must join before a new model call, after whole non-final rounds.");
1555
+ }
1556
+ if (raw.models.length > limits.turns + (resultTool ? 0 : 1) ||
1557
+ calls > limits.toolCalls ||
1558
+ snapshotInlineBytes(raw) > limits.inlineBytes)
1559
+ throw new TypeError("The snapshot exceeds this agent's limits.");
1560
+ const last = raw.models.at(-1);
1561
+ if (raw.state.status === "completed") {
1562
+ if (last?.status !== "completed" ||
1563
+ last.tools.some((tool) => tool.status !== "completed") ||
1564
+ last.turn.finishReason === null ||
1565
+ last.turn.finishReason === "length" ||
1566
+ last.turn.finishReason === "content_filter") {
1567
+ throw new TypeError("A completed run must have a completed final turn.");
1568
+ }
1569
+ const tools = last.turn.message.toolCalls ?? [];
1570
+ const final = finalHandoffResult(raw, last) ??
1571
+ finalToolResult(last, raw.definition.stopAtTools, resultTool);
1572
+ const candidate = final
1573
+ ? final.candidate
1574
+ : !resultTool && tools.length === 0 && last.turn.message.content.trim()
1575
+ ? last.turn.message.content
1576
+ : undefined;
1577
+ if (candidate === undefined || !equalData(candidate, raw.state.candidate)) {
1578
+ throw new TypeError("The completed result does not match its recorded turn.");
1579
+ }
1580
+ }
1581
+ checkMemorySnapshot(raw);
1582
+ checkCompactions(raw);
1583
+ for (const entry of raw.compactions) {
1584
+ if (raw.models
1585
+ .slice(0, entry.beforeModel)
1586
+ .some((model) => model.status !== "completed" ||
1587
+ !model.tools.length ||
1588
+ model.tools.some((tool) => tool.status !== "completed") ||
1589
+ !["stop", "tool_calls"].includes(model.turn.finishReason ?? "") ||
1590
+ finalToolResult(model, raw.definition.stopAtTools, resultTool) ||
1591
+ finalHandoffResult(raw, model)))
1592
+ throw new TypeError("Compaction must follow whole non-final rounds.");
1593
+ if (entry.model?.status === "completed") {
1594
+ readTurn(entry.model.turn);
1595
+ if (!equalData(entry.model.usage, entry.model.turn.usage))
1596
+ throw new TypeError("Summary usage does not match its completed turn.");
1597
+ }
1598
+ }
1599
+ checkGuards(raw);
1600
+ checkTree(raw);
1601
+ if (raw.state.status === "suspended" &&
1602
+ !raw.models.some((model) => model.status === "completed" &&
1603
+ model.tools.some((tool) => tool.status !== "completed" && (tool.asks?.length || tool.status === "delegating"))))
1604
+ throw new TypeError("A suspended run needs a journaled request or delegation.");
1605
+ return copyData(raw);
1606
+ }
1607
+ //# sourceMappingURL=snapshot.js.map