@nagi-js/core 0.1.1-rc.20 → 0.1.1-rc.22
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/{chunk-VQTYTI6X.js → chunk-PUAV56FC.js} +922 -519
- package/dist/chunk-PUAV56FC.js.map +1 -0
- package/dist/index.d.ts +90 -115
- package/dist/index.js +693 -1390
- package/dist/index.js.map +1 -1
- package/dist/testing.d.ts +2 -1
- package/dist/testing.js +675 -214
- package/dist/testing.js.map +1 -1
- package/dist/{types-DFSYjJE3.d.ts → types-Ct5xHI4W.d.ts} +119 -125
- package/package.json +1 -1
- package/dist/chunk-VQTYTI6X.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { InMemoryClock, makeEmit,
|
|
2
|
-
export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryStore, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError,
|
|
1
|
+
import { InMemoryClock, makeEmit, registerFlows, fingerprintFlows, makeFlowOf, makeSignals, compact, validationError, NagiRuntimeError, NagiSnapshotDriftError, requireCurrent, serializeError, NagiSignalTimeoutError, validate, Facts, foldRun, stepStateOf, isStepTerminal, isTerminalRun, attemptOf, dequeueBackoff, defaultSnapshotGonePolicy, DEFAULT_REAPER_INTERVAL_MS, runStatusOf, runCancelCause, asStepMapWithDefs, needsStepIds, getDef, stepStatusOf, handlerDef, resolveRetry, isAbortRequested, resolveNeeds, stepBackoff, NagiCanceledError, NagiStepTimeoutError, peekDef, attachDef, NagiNonRetryableError, pinRun, normalizeNeeds } from './chunk-PUAV56FC.js';
|
|
2
|
+
export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, admitsRunEnd, attemptOf, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, errorOf, factConsequences, isRunEnd, isStepTerminal, isStreamOver, isTerminalRun, isTerminalRunEvent, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, selectExpired, selectPruneBatch, stepStateOf, stepStatusOf, supersede, unwrap } from './chunk-PUAV56FC.js';
|
|
3
3
|
|
|
4
4
|
// src/builder.ts
|
|
5
5
|
function makeBuilder() {
|
|
6
|
-
function
|
|
6
|
+
function handler(kind, config) {
|
|
7
7
|
const def = {
|
|
8
|
-
kind
|
|
8
|
+
kind,
|
|
9
9
|
needs: normalizeNeeds(config.needs),
|
|
10
10
|
run: config.run,
|
|
11
11
|
...compact({
|
|
12
12
|
retry: config.retry,
|
|
13
|
+
timeoutMs: config.timeoutMs,
|
|
13
14
|
when: config.when,
|
|
14
15
|
onStart: config.onStart,
|
|
15
16
|
onComplete: config.onComplete,
|
|
@@ -17,39 +18,7 @@ function makeBuilder() {
|
|
|
17
18
|
onRetry: config.onRetry
|
|
18
19
|
})
|
|
19
20
|
};
|
|
20
|
-
return attachDef({ kind
|
|
21
|
-
}
|
|
22
|
-
function activity(config) {
|
|
23
|
-
const def = {
|
|
24
|
-
kind: "activity",
|
|
25
|
-
needs: normalizeNeeds(config.needs),
|
|
26
|
-
run: config.run,
|
|
27
|
-
...compact({
|
|
28
|
-
retry: config.retry,
|
|
29
|
-
when: config.when,
|
|
30
|
-
onStart: config.onStart,
|
|
31
|
-
onComplete: config.onComplete,
|
|
32
|
-
onError: config.onError,
|
|
33
|
-
onRetry: config.onRetry
|
|
34
|
-
})
|
|
35
|
-
};
|
|
36
|
-
return attachDef({ kind: "activity", id: "" }, def);
|
|
37
|
-
}
|
|
38
|
-
function streamingTask(config) {
|
|
39
|
-
const def = {
|
|
40
|
-
kind: "streaming",
|
|
41
|
-
needs: normalizeNeeds(config.needs),
|
|
42
|
-
run: config.run,
|
|
43
|
-
...compact({
|
|
44
|
-
retry: config.retry,
|
|
45
|
-
when: config.when,
|
|
46
|
-
onStart: config.onStart,
|
|
47
|
-
onComplete: config.onComplete,
|
|
48
|
-
onError: config.onError,
|
|
49
|
-
onRetry: config.onRetry
|
|
50
|
-
})
|
|
51
|
-
};
|
|
52
|
-
return attachDef({ kind: "streaming", id: "" }, def);
|
|
21
|
+
return attachDef({ kind, id: "" }, def);
|
|
53
22
|
}
|
|
54
23
|
function signal(config) {
|
|
55
24
|
const def = {
|
|
@@ -79,42 +48,18 @@ function makeBuilder() {
|
|
|
79
48
|
def
|
|
80
49
|
);
|
|
81
50
|
}
|
|
82
|
-
function match(config) {
|
|
83
|
-
const needs = normalizeNeeds(config.needs);
|
|
84
|
-
const arms = [];
|
|
85
|
-
for (let i = 0; i < config.arms.length; i++) {
|
|
86
|
-
const arm = config.arms[i];
|
|
87
|
-
const nested = arm.build(makeBuilder());
|
|
88
|
-
const guard = arm.otherwise ? { kind: "otherwise" } : { kind: "when", when: arm.when };
|
|
89
|
-
const armId = guard.kind === "otherwise" ? "otherwise" : `arm${i}`;
|
|
90
|
-
arms.push({ id: armId, guard, nested });
|
|
91
|
-
}
|
|
92
|
-
const def = { kind: "match", needs, arms };
|
|
93
|
-
return attachDef({ kind: "match", id: "" }, def);
|
|
94
|
-
}
|
|
95
51
|
return {
|
|
96
|
-
task,
|
|
97
|
-
activity,
|
|
98
|
-
streamingTask,
|
|
52
|
+
task: (config) => handler("task", config),
|
|
53
|
+
activity: (config) => handler("activity", config),
|
|
54
|
+
streamingTask: (config) => handler("streaming", config),
|
|
99
55
|
signal,
|
|
100
|
-
subflow
|
|
101
|
-
match
|
|
56
|
+
subflow
|
|
102
57
|
};
|
|
103
58
|
}
|
|
104
59
|
function flow(config) {
|
|
105
60
|
const builder = makeBuilder();
|
|
106
61
|
const built = config.build(builder);
|
|
107
|
-
const
|
|
108
|
-
collectIds(built, "", idByIdentity);
|
|
109
|
-
const finalSteps = {};
|
|
110
|
-
walkAndRewrite({
|
|
111
|
-
flowId: config.id,
|
|
112
|
-
map: built,
|
|
113
|
-
prefix: "",
|
|
114
|
-
parentMatch: void 0,
|
|
115
|
-
idByIdentity,
|
|
116
|
-
out: finalSteps
|
|
117
|
-
});
|
|
62
|
+
const finalSteps = rewriteSteps(config.id, built);
|
|
118
63
|
assertSignalNameUniqueness(config.id, finalSteps);
|
|
119
64
|
return {
|
|
120
65
|
id: config.id,
|
|
@@ -145,23 +90,11 @@ function normalizeConcurrency(c) {
|
|
|
145
90
|
mode: "cancel-in-progress"
|
|
146
91
|
};
|
|
147
92
|
}
|
|
148
|
-
function
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
if (def?.kind === "match") {
|
|
154
|
-
const pending = def;
|
|
155
|
-
for (const arm of pending.arms) {
|
|
156
|
-
collectIds(arm.nested, `${id}.${arm.id}`, idByIdentity);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
function walkAndRewrite(args) {
|
|
162
|
-
const { flowId, map, prefix, parentMatch, idByIdentity, out } = args;
|
|
163
|
-
for (const [key, step] of Object.entries(map)) {
|
|
164
|
-
const id = prefix ? `${prefix}.${key}` : key;
|
|
93
|
+
function rewriteSteps(flowId, map) {
|
|
94
|
+
const idByIdentity = /* @__PURE__ */ new Map();
|
|
95
|
+
for (const [id, step] of Object.entries(map)) idByIdentity.set(step, id);
|
|
96
|
+
const out = {};
|
|
97
|
+
for (const [id, step] of Object.entries(map)) {
|
|
165
98
|
const def = peekDef(step);
|
|
166
99
|
if (def === void 0) {
|
|
167
100
|
throw new Error(
|
|
@@ -188,45 +121,10 @@ function walkAndRewrite(args) {
|
|
|
188
121
|
optional: ref.optional
|
|
189
122
|
};
|
|
190
123
|
}
|
|
191
|
-
|
|
192
|
-
const pending = def;
|
|
193
|
-
const finalizedArms = [];
|
|
194
|
-
for (const arm of pending.arms) {
|
|
195
|
-
const armPrefix = `${id}.${arm.id}`;
|
|
196
|
-
const nestedStepIds = [];
|
|
197
|
-
for (const nestedKey of Object.keys(arm.nested)) {
|
|
198
|
-
nestedStepIds.push(`${armPrefix}.${nestedKey}`);
|
|
199
|
-
}
|
|
200
|
-
walkAndRewrite({
|
|
201
|
-
flowId,
|
|
202
|
-
map: arm.nested,
|
|
203
|
-
prefix: armPrefix,
|
|
204
|
-
parentMatch: { matchId: id, armId: arm.id },
|
|
205
|
-
idByIdentity,
|
|
206
|
-
out
|
|
207
|
-
});
|
|
208
|
-
finalizedArms.push({
|
|
209
|
-
id: arm.id,
|
|
210
|
-
guard: arm.guard,
|
|
211
|
-
stepIds: nestedStepIds
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
const finalizedDef2 = {
|
|
215
|
-
kind: "match",
|
|
216
|
-
needs: rewrittenNeeds,
|
|
217
|
-
arms: finalizedArms,
|
|
218
|
-
...compact({ parentMatch })
|
|
219
|
-
};
|
|
220
|
-
out[id] = attachDef({ kind: "match", id }, finalizedDef2);
|
|
221
|
-
continue;
|
|
222
|
-
}
|
|
223
|
-
const finalizedDef = {
|
|
224
|
-
...def,
|
|
225
|
-
needs: rewrittenNeeds,
|
|
226
|
-
...compact({ parentMatch })
|
|
227
|
-
};
|
|
124
|
+
const finalizedDef = { ...def, needs: rewrittenNeeds };
|
|
228
125
|
out[id] = attachDef({ kind: finalizedDef.kind, id }, finalizedDef);
|
|
229
126
|
}
|
|
127
|
+
return out;
|
|
230
128
|
}
|
|
231
129
|
function assertSignalNameUniqueness(flowId, finalSteps) {
|
|
232
130
|
const owners = /* @__PURE__ */ new Map();
|
|
@@ -251,246 +149,6 @@ function assertSignalNameUniqueness(flowId, finalSteps) {
|
|
|
251
149
|
}
|
|
252
150
|
}
|
|
253
151
|
|
|
254
|
-
// src/canonicalize.ts
|
|
255
|
-
var warnedAboutSourceHash = false;
|
|
256
|
-
function warnSourceHashOnce() {
|
|
257
|
-
if (warnedAboutSourceHash) return;
|
|
258
|
-
warnedAboutSourceHash = true;
|
|
259
|
-
console.warn(
|
|
260
|
-
"[nagi] canonicalize: hashing `when`/schema source via Function.prototype.toString(). Cosmetic source changes (minification, whitespace, identifier renames) will flip the flow hash even when behavior is unchanged."
|
|
261
|
-
);
|
|
262
|
-
}
|
|
263
|
-
async function canonicalize(flow2) {
|
|
264
|
-
const withDefs = asStepMapWithDefs(flow2.steps);
|
|
265
|
-
const ids = Object.keys(withDefs).sort();
|
|
266
|
-
const steps = [];
|
|
267
|
-
for (const id of ids) {
|
|
268
|
-
const step = withDefs[id];
|
|
269
|
-
if (step === void 0) continue;
|
|
270
|
-
steps.push(await canonicalizeStep(id, getDef(step)));
|
|
271
|
-
}
|
|
272
|
-
return {
|
|
273
|
-
flowId: flow2.id,
|
|
274
|
-
inputSchema: await canonicalizeSchema(flow2.input),
|
|
275
|
-
steps
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
async function canonicalizeStep(id, def) {
|
|
279
|
-
const needs = [...needsStepIds(def)].sort();
|
|
280
|
-
const base = { id, kind: def.kind, needs };
|
|
281
|
-
if (def.kind === "task" || def.kind === "activity" || def.kind === "streaming")
|
|
282
|
-
return canonicalizeTask(base, def);
|
|
283
|
-
if (def.kind === "signal") return canonicalizeSignal(base, def);
|
|
284
|
-
if (def.kind === "subflow") return canonicalizeSubflow(base, def);
|
|
285
|
-
return canonicalizeMatch(base, def);
|
|
286
|
-
}
|
|
287
|
-
async function applyGuardAndTimeout(out, def) {
|
|
288
|
-
if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
|
|
289
|
-
if (def.timeoutMs !== void 0 && def.timeoutMs !== "unbounded")
|
|
290
|
-
out.timeoutMs = def.timeoutMs;
|
|
291
|
-
}
|
|
292
|
-
async function canonicalizeTask(base, def) {
|
|
293
|
-
const out = { ...base };
|
|
294
|
-
await applyGuardAndTimeout(out, def);
|
|
295
|
-
if (def.retry !== void 0) out.retry = normalizeRetry(def.retry);
|
|
296
|
-
return out;
|
|
297
|
-
}
|
|
298
|
-
async function canonicalizeSignal(base, def) {
|
|
299
|
-
const out = { ...base };
|
|
300
|
-
await applyGuardAndTimeout(out, def);
|
|
301
|
-
out.signalSchema = await canonicalizeSchema(def.schema);
|
|
302
|
-
if (def.names !== void 0) {
|
|
303
|
-
out.signalNames = [...def.names].sort();
|
|
304
|
-
}
|
|
305
|
-
return out;
|
|
306
|
-
}
|
|
307
|
-
async function canonicalizeSubflow(base, def) {
|
|
308
|
-
const out = { ...base };
|
|
309
|
-
await applyGuardAndTimeout(out, def);
|
|
310
|
-
out.childFlowId = def.childFlowId;
|
|
311
|
-
out.subflowInputHash = await hashFnSource(def.buildInput);
|
|
312
|
-
return out;
|
|
313
|
-
}
|
|
314
|
-
async function canonicalizeMatch(base, def) {
|
|
315
|
-
const out = { ...base };
|
|
316
|
-
const arms = [];
|
|
317
|
-
for (const arm of def.arms) {
|
|
318
|
-
arms.push(await canonicalizeArm(arm));
|
|
319
|
-
}
|
|
320
|
-
out.matchArms = arms;
|
|
321
|
-
return out;
|
|
322
|
-
}
|
|
323
|
-
async function canonicalizeArm(arm) {
|
|
324
|
-
const out = {
|
|
325
|
-
id: arm.id,
|
|
326
|
-
stepIds: [...arm.stepIds].sort()
|
|
327
|
-
};
|
|
328
|
-
if (arm.guard.kind === "otherwise") out.otherwise = true;
|
|
329
|
-
else out.whenHash = await hashFnSource(arm.guard.when);
|
|
330
|
-
return out;
|
|
331
|
-
}
|
|
332
|
-
function normalizeRetry(retry) {
|
|
333
|
-
return {
|
|
334
|
-
maxAttempts: retry.maxAttempts,
|
|
335
|
-
backoff: retry.backoff,
|
|
336
|
-
initialDelayMs: retry.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs,
|
|
337
|
-
maxDelayMs: retry.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
async function canonicalizeSchema(schema) {
|
|
341
|
-
const props = schema["~standard"];
|
|
342
|
-
return {
|
|
343
|
-
vendor: props.vendor,
|
|
344
|
-
version: props.version,
|
|
345
|
-
validateHash: await hashFnSource(props.validate)
|
|
346
|
-
};
|
|
347
|
-
}
|
|
348
|
-
async function hashFnSource(fn) {
|
|
349
|
-
warnSourceHashOnce();
|
|
350
|
-
return sha256Hex(fn.toString());
|
|
351
|
-
}
|
|
352
|
-
async function sha256Canonical(dag) {
|
|
353
|
-
return sha256Hex(stableStringify(dag));
|
|
354
|
-
}
|
|
355
|
-
async function fingerprintFlows(flows) {
|
|
356
|
-
const entries = [];
|
|
357
|
-
for (const f of flows) {
|
|
358
|
-
const dag = await canonicalize(f);
|
|
359
|
-
entries.push([f.id, await sha256Canonical(dag)]);
|
|
360
|
-
}
|
|
361
|
-
entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
362
|
-
return sha256Hex(stableStringify(entries));
|
|
363
|
-
}
|
|
364
|
-
function stableStringify(value) {
|
|
365
|
-
if (value === void 0) return "null";
|
|
366
|
-
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
367
|
-
if (Array.isArray(value)) {
|
|
368
|
-
return `[${value.map(stableStringify).join(",")}]`;
|
|
369
|
-
}
|
|
370
|
-
const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
371
|
-
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
|
|
372
|
-
}
|
|
373
|
-
async function sha256Hex(input) {
|
|
374
|
-
const bytes = new TextEncoder().encode(input);
|
|
375
|
-
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
376
|
-
return hex(new Uint8Array(digest));
|
|
377
|
-
}
|
|
378
|
-
function hex(bytes) {
|
|
379
|
-
let s = "";
|
|
380
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
381
|
-
s += bytes[i].toString(16).padStart(2, "0");
|
|
382
|
-
}
|
|
383
|
-
return s;
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// src/diff.ts
|
|
387
|
-
function diffSnapshots(before, after) {
|
|
388
|
-
const beforeStepsById = new Map(before.steps.map((s) => [s.id, s]));
|
|
389
|
-
const afterStepsById = new Map(after.steps.map((s) => [s.id, s]));
|
|
390
|
-
const addedSteps = [];
|
|
391
|
-
const removedSteps = [];
|
|
392
|
-
for (const id of afterStepsById.keys()) {
|
|
393
|
-
if (!beforeStepsById.has(id)) addedSteps.push(id);
|
|
394
|
-
}
|
|
395
|
-
for (const id of beforeStepsById.keys()) {
|
|
396
|
-
if (!afterStepsById.has(id)) removedSteps.push(id);
|
|
397
|
-
}
|
|
398
|
-
addedSteps.sort();
|
|
399
|
-
removedSteps.sort();
|
|
400
|
-
const changedEdges = [];
|
|
401
|
-
const changedPredicates = [];
|
|
402
|
-
for (const id of afterStepsById.keys()) {
|
|
403
|
-
const beforeStep = beforeStepsById.get(id);
|
|
404
|
-
const afterStep = afterStepsById.get(id);
|
|
405
|
-
if (beforeStep === void 0 || afterStep === void 0) continue;
|
|
406
|
-
diffEdges(id, beforeStep, afterStep, changedEdges);
|
|
407
|
-
diffFields(beforeStep, afterStep, changedPredicates);
|
|
408
|
-
}
|
|
409
|
-
changedEdges.sort(
|
|
410
|
-
(a, b) => a.to !== b.to ? cmp(a.to, b.to) : cmp(a.from, b.from)
|
|
411
|
-
);
|
|
412
|
-
changedPredicates.sort(
|
|
413
|
-
(a, b) => a.stepId !== b.stepId ? cmp(a.stepId, b.stepId) : cmp(a.field, b.field)
|
|
414
|
-
);
|
|
415
|
-
return { addedSteps, removedSteps, changedEdges, changedPredicates };
|
|
416
|
-
}
|
|
417
|
-
function diffEdges(stepId, before, after, out) {
|
|
418
|
-
const beforeSet = new Set(before.needs);
|
|
419
|
-
const afterSet = new Set(after.needs);
|
|
420
|
-
for (const upstream of afterSet) {
|
|
421
|
-
if (!beforeSet.has(upstream)) {
|
|
422
|
-
out.push({
|
|
423
|
-
from: upstream,
|
|
424
|
-
to: stepId,
|
|
425
|
-
before: "absent",
|
|
426
|
-
after: "needed"
|
|
427
|
-
});
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
for (const upstream of beforeSet) {
|
|
431
|
-
if (!afterSet.has(upstream)) {
|
|
432
|
-
out.push({
|
|
433
|
-
from: upstream,
|
|
434
|
-
to: stepId,
|
|
435
|
-
before: "needed",
|
|
436
|
-
after: "absent"
|
|
437
|
-
});
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
function diffFields(before, after, out) {
|
|
442
|
-
const id = after.id;
|
|
443
|
-
if (before.kind !== after.kind) {
|
|
444
|
-
out.push({ stepId: id, field: "kind" });
|
|
445
|
-
}
|
|
446
|
-
if (before.whenHash !== after.whenHash) {
|
|
447
|
-
out.push({ stepId: id, field: "when" });
|
|
448
|
-
}
|
|
449
|
-
if (!retryEq(before.retry, after.retry)) {
|
|
450
|
-
out.push({ stepId: id, field: "retry" });
|
|
451
|
-
}
|
|
452
|
-
if (before.timeoutMs !== after.timeoutMs) {
|
|
453
|
-
out.push({ stepId: id, field: "timeoutMs" });
|
|
454
|
-
}
|
|
455
|
-
if (!schemaEq(before.signalSchema, after.signalSchema)) {
|
|
456
|
-
out.push({ stepId: id, field: "signalSchema" });
|
|
457
|
-
}
|
|
458
|
-
if (!armsEq(before.matchArms, after.matchArms)) {
|
|
459
|
-
out.push({ stepId: id, field: "matchArms" });
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
function retryEq(a, b) {
|
|
463
|
-
if (a === b) return true;
|
|
464
|
-
if (a === void 0 || b === void 0) return false;
|
|
465
|
-
return a.maxAttempts === b.maxAttempts && a.backoff === b.backoff && a.initialDelayMs === b.initialDelayMs && a.maxDelayMs === b.maxDelayMs;
|
|
466
|
-
}
|
|
467
|
-
function schemaEq(a, b) {
|
|
468
|
-
if (a === b) return true;
|
|
469
|
-
if (a === void 0 || b === void 0) return false;
|
|
470
|
-
return a.vendor === b.vendor && a.version === b.version && a.validateHash === b.validateHash;
|
|
471
|
-
}
|
|
472
|
-
function armsEq(a, b) {
|
|
473
|
-
if (a === b) return true;
|
|
474
|
-
if (a === void 0 || b === void 0) return false;
|
|
475
|
-
if (a.length !== b.length) return false;
|
|
476
|
-
for (let i = 0; i < a.length; i++) {
|
|
477
|
-
const x = a[i];
|
|
478
|
-
const y = b[i];
|
|
479
|
-
if (x === void 0 || y === void 0) return false;
|
|
480
|
-
if (x.id !== y.id) return false;
|
|
481
|
-
if (x.otherwise !== y.otherwise) return false;
|
|
482
|
-
if (x.whenHash !== y.whenHash) return false;
|
|
483
|
-
if (x.stepIds.length !== y.stepIds.length) return false;
|
|
484
|
-
for (let j = 0; j < x.stepIds.length; j++) {
|
|
485
|
-
if (x.stepIds[j] !== y.stepIds[j]) return false;
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
return true;
|
|
489
|
-
}
|
|
490
|
-
function cmp(a, b) {
|
|
491
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
492
|
-
}
|
|
493
|
-
|
|
494
152
|
// src/run-id.ts
|
|
495
153
|
var RunId = {
|
|
496
154
|
parse(s) {
|
|
@@ -519,17 +177,17 @@ async function deriveChildRunId(key) {
|
|
|
519
177
|
const bytes = new Uint8Array(digest).subarray(0, 16);
|
|
520
178
|
bytes[6] = (bytes[6] ?? 0) & 15 | 80;
|
|
521
179
|
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
522
|
-
const
|
|
180
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
|
|
523
181
|
""
|
|
524
182
|
);
|
|
525
|
-
const uuid = `${
|
|
183
|
+
const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
|
526
184
|
return `run-${uuid}`;
|
|
527
185
|
}
|
|
528
186
|
|
|
529
187
|
// src/exec/hooks.ts
|
|
530
188
|
function makeHooks(deps) {
|
|
531
189
|
async function fireHook(hook, event, hookName) {
|
|
532
|
-
if (deps.fireHooks
|
|
190
|
+
if (!deps.fireHooks) return;
|
|
533
191
|
if (hook === void 0) return;
|
|
534
192
|
try {
|
|
535
193
|
await hook(event);
|
|
@@ -549,194 +207,6 @@ function makeHooks(deps) {
|
|
|
549
207
|
return { fireHook, fireStepLifecycle };
|
|
550
208
|
}
|
|
551
209
|
|
|
552
|
-
// src/scheduler.ts
|
|
553
|
-
function nextRunnable({
|
|
554
|
-
flow: flow2,
|
|
555
|
-
runState,
|
|
556
|
-
input
|
|
557
|
-
}) {
|
|
558
|
-
const runnable = [];
|
|
559
|
-
const skip = [];
|
|
560
|
-
for (const [stepId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
561
|
-
if (stepStateOf(runState, stepId).tag !== "pending") continue;
|
|
562
|
-
const gate = gateStep(getDef(step), runState, input);
|
|
563
|
-
switch (gate.kind) {
|
|
564
|
-
case "run":
|
|
565
|
-
runnable.push(stepId);
|
|
566
|
-
break;
|
|
567
|
-
case "skip":
|
|
568
|
-
skip.push({ stepId, reason: gate.reason });
|
|
569
|
-
break;
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
return { runnable, skip };
|
|
573
|
-
}
|
|
574
|
-
function gateStep(def, runState, input) {
|
|
575
|
-
const parent = checkParentMatch(def, runState);
|
|
576
|
-
if (parent !== "ready") return gateFor(parent);
|
|
577
|
-
const upstream = checkUpstream(def, runState);
|
|
578
|
-
if (upstream !== "ready") return gateFor(upstream);
|
|
579
|
-
const when = def.kind === "match" ? void 0 : def.when;
|
|
580
|
-
if (when) {
|
|
581
|
-
const needs = resolveNeeds(
|
|
582
|
-
def,
|
|
583
|
-
(id) => resolvedOf(stepStateOf(runState, id))
|
|
584
|
-
);
|
|
585
|
-
if (!when({ input, needs })) return { kind: "skip", reason: "when-false" };
|
|
586
|
-
}
|
|
587
|
-
return { kind: "run" };
|
|
588
|
-
}
|
|
589
|
-
function gateFor(status) {
|
|
590
|
-
switch (status) {
|
|
591
|
-
case "blocked":
|
|
592
|
-
return { kind: "block" };
|
|
593
|
-
case "transitive-skip":
|
|
594
|
-
return { kind: "skip", reason: "transitive" };
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
function checkUpstream(def, runState) {
|
|
598
|
-
for (const ref of Object.values(def.needs)) {
|
|
599
|
-
const upstreamState = stepStateOf(runState, ref.step.id);
|
|
600
|
-
if (upstreamState.tag === "completed") continue;
|
|
601
|
-
if (ref.optional && upstreamState.tag === "skipped") continue;
|
|
602
|
-
if (upstreamState.tag === "skipped" || upstreamState.tag === "failed") {
|
|
603
|
-
return "transitive-skip";
|
|
604
|
-
}
|
|
605
|
-
return "blocked";
|
|
606
|
-
}
|
|
607
|
-
return "ready";
|
|
608
|
-
}
|
|
609
|
-
function checkParentMatch(def, runState) {
|
|
610
|
-
if (!def.parentMatch) return "ready";
|
|
611
|
-
const { matchId, armId } = def.parentMatch;
|
|
612
|
-
const parentState = stepStateOf(runState, matchId);
|
|
613
|
-
if (parentState.tag === "failed" || parentState.tag === "skipped") {
|
|
614
|
-
return "transitive-skip";
|
|
615
|
-
}
|
|
616
|
-
const selected = runState.selectedArms[matchId] ?? null;
|
|
617
|
-
if (selected === null) return "blocked";
|
|
618
|
-
return selected === armId ? "ready" : "transitive-skip";
|
|
619
|
-
}
|
|
620
|
-
function aggregateMatch(matchId, flow2, runState) {
|
|
621
|
-
const step = asStepMapWithDefs(flow2.steps)[matchId];
|
|
622
|
-
if (!step) return { kind: "pending" };
|
|
623
|
-
const def = getDef(step);
|
|
624
|
-
if (def.kind !== "match") return { kind: "pending" };
|
|
625
|
-
const selected = runState.selectedArms[matchId] ?? null;
|
|
626
|
-
if (selected === null) return { kind: "pending" };
|
|
627
|
-
const arm = def.arms.find((a) => a.id === selected);
|
|
628
|
-
if (!arm) return { kind: "pending" };
|
|
629
|
-
for (const stepId of arm.stepIds) {
|
|
630
|
-
const state = stepStateOf(runState, stepId);
|
|
631
|
-
if (state.tag === "failed")
|
|
632
|
-
return { kind: "fail-fast", error: state.error };
|
|
633
|
-
}
|
|
634
|
-
const output = {};
|
|
635
|
-
for (const stepId of arm.stepIds) {
|
|
636
|
-
const state = stepStateOf(runState, stepId);
|
|
637
|
-
if (!isStepTerminal(state)) return { kind: "pending" };
|
|
638
|
-
output[stripArmPrefix(matchId, arm.id, stepId)] = outputOf(state);
|
|
639
|
-
}
|
|
640
|
-
return { kind: "complete", output };
|
|
641
|
-
}
|
|
642
|
-
function stripArmPrefix(matchId, armId, stepId) {
|
|
643
|
-
const prefix = `${matchId}.${armId}.`;
|
|
644
|
-
if (stepId.startsWith(prefix)) return stepId.slice(prefix.length);
|
|
645
|
-
return stepId;
|
|
646
|
-
}
|
|
647
|
-
function flowTermination(flow2, runState) {
|
|
648
|
-
let failure;
|
|
649
|
-
for (const stepId of Object.keys(flow2.steps)) {
|
|
650
|
-
const state = stepStateOf(runState, stepId);
|
|
651
|
-
if (!isStepTerminal(state)) return { kind: "running" };
|
|
652
|
-
if (state.tag === "failed" && failure === void 0) failure = state.error;
|
|
653
|
-
}
|
|
654
|
-
if (failure !== void 0) return { kind: "failed", error: failure };
|
|
655
|
-
return { kind: "succeeded" };
|
|
656
|
-
}
|
|
657
|
-
function nextTransition(flow2, runState) {
|
|
658
|
-
const promotions = readyPromotions(flow2, runState);
|
|
659
|
-
if (promotions.length > 0) return { kind: "promote-match", promotions };
|
|
660
|
-
const term = flowTermination(flow2, runState);
|
|
661
|
-
switch (term.kind) {
|
|
662
|
-
case "succeeded":
|
|
663
|
-
case "failed": {
|
|
664
|
-
if (isTerminalRun(runState)) return { kind: "settled" };
|
|
665
|
-
if (term.kind === "failed") return { kind: "fail", error: term.error };
|
|
666
|
-
return { kind: "complete", output: computeFlowOutput(flow2, runState) };
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
const input = runState.input;
|
|
670
|
-
const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
|
|
671
|
-
if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
|
|
672
|
-
if (skip.length > 0) return { kind: "skip", skip };
|
|
673
|
-
return { kind: "waiting" };
|
|
674
|
-
}
|
|
675
|
-
function readyPromotions(flow2, runState) {
|
|
676
|
-
const out = [];
|
|
677
|
-
for (const [matchId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
678
|
-
const def = getDef(step);
|
|
679
|
-
if (def.kind !== "match") continue;
|
|
680
|
-
const state = stepStateOf(runState, matchId);
|
|
681
|
-
if (state.tag !== "running") continue;
|
|
682
|
-
const agg = aggregateMatch(matchId, flow2, runState);
|
|
683
|
-
if (agg.kind === "pending") continue;
|
|
684
|
-
const attempt = attemptOf(state);
|
|
685
|
-
if (agg.kind === "fail-fast") {
|
|
686
|
-
out.push({
|
|
687
|
-
matchId,
|
|
688
|
-
attempt,
|
|
689
|
-
result: { kind: "fail", error: agg.error }
|
|
690
|
-
});
|
|
691
|
-
} else {
|
|
692
|
-
out.push({
|
|
693
|
-
matchId,
|
|
694
|
-
attempt,
|
|
695
|
-
result: { kind: "complete", output: agg.output }
|
|
696
|
-
});
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
return out;
|
|
700
|
-
}
|
|
701
|
-
function computeFlowOutput(flow2, runState) {
|
|
702
|
-
if (flow2.output === void 0) return null;
|
|
703
|
-
const stepOutputs = {};
|
|
704
|
-
for (const [sid, sstate] of Object.entries(runState.steps)) {
|
|
705
|
-
if (sstate.tag === "completed") stepOutputs[sid] = sstate.output;
|
|
706
|
-
}
|
|
707
|
-
return flow2.output(stepOutputs);
|
|
708
|
-
}
|
|
709
|
-
function descendantsOf(flow2, stepId) {
|
|
710
|
-
const children = /* @__PURE__ */ new Map();
|
|
711
|
-
const addEdge = (from, to) => {
|
|
712
|
-
const bucket = children.get(from);
|
|
713
|
-
if (bucket) bucket.push(to);
|
|
714
|
-
else children.set(from, [to]);
|
|
715
|
-
};
|
|
716
|
-
for (const [id, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
717
|
-
const def = getDef(step);
|
|
718
|
-
for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
|
|
719
|
-
if (def.kind === "match") {
|
|
720
|
-
for (const arm of def.arms) {
|
|
721
|
-
for (const armStepId of arm.stepIds) addEdge(id, armStepId);
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
const out = [stepId];
|
|
726
|
-
const seen = /* @__PURE__ */ new Set([stepId]);
|
|
727
|
-
for (let i = 0; i < out.length; i++) {
|
|
728
|
-
const current = out[i];
|
|
729
|
-
if (current === void 0) continue;
|
|
730
|
-
for (const child of children.get(current) ?? []) {
|
|
731
|
-
if (seen.has(child)) continue;
|
|
732
|
-
if (!(child in flow2.steps)) continue;
|
|
733
|
-
seen.add(child);
|
|
734
|
-
out.push(child);
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
return out;
|
|
738
|
-
}
|
|
739
|
-
|
|
740
210
|
// src/idempotency.ts
|
|
741
211
|
function makeIdempotencyKey(runId, stepId) {
|
|
742
212
|
return (scope) => `nagi:${runId}:${stepId}:${scope}`;
|
|
@@ -748,7 +218,7 @@ function makeOnce({
|
|
|
748
218
|
}) {
|
|
749
219
|
return async function once(scope, fn) {
|
|
750
220
|
const cached = await store.getOnce(runId, stepId, scope);
|
|
751
|
-
if (cached
|
|
221
|
+
if (cached.tag === "hit") return cached.value;
|
|
752
222
|
const value = await fn();
|
|
753
223
|
await store.recordOnce(runId, stepId, scope, value);
|
|
754
224
|
return value;
|
|
@@ -762,7 +232,7 @@ var NagiAbortError = class extends Error {
|
|
|
762
232
|
kind;
|
|
763
233
|
constructor(runId, kind) {
|
|
764
234
|
super(
|
|
765
|
-
kind === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by
|
|
235
|
+
kind === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by replay({ from }) \u2014 ctx.signal aborted.`
|
|
766
236
|
);
|
|
767
237
|
this.name = "AbortError";
|
|
768
238
|
this.runId = runId;
|
|
@@ -788,98 +258,111 @@ function resolveExecutionFact(args) {
|
|
|
788
258
|
abortedHere: false
|
|
789
259
|
};
|
|
790
260
|
}
|
|
791
|
-
function
|
|
792
|
-
const { store, runId, stepId, attempt, ac, intervalMs } = args;
|
|
261
|
+
function every(intervalMs, tick) {
|
|
793
262
|
let stopped = false;
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
}
|
|
804
|
-
if (isAbortRequested(stepStateOf(s, stepId), attempt)) {
|
|
805
|
-
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
|
|
806
|
-
return;
|
|
263
|
+
let timer;
|
|
264
|
+
let running = Promise.resolve();
|
|
265
|
+
const schedule = () => {
|
|
266
|
+
timer = setTimeout(() => {
|
|
267
|
+
running = (async () => {
|
|
268
|
+
let next;
|
|
269
|
+
try {
|
|
270
|
+
next = await tick();
|
|
271
|
+
} catch {
|
|
807
272
|
}
|
|
808
|
-
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
}
|
|
273
|
+
if (!stopped && next !== "stop") schedule();
|
|
274
|
+
})();
|
|
275
|
+
}, intervalMs);
|
|
276
|
+
};
|
|
277
|
+
schedule();
|
|
812
278
|
return {
|
|
813
|
-
stop: () => {
|
|
279
|
+
stop: async () => {
|
|
814
280
|
stopped = true;
|
|
281
|
+
clearTimeout(timer);
|
|
282
|
+
await running;
|
|
815
283
|
}
|
|
816
284
|
};
|
|
817
285
|
}
|
|
286
|
+
function startCancelWatcher(args) {
|
|
287
|
+
const { store, runId, stepId, attempt, ac, intervalMs } = args;
|
|
288
|
+
return every(intervalMs, async () => {
|
|
289
|
+
try {
|
|
290
|
+
const s = await store.loadRunState(runId);
|
|
291
|
+
if (isTerminalRun(s)) {
|
|
292
|
+
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
|
|
293
|
+
return "stop";
|
|
294
|
+
}
|
|
295
|
+
if (isAbortRequested(stepStateOf(s, stepId), attempt)) {
|
|
296
|
+
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
|
|
297
|
+
return "stop";
|
|
298
|
+
}
|
|
299
|
+
} catch {
|
|
300
|
+
}
|
|
301
|
+
return void 0;
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
function startDeadline(args) {
|
|
305
|
+
const { runId, stepId, attempt, timeoutMs, ac } = args;
|
|
306
|
+
const timer = setTimeout(() => {
|
|
307
|
+
if (!ac.signal.aborted)
|
|
308
|
+
ac.abort(new NagiStepTimeoutError({ runId, stepId, attempt, timeoutMs }));
|
|
309
|
+
}, timeoutMs);
|
|
310
|
+
return {
|
|
311
|
+
stop: () => clearTimeout(timer)
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
function unwrapDeadline(err, signal) {
|
|
315
|
+
return signal.reason instanceof NagiStepTimeoutError ? signal.reason : err;
|
|
316
|
+
}
|
|
818
317
|
var DEFAULT_HEARTBEAT_LEASE_MS = 12e4;
|
|
819
318
|
var DEFAULT_HEARTBEAT_INTERVAL_MS = 4e4;
|
|
820
319
|
var DEFAULT_LEASE_HOLD_WARN_MS = 3e5;
|
|
821
320
|
function startHeartbeat(args) {
|
|
822
321
|
const {
|
|
823
322
|
queue,
|
|
824
|
-
store,
|
|
825
|
-
runId,
|
|
826
|
-
stepId,
|
|
827
|
-
attempt,
|
|
828
|
-
receipt,
|
|
829
|
-
intervalMs,
|
|
830
|
-
leaseMs,
|
|
831
|
-
holdWarnMs,
|
|
832
|
-
emitLog
|
|
833
|
-
} = args;
|
|
834
|
-
|
|
835
|
-
let
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
msg: "heartbeat: step is holding a worker slot unusually long \u2014 slow handler, or an in-step wait that should be a b.signal step?",
|
|
849
|
-
attrs: { runId, stepId, attempt, heldMs }
|
|
850
|
-
});
|
|
851
|
-
}
|
|
852
|
-
}
|
|
853
|
-
await Promise.all([
|
|
854
|
-
queue.extend(receipt, leaseMs).catch((err) => {
|
|
855
|
-
emitLog({
|
|
856
|
-
level: "warn",
|
|
857
|
-
msg: "heartbeat: failed to extend message visibility",
|
|
858
|
-
attrs: { receipt, error: String(err) }
|
|
859
|
-
});
|
|
860
|
-
}),
|
|
861
|
-
store.extendLease(runId, stepId, attempt, leaseMs).catch((err) => {
|
|
862
|
-
emitLog({
|
|
863
|
-
level: "warn",
|
|
864
|
-
msg: "heartbeat: failed to extend store lease",
|
|
865
|
-
attrs: { runId, stepId, attempt, error: String(err) }
|
|
866
|
-
});
|
|
867
|
-
})
|
|
868
|
-
]);
|
|
869
|
-
if (!stopped) schedule();
|
|
870
|
-
})();
|
|
871
|
-
}, intervalMs);
|
|
872
|
-
};
|
|
873
|
-
schedule();
|
|
874
|
-
return {
|
|
875
|
-
// Clear the pending timer so a settled step strands nothing on the event
|
|
876
|
-
// loop — without this every fast step would leak a timer for up to
|
|
877
|
-
// intervalMs, keeping the process alive and delaying clean shutdown.
|
|
878
|
-
stop: () => {
|
|
879
|
-
stopped = true;
|
|
880
|
-
if (timer !== void 0) clearTimeout(timer);
|
|
323
|
+
store,
|
|
324
|
+
runId,
|
|
325
|
+
stepId,
|
|
326
|
+
attempt,
|
|
327
|
+
receipt,
|
|
328
|
+
intervalMs,
|
|
329
|
+
leaseMs,
|
|
330
|
+
holdWarnMs,
|
|
331
|
+
emitLog
|
|
332
|
+
} = args;
|
|
333
|
+
const startedAtMs = Date.now();
|
|
334
|
+
let warnedCrossings = 0;
|
|
335
|
+
return every(intervalMs, async () => {
|
|
336
|
+
if (holdWarnMs > 0) {
|
|
337
|
+
const heldMs = Date.now() - startedAtMs;
|
|
338
|
+
const crossings = Math.floor(heldMs / holdWarnMs);
|
|
339
|
+
if (crossings > warnedCrossings) {
|
|
340
|
+
warnedCrossings = crossings;
|
|
341
|
+
emitLog({
|
|
342
|
+
level: "warn",
|
|
343
|
+
msg: "heartbeat: step is holding a worker slot unusually long \u2014 slow handler, or an in-step wait that should be a b.signal step?",
|
|
344
|
+
attrs: { runId, stepId, attempt, heldMs }
|
|
345
|
+
});
|
|
346
|
+
}
|
|
881
347
|
}
|
|
882
|
-
|
|
348
|
+
await Promise.all([
|
|
349
|
+
queue.extend(receipt, leaseMs).catch((err) => {
|
|
350
|
+
emitLog({
|
|
351
|
+
level: "warn",
|
|
352
|
+
msg: "heartbeat: failed to extend message visibility",
|
|
353
|
+
attrs: { receipt, error: String(err) }
|
|
354
|
+
});
|
|
355
|
+
}),
|
|
356
|
+
store.extendLease(runId, stepId, attempt, leaseMs).catch((err) => {
|
|
357
|
+
emitLog({
|
|
358
|
+
level: "warn",
|
|
359
|
+
msg: "heartbeat: failed to extend store lease",
|
|
360
|
+
attrs: { runId, stepId, attempt, error: String(err) }
|
|
361
|
+
});
|
|
362
|
+
})
|
|
363
|
+
]);
|
|
364
|
+
return void 0;
|
|
365
|
+
});
|
|
883
366
|
}
|
|
884
367
|
function classifyFailure(args) {
|
|
885
368
|
const { attempt, policy, err, runIsCanceled, stepAborted } = args;
|
|
@@ -958,19 +441,23 @@ function makeActivityCtx(args) {
|
|
|
958
441
|
}
|
|
959
442
|
|
|
960
443
|
// src/exec/message.ts
|
|
961
|
-
function
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
444
|
+
function startInput(def, input) {
|
|
445
|
+
switch (def.kind) {
|
|
446
|
+
case "task":
|
|
447
|
+
case "activity":
|
|
448
|
+
case "streaming":
|
|
449
|
+
case "subflow":
|
|
450
|
+
return input;
|
|
451
|
+
case "signal":
|
|
452
|
+
return null;
|
|
965
453
|
}
|
|
966
|
-
return n;
|
|
967
454
|
}
|
|
968
455
|
function makeMessage(deps, hooks, progression) {
|
|
969
456
|
const { fireHook, fireStepLifecycle } = hooks;
|
|
970
457
|
const { advance } = progression;
|
|
971
458
|
async function dispatchMessage(message) {
|
|
972
459
|
const { queue } = deps;
|
|
973
|
-
const resolution = await deps.
|
|
460
|
+
const resolution = await deps.flowOf(message.runId);
|
|
974
461
|
let flow2;
|
|
975
462
|
switch (resolution.kind) {
|
|
976
463
|
case "current":
|
|
@@ -1016,7 +503,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1016
503
|
} catch (err) {
|
|
1017
504
|
outcome = await handleStepError({ flow: flow2, message, def, err });
|
|
1018
505
|
} finally {
|
|
1019
|
-
heartbeat.stop();
|
|
506
|
+
await heartbeat.stop();
|
|
1020
507
|
}
|
|
1021
508
|
await interpret({ flow: flow2, message, def, startedAt, outcome });
|
|
1022
509
|
await queue.ack(message.receipt);
|
|
@@ -1061,8 +548,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1061
548
|
new Date(startedAt.getTime() + def.timeoutMs)
|
|
1062
549
|
);
|
|
1063
550
|
}
|
|
1064
|
-
const
|
|
1065
|
-
const input = startCarriesInput ? state.input : null;
|
|
551
|
+
const input = startInput(def, state.input);
|
|
1066
552
|
await fireStepLifecycle(
|
|
1067
553
|
handler?.onStart,
|
|
1068
554
|
deps.hooks?.onStepStart,
|
|
@@ -1083,26 +569,9 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1083
569
|
const { runId, stepId, attempt } = message;
|
|
1084
570
|
switch (def.kind) {
|
|
1085
571
|
case "task":
|
|
1086
|
-
case "
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
runId,
|
|
1090
|
-
stepId,
|
|
1091
|
-
attempt,
|
|
1092
|
-
state
|
|
1093
|
-
});
|
|
1094
|
-
return skipAdvance ? { tag: "parked" } : { tag: "completed", output };
|
|
1095
|
-
}
|
|
1096
|
-
case "activity": {
|
|
1097
|
-
const { output, skipAdvance } = await executeActivity({
|
|
1098
|
-
def,
|
|
1099
|
-
runId,
|
|
1100
|
-
stepId,
|
|
1101
|
-
attempt,
|
|
1102
|
-
state
|
|
1103
|
-
});
|
|
1104
|
-
return skipAdvance ? { tag: "parked" } : { tag: "completed", output };
|
|
1105
|
-
}
|
|
572
|
+
case "activity":
|
|
573
|
+
case "streaming":
|
|
574
|
+
return await executeHandler({ def, runId, stepId, attempt, state });
|
|
1106
575
|
case "signal": {
|
|
1107
576
|
const settled = await deps.store.settleSignal({
|
|
1108
577
|
runId,
|
|
@@ -1127,9 +596,6 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1127
596
|
}
|
|
1128
597
|
return { tag: "parked" };
|
|
1129
598
|
}
|
|
1130
|
-
case "match":
|
|
1131
|
-
await executeMatch({ def, runId, stepId, state });
|
|
1132
|
-
return { tag: "advance" };
|
|
1133
599
|
case "subflow":
|
|
1134
600
|
return await executeSubflow({ def, runId, stepId, attempt, state });
|
|
1135
601
|
}
|
|
@@ -1163,34 +629,25 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1163
629
|
return;
|
|
1164
630
|
}
|
|
1165
631
|
}
|
|
1166
|
-
async function
|
|
1167
|
-
const { input, needs, ctx, runId, stepId } = args;
|
|
1168
|
-
if (def.kind !== "streaming") {
|
|
1169
|
-
return await def.run({ input, needs, ctx });
|
|
1170
|
-
}
|
|
632
|
+
async function withEmit(runId, stepId, base, body) {
|
|
1171
633
|
let emitActive = true;
|
|
1172
|
-
const streamingCtx = {
|
|
1173
|
-
...ctx,
|
|
1174
|
-
emit: async (chunk) => {
|
|
1175
|
-
if (emitActive)
|
|
1176
|
-
deps.streamTransport?.publishChunk(runId, stepId, chunk);
|
|
1177
|
-
}
|
|
1178
|
-
};
|
|
1179
634
|
try {
|
|
1180
|
-
return await
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
635
|
+
return await body({
|
|
636
|
+
...base,
|
|
637
|
+
emit: async (chunk) => {
|
|
638
|
+
if (emitActive)
|
|
639
|
+
deps.streamTransport?.publishChunk(runId, stepId, chunk);
|
|
640
|
+
}
|
|
1184
641
|
});
|
|
1185
642
|
} finally {
|
|
1186
643
|
emitActive = false;
|
|
1187
644
|
}
|
|
1188
645
|
}
|
|
1189
|
-
async function
|
|
646
|
+
async function executeHandler(args) {
|
|
1190
647
|
const { def, runId, stepId, attempt, state } = args;
|
|
1191
648
|
const { store, clock } = deps;
|
|
1192
649
|
const input = state.input;
|
|
1193
|
-
const needs = resolveNeeds(def,
|
|
650
|
+
const needs = resolveNeeds(def, state);
|
|
1194
651
|
const ac = new AbortController();
|
|
1195
652
|
const watcher = startCancelWatcher({
|
|
1196
653
|
store,
|
|
@@ -1198,99 +655,81 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1198
655
|
stepId,
|
|
1199
656
|
attempt,
|
|
1200
657
|
ac,
|
|
1201
|
-
intervalMs:
|
|
658
|
+
intervalMs: CANCEL_POLL_INTERVAL_MS
|
|
1202
659
|
});
|
|
1203
|
-
|
|
1204
|
-
let stepAbortedHere = false;
|
|
1205
|
-
const output = await store.runStep(
|
|
1206
|
-
runId,
|
|
1207
|
-
stepId,
|
|
1208
|
-
attempt,
|
|
1209
|
-
async (tx) => {
|
|
1210
|
-
const ctx = makeStepCtx({
|
|
1211
|
-
runId,
|
|
1212
|
-
stepId,
|
|
1213
|
-
attempt,
|
|
1214
|
-
input,
|
|
1215
|
-
store,
|
|
1216
|
-
clock,
|
|
1217
|
-
tx,
|
|
1218
|
-
signal: ac.signal,
|
|
1219
|
-
emitLog: deps.emitLog
|
|
1220
|
-
});
|
|
1221
|
-
const out = await runHandler(def, {
|
|
1222
|
-
input,
|
|
1223
|
-
needs,
|
|
1224
|
-
ctx,
|
|
1225
|
-
runId,
|
|
1226
|
-
stepId
|
|
1227
|
-
});
|
|
1228
|
-
const postState = await store.loadRunState(runId);
|
|
1229
|
-
const { fact, abortedHere } = resolveExecutionFact({
|
|
1230
|
-
postState,
|
|
1231
|
-
runId,
|
|
1232
|
-
stepId,
|
|
1233
|
-
attempt,
|
|
1234
|
-
output: out,
|
|
1235
|
-
at: clock.now()
|
|
1236
|
-
});
|
|
1237
|
-
stepAbortedHere = abortedHere;
|
|
1238
|
-
return { output: out, fact };
|
|
1239
|
-
}
|
|
1240
|
-
);
|
|
1241
|
-
return { output, skipAdvance: stepAbortedHere };
|
|
1242
|
-
} finally {
|
|
1243
|
-
watcher.stop();
|
|
1244
|
-
}
|
|
1245
|
-
}
|
|
1246
|
-
async function executeActivity(args) {
|
|
1247
|
-
const { def, runId, stepId, attempt, state } = args;
|
|
1248
|
-
const { store, clock } = deps;
|
|
1249
|
-
const input = state.input;
|
|
1250
|
-
const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
|
|
1251
|
-
const ac = new AbortController();
|
|
1252
|
-
const watcher = startCancelWatcher({
|
|
1253
|
-
store,
|
|
660
|
+
const deadline = def.timeoutMs === void 0 ? void 0 : startDeadline({
|
|
1254
661
|
runId,
|
|
1255
662
|
stepId,
|
|
1256
663
|
attempt,
|
|
1257
|
-
|
|
1258
|
-
|
|
664
|
+
timeoutMs: def.timeoutMs,
|
|
665
|
+
ac
|
|
1259
666
|
});
|
|
1260
|
-
|
|
1261
|
-
|
|
667
|
+
const ctxArgs = {
|
|
668
|
+
runId,
|
|
669
|
+
stepId,
|
|
670
|
+
attempt,
|
|
671
|
+
input,
|
|
672
|
+
store,
|
|
673
|
+
clock,
|
|
674
|
+
signal: ac.signal,
|
|
675
|
+
emitLog: deps.emitLog
|
|
676
|
+
};
|
|
677
|
+
let abortedHere = false;
|
|
678
|
+
const settle = async (output) => {
|
|
679
|
+
const resolved = resolveExecutionFact({
|
|
680
|
+
postState: await store.loadRunState(runId),
|
|
1262
681
|
runId,
|
|
1263
682
|
stepId,
|
|
1264
683
|
attempt,
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
clock,
|
|
1268
|
-
signal: ac.signal,
|
|
1269
|
-
emitLog: deps.emitLog
|
|
684
|
+
output,
|
|
685
|
+
at: clock.now()
|
|
1270
686
|
});
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
687
|
+
abortedHere = resolved.abortedHere;
|
|
688
|
+
return { output, fact: resolved.fact };
|
|
689
|
+
};
|
|
690
|
+
const inTx = (body) => store.runStep(
|
|
691
|
+
runId,
|
|
692
|
+
stepId,
|
|
693
|
+
attempt,
|
|
694
|
+
async (tx) => settle(await body(makeStepCtx({ ...ctxArgs, tx })))
|
|
695
|
+
);
|
|
696
|
+
try {
|
|
697
|
+
let output;
|
|
698
|
+
switch (def.kind) {
|
|
699
|
+
case "task":
|
|
700
|
+
output = await inTx((ctx) => def.run({ input, needs, ctx }));
|
|
701
|
+
break;
|
|
702
|
+
case "streaming":
|
|
703
|
+
output = await inTx(
|
|
704
|
+
(base) => withEmit(
|
|
705
|
+
runId,
|
|
706
|
+
stepId,
|
|
707
|
+
base,
|
|
708
|
+
(ctx) => def.run({ input, needs, ctx })
|
|
709
|
+
)
|
|
710
|
+
);
|
|
711
|
+
break;
|
|
712
|
+
// The body runs OUTSIDE the durable transaction (RFC 0013): an external
|
|
713
|
+
// effect must not hold a tx for minutes. Only the terminal fact commits,
|
|
714
|
+
// in a short runStep tx, through the same settle as a task.
|
|
715
|
+
case "activity": {
|
|
716
|
+
const ctx = makeActivityCtx(ctxArgs);
|
|
717
|
+
const out = await def.run({ input, needs, ctx });
|
|
718
|
+
output = await store.runStep(
|
|
1281
719
|
runId,
|
|
1282
720
|
stepId,
|
|
1283
721
|
attempt,
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
stepAbortedHere = abortedHere;
|
|
1288
|
-
return { output: out, fact };
|
|
722
|
+
() => settle(out)
|
|
723
|
+
);
|
|
724
|
+
break;
|
|
1289
725
|
}
|
|
1290
|
-
|
|
1291
|
-
return {
|
|
726
|
+
}
|
|
727
|
+
return abortedHere ? { tag: "parked" } : { tag: "completed", output };
|
|
728
|
+
} catch (err) {
|
|
729
|
+
throw unwrapDeadline(err, ac.signal);
|
|
1292
730
|
} finally {
|
|
1293
|
-
watcher.stop();
|
|
731
|
+
await watcher.stop();
|
|
732
|
+
deadline?.stop();
|
|
1294
733
|
}
|
|
1295
734
|
}
|
|
1296
735
|
async function executeSubflow(args) {
|
|
@@ -1301,7 +740,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1301
740
|
`Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
|
|
1302
741
|
);
|
|
1303
742
|
}
|
|
1304
|
-
const generation =
|
|
743
|
+
const generation = state.resetCounts[stepId] ?? 0;
|
|
1305
744
|
const childRunId = await deriveChildRunId({ runId, stepId, generation });
|
|
1306
745
|
const childState = await deps.store.loadRunState(childRunId);
|
|
1307
746
|
if (isTerminalRun(childState)) {
|
|
@@ -1309,7 +748,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1309
748
|
return { tag: "parked" };
|
|
1310
749
|
}
|
|
1311
750
|
const parentInput = state.input;
|
|
1312
|
-
const needs = resolveNeeds(def,
|
|
751
|
+
const needs = resolveNeeds(def, state);
|
|
1313
752
|
const childInput = def.buildInput({ input: parentInput, needs });
|
|
1314
753
|
await deps.startChildRun({
|
|
1315
754
|
child,
|
|
@@ -1319,17 +758,6 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1319
758
|
});
|
|
1320
759
|
return { tag: "parked" };
|
|
1321
760
|
}
|
|
1322
|
-
async function executeMatch(args) {
|
|
1323
|
-
const { def, runId, stepId, state } = args;
|
|
1324
|
-
const { store, clock } = deps;
|
|
1325
|
-
const input = state.input;
|
|
1326
|
-
const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
|
|
1327
|
-
const armId = selectArm(def, { input, needs });
|
|
1328
|
-
await store.appendFact(
|
|
1329
|
-
runId,
|
|
1330
|
-
Facts.matchArmSelected(runId, stepId, armId, clock.now())
|
|
1331
|
-
);
|
|
1332
|
-
}
|
|
1333
761
|
async function handleStepError(args) {
|
|
1334
762
|
const { flow: flow2, message, def, err } = args;
|
|
1335
763
|
const { store, queue, clock } = deps;
|
|
@@ -1382,9 +810,8 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1382
810
|
}
|
|
1383
811
|
case "failed": {
|
|
1384
812
|
const at = clock.now();
|
|
1385
|
-
await store.
|
|
813
|
+
await store.appendFact(
|
|
1386
814
|
runId,
|
|
1387
|
-
stepId,
|
|
1388
815
|
Facts.stepFailed(runId, stepId, attempt, error, at)
|
|
1389
816
|
);
|
|
1390
817
|
await fireStepLifecycle(
|
|
@@ -1396,19 +823,20 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1396
823
|
return { tag: "advance" };
|
|
1397
824
|
}
|
|
1398
825
|
case "flowCanceled": {
|
|
1399
|
-
const at = clock.now();
|
|
1400
826
|
await store.appendFact(
|
|
1401
827
|
runId,
|
|
1402
|
-
Facts.stepCanceled(runId, stepId, attempt,
|
|
828
|
+
Facts.stepCanceled(runId, stepId, attempt, clock.now(), error)
|
|
1403
829
|
);
|
|
1404
|
-
await
|
|
1405
|
-
runId,
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
830
|
+
await progression.terminate(
|
|
831
|
+
{ kind: "resolved", runId, flow: flow2 },
|
|
832
|
+
{
|
|
833
|
+
tag: "canceled",
|
|
834
|
+
cause: {
|
|
835
|
+
kind: "concurrency",
|
|
836
|
+
canceledByRunId: outcome.canceledByRunId,
|
|
837
|
+
concurrencyKey: outcome.concurrencyKey
|
|
838
|
+
}
|
|
839
|
+
}
|
|
1412
840
|
);
|
|
1413
841
|
return { tag: "parked" };
|
|
1414
842
|
}
|
|
@@ -1417,191 +845,135 @@ function makeMessage(deps, hooks, progression) {
|
|
|
1417
845
|
return { dispatchMessage };
|
|
1418
846
|
}
|
|
1419
847
|
|
|
1420
|
-
// src/
|
|
1421
|
-
function
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
const
|
|
1427
|
-
const
|
|
1428
|
-
const
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
asStepMapWithDefs(flow2.steps)
|
|
1439
|
-
)) {
|
|
1440
|
-
if (getDef(step).kind === "streaming") streamingStepIds.add(stepId);
|
|
848
|
+
// src/scheduler.ts
|
|
849
|
+
function nextRunnable({
|
|
850
|
+
flow: flow2,
|
|
851
|
+
runState,
|
|
852
|
+
input
|
|
853
|
+
}) {
|
|
854
|
+
const runnable = [];
|
|
855
|
+
const skip = [];
|
|
856
|
+
for (const [stepId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
857
|
+
if (stepStateOf(runState, stepId).tag !== "pending") continue;
|
|
858
|
+
const gate = gateStep(getDef(step), runState, input);
|
|
859
|
+
switch (gate.kind) {
|
|
860
|
+
case "run":
|
|
861
|
+
runnable.push(stepId);
|
|
862
|
+
break;
|
|
863
|
+
case "skip":
|
|
864
|
+
skip.push({ stepId, reason: gate.reason });
|
|
865
|
+
break;
|
|
1441
866
|
}
|
|
1442
867
|
}
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
const previousHash = await store.getRef(flow2.id);
|
|
1453
|
-
if (previousHash !== flowHash) {
|
|
1454
|
-
await store.setRef(flow2.id, flowHash);
|
|
1455
|
-
await store.appendGlobalFact(
|
|
1456
|
-
Facts.flowRefUpdated({
|
|
1457
|
-
flowId: flow2.id,
|
|
1458
|
-
from: previousHash,
|
|
1459
|
-
to: flowHash,
|
|
1460
|
-
at: clock.now()
|
|
1461
|
-
})
|
|
1462
|
-
);
|
|
1463
|
-
}
|
|
868
|
+
return { runnable, skip };
|
|
869
|
+
}
|
|
870
|
+
function gateStep(def, runState, input) {
|
|
871
|
+
const upstream = checkUpstream(def, runState);
|
|
872
|
+
if (upstream !== "ready") return gateFor(upstream);
|
|
873
|
+
if (def.when) {
|
|
874
|
+
const needs = resolveNeeds(def, runState);
|
|
875
|
+
if (!def.when({ input, needs }))
|
|
876
|
+
return { kind: "skip", reason: "when-false" };
|
|
1464
877
|
}
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
878
|
+
return { kind: "run" };
|
|
879
|
+
}
|
|
880
|
+
function gateFor(status) {
|
|
881
|
+
switch (status) {
|
|
882
|
+
case "blocked":
|
|
883
|
+
return { kind: "block" };
|
|
884
|
+
case "transitive-skip":
|
|
885
|
+
return { kind: "skip", reason: "transitive" };
|
|
1473
886
|
}
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
887
|
+
}
|
|
888
|
+
function checkUpstream(def, runState) {
|
|
889
|
+
for (const ref of Object.values(def.needs)) {
|
|
890
|
+
const upstreamState = stepStateOf(runState, ref.step.id);
|
|
891
|
+
if (upstreamState.tag === "completed") continue;
|
|
892
|
+
if (ref.optional && upstreamState.tag === "skipped") continue;
|
|
893
|
+
if (upstreamState.tag === "skipped" || upstreamState.tag === "failed") {
|
|
894
|
+
return "transitive-skip";
|
|
1480
895
|
}
|
|
1481
|
-
return
|
|
896
|
+
return "blocked";
|
|
1482
897
|
}
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
}
|
|
1492
|
-
return { kind: "current", flow: live };
|
|
1493
|
-
}
|
|
1494
|
-
const currentHash = live === void 0 ? null : hashOf(flowId);
|
|
1495
|
-
if (live !== void 0 && currentHash === pinnedHash) {
|
|
1496
|
-
return { kind: "current", flow: live };
|
|
1497
|
-
}
|
|
1498
|
-
const error = new NagiFlowSnapshotGoneError({
|
|
1499
|
-
runId,
|
|
1500
|
-
flowId,
|
|
1501
|
-
pinnedHash,
|
|
1502
|
-
currentHash
|
|
1503
|
-
});
|
|
1504
|
-
return isTerminalRun(state) ? { kind: "gone-terminal", error, live } : { kind: "gone-live", error, live };
|
|
1505
|
-
}
|
|
1506
|
-
const synthesizedByHash = /* @__PURE__ */ new Map();
|
|
1507
|
-
function synthesize(gone) {
|
|
1508
|
-
const { pinnedHash } = gone.error;
|
|
1509
|
-
const cached = synthesizedByHash.get(pinnedHash);
|
|
1510
|
-
if (cached !== void 0) return cached;
|
|
1511
|
-
const pending = synthesizeUncached(gone);
|
|
1512
|
-
synthesizedByHash.set(pinnedHash, pending);
|
|
1513
|
-
pending.catch(() => synthesizedByHash.delete(pinnedHash));
|
|
1514
|
-
return pending;
|
|
1515
|
-
}
|
|
1516
|
-
async function synthesizeUncached(gone) {
|
|
1517
|
-
const { runId, flowId, pinnedHash } = gone.error;
|
|
1518
|
-
if (gone.live === void 0) {
|
|
1519
|
-
throw new NagiRuntimeError(
|
|
1520
|
-
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
1521
|
-
);
|
|
1522
|
-
}
|
|
1523
|
-
const snapshot = await store.loadSnapshot(pinnedHash);
|
|
1524
|
-
if (snapshot === null) {
|
|
1525
|
-
throw new NagiRuntimeError(
|
|
1526
|
-
`Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Nothing can resume it.`
|
|
1527
|
-
);
|
|
1528
|
-
}
|
|
1529
|
-
return synthesizeReplayFlow(
|
|
1530
|
-
snapshot.dag,
|
|
1531
|
-
gone.live
|
|
1532
|
-
);
|
|
898
|
+
return "ready";
|
|
899
|
+
}
|
|
900
|
+
function flowTermination(flow2, runState) {
|
|
901
|
+
let failure;
|
|
902
|
+
for (const stepId of Object.keys(flow2.steps)) {
|
|
903
|
+
const state = stepStateOf(runState, stepId);
|
|
904
|
+
if (!isStepTerminal(state)) return { kind: "running" };
|
|
905
|
+
if (state.tag === "failed" && failure === void 0) failure = state.error;
|
|
1533
906
|
}
|
|
1534
|
-
return {
|
|
1535
|
-
|
|
1536
|
-
has: (flowId) => byId.has(flowId),
|
|
1537
|
-
require: require2,
|
|
1538
|
-
hashOf,
|
|
1539
|
-
isStreaming: (stepId) => streamingStepIds.has(stepId),
|
|
1540
|
-
resolve,
|
|
1541
|
-
synthesize
|
|
1542
|
-
};
|
|
907
|
+
if (failure !== void 0) return { kind: "failed", error: failure };
|
|
908
|
+
return { kind: "succeeded" };
|
|
1543
909
|
}
|
|
1544
|
-
function
|
|
1545
|
-
const
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
);
|
|
910
|
+
function nextTransition(flow2, runState) {
|
|
911
|
+
const term = flowTermination(flow2, runState);
|
|
912
|
+
switch (term.kind) {
|
|
913
|
+
case "succeeded":
|
|
914
|
+
case "failed": {
|
|
915
|
+
if (isTerminalRun(runState)) return { kind: "settled" };
|
|
916
|
+
if (term.kind === "failed") return { kind: "fail", error: term.error };
|
|
917
|
+
return { kind: "complete", output: computeFlowOutput(flow2, runState) };
|
|
1553
918
|
}
|
|
1554
|
-
synthesized[canonStep.id] = attachDef(
|
|
1555
|
-
{ kind: canonStep.kind, id: canonStep.id },
|
|
1556
|
-
getDef(liveStep)
|
|
1557
|
-
);
|
|
1558
919
|
}
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
synthesizedNeeds[upstreamId] = upstreamShell;
|
|
1571
|
-
}
|
|
1572
|
-
setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
|
|
920
|
+
const input = runState.input;
|
|
921
|
+
const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
|
|
922
|
+
if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
|
|
923
|
+
if (skip.length > 0) return { kind: "skip", skip };
|
|
924
|
+
return { kind: "waiting" };
|
|
925
|
+
}
|
|
926
|
+
function computeFlowOutput(flow2, runState) {
|
|
927
|
+
if (flow2.output === void 0) return null;
|
|
928
|
+
const stepOutputs = {};
|
|
929
|
+
for (const [sid, sstate] of Object.entries(runState.steps)) {
|
|
930
|
+
if (sstate.tag === "completed") stepOutputs[sid] = sstate.output;
|
|
1573
931
|
}
|
|
1574
|
-
return
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
932
|
+
return flow2.output(stepOutputs);
|
|
933
|
+
}
|
|
934
|
+
function resetFactsOf(flow2, origin) {
|
|
935
|
+
const { runId, stepId, at } = origin;
|
|
936
|
+
const set = origin.scope === "step" ? [stepId] : descendantsOf(flow2, stepId);
|
|
937
|
+
return set.map(
|
|
938
|
+
(id) => id === stepId ? Facts.stepReset(origin) : Facts.stepReset({ runId, stepId: id, at, cascadedFrom: stepId })
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
function descendantsOf(flow2, stepId) {
|
|
942
|
+
const children = /* @__PURE__ */ new Map();
|
|
943
|
+
const addEdge = (from, to) => {
|
|
944
|
+
const bucket = children.get(from);
|
|
945
|
+
if (bucket) bucket.push(to);
|
|
946
|
+
else children.set(from, [to]);
|
|
1579
947
|
};
|
|
948
|
+
for (const [id, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
949
|
+
for (const upstreamId of needsStepIds(getDef(step)))
|
|
950
|
+
addEdge(upstreamId, id);
|
|
951
|
+
}
|
|
952
|
+
const out = [stepId];
|
|
953
|
+
const seen = /* @__PURE__ */ new Set([stepId]);
|
|
954
|
+
for (let i = 0; i < out.length; i++) {
|
|
955
|
+
const current = out[i];
|
|
956
|
+
if (current === void 0) continue;
|
|
957
|
+
for (const child of children.get(current) ?? []) {
|
|
958
|
+
if (seen.has(child)) continue;
|
|
959
|
+
seen.add(child);
|
|
960
|
+
out.push(child);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return out;
|
|
1580
964
|
}
|
|
1581
965
|
|
|
1582
966
|
// src/exec/progression.ts
|
|
1583
967
|
var MAX_ADVANCE_ITERS = 1024;
|
|
1584
|
-
function
|
|
1585
|
-
|
|
1586
|
-
case "completed":
|
|
1587
|
-
return { kind: "completed", output: child.phase.output };
|
|
1588
|
-
case "failed":
|
|
1589
|
-
return { kind: "failed", error: child.phase.error };
|
|
1590
|
-
case "canceled":
|
|
1591
|
-
return {
|
|
1592
|
-
kind: "canceled",
|
|
1593
|
-
error: cancelCauseToError(childRunId, child.phase.cause)
|
|
1594
|
-
};
|
|
1595
|
-
default:
|
|
1596
|
-
return void 0;
|
|
1597
|
-
}
|
|
968
|
+
function terminalErrorOf(runId, end) {
|
|
969
|
+
return end.tag === "failed" ? end.error : cancelCauseToError(runId, end.cause);
|
|
1598
970
|
}
|
|
1599
971
|
function cancelCauseToError(runId, cause) {
|
|
1600
972
|
switch (cause.kind) {
|
|
1601
973
|
case "concurrency":
|
|
1602
974
|
return {
|
|
1603
975
|
name: "NagiCanceledError",
|
|
1604
|
-
message:
|
|
976
|
+
message: new NagiCanceledError({ runId, ...cause }).message,
|
|
1605
977
|
cause: {
|
|
1606
978
|
canceledByRunId: cause.canceledByRunId,
|
|
1607
979
|
concurrencyKey: cause.concurrencyKey
|
|
@@ -1612,18 +984,31 @@ function cancelCauseToError(runId, cause) {
|
|
|
1612
984
|
name: "NagiCanceledError",
|
|
1613
985
|
message: `Run ${runId} was canceled: ${cause.reason}`
|
|
1614
986
|
};
|
|
1615
|
-
case "operator":
|
|
1616
|
-
return {
|
|
1617
|
-
name: "NagiCanceledError",
|
|
1618
|
-
message: `Run ${runId} was canceled by ${cause.actor}: ${cause.reason}`
|
|
1619
|
-
};
|
|
1620
987
|
}
|
|
1621
988
|
}
|
|
989
|
+
function endFact(runId, end, at) {
|
|
990
|
+
switch (end.tag) {
|
|
991
|
+
case "completed":
|
|
992
|
+
return Facts.flowCompleted(runId, end.output, at);
|
|
993
|
+
case "failed":
|
|
994
|
+
return Facts.flowFailed(runId, end.error, at);
|
|
995
|
+
case "canceled":
|
|
996
|
+
return Facts.flowCanceledByConcurrency({
|
|
997
|
+
runId,
|
|
998
|
+
at,
|
|
999
|
+
canceledByRunId: end.cause.canceledByRunId,
|
|
1000
|
+
concurrencyKey: end.cause.concurrencyKey
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
function endingRunOf(runId, resolution) {
|
|
1005
|
+
return resolution.kind === "current" ? { kind: "resolved", runId, flow: resolution.flow } : { kind: "gone", runId, flowId: resolution.error.flowId };
|
|
1006
|
+
}
|
|
1622
1007
|
function makeProgression(deps, hooks) {
|
|
1623
1008
|
const { fireHook } = hooks;
|
|
1624
1009
|
async function advance(runId) {
|
|
1625
1010
|
const { store, queue } = deps;
|
|
1626
|
-
const flow2 = requireCurrent(await deps.
|
|
1011
|
+
const flow2 = requireCurrent(await deps.flowOf(runId));
|
|
1627
1012
|
for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
|
|
1628
1013
|
const runState = await store.loadRunState(runId);
|
|
1629
1014
|
const t = nextTransition(flow2, runState);
|
|
@@ -1632,10 +1017,16 @@ function makeProgression(deps, hooks) {
|
|
|
1632
1017
|
case "waiting":
|
|
1633
1018
|
return;
|
|
1634
1019
|
case "complete":
|
|
1635
|
-
await
|
|
1020
|
+
await terminate(
|
|
1021
|
+
{ kind: "resolved", runId, flow: flow2 },
|
|
1022
|
+
{ tag: "completed", output: t.output }
|
|
1023
|
+
);
|
|
1636
1024
|
return;
|
|
1637
1025
|
case "fail":
|
|
1638
|
-
await
|
|
1026
|
+
await terminate(
|
|
1027
|
+
{ kind: "resolved", runId, flow: flow2 },
|
|
1028
|
+
{ tag: "failed", error: t.error }
|
|
1029
|
+
);
|
|
1639
1030
|
return;
|
|
1640
1031
|
case "dispatch":
|
|
1641
1032
|
await recordSkips(runId, t.skip);
|
|
@@ -1645,19 +1036,16 @@ function makeProgression(deps, hooks) {
|
|
|
1645
1036
|
case "skip":
|
|
1646
1037
|
await recordSkips(runId, t.skip);
|
|
1647
1038
|
continue;
|
|
1648
|
-
case "promote-match":
|
|
1649
|
-
await applyPromotions(flow2, runState, t.promotions);
|
|
1650
|
-
continue;
|
|
1651
1039
|
}
|
|
1652
1040
|
}
|
|
1653
1041
|
const cycleError = {
|
|
1654
1042
|
name: "NagiCycleError",
|
|
1655
1043
|
message: `advance exceeded ${MAX_ADVANCE_ITERS} iterations \u2014 likely a cycle or infinite skip loop in flow "${flow2.id}"`
|
|
1656
1044
|
};
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1045
|
+
await terminate(
|
|
1046
|
+
{ kind: "resolved", runId, flow: flow2 },
|
|
1047
|
+
{ tag: "failed", error: cycleError }
|
|
1048
|
+
);
|
|
1661
1049
|
}
|
|
1662
1050
|
async function recordSkips(runId, skip) {
|
|
1663
1051
|
const { store, clock } = deps;
|
|
@@ -1668,21 +1056,20 @@ function makeProgression(deps, hooks) {
|
|
|
1668
1056
|
);
|
|
1669
1057
|
}
|
|
1670
1058
|
}
|
|
1671
|
-
async function
|
|
1672
|
-
const { flow: flow2, runId, stepId, attempt,
|
|
1059
|
+
async function settleSubflowStep(args) {
|
|
1060
|
+
const { flow: flow2, runId, stepId, attempt, settlement } = args;
|
|
1673
1061
|
const at = deps.clock.now();
|
|
1674
1062
|
const base = {
|
|
1675
1063
|
runId,
|
|
1676
1064
|
flowId: flow2.id,
|
|
1677
1065
|
stepId,
|
|
1678
1066
|
attempt,
|
|
1679
|
-
kind:
|
|
1067
|
+
kind: "subflow",
|
|
1680
1068
|
at
|
|
1681
1069
|
};
|
|
1682
1070
|
if (settlement.kind === "complete") {
|
|
1683
|
-
await deps.store.
|
|
1071
|
+
await deps.store.appendFact(
|
|
1684
1072
|
runId,
|
|
1685
|
-
stepId,
|
|
1686
1073
|
Facts.stepCompleted(runId, stepId, attempt, settlement.output, at)
|
|
1687
1074
|
);
|
|
1688
1075
|
await fireHook(
|
|
@@ -1691,9 +1078,8 @@ function makeProgression(deps, hooks) {
|
|
|
1691
1078
|
"onStepComplete"
|
|
1692
1079
|
);
|
|
1693
1080
|
} else {
|
|
1694
|
-
await deps.store.
|
|
1081
|
+
await deps.store.appendFact(
|
|
1695
1082
|
runId,
|
|
1696
|
-
stepId,
|
|
1697
1083
|
Facts.stepFailed(runId, stepId, attempt, settlement.error, at)
|
|
1698
1084
|
);
|
|
1699
1085
|
await fireHook(
|
|
@@ -1703,40 +1089,62 @@ function makeProgression(deps, hooks) {
|
|
|
1703
1089
|
);
|
|
1704
1090
|
}
|
|
1705
1091
|
}
|
|
1706
|
-
async function
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
stepKind: "match",
|
|
1714
|
-
settlement: result
|
|
1092
|
+
async function terminate(run, end) {
|
|
1093
|
+
const at = deps.clock.now();
|
|
1094
|
+
if (!await deps.store.endRun(run.runId, endFact(run.runId, end, at))) {
|
|
1095
|
+
deps.emitLog({
|
|
1096
|
+
level: "info",
|
|
1097
|
+
msg: "nagi: run end skipped \u2014 run already terminal",
|
|
1098
|
+
attrs: { runId: run.runId, end: end.tag }
|
|
1715
1099
|
});
|
|
1100
|
+
return;
|
|
1716
1101
|
}
|
|
1102
|
+
await fireTerminalHooks(run, end, at);
|
|
1103
|
+
await propagateToParent(run.runId, end);
|
|
1717
1104
|
}
|
|
1718
|
-
async function
|
|
1719
|
-
const {
|
|
1720
|
-
|
|
1721
|
-
await
|
|
1722
|
-
const event = { runId, flowId: flow2.id, error, at: clock.now() };
|
|
1723
|
-
await fireHook(flow2.onError, event, "flow.onError");
|
|
1724
|
-
await fireHook(deps.hooks?.onFlowError, event, "onFlowError");
|
|
1725
|
-
await propagateToParent(runId, { kind: "failed", error });
|
|
1105
|
+
async function settleSuperseded(run, fact) {
|
|
1106
|
+
const end = { tag: "canceled", cause: runCancelCause(fact) };
|
|
1107
|
+
await fireTerminalHooks(run, end, fact.at);
|
|
1108
|
+
await propagateToParent(run.runId, end);
|
|
1726
1109
|
}
|
|
1727
|
-
async function
|
|
1728
|
-
const { flow: flow2, runId, output } = args;
|
|
1110
|
+
async function cancel(runId, args) {
|
|
1729
1111
|
const { store, clock } = deps;
|
|
1730
|
-
await
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1112
|
+
const run = endingRunOf(runId, await deps.flowOf(runId));
|
|
1113
|
+
const at = clock.now();
|
|
1114
|
+
if (!await store.endRun(runId, Facts.flowCanceled(runId, args, at))) {
|
|
1115
|
+
deps.emitLog({
|
|
1116
|
+
level: "info",
|
|
1117
|
+
msg: "nagi: cancel skipped \u2014 run already terminal",
|
|
1118
|
+
attrs: { runId, status: runStatusOf(await store.loadRunState(runId)) }
|
|
1119
|
+
});
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
const end = { tag: "canceled", cause: runCancelCause(args) };
|
|
1123
|
+
await fireTerminalHooks(run, end, at);
|
|
1124
|
+
for (const childId of await store.listChildren(runId)) {
|
|
1125
|
+
await cancel(childId, {
|
|
1126
|
+
cause: "explicit",
|
|
1127
|
+
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
1128
|
+
note: `cascade from parent ${runId}`
|
|
1129
|
+
});
|
|
1130
|
+
}
|
|
1131
|
+
await propagateToParent(runId, end);
|
|
1132
|
+
}
|
|
1133
|
+
async function fireTerminalHooks(run, end, at) {
|
|
1134
|
+
const { runId } = run;
|
|
1135
|
+
const flow2 = run.kind === "resolved" ? run.flow : void 0;
|
|
1136
|
+
const flowId = run.kind === "resolved" ? run.flow.id : run.flowId;
|
|
1137
|
+
if (end.tag === "completed") {
|
|
1138
|
+
const event2 = { runId, flowId, output: end.output, at };
|
|
1139
|
+
await fireHook(flow2?.onComplete, event2, "flow.onComplete");
|
|
1140
|
+
await fireHook(deps.hooks?.onFlowComplete, event2, "onFlowComplete");
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
const event = { runId, flowId, error: terminalErrorOf(runId, end), at };
|
|
1144
|
+
await fireHook(flow2?.onError, event, "flow.onError");
|
|
1145
|
+
await fireHook(deps.hooks?.onFlowError, event, "onFlowError");
|
|
1738
1146
|
}
|
|
1739
|
-
async function propagateToParent(childRunId,
|
|
1147
|
+
async function propagateToParent(childRunId, end) {
|
|
1740
1148
|
const { store } = deps;
|
|
1741
1149
|
const childState = await store.loadRunState(childRunId);
|
|
1742
1150
|
if (childState.parent === void 0) {
|
|
@@ -1772,24 +1180,22 @@ function makeProgression(deps, hooks) {
|
|
|
1772
1180
|
return;
|
|
1773
1181
|
}
|
|
1774
1182
|
const attempt = parentStep.attempt;
|
|
1775
|
-
const parentFlow = requireCurrent(await deps.
|
|
1776
|
-
await
|
|
1183
|
+
const parentFlow = requireCurrent(await deps.flowOf(parentRunId));
|
|
1184
|
+
await settleSubflowStep({
|
|
1777
1185
|
flow: parentFlow,
|
|
1778
1186
|
runId: parentRunId,
|
|
1779
1187
|
stepId: parentStepId,
|
|
1780
1188
|
attempt,
|
|
1781
|
-
|
|
1782
|
-
settlement: outcome.kind === "completed" ? { kind: "complete", output: { childRunId, output: outcome.output } } : { kind: "fail", error: outcome.error }
|
|
1189
|
+
settlement: end.tag === "completed" ? { kind: "complete", output: { childRunId, output: end.output } } : { kind: "fail", error: terminalErrorOf(childRunId, end) }
|
|
1783
1190
|
});
|
|
1784
1191
|
await advance(parentRunId);
|
|
1785
1192
|
}
|
|
1786
1193
|
async function wakeParentFromChild(childRunId) {
|
|
1787
|
-
const
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
await propagateToParent(childRunId, outcome);
|
|
1194
|
+
const { phase } = await deps.store.loadRunState(childRunId);
|
|
1195
|
+
if (phase.tag === "pending" || phase.tag === "running") return;
|
|
1196
|
+
await propagateToParent(childRunId, phase);
|
|
1791
1197
|
}
|
|
1792
|
-
return { advance,
|
|
1198
|
+
return { advance, terminate, settleSuperseded, cancel, wakeParentFromChild };
|
|
1793
1199
|
}
|
|
1794
1200
|
|
|
1795
1201
|
// src/dispatch.ts
|
|
@@ -1802,7 +1208,7 @@ function makeDispatcher(deps) {
|
|
|
1802
1208
|
for (const { runId, stepId, attempt, fireAt } of timedOut) {
|
|
1803
1209
|
try {
|
|
1804
1210
|
if (deps.hooks?.onStepError) {
|
|
1805
|
-
const flow2 = requireCurrent(await deps.
|
|
1211
|
+
const flow2 = requireCurrent(await deps.flowOf(runId));
|
|
1806
1212
|
await hooks.fireHook(
|
|
1807
1213
|
deps.hooks.onStepError,
|
|
1808
1214
|
{
|
|
@@ -1823,7 +1229,7 @@ function makeDispatcher(deps) {
|
|
|
1823
1229
|
} catch (err) {
|
|
1824
1230
|
deps.emitLog({
|
|
1825
1231
|
level: "error",
|
|
1826
|
-
msg: "nagi: signal timeout fired but the run could not be advanced \u2014 re-drive with
|
|
1232
|
+
msg: "nagi: signal timeout fired but the run could not be advanced \u2014 re-drive with replay({ from })",
|
|
1827
1233
|
attrs: { runId, stepId, attempt, error: String(err) }
|
|
1828
1234
|
});
|
|
1829
1235
|
}
|
|
@@ -1833,215 +1239,179 @@ function makeDispatcher(deps) {
|
|
|
1833
1239
|
return {
|
|
1834
1240
|
dispatchMessage: message.dispatchMessage,
|
|
1835
1241
|
advance: progression.advance,
|
|
1836
|
-
|
|
1242
|
+
terminate: progression.terminate,
|
|
1243
|
+
settleSuperseded: progression.settleSuperseded,
|
|
1244
|
+
cancel: progression.cancel,
|
|
1837
1245
|
sweepTimers
|
|
1838
1246
|
};
|
|
1839
1247
|
}
|
|
1840
1248
|
|
|
1841
|
-
// src/operator.ts
|
|
1842
|
-
var ABORT_SETTLE_DEADLINE_MS = 3e4;
|
|
1843
|
-
var ABORT_SETTLE_POLL_MS = 50;
|
|
1844
|
-
function requireActor(method, actor) {
|
|
1845
|
-
if (typeof actor !== "string" || actor.length === 0) {
|
|
1846
|
-
throw validationError(`${method}: opts.actor must be a non-empty string`, [
|
|
1847
|
-
"actor"
|
|
1848
|
-
]);
|
|
1849
|
-
}
|
|
1850
|
-
}
|
|
1851
|
-
function makeOperator(o) {
|
|
1852
|
-
const { dispatcher, store, clock, registry, cancelRunRecursive, emitLog } = o;
|
|
1853
|
-
async function skip(runId, stepId, opts) {
|
|
1854
|
-
requireActor("operator.skip", opts.actor);
|
|
1855
|
-
const state = await store.loadRunState(runId);
|
|
1856
|
-
const flow2 = registry.require(state.flowId);
|
|
1857
|
-
if (!(stepId in flow2.steps)) {
|
|
1858
|
-
throw validationError(
|
|
1859
|
-
`operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
1860
|
-
["stepId"]
|
|
1861
|
-
);
|
|
1862
|
-
}
|
|
1863
|
-
const stepState = stepStateOf(state, stepId);
|
|
1864
|
-
if (isStepTerminal(stepState)) {
|
|
1865
|
-
emitLog({
|
|
1866
|
-
level: "info",
|
|
1867
|
-
msg: "nagi: operator.skip noop \u2014 step already terminal",
|
|
1868
|
-
attrs: { runId, stepId, status: stepStatusOf(stepState) }
|
|
1869
|
-
});
|
|
1870
|
-
return;
|
|
1871
|
-
}
|
|
1872
|
-
if (isTerminalRun(state)) {
|
|
1873
|
-
throw new NagiRuntimeError(
|
|
1874
|
-
`operator.skip: run ${runId} is already terminal (${runStatusOf(state)}); cannot skip step "${stepId}".`
|
|
1875
|
-
);
|
|
1876
|
-
}
|
|
1877
|
-
await store.appendFact(
|
|
1878
|
-
runId,
|
|
1879
|
-
Facts.stepSkipped({
|
|
1880
|
-
runId,
|
|
1881
|
-
stepId,
|
|
1882
|
-
at: clock.now(),
|
|
1883
|
-
reason: "manual",
|
|
1884
|
-
actor: opts.actor,
|
|
1885
|
-
...compact({ note: opts.note })
|
|
1886
|
-
})
|
|
1887
|
-
);
|
|
1888
|
-
await dispatcher.advance(runId);
|
|
1889
|
-
}
|
|
1890
|
-
async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
|
|
1891
|
-
const start = Date.now();
|
|
1892
|
-
while (Date.now() - start < deadlineMs) {
|
|
1893
|
-
const s = await store.loadRunState(runId);
|
|
1894
|
-
const ss = s.steps[stepId];
|
|
1895
|
-
if (ss === void 0) return;
|
|
1896
|
-
if (isStepTerminal(ss)) return;
|
|
1897
|
-
if (isTerminalRun(s)) return;
|
|
1898
|
-
if (attemptOf(ss) > attempt) return;
|
|
1899
|
-
await new Promise((r) => setTimeout(r, ABORT_SETTLE_POLL_MS));
|
|
1900
|
-
}
|
|
1901
|
-
throw new NagiRuntimeError(
|
|
1902
|
-
`operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
|
|
1903
|
-
);
|
|
1904
|
-
}
|
|
1905
|
-
async function retry(runId, stepId, opts) {
|
|
1906
|
-
requireActor("operator.retry", opts.actor);
|
|
1907
|
-
const state = await store.loadRunState(runId);
|
|
1908
|
-
if (state.phase.tag === "canceled") {
|
|
1909
|
-
throw new NagiRuntimeError(
|
|
1910
|
-
`operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
|
|
1911
|
-
);
|
|
1912
|
-
}
|
|
1913
|
-
const flow2 = registry.require(state.flowId);
|
|
1914
|
-
if (!(stepId in flow2.steps)) {
|
|
1915
|
-
throw validationError(
|
|
1916
|
-
`operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
1917
|
-
["stepId"]
|
|
1918
|
-
);
|
|
1919
|
-
}
|
|
1920
|
-
const stepState = stepStateOf(state, stepId);
|
|
1921
|
-
if (stepState.tag === "running") {
|
|
1922
|
-
await store.appendFact(
|
|
1923
|
-
runId,
|
|
1924
|
-
Facts.stepAbortRequested({
|
|
1925
|
-
runId,
|
|
1926
|
-
stepId,
|
|
1927
|
-
attempt: stepState.attempt,
|
|
1928
|
-
at: clock.now(),
|
|
1929
|
-
actor: opts.actor,
|
|
1930
|
-
...compact({ note: opts.note })
|
|
1931
|
-
})
|
|
1932
|
-
);
|
|
1933
|
-
await waitForStepToSettle(
|
|
1934
|
-
runId,
|
|
1935
|
-
stepId,
|
|
1936
|
-
stepState.attempt,
|
|
1937
|
-
ABORT_SETTLE_DEADLINE_MS
|
|
1938
|
-
);
|
|
1939
|
-
}
|
|
1940
|
-
const cascade = descendantsOf(flow2, stepId);
|
|
1941
|
-
const at = clock.now();
|
|
1942
|
-
for (const id of cascade) {
|
|
1943
|
-
const fact = id === stepId ? Facts.stepReset({
|
|
1944
|
-
runId,
|
|
1945
|
-
stepId: id,
|
|
1946
|
-
at,
|
|
1947
|
-
actor: opts.actor,
|
|
1948
|
-
...compact({ note: opts.note })
|
|
1949
|
-
}) : Facts.stepReset({ runId, stepId: id, at, cascadedFrom: stepId });
|
|
1950
|
-
await store.appendFact(runId, fact);
|
|
1951
|
-
}
|
|
1952
|
-
await dispatcher.advance(runId);
|
|
1953
|
-
}
|
|
1954
|
-
async function abort(runId, opts) {
|
|
1955
|
-
requireActor("operator.abort", opts.actor);
|
|
1956
|
-
await cancelRunRecursive(runId, {
|
|
1957
|
-
cause: "operator",
|
|
1958
|
-
reason: opts.note ?? `aborted by operator ${opts.actor}`,
|
|
1959
|
-
actor: opts.actor,
|
|
1960
|
-
...compact({ note: opts.note })
|
|
1961
|
-
});
|
|
1962
|
-
}
|
|
1963
|
-
return { skip, retry, abort };
|
|
1964
|
-
}
|
|
1965
|
-
|
|
1966
1249
|
// src/replay.ts
|
|
1967
1250
|
function makeReplay(deps) {
|
|
1968
1251
|
const { registry, store, queue, clock, driftPolicy } = deps;
|
|
1969
1252
|
async function replay(runId, opts = { mode: "continue" }) {
|
|
1970
|
-
const
|
|
1971
|
-
const resolution =
|
|
1972
|
-
|
|
1973
|
-
if (liveFlow === void 0) {
|
|
1253
|
+
const drift = opts.allowDrift === true ? "synthesize" : driftPolicy;
|
|
1254
|
+
const resolution = await deps.flowOfUnder(runId, drift);
|
|
1255
|
+
if (resolution.kind !== "current" && resolution.live === void 0) {
|
|
1974
1256
|
throw new NagiRuntimeError(
|
|
1975
|
-
`Run ${runId} references flow "${
|
|
1257
|
+
`Run ${runId} references flow "${resolution.error.flowId}" which is not registered with nagi().`
|
|
1976
1258
|
);
|
|
1977
1259
|
}
|
|
1260
|
+
const runState = await store.loadRunState(runId);
|
|
1978
1261
|
if (runState.phase.tag === "canceled") {
|
|
1979
1262
|
throw new NagiRuntimeError(
|
|
1980
|
-
`Run ${runId} was canceled
|
|
1263
|
+
`Run ${runId} was canceled. Replay is not supported for canceled runs \u2014 start a new run instead.`
|
|
1981
1264
|
);
|
|
1982
1265
|
}
|
|
1983
1266
|
if (opts.mode === "inspect") return;
|
|
1984
|
-
const fireHooks = opts.fireHooks !== false;
|
|
1985
|
-
const baseDeps = fireHooks ? deps : { ...deps, fireHooks: false };
|
|
1986
|
-
let replayDeps = baseDeps;
|
|
1987
|
-
let effectiveFlow = liveFlow;
|
|
1988
1267
|
if (resolution.kind !== "current") {
|
|
1989
|
-
if (
|
|
1268
|
+
if (drift === "freeze") {
|
|
1990
1269
|
throw new NagiSnapshotDriftError({
|
|
1991
1270
|
runId,
|
|
1992
1271
|
expected: resolution.error.pinnedHash,
|
|
1993
|
-
actual: registry.hashOf(
|
|
1272
|
+
actual: registry.hashOf(resolution.error.flowId)
|
|
1994
1273
|
});
|
|
1995
1274
|
}
|
|
1996
|
-
|
|
1997
|
-
replayDeps = {
|
|
1998
|
-
...baseDeps,
|
|
1999
|
-
resolveFlow: async () => ({ kind: "current", flow: synthesized })
|
|
2000
|
-
};
|
|
2001
|
-
effectiveFlow = synthesized;
|
|
1275
|
+
throw resolution.error;
|
|
2002
1276
|
}
|
|
1277
|
+
const { flow: flow2 } = resolution;
|
|
2003
1278
|
if (opts.from !== void 0) {
|
|
2004
|
-
if (
|
|
2005
|
-
throw new NagiRuntimeError(
|
|
2006
|
-
`Run ${runId} is still running \u2014 replay({ from }) would race in-flight workers. Wait for the run to settle (completed / failed) before resetting from a step.`
|
|
2007
|
-
);
|
|
2008
|
-
}
|
|
2009
|
-
if (!(opts.from in effectiveFlow.steps)) {
|
|
1279
|
+
if (!(opts.from in flow2.steps)) {
|
|
2010
1280
|
throw validationError(
|
|
2011
|
-
`replay({ from }): step "${opts.from}" is not a step in flow "${
|
|
1281
|
+
`replay({ from }): step "${opts.from}" is not a step in flow "${flow2.id}".`,
|
|
2012
1282
|
["from"]
|
|
2013
1283
|
);
|
|
2014
1284
|
}
|
|
2015
|
-
|
|
2016
|
-
const
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
1285
|
+
await abortInFlight(runState, opts.from);
|
|
1286
|
+
const resets = resetFactsOf(flow2, {
|
|
1287
|
+
runId,
|
|
1288
|
+
stepId: opts.from,
|
|
1289
|
+
at: clock.now(),
|
|
1290
|
+
...compact({ scope: opts.scope })
|
|
1291
|
+
});
|
|
1292
|
+
for (const fact of resets) await store.appendFact(runId, fact);
|
|
1293
|
+
}
|
|
1294
|
+
const run = { runId, flow: flow2 };
|
|
1295
|
+
if (opts.fireHooks !== false) {
|
|
1296
|
+
await deps.dispatcherFor({ kind: "enqueue", run }).advance(runId);
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
const inline = makeInlineQueue(queue);
|
|
1300
|
+
const dispatcher = deps.dispatcherFor({
|
|
1301
|
+
kind: "inline",
|
|
1302
|
+
run,
|
|
1303
|
+
queue: inline
|
|
1304
|
+
});
|
|
1305
|
+
try {
|
|
1306
|
+
await dispatcher.advance(runId);
|
|
1307
|
+
await drainInline(dispatcher, inline);
|
|
1308
|
+
} finally {
|
|
1309
|
+
await inline.handOff();
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
async function abortInFlight(state, stepId) {
|
|
1313
|
+
const step = stepStateOf(state, stepId);
|
|
1314
|
+
if (step.tag !== "running") return;
|
|
1315
|
+
const { runId } = state;
|
|
1316
|
+
await store.appendFact(
|
|
1317
|
+
runId,
|
|
1318
|
+
Facts.stepAbortRequested({
|
|
1319
|
+
runId,
|
|
1320
|
+
stepId,
|
|
1321
|
+
attempt: step.attempt,
|
|
1322
|
+
at: clock.now()
|
|
1323
|
+
})
|
|
1324
|
+
);
|
|
1325
|
+
const start = Date.now();
|
|
1326
|
+
while (Date.now() - start < ABORT_SETTLE_DEADLINE_MS) {
|
|
1327
|
+
const s = await store.loadRunState(runId);
|
|
1328
|
+
const ss = s.steps[stepId];
|
|
1329
|
+
if (ss === void 0 || isStepTerminal(ss) || isTerminalRun(s) || attemptOf(ss) > step.attempt) {
|
|
1330
|
+
return;
|
|
2020
1331
|
}
|
|
1332
|
+
await new Promise((r) => setTimeout(r, ABORT_SETTLE_POLL_MS));
|
|
2021
1333
|
}
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
1334
|
+
throw new NagiRuntimeError(
|
|
1335
|
+
`replay({ from }): timed out after ${ABORT_SETTLE_DEADLINE_MS}ms waiting for step "${stepId}" (attempt ${step.attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
|
|
1336
|
+
);
|
|
2025
1337
|
}
|
|
2026
1338
|
return { replay };
|
|
2027
1339
|
}
|
|
1340
|
+
var ABORT_SETTLE_DEADLINE_MS = 3e4;
|
|
1341
|
+
var ABORT_SETTLE_POLL_MS = 50;
|
|
2028
1342
|
var MAX_REPLAY_DISPATCHES = 4096;
|
|
2029
|
-
async function drainInline(dispatcher,
|
|
1343
|
+
async function drainInline(dispatcher, inline) {
|
|
2030
1344
|
for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
|
|
2031
|
-
const
|
|
2032
|
-
if (
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
1345
|
+
const [msg] = await inline.dequeue({ count: 1 });
|
|
1346
|
+
if (msg === void 0) return;
|
|
1347
|
+
const result = await dispatcher.dispatchMessage(msg);
|
|
1348
|
+
if (result.kind === "snapshot-gone") throw result.error;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
function makeInlineQueue(shared) {
|
|
1352
|
+
const ready = [];
|
|
1353
|
+
const leased = /* @__PURE__ */ new Map();
|
|
1354
|
+
let seq = 0;
|
|
1355
|
+
const toShared = (m, delayMs) => shared.enqueue(m.runId, m.stepId, {
|
|
1356
|
+
attempt: m.attempt,
|
|
1357
|
+
payload: m.payload,
|
|
1358
|
+
...compact({ flowId: m.flowId, delayMs })
|
|
1359
|
+
});
|
|
1360
|
+
return {
|
|
1361
|
+
async enqueue(runId, stepId, opts) {
|
|
1362
|
+
if ((opts?.delayMs ?? 0) > 0) {
|
|
1363
|
+
await shared.enqueue(runId, stepId, opts);
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
ready.push({
|
|
1367
|
+
receipt: `inline-${seq++}`,
|
|
1368
|
+
runId,
|
|
1369
|
+
stepId,
|
|
1370
|
+
payload: opts?.payload ?? null,
|
|
1371
|
+
attempt: opts?.attempt ?? 1,
|
|
1372
|
+
readCount: 0,
|
|
1373
|
+
...compact({ flowId: opts?.flowId })
|
|
1374
|
+
});
|
|
1375
|
+
},
|
|
1376
|
+
async dequeue({ count }) {
|
|
1377
|
+
const out = ready.splice(0, count).map((m) => ({ ...m, readCount: m.readCount + 1 }));
|
|
1378
|
+
for (const m of out) leased.set(m.receipt, m);
|
|
1379
|
+
return out;
|
|
1380
|
+
},
|
|
1381
|
+
async ack(receipt) {
|
|
1382
|
+
leased.delete(receipt);
|
|
1383
|
+
},
|
|
1384
|
+
async nack(receipt, opts) {
|
|
1385
|
+
const m = leased.get(receipt);
|
|
1386
|
+
if (m === void 0) return;
|
|
1387
|
+
leased.delete(receipt);
|
|
1388
|
+
if ((opts?.delayMs ?? 0) > 0) await toShared(m, opts?.delayMs);
|
|
1389
|
+
else ready.push(m);
|
|
1390
|
+
},
|
|
1391
|
+
async extend() {
|
|
1392
|
+
},
|
|
1393
|
+
async handOff() {
|
|
1394
|
+
const rest = [...leased.values(), ...ready.splice(0)];
|
|
1395
|
+
leased.clear();
|
|
1396
|
+
for (const m of rest) await toShared(m);
|
|
2036
1397
|
}
|
|
2037
|
-
}
|
|
1398
|
+
};
|
|
2038
1399
|
}
|
|
2039
1400
|
|
|
2040
1401
|
// src/run-lifecycle.ts
|
|
2041
1402
|
var EXISTS = { kind: "exists" };
|
|
2042
1403
|
var ADVANCE = { kind: "advance" };
|
|
2043
1404
|
function makeRunLifecycle(deps) {
|
|
2044
|
-
const {
|
|
1405
|
+
const {
|
|
1406
|
+
store,
|
|
1407
|
+
queue,
|
|
1408
|
+
clock,
|
|
1409
|
+
registry,
|
|
1410
|
+
flowOf,
|
|
1411
|
+
hooks,
|
|
1412
|
+
flowHooks,
|
|
1413
|
+
dispatcher
|
|
1414
|
+
} = deps;
|
|
2045
1415
|
function resolveBoundary(boundary) {
|
|
2046
1416
|
switch (boundary.kind) {
|
|
2047
1417
|
case "own":
|
|
@@ -2085,7 +1455,8 @@ function makeRunLifecycle(deps) {
|
|
|
2085
1455
|
return {
|
|
2086
1456
|
kind: "started",
|
|
2087
1457
|
effects: {
|
|
2088
|
-
|
|
1458
|
+
flow: flow2,
|
|
1459
|
+
superseded: canceled,
|
|
2089
1460
|
started: {
|
|
2090
1461
|
runId,
|
|
2091
1462
|
flowId: flow2.id,
|
|
@@ -2098,15 +1469,12 @@ function makeRunLifecycle(deps) {
|
|
|
2098
1469
|
};
|
|
2099
1470
|
}
|
|
2100
1471
|
async function applyEffects(effects) {
|
|
2101
|
-
const { superseded, started, dispatch } = effects;
|
|
2102
|
-
const
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
kind: "canceled",
|
|
2108
|
-
error: event.error
|
|
2109
|
-
});
|
|
1472
|
+
const { flow: flow2, superseded, started, dispatch } = effects;
|
|
1473
|
+
for (const { runId, fact } of superseded) {
|
|
1474
|
+
await dispatcher.settleSuperseded(
|
|
1475
|
+
endingRunOf(runId, await flowOf(runId)),
|
|
1476
|
+
fact
|
|
1477
|
+
);
|
|
2110
1478
|
}
|
|
2111
1479
|
await hooks.fireHook(flow2.onStart, started, "flow.onStart");
|
|
2112
1480
|
await hooks.fireHook(flowHooks?.onFlowStart, started, "onFlowStart");
|
|
@@ -2171,37 +1539,7 @@ function makeRunLifecycle(deps) {
|
|
|
2171
1539
|
if (staged.kind === "started") await applyEffects(staged.effects);
|
|
2172
1540
|
return runId;
|
|
2173
1541
|
}
|
|
2174
|
-
|
|
2175
|
-
const state = await store.loadRunState(runId);
|
|
2176
|
-
if (isTerminalRun(state)) {
|
|
2177
|
-
deps.emitLog({
|
|
2178
|
-
level: "info",
|
|
2179
|
-
msg: "nagi: cancel skipped \u2014 run already terminal",
|
|
2180
|
-
attrs: { runId, status: runStatusOf(state) }
|
|
2181
|
-
});
|
|
2182
|
-
return;
|
|
2183
|
-
}
|
|
2184
|
-
const flow2 = registry.get(state.flowId);
|
|
2185
|
-
await store.appendFact(runId, Facts.flowCanceled(runId, args, clock.now()));
|
|
2186
|
-
const error = {
|
|
2187
|
-
name: "NagiCanceledError",
|
|
2188
|
-
message: `Run ${runId} was canceled: ${args.reason}`
|
|
2189
|
-
};
|
|
2190
|
-
if (flow2 !== void 0) {
|
|
2191
|
-
const event = { runId, flowId: flow2.id, error, at: clock.now() };
|
|
2192
|
-
await hooks.fireHook(flow2.onError, event, "flow.onError");
|
|
2193
|
-
await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
|
|
2194
|
-
}
|
|
2195
|
-
for (const childId of await store.listChildren(runId)) {
|
|
2196
|
-
await cancelRunRecursive(childId, {
|
|
2197
|
-
cause: "explicit",
|
|
2198
|
-
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
2199
|
-
note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
2200
|
-
});
|
|
2201
|
-
}
|
|
2202
|
-
await dispatcher.propagateToParent(runId, { kind: "canceled", error });
|
|
2203
|
-
}
|
|
2204
|
-
return { start, stage, applyEffects, startChildRun, cancelRunRecursive };
|
|
1542
|
+
return { start, stage, applyEffects, startChildRun };
|
|
2205
1543
|
}
|
|
2206
1544
|
function resolveRunId(runId) {
|
|
2207
1545
|
if (runId === void 0) return `run-${crypto.randomUUID()}`;
|
|
@@ -2221,14 +1559,6 @@ function concurrencyOf(flow2, input) {
|
|
|
2221
1559
|
}
|
|
2222
1560
|
return { key, mode: flow2.concurrency.mode };
|
|
2223
1561
|
}
|
|
2224
|
-
function supersededEvent(flowId, canceledByRunId, c) {
|
|
2225
|
-
const cause = { canceledByRunId, concurrencyKey: c.fact.concurrencyKey };
|
|
2226
|
-
const error = {
|
|
2227
|
-
...serializeError(new NagiCanceledError({ runId: c.runId, ...cause })),
|
|
2228
|
-
cause
|
|
2229
|
-
};
|
|
2230
|
-
return { runId: c.runId, flowId, error, at: c.fact.at };
|
|
2231
|
-
}
|
|
2232
1562
|
|
|
2233
1563
|
// src/worker.ts
|
|
2234
1564
|
var DEFAULT_CONCURRENCY = 4;
|
|
@@ -2248,21 +1578,34 @@ var WorkerImpl = class {
|
|
|
2248
1578
|
this.dispatcher = makeDispatcher(deps);
|
|
2249
1579
|
this.snapshotGonePolicy = config?.snapshotGonePolicy ?? defaultSnapshotGonePolicy;
|
|
2250
1580
|
this.maxPerFlow = config?.maxConcurrencyPerFlow !== void 0 ? Math.max(1, config.maxConcurrencyPerFlow) : void 0;
|
|
2251
|
-
|
|
2252
|
-
|
|
1581
|
+
const bootAt = deps.clock.now().getTime();
|
|
1582
|
+
const sweeps = [
|
|
1583
|
+
{
|
|
1584
|
+
label: "signal-timeout",
|
|
1585
|
+
intervalMs: config?.timerSweepIntervalMs ?? DEFAULT_TIMER_SWEEP_INTERVAL_MS,
|
|
1586
|
+
run: (now) => this.dispatcher.sweepTimers(now),
|
|
1587
|
+
lastAt: bootAt
|
|
1588
|
+
},
|
|
1589
|
+
{
|
|
1590
|
+
label: "lease-reaper",
|
|
1591
|
+
intervalMs: config?.reaperIntervalMs ?? DEFAULT_REAPER_INTERVAL_MS,
|
|
1592
|
+
run: (now) => deps.store.sweepLeases({ now, queue: deps.queue }),
|
|
1593
|
+
lastAt: bootAt
|
|
1594
|
+
}
|
|
1595
|
+
];
|
|
1596
|
+
this.sweeps = sweeps.filter((s) => s.intervalMs > 0);
|
|
2253
1597
|
}
|
|
2254
1598
|
deps;
|
|
2255
|
-
inFlight =
|
|
1599
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
2256
1600
|
concurrency;
|
|
2257
1601
|
pollIntervalMs;
|
|
2258
1602
|
dequeueBackoffMs;
|
|
2259
1603
|
signal;
|
|
2260
1604
|
dispatcher;
|
|
2261
|
-
|
|
1605
|
+
sweeps;
|
|
2262
1606
|
snapshotGonePolicy;
|
|
2263
1607
|
maxPerFlow;
|
|
2264
1608
|
inFlightByFlow = /* @__PURE__ */ new Map();
|
|
2265
|
-
lastTimerSweepAt;
|
|
2266
1609
|
// Per-flow blast-radius bound (maxConcurrencyPerFlow). A message over its
|
|
2267
1610
|
// flow's cap is DEFERRED — delayed nack, redelivered after ~pollIntervalMs —
|
|
2268
1611
|
// not dropped. Messages without flowId (enqueued pre-upgrade) are exempt.
|
|
@@ -2299,8 +1642,8 @@ var WorkerImpl = class {
|
|
|
2299
1642
|
async run() {
|
|
2300
1643
|
let dequeueFailures = 0;
|
|
2301
1644
|
while (!this.aborted()) {
|
|
2302
|
-
await this.
|
|
2303
|
-
const slots = this.concurrency - this.inFlight;
|
|
1645
|
+
await this.runDueSweeps();
|
|
1646
|
+
const slots = this.concurrency - this.inFlight.size;
|
|
2304
1647
|
if (slots <= 0) {
|
|
2305
1648
|
await this.sleep(50);
|
|
2306
1649
|
continue;
|
|
@@ -2381,12 +1724,12 @@ var WorkerImpl = class {
|
|
|
2381
1724
|
return this.deps.queue.dequeue({ count: Math.max(1, count) });
|
|
2382
1725
|
}
|
|
2383
1726
|
fire(msg) {
|
|
2384
|
-
this.inFlight++;
|
|
2385
1727
|
const release = this.trackFlow(msg);
|
|
2386
|
-
|
|
1728
|
+
const dispatch = this.dispatchSafely(msg).finally(() => {
|
|
2387
1729
|
release();
|
|
2388
|
-
this.inFlight
|
|
1730
|
+
this.inFlight.delete(dispatch);
|
|
2389
1731
|
});
|
|
1732
|
+
this.inFlight.add(dispatch);
|
|
2390
1733
|
}
|
|
2391
1734
|
async dispatchSafely(msg) {
|
|
2392
1735
|
let result;
|
|
@@ -2458,48 +1801,46 @@ var WorkerImpl = class {
|
|
|
2458
1801
|
msg: "worker.dispatch: flow snapshot gone \u2014 redelivery budget exhausted, failing run",
|
|
2459
1802
|
attrs
|
|
2460
1803
|
});
|
|
2461
|
-
const serialized = serializeError(err);
|
|
2462
|
-
await this.deps.store.appendFact(
|
|
2463
|
-
msg.runId,
|
|
2464
|
-
Facts.flowFailed(msg.runId, serialized, this.deps.clock.now())
|
|
2465
|
-
);
|
|
2466
1804
|
try {
|
|
2467
|
-
await this.dispatcher.
|
|
2468
|
-
kind: "
|
|
2469
|
-
error:
|
|
2470
|
-
|
|
2471
|
-
} catch (
|
|
1805
|
+
await this.dispatcher.terminate(
|
|
1806
|
+
{ kind: "gone", runId: msg.runId, flowId: err.flowId },
|
|
1807
|
+
{ tag: "failed", error: serializeError(err) }
|
|
1808
|
+
);
|
|
1809
|
+
} catch (terminateErr) {
|
|
1810
|
+
const state = await this.deps.store.loadRunState(msg.runId);
|
|
1811
|
+
if (!isTerminalRun(state)) throw terminateErr;
|
|
2472
1812
|
this.deps.emitLog({
|
|
2473
1813
|
level: "warn",
|
|
2474
1814
|
msg: "worker.dispatch: snapshot-gone fail could not propagate to parent",
|
|
2475
|
-
attrs: { ...attrs, error: String(
|
|
1815
|
+
attrs: { ...attrs, error: String(terminateErr) }
|
|
2476
1816
|
});
|
|
2477
1817
|
}
|
|
2478
1818
|
await this.deps.queue.ack(msg.receipt);
|
|
2479
1819
|
}
|
|
2480
1820
|
async drain() {
|
|
2481
|
-
while (this.inFlight > 0) {
|
|
2482
|
-
await this.
|
|
1821
|
+
while (this.inFlight.size > 0) {
|
|
1822
|
+
await Promise.allSettled(this.inFlight);
|
|
2483
1823
|
}
|
|
2484
1824
|
}
|
|
2485
|
-
//
|
|
2486
|
-
//
|
|
2487
|
-
//
|
|
2488
|
-
// sweep must not kill the worker; the next tick retries.
|
|
2489
|
-
async
|
|
2490
|
-
if (this.
|
|
1825
|
+
// Runs inline in the dispatch loop (not fired concurrently) so two passes of
|
|
1826
|
+
// a sweep never overlap within a worker; across workers the store's sweeps
|
|
1827
|
+
// are safe to race (row locks / take-before-await). Errors are logged, never
|
|
1828
|
+
// thrown — a failed sweep must not kill the worker; the next tick retries.
|
|
1829
|
+
async runDueSweeps() {
|
|
1830
|
+
if (this.sweeps.length === 0) return;
|
|
2491
1831
|
const now = this.deps.clock.now();
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
1832
|
+
for (const sweep of this.sweeps) {
|
|
1833
|
+
if (now.getTime() - sweep.lastAt < sweep.intervalMs) continue;
|
|
1834
|
+
sweep.lastAt = now.getTime();
|
|
1835
|
+
try {
|
|
1836
|
+
await sweep.run(now);
|
|
1837
|
+
} catch (err) {
|
|
1838
|
+
this.deps.emitLog({
|
|
1839
|
+
level: "warn",
|
|
1840
|
+
msg: `worker: ${sweep.label} sweep failed`,
|
|
1841
|
+
attrs: { error: String(err) }
|
|
1842
|
+
});
|
|
1843
|
+
}
|
|
2503
1844
|
}
|
|
2504
1845
|
}
|
|
2505
1846
|
aborted() {
|
|
@@ -2519,16 +1860,15 @@ async function nagiImpl(config) {
|
|
|
2519
1860
|
const emitLog = makeEmit(config.onLog);
|
|
2520
1861
|
await config.queue.ensureSchema?.();
|
|
2521
1862
|
const streamTransport = config.store.stream;
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
);
|
|
2529
|
-
}
|
|
1863
|
+
const requireEvents = (caller) => {
|
|
1864
|
+
const events = config.store.events;
|
|
1865
|
+
if (events === void 0) {
|
|
1866
|
+
throw new NagiRuntimeError(
|
|
1867
|
+
`${caller}: this store has no \`events\` transport, so lifecycle events cannot be observed. The in-memory store always has one; postgresStore() needs a \`listener\`.`
|
|
1868
|
+
);
|
|
2530
1869
|
}
|
|
2531
|
-
|
|
1870
|
+
return events;
|
|
1871
|
+
};
|
|
2532
1872
|
const registry = await registerFlows({
|
|
2533
1873
|
flows: config.flows,
|
|
2534
1874
|
store: config.store,
|
|
@@ -2536,76 +1876,77 @@ async function nagiImpl(config) {
|
|
|
2536
1876
|
});
|
|
2537
1877
|
const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
|
|
2538
1878
|
const driftPolicy = config.driftPolicy ?? "freeze";
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
}
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
1879
|
+
const flowOfUnder = makeFlowOf({ registry, store: config.store, emitLog });
|
|
1880
|
+
const flowOf = (runId) => flowOfUnder(runId, driftPolicy);
|
|
1881
|
+
function makeEngine(env) {
|
|
1882
|
+
const deps = {
|
|
1883
|
+
flowOf: env.flowOf,
|
|
1884
|
+
lookupFlow: (flowId) => registry.get(flowId),
|
|
1885
|
+
startChildRun: (args) => lifecycle2.startChildRun(args),
|
|
1886
|
+
store: config.store,
|
|
1887
|
+
queue: env.queue,
|
|
1888
|
+
clock,
|
|
1889
|
+
emitLog,
|
|
1890
|
+
fireHooks: env.fireHooks,
|
|
1891
|
+
// The one fork point for heartbeat tuning: collapse the public optionals to
|
|
1892
|
+
// a single required config here so the dispatch internals never re-check it.
|
|
1893
|
+
heartbeat: {
|
|
1894
|
+
intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
|
|
1895
|
+
leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS,
|
|
1896
|
+
holdWarnMs: config.leaseHoldWarnMs ?? DEFAULT_LEASE_HOLD_WARN_MS
|
|
1897
|
+
},
|
|
1898
|
+
...compact({
|
|
1899
|
+
hooks: config.hooks,
|
|
1900
|
+
defaultRetry: config.defaultRetry,
|
|
1901
|
+
streamTransport
|
|
1902
|
+
})
|
|
1903
|
+
};
|
|
1904
|
+
const dispatcher2 = makeDispatcher(deps);
|
|
1905
|
+
const hooks2 = makeHooks(deps);
|
|
1906
|
+
const lifecycle2 = makeRunLifecycle({
|
|
1907
|
+
store: config.store,
|
|
1908
|
+
queue: env.queue,
|
|
1909
|
+
clock,
|
|
1910
|
+
registry,
|
|
1911
|
+
flowOf: env.flowOf,
|
|
1912
|
+
codeVersion,
|
|
1913
|
+
queueForTx: (tx) => config.queue.withTx?.(tx) ?? config.queue,
|
|
1914
|
+
hooks: hooks2,
|
|
1915
|
+
flowHooks: config.hooks,
|
|
1916
|
+
dispatcher: dispatcher2
|
|
1917
|
+
});
|
|
1918
|
+
return { deps, dispatcher: dispatcher2, hooks: hooks2, lifecycle: lifecycle2 };
|
|
2563
1919
|
}
|
|
2564
|
-
const
|
|
2565
|
-
|
|
2566
|
-
lookupFlow,
|
|
2567
|
-
startChildRun: (args) => lifecycle.startChildRun(args),
|
|
2568
|
-
store: config.store,
|
|
2569
|
-
queue: config.queue,
|
|
2570
|
-
clock,
|
|
2571
|
-
emitLog,
|
|
2572
|
-
// The one fork point for heartbeat tuning: collapse the public optionals to
|
|
2573
|
-
// a single required config here so the dispatch internals never re-check it.
|
|
2574
|
-
heartbeat: {
|
|
2575
|
-
intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
|
|
2576
|
-
leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS,
|
|
2577
|
-
holdWarnMs: config.leaseHoldWarnMs ?? DEFAULT_LEASE_HOLD_WARN_MS
|
|
2578
|
-
},
|
|
2579
|
-
...compact({
|
|
2580
|
-
hooks: config.hooks,
|
|
2581
|
-
defaultRetry: config.defaultRetry,
|
|
2582
|
-
streamTransport
|
|
2583
|
-
})
|
|
2584
|
-
};
|
|
2585
|
-
const dispatcher = makeDispatcher(dispatchDeps);
|
|
2586
|
-
const hooks = makeHooks(dispatchDeps);
|
|
2587
|
-
const lifecycle = makeRunLifecycle({
|
|
2588
|
-
store: config.store,
|
|
2589
|
-
queue: config.queue,
|
|
2590
|
-
clock,
|
|
2591
|
-
registry,
|
|
2592
|
-
codeVersion,
|
|
2593
|
-
queueForTx: (tx) => config.queue.withTx?.(tx) ?? config.queue,
|
|
2594
|
-
hooks,
|
|
2595
|
-
flowHooks: config.hooks,
|
|
1920
|
+
const {
|
|
1921
|
+
deps: dispatchDeps,
|
|
2596
1922
|
dispatcher,
|
|
2597
|
-
|
|
2598
|
-
|
|
1923
|
+
hooks,
|
|
1924
|
+
lifecycle
|
|
1925
|
+
} = makeEngine({ flowOf, queue: config.queue, fireHooks: true });
|
|
2599
1926
|
const signals = makeSignals({
|
|
2600
1927
|
dispatcher,
|
|
2601
1928
|
store: config.store,
|
|
2602
1929
|
clock,
|
|
2603
|
-
|
|
1930
|
+
// A signal only settles facts; under "freeze" a frozen-version worker may
|
|
1931
|
+
// still own the run and apply it, so its steps are named from the pinned
|
|
1932
|
+
// shape whatever this process may run.
|
|
1933
|
+
flowOf: (runId) => flowOfUnder(runId, "synthesize"),
|
|
2604
1934
|
hooks,
|
|
2605
1935
|
emitLog,
|
|
2606
1936
|
...compact({ flowHooks: config.hooks })
|
|
2607
1937
|
});
|
|
2608
|
-
const replayer = makeReplay({
|
|
1938
|
+
const replayer = makeReplay({
|
|
1939
|
+
store: config.store,
|
|
1940
|
+
queue: config.queue,
|
|
1941
|
+
clock,
|
|
1942
|
+
registry,
|
|
1943
|
+
driftPolicy,
|
|
1944
|
+
flowOfUnder,
|
|
1945
|
+
dispatcherFor: (scope) => makeEngine({
|
|
1946
|
+
flowOf: pinRun(scope.run.runId, scope.run.flow, flowOf),
|
|
1947
|
+
...scope.kind === "enqueue" ? { queue: config.queue, fireHooks: true } : { queue: scope.queue, fireHooks: false }
|
|
1948
|
+
}).dispatcher
|
|
1949
|
+
});
|
|
2609
1950
|
const wf = {
|
|
2610
1951
|
async start(flow2, input, opts) {
|
|
2611
1952
|
return wf.startById(flow2.id, input, opts);
|
|
@@ -2650,28 +1991,26 @@ async function nagiImpl(config) {
|
|
|
2650
1991
|
},
|
|
2651
1992
|
signal: signals.signal,
|
|
2652
1993
|
async cancel(runId, opts) {
|
|
2653
|
-
await
|
|
1994
|
+
await dispatcher.cancel(runId, {
|
|
2654
1995
|
cause: "explicit",
|
|
2655
1996
|
reason: opts?.reason ?? "explicit wf.cancel()"
|
|
2656
1997
|
});
|
|
2657
1998
|
},
|
|
2658
|
-
operator() {
|
|
2659
|
-
return makeOperator({
|
|
2660
|
-
dispatcher,
|
|
2661
|
-
store: config.store,
|
|
2662
|
-
clock,
|
|
2663
|
-
registry,
|
|
2664
|
-
cancelRunRecursive: lifecycle.cancelRunRecursive,
|
|
2665
|
-
emitLog
|
|
2666
|
-
});
|
|
2667
|
-
},
|
|
2668
1999
|
worker(workerConfig) {
|
|
2669
2000
|
if (config.flows.length === 0) {
|
|
2670
2001
|
throw new NagiRuntimeError(
|
|
2671
2002
|
"nagi(): no flows registered \u2014 cannot create a worker."
|
|
2672
2003
|
);
|
|
2673
2004
|
}
|
|
2674
|
-
return makeWorker(
|
|
2005
|
+
return makeWorker(
|
|
2006
|
+
{ ...dispatchDeps, clock },
|
|
2007
|
+
{
|
|
2008
|
+
...workerConfig,
|
|
2009
|
+
...compact({
|
|
2010
|
+
reaperIntervalMs: workerConfig?.reaperIntervalMs ?? config.reaperIntervalMs
|
|
2011
|
+
})
|
|
2012
|
+
}
|
|
2013
|
+
);
|
|
2675
2014
|
},
|
|
2676
2015
|
replay: replayer.replay,
|
|
2677
2016
|
async describe(runId) {
|
|
@@ -2685,17 +2024,6 @@ async function nagiImpl(config) {
|
|
|
2685
2024
|
}
|
|
2686
2025
|
return config.queue.inspect(runId);
|
|
2687
2026
|
},
|
|
2688
|
-
async queryRuns(opts = {}) {
|
|
2689
|
-
if (opts.latest === true) {
|
|
2690
|
-
if (opts.limit !== void 0 || opts.cursor !== void 0) {
|
|
2691
|
-
throw validationError(
|
|
2692
|
-
"queryRuns: `latest: true` is incompatible with `limit` / `cursor` \u2014 `latest` returns at most one row.",
|
|
2693
|
-
["latest"]
|
|
2694
|
-
);
|
|
2695
|
-
}
|
|
2696
|
-
}
|
|
2697
|
-
return config.store.queryRuns(opts);
|
|
2698
|
-
},
|
|
2699
2027
|
subscribe(runId, stepId, opts) {
|
|
2700
2028
|
if (!registry.isStreaming(stepId)) {
|
|
2701
2029
|
throw new NagiRuntimeError(
|
|
@@ -2708,6 +2036,12 @@ async function nagiImpl(config) {
|
|
|
2708
2036
|
opts
|
|
2709
2037
|
);
|
|
2710
2038
|
},
|
|
2039
|
+
watchRun(runId, handler) {
|
|
2040
|
+
return requireEvents("wf.watchRun").watchRun(runId, handler);
|
|
2041
|
+
},
|
|
2042
|
+
watchRuns(handler) {
|
|
2043
|
+
return requireEvents("wf.watchRuns").watchRuns(handler);
|
|
2044
|
+
},
|
|
2711
2045
|
async pruneFacts(opts) {
|
|
2712
2046
|
if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
|
|
2713
2047
|
throw validationError("pruneFacts: `olderThan` must be a valid Date.", [
|
|
@@ -2748,42 +2082,15 @@ async function nagiRun(config) {
|
|
|
2748
2082
|
const internal = new AbortController();
|
|
2749
2083
|
const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
|
|
2750
2084
|
const worker = wf.worker({ ...config.worker, signal });
|
|
2751
|
-
const emitLog = makeEmit(config.onLog);
|
|
2752
|
-
const clock = config.clock ?? new InMemoryClock();
|
|
2753
2085
|
const loop = worker.run();
|
|
2754
2086
|
loop.catch((err) => {
|
|
2755
2087
|
if (signal.aborted) return;
|
|
2756
|
-
|
|
2088
|
+
makeEmit(config.onLog)({
|
|
2757
2089
|
level: "error",
|
|
2758
2090
|
msg: "nagi.run: worker exited unexpectedly",
|
|
2759
2091
|
attrs: { error: String(err) }
|
|
2760
2092
|
});
|
|
2761
2093
|
});
|
|
2762
|
-
const reaperIntervalMs = config.reaperIntervalMs ?? DEFAULT_REAPER_INTERVAL_MS;
|
|
2763
|
-
const reaper = reaperIntervalMs > 0 ? (async () => {
|
|
2764
|
-
while (!signal.aborted) {
|
|
2765
|
-
try {
|
|
2766
|
-
await clock.sleep(reaperIntervalMs, signal);
|
|
2767
|
-
} catch {
|
|
2768
|
-
return;
|
|
2769
|
-
}
|
|
2770
|
-
if (signal.aborted) return;
|
|
2771
|
-
try {
|
|
2772
|
-
await config.store.sweepLeases({
|
|
2773
|
-
now: clock.now(),
|
|
2774
|
-
queue: config.queue
|
|
2775
|
-
});
|
|
2776
|
-
} catch (err) {
|
|
2777
|
-
emitLog({
|
|
2778
|
-
level: "warn",
|
|
2779
|
-
msg: "nagi.run: lease reaper sweep failed",
|
|
2780
|
-
attrs: { error: String(err) }
|
|
2781
|
-
});
|
|
2782
|
-
}
|
|
2783
|
-
}
|
|
2784
|
-
})() : Promise.resolve();
|
|
2785
|
-
reaper.catch(() => {
|
|
2786
|
-
});
|
|
2787
2094
|
let stopping;
|
|
2788
2095
|
const stop = () => {
|
|
2789
2096
|
stopping ??= (async () => {
|
|
@@ -2792,10 +2099,6 @@ async function nagiRun(config) {
|
|
|
2792
2099
|
await loop;
|
|
2793
2100
|
} catch {
|
|
2794
2101
|
}
|
|
2795
|
-
try {
|
|
2796
|
-
await reaper;
|
|
2797
|
-
} catch {
|
|
2798
|
-
}
|
|
2799
2102
|
})();
|
|
2800
2103
|
return stopping;
|
|
2801
2104
|
};
|
|
@@ -2808,6 +2111,6 @@ var nagi = Object.assign(
|
|
|
2808
2111
|
async function noop() {
|
|
2809
2112
|
}
|
|
2810
2113
|
|
|
2811
|
-
export { NagiAbortError, RunId,
|
|
2114
|
+
export { NagiAbortError, RunId, flow, nagi, optional };
|
|
2812
2115
|
//# sourceMappingURL=index.js.map
|
|
2813
2116
|
//# sourceMappingURL=index.js.map
|