@providerkit/agents 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/LICENSE-APACHE-2.0 +202 -0
  2. package/README.md +2108 -52
  3. package/THIRD_PARTY_NOTICES.md +521 -0
  4. package/dist/a2a/auth.d.ts +10 -0
  5. package/dist/a2a/auth.d.ts.map +1 -0
  6. package/dist/a2a/auth.js +52 -0
  7. package/dist/a2a/auth.js.map +1 -0
  8. package/dist/a2a/client.d.ts +74 -0
  9. package/dist/a2a/client.d.ts.map +1 -0
  10. package/dist/a2a/client.js +601 -0
  11. package/dist/a2a/client.js.map +1 -0
  12. package/dist/a2a/index.d.ts +22 -0
  13. package/dist/a2a/index.d.ts.map +1 -0
  14. package/dist/a2a/index.js +11 -0
  15. package/dist/a2a/index.js.map +1 -0
  16. package/dist/a2a/memory-runs.d.ts +62 -0
  17. package/dist/a2a/memory-runs.d.ts.map +1 -0
  18. package/dist/a2a/memory-runs.js +349 -0
  19. package/dist/a2a/memory-runs.js.map +1 -0
  20. package/dist/a2a/policy.d.ts +15 -0
  21. package/dist/a2a/policy.d.ts.map +1 -0
  22. package/dist/a2a/policy.js +114 -0
  23. package/dist/a2a/policy.js.map +1 -0
  24. package/dist/a2a/push.d.ts +34 -0
  25. package/dist/a2a/push.d.ts.map +1 -0
  26. package/dist/a2a/push.js +180 -0
  27. package/dist/a2a/push.js.map +1 -0
  28. package/dist/a2a/remote.d.ts +155 -0
  29. package/dist/a2a/remote.d.ts.map +1 -0
  30. package/dist/a2a/remote.js +1196 -0
  31. package/dist/a2a/remote.js.map +1 -0
  32. package/dist/a2a/server.d.ts +110 -0
  33. package/dist/a2a/server.d.ts.map +1 -0
  34. package/dist/a2a/server.js +1139 -0
  35. package/dist/a2a/server.js.map +1 -0
  36. package/dist/a2a/signing.d.ts +21 -0
  37. package/dist/a2a/signing.d.ts.map +1 -0
  38. package/dist/a2a/signing.js +305 -0
  39. package/dist/a2a/signing.js.map +1 -0
  40. package/dist/a2a/tasks.d.ts +88 -0
  41. package/dist/a2a/tasks.d.ts.map +1 -0
  42. package/dist/a2a/tasks.js +170 -0
  43. package/dist/a2a/tasks.js.map +1 -0
  44. package/dist/a2a/wire.d.ts +267 -0
  45. package/dist/a2a/wire.d.ts.map +1 -0
  46. package/dist/a2a/wire.js +1202 -0
  47. package/dist/a2a/wire.js.map +1 -0
  48. package/dist/background-types.d.ts +76 -0
  49. package/dist/background-types.d.ts.map +1 -0
  50. package/dist/background-types.js +2 -0
  51. package/dist/background-types.js.map +1 -0
  52. package/dist/child.d.ts +25 -0
  53. package/dist/child.d.ts.map +1 -0
  54. package/dist/child.js +129 -0
  55. package/dist/child.js.map +1 -0
  56. package/dist/code-driver.d.ts +40 -0
  57. package/dist/code-driver.d.ts.map +1 -0
  58. package/dist/code-driver.js +2 -0
  59. package/dist/code-driver.js.map +1 -0
  60. package/dist/code-mode.d.ts +3 -0
  61. package/dist/code-mode.d.ts.map +1 -0
  62. package/dist/code-mode.js +2 -0
  63. package/dist/code-mode.js.map +1 -0
  64. package/dist/code-script.d.ts +3 -0
  65. package/dist/code-script.d.ts.map +1 -0
  66. package/dist/code-script.js +149 -0
  67. package/dist/code-script.js.map +1 -0
  68. package/dist/code.d.ts +75 -0
  69. package/dist/code.d.ts.map +1 -0
  70. package/dist/code.js +326 -0
  71. package/dist/code.js.map +1 -0
  72. package/dist/compaction.d.ts +15 -0
  73. package/dist/compaction.d.ts.map +1 -0
  74. package/dist/compaction.js +168 -0
  75. package/dist/compaction.js.map +1 -0
  76. package/dist/delegation.d.ts +85 -16
  77. package/dist/delegation.d.ts.map +1 -1
  78. package/dist/delegation.js +240 -106
  79. package/dist/delegation.js.map +1 -1
  80. package/dist/evals/driver.d.ts +10 -0
  81. package/dist/evals/driver.d.ts.map +1 -0
  82. package/dist/evals/driver.js +192 -0
  83. package/dist/evals/driver.js.map +1 -0
  84. package/dist/evals/journal.d.ts +26 -0
  85. package/dist/evals/journal.d.ts.map +1 -0
  86. package/dist/evals/journal.js +483 -0
  87. package/dist/evals/journal.js.map +1 -0
  88. package/dist/evals/judge.d.ts +31 -0
  89. package/dist/evals/judge.d.ts.map +1 -0
  90. package/dist/evals/judge.js +142 -0
  91. package/dist/evals/judge.js.map +1 -0
  92. package/dist/evals/report.d.ts +38 -0
  93. package/dist/evals/report.d.ts.map +1 -0
  94. package/dist/evals/report.js +241 -0
  95. package/dist/evals/report.js.map +1 -0
  96. package/dist/evals/runner.d.ts +24 -0
  97. package/dist/evals/runner.d.ts.map +1 -0
  98. package/dist/evals/runner.js +655 -0
  99. package/dist/evals/runner.js.map +1 -0
  100. package/dist/evals/scorers.d.ts +36 -0
  101. package/dist/evals/scorers.d.ts.map +1 -0
  102. package/dist/evals/scorers.js +259 -0
  103. package/dist/evals/scorers.js.map +1 -0
  104. package/dist/evals/simulation.d.ts +7 -0
  105. package/dist/evals/simulation.d.ts.map +1 -0
  106. package/dist/evals/simulation.js +38 -0
  107. package/dist/evals/simulation.js.map +1 -0
  108. package/dist/evals/testing.d.ts +36 -0
  109. package/dist/evals/testing.d.ts.map +1 -0
  110. package/dist/evals/testing.js +87 -0
  111. package/dist/evals/testing.js.map +1 -0
  112. package/dist/evals/trajectory.d.ts +11 -0
  113. package/dist/evals/trajectory.d.ts.map +1 -0
  114. package/dist/evals/trajectory.js +180 -0
  115. package/dist/evals/trajectory.js.map +1 -0
  116. package/dist/evals/types.d.ts +431 -0
  117. package/dist/evals/types.d.ts.map +1 -0
  118. package/dist/evals/types.js +4 -0
  119. package/dist/evals/types.js.map +1 -0
  120. package/dist/evals.d.ts +14 -0
  121. package/dist/evals.d.ts.map +1 -0
  122. package/dist/evals.js +9 -0
  123. package/dist/evals.js.map +1 -0
  124. package/dist/extensions.d.ts +33 -0
  125. package/dist/extensions.d.ts.map +1 -0
  126. package/dist/extensions.js +188 -0
  127. package/dist/extensions.js.map +1 -0
  128. package/dist/handoff.d.ts +58 -0
  129. package/dist/handoff.d.ts.map +1 -0
  130. package/dist/handoff.js +160 -0
  131. package/dist/handoff.js.map +1 -0
  132. package/dist/index.d.ts +14 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +8 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/input.d.ts +42 -0
  137. package/dist/input.d.ts.map +1 -0
  138. package/dist/input.js +266 -0
  139. package/dist/input.js.map +1 -0
  140. package/dist/mcp.d.ts +77 -0
  141. package/dist/mcp.d.ts.map +1 -0
  142. package/dist/mcp.js +505 -0
  143. package/dist/mcp.js.map +1 -0
  144. package/dist/memory-store.d.ts +11 -0
  145. package/dist/memory-store.d.ts.map +1 -0
  146. package/dist/memory-store.js +272 -0
  147. package/dist/memory-store.js.map +1 -0
  148. package/dist/memory.d.ts +212 -0
  149. package/dist/memory.d.ts.map +1 -0
  150. package/dist/memory.js +613 -0
  151. package/dist/memory.js.map +1 -0
  152. package/dist/otel.d.ts +74 -0
  153. package/dist/otel.d.ts.map +1 -0
  154. package/dist/otel.js +427 -0
  155. package/dist/otel.js.map +1 -0
  156. package/dist/progress.d.ts +17 -0
  157. package/dist/progress.d.ts.map +1 -0
  158. package/dist/progress.js +193 -0
  159. package/dist/progress.js.map +1 -0
  160. package/dist/quickjs.d.ts +19 -0
  161. package/dist/quickjs.d.ts.map +1 -0
  162. package/dist/quickjs.js +519 -0
  163. package/dist/quickjs.js.map +1 -0
  164. package/dist/recovery.d.ts +10 -0
  165. package/dist/recovery.d.ts.map +1 -0
  166. package/dist/recovery.js +62 -0
  167. package/dist/recovery.js.map +1 -0
  168. package/dist/request.d.ts +88 -0
  169. package/dist/request.d.ts.map +1 -0
  170. package/dist/request.js +422 -0
  171. package/dist/request.js.map +1 -0
  172. package/dist/run.d.ts +16 -4
  173. package/dist/run.d.ts.map +1 -1
  174. package/dist/run.js +2016 -245
  175. package/dist/run.js.map +1 -1
  176. package/dist/runs.d.ts +77 -34
  177. package/dist/runs.d.ts.map +1 -1
  178. package/dist/runs.js +267 -85
  179. package/dist/runs.js.map +1 -1
  180. package/dist/schema-to-ts.d.ts +4 -0
  181. package/dist/schema-to-ts.d.ts.map +1 -0
  182. package/dist/schema-to-ts.js +191 -0
  183. package/dist/schema-to-ts.js.map +1 -0
  184. package/dist/session.d.ts +23 -0
  185. package/dist/session.d.ts.map +1 -0
  186. package/dist/session.js +137 -0
  187. package/dist/session.js.map +1 -0
  188. package/dist/snapshot.d.ts +57 -8
  189. package/dist/snapshot.d.ts.map +1 -1
  190. package/dist/snapshot.js +1206 -109
  191. package/dist/snapshot.js.map +1 -1
  192. package/dist/steering.d.ts +75 -0
  193. package/dist/steering.d.ts.map +1 -0
  194. package/dist/steering.js +214 -0
  195. package/dist/steering.js.map +1 -0
  196. package/dist/subagents.d.ts +141 -0
  197. package/dist/subagents.d.ts.map +1 -0
  198. package/dist/subagents.js +746 -0
  199. package/dist/subagents.js.map +1 -0
  200. package/dist/tool-retry.d.ts +12 -0
  201. package/dist/tool-retry.d.ts.map +1 -0
  202. package/dist/tool-retry.js +53 -0
  203. package/dist/tool-retry.js.map +1 -0
  204. package/dist/tree.d.ts +62 -6
  205. package/dist/tree.d.ts.map +1 -1
  206. package/dist/tree.js +192 -23
  207. package/dist/tree.js.map +1 -1
  208. package/dist/types.d.ts +767 -52
  209. package/dist/types.d.ts.map +1 -1
  210. package/dist/workflow-snapshot.d.ts +8 -0
  211. package/dist/workflow-snapshot.d.ts.map +1 -0
  212. package/dist/workflow-snapshot.js +276 -0
  213. package/dist/workflow-snapshot.js.map +1 -0
  214. package/dist/workflow-types.d.ts +171 -0
  215. package/dist/workflow-types.d.ts.map +1 -0
  216. package/dist/workflow-types.js +2 -0
  217. package/dist/workflow-types.js.map +1 -0
  218. package/dist/workflow.d.ts +19 -0
  219. package/dist/workflow.d.ts.map +1 -0
  220. package/dist/workflow.js +1053 -0
  221. package/dist/workflow.js.map +1 -0
  222. package/examples/a2a-remote.ts +85 -0
  223. package/examples/a2a-server.ts +100 -0
  224. package/examples/background.ts +18 -4
  225. package/examples/code-mode.ts +76 -0
  226. package/examples/conversation.ts +57 -0
  227. package/examples/evals.ts +79 -0
  228. package/examples/guardrails.ts +56 -0
  229. package/examples/handoff.ts +79 -0
  230. package/examples/memory.ts +44 -0
  231. package/examples/otel.ts +99 -0
  232. package/examples/steering.ts +69 -0
  233. package/examples/structured-handoff.ts +92 -0
  234. package/examples/subagents.ts +127 -0
  235. package/examples/workflow.ts +74 -0
  236. package/package.json +58 -6
  237. package/src/a2a/auth.ts +62 -0
  238. package/src/a2a/client.ts +733 -0
  239. package/src/a2a/index.ts +74 -0
  240. package/src/a2a/memory-runs.ts +448 -0
  241. package/src/a2a/policy.ts +148 -0
  242. package/src/a2a/push.ts +251 -0
  243. package/src/a2a/remote.ts +1652 -0
  244. package/src/a2a/server.ts +1390 -0
  245. package/src/a2a/signing.ts +348 -0
  246. package/src/a2a/tasks.ts +260 -0
  247. package/src/a2a/wire.ts +1443 -0
  248. package/src/background-types.ts +86 -0
  249. package/src/child.ts +181 -0
  250. package/src/code-driver.ts +48 -0
  251. package/src/code-mode.ts +12 -0
  252. package/src/code-script.ts +149 -0
  253. package/src/code.ts +424 -0
  254. package/src/compaction.ts +212 -0
  255. package/src/delegation.ts +444 -155
  256. package/src/evals/driver.ts +222 -0
  257. package/src/evals/journal.ts +605 -0
  258. package/src/evals/judge.ts +188 -0
  259. package/src/evals/report.ts +295 -0
  260. package/src/evals/runner.ts +826 -0
  261. package/src/evals/scorers.ts +339 -0
  262. package/src/evals/simulation.ts +46 -0
  263. package/src/evals/testing.ts +126 -0
  264. package/src/evals/trajectory.ts +223 -0
  265. package/src/evals/types.ts +463 -0
  266. package/src/evals.ts +72 -0
  267. package/src/extensions.ts +247 -0
  268. package/src/handoff.ts +214 -0
  269. package/src/index.ts +51 -0
  270. package/src/input.ts +319 -0
  271. package/src/mcp.ts +690 -0
  272. package/src/memory-store.ts +366 -0
  273. package/src/memory.ts +893 -0
  274. package/src/otel.ts +568 -0
  275. package/src/progress.ts +214 -0
  276. package/src/quickjs.ts +524 -0
  277. package/src/recovery.ts +90 -0
  278. package/src/request.ts +513 -0
  279. package/src/run.ts +2678 -313
  280. package/src/runs.ts +464 -133
  281. package/src/schema-to-ts.ts +194 -0
  282. package/src/session.ts +178 -0
  283. package/src/snapshot.ts +1595 -124
  284. package/src/steering.ts +329 -0
  285. package/src/subagents.ts +1084 -0
  286. package/src/tool-retry.ts +86 -0
  287. package/src/tree.ts +223 -27
  288. package/src/types.ts +711 -52
  289. package/src/workflow-snapshot.ts +366 -0
  290. package/src/workflow-types.ts +213 -0
  291. package/src/workflow.ts +1316 -0
