@tangle-network/agent-runtime 0.166.0 → 0.167.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/dist/{activation-BkO0p4I1.js → activation-CIwer0zU.js} +3 -3
- package/dist/{activation-BkO0p4I1.js.map → activation-CIwer0zU.js.map} +1 -1
- package/dist/agent.js +2 -2
- package/dist/{authoring-Bt17KOML.js → authoring-CUTgAxxE.js} +2 -2
- package/dist/{authoring-Bt17KOML.js.map → authoring-CUTgAxxE.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-DC0T8l2p.js → candidate-execution-BbMbyhgC.js} +4 -4
- package/dist/{candidate-execution-DC0T8l2p.js.map → candidate-execution-BbMbyhgC.js.map} +1 -1
- package/dist/durable.js +1 -1
- package/dist/graph-ZDMygFIo.js +546 -0
- package/dist/graph-ZDMygFIo.js.map +1 -0
- package/dist/graph.d.ts +35 -54
- package/dist/graph.js +2073 -2
- package/dist/graph.js.map +1 -0
- package/dist/{improvement-cycle-BAWOyeTA.js → improvement-cycle-BAKN_f4x.js} +4 -4
- package/dist/{improvement-cycle-BAWOyeTA.js.map → improvement-cycle-BAKN_f4x.js.map} +1 -1
- package/dist/index.js +11 -11
- package/dist/intelligence.js +5 -5
- package/dist/kernel.js +6 -6
- package/dist/{knowledge-Bhhz6lvH.js → knowledge-D-7PXKUV.js} +5 -5
- package/dist/{knowledge-Bhhz6lvH.js.map → knowledge-D-7PXKUV.js.map} +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-BQnpSn0h.js → loop-runner-bin-DHxQ_VQD.js} +3 -3
- package/dist/{loop-runner-bin-BQnpSn0h.js.map → loop-runner-bin-DHxQ_VQD.js.map} +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.js +4 -4
- package/dist/{openai-tools-t6spVYKL.js → openai-tools-UyXVO0kd.js} +2 -2
- package/dist/{openai-tools-t6spVYKL.js.map → openai-tools-UyXVO0kd.js.map} +1 -1
- package/dist/{prepare-BCScSDCv.js → prepare-BAyaNoZu.js} +3 -3
- package/dist/prepare-BAyaNoZu.js.map +1 -0
- package/dist/{protected-model-port-D-5E3HBe.js → protected-model-port-T2UWrDNQ.js} +2 -2
- package/dist/{protected-model-port-D-5E3HBe.js.map → protected-model-port-T2UWrDNQ.js.map} +1 -1
- package/dist/{runtime-BJoNta1Y.js → runtime-D5l-enW9.js} +6 -6
- package/dist/{runtime-BJoNta1Y.js.map → runtime-D5l-enW9.js.map} +1 -1
- package/dist/{structural-rollout-B5E0mWCH.js → structural-rollout-C7nNNhri.js} +2 -2
- package/dist/{structural-rollout-B5E0mWCH.js.map → structural-rollout-C7nNNhri.js.map} +1 -1
- package/dist/{supervise-CnxqHx1P.js → supervise-rEE46ruH.js} +2 -2
- package/dist/{supervise-CnxqHx1P.js.map → supervise-rEE46ruH.js.map} +1 -1
- package/dist/{supervisor-C8kgh8mf.js → supervisor-B-mmmiOU.js} +4 -3
- package/dist/supervisor-B-mmmiOU.js.map +1 -0
- package/dist/testing.js +12 -12
- package/dist/{workspace-archive-CHY5HvrF.js → workspace-archive-B0Hqp2eJ.js} +12 -7
- package/dist/workspace-archive-B0Hqp2eJ.js.map +1 -0
- package/package.json +3 -3
- package/dist/graph-E0U0c2YP.js +0 -2668
- package/dist/graph-E0U0c2YP.js.map +0 -1
- package/dist/prepare-BCScSDCv.js.map +0 -1
- package/dist/supervisor-C8kgh8mf.js.map +0 -1
- package/dist/workspace-archive-CHY5HvrF.js.map +0 -1
package/dist/graph.js
CHANGED
|
@@ -1,2 +1,2073 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { m as ValidationError } from "./errors-CDZ8XsVj.js";
|
|
2
|
+
import { d as replaySpawnTree, i as InMemorySpawnJournal, l as materializeTreeView, o as closesCursorSlot, r as InMemoryResultBlobStore, u as pendingWaits, x as contentAddress } from "./spawn-journal-Tgvp5VS5.js";
|
|
3
|
+
import { t as addSpend } from "./util-D6ZEuBMi.js";
|
|
4
|
+
import { N as createBudgetPool, U as createExecutorRegistry, a as uncertainSpawnBudgets, i as sumMeasuredSpendFromEvents, l as runFinalizer, o as bestDelivered, p as createScope, r as maxSeqOf, s as collectDelivered } from "./supervisor-B-mmmiOU.js";
|
|
5
|
+
import { i as workerFromBackend, s as supervisorAgent } from "./supervise-rEE46ruH.js";
|
|
6
|
+
import { t as GraphEdgeCapError } from "./graph-ZDMygFIo.js";
|
|
7
|
+
//#region src/runtime/graph/condition.ts
|
|
8
|
+
/**
|
|
9
|
+
* The ONE predicate tree: every guard in a graph — an edge `guard`, a filter projection's
|
|
10
|
+
* predicate — is this shape, evaluated by this evaluator, so `contains`, ordering and equality can
|
|
11
|
+
* never mean two different things on two surfaces (adopted from ADC's `workflow-conditions`,
|
|
12
|
+
* agent-runtime#968). A declarative tree keeps an untrusted predicate incapable of code execution;
|
|
13
|
+
* the size and depth bounds keep a predicate authored once from burning CPU on every settle.
|
|
14
|
+
*
|
|
15
|
+
* No zod: the kernel's grain is a hand-written validator that throws `ValidationError` by name.
|
|
16
|
+
*/
|
|
17
|
+
/** The leaf comparison operators; `exists`/`truthy` are unary, the rest compare against `value`. */
|
|
18
|
+
const CONDITION_OPS = [
|
|
19
|
+
"eq",
|
|
20
|
+
"neq",
|
|
21
|
+
"gt",
|
|
22
|
+
"gte",
|
|
23
|
+
"lt",
|
|
24
|
+
"lte",
|
|
25
|
+
"in",
|
|
26
|
+
"contains",
|
|
27
|
+
"exists",
|
|
28
|
+
"truthy"
|
|
29
|
+
];
|
|
30
|
+
/** Operators that compare against `value`; `exists`/`truthy` are unary and must omit it. */
|
|
31
|
+
const OPS_NEEDING_VALUE = new Set(CONDITION_OPS.filter((op) => op !== "exists" && op !== "truthy"));
|
|
32
|
+
const MAX_PATH_LENGTH = 256;
|
|
33
|
+
const MAX_PATH_SEGMENTS = 16;
|
|
34
|
+
const PATH_SEGMENT = /^[A-Za-z_$][A-Za-z0-9_$-]*$/u;
|
|
35
|
+
/** Parse `a.b[0].c` into steps; refuse anything outside the bounded grammar. */
|
|
36
|
+
function parseConditionPath(path, context) {
|
|
37
|
+
if (typeof path !== "string" || path.length === 0 || path.length > MAX_PATH_LENGTH) throw new ValidationError(`${context}: path must be a non-empty string of at most ${MAX_PATH_LENGTH} chars`);
|
|
38
|
+
const steps = [];
|
|
39
|
+
for (const part of path.split(".")) {
|
|
40
|
+
const open = part.indexOf("[");
|
|
41
|
+
const head = open === -1 ? part : part.slice(0, open);
|
|
42
|
+
if (head.length > 0) {
|
|
43
|
+
if (!PATH_SEGMENT.test(head)) throw new ValidationError(`${context}: path segment ${JSON.stringify(head)} is not addressable`);
|
|
44
|
+
steps.push(head);
|
|
45
|
+
} else if (open !== 0 || steps.length === 0) throw new ValidationError(`${context}: path ${JSON.stringify(path)} has an empty segment`);
|
|
46
|
+
let rest = open === -1 ? "" : part.slice(open);
|
|
47
|
+
while (rest.length > 0) {
|
|
48
|
+
const match = /^\[(\d{1,6})\]/u.exec(rest);
|
|
49
|
+
if (!match) throw new ValidationError(`${context}: path index in ${JSON.stringify(part)} must be [N]`);
|
|
50
|
+
steps.push(Number(match[1]));
|
|
51
|
+
rest = rest.slice(match[0].length);
|
|
52
|
+
}
|
|
53
|
+
if (steps.length > MAX_PATH_SEGMENTS) throw new ValidationError(`${context}: path exceeds ${MAX_PATH_SEGMENTS} segments`);
|
|
54
|
+
}
|
|
55
|
+
if (steps.length === 0) throw new ValidationError(`${context}: path resolves no segment`);
|
|
56
|
+
return steps;
|
|
57
|
+
}
|
|
58
|
+
/** Walk a parsed path; any miss resolves `undefined`, never a throw — absence is an answer. */
|
|
59
|
+
function resolveConditionPath(context, steps) {
|
|
60
|
+
let current = context;
|
|
61
|
+
for (const step of steps) {
|
|
62
|
+
if (current === null || current === void 0) return void 0;
|
|
63
|
+
if (typeof step === "number") {
|
|
64
|
+
if (!Array.isArray(current)) return void 0;
|
|
65
|
+
current = current[step];
|
|
66
|
+
} else {
|
|
67
|
+
if (typeof current !== "object" || Array.isArray(current)) return void 0;
|
|
68
|
+
current = current[step];
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return current;
|
|
72
|
+
}
|
|
73
|
+
function isLeaf(condition) {
|
|
74
|
+
return typeof condition.path === "string";
|
|
75
|
+
}
|
|
76
|
+
/** Validate shape, bounds, and per-leaf path/operator rules; returns the input for chaining. */
|
|
77
|
+
function validateCondition(raw, context) {
|
|
78
|
+
let nodes = 0;
|
|
79
|
+
const walk = (value, depth) => {
|
|
80
|
+
nodes += 1;
|
|
81
|
+
if (nodes > 40) throw new ValidationError(`${context}: condition exceeds 40 nodes`);
|
|
82
|
+
if (depth > 6) throw new ValidationError(`${context}: condition exceeds depth 6`);
|
|
83
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ValidationError(`${context}: a condition must be an object`);
|
|
84
|
+
const record = value;
|
|
85
|
+
const combinators = [
|
|
86
|
+
"all",
|
|
87
|
+
"any",
|
|
88
|
+
"not"
|
|
89
|
+
].filter((key) => record[key] !== void 0);
|
|
90
|
+
if (combinators.length > 1) throw new ValidationError(`${context}: a condition carries ONE of all/any/not, got ${combinators.join("+")}`);
|
|
91
|
+
if (record.all !== void 0 || record.any !== void 0) {
|
|
92
|
+
const key = record.all !== void 0 ? "all" : "any";
|
|
93
|
+
const branch = record[key];
|
|
94
|
+
if (!Array.isArray(branch) || branch.length === 0) throw new ValidationError(`${context}: ${key} must be a non-empty array`);
|
|
95
|
+
for (const child of branch) walk(child, depth + 1);
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
if (record.not !== void 0) {
|
|
99
|
+
walk(record.not, depth + 1);
|
|
100
|
+
return value;
|
|
101
|
+
}
|
|
102
|
+
const op = record.op;
|
|
103
|
+
if (typeof record.path !== "string" || typeof op !== "string") throw new ValidationError(`${context}: a leaf needs { path, op }`);
|
|
104
|
+
if (!CONDITION_OPS.includes(op)) throw new ValidationError(`${context}: unknown op ${JSON.stringify(op)}; known: ${CONDITION_OPS.join(", ")}`);
|
|
105
|
+
parseConditionPath(record.path, context);
|
|
106
|
+
const needsValue = OPS_NEEDING_VALUE.has(op);
|
|
107
|
+
if (needsValue && !("value" in record)) throw new ValidationError(`${context}: op ${JSON.stringify(op)} requires a value`);
|
|
108
|
+
if (!needsValue && "value" in record) throw new ValidationError(`${context}: op ${JSON.stringify(op)} is unary — remove value`);
|
|
109
|
+
if (op === "in" && !Array.isArray(record.value)) throw new ValidationError(`${context}: op "in" takes an array value`);
|
|
110
|
+
return value;
|
|
111
|
+
};
|
|
112
|
+
return walk(raw, 1);
|
|
113
|
+
}
|
|
114
|
+
function canonicalEquals(a, b) {
|
|
115
|
+
if (Object.is(a, b)) return true;
|
|
116
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
|
|
117
|
+
try {
|
|
118
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
119
|
+
} catch {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function ordering(op, left, right) {
|
|
124
|
+
if (typeof left === "number" && typeof right === "number") {
|
|
125
|
+
if (Number.isNaN(left) || Number.isNaN(right)) return false;
|
|
126
|
+
if (op === "gt") return left > right;
|
|
127
|
+
if (op === "gte") return left >= right;
|
|
128
|
+
if (op === "lt") return left < right;
|
|
129
|
+
return left <= right;
|
|
130
|
+
}
|
|
131
|
+
if (typeof left === "string" && typeof right === "string") {
|
|
132
|
+
if (op === "gt") return left > right;
|
|
133
|
+
if (op === "gte") return left >= right;
|
|
134
|
+
if (op === "lt") return left < right;
|
|
135
|
+
return left <= right;
|
|
136
|
+
}
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
/** Walk a validated condition over a context to a boolean. Never throws on data shape. */
|
|
140
|
+
function evaluateCondition(condition, context) {
|
|
141
|
+
if (isLeaf(condition)) {
|
|
142
|
+
const resolved = resolveConditionPath(context, parseConditionPath(condition.path, "evaluate"));
|
|
143
|
+
switch (condition.op) {
|
|
144
|
+
case "exists": return resolved !== void 0 && resolved !== null;
|
|
145
|
+
case "truthy": return Boolean(resolved);
|
|
146
|
+
case "eq": return canonicalEquals(resolved, condition.value);
|
|
147
|
+
case "neq": return !canonicalEquals(resolved, condition.value);
|
|
148
|
+
case "in": return Array.isArray(condition.value) ? condition.value.some((candidate) => canonicalEquals(resolved, candidate)) : false;
|
|
149
|
+
case "contains":
|
|
150
|
+
if (Array.isArray(resolved)) return resolved.some((element) => canonicalEquals(element, condition.value));
|
|
151
|
+
return typeof resolved === "string" && typeof condition.value === "string" ? resolved.includes(condition.value) : false;
|
|
152
|
+
default: return ordering(condition.op, resolved, condition.value);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if ("all" in condition) return condition.all.every((child) => evaluateCondition(child, context));
|
|
156
|
+
if ("any" in condition) return condition.any.some((child) => evaluateCondition(child, context));
|
|
157
|
+
return !evaluateCondition(condition.not, context);
|
|
158
|
+
}
|
|
159
|
+
//#endregion
|
|
160
|
+
//#region src/runtime/graph/projection.ts
|
|
161
|
+
/**
|
|
162
|
+
* The ONE pure projection a `data` edge may carry (agent-runtime#971): the bounded,
|
|
163
|
+
* schema-preserving subset of ADC's collection helpers. Anything richer is a `script` NODE, so it
|
|
164
|
+
* is journaled (`inputRef` → `outRef`), typed, and visible. Exactly one operator per projection.
|
|
165
|
+
*/
|
|
166
|
+
const PROJECTION_KEYS = [
|
|
167
|
+
"path",
|
|
168
|
+
"pick",
|
|
169
|
+
"map",
|
|
170
|
+
"filter",
|
|
171
|
+
"first",
|
|
172
|
+
"last",
|
|
173
|
+
"count"
|
|
174
|
+
];
|
|
175
|
+
/** Validate a projection: exactly one known operator, its argument well-formed. */
|
|
176
|
+
function validateProjection(raw, context) {
|
|
177
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new ValidationError(`${context}: a projection must be an object`);
|
|
178
|
+
const record = raw;
|
|
179
|
+
const keys = PROJECTION_KEYS.filter((key) => record[key] !== void 0);
|
|
180
|
+
const unknown = Object.keys(record).filter((key) => !PROJECTION_KEYS.includes(key));
|
|
181
|
+
if (unknown.length > 0) throw new ValidationError(`${context}: unknown projection key(s) ${unknown.join(", ")}; known: ${PROJECTION_KEYS.join(", ")}`);
|
|
182
|
+
if (keys.length !== 1) throw new ValidationError(`${context}: a projection carries exactly ONE of ${PROJECTION_KEYS.join("/")}`);
|
|
183
|
+
const key = keys[0];
|
|
184
|
+
if (key === "path" || key === "map") parseConditionPath(record[key], context);
|
|
185
|
+
if (key === "pick") {
|
|
186
|
+
const fields = record.pick;
|
|
187
|
+
if (!Array.isArray(fields) || fields.length === 0 || fields.some((f) => typeof f !== "string")) throw new ValidationError(`${context}: pick must be a non-empty array of field names`);
|
|
188
|
+
}
|
|
189
|
+
if (key === "filter") validateCondition(record.filter, context);
|
|
190
|
+
if ((key === "first" || key === "last" || key === "count") && record[key] !== true) throw new ValidationError(`${context}: ${key} must be literally true`);
|
|
191
|
+
return raw;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Apply a validated projection to an admitted payload. Collection operators over a non-array
|
|
195
|
+
* refuse by name — a shape the author did not expect is a graph defect, not an empty result.
|
|
196
|
+
*/
|
|
197
|
+
function applyProjection(value, projection, context) {
|
|
198
|
+
if ("path" in projection) return resolveConditionPath(value, parseConditionPath(projection.path, context));
|
|
199
|
+
if ("pick" in projection) {
|
|
200
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ValidationError(`${context}: pick needs an object payload`);
|
|
201
|
+
const record = value;
|
|
202
|
+
const out = {};
|
|
203
|
+
for (const field of projection.pick) if (field in record) out[field] = record[field];
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
const collection = value;
|
|
207
|
+
if (!Array.isArray(collection)) throw new ValidationError(`${context}: this projection needs an array payload`);
|
|
208
|
+
if ("map" in projection) {
|
|
209
|
+
const steps = parseConditionPath(projection.map, context);
|
|
210
|
+
return collection.map((element) => resolveConditionPath(element, steps));
|
|
211
|
+
}
|
|
212
|
+
if ("filter" in projection) return collection.filter((element) => evaluateCondition(projection.filter, element));
|
|
213
|
+
if ("first" in projection) return collection[0];
|
|
214
|
+
if ("last" in projection) return collection[collection.length - 1];
|
|
215
|
+
return collection.length;
|
|
216
|
+
}
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/runtime/graph/registry.ts
|
|
219
|
+
/**
|
|
220
|
+
* `Registry<T>` — the ONE name→thing shape for the graph engine.
|
|
221
|
+
*
|
|
222
|
+
* The kernel grew fourteen of these (agent-runtime#978) that differ in three properties:
|
|
223
|
+
* whether names can be listed, what a miss does, and whether the table is global. This one
|
|
224
|
+
* fixes all three — enumerable, a miss is refused BY NAME listing what is registered, and every
|
|
225
|
+
* registry is per-instance — and it is lifted from `AgentEnvironmentProviderRegistry`, the
|
|
226
|
+
* richest and best-tested of the fourteen, not invented.
|
|
227
|
+
*
|
|
228
|
+
* Entries are addressed by a versioned handle, `<id>/v<n>`, the same way the prompt registry
|
|
229
|
+
* addresses directives. A graph names a kind by handle; a host registers exact versions; a
|
|
230
|
+
* missing version is refused, never served by a newer one.
|
|
231
|
+
*/
|
|
232
|
+
/** `<id>/v<n>` — the only spelling a handle has on the wire, in a journal, or in an error. */
|
|
233
|
+
function formatRegistryHandle(handle) {
|
|
234
|
+
return `${handle.id}/v${handle.version}`;
|
|
235
|
+
}
|
|
236
|
+
/** Parse the wire spelling back. Refuses anything that is not exactly `<id>/v<n>`. */
|
|
237
|
+
function parseRegistryHandle(text, context) {
|
|
238
|
+
const match = /^([A-Za-z0-9][A-Za-z0-9._-]*)\/v(\d+)$/u.exec(text);
|
|
239
|
+
if (!match) throw new ValidationError(`${context}: ${JSON.stringify(text)} is not a registry handle; expected "<id>/v<n>"`);
|
|
240
|
+
const version = Number(match[2]);
|
|
241
|
+
if (!Number.isSafeInteger(version) || version < 1) throw new ValidationError(`${context}: handle version must be a positive integer`);
|
|
242
|
+
return {
|
|
243
|
+
id: match[1],
|
|
244
|
+
version
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Create a registry. Per-instance by construction: two engines in one process may hold
|
|
249
|
+
* different kind sets, a test is hermetic, and a run can print its own table. There is
|
|
250
|
+
* deliberately no module-level singleton — `builtinShapes` was the one mutable global in the
|
|
251
|
+
* kernel and it had zero tests.
|
|
252
|
+
*/
|
|
253
|
+
function createRegistry(label, seed = []) {
|
|
254
|
+
const table = /* @__PURE__ */ new Map();
|
|
255
|
+
const registry = {
|
|
256
|
+
register(entry, options = {}) {
|
|
257
|
+
if (typeof entry.id !== "string" || entry.id.length === 0) throw new ValidationError(`${label}: an entry must carry a non-empty id`);
|
|
258
|
+
if (!Number.isSafeInteger(entry.version) || entry.version < 1) throw new ValidationError(`${label}: ${JSON.stringify(entry.id)} must carry a positive integer version`);
|
|
259
|
+
const key = formatRegistryHandle(entry);
|
|
260
|
+
if (!options.replace && table.has(key)) throw new ValidationError(`${label}: ${JSON.stringify(key)} is already registered`);
|
|
261
|
+
table.set(key, entry);
|
|
262
|
+
},
|
|
263
|
+
has(handle) {
|
|
264
|
+
return table.has(formatRegistryHandle(handle));
|
|
265
|
+
},
|
|
266
|
+
get(handle) {
|
|
267
|
+
return table.get(formatRegistryHandle(handle));
|
|
268
|
+
},
|
|
269
|
+
require(handle, context = label) {
|
|
270
|
+
const key = formatRegistryHandle(handle);
|
|
271
|
+
const entry = table.get(key);
|
|
272
|
+
if (entry === void 0) {
|
|
273
|
+
const known = registry.names();
|
|
274
|
+
const suffix = known.length > 0 ? `; registered: ${known.join(", ")}` : "; nothing is registered";
|
|
275
|
+
throw new ValidationError(`${context}: ${JSON.stringify(key)} is not registered${suffix}`);
|
|
276
|
+
}
|
|
277
|
+
return entry;
|
|
278
|
+
},
|
|
279
|
+
names() {
|
|
280
|
+
return Array.from(table.keys()).sort();
|
|
281
|
+
},
|
|
282
|
+
entries() {
|
|
283
|
+
return registry.names().map((key) => table.get(key));
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
for (const entry of seed) registry.register(entry);
|
|
287
|
+
return registry;
|
|
288
|
+
}
|
|
289
|
+
//#endregion
|
|
290
|
+
//#region src/runtime/graph/definition.ts
|
|
291
|
+
/** Which gating-edge outcomes release a node (adopted from ADC, agent-runtime#968). */
|
|
292
|
+
const JOIN_RULES = [
|
|
293
|
+
"all",
|
|
294
|
+
"any",
|
|
295
|
+
"any_failed",
|
|
296
|
+
"all_done"
|
|
297
|
+
];
|
|
298
|
+
/** ADC-compatible visit backstop: nothing may be ENTERED more than this many times. */
|
|
299
|
+
const DEFAULT_MAX_NODE_VISITS = 25;
|
|
300
|
+
/** The hard ceiling an author's `maxVisits`/`maxNodeVisits` override may reach. */
|
|
301
|
+
const MAX_MAX_NODE_VISITS = 100;
|
|
302
|
+
/** Structural validation only — everything a registry is not needed for. */
|
|
303
|
+
function validateEngineGraphSpec(spec, context = "compileGraph") {
|
|
304
|
+
if (!Array.isArray(spec.nodes) || spec.nodes.length === 0) throw new ValidationError(`${context}: a graph needs at least one node`);
|
|
305
|
+
const ids = /* @__PURE__ */ new Set();
|
|
306
|
+
for (const node of spec.nodes) {
|
|
307
|
+
if (typeof node.id !== "string" || node.id.length === 0) throw new ValidationError(`${context}: every node needs a non-empty id`);
|
|
308
|
+
if (ids.has(node.id)) throw new ValidationError(`${context}: duplicate node id ${JSON.stringify(node.id)}`);
|
|
309
|
+
ids.add(node.id);
|
|
310
|
+
parseRegistryHandle(node.kind, `${context}: node ${node.id} kind`);
|
|
311
|
+
if (node.join !== void 0 && !JOIN_RULES.includes(node.join)) throw new ValidationError(`${context}: node ${node.id} join ${JSON.stringify(node.join)}; known: ${JOIN_RULES.join(", ")}`);
|
|
312
|
+
if (node.maxVisits !== void 0) {
|
|
313
|
+
if (!Number.isSafeInteger(node.maxVisits) || node.maxVisits < 1 || node.maxVisits > 100) throw new ValidationError(`${context}: node ${node.id} maxVisits must be an integer in [1, 100]`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (!Array.isArray(spec.edges)) throw new ValidationError(`${context}: edges must be an array`);
|
|
317
|
+
for (const [index, edge] of spec.edges.entries()) {
|
|
318
|
+
const who = `${context}: edge[${index}]`;
|
|
319
|
+
if (edge.kind !== "delegates" && edge.kind !== "analyzes" && edge.kind !== "data") throw new ValidationError(`${who}: kind must be delegates | analyzes | data`);
|
|
320
|
+
for (const end of ["from", "to"]) {
|
|
321
|
+
const ref = edge[end];
|
|
322
|
+
if (typeof ref !== "object" || ref === null || typeof ref.node !== "string" || !ids.has(ref.node)) throw new ValidationError(`${who}: ${end}.node must name a node in this graph`);
|
|
323
|
+
}
|
|
324
|
+
if (edge.guard !== void 0) validateCondition(edge.guard, `${who} guard`);
|
|
325
|
+
if (edge.projection !== void 0) {
|
|
326
|
+
if (edge.kind !== "data") throw new ValidationError(`${who}: only a data edge carries a projection`);
|
|
327
|
+
validateProjection(edge.projection, `${who} projection`);
|
|
328
|
+
}
|
|
329
|
+
if (edge.maxTraversals !== void 0) {
|
|
330
|
+
if (!Number.isSafeInteger(edge.maxTraversals) || edge.maxTraversals < 0) throw new ValidationError(`${who}: maxTraversals must be a non-negative integer`);
|
|
331
|
+
}
|
|
332
|
+
if (edge.kind === "data" && edge.directive !== void 0) throw new ValidationError(`${who}: a data edge carries a port binding, never a directive`);
|
|
333
|
+
}
|
|
334
|
+
if (spec.root !== void 0 && !ids.has(spec.root)) throw new ValidationError(`${context}: root ${JSON.stringify(spec.root)} names no node`);
|
|
335
|
+
if (spec.maxNodeVisits !== void 0) {
|
|
336
|
+
if (!Number.isSafeInteger(spec.maxNodeVisits) || spec.maxNodeVisits < 1 || spec.maxNodeVisits > 100) throw new ValidationError(`${context}: maxNodeVisits must be an integer in [1, 100]`);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
//#endregion
|
|
340
|
+
//#region src/runtime/graph/compile.ts
|
|
341
|
+
/**
|
|
342
|
+
* Compile an authored graph against an engine's kind registry into the schedulable form. Every
|
|
343
|
+
* refusal here happens before any spend: an unknown kind, a port that does not exist, a `data`
|
|
344
|
+
* binding whose schemas cannot fit, a `delegates`/`data` edge into an oracle, a terminal with no
|
|
345
|
+
* completion check (agent-runtime#971, #973).
|
|
346
|
+
*/
|
|
347
|
+
/** A node's ports: its kind's declared outputs plus the two implicit ones every node has. */
|
|
348
|
+
const IMPLICIT_OUTPUT_PORTS = ["out", "trace"];
|
|
349
|
+
/** `delegates` is the one MODEL-fired edge kind (agent-runtime#971): its payload is a directive and
|
|
350
|
+
* its target is spawned by the source supervisor through the coordination protocol, not released
|
|
351
|
+
* by the scheduler. `data` and `analyzes` are engine-fired. */
|
|
352
|
+
function isEngineFired(edge) {
|
|
353
|
+
return edge.spec.kind !== "delegates";
|
|
354
|
+
}
|
|
355
|
+
/** A node's ports: node-level declarations merged OVER its kind's (the node wins on a name). */
|
|
356
|
+
function nodePorts(kind, node) {
|
|
357
|
+
const merge = (declared, own) => {
|
|
358
|
+
if (own === void 0 || own.length === 0) return declared;
|
|
359
|
+
const names = new Set(own.map((port) => port.name));
|
|
360
|
+
return [...own, ...declared.filter((port) => !names.has(port.name))];
|
|
361
|
+
};
|
|
362
|
+
return {
|
|
363
|
+
inputs: merge(kind.inputs, node.ports?.inputs),
|
|
364
|
+
outputs: merge(kind.outputs, node.ports?.outputs)
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
function outputPort(ports, port) {
|
|
368
|
+
if (IMPLICIT_OUTPUT_PORTS.includes(port)) return {
|
|
369
|
+
name: port,
|
|
370
|
+
schema: {}
|
|
371
|
+
};
|
|
372
|
+
return ports.outputs.find((candidate) => candidate.name === port);
|
|
373
|
+
}
|
|
374
|
+
function inputPort(ports, port) {
|
|
375
|
+
return ports.inputs.find((candidate) => candidate.name === port);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Bounded structural acceptance: does a value of `source`'s shape fit `target`? Schemas with no
|
|
379
|
+
* `type` accept anything; object targets require their `required` properties to be present and
|
|
380
|
+
* accepted when the source declares properties. Depth-bounded — this is a compile-time tripwire,
|
|
381
|
+
* not a full JSON Schema validator.
|
|
382
|
+
*/
|
|
383
|
+
function schemaAccepts(source, target, depth = 0) {
|
|
384
|
+
if (depth > 6) return true;
|
|
385
|
+
const sourceType = source.type;
|
|
386
|
+
const targetType = target.type;
|
|
387
|
+
if (targetType === void 0 || sourceType === void 0) return true;
|
|
388
|
+
const targets = Array.isArray(targetType) ? targetType : [targetType];
|
|
389
|
+
const sources = Array.isArray(sourceType) ? sourceType : [sourceType];
|
|
390
|
+
if (sources.filter((candidate) => targets.includes(candidate === "integer" ? "number" : candidate) || targets.includes(candidate)).length === 0) return false;
|
|
391
|
+
if (targets.includes("object") && sources.includes("object")) {
|
|
392
|
+
const required = Array.isArray(target.required) ? target.required : [];
|
|
393
|
+
const sourceProps = source.properties;
|
|
394
|
+
const targetProps = target.properties;
|
|
395
|
+
if (sourceProps !== void 0) for (const name of required) {
|
|
396
|
+
const sourceProp = sourceProps[name];
|
|
397
|
+
if (sourceProp === void 0) return false;
|
|
398
|
+
const targetProp = targetProps?.[name];
|
|
399
|
+
if (targetProp !== void 0 && !schemaAccepts(sourceProp, targetProp, depth + 1)) return false;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (targets.includes("array") && sources.includes("array")) {
|
|
403
|
+
const sourceItems = source.items;
|
|
404
|
+
const targetItems = target.items;
|
|
405
|
+
if (sourceItems !== void 0 && targetItems !== void 0) return schemaAccepts(sourceItems, targetItems, depth + 1);
|
|
406
|
+
}
|
|
407
|
+
return true;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Lower an authored graph against an engine's kind registry into the schedulable form, refusing
|
|
411
|
+
* every structural defect before any spend.
|
|
412
|
+
*/
|
|
413
|
+
function compileGraph(engine, spec, context = "compileGraph") {
|
|
414
|
+
validateEngineGraphSpec(spec, context);
|
|
415
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
416
|
+
const configs = /* @__PURE__ */ new Map();
|
|
417
|
+
for (const node of spec.nodes) {
|
|
418
|
+
const handle = parseRegistryHandle(node.kind, `${context}: node ${node.id}`);
|
|
419
|
+
const kind = engine.kinds.require(handle, `${context}: node ${node.id}`);
|
|
420
|
+
kinds.set(node.id, kind);
|
|
421
|
+
configs.set(node.id, kind.validateConfig(node.config ?? {}, `${context}: node ${node.id}`));
|
|
422
|
+
if (node.flags?.pure && kind.id !== "script") throw new ValidationError(`${context}: node ${node.id} sets pure, which only a script node may claim`);
|
|
423
|
+
}
|
|
424
|
+
const compiledEdges = [];
|
|
425
|
+
const inbound = /* @__PURE__ */ new Map();
|
|
426
|
+
const outbound = /* @__PURE__ */ new Map();
|
|
427
|
+
for (const [index, edge] of spec.edges.entries()) {
|
|
428
|
+
const who = `${context}: edge[${index}] ${edge.from.node}->${edge.to.node}`;
|
|
429
|
+
const fromKind = kinds.get(edge.from.node);
|
|
430
|
+
const toKind = kinds.get(edge.to.node);
|
|
431
|
+
if (!fromKind || !toKind) throw new ValidationError(`${who}: unresolved endpoint`);
|
|
432
|
+
const toNode = spec.nodes.find((node) => node.id === edge.to.node);
|
|
433
|
+
if (edge.kind !== "analyzes" && toNode?.flags?.oracle) throw new ValidationError(`${who}: a ${edge.kind} edge may not target oracle node ${edge.to.node}; use analyzes`);
|
|
434
|
+
const fromPort = edge.from.port ?? (edge.kind === "analyzes" ? "trace" : "out");
|
|
435
|
+
if (edge.kind === "analyzes" && fromPort !== "trace") throw new ValidationError(`${who}: an analyzes edge reads the trace port, got ${fromPort}`);
|
|
436
|
+
const fromPorts = nodePorts(fromKind, spec.nodes.find((node) => node.id === edge.from.node));
|
|
437
|
+
const toPorts = nodePorts(toKind, toNode);
|
|
438
|
+
const sourcePort = outputPort(fromPorts, fromPort);
|
|
439
|
+
if (!sourcePort) {
|
|
440
|
+
const known = [...IMPLICIT_OUTPUT_PORTS, ...fromPorts.outputs.map((port) => port.name)];
|
|
441
|
+
throw new ValidationError(`${who}: ${formatRegistryHandle(fromKind)} has no output port ${JSON.stringify(fromPort)}; known: ${known.join(", ")}`);
|
|
442
|
+
}
|
|
443
|
+
let toPort = edge.to.port ?? "";
|
|
444
|
+
if (edge.kind === "data") {
|
|
445
|
+
if (toPort === "") if (toPorts.inputs.length === 1) toPort = toPorts.inputs[0]?.name ?? "";
|
|
446
|
+
else throw new ValidationError(`${who}: a data edge needs to.port; ${formatRegistryHandle(toKind)} declares ${toPorts.inputs.length} inputs`);
|
|
447
|
+
const targetPort = inputPort(toPorts, toPort);
|
|
448
|
+
if (!targetPort) throw new ValidationError(`${who}: ${formatRegistryHandle(toKind)} has no input port ${JSON.stringify(toPort)}; known: ${toPorts.inputs.map((port) => port.name).join(", ") || "(none)"}`);
|
|
449
|
+
if (edge.projection === void 0 && !schemaAccepts(sourcePort.schema, targetPort.schema)) throw new ValidationError(`${who}: output ${fromPort} (${JSON.stringify(sourcePort.schema.type ?? "any")}) cannot fit input ${toPort} (${JSON.stringify(targetPort.schema.type ?? "any")})`);
|
|
450
|
+
}
|
|
451
|
+
const compiled = {
|
|
452
|
+
id: edge.id ?? `${edge.from.node}->${edge.to.node}#${index}`,
|
|
453
|
+
spec: edge,
|
|
454
|
+
fromPort,
|
|
455
|
+
toPort: toPort === "" ? "out" : toPort
|
|
456
|
+
};
|
|
457
|
+
compiledEdges.push(compiled);
|
|
458
|
+
outbound.set(edge.from.node, [...outbound.get(edge.from.node) ?? [], compiled]);
|
|
459
|
+
inbound.set(edge.to.node, [...inbound.get(edge.to.node) ?? [], compiled]);
|
|
460
|
+
}
|
|
461
|
+
const dupes = /* @__PURE__ */ new Set();
|
|
462
|
+
for (const edge of compiledEdges) {
|
|
463
|
+
if (dupes.has(edge.id)) throw new ValidationError(`${context}: duplicate edge id ${edge.id}`);
|
|
464
|
+
dupes.add(edge.id);
|
|
465
|
+
}
|
|
466
|
+
const engineInbound = (id) => (inbound.get(id) ?? []).filter(isEngineFired);
|
|
467
|
+
const engineOutbound = (id) => (outbound.get(id) ?? []).filter(isEngineFired);
|
|
468
|
+
const unfed = spec.nodes.filter((node) => (inbound.get(node.id) ?? []).length === 0);
|
|
469
|
+
if (unfed.length === 0 && spec.root === void 0) throw new ValidationError(`${context}: no entry node — every node has an inbound edge`);
|
|
470
|
+
const root = spec.root ?? (unfed.length === 1 ? unfed[0]?.id ?? "" : (() => {
|
|
471
|
+
throw new ValidationError(`${context}: ${unfed.length} entry nodes (${unfed.map((node) => node.id).join(", ")}) — name spec.root`);
|
|
472
|
+
})());
|
|
473
|
+
const declaredOut = new Set(spec.nodes.filter((node) => node.entry === false).map((node) => node.id));
|
|
474
|
+
const entries = [root, ...unfed.map((node) => node.id).filter((id) => id !== root)].filter((id) => !declaredOut.has(id));
|
|
475
|
+
if (entries.length === 0) throw new ValidationError(`${context}: every entry node declares entry: false — nothing starts`);
|
|
476
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
477
|
+
const terminals = [];
|
|
478
|
+
for (const node of spec.nodes) {
|
|
479
|
+
const kind = kinds.get(node.id);
|
|
480
|
+
if (!kind) throw new ValidationError(`${context}: unresolved node ${node.id}`);
|
|
481
|
+
const modelFired = (inbound.get(node.id) ?? []).some((edge) => !isEngineFired(edge));
|
|
482
|
+
const terminal = node.terminal ?? (!modelFired && engineOutbound(node.id).length === 0);
|
|
483
|
+
const deliverable = node.deliverable ?? (node.id === root ? spec.deliverable : void 0);
|
|
484
|
+
if (terminal) terminals.push(node.id);
|
|
485
|
+
nodes.set(node.id, {
|
|
486
|
+
id: node.id,
|
|
487
|
+
kind,
|
|
488
|
+
config: configs.get(node.id),
|
|
489
|
+
join: node.join ?? "all",
|
|
490
|
+
maxVisits: node.maxVisits ?? spec.maxNodeVisits ?? 25,
|
|
491
|
+
oracle: node.flags?.oracle ?? false,
|
|
492
|
+
pure: node.flags?.pure ?? false,
|
|
493
|
+
terminal,
|
|
494
|
+
...deliverable === void 0 ? {} : { deliverable },
|
|
495
|
+
inbound: engineInbound(node.id),
|
|
496
|
+
outbound: outbound.get(node.id) ?? [],
|
|
497
|
+
modelFired,
|
|
498
|
+
spec: node
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
if (terminals.filter((id) => nodes.get(id)?.deliverable === void 0).length === terminals.length) throw new ValidationError(`${context}: no terminal declares a completion check (terminals: ${terminals.join(", ")}); give a node a deliverable or set spec.deliverable`);
|
|
502
|
+
return {
|
|
503
|
+
nodes,
|
|
504
|
+
edges: compiledEdges,
|
|
505
|
+
entries,
|
|
506
|
+
terminals,
|
|
507
|
+
root,
|
|
508
|
+
maxNodeVisits: spec.maxNodeVisits ?? 25
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
//#endregion
|
|
512
|
+
//#region src/runtime/graph/kind.ts
|
|
513
|
+
/** Validate a kind declaration at registration — so a malformed kind is refused by name once,
|
|
514
|
+
* not at the first node that uses it. */
|
|
515
|
+
function validateNodeKind(kind, context = "registerNodeKind") {
|
|
516
|
+
const who = `${context}: kind ${JSON.stringify(`${kind.id}/v${kind.version}`)}`;
|
|
517
|
+
if (typeof kind.id !== "string" || kind.id.length === 0) throw new ValidationError(`${context}: a kind must carry a non-empty id`);
|
|
518
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(kind.id)) throw new ValidationError(`${who}: id may contain only letters, digits, ".", "_" and "-"`);
|
|
519
|
+
if (!Number.isSafeInteger(kind.version) || kind.version < 1) throw new ValidationError(`${who}: version must be a positive integer`);
|
|
520
|
+
if (typeof kind.description !== "string" || kind.description.trim().length === 0) throw new ValidationError(`${who}: description is required`);
|
|
521
|
+
if (typeof kind.validateConfig !== "function") throw new ValidationError(`${who}: validateConfig must be a function`);
|
|
522
|
+
if (!isRecord(kind.configSchema)) throw new ValidationError(`${who}: configSchema must be a JSON Schema object`);
|
|
523
|
+
for (const [field, ports] of [["inputs", kind.inputs], ["outputs", kind.outputs]]) {
|
|
524
|
+
if (!Array.isArray(ports)) throw new ValidationError(`${who}: ${field} must be an array`);
|
|
525
|
+
const seen = /* @__PURE__ */ new Set();
|
|
526
|
+
for (const port of ports) {
|
|
527
|
+
if (!port || typeof port.name !== "string" || port.name.length === 0) throw new ValidationError(`${who}: every ${field} port needs a non-empty name`);
|
|
528
|
+
if (field === "outputs" && (port.name === "out" || port.name === "trace")) throw new ValidationError(`${who}: output port ${JSON.stringify(port.name)} is implicit on every node and cannot be declared`);
|
|
529
|
+
if (seen.has(port.name)) throw new ValidationError(`${who}: duplicate ${field} port ${JSON.stringify(port.name)}`);
|
|
530
|
+
seen.add(port.name);
|
|
531
|
+
if (!isRecord(port.schema)) throw new ValidationError(`${who}: ${field} port ${JSON.stringify(port.name)} needs a JSON Schema`);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
if (!Array.isArray(kind.effects) || kind.effects.some((e) => typeof e !== "string" || e.length === 0)) throw new ValidationError(`${who}: effects must be an array of non-empty names`);
|
|
535
|
+
if (new Set(kind.effects).size !== kind.effects.length) throw new ValidationError(`${who}: effects must not repeat a name`);
|
|
536
|
+
if (kind.onCrash !== "restart" && kind.onCrash !== "resume") throw new ValidationError(`${who}: onCrash must be "restart" or "resume"`);
|
|
537
|
+
if (kind.budget !== "metered" && kind.budget !== "exempt") throw new ValidationError(`${who}: budget must be "metered" or "exempt"`);
|
|
538
|
+
if (typeof kind.run !== "function") throw new ValidationError(`${who}: run must be a function`);
|
|
539
|
+
return kind;
|
|
540
|
+
}
|
|
541
|
+
/** The handle a graph writes to name this kind. */
|
|
542
|
+
function kindHandle(kind) {
|
|
543
|
+
return {
|
|
544
|
+
id: kind.id,
|
|
545
|
+
version: kind.version
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Narrow a host's effect table to exactly what one kind declared. Anything the kind did not
|
|
550
|
+
* declare is absent — `undefined` on read — so a kind cannot reach past its declaration, and the
|
|
551
|
+
* engine can list a graph's required effects before spending a token.
|
|
552
|
+
*/
|
|
553
|
+
function narrowEffects(declared, provided, context) {
|
|
554
|
+
const out = {};
|
|
555
|
+
const missing = [];
|
|
556
|
+
for (const name of declared) {
|
|
557
|
+
if (!(name in provided)) {
|
|
558
|
+
missing.push(name);
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
out[name] = provided[name];
|
|
562
|
+
}
|
|
563
|
+
if (missing.length > 0) throw new ValidationError(`${context}: host provides no effect for ${missing.map((m) => JSON.stringify(m)).join(", ")}; provided: ${Object.keys(provided).sort().join(", ") || "none"}`);
|
|
564
|
+
return Object.freeze(out);
|
|
565
|
+
}
|
|
566
|
+
function isRecord(value) {
|
|
567
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
568
|
+
}
|
|
569
|
+
//#endregion
|
|
570
|
+
//#region src/runtime/graph/engine.ts
|
|
571
|
+
/**
|
|
572
|
+
* `createGraphEngine` — one engine instance: its kind registry (core kinds pre-registered, host
|
|
573
|
+
* kinds added by the caller), its effect table, and nothing global.
|
|
574
|
+
*
|
|
575
|
+
* The scheduler (#980), journal fold (#981) and the `runGraph` preset (#982) attach here; this
|
|
576
|
+
* file is the part that must exist first so a host can register kinds and a compiler can ask
|
|
577
|
+
* "which effects does this graph need" before a token is spent.
|
|
578
|
+
*/
|
|
579
|
+
/**
|
|
580
|
+
* Build one engine: a kind registry seeded with the core kinds plus the host's, and the host's
|
|
581
|
+
* effect values. Every kind is validated by name at construction, so a malformed host kind fails
|
|
582
|
+
* here, never at its first node.
|
|
583
|
+
*/
|
|
584
|
+
function createGraphEngine(options) {
|
|
585
|
+
const kinds = createRegistry("graph kinds");
|
|
586
|
+
for (const kind of options.coreKinds) kinds.register(validateNodeKind(kind, "createGraphEngine"));
|
|
587
|
+
for (const kind of options.kinds ?? []) kinds.register(validateNodeKind(kind, "createGraphEngine"));
|
|
588
|
+
const effects = Object.freeze({ ...options.effects ?? {} });
|
|
589
|
+
if (Object.keys(effects).some((name) => name.length === 0)) throw new ValidationError("createGraphEngine: an effect name must be non-empty");
|
|
590
|
+
const engine = {
|
|
591
|
+
kinds,
|
|
592
|
+
effects,
|
|
593
|
+
requiredEffects() {
|
|
594
|
+
const names = /* @__PURE__ */ new Set();
|
|
595
|
+
for (const kind of kinds.entries()) for (const name of kind.effects) names.add(name);
|
|
596
|
+
return Array.from(names).sort();
|
|
597
|
+
},
|
|
598
|
+
missingEffects() {
|
|
599
|
+
return engine.requiredEffects().filter((name) => !(name in effects));
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
return engine;
|
|
603
|
+
}
|
|
604
|
+
//#endregion
|
|
605
|
+
//#region src/runtime/graph/fold.ts
|
|
606
|
+
/**
|
|
607
|
+
* The fold (agent-runtime#974): scheduler state is a pure function of the journal, reconstructed
|
|
608
|
+
* by replaying events through the SAME reducer the live scheduler feeds — fold, never checkpoint.
|
|
609
|
+
* Kernel events (`spawned`, `settled`, `waiting`, `woken`) carry what the kernel owns; the engine's
|
|
610
|
+
* events (`node-inputs-resolved`, `edge-verdict`, `join-state`) carry what the scheduler decided,
|
|
611
|
+
* each journaled BEFORE its effect was visible. `edge` stays observability and is skipped here
|
|
612
|
+
* exactly as the kernel's own replay skips it.
|
|
613
|
+
*
|
|
614
|
+
* Events are consumed in APPEND order (the journal file's line order), not by `seq`: kernel and
|
|
615
|
+
* engine events carry independent ordinal counters, and append order is the one total order both
|
|
616
|
+
* share.
|
|
617
|
+
*/
|
|
618
|
+
/** The reducer's zero: every node unvisited, every edge pending, nothing suspended. */
|
|
619
|
+
function emptyFoldState(compiled) {
|
|
620
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
621
|
+
for (const id of compiled.nodes.keys()) nodes.set(id, {
|
|
622
|
+
visits: 0,
|
|
623
|
+
blocked: false,
|
|
624
|
+
settles: []
|
|
625
|
+
});
|
|
626
|
+
const edges = /* @__PURE__ */ new Map();
|
|
627
|
+
for (const edge of compiled.edges) edges.set(edge.id, {
|
|
628
|
+
state: "pending",
|
|
629
|
+
consumedOnce: false,
|
|
630
|
+
traversals: 0,
|
|
631
|
+
judgedSourceSettles: 0,
|
|
632
|
+
capped: false
|
|
633
|
+
});
|
|
634
|
+
return {
|
|
635
|
+
nodes,
|
|
636
|
+
edges,
|
|
637
|
+
instances: /* @__PURE__ */ new Map(),
|
|
638
|
+
spawnedIds: /* @__PURE__ */ new Map(),
|
|
639
|
+
suspensions: /* @__PURE__ */ new Map(),
|
|
640
|
+
exhaustedEdges: /* @__PURE__ */ new Set()
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
function instanceOf(state, label) {
|
|
644
|
+
return state.instances.get(label);
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Apply ONE journal event. The live scheduler calls this right after each append; the restart path
|
|
648
|
+
* calls it over the loaded journal. Unknown kernel events are ignored — the engine folds only what
|
|
649
|
+
* it understands, exactly as the kernel's replay skips the engine's events.
|
|
650
|
+
*/
|
|
651
|
+
function applyGraphFoldEvent(state, ev, compiled) {
|
|
652
|
+
switch (ev.kind) {
|
|
653
|
+
case "node-inputs-resolved": {
|
|
654
|
+
const visit = Number(ev.instance.split("#").at(-1));
|
|
655
|
+
if (!Number.isSafeInteger(visit)) throw new ValidationError(`graph fold: instance ${ev.instance} carries no visit ordinal`);
|
|
656
|
+
state.instances.set(ev.instance, {
|
|
657
|
+
node: ev.node,
|
|
658
|
+
instance: ev.instance,
|
|
659
|
+
visit,
|
|
660
|
+
inputRef: ev.inputRef,
|
|
661
|
+
status: "released"
|
|
662
|
+
});
|
|
663
|
+
const node = state.nodes.get(ev.node);
|
|
664
|
+
if (node) node.visits = Math.max(node.visits, visit);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
case "spawned": {
|
|
668
|
+
const instance = instanceOf(state, ev.label);
|
|
669
|
+
if (instance) {
|
|
670
|
+
instance.status = "live";
|
|
671
|
+
state.spawnedIds.set(ev.id, ev.label);
|
|
672
|
+
}
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
case "settled": {
|
|
676
|
+
const label = state.spawnedIds.get(ev.id);
|
|
677
|
+
const instance = label === void 0 ? void 0 : instanceOf(state, label);
|
|
678
|
+
if (!instance) return;
|
|
679
|
+
instance.status = ev.status;
|
|
680
|
+
const settle = {
|
|
681
|
+
node: instance.node,
|
|
682
|
+
visit: instance.visit,
|
|
683
|
+
status: ev.status,
|
|
684
|
+
...ev.outRef !== void 0 ? { outRef: ev.outRef } : {},
|
|
685
|
+
...ev.reason !== void 0 ? { reason: ev.reason } : {}
|
|
686
|
+
};
|
|
687
|
+
if (ev.trace?.status === "available") settle.traceRef = ev.trace.traceRef;
|
|
688
|
+
instance.settle = settle;
|
|
689
|
+
state.nodes.get(instance.node)?.settles.push(settle);
|
|
690
|
+
const node = compiled.nodes.get(instance.node);
|
|
691
|
+
for (const edge of node?.outbound ?? []) {
|
|
692
|
+
const folded = state.edges.get(edge.id);
|
|
693
|
+
if (folded?.consumedOnce && folded.state === "pending") {
|
|
694
|
+
folded.consumedOnce = false;
|
|
695
|
+
folded.judgedSourceSettles += 1;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
case "edge-verdict": {
|
|
701
|
+
const folded = state.edges.get(ev.edge);
|
|
702
|
+
if (!folded) return;
|
|
703
|
+
if (ev.capped) {
|
|
704
|
+
folded.capped = true;
|
|
705
|
+
state.exhaustedEdges.add(ev.edge);
|
|
706
|
+
const target = compiled.edges.find((edge) => edge.id === ev.edge)?.spec.to.node;
|
|
707
|
+
const compiledTarget = target === void 0 ? void 0 : compiled.nodes.get(target);
|
|
708
|
+
if (compiledTarget && (compiledTarget.join === "all" || compiledTarget.join === "all_done")) {
|
|
709
|
+
const node = state.nodes.get(target);
|
|
710
|
+
if (node) node.blocked = true;
|
|
711
|
+
}
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
folded.judgedSourceSettles += 1;
|
|
715
|
+
if (!ev.fired) {
|
|
716
|
+
folded.state = ev.sourceStatus === "done" ? "dead" : "failed";
|
|
717
|
+
folded.payloadRef = void 0;
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
folded.state = "satisfied";
|
|
721
|
+
folded.payloadRef = ev.inputRef;
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
case "join-state": {
|
|
725
|
+
for (const edgeId of ev.satisfiedBy) {
|
|
726
|
+
const folded = state.edges.get(edgeId);
|
|
727
|
+
if (!folded) continue;
|
|
728
|
+
folded.traversals += 1;
|
|
729
|
+
folded.state = "pending";
|
|
730
|
+
folded.payloadRef = void 0;
|
|
731
|
+
}
|
|
732
|
+
const target = compiled.nodes.get(ev.node);
|
|
733
|
+
for (const edge of target?.inbound ?? []) {
|
|
734
|
+
const folded = state.edges.get(edge.id);
|
|
735
|
+
if (!folded) continue;
|
|
736
|
+
if (ev.consumedPending.includes(edge.id)) folded.consumedOnce = true;
|
|
737
|
+
else if (folded.state !== "pending" && !ev.satisfiedBy.includes(edge.id)) {
|
|
738
|
+
folded.state = "pending";
|
|
739
|
+
folded.payloadRef = void 0;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
case "waiting": {
|
|
745
|
+
if (ev.spec.kind !== "token") return;
|
|
746
|
+
const instance = instanceOf(state, ev.label);
|
|
747
|
+
if (instance) {
|
|
748
|
+
instance.status = "suspended";
|
|
749
|
+
if (instance.settle !== void 0) {
|
|
750
|
+
const settles = state.nodes.get(instance.node)?.settles;
|
|
751
|
+
if (settles && settles.at(-1) === instance.settle) settles.pop();
|
|
752
|
+
instance.settle = void 0;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
state.suspensions.set(ev.spec.token, {
|
|
756
|
+
token: ev.spec.token,
|
|
757
|
+
node: instance?.node ?? ev.label.split("#")[0] ?? ev.label,
|
|
758
|
+
instance: ev.label,
|
|
759
|
+
onExpire: ev.spec.onExpire,
|
|
760
|
+
...ev.spec.expiresAtMs !== void 0 ? { expiresAtMs: ev.spec.expiresAtMs } : {},
|
|
761
|
+
...ev.spec.defaultRef !== void 0 ? { defaultRef: ev.spec.defaultRef } : {},
|
|
762
|
+
status: "pending"
|
|
763
|
+
});
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
case "woken": {
|
|
767
|
+
const token = ev.id.startsWith("graphwait:") ? ev.id.slice(10) : void 0;
|
|
768
|
+
const suspension = token === void 0 ? void 0 : state.suspensions.get(token);
|
|
769
|
+
if (!suspension) return;
|
|
770
|
+
const instance = instanceOf(state, suspension.instance);
|
|
771
|
+
if (ev.by === "expired") {
|
|
772
|
+
suspension.status = "expired";
|
|
773
|
+
if (instance) {
|
|
774
|
+
instance.status = "down";
|
|
775
|
+
const settle = {
|
|
776
|
+
node: suspension.node,
|
|
777
|
+
visit: instance.visit,
|
|
778
|
+
status: "down",
|
|
779
|
+
reason: "suspension expired"
|
|
780
|
+
};
|
|
781
|
+
instance.settle = settle;
|
|
782
|
+
state.nodes.get(suspension.node)?.settles.push(settle);
|
|
783
|
+
}
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
suspension.status = "woken";
|
|
787
|
+
if (instance) {
|
|
788
|
+
instance.status = "done";
|
|
789
|
+
const settle = {
|
|
790
|
+
node: suspension.node,
|
|
791
|
+
visit: instance.visit,
|
|
792
|
+
status: "done",
|
|
793
|
+
...ev.outRef !== void 0 ? { outRef: ev.outRef } : {}
|
|
794
|
+
};
|
|
795
|
+
instance.settle = settle;
|
|
796
|
+
state.nodes.get(suspension.node)?.settles.push(settle);
|
|
797
|
+
}
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
default: return;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
/** Fold a loaded journal (append order) into scheduler state. */
|
|
804
|
+
function foldGraphJournal(events, compiled) {
|
|
805
|
+
const state = emptyFoldState(compiled);
|
|
806
|
+
for (const ev of events) applyGraphFoldEvent(state, ev, compiled);
|
|
807
|
+
return state;
|
|
808
|
+
}
|
|
809
|
+
//#endregion
|
|
810
|
+
//#region src/runtime/graph/join.ts
|
|
811
|
+
const NOTHING = {
|
|
812
|
+
release: false,
|
|
813
|
+
consuming: [],
|
|
814
|
+
blocked: false
|
|
815
|
+
};
|
|
816
|
+
/** Decide whether a node's gating edges release it, and which of them the release consumes. */
|
|
817
|
+
function decideJoin(rule, gating) {
|
|
818
|
+
if (gating.length === 0) return NOTHING;
|
|
819
|
+
const settled = gating.filter((entry) => entry.folded && entry.folded.state !== "pending");
|
|
820
|
+
const satisfied = gating.filter((entry) => entry.folded?.state === "satisfied");
|
|
821
|
+
const failed = gating.filter((entry) => entry.folded?.state === "failed");
|
|
822
|
+
const allSettled = settled.length === gating.length;
|
|
823
|
+
switch (rule) {
|
|
824
|
+
case "all": {
|
|
825
|
+
const release = !gating.some((entry) => entry.folded?.state === "dead" || entry.folded?.state === "failed") && satisfied.length === gating.length;
|
|
826
|
+
return {
|
|
827
|
+
release,
|
|
828
|
+
consuming: release ? settled : [],
|
|
829
|
+
blocked: false
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
case "any": {
|
|
833
|
+
const first = satisfied[0];
|
|
834
|
+
if (first === void 0) return {
|
|
835
|
+
release: false,
|
|
836
|
+
consuming: [],
|
|
837
|
+
blocked: allSettled
|
|
838
|
+
};
|
|
839
|
+
return {
|
|
840
|
+
release: true,
|
|
841
|
+
consuming: [first],
|
|
842
|
+
blocked: false
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
case "any_failed": {
|
|
846
|
+
const first = failed[0];
|
|
847
|
+
if (first === void 0) return {
|
|
848
|
+
release: false,
|
|
849
|
+
consuming: [],
|
|
850
|
+
blocked: allSettled
|
|
851
|
+
};
|
|
852
|
+
return {
|
|
853
|
+
release: true,
|
|
854
|
+
consuming: [first],
|
|
855
|
+
blocked: false
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
case "all_done": return {
|
|
859
|
+
release: allSettled,
|
|
860
|
+
consuming: allSettled ? settled : [],
|
|
861
|
+
blocked: false
|
|
862
|
+
};
|
|
863
|
+
default: return NOTHING;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
//#endregion
|
|
867
|
+
//#region src/runtime/graph/kinds.ts
|
|
868
|
+
/**
|
|
869
|
+
* One profile, one run: the kernel's leaf, exactly as `supervise()` derives it from `backend`.
|
|
870
|
+
* The model cannot decide this — it is what gets run.
|
|
871
|
+
*/
|
|
872
|
+
function agentKind(defaults) {
|
|
873
|
+
return {
|
|
874
|
+
id: "agent",
|
|
875
|
+
version: 1,
|
|
876
|
+
description: "One AgentProfile run as a leaf on a backend; the kernel derives the executor.",
|
|
877
|
+
validateConfig: (raw, context) => {
|
|
878
|
+
const config = asRecord(raw, `${context}: agent config`);
|
|
879
|
+
return {
|
|
880
|
+
...config.backend !== void 0 ? { backend: config.backend } : {},
|
|
881
|
+
...config.deliverable !== void 0 ? { deliverable: config.deliverable } : {}
|
|
882
|
+
};
|
|
883
|
+
},
|
|
884
|
+
configSchema: {
|
|
885
|
+
type: "object",
|
|
886
|
+
properties: {
|
|
887
|
+
backend: { type: "object" },
|
|
888
|
+
deliverable: { type: "object" }
|
|
889
|
+
},
|
|
890
|
+
additionalProperties: false
|
|
891
|
+
},
|
|
892
|
+
inputs: [],
|
|
893
|
+
outputs: [],
|
|
894
|
+
effects: [],
|
|
895
|
+
onCrash: "restart",
|
|
896
|
+
budget: "metered",
|
|
897
|
+
run: ({ config, profile, spawn }) => {
|
|
898
|
+
const backend = config.backend ?? defaults.backend;
|
|
899
|
+
if (!backend) throw new ValidationError(`agent kind: node ${JSON.stringify(profile.name)} has no backend — set config.backend or the engine default`);
|
|
900
|
+
return workerFromBackend(backend, config.deliverable ?? defaults.deliverable)(profile, spawn);
|
|
901
|
+
}
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* The thing that DECIDES: a nested `supervisorAgent` with the coordination verbs. Its children
|
|
906
|
+
* are its own tree — the graph sees one node in, one `Settled` out. A `subgraph` constrains what
|
|
907
|
+
* it may spawn; without one it is free-form under `profileSecurity` and `allowedModels`.
|
|
908
|
+
*/
|
|
909
|
+
function supervisorKind(deps) {
|
|
910
|
+
return {
|
|
911
|
+
id: "supervisor",
|
|
912
|
+
version: 1,
|
|
913
|
+
description: "A nested supervisor: spawns, observes, steers and awaits its own children with the coordination verbs.",
|
|
914
|
+
validateConfig: (raw, context) => {
|
|
915
|
+
const config = asRecord(raw, `${context}: supervisor config`);
|
|
916
|
+
return {
|
|
917
|
+
perWorker: asRecord(config.perWorker, `${context}: supervisor config.perWorker`),
|
|
918
|
+
...config.maxLiveWorkers !== void 0 ? { maxLiveWorkers: Number(config.maxLiveWorkers) } : {}
|
|
919
|
+
};
|
|
920
|
+
},
|
|
921
|
+
configSchema: {
|
|
922
|
+
type: "object",
|
|
923
|
+
properties: {
|
|
924
|
+
perWorker: { type: "object" },
|
|
925
|
+
maxLiveWorkers: { type: "integer" }
|
|
926
|
+
},
|
|
927
|
+
required: ["perWorker"],
|
|
928
|
+
additionalProperties: false
|
|
929
|
+
},
|
|
930
|
+
inputs: [],
|
|
931
|
+
outputs: [],
|
|
932
|
+
effects: [],
|
|
933
|
+
onCrash: "restart",
|
|
934
|
+
budget: "metered",
|
|
935
|
+
run: ({ config, profile }) => supervisorAgent(profile, {
|
|
936
|
+
blobs: deps.blobs,
|
|
937
|
+
makeWorkerAgent: deps.makeWorkerAgent,
|
|
938
|
+
perWorker: config.perWorker,
|
|
939
|
+
...config.maxLiveWorkers !== void 0 ? { maxLiveWorkers: config.maxLiveWorkers } : {},
|
|
940
|
+
...deps.router ? { router: deps.router } : {},
|
|
941
|
+
...deps.driveHarness ? { driveHarness: deps.driveHarness } : {}
|
|
942
|
+
})
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
/** The script kind's handle; it also names the kind in every script node's identity. */
|
|
946
|
+
const SCRIPT = {
|
|
947
|
+
id: "script",
|
|
948
|
+
version: 1
|
|
949
|
+
};
|
|
950
|
+
/**
|
|
951
|
+
* Caller code as a node. The one kind with no kernel primitive behind it: the kernel has no
|
|
952
|
+
* "data→data with no execution" concept (agent-runtime#970 fact-finding), so this is new. It is
|
|
953
|
+
* still a leaf `Agent` carrying an `Executor`, so the journal, the gate and the pool treat it like
|
|
954
|
+
* any other node.
|
|
955
|
+
*/
|
|
956
|
+
function scriptKind() {
|
|
957
|
+
return {
|
|
958
|
+
...SCRIPT,
|
|
959
|
+
description: "Run caller code over the resolved inputs; pure scripts are exempt and restorable.",
|
|
960
|
+
validateConfig: (raw, context) => {
|
|
961
|
+
const config = asRecord(raw, `${context}: script config`);
|
|
962
|
+
if (typeof config.body !== "function") throw new ValidationError(`${context}: script config.body must be a function`);
|
|
963
|
+
if (config.pure !== void 0 && typeof config.pure !== "boolean") throw new ValidationError(`${context}: script config.pure must be a boolean`);
|
|
964
|
+
if (config.pure === true && config.spent !== void 0) throw new ValidationError(`${context}: a pure script is budget-exempt and cannot report spent`);
|
|
965
|
+
return {
|
|
966
|
+
body: config.body,
|
|
967
|
+
...config.pure !== void 0 ? { pure: config.pure } : {},
|
|
968
|
+
...config.spent !== void 0 ? { spent: config.spent } : {}
|
|
969
|
+
};
|
|
970
|
+
},
|
|
971
|
+
configSchema: {
|
|
972
|
+
type: "object",
|
|
973
|
+
properties: {
|
|
974
|
+
pure: { type: "boolean" },
|
|
975
|
+
spent: { type: "object" }
|
|
976
|
+
},
|
|
977
|
+
additionalProperties: true
|
|
978
|
+
},
|
|
979
|
+
inputs: [],
|
|
980
|
+
outputs: [],
|
|
981
|
+
effects: [],
|
|
982
|
+
onCrash: "restart",
|
|
983
|
+
budget: "metered",
|
|
984
|
+
run: ({ config, profile, inputs }) => scriptAgent(profile, config, inputs, SCRIPT)
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
function scriptAgent(profile, config, inputs, kind) {
|
|
988
|
+
let artifact;
|
|
989
|
+
const spec = {
|
|
990
|
+
profile,
|
|
991
|
+
harness: null,
|
|
992
|
+
executor: {
|
|
993
|
+
runtime: "inline",
|
|
994
|
+
...config.pure ? { budgetExempt: true } : {},
|
|
995
|
+
async execute(_task, signal) {
|
|
996
|
+
const startedAt = Date.now();
|
|
997
|
+
const out = await config.body(inputs, signal);
|
|
998
|
+
const ms = Date.now() - startedAt;
|
|
999
|
+
const spent = config.pure ? {
|
|
1000
|
+
iterations: 0,
|
|
1001
|
+
tokens: {
|
|
1002
|
+
input: 0,
|
|
1003
|
+
output: 0
|
|
1004
|
+
},
|
|
1005
|
+
usd: 0,
|
|
1006
|
+
ms
|
|
1007
|
+
} : config.spent ?? {
|
|
1008
|
+
iterations: 1,
|
|
1009
|
+
tokens: {
|
|
1010
|
+
input: 0,
|
|
1011
|
+
output: 0,
|
|
1012
|
+
tokensKnown: false
|
|
1013
|
+
},
|
|
1014
|
+
tokensKnown: false,
|
|
1015
|
+
usd: 0,
|
|
1016
|
+
usdKnown: false,
|
|
1017
|
+
ms
|
|
1018
|
+
};
|
|
1019
|
+
artifact = {
|
|
1020
|
+
outRef: contentAddress(out),
|
|
1021
|
+
out,
|
|
1022
|
+
spent
|
|
1023
|
+
};
|
|
1024
|
+
return artifact;
|
|
1025
|
+
},
|
|
1026
|
+
teardown: () => Promise.resolve({ destroyed: true }),
|
|
1027
|
+
resultArtifact() {
|
|
1028
|
+
if (!artifact) throw new ValidationError("script: resultArtifact() read before execute()");
|
|
1029
|
+
return artifact;
|
|
1030
|
+
}
|
|
1031
|
+
},
|
|
1032
|
+
execution: { correlation: { nodeKind: formatRegistryHandle(kind) } }
|
|
1033
|
+
};
|
|
1034
|
+
return {
|
|
1035
|
+
name: profile.name ?? "script",
|
|
1036
|
+
act: () => Promise.reject(new ValidationError("script: act() is not the execution path")),
|
|
1037
|
+
executorSpec: spec
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
/** A node carrying its own graph: it runs as a full engine run on the host's kinds and effects. */
|
|
1041
|
+
function subgraphKind() {
|
|
1042
|
+
return {
|
|
1043
|
+
id: "subgraph",
|
|
1044
|
+
version: 1,
|
|
1045
|
+
description: "A node that runs its own graph; constrains a supervisor at depth>1.",
|
|
1046
|
+
validateConfig: (raw, context) => {
|
|
1047
|
+
const config = asRecord(raw, `${context}: subgraph config`);
|
|
1048
|
+
if (config.graph === void 0) throw new ValidationError(`${context}: subgraph config.graph is required`);
|
|
1049
|
+
return {
|
|
1050
|
+
graph: config.graph,
|
|
1051
|
+
...config.budget === void 0 ? {} : { budget: config.budget },
|
|
1052
|
+
...config.perNode === void 0 ? {} : { perNode: config.perNode }
|
|
1053
|
+
};
|
|
1054
|
+
},
|
|
1055
|
+
configSchema: {
|
|
1056
|
+
type: "object",
|
|
1057
|
+
properties: { graph: { type: "object" } },
|
|
1058
|
+
required: ["graph"]
|
|
1059
|
+
},
|
|
1060
|
+
inputs: [],
|
|
1061
|
+
outputs: [],
|
|
1062
|
+
effects: [],
|
|
1063
|
+
onCrash: "restart",
|
|
1064
|
+
budget: "metered",
|
|
1065
|
+
run: ({ config, profile, host }) => {
|
|
1066
|
+
const name = profile.name ?? "subgraph";
|
|
1067
|
+
if (!host) throw new ValidationError(`subgraph kind: node ${JSON.stringify(name)} needs its hosting engine; run it through the scheduler, which supplies one`);
|
|
1068
|
+
let artifact;
|
|
1069
|
+
return {
|
|
1070
|
+
name,
|
|
1071
|
+
act: () => Promise.reject(new ValidationError("subgraph: act() is not the execution path")),
|
|
1072
|
+
executorSpec: {
|
|
1073
|
+
profile,
|
|
1074
|
+
harness: null,
|
|
1075
|
+
executor: {
|
|
1076
|
+
runtime: "inline",
|
|
1077
|
+
async execute(_task, signal) {
|
|
1078
|
+
const inner = await host.runNested(config.graph, name, {
|
|
1079
|
+
budget: config.budget ?? {
|
|
1080
|
+
maxIterations: 1,
|
|
1081
|
+
maxTokens: 0
|
|
1082
|
+
},
|
|
1083
|
+
...config.perNode === void 0 ? {} : { perNode: config.perNode },
|
|
1084
|
+
runId: `${name}:subgraph`,
|
|
1085
|
+
signal
|
|
1086
|
+
});
|
|
1087
|
+
const out = {
|
|
1088
|
+
kind: inner.kind,
|
|
1089
|
+
out: inner.out
|
|
1090
|
+
};
|
|
1091
|
+
artifact = {
|
|
1092
|
+
outRef: contentAddress(out),
|
|
1093
|
+
out,
|
|
1094
|
+
spent: {
|
|
1095
|
+
iterations: 1,
|
|
1096
|
+
tokens: {
|
|
1097
|
+
input: 0,
|
|
1098
|
+
output: 0
|
|
1099
|
+
},
|
|
1100
|
+
usd: 0,
|
|
1101
|
+
ms: 0
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
return artifact;
|
|
1105
|
+
},
|
|
1106
|
+
teardown: () => Promise.resolve({ destroyed: true }),
|
|
1107
|
+
resultArtifact: () => {
|
|
1108
|
+
if (!artifact) throw new ValidationError(`subgraph: resultArtifact() read before execute()`);
|
|
1109
|
+
return artifact;
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
function asRecord(value, context) {
|
|
1118
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ValidationError(`${context} must be an object`);
|
|
1119
|
+
return value;
|
|
1120
|
+
}
|
|
1121
|
+
//#endregion
|
|
1122
|
+
//#region src/runtime/graph/ledger.ts
|
|
1123
|
+
/** Open a ledger for one run; its ordinals continue past whatever a prior process recorded. */
|
|
1124
|
+
function createEdgeLedger(args) {
|
|
1125
|
+
const entries = [];
|
|
1126
|
+
let seq = args.startSeq;
|
|
1127
|
+
return {
|
|
1128
|
+
entries,
|
|
1129
|
+
async record(edge, traversal, outcome, reason) {
|
|
1130
|
+
const spec = edge.spec;
|
|
1131
|
+
const entry = {
|
|
1132
|
+
edge: edge.id,
|
|
1133
|
+
kind: spec.kind,
|
|
1134
|
+
from: spec.from.node,
|
|
1135
|
+
to: spec.to.node,
|
|
1136
|
+
traversal,
|
|
1137
|
+
outcome,
|
|
1138
|
+
...spec.directive !== void 0 ? { directive: `${spec.directive.surface}/v${spec.directive.version}` } : {},
|
|
1139
|
+
...spec.kind === "data" ? { port: edge.toPort } : {},
|
|
1140
|
+
...reason !== void 0 ? { reason } : {}
|
|
1141
|
+
};
|
|
1142
|
+
entries.push(entry);
|
|
1143
|
+
await args.journal.appendEvent(args.runId, {
|
|
1144
|
+
kind: "edge",
|
|
1145
|
+
id: `graph:${spec.to.node}`,
|
|
1146
|
+
edge: {
|
|
1147
|
+
kind: spec.kind,
|
|
1148
|
+
from: spec.from.node,
|
|
1149
|
+
to: spec.to.node,
|
|
1150
|
+
...entry.directive !== void 0 ? { directive: entry.directive } : {},
|
|
1151
|
+
...entry.port !== void 0 ? { port: entry.port } : {}
|
|
1152
|
+
},
|
|
1153
|
+
traversal,
|
|
1154
|
+
outcome,
|
|
1155
|
+
bytes: 0,
|
|
1156
|
+
...reason !== void 0 ? { reason } : {},
|
|
1157
|
+
seq: seq++,
|
|
1158
|
+
at: new Date(args.now()).toISOString()
|
|
1159
|
+
});
|
|
1160
|
+
}
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
//#endregion
|
|
1164
|
+
//#region src/runtime/graph/preset-run-graph.ts
|
|
1165
|
+
/**
|
|
1166
|
+
* `runGraph` as an engine graph (agent-runtime#982, #975) — a COMPILER, not a second runtime.
|
|
1167
|
+
*
|
|
1168
|
+
* `graphFromRunGraph` lowers today's `AgentGraph` into the engine's vocabulary: one supervisor
|
|
1169
|
+
* root carrying the graph, one pinned `agent` node per worker, the authored `delegates`/`analyzes`
|
|
1170
|
+
* edges. That gives a `runGraph` consumer a first-class engine graph it can inspect, diff, and use
|
|
1171
|
+
* as the starting point for authoring one natively — the migration path #975 asked for.
|
|
1172
|
+
*
|
|
1173
|
+
* WHAT THIS DELIBERATELY DOES NOT DO: run it. `runGraph` executes through `superviseAgentGraph`,
|
|
1174
|
+
* exactly as it always has. An earlier version of this module wrapped that call in a one-node
|
|
1175
|
+
* engine run, which read as "runGraph runs on the engine" while changing nothing about execution
|
|
1176
|
+
* and costing a second journal tree, a second budget pool and a second `Scope`. A wrapper that
|
|
1177
|
+
* moves no behaviour is a second source of truth, so it is gone: the graph a consumer runs and the
|
|
1178
|
+
* graph they can inspect are produced from the same `AgentGraph`, and only one of them executes.
|
|
1179
|
+
*
|
|
1180
|
+
* The engine EXECUTES a graph a consumer authors directly (`runEngineGraph`), where nodes are
|
|
1181
|
+
* scheduled over `data` edges, guards decide traversal, and the fold makes it restartable.
|
|
1182
|
+
*/
|
|
1183
|
+
/** The kind id the root node carries: a supervisor holding the whole `AgentGraph`. */
|
|
1184
|
+
const RUN_GRAPH_ROOT_KIND = "supervisor/v1";
|
|
1185
|
+
/**
|
|
1186
|
+
* Compile an `AgentGraph` into the engine graph that describes it. Pure: nothing runs, nothing is
|
|
1187
|
+
* registered, no executor is built. A `delegates` edge is MODEL-fired (#971) — its target is
|
|
1188
|
+
* spawned by the supervisor through the coordination protocol — so every worker node is marked
|
|
1189
|
+
* `entry: false`, which is exactly what the engine's scheduler would honour if this graph were
|
|
1190
|
+
* handed to it.
|
|
1191
|
+
*/
|
|
1192
|
+
function graphFromRunGraph(graph, options) {
|
|
1193
|
+
const root = graph.nodes[0];
|
|
1194
|
+
if (root === void 0) throw new ValidationError("graphFromRunGraph: a graph needs a root node");
|
|
1195
|
+
return {
|
|
1196
|
+
nodes: graph.nodes.map((node, index) => index === 0 ? {
|
|
1197
|
+
id: node.id,
|
|
1198
|
+
kind: RUN_GRAPH_ROOT_KIND,
|
|
1199
|
+
config: {
|
|
1200
|
+
perWorker: options.perWorker ?? graph.budget,
|
|
1201
|
+
...options.maxLiveWorkers === void 0 ? {} : { maxLiveWorkers: options.maxLiveWorkers }
|
|
1202
|
+
},
|
|
1203
|
+
profile: node.profile,
|
|
1204
|
+
budget: graph.budget,
|
|
1205
|
+
terminal: true,
|
|
1206
|
+
deliverable: graph.deliverable
|
|
1207
|
+
} : {
|
|
1208
|
+
id: node.id,
|
|
1209
|
+
kind: "agent/v1",
|
|
1210
|
+
profile: node.profile,
|
|
1211
|
+
entry: false,
|
|
1212
|
+
terminal: false,
|
|
1213
|
+
budget: options.perWorker ?? graph.budget
|
|
1214
|
+
}),
|
|
1215
|
+
edges: graph.edges.flatMap((edge) => edge.kind === "delegates" ? [{
|
|
1216
|
+
kind: "delegates",
|
|
1217
|
+
from: { node: edge.from },
|
|
1218
|
+
to: { node: edge.to },
|
|
1219
|
+
directive: edge.directive,
|
|
1220
|
+
...edge.maxTraversals !== void 0 ? { maxTraversals: edge.maxTraversals } : {}
|
|
1221
|
+
}] : edge.over.map((source) => ({
|
|
1222
|
+
kind: "analyzes",
|
|
1223
|
+
from: {
|
|
1224
|
+
node: source,
|
|
1225
|
+
port: "trace"
|
|
1226
|
+
},
|
|
1227
|
+
to: { node: edge.to },
|
|
1228
|
+
directive: edge.directive,
|
|
1229
|
+
...edge.maxTraversals !== void 0 ? { maxTraversals: edge.maxTraversals } : {}
|
|
1230
|
+
}))),
|
|
1231
|
+
root: root.id,
|
|
1232
|
+
deliverable: graph.deliverable
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
//#endregion
|
|
1236
|
+
//#region src/runtime/graph/admit.ts
|
|
1237
|
+
/**
|
|
1238
|
+
* Edge payload admission (agent-runtime#971): every value crossing an edge is JSON round-tripped,
|
|
1239
|
+
* `undefined` stripped to absence, and a non-representable value (a cycle, a BigInt, a function)
|
|
1240
|
+
* becomes a RECORD of that fact. This is the kernel's existing findings-guard rule, and it is what
|
|
1241
|
+
* makes `inputRef` stable and `onCrash: 'restart'` well defined — a degraded record beats a
|
|
1242
|
+
* vanished edge.
|
|
1243
|
+
*/
|
|
1244
|
+
function admitPayload(value) {
|
|
1245
|
+
if (value === void 0) return void 0;
|
|
1246
|
+
try {
|
|
1247
|
+
const text = JSON.stringify(value);
|
|
1248
|
+
if (text === void 0) return { nonCanonical: `payload of type ${typeof value}` };
|
|
1249
|
+
return JSON.parse(text);
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
return { nonCanonical: error instanceof Error ? error.message : String(error) };
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
//#endregion
|
|
1255
|
+
//#region src/runtime/graph/result.ts
|
|
1256
|
+
/**
|
|
1257
|
+
* Turning a finished run into its result: rehydrate each settle's output, reduce the terminals
|
|
1258
|
+
* through the kernel's finalizer seam, and name the honest cause when nothing delivered
|
|
1259
|
+
* (agent-runtime#973). Separate from the loop so "what happened" is readable without reading
|
|
1260
|
+
* "what ran".
|
|
1261
|
+
*/
|
|
1262
|
+
function resolveFinalizer(choice) {
|
|
1263
|
+
if (choice === void 0 || choice === "bestDelivered") return bestDelivered;
|
|
1264
|
+
if (choice === "collectDelivered") return collectDelivered;
|
|
1265
|
+
return choice;
|
|
1266
|
+
}
|
|
1267
|
+
/** Every node settlement with its output rehydrated and its completion check applied. */
|
|
1268
|
+
async function materializeSettles(compiled, state, blobs, outCache) {
|
|
1269
|
+
const rehydrate = async (settle) => {
|
|
1270
|
+
if (settle.out !== void 0 || settle.outRef === void 0) return settle;
|
|
1271
|
+
const out = outCache.get(settle.outRef) ?? admitPayload(await blobs.get(settle.outRef));
|
|
1272
|
+
const node = compiled.nodes.get(settle.node);
|
|
1273
|
+
let valid = settle.valid;
|
|
1274
|
+
if (valid === void 0 && node?.deliverable !== void 0 && settle.status === "done") try {
|
|
1275
|
+
valid = await node.deliverable.check(out);
|
|
1276
|
+
} catch {
|
|
1277
|
+
valid = false;
|
|
1278
|
+
}
|
|
1279
|
+
return {
|
|
1280
|
+
...settle,
|
|
1281
|
+
out,
|
|
1282
|
+
...valid !== void 0 ? { valid } : {}
|
|
1283
|
+
};
|
|
1284
|
+
};
|
|
1285
|
+
return Promise.all([...compiled.nodes.keys()].flatMap((id) => state.nodes.get(id)?.settles ?? []).map(rehydrate));
|
|
1286
|
+
}
|
|
1287
|
+
/** Turn a finished run into its result: rehydrate, reduce the terminals, classify a no-winner. */
|
|
1288
|
+
async function assembleGraphResult(args) {
|
|
1289
|
+
const settles = await materializeSettles(args.compiled, args.state, args.blobs, args.outCache);
|
|
1290
|
+
const terminals = settles.filter((settle) => args.compiled.nodes.get(settle.node)?.terminal);
|
|
1291
|
+
const ledger = args.ledger;
|
|
1292
|
+
const finish = (result) => {
|
|
1293
|
+
if (result.kind === "no-winner" && args.state.exhaustedEdges.size > 0) throw new GraphEdgeCapError(Object.freeze([...args.state.exhaustedEdges]), Object.freeze([...ledger]), result);
|
|
1294
|
+
return result;
|
|
1295
|
+
};
|
|
1296
|
+
if (args.failure) return finish({
|
|
1297
|
+
kind: "no-winner",
|
|
1298
|
+
reason: args.failure.reason,
|
|
1299
|
+
...args.failure.error ? { error: args.failure.error } : {},
|
|
1300
|
+
terminals,
|
|
1301
|
+
settles,
|
|
1302
|
+
ledger,
|
|
1303
|
+
unreachable: []
|
|
1304
|
+
});
|
|
1305
|
+
const allTerminalsSettled = args.compiled.terminals.every((id) => (args.state.nodes.get(id)?.settles.length ?? 0) > 0);
|
|
1306
|
+
const pendingTokens = [...args.state.suspensions.values()].filter((suspension) => suspension.status === "pending").map((suspension) => suspension.token);
|
|
1307
|
+
if (pendingTokens.length > 0 && !allTerminalsSettled) return {
|
|
1308
|
+
kind: "suspended",
|
|
1309
|
+
tokens: pendingTokens,
|
|
1310
|
+
terminals,
|
|
1311
|
+
settles,
|
|
1312
|
+
ledger
|
|
1313
|
+
};
|
|
1314
|
+
if (args.aborted) return finish({
|
|
1315
|
+
kind: "no-winner",
|
|
1316
|
+
reason: "aborted",
|
|
1317
|
+
terminals,
|
|
1318
|
+
settles,
|
|
1319
|
+
ledger,
|
|
1320
|
+
unreachable: []
|
|
1321
|
+
});
|
|
1322
|
+
const out = terminals.filter((settle) => settle.status === "done" && settle.valid !== false).length === 0 ? void 0 : await runFinalizer(resolveFinalizer(args.finalizer), {
|
|
1323
|
+
settled: terminals.map((settle) => ({
|
|
1324
|
+
id: settle.node,
|
|
1325
|
+
status: settle.status,
|
|
1326
|
+
valid: settle.status === "done" && settle.valid !== false,
|
|
1327
|
+
...settle.outRef !== void 0 ? { outRef: settle.outRef } : {}
|
|
1328
|
+
})),
|
|
1329
|
+
blobs: args.blobs,
|
|
1330
|
+
tree: args.scope.view,
|
|
1331
|
+
budget: args.scope.budget
|
|
1332
|
+
});
|
|
1333
|
+
if (out !== void 0) return {
|
|
1334
|
+
kind: "winner",
|
|
1335
|
+
out,
|
|
1336
|
+
terminals,
|
|
1337
|
+
settles,
|
|
1338
|
+
ledger
|
|
1339
|
+
};
|
|
1340
|
+
const unreachable = [...args.compiled.nodes.keys()].filter((id) => (args.state.nodes.get(id)?.settles.length ?? 0) === 0);
|
|
1341
|
+
return finish({
|
|
1342
|
+
kind: "no-winner",
|
|
1343
|
+
reason: args.compiled.terminals.some((id) => unreachable.includes(id)) ? unreachable.length === args.compiled.nodes.size ? "budget-exhausted" : "unreachable-terminal" : "all-children-down",
|
|
1344
|
+
terminals,
|
|
1345
|
+
settles,
|
|
1346
|
+
ledger,
|
|
1347
|
+
unreachable
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
//#endregion
|
|
1351
|
+
//#region src/runtime/graph/run-context.ts
|
|
1352
|
+
/**
|
|
1353
|
+
* Opening a graph run: begin or resume the journaled tree, rebuild the pool and the kernel `Scope`
|
|
1354
|
+
* on the SAME recipe the kernel supervisor uses for its own resume, and fold the prior journal
|
|
1355
|
+
* into scheduler state. Extracted so the restart contract is one readable unit rather than a
|
|
1356
|
+
* preamble inside the loop.
|
|
1357
|
+
*/
|
|
1358
|
+
/** Engine-appended `woken` ordinals start here — far above any kernel cursor counter, so the two
|
|
1359
|
+
* counters can advance independently without ever colliding. */
|
|
1360
|
+
const ENGINE_WOKEN_SEQ_BASE = 1e7;
|
|
1361
|
+
/** Begin or resume a run's journaled tree, pool, scope and folded state. */
|
|
1362
|
+
async function openGraphRun(args) {
|
|
1363
|
+
const journal = args.journal ?? new InMemorySpawnJournal();
|
|
1364
|
+
const blobs = args.blobs ?? new InMemoryResultBlobStore();
|
|
1365
|
+
const loaded = await journal.loadTree(args.runId);
|
|
1366
|
+
if (loaded !== void 0 && args.resume !== true) throw new ValidationError(`runEngineGraph: runId '${args.runId}' already exists; pass resume: true to continue it or use a new runId`);
|
|
1367
|
+
const prior = loaded ?? [];
|
|
1368
|
+
const resuming = args.resume === true && prior.length > 0;
|
|
1369
|
+
let runEpochMs = args.now();
|
|
1370
|
+
let rootBudget = args.budget;
|
|
1371
|
+
if (loaded === void 0) await journal.beginTree(args.runId, new Date(runEpochMs).toISOString());
|
|
1372
|
+
if (resuming) {
|
|
1373
|
+
const root = prior.find((ev) => ev.kind === "spawned" && ev.id === args.runId);
|
|
1374
|
+
if (root?.kind === "spawned") {
|
|
1375
|
+
runEpochMs = Date.parse(root.at);
|
|
1376
|
+
rootBudget = root.budget;
|
|
1377
|
+
}
|
|
1378
|
+
} else await journal.appendEvent(args.runId, {
|
|
1379
|
+
kind: "spawned",
|
|
1380
|
+
id: args.runId,
|
|
1381
|
+
label: "graph-root",
|
|
1382
|
+
budget: args.budget,
|
|
1383
|
+
runtime: "inline",
|
|
1384
|
+
seq: 0,
|
|
1385
|
+
at: new Date(runEpochMs).toISOString()
|
|
1386
|
+
});
|
|
1387
|
+
const elapsed = () => args.now() - runEpochMs;
|
|
1388
|
+
const measured = resuming ? sumMeasuredSpendFromEvents([...prior]) : void 0;
|
|
1389
|
+
const pool = createBudgetPool(rootBudget, elapsed, measured === void 0 ? void 0 : {
|
|
1390
|
+
committed: addSpend(measured.childWork, measured.driverInference),
|
|
1391
|
+
uncertainReservations: uncertainSpawnBudgets([...prior]),
|
|
1392
|
+
...rootBudget.deadlineMs !== void 0 ? { absoluteDeadlineMs: runEpochMs + rootBudget.deadlineMs } : {}
|
|
1393
|
+
});
|
|
1394
|
+
const abort = new AbortController();
|
|
1395
|
+
if (args.signal !== void 0) {
|
|
1396
|
+
const forward = () => abort.abort(args.signal?.reason);
|
|
1397
|
+
args.signal.addEventListener("abort", forward, { once: true });
|
|
1398
|
+
args.onAbort(() => args.signal?.removeEventListener("abort", forward));
|
|
1399
|
+
if (args.signal.aborted) abort.abort(args.signal.reason);
|
|
1400
|
+
}
|
|
1401
|
+
const scope = createScope({
|
|
1402
|
+
parentId: args.runId,
|
|
1403
|
+
root: args.runId,
|
|
1404
|
+
pool,
|
|
1405
|
+
journal,
|
|
1406
|
+
blobs,
|
|
1407
|
+
executors: createExecutorRegistry(),
|
|
1408
|
+
seams: {},
|
|
1409
|
+
depth: 0,
|
|
1410
|
+
signal: abort.signal,
|
|
1411
|
+
now: args.now,
|
|
1412
|
+
...resuming ? { resumeFrom: {
|
|
1413
|
+
settled: await replaySpawnTree(journal, blobs, args.runId),
|
|
1414
|
+
view: materializeTreeView([...prior]),
|
|
1415
|
+
maxSpawnOrdinal: maxSeqOf([...prior], (ev) => ev.kind === "spawned"),
|
|
1416
|
+
maxCursorSeq: maxSeqOf([...prior], closesCursorSlot),
|
|
1417
|
+
maxWaitOrdinal: maxSeqOf([...prior], (ev) => ev.kind === "waiting"),
|
|
1418
|
+
waits: pendingWaits([...prior]),
|
|
1419
|
+
keys: /* @__PURE__ */ new Map(),
|
|
1420
|
+
priorSpend: sumMeasuredSpendFromEvents([...prior])
|
|
1421
|
+
} } : {}
|
|
1422
|
+
});
|
|
1423
|
+
const state = emptyFoldState(args.compiled);
|
|
1424
|
+
if (resuming) for (const ev of prior) applyGraphFoldEvent(state, ev, args.compiled);
|
|
1425
|
+
return {
|
|
1426
|
+
runId: args.runId,
|
|
1427
|
+
journal,
|
|
1428
|
+
blobs,
|
|
1429
|
+
scope,
|
|
1430
|
+
abort,
|
|
1431
|
+
state,
|
|
1432
|
+
resuming,
|
|
1433
|
+
prior,
|
|
1434
|
+
engineSeq: resuming ? maxEngineSeq(prior) + 1 : 0,
|
|
1435
|
+
engineWokenSeq: ENGINE_WOKEN_SEQ_BASE + (resuming ? prior.filter((ev) => ev.kind === "woken" && ev.seq >= 1e7).length : 0),
|
|
1436
|
+
ledgerSeq: prior.filter((ev) => ev.kind === "edge").length
|
|
1437
|
+
};
|
|
1438
|
+
}
|
|
1439
|
+
function maxEngineSeq(events) {
|
|
1440
|
+
let max = -1;
|
|
1441
|
+
for (const ev of events) if ((ev.kind === "node-inputs-resolved" || ev.kind === "edge-verdict" || ev.kind === "join-state" || ev.kind === "waiting" && ev.spec.kind === "token") && ev.seq > max) max = ev.seq;
|
|
1442
|
+
return max;
|
|
1443
|
+
}
|
|
1444
|
+
//#endregion
|
|
1445
|
+
//#region src/runtime/graph/suspension.ts
|
|
1446
|
+
/**
|
|
1447
|
+
* Suspensions (agent-runtime#976): a node parks on a host wake as the kernel's `waiting`/`woken`
|
|
1448
|
+
* pair. The engine owns the transition table; a host owns only how the wake arrives.
|
|
1449
|
+
*/
|
|
1450
|
+
const SUSPEND_MARK = "__graphSuspension";
|
|
1451
|
+
/** Build a suspension request. `wait` never expires; `fail` settles the node down at its deadline;
|
|
1452
|
+
* `default` resolves with the given payload. */
|
|
1453
|
+
function suspended(options = {}) {
|
|
1454
|
+
const onExpire = options.onExpire ?? "wait";
|
|
1455
|
+
if (onExpire !== "wait" && options.expiresInMs === void 0) throw new ValidationError(`suspended: onExpire '${onExpire}' requires expiresInMs`);
|
|
1456
|
+
if (onExpire === "wait" && options.expiresInMs !== void 0) throw new ValidationError("suspended: onExpire 'wait' never expires — remove expiresInMs");
|
|
1457
|
+
if (onExpire === "default" && options.default === void 0) throw new ValidationError("suspended: onExpire 'default' requires a default payload");
|
|
1458
|
+
return {
|
|
1459
|
+
[SUSPEND_MARK]: true,
|
|
1460
|
+
onExpire,
|
|
1461
|
+
...options.expiresInMs !== void 0 ? { expiresInMs: options.expiresInMs } : {},
|
|
1462
|
+
...options.default !== void 0 ? { default: options.default } : {}
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
/** Whether a node's output is a park request rather than its result. */
|
|
1466
|
+
function isSuspensionRequest(value) {
|
|
1467
|
+
return typeof value === "object" && value !== null && value[SUSPEND_MARK] === true;
|
|
1468
|
+
}
|
|
1469
|
+
/** Content-addressed over the run identity, so a restart recomputes it and needs no token table. */
|
|
1470
|
+
function mintSuspensionToken(runId, instance) {
|
|
1471
|
+
return contentAddress({
|
|
1472
|
+
runId,
|
|
1473
|
+
instance,
|
|
1474
|
+
kind: "graph-suspension"
|
|
1475
|
+
});
|
|
1476
|
+
}
|
|
1477
|
+
/** The journal id one suspension's `waiting`/`woken` pair shares. */
|
|
1478
|
+
function suspensionNodeId(token) {
|
|
1479
|
+
return `graphwait:${token}`;
|
|
1480
|
+
}
|
|
1481
|
+
/** The token inside a suspension node id, or `undefined` for any other id. */
|
|
1482
|
+
function tokenFromSuspensionNodeId(id) {
|
|
1483
|
+
return id.startsWith("graphwait:") ? id.slice(10) : void 0;
|
|
1484
|
+
}
|
|
1485
|
+
//#endregion
|
|
1486
|
+
//#region src/runtime/graph/scheduler.ts
|
|
1487
|
+
/**
|
|
1488
|
+
* The engine scheduler (agent-runtime#980, durable per #974/#976): run a compiled graph by hosting
|
|
1489
|
+
* every node instance on one kernel `Scope`. The pool, the journal, the blob store and
|
|
1490
|
+
* cancellation are the kernel's; the scheduler owns only what a graph adds — releasing nodes over
|
|
1491
|
+
* guarded edges, delivering payloads and directives, the two cycle caps, and suspensions.
|
|
1492
|
+
*
|
|
1493
|
+
* DURABILITY — fold, never checkpoint. Every decision is journaled BEFORE its effect is visible
|
|
1494
|
+
* (blob-then-journal where a ref is minted), then applied to live state through the SAME reducer
|
|
1495
|
+
* (`applyGraphFoldEvent`) a restart replays the journal through. Kill the process at any journal
|
|
1496
|
+
* boundary and a restart re-enters the exact state: settled nodes restore from `outRef` and never
|
|
1497
|
+
* re-execute; a released-but-unspawned instance re-enters from its pinned `inputRef`; an in-flight
|
|
1498
|
+
* instance is in-doubt and re-enters per its kind's `onCrash`.
|
|
1499
|
+
*
|
|
1500
|
+
* The parts this file does NOT own, so it stays a loop and not a god object: payload admission
|
|
1501
|
+
* (`admit.ts`), the edge ledger (`ledger.ts`), the join rule (`join.ts`), suspension vocabulary
|
|
1502
|
+
* (`suspension.ts`), the journal/pool/scope bootstrap (`run-context.ts`), and result assembly
|
|
1503
|
+
* (`result.ts`).
|
|
1504
|
+
*/
|
|
1505
|
+
/** Run a graph to its result: `createGraphRun` awaited — the one-call form for a run that needs no
|
|
1506
|
+
* live host wakes. */
|
|
1507
|
+
async function runEngineGraph(engine, spec, task, options) {
|
|
1508
|
+
return createGraphRun(engine, spec, task, options).done;
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Start (or resume) a graph run and return its handle: await `done` for the result; deliver host
|
|
1512
|
+
* wakes through `resume`/`expire` while it runs (#976).
|
|
1513
|
+
*/
|
|
1514
|
+
function createGraphRun(engine, spec, task, options) {
|
|
1515
|
+
const compiled = asCompiled(engine, spec);
|
|
1516
|
+
const wakes = [];
|
|
1517
|
+
let signalWake = () => {};
|
|
1518
|
+
let finished = false;
|
|
1519
|
+
const done = runGraphLoop(engine, compiled, task, options, wakes, (fn) => {
|
|
1520
|
+
signalWake = fn;
|
|
1521
|
+
}).finally(() => {
|
|
1522
|
+
finished = true;
|
|
1523
|
+
});
|
|
1524
|
+
const queue = (token, payload, expire) => {
|
|
1525
|
+
if (finished) return Promise.reject(new ValidationError(`graph resume: run completed; start a new run over the same journal to wake '${token}'`));
|
|
1526
|
+
return new Promise((settle, fail) => {
|
|
1527
|
+
wakes.push({
|
|
1528
|
+
token,
|
|
1529
|
+
payload,
|
|
1530
|
+
expire,
|
|
1531
|
+
settle,
|
|
1532
|
+
fail
|
|
1533
|
+
});
|
|
1534
|
+
signalWake();
|
|
1535
|
+
});
|
|
1536
|
+
};
|
|
1537
|
+
return {
|
|
1538
|
+
done,
|
|
1539
|
+
resume: (token, payload) => queue(token, payload, false),
|
|
1540
|
+
expire: (token) => queue(token, void 0, true)
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
function asCompiled(engine, spec) {
|
|
1544
|
+
return "nodes" in spec && spec.nodes instanceof Map ? spec : compileGraph(engine, spec);
|
|
1545
|
+
}
|
|
1546
|
+
/** Everything a run must be able to satisfy before it spends anything. */
|
|
1547
|
+
function assertRunnable(engine, compiled, options) {
|
|
1548
|
+
const context = "runEngineGraph";
|
|
1549
|
+
for (const node of compiled.nodes.values()) {
|
|
1550
|
+
const missing = node.kind.effects.filter((name) => !(name in engine.effects));
|
|
1551
|
+
if (missing.length > 0) throw new ValidationError(`${context}: node ${node.id} needs effect(s) ${missing.join(", ")} the host did not provide`);
|
|
1552
|
+
if (node.spec.budget === void 0 && options.perNode === void 0) throw new ValidationError(`${context}: node ${node.id} declares no budget and options.perNode is absent — the engine invents no split`);
|
|
1553
|
+
}
|
|
1554
|
+
for (const edge of compiled.edges) if (isEngineFired(edge) && edge.spec.directive !== void 0 && options.prompts === void 0) throw new ValidationError(`${context}: edge ${edge.id} carries a directive but options.prompts is absent`);
|
|
1555
|
+
}
|
|
1556
|
+
async function runGraphLoop(engine, compiled, task, options, wakes, onWakeSignal) {
|
|
1557
|
+
assertRunnable(engine, compiled, options);
|
|
1558
|
+
const now = options.now ?? Date.now;
|
|
1559
|
+
const runId = options.runId ?? `graph:${contentAddress({ task }).slice(0, 18)}`;
|
|
1560
|
+
let detachOuterAbort = () => {};
|
|
1561
|
+
const context = await openGraphRun({
|
|
1562
|
+
compiled,
|
|
1563
|
+
runId,
|
|
1564
|
+
budget: options.budget,
|
|
1565
|
+
...options.journal !== void 0 ? { journal: options.journal } : {},
|
|
1566
|
+
...options.blobs !== void 0 ? { blobs: options.blobs } : {},
|
|
1567
|
+
now,
|
|
1568
|
+
...options.resume !== void 0 ? { resume: options.resume } : {},
|
|
1569
|
+
...options.signal !== void 0 ? { signal: options.signal } : {},
|
|
1570
|
+
onAbort: (detach) => {
|
|
1571
|
+
detachOuterAbort = detach;
|
|
1572
|
+
}
|
|
1573
|
+
});
|
|
1574
|
+
const { abort, blobs, journal, scope, state } = context;
|
|
1575
|
+
const ledger = createEdgeLedger({
|
|
1576
|
+
journal,
|
|
1577
|
+
runId,
|
|
1578
|
+
now,
|
|
1579
|
+
startSeq: context.ledgerSeq
|
|
1580
|
+
});
|
|
1581
|
+
let engineSeq = context.engineSeq;
|
|
1582
|
+
let wokenSeq = context.engineWokenSeq;
|
|
1583
|
+
const liveHandles = /* @__PURE__ */ new Map();
|
|
1584
|
+
const waitingForBudget = [];
|
|
1585
|
+
const outCache = /* @__PURE__ */ new Map();
|
|
1586
|
+
let liveCount = 0;
|
|
1587
|
+
let failure;
|
|
1588
|
+
/** Journal one engine event, then apply it through the reducer a restart will replay. */
|
|
1589
|
+
const emit = async (ev) => {
|
|
1590
|
+
await journal.appendEvent(runId, ev);
|
|
1591
|
+
applyGraphFoldEvent(state, ev, compiled);
|
|
1592
|
+
};
|
|
1593
|
+
const stamp = () => new Date(now()).toISOString();
|
|
1594
|
+
const fail = (reason, name, message) => {
|
|
1595
|
+
failure = {
|
|
1596
|
+
reason,
|
|
1597
|
+
error: {
|
|
1598
|
+
name,
|
|
1599
|
+
message
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
abort.abort(`${reason}: ${message}`);
|
|
1603
|
+
};
|
|
1604
|
+
/** The ONE entry path: spawn a released instance from its journaled envelope. Used by a fresh
|
|
1605
|
+
* release, a budget-parked retry, and a restart re-entry alike. */
|
|
1606
|
+
const spawnInstance = async (label) => {
|
|
1607
|
+
if (failure) return;
|
|
1608
|
+
const instance = state.instances.get(label);
|
|
1609
|
+
const node = instance === void 0 ? void 0 : compiled.nodes.get(instance.node);
|
|
1610
|
+
if (!instance || !node || instance.inputRef === void 0) throw new ValidationError(`runEngineGraph: instance ${label} has no journaled envelope`);
|
|
1611
|
+
const envelope = await blobs.get(instance.inputRef);
|
|
1612
|
+
if (envelope === void 0) throw new ValidationError(`runEngineGraph: envelope ${instance.inputRef} is not in the blob store`);
|
|
1613
|
+
const agent = node.kind.run({
|
|
1614
|
+
config: node.config,
|
|
1615
|
+
profile: {
|
|
1616
|
+
name: node.id,
|
|
1617
|
+
...node.spec.profile ?? {}
|
|
1618
|
+
},
|
|
1619
|
+
inputs: envelope.inputs,
|
|
1620
|
+
effects: narrowEffects(node.kind.effects, engine.effects, `runEngineGraph: node ${node.id}`),
|
|
1621
|
+
host: { runNested: (inner, task, opts) => runEngineGraph(engine, inner, task, {
|
|
1622
|
+
budget: opts.budget,
|
|
1623
|
+
...opts.perNode === void 0 ? {} : { perNode: opts.perNode },
|
|
1624
|
+
journal,
|
|
1625
|
+
blobs,
|
|
1626
|
+
...options.prompts === void 0 ? {} : { prompts: options.prompts },
|
|
1627
|
+
runId: `${runId}:${opts.runId}`,
|
|
1628
|
+
...opts.signal === void 0 ? {} : { signal: opts.signal },
|
|
1629
|
+
now
|
|
1630
|
+
}).then((result) => ({
|
|
1631
|
+
kind: result.kind,
|
|
1632
|
+
...result.kind === "winner" ? { out: result.out } : {}
|
|
1633
|
+
})) }
|
|
1634
|
+
});
|
|
1635
|
+
const budget = node.spec.budget ?? options.perNode;
|
|
1636
|
+
const spawned = scope.spawn(agent, envelope.task, {
|
|
1637
|
+
label,
|
|
1638
|
+
budget
|
|
1639
|
+
});
|
|
1640
|
+
if (spawned.ok) {
|
|
1641
|
+
liveCount += 1;
|
|
1642
|
+
liveHandles.set(spawned.handle.id, label);
|
|
1643
|
+
applyGraphFoldEvent(state, {
|
|
1644
|
+
kind: "spawned",
|
|
1645
|
+
id: spawned.handle.id,
|
|
1646
|
+
label,
|
|
1647
|
+
budget,
|
|
1648
|
+
runtime: "inline",
|
|
1649
|
+
seq: 0,
|
|
1650
|
+
at: ""
|
|
1651
|
+
}, compiled);
|
|
1652
|
+
return;
|
|
1653
|
+
}
|
|
1654
|
+
if (spawned.reason === "budget-exhausted" || spawned.reason === "max-live-workers") {
|
|
1655
|
+
waitingForBudget.push(label);
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
fail("driver-failed", "SpawnRefused", `node ${node.id}: ${spawned.reason}`);
|
|
1659
|
+
};
|
|
1660
|
+
/** Pin an instance's envelope (inputs + task) by content address; answers the instance label. */
|
|
1661
|
+
const openInstance = async (nodeId, visit, envelope) => {
|
|
1662
|
+
const label = `${nodeId}#${visit}`;
|
|
1663
|
+
const inputRef = contentAddress(envelope);
|
|
1664
|
+
await blobs.put(inputRef, envelope);
|
|
1665
|
+
await emit({
|
|
1666
|
+
kind: "node-inputs-resolved",
|
|
1667
|
+
id: label,
|
|
1668
|
+
node: nodeId,
|
|
1669
|
+
instance: label,
|
|
1670
|
+
inputRef,
|
|
1671
|
+
seq: engineSeq++,
|
|
1672
|
+
at: stamp()
|
|
1673
|
+
});
|
|
1674
|
+
return label;
|
|
1675
|
+
};
|
|
1676
|
+
const enterEntryNode = async (nodeId) => {
|
|
1677
|
+
const node = compiled.nodes.get(nodeId);
|
|
1678
|
+
const folded = state.nodes.get(nodeId);
|
|
1679
|
+
if (!node || !folded) return;
|
|
1680
|
+
const visit = folded.visits + 1;
|
|
1681
|
+
if (visit > node.maxVisits) return;
|
|
1682
|
+
await spawnInstance(await openInstance(nodeId, visit, {
|
|
1683
|
+
task,
|
|
1684
|
+
inputs: {}
|
|
1685
|
+
}));
|
|
1686
|
+
};
|
|
1687
|
+
/** Build the released instance's envelope from its wave: data payloads projected and admitted,
|
|
1688
|
+
* directives resolved, trace refs lined up — every consumption ledgered as it is taken. */
|
|
1689
|
+
const consumeWave = async (nodeId, consuming) => {
|
|
1690
|
+
const inputs = {};
|
|
1691
|
+
const directives = [];
|
|
1692
|
+
const traces = [];
|
|
1693
|
+
for (const { edge, folded } of consuming) {
|
|
1694
|
+
const spec = edge.spec;
|
|
1695
|
+
const traversal = (folded?.traversals ?? 0) + 1;
|
|
1696
|
+
if (spec.kind === "data" && folded?.state === "satisfied") {
|
|
1697
|
+
let payload = folded.payloadRef === void 0 ? void 0 : outCache.get(folded.payloadRef) ?? admitPayload(await blobs.get(folded.payloadRef));
|
|
1698
|
+
let outcome = "delivered";
|
|
1699
|
+
let reason;
|
|
1700
|
+
if (spec.projection !== void 0) try {
|
|
1701
|
+
payload = admitPayload(applyProjection(payload, spec.projection, `edge ${edge.id}`));
|
|
1702
|
+
} catch (error) {
|
|
1703
|
+
outcome = "empty";
|
|
1704
|
+
reason = error instanceof Error ? error.message : String(error);
|
|
1705
|
+
payload = void 0;
|
|
1706
|
+
}
|
|
1707
|
+
if (payload === void 0) outcome = "empty";
|
|
1708
|
+
await ledger.record(edge, traversal, outcome, reason);
|
|
1709
|
+
if (payload !== void 0) inputs[edge.toPort] = payload;
|
|
1710
|
+
continue;
|
|
1711
|
+
}
|
|
1712
|
+
if (spec.directive !== void 0 && options.prompts !== void 0) directives.push(options.prompts.resolve(spec.directive).text);
|
|
1713
|
+
if (spec.kind === "analyzes" && folded?.state === "satisfied") traces.push(`trace of ${spec.from.node}: ${folded.payloadRef ?? "(no traceRef)"}`);
|
|
1714
|
+
await ledger.record(edge, traversal, "delivered");
|
|
1715
|
+
}
|
|
1716
|
+
const composed = [
|
|
1717
|
+
nodeId === compiled.root ? task : "",
|
|
1718
|
+
...directives,
|
|
1719
|
+
...traces
|
|
1720
|
+
].filter((part) => part.length > 0).join("\n\n");
|
|
1721
|
+
return {
|
|
1722
|
+
task: composed.length > 0 ? composed : task,
|
|
1723
|
+
inputs
|
|
1724
|
+
};
|
|
1725
|
+
};
|
|
1726
|
+
const release = async (nodeId, consuming, consumedPending) => {
|
|
1727
|
+
const node = compiled.nodes.get(nodeId);
|
|
1728
|
+
const folded = state.nodes.get(nodeId);
|
|
1729
|
+
if (!node || !folded) return;
|
|
1730
|
+
const visit = folded.visits + 1;
|
|
1731
|
+
if (visit > node.maxVisits) {
|
|
1732
|
+
fail("cycle-budget-exceeded", "GraphCycleBudget", `node ${nodeId} entered ${visit} times; maxVisits ${node.maxVisits}`);
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
const envelope = await consumeWave(nodeId, consuming);
|
|
1736
|
+
const label = await openInstance(nodeId, visit, envelope);
|
|
1737
|
+
await emit({
|
|
1738
|
+
kind: "join-state",
|
|
1739
|
+
id: label,
|
|
1740
|
+
node: nodeId,
|
|
1741
|
+
rule: node.join,
|
|
1742
|
+
satisfiedBy: consuming.map(({ edge }) => edge.id),
|
|
1743
|
+
consumedPending: [...consumedPending],
|
|
1744
|
+
instance: label,
|
|
1745
|
+
seq: engineSeq++,
|
|
1746
|
+
at: stamp()
|
|
1747
|
+
});
|
|
1748
|
+
await spawnInstance(label);
|
|
1749
|
+
};
|
|
1750
|
+
const tryRelease = async (nodeId) => {
|
|
1751
|
+
const node = compiled.nodes.get(nodeId);
|
|
1752
|
+
const folded = state.nodes.get(nodeId);
|
|
1753
|
+
if (!node || !folded || folded.blocked || failure) return;
|
|
1754
|
+
const gating = node.inbound.map((edge) => ({
|
|
1755
|
+
edge,
|
|
1756
|
+
folded: state.edges.get(edge.id)
|
|
1757
|
+
}));
|
|
1758
|
+
const decision = decideJoin(node.join, gating);
|
|
1759
|
+
if (decision.blocked) folded.blocked = true;
|
|
1760
|
+
if (!decision.release) return;
|
|
1761
|
+
for (const entry of decision.consuming) {
|
|
1762
|
+
const cap = entry.edge.spec.maxTraversals;
|
|
1763
|
+
if (cap !== void 0 && (entry.folded?.traversals ?? 0) >= cap) {
|
|
1764
|
+
await ledger.record(entry.edge, (entry.folded?.traversals ?? 0) + 1, "unpropagated", `traversal-cap-exhausted (max ${cap})`);
|
|
1765
|
+
await emit({
|
|
1766
|
+
kind: "edge-verdict",
|
|
1767
|
+
id: `graph:${nodeId}`,
|
|
1768
|
+
edge: entry.edge.id,
|
|
1769
|
+
fired: false,
|
|
1770
|
+
sourceStatus: "done",
|
|
1771
|
+
capped: true,
|
|
1772
|
+
seq: engineSeq++,
|
|
1773
|
+
at: stamp()
|
|
1774
|
+
});
|
|
1775
|
+
return;
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
const consumedPending = gating.filter((entry) => entry.folded?.state === "pending" && hasLiveInstance(entry.edge.spec.from.node)).map((entry) => entry.edge.id);
|
|
1779
|
+
await release(nodeId, decision.consuming, consumedPending);
|
|
1780
|
+
};
|
|
1781
|
+
const hasLiveInstance = (nodeId) => {
|
|
1782
|
+
for (const label of liveHandles.values()) if (state.instances.get(label)?.node === nodeId) return true;
|
|
1783
|
+
return false;
|
|
1784
|
+
};
|
|
1785
|
+
/** Journal a verdict for every unaccounted outbound edge of a settle, then try the joins. */
|
|
1786
|
+
const propagate = async (label, settle) => {
|
|
1787
|
+
const node = compiled.nodes.get(settle.node);
|
|
1788
|
+
if (!node) return;
|
|
1789
|
+
const succeeded = settle.status === "done" && settle.valid !== false;
|
|
1790
|
+
const sourceSettles = state.nodes.get(settle.node)?.settles.length ?? 0;
|
|
1791
|
+
for (const edge of node.outbound) {
|
|
1792
|
+
if (!isEngineFired(edge)) continue;
|
|
1793
|
+
const folded = state.edges.get(edge.id);
|
|
1794
|
+
if (!folded || folded.judgedSourceSettles >= sourceSettles) continue;
|
|
1795
|
+
let fired = false;
|
|
1796
|
+
let inputRef;
|
|
1797
|
+
if (succeeded) {
|
|
1798
|
+
fired = edge.spec.guard === void 0 || evaluateCondition(edge.spec.guard, {
|
|
1799
|
+
node: settle.node,
|
|
1800
|
+
out: settle.out,
|
|
1801
|
+
visits: state.nodes.get(settle.node)?.visits ?? 0,
|
|
1802
|
+
valid: settle.valid ?? true
|
|
1803
|
+
});
|
|
1804
|
+
if (fired) inputRef = edge.spec.kind === "analyzes" ? settle.traceRef : settle.outRef;
|
|
1805
|
+
}
|
|
1806
|
+
await emit({
|
|
1807
|
+
kind: "edge-verdict",
|
|
1808
|
+
id: label,
|
|
1809
|
+
edge: edge.id,
|
|
1810
|
+
fired,
|
|
1811
|
+
sourceStatus: settle.status === "down" ? "down" : succeeded ? "done" : "invalid",
|
|
1812
|
+
...inputRef !== void 0 ? { inputRef } : {},
|
|
1813
|
+
seq: engineSeq++,
|
|
1814
|
+
at: stamp()
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
for (const edge of node.outbound) if (isEngineFired(edge)) await tryRelease(edge.spec.to.node);
|
|
1818
|
+
};
|
|
1819
|
+
const park = async (label, request) => {
|
|
1820
|
+
const token = mintSuspensionToken(runId, label);
|
|
1821
|
+
let defaultRef;
|
|
1822
|
+
if (request.default !== void 0) {
|
|
1823
|
+
const admitted = admitPayload(request.default);
|
|
1824
|
+
defaultRef = contentAddress(admitted);
|
|
1825
|
+
await blobs.put(defaultRef, admitted);
|
|
1826
|
+
}
|
|
1827
|
+
await emit({
|
|
1828
|
+
kind: "waiting",
|
|
1829
|
+
id: suspensionNodeId(token),
|
|
1830
|
+
label,
|
|
1831
|
+
spec: {
|
|
1832
|
+
kind: "token",
|
|
1833
|
+
token,
|
|
1834
|
+
onExpire: request.onExpire,
|
|
1835
|
+
...request.expiresInMs !== void 0 ? { expiresAtMs: now() + request.expiresInMs } : {},
|
|
1836
|
+
...defaultRef !== void 0 ? { defaultRef } : {}
|
|
1837
|
+
},
|
|
1838
|
+
armedAt: now(),
|
|
1839
|
+
seq: engineSeq++,
|
|
1840
|
+
at: stamp()
|
|
1841
|
+
});
|
|
1842
|
+
};
|
|
1843
|
+
const wake = async (suspension, by, outRef) => {
|
|
1844
|
+
await emit({
|
|
1845
|
+
kind: "woken",
|
|
1846
|
+
id: suspensionNodeId(suspension.token),
|
|
1847
|
+
by,
|
|
1848
|
+
...outRef !== void 0 ? { outRef } : {},
|
|
1849
|
+
seq: wokenSeq++,
|
|
1850
|
+
at: stamp()
|
|
1851
|
+
});
|
|
1852
|
+
const settle = state.instances.get(suspension.instance)?.settle;
|
|
1853
|
+
if (settle === void 0) return;
|
|
1854
|
+
const out = settle.outRef === void 0 ? void 0 : admitPayload(await blobs.get(settle.outRef));
|
|
1855
|
+
if (settle.outRef !== void 0 && out !== void 0) outCache.set(settle.outRef, out);
|
|
1856
|
+
await propagate(suspension.instance, out === void 0 ? settle : {
|
|
1857
|
+
...settle,
|
|
1858
|
+
out
|
|
1859
|
+
});
|
|
1860
|
+
};
|
|
1861
|
+
/** Expiries are engine-clocked, so an offline run transitions them without a host sweep (#976). */
|
|
1862
|
+
const expireDue = async () => {
|
|
1863
|
+
let transitioned = false;
|
|
1864
|
+
for (const suspension of [...state.suspensions.values()]) {
|
|
1865
|
+
if (suspension.status !== "pending") continue;
|
|
1866
|
+
if (suspension.expiresAtMs === void 0 || now() < suspension.expiresAtMs) continue;
|
|
1867
|
+
if (suspension.onExpire === "fail") await wake(suspension, "expired");
|
|
1868
|
+
else if (suspension.onExpire === "default") await wake(suspension, "fired", suspension.defaultRef);
|
|
1869
|
+
else continue;
|
|
1870
|
+
transitioned = true;
|
|
1871
|
+
}
|
|
1872
|
+
return transitioned;
|
|
1873
|
+
};
|
|
1874
|
+
const drainWakes = async () => {
|
|
1875
|
+
while (wakes.length > 0) {
|
|
1876
|
+
const request = wakes.shift();
|
|
1877
|
+
if (!request) return;
|
|
1878
|
+
try {
|
|
1879
|
+
const suspension = state.suspensions.get(request.token);
|
|
1880
|
+
if (!suspension) throw new ValidationError(`graph resume: unknown token '${request.token}'`);
|
|
1881
|
+
if (suspension.status !== "pending") throw new ValidationError(`graph resume: token '${request.token}' already woken`);
|
|
1882
|
+
if (request.expire) await wake(suspension, suspension.onExpire === "default" ? "fired" : "expired", suspension.onExpire === "default" ? suspension.defaultRef : void 0);
|
|
1883
|
+
else {
|
|
1884
|
+
const admitted = admitPayload(request.payload);
|
|
1885
|
+
const outRef = contentAddress(admitted);
|
|
1886
|
+
await blobs.put(outRef, admitted);
|
|
1887
|
+
outCache.set(outRef, admitted);
|
|
1888
|
+
await wake(suspension, "fired", outRef);
|
|
1889
|
+
}
|
|
1890
|
+
request.settle();
|
|
1891
|
+
} catch (error) {
|
|
1892
|
+
request.fail(error);
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
};
|
|
1896
|
+
const handleSettle = async (settled) => {
|
|
1897
|
+
const label = liveHandles.get(settled.handle.id);
|
|
1898
|
+
if (label === void 0) return;
|
|
1899
|
+
liveHandles.delete(settled.handle.id);
|
|
1900
|
+
liveCount -= 1;
|
|
1901
|
+
const instance = state.instances.get(label);
|
|
1902
|
+
const node = instance === void 0 ? void 0 : compiled.nodes.get(instance.node);
|
|
1903
|
+
if (!instance || !node) return;
|
|
1904
|
+
if (settled.kind === "done" && isSuspensionRequest(settled.out)) {
|
|
1905
|
+
await park(label, settled.out);
|
|
1906
|
+
return;
|
|
1907
|
+
}
|
|
1908
|
+
applyGraphFoldEvent(state, {
|
|
1909
|
+
kind: "settled",
|
|
1910
|
+
id: settled.handle.id,
|
|
1911
|
+
status: settled.kind === "done" ? "done" : "down",
|
|
1912
|
+
...settled.kind === "done" ? { outRef: settled.outRef } : {},
|
|
1913
|
+
...settled.kind === "down" ? { reason: settled.reason } : {},
|
|
1914
|
+
...settled.kind === "done" && settled.trace?.status === "available" ? { trace: settled.trace } : {},
|
|
1915
|
+
spent: {
|
|
1916
|
+
iterations: 0,
|
|
1917
|
+
tokens: {
|
|
1918
|
+
input: 0,
|
|
1919
|
+
output: 0
|
|
1920
|
+
},
|
|
1921
|
+
usd: 0,
|
|
1922
|
+
ms: 0
|
|
1923
|
+
},
|
|
1924
|
+
seq: 0,
|
|
1925
|
+
at: ""
|
|
1926
|
+
}, compiled);
|
|
1927
|
+
const folded = state.instances.get(label)?.settle;
|
|
1928
|
+
if (!folded) return;
|
|
1929
|
+
let enriched = folded;
|
|
1930
|
+
if (settled.kind === "done") {
|
|
1931
|
+
const admitted = admitPayload(settled.out);
|
|
1932
|
+
if (settled.outRef !== void 0) outCache.set(settled.outRef, admitted);
|
|
1933
|
+
enriched = {
|
|
1934
|
+
...folded,
|
|
1935
|
+
out: admitted,
|
|
1936
|
+
...await checkDeliverable(node, admitted)
|
|
1937
|
+
};
|
|
1938
|
+
const settles = state.nodes.get(instance.node)?.settles;
|
|
1939
|
+
if (settles) settles[settles.length - 1] = enriched;
|
|
1940
|
+
state.instances.get(label).settle = enriched;
|
|
1941
|
+
}
|
|
1942
|
+
if (instance.node === compiled.root && enriched.status === "done" && enriched.valid === true) {
|
|
1943
|
+
abort.abort("root delivered");
|
|
1944
|
+
return;
|
|
1945
|
+
}
|
|
1946
|
+
await propagate(label, enriched);
|
|
1947
|
+
};
|
|
1948
|
+
const checkDeliverable = async (node, out) => {
|
|
1949
|
+
if (node.deliverable === void 0) return {};
|
|
1950
|
+
try {
|
|
1951
|
+
return { valid: await node.deliverable.check(out) };
|
|
1952
|
+
} catch {
|
|
1953
|
+
return { valid: false };
|
|
1954
|
+
}
|
|
1955
|
+
};
|
|
1956
|
+
if (!context.resuming) for (const id of compiled.entries) await enterEntryNode(id);
|
|
1957
|
+
else await reenterAfterCrash();
|
|
1958
|
+
/** Kill-anywhere re-entry: finish every half-done transition the crashed process left, from the
|
|
1959
|
+
* pinned envelopes and journaled settles only — never by re-deriving anything (#974). */
|
|
1960
|
+
async function reenterAfterCrash() {
|
|
1961
|
+
for (const instance of [...state.instances.values()]) {
|
|
1962
|
+
if (instance.status === "released") {
|
|
1963
|
+
await spawnInstance(instance.instance);
|
|
1964
|
+
continue;
|
|
1965
|
+
}
|
|
1966
|
+
if (instance.status !== "live") continue;
|
|
1967
|
+
const node = compiled.nodes.get(instance.node);
|
|
1968
|
+
const folded = state.nodes.get(instance.node);
|
|
1969
|
+
if (!node || !folded) continue;
|
|
1970
|
+
const visit = folded.visits + 1;
|
|
1971
|
+
if (visit > node.maxVisits) {
|
|
1972
|
+
fail("cycle-budget-exceeded", "GraphCycleBudget", `node ${instance.node} entered ${visit} times; maxVisits ${node.maxVisits}`);
|
|
1973
|
+
return;
|
|
1974
|
+
}
|
|
1975
|
+
instance.status = "down";
|
|
1976
|
+
const label = `${instance.node}#${visit}`;
|
|
1977
|
+
await emit({
|
|
1978
|
+
kind: "node-inputs-resolved",
|
|
1979
|
+
id: label,
|
|
1980
|
+
node: instance.node,
|
|
1981
|
+
instance: label,
|
|
1982
|
+
inputRef: instance.inputRef,
|
|
1983
|
+
seq: engineSeq++,
|
|
1984
|
+
at: stamp()
|
|
1985
|
+
});
|
|
1986
|
+
await spawnInstance(label);
|
|
1987
|
+
}
|
|
1988
|
+
for (const [nodeId, folded] of state.nodes) {
|
|
1989
|
+
const latest = folded.settles.at(-1);
|
|
1990
|
+
if (latest === void 0) continue;
|
|
1991
|
+
const label = `${nodeId}#${latest.visit}`;
|
|
1992
|
+
if (latest.status === "done" && latest.outRef !== void 0) {
|
|
1993
|
+
const out = admitPayload(await blobs.get(latest.outRef));
|
|
1994
|
+
if (isSuspensionRequest(out)) {
|
|
1995
|
+
folded.settles.pop();
|
|
1996
|
+
const instance = state.instances.get(label);
|
|
1997
|
+
if (instance) instance.settle = void 0;
|
|
1998
|
+
await park(label, out);
|
|
1999
|
+
continue;
|
|
2000
|
+
}
|
|
2001
|
+
outCache.set(latest.outRef, out);
|
|
2002
|
+
const node = compiled.nodes.get(nodeId);
|
|
2003
|
+
await propagate(label, {
|
|
2004
|
+
...latest,
|
|
2005
|
+
out,
|
|
2006
|
+
...node === void 0 ? {} : await checkDeliverable(node, out)
|
|
2007
|
+
});
|
|
2008
|
+
continue;
|
|
2009
|
+
}
|
|
2010
|
+
await propagate(label, latest);
|
|
2011
|
+
}
|
|
2012
|
+
for (const id of compiled.entries) if ((state.nodes.get(id)?.visits ?? 0) === 0) await enterEntryNode(id);
|
|
2013
|
+
for (const id of compiled.nodes.keys()) await tryRelease(id);
|
|
2014
|
+
}
|
|
2015
|
+
const allTerminalsSettled = () => compiled.terminals.every((id) => (state.nodes.get(id)?.settles.length ?? 0) > 0);
|
|
2016
|
+
let wakeSignal = Promise.resolve();
|
|
2017
|
+
const rearmWakeSignal = () => {
|
|
2018
|
+
wakeSignal = new Promise((fire) => {
|
|
2019
|
+
onWakeSignal(fire);
|
|
2020
|
+
});
|
|
2021
|
+
};
|
|
2022
|
+
rearmWakeSignal();
|
|
2023
|
+
let pendingNext;
|
|
2024
|
+
while (!failure) {
|
|
2025
|
+
if (await expireDue()) continue;
|
|
2026
|
+
if (wakes.length > 0) {
|
|
2027
|
+
await drainWakes();
|
|
2028
|
+
continue;
|
|
2029
|
+
}
|
|
2030
|
+
if (allTerminalsSettled()) break;
|
|
2031
|
+
if (liveCount === 0) {
|
|
2032
|
+
const parked = [...state.suspensions.values()].filter((suspension) => suspension.status === "pending");
|
|
2033
|
+
if (parked.length === 0) break;
|
|
2034
|
+
if (options.waitForWakes) {
|
|
2035
|
+
rearmWakeSignal();
|
|
2036
|
+
await wakeSignal;
|
|
2037
|
+
continue;
|
|
2038
|
+
}
|
|
2039
|
+
const defaulting = parked.filter((suspension) => suspension.onExpire === "default");
|
|
2040
|
+
if (defaulting.length === 0) break;
|
|
2041
|
+
for (const suspension of defaulting) await wake(suspension, "fired", suspension.defaultRef);
|
|
2042
|
+
continue;
|
|
2043
|
+
}
|
|
2044
|
+
pendingNext ??= scope.next();
|
|
2045
|
+
const raced = await Promise.race([pendingNext.then((settle) => ({ settle })), wakeSignal.then(() => "wake")]);
|
|
2046
|
+
if (raced === "wake") {
|
|
2047
|
+
rearmWakeSignal();
|
|
2048
|
+
continue;
|
|
2049
|
+
}
|
|
2050
|
+
pendingNext = void 0;
|
|
2051
|
+
if (raced.settle === null) break;
|
|
2052
|
+
await handleSettle(raced.settle);
|
|
2053
|
+
for (const label of waitingForBudget.splice(0)) await spawnInstance(label);
|
|
2054
|
+
}
|
|
2055
|
+
detachOuterAbort();
|
|
2056
|
+
abort.abort("graph loop complete");
|
|
2057
|
+
while (await (pendingNext ?? scope.next()) !== null) pendingNext = void 0;
|
|
2058
|
+
return assembleGraphResult({
|
|
2059
|
+
compiled,
|
|
2060
|
+
state,
|
|
2061
|
+
blobs,
|
|
2062
|
+
scope,
|
|
2063
|
+
outCache,
|
|
2064
|
+
ledger: ledger.entries,
|
|
2065
|
+
...options.finalizer !== void 0 ? { finalizer: options.finalizer } : {},
|
|
2066
|
+
...failure !== void 0 ? { failure } : {},
|
|
2067
|
+
aborted: options.signal?.aborted ?? false
|
|
2068
|
+
});
|
|
2069
|
+
}
|
|
2070
|
+
//#endregion
|
|
2071
|
+
export { CONDITION_OPS, DEFAULT_MAX_NODE_VISITS, ENGINE_WOKEN_SEQ_BASE, JOIN_RULES, MAX_MAX_NODE_VISITS, RUN_GRAPH_ROOT_KIND, admitPayload, agentKind, applyGraphFoldEvent, applyProjection, assembleGraphResult, compileGraph, createEdgeLedger, createGraphEngine, createGraphRun, createRegistry, decideJoin, emptyFoldState, evaluateCondition, foldGraphJournal, formatRegistryHandle, graphFromRunGraph, isEngineFired, isSuspensionRequest, kindHandle, materializeSettles, mintSuspensionToken, narrowEffects, openGraphRun, parseRegistryHandle, runEngineGraph, schemaAccepts, scriptKind, subgraphKind, supervisorKind, suspended, suspensionNodeId, tokenFromSuspensionNodeId, validateCondition, validateNodeKind, validateProjection };
|
|
2072
|
+
|
|
2073
|
+
//# sourceMappingURL=graph.js.map
|