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