package/dist/snapshot.js CHANGED
@@ -1,4 +1,15 @@
1
- import { parseToolArgs } from "@providerkit/core";
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";
2
13
  export function isRecord(value) {
3
14
  return typeof value === "object" && value !== null && !Array.isArray(value);
4
15
  }
@@ -70,9 +81,10 @@ export function readLimits(value = {}) {
70
81
  toolCalls: value.toolCalls ?? 32,
71
82
  elapsedMs: value.elapsedMs ?? 300_000,
72
83
  parallelTools: value.parallelTools ?? 3,
84
+ inlineBytes: value.inlineBytes ?? 5_000_000,
73
85
  };
74
86
  if (!isLimits(limits)) {
75
- throw new TypeError("Agent limits must be positive finite integers; elapsedMs must fit a timer.");
87
+ throw new TypeError("Agent limits must be positive finite integers (inlineBytes may be 0); elapsedMs must fit a timer.");
76
88
  }
77
89
  return limits;
78
90
  }
@@ -82,7 +94,148 @@ function isLimits(value) {
82
94
  positive(value.toolCalls) &&
83
95
  positive(value.elapsedMs) &&
84
96
  value.elapsedMs <= 2_147_483_647 &&
85
- positive(value.parallelTools));
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");
86
239
  }
