@providerkit/agents 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +272 -2
- package/dist/delegation.d.ts +66 -0
- package/dist/delegation.d.ts.map +1 -0
- package/dist/delegation.js +267 -0
- package/dist/delegation.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/run.d.ts +8 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +636 -0
- package/dist/run.js.map +1 -0
- package/dist/runs.d.ts +67 -0
- package/dist/runs.d.ts.map +1 -0
- package/dist/runs.js +256 -0
- package/dist/runs.js.map +1 -0
- package/dist/snapshot.d.ts +26 -0
- package/dist/snapshot.d.ts.map +1 -0
- package/dist/snapshot.js +510 -0
- package/dist/snapshot.js.map +1 -0
- package/dist/tree.d.ts +42 -0
- package/dist/tree.d.ts.map +1 -0
- package/dist/tree.js +151 -0
- package/dist/tree.js.map +1 -0
- package/dist/types.d.ts +292 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/examples/background.ts +45 -0
- package/examples/basic.ts +44 -0
- package/examples/specialists.ts +99 -0
- package/package.json +62 -4
- package/src/delegation.ts +405 -0
- package/src/index.ts +11 -0
- package/src/run.ts +834 -0
- package/src/runs.ts +365 -0
- package/src/snapshot.ts +628 -0
- package/src/tree.ts +170 -0
- package/src/types.ts +285 -0
package/src/snapshot.ts
ADDED
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
import { parseToolArgs, type TokenUsage, type ToolCall, type Turn } from "@providerkit/core";
|
|
2
|
+
import type {
|
|
3
|
+
ApprovalScope,
|
|
4
|
+
ChildPathStep,
|
|
5
|
+
DelegationExecution,
|
|
6
|
+
ModelExecution,
|
|
7
|
+
PendingApproval,
|
|
8
|
+
RunLimits,
|
|
9
|
+
RunOptions,
|
|
10
|
+
RunSnapshot,
|
|
11
|
+
RunState,
|
|
12
|
+
ToolExecution,
|
|
13
|
+
ToolRequest,
|
|
14
|
+
ToolResult,
|
|
15
|
+
TreeLimits,
|
|
16
|
+
} from "./types.ts";
|
|
17
|
+
|
|
18
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
19
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isId(value: unknown): value is string {
|
|
23
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function finite(value: unknown): value is number {
|
|
27
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function positive(value: unknown): value is number {
|
|
31
|
+
return finite(value) && Number.isSafeInteger(value) && value > 0;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function optional(value: unknown, guard: (value: unknown) => boolean): boolean {
|
|
35
|
+
return value === undefined || guard(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** JSON cannot preserve cycles, class instances, non-finite numbers or functions. */
|
|
39
|
+
function serializable(value: unknown, parents = new Set<object>()): boolean {
|
|
40
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
41
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
42
|
+
if (typeof value !== "object" || parents.has(value)) return false;
|
|
43
|
+
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) return false;
|
|
44
|
+
parents.add(value);
|
|
45
|
+
const valid = Array.isArray(value)
|
|
46
|
+
? value.every((item) => serializable(item, parents))
|
|
47
|
+
: Object.values(value).every((item) => item === undefined || serializable(item, parents));
|
|
48
|
+
parents.delete(value);
|
|
49
|
+
return valid;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function copyData<T>(value: T): T {
|
|
53
|
+
if (value !== undefined && !serializable(value)) {
|
|
54
|
+
throw new TypeError("Run data must use plain JSON values so a checkpoint can save it.");
|
|
55
|
+
}
|
|
56
|
+
return structuredClone(value);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A callback cannot edit the live journal, even by retaining a nested reference. */
|
|
60
|
+
export function immutableCopy<T>(value: T): T {
|
|
61
|
+
const copy = copyData(value);
|
|
62
|
+
function freeze(item: unknown): void {
|
|
63
|
+
if (typeof item !== "object" || item === null) return;
|
|
64
|
+
for (const child of Object.values(item)) freeze(child);
|
|
65
|
+
Object.freeze(item);
|
|
66
|
+
}
|
|
67
|
+
freeze(copy);
|
|
68
|
+
return copy;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Object key order can change when a host stores JSON; array order cannot. */
|
|
72
|
+
export function equalData(left: unknown, right: unknown): boolean {
|
|
73
|
+
if (left === right) return true;
|
|
74
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
75
|
+
return (
|
|
76
|
+
left.length === right.length && left.every((item, index) => equalData(item, right[index]))
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
if (!isRecord(left) || !isRecord(right)) return false;
|
|
80
|
+
const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
|
|
81
|
+
return [...keys].every((key) => equalData(left[key], right[key]));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function readLimits(value: unknown = {}): RunLimits {
|
|
85
|
+
if (!isRecord(value)) throw new TypeError("Agent limits must be an object.");
|
|
86
|
+
const limits = {
|
|
87
|
+
turns: value.turns ?? 12,
|
|
88
|
+
toolCalls: value.toolCalls ?? 32,
|
|
89
|
+
elapsedMs: value.elapsedMs ?? 300_000,
|
|
90
|
+
parallelTools: value.parallelTools ?? 3,
|
|
91
|
+
};
|
|
92
|
+
if (!isLimits(limits)) {
|
|
93
|
+
throw new TypeError(
|
|
94
|
+
"Agent limits must be positive finite integers; elapsedMs must fit a timer.",
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
return limits;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function isLimits(value: unknown): value is RunLimits {
|
|
101
|
+
return (
|
|
102
|
+
isRecord(value) &&
|
|
103
|
+
positive(value.turns) &&
|
|
104
|
+
positive(value.toolCalls) &&
|
|
105
|
+
positive(value.elapsedMs) &&
|
|
106
|
+
value.elapsedMs <= 2_147_483_647 &&
|
|
107
|
+
positive(value.parallelTools)
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function readTreeLimits(value: unknown = {}): TreeLimits {
|
|
112
|
+
if (!isRecord(value)) throw new TypeError("Tree limits must be an object.");
|
|
113
|
+
const limits = {
|
|
114
|
+
maxParallel: value.maxParallel ?? 4,
|
|
115
|
+
maxChildren: value.maxChildren ?? 32,
|
|
116
|
+
maxDepth: value.maxDepth ?? 4,
|
|
117
|
+
modelCalls: value.modelCalls ?? 128,
|
|
118
|
+
elapsedMs: value.elapsedMs ?? 300_000,
|
|
119
|
+
};
|
|
120
|
+
if (!isTreeLimits(limits))
|
|
121
|
+
throw new TypeError("Tree limits must be finite integers; elapsedMs must fit a timer.");
|
|
122
|
+
return limits;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function isTreeLimits(value: unknown): value is TreeLimits {
|
|
126
|
+
return (
|
|
127
|
+
isRecord(value) &&
|
|
128
|
+
positive(value.maxParallel) &&
|
|
129
|
+
finite(value.maxChildren) &&
|
|
130
|
+
Number.isSafeInteger(value.maxChildren) &&
|
|
131
|
+
finite(value.maxDepth) &&
|
|
132
|
+
Number.isSafeInteger(value.maxDepth) &&
|
|
133
|
+
positive(value.modelCalls) &&
|
|
134
|
+
positive(value.elapsedMs) &&
|
|
135
|
+
value.elapsedMs <= 2_147_483_647
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isPath(value: unknown): value is ChildPathStep[] {
|
|
140
|
+
return (
|
|
141
|
+
Array.isArray(value) &&
|
|
142
|
+
value.every((step) => isRecord(step) && [step.operationId, step.key, step.runId].every(isId))
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function checkOptions(value: unknown): asserts value is RunOptions {
|
|
147
|
+
if (
|
|
148
|
+
!isRecord(value) ||
|
|
149
|
+
!optional(value.runId, isId) ||
|
|
150
|
+
!optional(value.signal, (signal) => signal instanceof AbortSignal) ||
|
|
151
|
+
!optional(value.context, isRecord) ||
|
|
152
|
+
!optional(value.onEvent, (fn) => typeof fn === "function") ||
|
|
153
|
+
!optional(value.approvalPath, isPath)
|
|
154
|
+
) {
|
|
155
|
+
throw new TypeError("Invalid run options.");
|
|
156
|
+
}
|
|
157
|
+
if (value.host !== undefined) {
|
|
158
|
+
if (!isRecord(value.host)) throw new TypeError("The run host must be an object.");
|
|
159
|
+
for (const key of [
|
|
160
|
+
"checkpoint",
|
|
161
|
+
"authorizeResume",
|
|
162
|
+
"approvalContext",
|
|
163
|
+
"resolveApproval",
|
|
164
|
+
"beforeTool",
|
|
165
|
+
"canRunConcurrently",
|
|
166
|
+
"child",
|
|
167
|
+
]) {
|
|
168
|
+
if (!optional(value.host[key], (fn) => typeof fn === "function")) {
|
|
169
|
+
throw new TypeError(`host.${key} must be a function.`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function isScope(value: unknown): value is ApprovalScope {
|
|
176
|
+
return (
|
|
177
|
+
isRecord(value) &&
|
|
178
|
+
isId(value.actorId) &&
|
|
179
|
+
isRecord(value.resource) &&
|
|
180
|
+
isId(value.resource.id) &&
|
|
181
|
+
isId(value.resource.version) &&
|
|
182
|
+
positive(value.expiresAt)
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function completeArguments(raw: string): boolean {
|
|
187
|
+
try {
|
|
188
|
+
return isRecord(JSON.parse(raw));
|
|
189
|
+
} catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function isCall(value: unknown): value is ToolCall {
|
|
195
|
+
return (
|
|
196
|
+
isRecord(value) &&
|
|
197
|
+
isId(value.id) &&
|
|
198
|
+
isId(value.name) &&
|
|
199
|
+
typeof value.arguments === "string" &&
|
|
200
|
+
optional(value.thoughtSignature, (v) => typeof v === "string")
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function isRequest(value: unknown): value is ToolRequest {
|
|
205
|
+
return (
|
|
206
|
+
isRecord(value) &&
|
|
207
|
+
[value.agentId, value.version, value.runId, value.attemptId, value.operationId].every(isId) &&
|
|
208
|
+
isCall(value.call) &&
|
|
209
|
+
isRecord(value.arguments)
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function isApproval(value: unknown): value is PendingApproval {
|
|
214
|
+
return isRecord(value) && isRequest(value.request) && isScope(value.scope);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function isUsage(value: unknown): value is TokenUsage {
|
|
218
|
+
return (
|
|
219
|
+
isRecord(value) &&
|
|
220
|
+
finite(value.inputTokens) &&
|
|
221
|
+
finite(value.outputTokens) &&
|
|
222
|
+
finite(value.cachedInputTokens) &&
|
|
223
|
+
[value.cacheWriteTokens, value.reasoningTokens, value.reportedCostUsd].every((v) =>
|
|
224
|
+
optional(v, finite),
|
|
225
|
+
)
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function isTurn(value: unknown): value is Turn {
|
|
230
|
+
if (!isRecord(value) || !isUsage(value.usage) || !isRecord(value.message)) return false;
|
|
231
|
+
const message = value.message;
|
|
232
|
+
return (
|
|
233
|
+
message.role === "assistant" &&
|
|
234
|
+
typeof message.content === "string" &&
|
|
235
|
+
optional(message.reasoning, (v) => typeof v === "string") &&
|
|
236
|
+
optional(message.reasoningDetails, Array.isArray) &&
|
|
237
|
+
optional(
|
|
238
|
+
message.reasoningItems,
|
|
239
|
+
(v) => isRecord(v) && typeof v.provider === "string" && Array.isArray(v.items),
|
|
240
|
+
) &&
|
|
241
|
+
optional(message.toolCalls, (v) => Array.isArray(v) && v.every(isCall)) &&
|
|
242
|
+
[null, "stop", "length", "tool_calls", "content_filter"].some(
|
|
243
|
+
(v) => v === value.finishReason,
|
|
244
|
+
) &&
|
|
245
|
+
optional(
|
|
246
|
+
value.source,
|
|
247
|
+
(v) => isRecord(v) && typeof v.provider === "string" && typeof v.model === "string",
|
|
248
|
+
)
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function readTurn(value: unknown): Turn {
|
|
253
|
+
if (!serializable(value) || !isTurn(value))
|
|
254
|
+
throw new TypeError("The provider returned an invalid or unsavable turn.");
|
|
255
|
+
const ids = value.message.toolCalls?.map((call) => call.id) ?? [];
|
|
256
|
+
if (new Set(ids).size !== ids.length)
|
|
257
|
+
throw new TypeError("The provider reused a tool-call ID within one turn.");
|
|
258
|
+
return copyData(value);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function isToolResult(value: unknown): value is ToolResult {
|
|
262
|
+
return (
|
|
263
|
+
isRecord(value) &&
|
|
264
|
+
typeof value.content === "string" &&
|
|
265
|
+
(value.ok === true
|
|
266
|
+
? value.kind === undefined
|
|
267
|
+
: value.ok === false &&
|
|
268
|
+
["invalid_input", "timeout", "aborted", "failed", "denied", "unknown_tool"].some(
|
|
269
|
+
(kind) => kind === value.kind,
|
|
270
|
+
))
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function isToolExecution(value: unknown): value is ToolExecution {
|
|
275
|
+
if (!isRecord(value) || !isId(value.id)) return false;
|
|
276
|
+
return (
|
|
277
|
+
value.status === "pending" ||
|
|
278
|
+
(isId(value.attemptId) &&
|
|
279
|
+
(value.status === "running" ||
|
|
280
|
+
value.status === "delegating" ||
|
|
281
|
+
(value.status === "completed" && isToolResult(value.result))))
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function isModel(value: unknown): value is ModelExecution {
|
|
286
|
+
if (!isRecord(value) || !isId(value.id) || !isId(value.attemptId) || !isUsage(value.usage))
|
|
287
|
+
return false;
|
|
288
|
+
return (
|
|
289
|
+
value.status === "running" ||
|
|
290
|
+
(value.status === "completed" &&
|
|
291
|
+
isTurn(value.turn) &&
|
|
292
|
+
Array.isArray(value.tools) &&
|
|
293
|
+
value.tools.every(isToolExecution))
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function isState(value: unknown): value is RunState {
|
|
298
|
+
if (!isRecord(value)) return false;
|
|
299
|
+
switch (value.status) {
|
|
300
|
+
case "running":
|
|
301
|
+
case "cancelled":
|
|
302
|
+
return true;
|
|
303
|
+
case "completed":
|
|
304
|
+
return serializable(value.candidate);
|
|
305
|
+
case "suspended":
|
|
306
|
+
return isApproval(value.approval) && isPath(value.path);
|
|
307
|
+
case "limited":
|
|
308
|
+
return [
|
|
309
|
+
"turns",
|
|
310
|
+
"toolCalls",
|
|
311
|
+
"elapsedMs",
|
|
312
|
+
"outputTokens",
|
|
313
|
+
"maxChildren",
|
|
314
|
+
"maxDepth",
|
|
315
|
+
"modelCalls",
|
|
316
|
+
"treeElapsedMs",
|
|
317
|
+
].some((v) => v === value.limit);
|
|
318
|
+
case "failed":
|
|
319
|
+
return (
|
|
320
|
+
isRecord(value.error) &&
|
|
321
|
+
isId(value.error.code) &&
|
|
322
|
+
isId(value.error.message) &&
|
|
323
|
+
optional(value.error.operationId, isId)
|
|
324
|
+
);
|
|
325
|
+
default:
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function isDelegationJournal(value: unknown): value is DelegationExecution {
|
|
331
|
+
return (
|
|
332
|
+
isRecord(value) &&
|
|
333
|
+
isId(value.operationId) &&
|
|
334
|
+
Array.isArray(value.children) &&
|
|
335
|
+
value.children.every(
|
|
336
|
+
(child) =>
|
|
337
|
+
isRecord(child) &&
|
|
338
|
+
isId(child.key) &&
|
|
339
|
+
optional(child.reference, isId) &&
|
|
340
|
+
isSnapshot(child.snapshot),
|
|
341
|
+
)
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function isSnapshot(value: unknown): value is RunSnapshot {
|
|
346
|
+
return (
|
|
347
|
+
isRecord(value) &&
|
|
348
|
+
value.format === 2 &&
|
|
349
|
+
[value.agentId, value.version, value.runId, value.attemptId, value.input].every(isId) &&
|
|
350
|
+
positive(value.startedAt) &&
|
|
351
|
+
isLimits(value.limits) &&
|
|
352
|
+
Array.isArray(value.models) &&
|
|
353
|
+
value.models.every(isModel) &&
|
|
354
|
+
Array.isArray(value.delegations) &&
|
|
355
|
+
value.delegations.every(isDelegationJournal) &&
|
|
356
|
+
isRecord(value.tree) &&
|
|
357
|
+
isId(value.tree.runId) &&
|
|
358
|
+
positive(value.tree.startedAt) &&
|
|
359
|
+
isTreeLimits(value.tree.limits) &&
|
|
360
|
+
isState(value.state)
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export function modelId(runId: string, index: number): string {
|
|
365
|
+
return `${runId}/model/${index + 1}`;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export function toolId(model: string, index: number): string {
|
|
369
|
+
return `${model}/tool/${index + 1}`;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export function childRunId(operationId: string, key: string): string {
|
|
373
|
+
return `${operationId}/child/${encodeURIComponent(key)}`;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Check global reservations from saved local journals, including work not yet sent. */
|
|
377
|
+
export function checkTree(root: RunSnapshot): void {
|
|
378
|
+
let children = 0;
|
|
379
|
+
let models = 0;
|
|
380
|
+
function visit(node: RunSnapshot, depth: number): void {
|
|
381
|
+
if (!equalData(node.tree, root.tree) || node.startedAt < root.tree.startedAt)
|
|
382
|
+
throw new TypeError("The child belongs to a different tree or deadline.");
|
|
383
|
+
if (depth > root.tree.limits.maxDepth) throw new TypeError("The tree exceeds its depth limit.");
|
|
384
|
+
models += node.models.length;
|
|
385
|
+
if (
|
|
386
|
+
new Set(node.delegations.map((journal) => journal.operationId)).size !==
|
|
387
|
+
node.delegations.length
|
|
388
|
+
)
|
|
389
|
+
throw new TypeError("Duplicate delegation journal.");
|
|
390
|
+
for (const journal of node.delegations) {
|
|
391
|
+
const tool = node.models
|
|
392
|
+
.flatMap((model) => (model.status === "completed" ? model.tools : []))
|
|
393
|
+
.find((tool) => tool.id === journal.operationId);
|
|
394
|
+
if (!tool || (tool.status !== "delegating" && tool.status !== "completed"))
|
|
395
|
+
throw new TypeError("The delegation journal does not match its tool call.");
|
|
396
|
+
if (new Set(journal.children.map((child) => child.key)).size !== journal.children.length)
|
|
397
|
+
throw new TypeError("Duplicate child key.");
|
|
398
|
+
for (const child of journal.children) {
|
|
399
|
+
if (
|
|
400
|
+
child.snapshot.runId !== childRunId(journal.operationId, child.key) ||
|
|
401
|
+
child.snapshot.startedAt < node.startedAt
|
|
402
|
+
)
|
|
403
|
+
throw new TypeError("Invalid child identity or start time.");
|
|
404
|
+
if (
|
|
405
|
+
(tool.status === "completed" || node.state.status === "completed") &&
|
|
406
|
+
(child.snapshot.state.status === "running" || child.snapshot.state.status === "suspended")
|
|
407
|
+
)
|
|
408
|
+
throw new TypeError("A completed delegation cannot contain unfinished children.");
|
|
409
|
+
children++;
|
|
410
|
+
visit(child.snapshot, depth + 1);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
for (const model of node.models) {
|
|
414
|
+
if (
|
|
415
|
+
model.status === "completed" &&
|
|
416
|
+
model.tools.some(
|
|
417
|
+
(tool) =>
|
|
418
|
+
tool.status === "delegating" &&
|
|
419
|
+
!node.delegations.some((journal) => journal.operationId === tool.id),
|
|
420
|
+
)
|
|
421
|
+
)
|
|
422
|
+
throw new TypeError("A delegation is missing its child journal.");
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
if (root.runId === root.tree.runId && root.startedAt !== root.tree.startedAt)
|
|
426
|
+
throw new TypeError("The root start time does not match its tree.");
|
|
427
|
+
visit(root, 0);
|
|
428
|
+
if (children > root.tree.limits.maxChildren || models > root.tree.limits.modelCalls)
|
|
429
|
+
throw new TypeError("The snapshot exceeds its tree limits.");
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** A host cache may fill a missing receipt, never erase or replace a known effect. */
|
|
433
|
+
export function checkChildProgress(previous: RunSnapshot, next: RunSnapshot): void {
|
|
434
|
+
if (
|
|
435
|
+
previous.runId !== next.runId ||
|
|
436
|
+
previous.input !== next.input ||
|
|
437
|
+
previous.startedAt !== next.startedAt ||
|
|
438
|
+
previous.agentId !== next.agentId ||
|
|
439
|
+
previous.version !== next.version ||
|
|
440
|
+
!equalData(previous.tree, next.tree)
|
|
441
|
+
)
|
|
442
|
+
throw new TypeError("The child host returned a different child.");
|
|
443
|
+
if (previous.models.length > next.models.length)
|
|
444
|
+
throw new TypeError("The child host dropped saved model receipts.");
|
|
445
|
+
if (
|
|
446
|
+
previous.state.status !== "running" &&
|
|
447
|
+
previous.state.status !== "suspended" &&
|
|
448
|
+
!equalData(previous.state, next.state)
|
|
449
|
+
)
|
|
450
|
+
throw new TypeError("The child host replaced a settled outcome.");
|
|
451
|
+
for (const [index, model] of previous.models.entries()) {
|
|
452
|
+
const saved = next.models[index];
|
|
453
|
+
if (!saved || saved.id !== model.id || saved.attemptId !== model.attemptId)
|
|
454
|
+
throw new TypeError("The child host changed a model operation.");
|
|
455
|
+
if (model.status !== "completed") continue;
|
|
456
|
+
if (saved.status !== "completed" || !equalData(model.turn, saved.turn))
|
|
457
|
+
throw new TypeError("The child host replaced a completed model receipt.");
|
|
458
|
+
for (const [position, tool] of model.tools.entries()) {
|
|
459
|
+
const restored = saved.tools[position];
|
|
460
|
+
if (
|
|
461
|
+
!restored ||
|
|
462
|
+
(tool.status === "completed" && !equalData(tool, restored)) ||
|
|
463
|
+
(tool.status === "running" &&
|
|
464
|
+
(restored.status === "pending" ||
|
|
465
|
+
restored.status === "delegating" ||
|
|
466
|
+
restored.attemptId !== tool.attemptId))
|
|
467
|
+
)
|
|
468
|
+
throw new TypeError("The child host replaced a tool receipt.");
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
for (const journal of previous.delegations) {
|
|
472
|
+
const saved = next.delegations.find((entry) => entry.operationId === journal.operationId);
|
|
473
|
+
if (!saved || saved.children.length < journal.children.length)
|
|
474
|
+
throw new TypeError("The child host dropped a delegation receipt.");
|
|
475
|
+
for (const [index, child] of journal.children.entries()) {
|
|
476
|
+
const restored = saved.children[index];
|
|
477
|
+
if (!restored || restored.key !== child.key)
|
|
478
|
+
throw new TypeError("The child host changed child admission order.");
|
|
479
|
+
checkChildProgress(child.snapshot, restored.snapshot);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Validate the journal as well as its fields, so a cursor cannot skip unrecorded work. */
|
|
485
|
+
export function readSnapshot(
|
|
486
|
+
raw: unknown,
|
|
487
|
+
agentId: string,
|
|
488
|
+
version: string,
|
|
489
|
+
limits: RunLimits,
|
|
490
|
+
resultTool?: string,
|
|
491
|
+
): RunSnapshot {
|
|
492
|
+
if (!serializable(raw) || !isSnapshot(raw)) throw new TypeError("Invalid agent snapshot.");
|
|
493
|
+
if (raw.agentId !== agentId || raw.version !== version)
|
|
494
|
+
throw new TypeError("The snapshot belongs to a different agent definition or version.");
|
|
495
|
+
if (!equalData(raw.limits, limits))
|
|
496
|
+
throw new TypeError("The snapshot limits do not match this agent version.");
|
|
497
|
+
let calls = 0;
|
|
498
|
+
for (const [index, model] of raw.models.entries()) {
|
|
499
|
+
if (model.id !== modelId(raw.runId, index))
|
|
500
|
+
throw new TypeError("Invalid model operation identity.");
|
|
501
|
+
const last = index === raw.models.length - 1;
|
|
502
|
+
if (model.status === "running") {
|
|
503
|
+
if (!last) throw new TypeError("A model operation has an unknown outcome before later work.");
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
readTurn(model.turn);
|
|
507
|
+
const tools = model.turn.message.toolCalls ?? [];
|
|
508
|
+
if (tools.length !== model.tools.length)
|
|
509
|
+
throw new TypeError("The tool journal does not match the model turn.");
|
|
510
|
+
if (!equalData(model.usage, model.turn.usage))
|
|
511
|
+
throw new TypeError("The model usage does not match its completed turn.");
|
|
512
|
+
let pending = false;
|
|
513
|
+
for (const [position, tool] of model.tools.entries()) {
|
|
514
|
+
if (
|
|
515
|
+
tool.id !== toolId(model.id, position) ||
|
|
516
|
+
(!last && tool.status !== "completed") ||
|
|
517
|
+
(pending && tool.status !== "pending")
|
|
518
|
+
) {
|
|
519
|
+
throw new TypeError("Invalid tool operation position.");
|
|
520
|
+
}
|
|
521
|
+
const call = tools[position];
|
|
522
|
+
if (
|
|
523
|
+
!call ||
|
|
524
|
+
(tool.status === "completed" && tool.result.ok && !completeArguments(call.arguments))
|
|
525
|
+
) {
|
|
526
|
+
throw new TypeError("A successful tool result must have complete arguments.");
|
|
527
|
+
}
|
|
528
|
+
if (
|
|
529
|
+
tool.status !== "pending" &&
|
|
530
|
+
model.turn.finishReason !== "stop" &&
|
|
531
|
+
model.turn.finishReason !== "tool_calls"
|
|
532
|
+
) {
|
|
533
|
+
throw new TypeError("An unfinished model turn cannot have executed tools.");
|
|
534
|
+
}
|
|
535
|
+
pending ||= tool.status === "pending";
|
|
536
|
+
if (tool.status !== "pending") calls++;
|
|
537
|
+
}
|
|
538
|
+
if (
|
|
539
|
+
!last &&
|
|
540
|
+
(tools.length === 0 ||
|
|
541
|
+
model.turn.finishReason === null ||
|
|
542
|
+
model.turn.finishReason === "length" ||
|
|
543
|
+
model.turn.finishReason === "content_filter" ||
|
|
544
|
+
(tools.length === 1 &&
|
|
545
|
+
tools[0]?.name === resultTool &&
|
|
546
|
+
model.tools[0]?.status === "completed" &&
|
|
547
|
+
model.tools[0].result.ok))
|
|
548
|
+
) {
|
|
549
|
+
throw new TypeError("A finished model turn cannot have later work.");
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (raw.models.length > limits.turns || calls > limits.toolCalls)
|
|
553
|
+
throw new TypeError("The snapshot exceeds this agent's limits.");
|
|
554
|
+
const last = raw.models.at(-1);
|
|
555
|
+
if (raw.state.status === "completed") {
|
|
556
|
+
if (
|
|
557
|
+
last?.status !== "completed" ||
|
|
558
|
+
last.tools.some((tool) => tool.status !== "completed") ||
|
|
559
|
+
last.turn.finishReason === null ||
|
|
560
|
+
last.turn.finishReason === "length" ||
|
|
561
|
+
last.turn.finishReason === "content_filter"
|
|
562
|
+
) {
|
|
563
|
+
throw new TypeError("A completed run must have a completed final turn.");
|
|
564
|
+
}
|
|
565
|
+
const tools = last.turn.message.toolCalls ?? [];
|
|
566
|
+
let candidate: unknown;
|
|
567
|
+
if (resultTool) {
|
|
568
|
+
if (
|
|
569
|
+
tools.length === 1 &&
|
|
570
|
+
tools[0]?.name === resultTool &&
|
|
571
|
+
last.tools[0]?.status === "completed" &&
|
|
572
|
+
last.tools[0].result.ok
|
|
573
|
+
) {
|
|
574
|
+
candidate = parseToolArgs(tools[0].arguments);
|
|
575
|
+
}
|
|
576
|
+
} else if (tools.length === 0 && last.turn.message.content.trim()) {
|
|
577
|
+
candidate = last.turn.message.content;
|
|
578
|
+
}
|
|
579
|
+
if (candidate === undefined || !equalData(candidate, raw.state.candidate)) {
|
|
580
|
+
throw new TypeError("The completed result does not match its recorded turn.");
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
checkTree(raw);
|
|
584
|
+
if (raw.state.status === "suspended") {
|
|
585
|
+
let leaf = raw;
|
|
586
|
+
for (const [index, step] of raw.state.path.entries()) {
|
|
587
|
+
const journal = leaf.delegations.find((journal) => journal.operationId === step.operationId);
|
|
588
|
+
const child = journal?.children.find((child) => child.key === step.key);
|
|
589
|
+
if (
|
|
590
|
+
!child ||
|
|
591
|
+
child.snapshot.runId !== step.runId ||
|
|
592
|
+
child.snapshot.state.status !== "suspended" ||
|
|
593
|
+
!equalData(child.snapshot.state.path, raw.state.path.slice(index + 1)) ||
|
|
594
|
+
!equalData(child.snapshot.state.approval, raw.state.approval)
|
|
595
|
+
)
|
|
596
|
+
throw new TypeError("The approval path does not match a suspended child.");
|
|
597
|
+
leaf = child.snapshot;
|
|
598
|
+
}
|
|
599
|
+
if (
|
|
600
|
+
leaf.state.status !== "suspended" ||
|
|
601
|
+
leaf.state.path.length !== 0 ||
|
|
602
|
+
!equalData(leaf.state.approval, raw.state.approval)
|
|
603
|
+
)
|
|
604
|
+
throw new TypeError("The approval path does not match the leaf decision.");
|
|
605
|
+
const last = leaf.models.at(-1);
|
|
606
|
+
if (last?.status !== "completed")
|
|
607
|
+
throw new TypeError("The approval does not match the pending tool call.");
|
|
608
|
+
const { request } = raw.state.approval;
|
|
609
|
+
const position = last.tools.findIndex((tool) => tool.status !== "completed");
|
|
610
|
+
const call = last.turn.message.toolCalls?.[position];
|
|
611
|
+
const tool = last.tools[position];
|
|
612
|
+
if (
|
|
613
|
+
!call ||
|
|
614
|
+
!completeArguments(call.arguments) ||
|
|
615
|
+
(last.turn.finishReason !== "stop" && last.turn.finishReason !== "tool_calls") ||
|
|
616
|
+
tool?.status !== "pending" ||
|
|
617
|
+
request.runId !== leaf.runId ||
|
|
618
|
+
request.agentId !== leaf.agentId ||
|
|
619
|
+
request.version !== leaf.version ||
|
|
620
|
+
request.operationId !== tool.id ||
|
|
621
|
+
!equalData(request.call, call) ||
|
|
622
|
+
!equalData(request.arguments, parseToolArgs(call.arguments))
|
|
623
|
+
) {
|
|
624
|
+
throw new TypeError("The approval does not match the pending tool call.");
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return copyData(raw);
|
|
628
|
+
}
|