87
240
  export function readTreeLimits(value = {}) {
88
241
  if (!isRecord(value))
@@ -113,26 +266,225 @@ function isPath(value) {
113
266
  return (Array.isArray(value) &&
114
267
  value.every((step) => isRecord(step) && [step.operationId, step.key, step.runId].every(isId)));
115
268
  }
116
- export function checkOptions(value) {
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") {
117
441
  if (!isRecord(value) ||
118
442
  !optional(value.runId, isId) ||
119
443
  !optional(value.signal, (signal) => signal instanceof AbortSignal) ||
120
444
  !optional(value.context, isRecord) ||
121
445
  !optional(value.onEvent, (fn) => typeof fn === "function") ||
122
- !optional(value.approvalPath, isPath)) {
446
+ !optional(value.onLifecycle, (fn) => typeof fn === "function") ||
447
+ !optional(value.answers, isRecord)) {
123
448
  throw new TypeError("Invalid run options.");
124
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.");
125
466
  if (value.host !== undefined) {
126
467
  if (!isRecord(value.host))
127
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.");
128
474
  for (const key of [
129
475
  "checkpoint",
130
476
  "authorizeResume",
131
- "approvalContext",
132
- "resolveApproval",
477
+ "prepareRequest",
478
+ "resolveRequest",
479
+ "needsApproval",
480
+ "answerNow",
481
+ "beforeStep",
482
+ "reconcileStep",
133
483
  "beforeTool",
484
+ "reconcileToolRetry",
134
485
  "canRunConcurrently",
135
486
  "child",
487
+ "loadMedia",
136
488
  ]) {
137
489
  if (!optional(value.host[key], (fn) => typeof fn === "function")) {
138
490
  throw new TypeError(`host.${key} must be a function.`);
@@ -148,14 +500,19 @@ export function isScope(value) {
148
500
  isId(value.resource.version) &&
149
501
  positive(value.expiresAt));
150
502
  }
151
- export function completeArguments(raw) {
503
+ /** Code and guest inputs are exact JSON, not prose whose escapes may be repaired. */
504
+ export function jsonArguments(raw) {
152
505
  try {
153
- return isRecord(JSON.parse(raw));
506
+ const value = JSON.parse(raw);
507
+ return isRecord(value) ? value : undefined;
154
508
  }
155
509
  catch {
156
- return false;
510
+ return undefined;
157
511
  }
158
512
  }
513
+ export function completeArguments(raw) {
514
+ return jsonArguments(raw) !== undefined;
515
+ }
159
516
  function isCall(value) {
160
517
  return (isRecord(value) &&
161
518
  isId(value.id) &&
@@ -167,10 +524,51 @@ function isRequest(value) {
167
524
  return (isRecord(value) &&
168
525
  [value.agentId, value.version, value.runId, value.attemptId, value.operationId].every(isId) &&
169
526
  isCall(value.call) &&
527
+ optional(value.subagent, isId) &&
528
+ optional(value.parentOperationId, isId) &&
170
529
  isRecord(value.arguments));
171
530
  }
172
- function isApproval(value) {
173
- return isRecord(value) && isRequest(value.request) && isScope(value.scope);
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;
174
572
  }
175
573
  export function isUsage(value) {
176
574
  return (isRecord(value) &&
@@ -180,15 +578,9 @@ export function isUsage(value) {
180
578
  [value.cacheWriteTokens, value.reasoningTokens, value.reportedCostUsd].every((v) => optional(v, finite)));
181
579
  }
182
580
  function isTurn(value) {
183
- if (!isRecord(value) || !isUsage(value.usage) || !isRecord(value.message))
581
+ if (!isRecord(value) || !isUsage(value.usage))
184
582
  return false;
185
- const message = value.message;
186
- return (message.role === "assistant" &&
187
- typeof message.content === "string" &&
188
- optional(message.reasoning, (v) => typeof v === "string") &&
189
- optional(message.reasoningDetails, Array.isArray) &&
190
- optional(message.reasoningItems, (v) => isRecord(v) && typeof v.provider === "string" && Array.isArray(v.items)) &&
191
- optional(message.toolCalls, (v) => Array.isArray(v) && v.every(isCall)) &&
583
+ return (isAssistant(value.message) &&
192
584
  [null, "stop", "length", "tool_calls", "content_filter"].some((v) => v === value.finishReason) &&
193
585
  optional(value.source, (v) => isRecord(v) && typeof v.provider === "string" && typeof v.model === "string"));
194
586
  }
@@ -204,21 +596,92 @@ function isToolResult(value) {
204
596
  return (isRecord(value) &&
205
597
  typeof value.content === "string" &&
206
598
  (value.ok === true
207
- ? value.kind === undefined
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))
208
603
  : value.ok === false &&
209
- ["invalid_input", "timeout", "aborted", "failed", "denied", "unknown_tool"].some((kind) => kind === value.kind)));
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))));
210
652
  }
211
653
  function isToolExecution(value) {
212
- if (!isRecord(value) || !isId(value.id))
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)))
213
663
  return false;
214
- return (value.status === "pending" ||
215
- (isId(value.attemptId) &&
216
- (value.status === "running" ||
217
- value.status === "delegating" ||
218
- (value.status === "completed" && isToolResult(value.result)))));
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))));
219
675
  }
220
676
  function isModel(value) {
221
- if (!isRecord(value) || !isId(value.id) || !isId(value.attemptId) || !isUsage(value.usage))
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)))
222
685
  return false;
223
686
  return (value.status === "running" ||
224
687
  (value.status === "completed" &&
@@ -226,7 +689,17 @@ function isModel(value) {
226
689
  Array.isArray(value.tools) &&
227
690
  value.tools.every(isToolExecution)));
228
691
  }
229
- function isState(value) {
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) {
230
703
  if (!isRecord(value))
231
704
  return false;
232
705
  switch (value.status) {
@@ -236,7 +709,7 @@ function isState(value) {
236
709
  case "completed":
237
710
  return serializable(value.candidate);
238
711
  case "suspended":
239
- return isApproval(value.approval) && isPath(value.path);
712
+ return Object.keys(value).length === 1;
240
713
  case "limited":
241
714
  return [
242
715
  "turns",
@@ -246,13 +719,11 @@ function isState(value) {
246
719
  "maxChildren",
247
720
  "maxDepth",
248
721
  "modelCalls",
722
+ "steps",
249
723
  "treeElapsedMs",
250
724
  ].some((v) => v === value.limit);
251
725
  case "failed":
252
- return (isRecord(value.error) &&
253
- isId(value.error.code) &&
254
- isId(value.error.message) &&
255
- optional(value.error.operationId, isId));
726
+ return isFailure(value.error);
256
727
  default:
257
728
  return false;
258
729
  }
@@ -260,17 +731,49 @@ function isState(value) {
260
731
  function isDelegationJournal(value) {
261
732
  return (isRecord(value) &&
262
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")) &&
263
741
  Array.isArray(value.children) &&
264
742
  value.children.every((child) => isRecord(child) &&
265
743
  isId(child.key) &&
266
744
  optional(child.reference, isId) &&
267
- isSnapshot(child.snapshot)));
745
+ isTreeNode(child.snapshot)));
268
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. */
269
758
  function isSnapshot(value) {
270
759
  return (isRecord(value) &&
271
- value.format === 2 &&
272
- [value.agentId, value.version, value.runId, value.attemptId, value.input].every(isId) &&
760
+ value.format === 3 &&
761
+ value.kind === "agent" &&
762
+ [value.agentId, value.version, value.runId, value.attemptId].every(isId) &&
273
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) &&
274
777
  isLimits(value.limits) &&
275
778
  Array.isArray(value.models) &&
276
779
  value.models.every(isModel) &&
@@ -280,8 +783,31 @@ function isSnapshot(value) {
280
783
  isId(value.tree.runId) &&
281
784
  positive(value.tree.startedAt) &&
282
785
  isTreeLimits(value.tree.limits) &&
786
+ optional(value.tree.memory, isMemoryScopes) &&
283
787
  isState(value.state));
284
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
+ }
285
811
  export function modelId(runId, index) {
286
812
  return `${runId}/model/${index + 1}`;
287
813
  }
@@ -295,12 +821,72 @@ export function childRunId(operationId, key) {
295
821
  export function checkTree(root) {
296
822
  let children = 0;
297
823
  let models = 0;
298
- function visit(node, depth) {
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
+ }
299
885
  if (!equalData(node.tree, root.tree) || node.startedAt < root.tree.startedAt)
300
886
  throw new TypeError("The child belongs to a different tree or deadline.");
301
887
  if (depth > root.tree.limits.maxDepth)
302
888
  throw new TypeError("The tree exceeds its depth limit.");
303
- models += node.models.length;
889
+ models += allModels(node).reduce((total, model) => total + 1 + model.interrupted.length, 0);
304
890
  if (new Set(node.delegations.map((journal) => journal.operationId)).size !==
305
891
  node.delegations.length)
306
892
  throw new TypeError("Duplicate delegation journal.");
@@ -310,6 +896,25 @@ export function checkTree(root) {
310
896
  .find((tool) => tool.id === journal.operationId);
311
897
  if (!tool || (tool.status !== "delegating" && tool.status !== "completed"))
312
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
+ }
313
918
  if (new Set(journal.children.map((child) => child.key)).size !== journal.children.length)
314
919
  throw new TypeError("Duplicate child key.");
315
920
  for (const child of journal.children) {
@@ -320,10 +925,21 @@ export function checkTree(root) {
320
925
  (child.snapshot.state.status === "running" || child.snapshot.state.status === "suspended"))
321
926
  throw new TypeError("A completed delegation cannot contain unfinished children.");
322
927
  children++;
323
- visit(child.snapshot, depth + 1);
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);
324
932
  }
325
933
  }
326
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.");
327
943
  if (model.status === "completed" &&
328
944
  model.tools.some((tool) => tool.status === "delegating" &&
329
945
  !node.delegations.some((journal) => journal.operationId === tool.id)))
@@ -332,19 +948,96 @@ export function checkTree(root) {
332
948
  }
333
949
  if (root.runId === root.tree.runId && root.startedAt !== root.tree.startedAt)
334
950
  throw new TypeError("The root start time does not match its tree.");
335
- visit(root, 0);
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.");
336
954
  if (children > root.tree.limits.maxChildren || models > root.tree.limits.modelCalls)
337
955
  throw new TypeError("The snapshot exceeds its tree limits.");
338
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
+ }
339
973
  /** A host cache may fill a missing receipt, never erase or replace a known effect. */
340
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.");
341
999
  if (previous.runId !== next.runId ||
342
- previous.input !== next.input ||
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) ||
343
1007
  previous.startedAt !== next.startedAt ||
344
1008
  previous.agentId !== next.agentId ||
345
1009
  previous.version !== next.version ||
346
1010
  !equalData(previous.tree, next.tree))
347
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.");
348
1041
  if (previous.models.length > next.models.length)
349
1042
  throw new TypeError("The child host dropped saved model receipts.");
350
1043
  if (previous.state.status !== "running" &&
@@ -353,27 +1046,90 @@ export function checkChildProgress(previous, next) {
353
1046
  throw new TypeError("The child host replaced a settled outcome.");
354
1047
  for (const [index, model] of previous.models.entries()) {
355
1048
  const saved = next.models[index];
356
- if (!saved || saved.id !== model.id || saved.attemptId !== model.attemptId)
1049
+ if (!saved || saved.id !== model.id)
357
1050
  throw new TypeError("The child host changed a model operation.");
1051
+ checkAttemptProgress(model, saved);
358
1052
  if (model.status !== "completed")
359
1053
  continue;
360
- if (saved.status !== "completed" || !equalData(model.turn, saved.turn))
1054
+ if (saved.status !== "completed" ||
1055
+ saved.attemptId !== model.attemptId ||
1056
+ saved.billing !== model.billing ||
1057
+ !equalData(model.turn, saved.turn))
361
1058
  throw new TypeError("The child host replaced a completed model receipt.");
362
1059
  for (const [position, tool] of model.tools.entries()) {
363
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
+ }
364
1069
  if (!restored ||
365
- (tool.status === "completed" && !equalData(tool, restored)) ||
366
- (tool.status === "running" &&
367
- (restored.status === "pending" ||
368
- restored.status === "delegating" ||
369
- restored.attemptId !== tool.attemptId)))
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"))
370
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);
371
1121
  }
372
1122
  }
373
1123
  for (const journal of previous.delegations) {
374
1124
  const saved = next.delegations.find((entry) => entry.operationId === journal.operationId);
375
1125
  if (!saved || saved.children.length < journal.children.length)
376
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.");
377
1133
  for (const [index, child] of journal.children.entries()) {
378
1134
  const restored = saved.children[index];
379
1135
  if (!restored || restored.key !== child.key)
@@ -382,10 +1138,252 @@ export function checkChildProgress(previous, next) {
382
1138
  }
383
1139
  }
384
1140
  }
385
- /** Validate the journal as well as its fields, so a cursor cannot skip unrecorded work. */
386
- export function readSnapshot(raw, agentId, version, limits, resultTool) {
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) {
387
1381
  if (!serializable(raw) || !isSnapshot(raw))
388
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
+ }
389
1387
  if (raw.agentId !== agentId || raw.version !== version)
390
1388
  throw new TypeError("The snapshot belongs to a different agent definition or version.");
391
1389
  if (!equalData(raw.limits, limits))
@@ -394,7 +1392,19 @@ export function readSnapshot(raw, agentId, version, limits, resultTool) {
394
1392
  for (const [index, model] of raw.models.entries()) {
395
1393
  if (model.id !== modelId(raw.runId, index))
396
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.");
397
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.");
398
1408
  if (model.status === "running") {
399
1409
  if (!last)
400
1410
  throw new TypeError("A model operation has an unknown outcome before later work.");
@@ -410,7 +1420,11 @@ export function readSnapshot(raw, agentId, version, limits, resultTool) {
410
1420
  for (const [position, tool] of model.tools.entries()) {
411
1421
  if (tool.id !== toolId(model.id, position) ||
412
1422
  (!last && tool.status !== "completed") ||
413
- (pending && tool.status !== "pending")) {
1423
+ (pending &&
1424
+ tool.status !== "pending" &&
1425
+ !tool.asks?.length &&
1426
+ !tool.interrupted.length &&
1427
+ !tool.retries.length)) {
414
1428
  throw new TypeError("Invalid tool operation position.");
415
1429
  }
416
1430
  const call = tools[position];
@@ -423,23 +1437,125 @@ export function readSnapshot(raw, agentId, version, limits, resultTool) {
423
1437
  model.turn.finishReason !== "tool_calls") {
424
1438
  throw new TypeError("An unfinished model turn cannot have executed tools.");
425
1439
  }
426
- pending ||= tool.status === "pending";
427
- if (tool.status !== "pending")
428
- calls++;
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);
429
1531
  }
430
1532
  if (!last &&
431
1533
  (tools.length === 0 ||
432
1534
  model.turn.finishReason === null ||
433
1535
  model.turn.finishReason === "length" ||
434
1536
  model.turn.finishReason === "content_filter" ||
435
- (tools.length === 1 &&
436
- tools[0]?.name === resultTool &&
437
- model.tools[0]?.status === "completed" &&
438
- model.tools[0].result.ok))) {
1537
+ finalToolResult(model, raw.definition.stopAtTools, resultTool))) {
439
1538
  throw new TypeError("A finished model turn cannot have later work.");
440
1539
  }
441
1540
  }
442
- if (raw.models.length > limits.turns || calls > limits.toolCalls)
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)
443
1559
  throw new TypeError("The snapshot exceeds this agent's limits.");
444
1560
  const last = raw.models.at(-1);
445
1561
  if (raw.state.status === "completed") {
@@ -451,60 +1567,41 @@ export function readSnapshot(raw, agentId, version, limits, resultTool) {
451
1567
  throw new TypeError("A completed run must have a completed final turn.");
452
1568
  }
453
1569
  const tools = last.turn.message.toolCalls ?? [];
454
- let candidate;
455
- if (resultTool) {
456
- if (tools.length === 1 &&
457
- tools[0]?.name === resultTool &&
458
- last.tools[0]?.status === "completed" &&
459
- last.tools[0].result.ok) {
460
- candidate = parseToolArgs(tools[0].arguments);
461
- }
462
- }
463
- else if (tools.length === 0 && last.turn.message.content.trim()) {
464
- candidate = last.turn.message.content;
465
- }
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;
466
1577
  if (candidate === undefined || !equalData(candidate, raw.state.candidate)) {
467
1578
  throw new TypeError("The completed result does not match its recorded turn.");
468
1579
  }
469
1580
  }
470
- checkTree(raw);
471
- if (raw.state.status === "suspended") {
472
- let leaf = raw;
473
- for (const [index, step] of raw.state.path.entries()) {
474
- const journal = leaf.delegations.find((journal) => journal.operationId === step.operationId);
475
- const child = journal?.children.find((child) => child.key === step.key);
476
- if (!child ||
477
- child.snapshot.runId !== step.runId ||
478
- child.snapshot.state.status !== "suspended" ||
479
- !equalData(child.snapshot.state.path, raw.state.path.slice(index + 1)) ||
480
- !equalData(child.snapshot.state.approval, raw.state.approval))
481
- throw new TypeError("The approval path does not match a suspended child.");
482
- leaf = child.snapshot;
483
- }
484
- if (leaf.state.status !== "suspended" ||
485
- leaf.state.path.length !== 0 ||
486
- !equalData(leaf.state.approval, raw.state.approval))
487
- throw new TypeError("The approval path does not match the leaf decision.");
488
- const last = leaf.models.at(-1);
489
- if (last?.status !== "completed")
490
- throw new TypeError("The approval does not match the pending tool call.");
491
- const { request } = raw.state.approval;
492
- const position = last.tools.findIndex((tool) => tool.status !== "completed");
493
- const call = last.turn.message.toolCalls?.[position];
494
- const tool = last.tools[position];
495
- if (!call ||
496
- !completeArguments(call.arguments) ||
497
- (last.turn.finishReason !== "stop" && last.turn.finishReason !== "tool_calls") ||
498
- tool?.status !== "pending" ||
499
- request.runId !== leaf.runId ||
500
- request.agentId !== leaf.agentId ||
501
- request.version !== leaf.version ||
502
- request.operationId !== tool.id ||
503
- !equalData(request.call, call) ||
504
- !equalData(request.arguments, parseToolArgs(call.arguments))) {
505
- throw new TypeError("The approval does not match the pending tool call.");
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.");
506
1597
  }
507
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.");
508
1605
  return copyData(raw);
509
1606
  }
510
1607
  //# sourceMappingURL=snapshot.js.map