@nagi-js/core 0.1.1-rc.17 → 0.1.1-rc.19
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 +1833 -0
- package/dist/chunk-VQTYTI6X.js.map +1 -0
- package/dist/index.d.ts +58 -850
- package/dist/index.js +821 -2269
- package/dist/index.js.map +1 -1
- package/dist/testing.d.ts +15 -0
- package/dist/testing.js +1335 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-DfxwD2MH.d.ts +905 -0
- package/package.json +6 -1
package/dist/index.js
CHANGED
|
@@ -1,323 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
function stepStateOf(runState, stepId) {
|
|
4
|
-
return runState.steps[stepId] ?? PENDING;
|
|
5
|
-
}
|
|
6
|
-
function runStatusOf(state) {
|
|
7
|
-
return state.phase.tag;
|
|
8
|
-
}
|
|
9
|
-
function stepStatusOf(s) {
|
|
10
|
-
switch (s.tag) {
|
|
11
|
-
case "pending":
|
|
12
|
-
return "pending";
|
|
13
|
-
case "running":
|
|
14
|
-
case "awaitingSignal":
|
|
15
|
-
case "awaitingChild":
|
|
16
|
-
case "backoff":
|
|
17
|
-
case "aborting":
|
|
18
|
-
return "running";
|
|
19
|
-
case "completed":
|
|
20
|
-
return "completed";
|
|
21
|
-
case "failed":
|
|
22
|
-
return "failed";
|
|
23
|
-
case "skipped":
|
|
24
|
-
return "skipped";
|
|
25
|
-
case "canceled":
|
|
26
|
-
return "canceled";
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
function outputOf(s) {
|
|
30
|
-
return s.tag === "completed" ? s.output : null;
|
|
31
|
-
}
|
|
32
|
-
function errorOf(s) {
|
|
33
|
-
if (s.tag === "failed" || s.tag === "backoff") return s.error;
|
|
34
|
-
if (s.tag === "canceled" && s.cause.kind === "aborted") return s.cause.error;
|
|
35
|
-
return void 0;
|
|
36
|
-
}
|
|
37
|
-
function attemptOf(s) {
|
|
38
|
-
switch (s.tag) {
|
|
39
|
-
case "running":
|
|
40
|
-
case "awaitingSignal":
|
|
41
|
-
case "awaitingChild":
|
|
42
|
-
case "aborting":
|
|
43
|
-
case "completed":
|
|
44
|
-
case "failed":
|
|
45
|
-
return s.attempt;
|
|
46
|
-
case "backoff":
|
|
47
|
-
return s.failedAttempt;
|
|
48
|
-
case "pending":
|
|
49
|
-
case "skipped":
|
|
50
|
-
case "canceled":
|
|
51
|
-
return 0;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
function resolvedOf(s) {
|
|
55
|
-
if (s.tag === "completed") return { tag: "value", value: s.output };
|
|
56
|
-
if (s.tag === "skipped") return { tag: "skipped" };
|
|
57
|
-
return { tag: "value", value: null };
|
|
58
|
-
}
|
|
59
|
-
function unwrap(r) {
|
|
60
|
-
if (r.tag === "skipped") {
|
|
61
|
-
throw new Error("nagi: upstream was skipped \u2014 its value is unavailable");
|
|
62
|
-
}
|
|
63
|
-
return r.value;
|
|
64
|
-
}
|
|
65
|
-
function isTerminalRun(state) {
|
|
66
|
-
return state.phase.tag !== "pending" && state.phase.tag !== "running";
|
|
67
|
-
}
|
|
68
|
-
function isAbortRequested(s, attempt) {
|
|
69
|
-
return s.tag === "aborting" && s.attempt === attempt;
|
|
70
|
-
}
|
|
71
|
-
function isStepTerminal(s) {
|
|
72
|
-
return s.tag === "completed" || s.tag === "failed" || s.tag === "skipped" || s.tag === "canceled";
|
|
73
|
-
}
|
|
74
|
-
function keep(prev) {
|
|
75
|
-
return { next: prev, anomaly: true };
|
|
76
|
-
}
|
|
77
|
-
function startTarget(stepKind, attempt) {
|
|
78
|
-
switch (stepKind) {
|
|
79
|
-
case "signal":
|
|
80
|
-
return { tag: "awaitingSignal", attempt };
|
|
81
|
-
case "subflow":
|
|
82
|
-
return { tag: "awaitingChild", attempt };
|
|
83
|
-
case "task":
|
|
84
|
-
case "activity":
|
|
85
|
-
case "streaming":
|
|
86
|
-
case "match":
|
|
87
|
-
return { tag: "running", attempt };
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
function stepTransition(prev, fact) {
|
|
91
|
-
switch (fact.kind) {
|
|
92
|
-
case "step.started":
|
|
93
|
-
if (prev.tag === "pending" || prev.tag === "backoff")
|
|
94
|
-
return {
|
|
95
|
-
next: startTarget(fact.stepKind, fact.attempt),
|
|
96
|
-
anomaly: false
|
|
97
|
-
};
|
|
98
|
-
return keep(prev);
|
|
99
|
-
// Terminal facts carry authoritative outcomes, so they settle a step from
|
|
100
|
-
// any non-terminal state; only a terminal→terminal contradiction is flagged.
|
|
101
|
-
case "step.completed":
|
|
102
|
-
if (isStepTerminal(prev)) return keep(prev);
|
|
103
|
-
return {
|
|
104
|
-
next: { tag: "completed", attempt: fact.attempt, output: fact.output },
|
|
105
|
-
anomaly: false
|
|
106
|
-
};
|
|
107
|
-
case "step.failed":
|
|
108
|
-
if (isStepTerminal(prev)) return keep(prev);
|
|
109
|
-
return {
|
|
110
|
-
next: { tag: "failed", attempt: fact.attempt, error: fact.error },
|
|
111
|
-
anomaly: false
|
|
112
|
-
};
|
|
113
|
-
case "step.canceled": {
|
|
114
|
-
if (isStepTerminal(prev)) return keep(prev);
|
|
115
|
-
const cause = prev.tag === "aborting" ? { kind: "aborted", ...compact({ error: fact.error }) } : { kind: "run-canceled" };
|
|
116
|
-
return { next: { tag: "canceled", cause }, anomaly: false };
|
|
117
|
-
}
|
|
118
|
-
case "step.retried":
|
|
119
|
-
if (prev.tag === "running")
|
|
120
|
-
return {
|
|
121
|
-
next: {
|
|
122
|
-
tag: "backoff",
|
|
123
|
-
failedAttempt: fact.attempt,
|
|
124
|
-
retryAt: fact.nextAttemptAt,
|
|
125
|
-
error: fact.error
|
|
126
|
-
},
|
|
127
|
-
anomaly: false
|
|
128
|
-
};
|
|
129
|
-
return keep(prev);
|
|
130
|
-
case "step.skipped":
|
|
131
|
-
if (!isStepTerminal(prev))
|
|
132
|
-
return {
|
|
133
|
-
next: {
|
|
134
|
-
tag: "skipped",
|
|
135
|
-
reason: fact.reason
|
|
136
|
-
},
|
|
137
|
-
anomaly: false
|
|
138
|
-
};
|
|
139
|
-
return keep(prev);
|
|
140
|
-
case "step.abort-requested":
|
|
141
|
-
if (prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild")
|
|
142
|
-
return {
|
|
143
|
-
next: { tag: "aborting", attempt: fact.attempt },
|
|
144
|
-
anomaly: false
|
|
145
|
-
};
|
|
146
|
-
return keep(prev);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
function runCancelCause(fact) {
|
|
150
|
-
switch (fact.cause) {
|
|
151
|
-
case "concurrency":
|
|
152
|
-
return {
|
|
153
|
-
kind: "concurrency",
|
|
154
|
-
canceledByRunId: fact.canceledByRunId,
|
|
155
|
-
concurrencyKey: fact.concurrencyKey
|
|
156
|
-
};
|
|
157
|
-
case "explicit":
|
|
158
|
-
return {
|
|
159
|
-
kind: "explicit",
|
|
160
|
-
reason: fact.reason,
|
|
161
|
-
...compact({ note: fact.note })
|
|
162
|
-
};
|
|
163
|
-
case "operator":
|
|
164
|
-
return {
|
|
165
|
-
kind: "operator",
|
|
166
|
-
actor: fact.actor,
|
|
167
|
-
reason: fact.reason,
|
|
168
|
-
...compact({ note: fact.note })
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
function foldRun(runId, facts) {
|
|
173
|
-
let flowId = "";
|
|
174
|
-
let input = null;
|
|
175
|
-
let phase = { tag: "pending" };
|
|
176
|
-
let parent;
|
|
177
|
-
let flowHash;
|
|
178
|
-
let codeVersion;
|
|
179
|
-
const steps = {};
|
|
180
|
-
const selectedArms = {};
|
|
181
|
-
const bufferedSignals = {};
|
|
182
|
-
const anomalies = [];
|
|
183
|
-
for (const fact of facts) {
|
|
184
|
-
switch (fact.kind) {
|
|
185
|
-
case "flow.started":
|
|
186
|
-
flowId = fact.flowId;
|
|
187
|
-
input = fact.input;
|
|
188
|
-
phase = { tag: "running" };
|
|
189
|
-
parent = fact.parent;
|
|
190
|
-
flowHash = fact.flowHash;
|
|
191
|
-
codeVersion = fact.codeVersion;
|
|
192
|
-
break;
|
|
193
|
-
case "flow.completed":
|
|
194
|
-
phase = { tag: "completed", output: fact.output };
|
|
195
|
-
break;
|
|
196
|
-
case "flow.failed":
|
|
197
|
-
phase = { tag: "failed", error: fact.error };
|
|
198
|
-
break;
|
|
199
|
-
case "flow.canceled":
|
|
200
|
-
phase = { tag: "canceled", cause: runCancelCause(fact) };
|
|
201
|
-
break;
|
|
202
|
-
case "match.arm-selected":
|
|
203
|
-
selectedArms[fact.stepId] = fact.arm;
|
|
204
|
-
break;
|
|
205
|
-
case "step.reset":
|
|
206
|
-
steps[fact.stepId] = PENDING;
|
|
207
|
-
delete selectedArms[fact.stepId];
|
|
208
|
-
break;
|
|
209
|
-
case "step.started":
|
|
210
|
-
case "step.completed":
|
|
211
|
-
case "step.failed":
|
|
212
|
-
case "step.canceled":
|
|
213
|
-
case "step.retried":
|
|
214
|
-
case "step.skipped":
|
|
215
|
-
case "step.abort-requested": {
|
|
216
|
-
const prev = steps[fact.stepId] ?? PENDING;
|
|
217
|
-
const t = stepTransition(prev, fact);
|
|
218
|
-
if (t.anomaly) {
|
|
219
|
-
anomalies.push({
|
|
220
|
-
at: fact.at,
|
|
221
|
-
stepId: fact.stepId,
|
|
222
|
-
from: prev.tag,
|
|
223
|
-
fact: fact.kind
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
steps[fact.stepId] = t.next;
|
|
227
|
-
break;
|
|
228
|
-
}
|
|
229
|
-
case "signal.buffered":
|
|
230
|
-
if (!(fact.stepId in bufferedSignals)) {
|
|
231
|
-
bufferedSignals[fact.stepId] = {
|
|
232
|
-
payload: fact.payload,
|
|
233
|
-
...compact({ signalName: fact.signalName })
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
break;
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
return {
|
|
240
|
-
runId,
|
|
241
|
-
flowId,
|
|
242
|
-
input,
|
|
243
|
-
phase,
|
|
244
|
-
steps,
|
|
245
|
-
selectedArms,
|
|
246
|
-
bufferedSignals,
|
|
247
|
-
anomalies,
|
|
248
|
-
facts,
|
|
249
|
-
...compact({ parent, flowHash, codeVersion })
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
// src/internal.ts
|
|
254
|
-
function isOptional(ref) {
|
|
255
|
-
return "__optional" in ref;
|
|
256
|
-
}
|
|
257
|
-
function normalizeNeeds(needs) {
|
|
258
|
-
const out = {};
|
|
259
|
-
if (needs === void 0) return out;
|
|
260
|
-
for (const [key, ref] of Object.entries(needs)) {
|
|
261
|
-
out[key] = isOptional(ref) ? { step: ref.__optional, optional: true } : { step: ref, optional: false };
|
|
262
|
-
}
|
|
263
|
-
return out;
|
|
264
|
-
}
|
|
265
|
-
function makeEmit(onLog) {
|
|
266
|
-
if (!onLog) return () => {
|
|
267
|
-
};
|
|
268
|
-
return (entry) => {
|
|
269
|
-
try {
|
|
270
|
-
onLog(entry);
|
|
271
|
-
} catch {
|
|
272
|
-
}
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
function compact(obj) {
|
|
276
|
-
const out = {};
|
|
277
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
278
|
-
if (value !== void 0) out[key] = value;
|
|
279
|
-
}
|
|
280
|
-
return out;
|
|
281
|
-
}
|
|
282
|
-
var DEF = /* @__PURE__ */ Symbol("nagi.def");
|
|
283
|
-
function attachDef(meta, def) {
|
|
284
|
-
return { kind: meta.kind, id: meta.id, [DEF]: def };
|
|
285
|
-
}
|
|
286
|
-
function setDef(step, def) {
|
|
287
|
-
step[DEF] = def;
|
|
288
|
-
}
|
|
289
|
-
function getDef(step) {
|
|
290
|
-
return step[DEF];
|
|
291
|
-
}
|
|
292
|
-
function peekDef(step) {
|
|
293
|
-
return step[DEF];
|
|
294
|
-
}
|
|
295
|
-
function handlerDef(def) {
|
|
296
|
-
return def.kind === "task" || def.kind === "activity" || def.kind === "streaming" ? def : void 0;
|
|
297
|
-
}
|
|
298
|
-
function needsStepIds(def) {
|
|
299
|
-
return Object.values(def.needs).map((ref) => ref.step.id);
|
|
300
|
-
}
|
|
301
|
-
function resolveNeeds(def, loadResolved) {
|
|
302
|
-
const result = {};
|
|
303
|
-
for (const [localKey, ref] of Object.entries(def.needs)) {
|
|
304
|
-
const resolved = loadResolved(ref.step.id);
|
|
305
|
-
result[localKey] = ref.optional ? resolved : unwrap(resolved);
|
|
306
|
-
}
|
|
307
|
-
return result;
|
|
308
|
-
}
|
|
309
|
-
function asStepMapWithDefs(steps) {
|
|
310
|
-
return steps;
|
|
311
|
-
}
|
|
312
|
-
function selectArm(def, args) {
|
|
313
|
-
for (const arm of def.arms) {
|
|
314
|
-
if (arm.guard.kind === "otherwise") return arm.id;
|
|
315
|
-
if (arm.guard.when(args)) return arm.id;
|
|
316
|
-
}
|
|
317
|
-
throw new Error(
|
|
318
|
-
`match: no arm matched and no { otherwise: true } fallback was provided`
|
|
319
|
-
);
|
|
320
|
-
}
|
|
1
|
+
import { InMemoryClock, makeEmit, asStepMapWithDefs, getDef, NagiRuntimeError, compact, makeSignals, DEFAULT_REAPER_INTERVAL_MS, Facts, validationError, NagiFlowSnapshotGoneError, isTerminalRun, runStatusOf, validate, foldRun, needsStepIds, attachDef, setDef, stepStateOf, serializeError, NagiCanceledError, NagiSignalTimeoutError, dequeueBackoff, defaultSnapshotGonePolicy, isStepTerminal, stepStatusOf, NagiSnapshotDriftError, attemptOf, DEFAULT_RETRY, outputOf, resolveNeeds, resolvedOf, handlerDef, resolveRetry, isAbortRequested, selectArm, stepBackoff, peekDef, NagiNonRetryableError, normalizeNeeds } from './chunk-VQTYTI6X.js';
|
|
2
|
+
export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryStore, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, QUERY_RUNS_DEFAULT_LIMIT, QUERY_RUNS_MAX_LIMIT, attemptOf, clampQueryLimit, compareRunOrder, decideExpiredLeaseAction, decideSignal, decideTimeout, decodeRunCursor, defaultSnapshotGonePolicy, encodeRunCursor, errorOf, factEffects, isPastCursor, isStepTerminal, isTerminalRun, jsonContains, outputOf, foldRun as projectRunState, resolvedOf, rowDeltaOf, runStatusOf, selectExpired, selectPruneBatch, stepStateOf, stepStatusOf, unwrap } from './chunk-VQTYTI6X.js';
|
|
321
3
|
|
|
322
4
|
// src/builder.ts
|
|
323
5
|
function makeBuilder() {
|
|
@@ -328,7 +10,6 @@ function makeBuilder() {
|
|
|
328
10
|
run: config.run,
|
|
329
11
|
...compact({
|
|
330
12
|
retry: config.retry,
|
|
331
|
-
timeoutMs: config.timeoutMs,
|
|
332
13
|
when: config.when,
|
|
333
14
|
onStart: config.onStart,
|
|
334
15
|
onComplete: config.onComplete,
|
|
@@ -345,7 +26,6 @@ function makeBuilder() {
|
|
|
345
26
|
run: config.run,
|
|
346
27
|
...compact({
|
|
347
28
|
retry: config.retry,
|
|
348
|
-
timeoutMs: config.timeoutMs,
|
|
349
29
|
when: config.when,
|
|
350
30
|
onStart: config.onStart,
|
|
351
31
|
onComplete: config.onComplete,
|
|
@@ -362,7 +42,6 @@ function makeBuilder() {
|
|
|
362
42
|
run: config.run,
|
|
363
43
|
...compact({
|
|
364
44
|
retry: config.retry,
|
|
365
|
-
timeoutMs: config.timeoutMs,
|
|
366
45
|
when: config.when,
|
|
367
46
|
onStart: config.onStart,
|
|
368
47
|
onComplete: config.onComplete,
|
|
@@ -377,9 +56,9 @@ function makeBuilder() {
|
|
|
377
56
|
kind: "signal",
|
|
378
57
|
needs: normalizeNeeds(config.needs),
|
|
379
58
|
schema: config.schema,
|
|
59
|
+
timeoutMs: config.timeoutMs,
|
|
380
60
|
...compact({
|
|
381
61
|
names: config.names,
|
|
382
|
-
timeoutMs: config.timeoutMs,
|
|
383
62
|
when: config.when
|
|
384
63
|
})
|
|
385
64
|
};
|
|
@@ -392,7 +71,6 @@ function makeBuilder() {
|
|
|
392
71
|
childFlowId: child.id,
|
|
393
72
|
buildInput: config.input,
|
|
394
73
|
...compact({
|
|
395
|
-
timeoutMs: config.timeoutMs,
|
|
396
74
|
when: config.when
|
|
397
75
|
})
|
|
398
76
|
};
|
|
@@ -574,10 +252,6 @@ function assertSignalNameUniqueness(flowId, finalSteps) {
|
|
|
574
252
|
}
|
|
575
253
|
|
|
576
254
|
// src/canonicalize.ts
|
|
577
|
-
var DEFAULT_RETRY = {
|
|
578
|
-
initialDelayMs: 1e3,
|
|
579
|
-
maxDelayMs: 6e4
|
|
580
|
-
};
|
|
581
255
|
var warnedAboutSourceHash = false;
|
|
582
256
|
function warnSourceHashOnce() {
|
|
583
257
|
if (warnedAboutSourceHash) return;
|
|
@@ -612,7 +286,8 @@ async function canonicalizeStep(id, def) {
|
|
|
612
286
|
}
|
|
613
287
|
async function applyGuardAndTimeout(out, def) {
|
|
614
288
|
if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
|
|
615
|
-
if (def.timeoutMs !== void 0
|
|
289
|
+
if (def.timeoutMs !== void 0 && def.timeoutMs !== "unbounded")
|
|
290
|
+
out.timeoutMs = def.timeoutMs;
|
|
616
291
|
}
|
|
617
292
|
async function canonicalizeTask(base, def) {
|
|
618
293
|
const out = { ...base };
|
|
@@ -816,1414 +491,131 @@ function cmp(a, b) {
|
|
|
816
491
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
817
492
|
}
|
|
818
493
|
|
|
819
|
-
// src/
|
|
820
|
-
var
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
494
|
+
// src/run-id.ts
|
|
495
|
+
var RunId = {
|
|
496
|
+
parse(s) {
|
|
497
|
+
if (typeof s !== "string" || s.length === 0) {
|
|
498
|
+
throw validationError("RunId.parse: must be a non-empty string", [
|
|
499
|
+
"runId"
|
|
500
|
+
]);
|
|
501
|
+
}
|
|
502
|
+
if (/\s/.test(s)) {
|
|
503
|
+
throw validationError("RunId.parse: must not contain whitespace", [
|
|
504
|
+
"runId"
|
|
505
|
+
]);
|
|
506
|
+
}
|
|
507
|
+
return s;
|
|
508
|
+
},
|
|
509
|
+
fromTrusted(s) {
|
|
510
|
+
return s;
|
|
826
511
|
}
|
|
827
512
|
};
|
|
828
|
-
function
|
|
829
|
-
|
|
513
|
+
async function deriveChildRunId(key) {
|
|
514
|
+
const seed = `nagi:subflow:${key.runId}:${key.stepId}:gen${key.generation}`;
|
|
515
|
+
const digest = await crypto.subtle.digest(
|
|
516
|
+
"SHA-256",
|
|
517
|
+
new TextEncoder().encode(seed)
|
|
518
|
+
);
|
|
519
|
+
const bytes = new Uint8Array(digest).subarray(0, 16);
|
|
520
|
+
bytes[6] = (bytes[6] ?? 0) & 15 | 80;
|
|
521
|
+
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
522
|
+
const hex2 = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
|
|
523
|
+
""
|
|
524
|
+
);
|
|
525
|
+
const uuid = `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20, 32)}`;
|
|
526
|
+
return `run-${uuid}`;
|
|
830
527
|
}
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
`Run ${runId} was canceled (superseded by run ${canceledByRunId} for concurrency key "${concurrencyKey}").`
|
|
848
|
-
);
|
|
849
|
-
this.name = "NagiCanceledError";
|
|
850
|
-
this.runId = runId;
|
|
851
|
-
this.canceledByRunId = canceledByRunId;
|
|
852
|
-
this.concurrencyKey = concurrencyKey;
|
|
853
|
-
this.cause = {
|
|
854
|
-
canceledByRunId,
|
|
855
|
-
concurrencyKey
|
|
856
|
-
};
|
|
857
|
-
}
|
|
858
|
-
};
|
|
859
|
-
var NagiSignalTimeoutError = class extends Error {
|
|
860
|
-
runId;
|
|
861
|
-
stepId;
|
|
862
|
-
fireAt;
|
|
863
|
-
constructor({
|
|
864
|
-
runId,
|
|
865
|
-
stepId,
|
|
866
|
-
fireAt
|
|
867
|
-
}) {
|
|
868
|
-
super(
|
|
869
|
-
`Signal step "${stepId}" (run ${runId}) timed out \u2014 no signal arrived before its deadline ${fireAt.toISOString()}.`
|
|
870
|
-
);
|
|
871
|
-
this.name = "NagiSignalTimeoutError";
|
|
872
|
-
this.runId = runId;
|
|
873
|
-
this.stepId = stepId;
|
|
874
|
-
this.fireAt = fireAt;
|
|
528
|
+
|
|
529
|
+
// src/exec/hooks.ts
|
|
530
|
+
function makeHooks(deps) {
|
|
531
|
+
async function fireHook(hook, event, hookName) {
|
|
532
|
+
if (deps.fireHooks === false) return;
|
|
533
|
+
if (hook === void 0) return;
|
|
534
|
+
try {
|
|
535
|
+
await hook(event);
|
|
536
|
+
} catch (err) {
|
|
537
|
+
const { message, stack } = serializeError(err);
|
|
538
|
+
deps.emitLog({
|
|
539
|
+
level: "error",
|
|
540
|
+
msg: `nagi hook "${hookName}" threw \u2014 swallowed`,
|
|
541
|
+
attrs: { error: message, ...stack !== void 0 ? { stack } : {} }
|
|
542
|
+
});
|
|
543
|
+
}
|
|
875
544
|
}
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
flowId;
|
|
880
|
-
pinnedHash;
|
|
881
|
-
currentHash;
|
|
882
|
-
constructor({
|
|
883
|
-
runId,
|
|
884
|
-
flowId,
|
|
885
|
-
pinnedHash,
|
|
886
|
-
currentHash
|
|
887
|
-
}) {
|
|
888
|
-
super(
|
|
889
|
-
currentHash === null ? `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but flow "${flowId}" is not registered with the current nagi(). Pin a worker on the prior code version or migrate the run.` : `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but the current registry has hash ${currentHash.slice(0, 12)}\u2026. Pin a worker on the prior code version or migrate the run.`
|
|
890
|
-
);
|
|
891
|
-
this.name = "NagiFlowSnapshotGoneError";
|
|
892
|
-
this.runId = runId;
|
|
893
|
-
this.flowId = flowId;
|
|
894
|
-
this.pinnedHash = pinnedHash;
|
|
895
|
-
this.currentHash = currentHash;
|
|
545
|
+
async function fireStepLifecycle(stepHook, flowHook, [stepName, flowName], event) {
|
|
546
|
+
await fireHook(stepHook, event, stepName);
|
|
547
|
+
await fireHook(flowHook, event, flowName);
|
|
896
548
|
}
|
|
897
|
-
};
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
);
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
549
|
+
return { fireHook, fireStepLifecycle };
|
|
550
|
+
}
|
|
551
|
+
|
|
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
|
+
}
|
|
914
571
|
}
|
|
915
|
-
};
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
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))
|
|
927
584
|
);
|
|
928
|
-
|
|
929
|
-
this.runId = runId;
|
|
930
|
-
this.expected = expected;
|
|
931
|
-
this.actual = actual;
|
|
932
|
-
}
|
|
933
|
-
};
|
|
934
|
-
function serializeError(err) {
|
|
935
|
-
if (err instanceof Error) {
|
|
936
|
-
return {
|
|
937
|
-
name: err.name,
|
|
938
|
-
message: err.message,
|
|
939
|
-
...compact({ stack: err.stack })
|
|
940
|
-
};
|
|
585
|
+
if (!when({ input, needs })) return { kind: "skip", reason: "when-false" };
|
|
941
586
|
}
|
|
942
|
-
return {
|
|
587
|
+
return { kind: "run" };
|
|
943
588
|
}
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
589
|
+
function gateFor(status) {
|
|
590
|
+
switch (status) {
|
|
591
|
+
case "blocked":
|
|
592
|
+
return { kind: "block" };
|
|
593
|
+
case "transitive-skip":
|
|
594
|
+
return { kind: "skip", reason: "transitive" };
|
|
950
595
|
}
|
|
951
|
-
|
|
952
|
-
|
|
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";
|
|
953
606
|
}
|
|
954
|
-
|
|
955
|
-
|
|
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";
|
|
956
615
|
}
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
backoffMs: 0
|
|
961
|
-
};
|
|
962
|
-
}
|
|
963
|
-
var DEFAULT_REAPER_INTERVAL_MS = 3e4;
|
|
964
|
-
|
|
965
|
-
// src/facts.ts
|
|
966
|
-
var Facts = {
|
|
967
|
-
flowStarted(a) {
|
|
968
|
-
return {
|
|
969
|
-
kind: "flow.started",
|
|
970
|
-
runId: a.runId,
|
|
971
|
-
flowId: a.flowId,
|
|
972
|
-
input: a.input,
|
|
973
|
-
at: a.at,
|
|
974
|
-
...compact({
|
|
975
|
-
codeVersion: a.codeVersion,
|
|
976
|
-
flowHash: a.flowHash,
|
|
977
|
-
parent: a.parent
|
|
978
|
-
})
|
|
979
|
-
};
|
|
980
|
-
},
|
|
981
|
-
flowCompleted(runId, output, at) {
|
|
982
|
-
return { kind: "flow.completed", runId, output, at };
|
|
983
|
-
},
|
|
984
|
-
flowFailed(runId, error, at) {
|
|
985
|
-
return { kind: "flow.failed", runId, error, at };
|
|
986
|
-
},
|
|
987
|
-
flowCanceled(runId, args, at) {
|
|
988
|
-
return { ...args, kind: "flow.canceled", runId, at };
|
|
989
|
-
},
|
|
990
|
-
flowCanceledByConcurrency(a) {
|
|
991
|
-
return {
|
|
992
|
-
kind: "flow.canceled",
|
|
993
|
-
cause: "concurrency",
|
|
994
|
-
runId: a.runId,
|
|
995
|
-
at: a.at,
|
|
996
|
-
canceledByRunId: a.canceledByRunId,
|
|
997
|
-
concurrencyKey: a.concurrencyKey
|
|
998
|
-
};
|
|
999
|
-
},
|
|
1000
|
-
stepStarted(runId, stepId, attempt, stepKind, at) {
|
|
1001
|
-
return { kind: "step.started", runId, stepId, attempt, stepKind, at };
|
|
1002
|
-
},
|
|
1003
|
-
stepCompleted(runId, stepId, attempt, output, at) {
|
|
1004
|
-
return { kind: "step.completed", runId, stepId, attempt, output, at };
|
|
1005
|
-
},
|
|
1006
|
-
stepFailed(runId, stepId, attempt, error, at) {
|
|
1007
|
-
return { kind: "step.failed", runId, stepId, attempt, error, at };
|
|
1008
|
-
},
|
|
1009
|
-
stepCanceled(runId, stepId, attempt, at, error) {
|
|
1010
|
-
return {
|
|
1011
|
-
kind: "step.canceled",
|
|
1012
|
-
runId,
|
|
1013
|
-
stepId,
|
|
1014
|
-
attempt,
|
|
1015
|
-
at,
|
|
1016
|
-
...compact({ error })
|
|
1017
|
-
};
|
|
1018
|
-
},
|
|
1019
|
-
stepRetried(runId, stepId, attempt, nextAttemptAt, error, at) {
|
|
1020
|
-
return {
|
|
1021
|
-
kind: "step.retried",
|
|
1022
|
-
runId,
|
|
1023
|
-
stepId,
|
|
1024
|
-
attempt,
|
|
1025
|
-
nextAttemptAt,
|
|
1026
|
-
error,
|
|
1027
|
-
at
|
|
1028
|
-
};
|
|
1029
|
-
},
|
|
1030
|
-
stepSkipped(a) {
|
|
1031
|
-
return {
|
|
1032
|
-
kind: "step.skipped",
|
|
1033
|
-
runId: a.runId,
|
|
1034
|
-
stepId: a.stepId,
|
|
1035
|
-
reason: a.reason,
|
|
1036
|
-
at: a.at,
|
|
1037
|
-
...compact({ actor: a.actor, note: a.note })
|
|
1038
|
-
};
|
|
1039
|
-
},
|
|
1040
|
-
stepReset(a) {
|
|
1041
|
-
return {
|
|
1042
|
-
kind: "step.reset",
|
|
1043
|
-
runId: a.runId,
|
|
1044
|
-
stepId: a.stepId,
|
|
1045
|
-
at: a.at,
|
|
1046
|
-
...compact({
|
|
1047
|
-
cascadedFrom: a.cascadedFrom,
|
|
1048
|
-
actor: a.actor,
|
|
1049
|
-
note: a.note
|
|
1050
|
-
})
|
|
1051
|
-
};
|
|
1052
|
-
},
|
|
1053
|
-
stepAbortRequested(a) {
|
|
1054
|
-
return {
|
|
1055
|
-
kind: "step.abort-requested",
|
|
1056
|
-
runId: a.runId,
|
|
1057
|
-
stepId: a.stepId,
|
|
1058
|
-
attempt: a.attempt,
|
|
1059
|
-
actor: a.actor,
|
|
1060
|
-
at: a.at,
|
|
1061
|
-
...compact({ note: a.note })
|
|
1062
|
-
};
|
|
1063
|
-
},
|
|
1064
|
-
matchArmSelected(runId, stepId, arm, at) {
|
|
1065
|
-
return { kind: "match.arm-selected", runId, stepId, arm, at };
|
|
1066
|
-
},
|
|
1067
|
-
signalReceived(a) {
|
|
1068
|
-
return {
|
|
1069
|
-
kind: "signal.received",
|
|
1070
|
-
runId: a.runId,
|
|
1071
|
-
stepId: a.stepId,
|
|
1072
|
-
payload: a.payload,
|
|
1073
|
-
at: a.at,
|
|
1074
|
-
...compact({ signalName: a.signalName })
|
|
1075
|
-
};
|
|
1076
|
-
},
|
|
1077
|
-
signalBuffered(a) {
|
|
1078
|
-
return {
|
|
1079
|
-
kind: "signal.buffered",
|
|
1080
|
-
runId: a.runId,
|
|
1081
|
-
stepId: a.stepId,
|
|
1082
|
-
payload: a.payload,
|
|
1083
|
-
at: a.at,
|
|
1084
|
-
...compact({ signalName: a.signalName })
|
|
1085
|
-
};
|
|
1086
|
-
},
|
|
1087
|
-
leaseReaped(a) {
|
|
1088
|
-
return {
|
|
1089
|
-
kind: "lease.reaped",
|
|
1090
|
-
runId: a.runId,
|
|
1091
|
-
stepId: a.stepId,
|
|
1092
|
-
attempt: a.attempt,
|
|
1093
|
-
at: a.at,
|
|
1094
|
-
reapedAt: a.reapedAt,
|
|
1095
|
-
reason: "expired"
|
|
1096
|
-
};
|
|
1097
|
-
},
|
|
1098
|
-
flowRefUpdated(a) {
|
|
1099
|
-
return {
|
|
1100
|
-
kind: "flow_ref.updated",
|
|
1101
|
-
flowId: a.flowId,
|
|
1102
|
-
from: a.from,
|
|
1103
|
-
to: a.to,
|
|
1104
|
-
at: a.at
|
|
1105
|
-
};
|
|
1106
|
-
}
|
|
1107
|
-
};
|
|
1108
|
-
|
|
1109
|
-
// src/validate.ts
|
|
1110
|
-
async function validate(schema, value) {
|
|
1111
|
-
const result = await schema["~standard"].validate(value);
|
|
1112
|
-
if ("issues" in result && result.issues !== void 0) {
|
|
1113
|
-
throw new NagiValidationError(result.issues);
|
|
1114
|
-
}
|
|
1115
|
-
return result.value;
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
// src/signals.ts
|
|
1119
|
-
var NOOP = { kind: "noop", result: { tag: "noop" } };
|
|
1120
|
-
function decideSignal(args) {
|
|
1121
|
-
const { runState, stepId, at, incoming } = args;
|
|
1122
|
-
const { runId } = runState;
|
|
1123
|
-
const step = stepStateOf(runState, stepId);
|
|
1124
|
-
if (isStepTerminal(step)) return NOOP;
|
|
1125
|
-
if (step.tag === "awaitingSignal") {
|
|
1126
|
-
const source = incoming ?? runState.bufferedSignals[stepId];
|
|
1127
|
-
if (source === void 0) return NOOP;
|
|
1128
|
-
const { attempt } = step;
|
|
1129
|
-
return {
|
|
1130
|
-
kind: "deliver",
|
|
1131
|
-
attempt,
|
|
1132
|
-
received: Facts.signalReceived({
|
|
1133
|
-
runId,
|
|
1134
|
-
stepId,
|
|
1135
|
-
payload: source.payload,
|
|
1136
|
-
at,
|
|
1137
|
-
...compact({ signalName: source.signalName })
|
|
1138
|
-
}),
|
|
1139
|
-
completed: Facts.stepCompleted(
|
|
1140
|
-
runId,
|
|
1141
|
-
stepId,
|
|
1142
|
-
attempt,
|
|
1143
|
-
source.payload,
|
|
1144
|
-
at
|
|
1145
|
-
),
|
|
1146
|
-
result: {
|
|
1147
|
-
tag: "delivered",
|
|
1148
|
-
attempt,
|
|
1149
|
-
payload: source.payload,
|
|
1150
|
-
...compact({ signalName: source.signalName })
|
|
1151
|
-
}
|
|
1152
|
-
};
|
|
1153
|
-
}
|
|
1154
|
-
if (incoming === void 0) return NOOP;
|
|
1155
|
-
if (runState.bufferedSignals[stepId] !== void 0) {
|
|
1156
|
-
return { kind: "buffer", fact: null, result: { tag: "buffered" } };
|
|
1157
|
-
}
|
|
1158
|
-
return {
|
|
1159
|
-
kind: "buffer",
|
|
1160
|
-
fact: Facts.signalBuffered({
|
|
1161
|
-
runId,
|
|
1162
|
-
stepId,
|
|
1163
|
-
payload: incoming.payload,
|
|
1164
|
-
at,
|
|
1165
|
-
...compact({ signalName: incoming.signalName })
|
|
1166
|
-
}),
|
|
1167
|
-
result: { tag: "buffered" }
|
|
1168
|
-
};
|
|
1169
|
-
}
|
|
1170
|
-
function decideTimeout(args) {
|
|
1171
|
-
const { runState, stepId, fireAt, at } = args;
|
|
1172
|
-
const step = stepStateOf(runState, stepId);
|
|
1173
|
-
if (step.tag !== "awaitingSignal") return { kind: "noop" };
|
|
1174
|
-
const error = serializeError(
|
|
1175
|
-
new NagiSignalTimeoutError({ runId: runState.runId, stepId, fireAt })
|
|
1176
|
-
);
|
|
1177
|
-
return {
|
|
1178
|
-
kind: "fail",
|
|
1179
|
-
attempt: step.attempt,
|
|
1180
|
-
fact: Facts.stepFailed(runState.runId, stepId, step.attempt, error, at)
|
|
1181
|
-
};
|
|
1182
|
-
}
|
|
1183
|
-
function makeSignals(deps) {
|
|
1184
|
-
const { dispatcher, store, clock, registry, hooks, flowHooks, emitLog } = deps;
|
|
1185
|
-
async function signal(runId, signalName, payload) {
|
|
1186
|
-
const runState = await store.loadRunState(runId);
|
|
1187
|
-
const flow2 = registry.requireForRun(runState.flowId, runId);
|
|
1188
|
-
const resolved = resolveSignalStep(flow2, signalName);
|
|
1189
|
-
if (resolved === null) {
|
|
1190
|
-
throw new NagiRuntimeError(
|
|
1191
|
-
`Flow "${flow2.id}" has no signal step accepting "${signalName}".`
|
|
1192
|
-
);
|
|
1193
|
-
}
|
|
1194
|
-
const { stepId, def } = resolved;
|
|
1195
|
-
const validated = await validate(def.schema, payload);
|
|
1196
|
-
const carriesAlias = signalName !== stepId;
|
|
1197
|
-
const result = await store.settleSignal({
|
|
1198
|
-
runId,
|
|
1199
|
-
stepId,
|
|
1200
|
-
at: clock.now(),
|
|
1201
|
-
incoming: {
|
|
1202
|
-
payload: validated,
|
|
1203
|
-
...carriesAlias ? { signalName } : {}
|
|
1204
|
-
}
|
|
1205
|
-
});
|
|
1206
|
-
switch (result.tag) {
|
|
1207
|
-
case "delivered":
|
|
1208
|
-
await hooks.fireHook(
|
|
1209
|
-
flowHooks?.onSignalReceived,
|
|
1210
|
-
{
|
|
1211
|
-
runId,
|
|
1212
|
-
flowId: flow2.id,
|
|
1213
|
-
stepId,
|
|
1214
|
-
attempt: result.attempt,
|
|
1215
|
-
kind: "signal",
|
|
1216
|
-
payload: validated,
|
|
1217
|
-
at: clock.now()
|
|
1218
|
-
},
|
|
1219
|
-
"onSignalReceived"
|
|
1220
|
-
);
|
|
1221
|
-
await dispatcher.advance(runId);
|
|
1222
|
-
return;
|
|
1223
|
-
case "buffered":
|
|
1224
|
-
emitLog({
|
|
1225
|
-
level: "info",
|
|
1226
|
-
msg: "nagi: signal buffered before step ready; will apply on dispatch",
|
|
1227
|
-
attrs: { runId, stepId, signalName }
|
|
1228
|
-
});
|
|
1229
|
-
return;
|
|
1230
|
-
case "noop":
|
|
1231
|
-
emitLog({
|
|
1232
|
-
level: "info",
|
|
1233
|
-
msg: "nagi: signal arrived after step resolved",
|
|
1234
|
-
attrs: { runId, stepId, signalName }
|
|
1235
|
-
});
|
|
1236
|
-
return;
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
return { signal };
|
|
1240
|
-
}
|
|
1241
|
-
function resolveSignalStep(flow2, signalName) {
|
|
1242
|
-
const steps = asStepMapWithDefs(flow2.steps);
|
|
1243
|
-
const direct = steps[signalName];
|
|
1244
|
-
if (direct !== void 0) {
|
|
1245
|
-
const d = getDef(direct);
|
|
1246
|
-
if (d.kind === "signal" && d.names === void 0) {
|
|
1247
|
-
return { stepId: signalName, def: d };
|
|
1248
|
-
}
|
|
1249
|
-
}
|
|
1250
|
-
for (const [id, s] of Object.entries(steps)) {
|
|
1251
|
-
const d = getDef(s);
|
|
1252
|
-
if (d.kind === "signal" && d.names?.includes(signalName)) {
|
|
1253
|
-
return { stepId: id, def: d };
|
|
1254
|
-
}
|
|
1255
|
-
}
|
|
1256
|
-
return null;
|
|
1257
|
-
}
|
|
1258
|
-
|
|
1259
|
-
// src/stream-hub.ts
|
|
1260
|
-
var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
|
|
1261
|
-
var STREAM_REPLAY_BUFFER_CAP = 256;
|
|
1262
|
-
function makeWake() {
|
|
1263
|
-
let resolve;
|
|
1264
|
-
const promise = new Promise((r) => {
|
|
1265
|
-
resolve = r;
|
|
1266
|
-
});
|
|
1267
|
-
return { promise, resolve };
|
|
1268
|
-
}
|
|
1269
|
-
var Subscriber = class {
|
|
1270
|
-
buffer = [];
|
|
1271
|
-
pendingDropped = 0;
|
|
1272
|
-
closed = false;
|
|
1273
|
-
wake = null;
|
|
1274
|
-
push(event) {
|
|
1275
|
-
if (this.closed) return;
|
|
1276
|
-
if (this.buffer.length >= STREAM_SUBSCRIBER_BUFFER_CAP) {
|
|
1277
|
-
const idx = this.buffer.findIndex((e) => e.kind === "chunk");
|
|
1278
|
-
if (idx === -1) {
|
|
1279
|
-
if (event.kind === "chunk") {
|
|
1280
|
-
this.pendingDropped += 1;
|
|
1281
|
-
this.signal();
|
|
1282
|
-
return;
|
|
1283
|
-
}
|
|
1284
|
-
} else {
|
|
1285
|
-
this.buffer.splice(idx, 1);
|
|
1286
|
-
this.pendingDropped += 1;
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
this.buffer.push(event);
|
|
1290
|
-
this.signal();
|
|
1291
|
-
}
|
|
1292
|
-
close() {
|
|
1293
|
-
if (this.closed) return;
|
|
1294
|
-
this.closed = true;
|
|
1295
|
-
this.signal();
|
|
1296
|
-
}
|
|
1297
|
-
signal() {
|
|
1298
|
-
if (this.wake !== null) {
|
|
1299
|
-
const w = this.wake;
|
|
1300
|
-
this.wake = null;
|
|
1301
|
-
w.resolve();
|
|
1302
|
-
}
|
|
1303
|
-
}
|
|
1304
|
-
async next() {
|
|
1305
|
-
for (; ; ) {
|
|
1306
|
-
if (this.pendingDropped > 0) {
|
|
1307
|
-
const count = this.pendingDropped;
|
|
1308
|
-
this.pendingDropped = 0;
|
|
1309
|
-
return { kind: "dropped", count };
|
|
1310
|
-
}
|
|
1311
|
-
const head = this.buffer.shift();
|
|
1312
|
-
if (head !== void 0) return head;
|
|
1313
|
-
if (this.closed) return null;
|
|
1314
|
-
const w = makeWake();
|
|
1315
|
-
this.wake = w;
|
|
1316
|
-
await w.promise;
|
|
1317
|
-
}
|
|
1318
|
-
}
|
|
1319
|
-
};
|
|
1320
|
-
var InMemoryStreamHub = class _InMemoryStreamHub {
|
|
1321
|
-
channels = /* @__PURE__ */ new Map();
|
|
1322
|
-
static key(runId, stepId) {
|
|
1323
|
-
return `${runId}::${stepId}`;
|
|
1324
|
-
}
|
|
1325
|
-
getOrCreate(runId, stepId) {
|
|
1326
|
-
const key = _InMemoryStreamHub.key(runId, stepId);
|
|
1327
|
-
let channel = this.channels.get(key);
|
|
1328
|
-
if (channel === void 0) {
|
|
1329
|
-
channel = { subscribers: /* @__PURE__ */ new Set(), replay: [], closed: false };
|
|
1330
|
-
this.channels.set(key, channel);
|
|
1331
|
-
}
|
|
1332
|
-
return channel;
|
|
1333
|
-
}
|
|
1334
|
-
publishChunk(runId, stepId, chunk) {
|
|
1335
|
-
const channel = this.getOrCreate(runId, stepId);
|
|
1336
|
-
if (channel.closed) return;
|
|
1337
|
-
const event = { kind: "chunk", chunk };
|
|
1338
|
-
channel.replay.push(event);
|
|
1339
|
-
if (channel.replay.length > STREAM_REPLAY_BUFFER_CAP)
|
|
1340
|
-
channel.replay.shift();
|
|
1341
|
-
for (const sub of channel.subscribers) sub.push(event);
|
|
1342
|
-
}
|
|
1343
|
-
signalRetry(runId, stepId, attempt) {
|
|
1344
|
-
const channel = this.getOrCreate(runId, stepId);
|
|
1345
|
-
if (channel.closed) return;
|
|
1346
|
-
channel.replay.length = 0;
|
|
1347
|
-
const event = { kind: "retry", attempt };
|
|
1348
|
-
for (const sub of channel.subscribers) sub.push(event);
|
|
1349
|
-
}
|
|
1350
|
-
// NB: no-op when no channel exists. InMemoryStore.appendFact fires this for
|
|
1351
|
-
// EVERY step.completed — including non-streaming steps that never published —
|
|
1352
|
-
// so creating a channel here would leak one per such step. Closed-ness is
|
|
1353
|
-
// authoritative in the durable facts, not the hub.
|
|
1354
|
-
closeOk(runId, stepId) {
|
|
1355
|
-
const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
|
|
1356
|
-
if (channel === void 0 || channel.closed) return;
|
|
1357
|
-
channel.closed = true;
|
|
1358
|
-
channel.replay.length = 0;
|
|
1359
|
-
for (const sub of channel.subscribers) sub.close();
|
|
1360
|
-
channel.subscribers.clear();
|
|
1361
|
-
}
|
|
1362
|
-
closeError(runId, stepId, error) {
|
|
1363
|
-
const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
|
|
1364
|
-
if (channel === void 0 || channel.closed) return;
|
|
1365
|
-
channel.closed = true;
|
|
1366
|
-
channel.replay.length = 0;
|
|
1367
|
-
const event = { kind: "error", error };
|
|
1368
|
-
for (const sub of channel.subscribers) {
|
|
1369
|
-
sub.push(event);
|
|
1370
|
-
sub.close();
|
|
1371
|
-
}
|
|
1372
|
-
channel.subscribers.clear();
|
|
1373
|
-
}
|
|
1374
|
-
closeRun(runId) {
|
|
1375
|
-
const prefix = `${runId}::`;
|
|
1376
|
-
for (const [key, channel] of this.channels) {
|
|
1377
|
-
if (!key.startsWith(prefix) || channel.closed) continue;
|
|
1378
|
-
channel.closed = true;
|
|
1379
|
-
channel.replay.length = 0;
|
|
1380
|
-
for (const sub of channel.subscribers) sub.close();
|
|
1381
|
-
channel.subscribers.clear();
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
subscribeStream(runId, stepId, opts) {
|
|
1385
|
-
const channel = this.getOrCreate(runId, stepId);
|
|
1386
|
-
if (channel.closed) {
|
|
1387
|
-
return {
|
|
1388
|
-
[Symbol.asyncIterator]() {
|
|
1389
|
-
return {
|
|
1390
|
-
next: async () => ({ value: void 0, done: true })
|
|
1391
|
-
};
|
|
1392
|
-
}
|
|
1393
|
-
};
|
|
1394
|
-
}
|
|
1395
|
-
const sub = new Subscriber();
|
|
1396
|
-
if (opts?.replayBuffered === true) {
|
|
1397
|
-
for (const event of channel.replay) sub.push(event);
|
|
1398
|
-
}
|
|
1399
|
-
channel.subscribers.add(sub);
|
|
1400
|
-
const remove = () => {
|
|
1401
|
-
channel.subscribers.delete(sub);
|
|
1402
|
-
};
|
|
1403
|
-
return {
|
|
1404
|
-
[Symbol.asyncIterator]() {
|
|
1405
|
-
return {
|
|
1406
|
-
next: async () => {
|
|
1407
|
-
const event = await sub.next();
|
|
1408
|
-
if (event === null) {
|
|
1409
|
-
remove();
|
|
1410
|
-
return { value: void 0, done: true };
|
|
1411
|
-
}
|
|
1412
|
-
return { value: event, done: false };
|
|
1413
|
-
},
|
|
1414
|
-
return: async () => {
|
|
1415
|
-
sub.close();
|
|
1416
|
-
remove();
|
|
1417
|
-
return { value: void 0, done: true };
|
|
1418
|
-
}
|
|
1419
|
-
};
|
|
1420
|
-
}
|
|
1421
|
-
};
|
|
1422
|
-
}
|
|
1423
|
-
};
|
|
1424
|
-
|
|
1425
|
-
// src/memory.ts
|
|
1426
|
-
var DEFAULT_STORE_LEASE_MS = 6e4;
|
|
1427
|
-
var InMemoryStore = class {
|
|
1428
|
-
facts = /* @__PURE__ */ new Map();
|
|
1429
|
-
onces = /* @__PURE__ */ new Map();
|
|
1430
|
-
leases = /* @__PURE__ */ new Map();
|
|
1431
|
-
snapshots = /* @__PURE__ */ new Map();
|
|
1432
|
-
refs = /* @__PURE__ */ new Map();
|
|
1433
|
-
globalFacts = [];
|
|
1434
|
-
activeByKey = /* @__PURE__ */ new Map();
|
|
1435
|
-
keyByActiveRun = /* @__PURE__ */ new Map();
|
|
1436
|
-
childrenByParent = /* @__PURE__ */ new Map();
|
|
1437
|
-
summaries = /* @__PURE__ */ new Map();
|
|
1438
|
-
streamHub = new InMemoryStreamHub();
|
|
1439
|
-
// Durable signal-timeout deadlines, keyed `${runId}::${stepId}` → fire_at.
|
|
1440
|
-
// The Postgres analogue is the nagi.timer table; this is its in-memory twin
|
|
1441
|
-
// (distinct from the InMemoryClock's setTimeout-based scheduler timers).
|
|
1442
|
-
signalTimers = /* @__PURE__ */ new Map();
|
|
1443
|
-
leaseMs;
|
|
1444
|
-
constructor(opts = {}) {
|
|
1445
|
-
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
1446
|
-
}
|
|
1447
|
-
async appendFact(runId, fact) {
|
|
1448
|
-
const list = this.facts.get(runId) ?? [];
|
|
1449
|
-
list.push(fact);
|
|
1450
|
-
this.facts.set(runId, list);
|
|
1451
|
-
switch (fact.kind) {
|
|
1452
|
-
case "step.completed":
|
|
1453
|
-
this.streamHub.closeOk(runId, fact.stepId);
|
|
1454
|
-
break;
|
|
1455
|
-
case "step.failed":
|
|
1456
|
-
this.streamHub.closeError(runId, fact.stepId, fact.error);
|
|
1457
|
-
break;
|
|
1458
|
-
case "step.retried":
|
|
1459
|
-
this.streamHub.signalRetry(
|
|
1460
|
-
runId,
|
|
1461
|
-
fact.stepId,
|
|
1462
|
-
fact.attempt + 1
|
|
1463
|
-
);
|
|
1464
|
-
break;
|
|
1465
|
-
case "flow.completed":
|
|
1466
|
-
case "flow.failed":
|
|
1467
|
-
case "flow.canceled":
|
|
1468
|
-
this.streamHub.closeRun(runId);
|
|
1469
|
-
break;
|
|
1470
|
-
}
|
|
1471
|
-
if (fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled") {
|
|
1472
|
-
const slot = this.keyByActiveRun.get(runId);
|
|
1473
|
-
if (slot !== void 0) {
|
|
1474
|
-
this.keyByActiveRun.delete(runId);
|
|
1475
|
-
if (this.activeByKey.get(slot) === runId) {
|
|
1476
|
-
this.activeByKey.delete(slot);
|
|
1477
|
-
}
|
|
1478
|
-
}
|
|
1479
|
-
}
|
|
1480
|
-
if (fact.kind === "step.reset") {
|
|
1481
|
-
const leasePrefix = `${runId}::${fact.stepId}::`;
|
|
1482
|
-
for (const key of this.leases.keys()) {
|
|
1483
|
-
if (key.startsWith(leasePrefix)) this.leases.delete(key);
|
|
1484
|
-
}
|
|
1485
|
-
this.signalTimers.delete(`${runId}::${fact.stepId}`);
|
|
1486
|
-
}
|
|
1487
|
-
}
|
|
1488
|
-
async tryStartRun(runId, fact, concurrency) {
|
|
1489
|
-
if (this.facts.has(runId) || this.summaries.has(runId)) {
|
|
1490
|
-
return { started: false, canceled: [] };
|
|
1491
|
-
}
|
|
1492
|
-
const canceled = [];
|
|
1493
|
-
if (concurrency !== void 0) {
|
|
1494
|
-
const slot = `${fact.flowId}::${concurrency.key}`;
|
|
1495
|
-
const priorRunId = this.activeByKey.get(slot);
|
|
1496
|
-
if (priorRunId !== void 0) {
|
|
1497
|
-
const cancelFact = Facts.flowCanceledByConcurrency({
|
|
1498
|
-
runId: priorRunId,
|
|
1499
|
-
at: fact.at,
|
|
1500
|
-
canceledByRunId: runId,
|
|
1501
|
-
concurrencyKey: concurrency.key
|
|
1502
|
-
});
|
|
1503
|
-
await this.appendFact(priorRunId, cancelFact);
|
|
1504
|
-
canceled.push({ runId: priorRunId, fact: cancelFact });
|
|
1505
|
-
}
|
|
1506
|
-
this.activeByKey.set(slot, runId);
|
|
1507
|
-
this.keyByActiveRun.set(runId, slot);
|
|
1508
|
-
}
|
|
1509
|
-
this.facts.set(runId, [fact]);
|
|
1510
|
-
const parentRunId = fact.parent?.runId;
|
|
1511
|
-
if (parentRunId !== void 0) {
|
|
1512
|
-
const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
|
|
1513
|
-
set.add(runId);
|
|
1514
|
-
this.childrenByParent.set(parentRunId, set);
|
|
1515
|
-
}
|
|
1516
|
-
return { started: true, canceled };
|
|
1517
|
-
}
|
|
1518
|
-
// In-memory has no real tx; we share the underlying maps with tryStartRun,
|
|
1519
|
-
// so the implementation is intentionally a straight delegate. The `tx`
|
|
1520
|
-
// parameter is accepted for shape-compat with the Store contract.
|
|
1521
|
-
async tryStartRunOnTx(_tx, runId, fact, concurrency) {
|
|
1522
|
-
return this.tryStartRun(runId, fact, concurrency);
|
|
1523
|
-
}
|
|
1524
|
-
async listChildren(parentRunId) {
|
|
1525
|
-
const set = this.childrenByParent.get(parentRunId);
|
|
1526
|
-
if (set === void 0) return [];
|
|
1527
|
-
return Array.from(set);
|
|
1528
|
-
}
|
|
1529
|
-
// Does a non-terminal child exist for this (parentRunId, stepId)? Used by the
|
|
1530
|
-
// reaper to leave a subflow step parked while its child still runs (instead
|
|
1531
|
-
// of re-dispatching it at attempt+1). childrenByParent is keyed by parent run
|
|
1532
|
-
// only, so filter on the child's parent.stepId.
|
|
1533
|
-
hasActiveChild(parentRunId, parentStepId) {
|
|
1534
|
-
const childIds = this.childrenByParent.get(parentRunId);
|
|
1535
|
-
if (childIds === void 0) return false;
|
|
1536
|
-
for (const childId of childIds) {
|
|
1537
|
-
const factList = this.facts.get(childId);
|
|
1538
|
-
if (factList === void 0) continue;
|
|
1539
|
-
const child = foldRun(childId, factList);
|
|
1540
|
-
if (child.parent?.stepId === parentStepId && !isTerminalRun(child)) {
|
|
1541
|
-
return true;
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
return false;
|
|
1545
|
-
}
|
|
1546
|
-
async loadRunState(runId) {
|
|
1547
|
-
return foldRun(runId, this.facts.get(runId) ?? []);
|
|
1548
|
-
}
|
|
1549
|
-
async claimStep(runId, stepId, attempt) {
|
|
1550
|
-
const key = `${runId}::${stepId}::${attempt}`;
|
|
1551
|
-
const now = Date.now();
|
|
1552
|
-
const existing = this.leases.get(key);
|
|
1553
|
-
if (existing && existing.expiresAt > now) {
|
|
1554
|
-
return null;
|
|
1555
|
-
}
|
|
1556
|
-
const token = `lease-${crypto.randomUUID()}`;
|
|
1557
|
-
this.leases.set(key, { token, expiresAt: now + this.leaseMs });
|
|
1558
|
-
return token;
|
|
1559
|
-
}
|
|
1560
|
-
async extendLease(runId, stepId, attempt, leaseMs) {
|
|
1561
|
-
const key = `${runId}::${stepId}::${attempt}`;
|
|
1562
|
-
const existing = this.leases.get(key);
|
|
1563
|
-
if (existing === void 0) return;
|
|
1564
|
-
this.leases.set(key, {
|
|
1565
|
-
token: existing.token,
|
|
1566
|
-
expiresAt: Date.now() + leaseMs
|
|
1567
|
-
});
|
|
1568
|
-
}
|
|
1569
|
-
async sweepLeases(args) {
|
|
1570
|
-
const { now, queue, limit = 100 } = args;
|
|
1571
|
-
const reaped = [];
|
|
1572
|
-
const candidates = [];
|
|
1573
|
-
for (const [key, lease] of this.leases) {
|
|
1574
|
-
if (candidates.length >= limit) break;
|
|
1575
|
-
const parts = key.split("::");
|
|
1576
|
-
if (parts.length !== 3) continue;
|
|
1577
|
-
const [runId, stepId, attemptStr] = parts;
|
|
1578
|
-
candidates.push({
|
|
1579
|
-
key,
|
|
1580
|
-
runId,
|
|
1581
|
-
stepId,
|
|
1582
|
-
attempt: Number(attemptStr),
|
|
1583
|
-
expiresAt: new Date(lease.expiresAt)
|
|
1584
|
-
});
|
|
1585
|
-
}
|
|
1586
|
-
for (const c of candidates) {
|
|
1587
|
-
const factList = this.facts.get(c.runId);
|
|
1588
|
-
const state = factList ? foldRun(c.runId, factList) : null;
|
|
1589
|
-
const ss = state ? stepStateOf(state, c.stepId) : null;
|
|
1590
|
-
const stepStatus = ss === null ? "pending" : stepStatusOf(ss);
|
|
1591
|
-
const decision = decideExpiredLeaseAction({
|
|
1592
|
-
lease: {
|
|
1593
|
-
runId: c.runId,
|
|
1594
|
-
stepId: c.stepId,
|
|
1595
|
-
attempt: c.attempt,
|
|
1596
|
-
expiresAt: c.expiresAt
|
|
1597
|
-
},
|
|
1598
|
-
stepStatus,
|
|
1599
|
-
childActive: this.hasActiveChild(c.runId, c.stepId),
|
|
1600
|
-
now
|
|
1601
|
-
});
|
|
1602
|
-
if (decision.tag === "skip") continue;
|
|
1603
|
-
this.leases.delete(c.key);
|
|
1604
|
-
await this.appendFact(
|
|
1605
|
-
c.runId,
|
|
1606
|
-
Facts.leaseReaped({
|
|
1607
|
-
runId: c.runId,
|
|
1608
|
-
stepId: c.stepId,
|
|
1609
|
-
attempt: c.attempt,
|
|
1610
|
-
at: now,
|
|
1611
|
-
reapedAt: now
|
|
1612
|
-
})
|
|
1613
|
-
);
|
|
1614
|
-
await queue.enqueue(c.runId, c.stepId, {
|
|
1615
|
-
attempt: decision.nextAttempt,
|
|
1616
|
-
delayMs: decision.backoffMs
|
|
1617
|
-
});
|
|
1618
|
-
reaped.push({
|
|
1619
|
-
runId: c.runId,
|
|
1620
|
-
stepId: c.stepId,
|
|
1621
|
-
attempt: c.attempt,
|
|
1622
|
-
nextAttempt: decision.nextAttempt
|
|
1623
|
-
});
|
|
1624
|
-
}
|
|
1625
|
-
return reaped;
|
|
1626
|
-
}
|
|
1627
|
-
async settleStep(runId, _stepId, fact) {
|
|
1628
|
-
await this.appendFact(runId, fact);
|
|
1629
|
-
}
|
|
1630
|
-
async settleSignal(args) {
|
|
1631
|
-
const { runId, stepId, at, incoming } = args;
|
|
1632
|
-
const runState = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1633
|
-
const decision = decideSignal({ runState, stepId, at, incoming });
|
|
1634
|
-
switch (decision.kind) {
|
|
1635
|
-
case "noop":
|
|
1636
|
-
return decision.result;
|
|
1637
|
-
case "buffer":
|
|
1638
|
-
if (decision.fact !== null) await this.appendFact(runId, decision.fact);
|
|
1639
|
-
return decision.result;
|
|
1640
|
-
case "deliver":
|
|
1641
|
-
await this.appendFact(runId, decision.received);
|
|
1642
|
-
await this.appendFact(runId, decision.completed);
|
|
1643
|
-
this.signalTimers.delete(`${runId}::${stepId}`);
|
|
1644
|
-
return decision.result;
|
|
1645
|
-
}
|
|
1646
|
-
}
|
|
1647
|
-
async upsertTimer(runId, stepId, fireAt) {
|
|
1648
|
-
const key = `${runId}::${stepId}`;
|
|
1649
|
-
if (!this.signalTimers.has(key)) this.signalTimers.set(key, fireAt);
|
|
1650
|
-
}
|
|
1651
|
-
async sweepSignalTimeouts(args) {
|
|
1652
|
-
const { now, limit = 100 } = args;
|
|
1653
|
-
const timedOut = [];
|
|
1654
|
-
const due = [];
|
|
1655
|
-
for (const [key, fireAt] of this.signalTimers) {
|
|
1656
|
-
if (due.length >= limit) break;
|
|
1657
|
-
if (fireAt > now) continue;
|
|
1658
|
-
const sep = key.indexOf("::");
|
|
1659
|
-
due.push({
|
|
1660
|
-
key,
|
|
1661
|
-
runId: key.slice(0, sep),
|
|
1662
|
-
stepId: key.slice(sep + 2)
|
|
1663
|
-
});
|
|
1664
|
-
}
|
|
1665
|
-
for (const { key, runId, stepId } of due) {
|
|
1666
|
-
const fireAt = this.signalTimers.get(key);
|
|
1667
|
-
if (fireAt === void 0) continue;
|
|
1668
|
-
const runState = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1669
|
-
const decision = decideTimeout({ runState, stepId, fireAt, at: now });
|
|
1670
|
-
this.signalTimers.delete(key);
|
|
1671
|
-
if (decision.kind === "noop") continue;
|
|
1672
|
-
await this.appendFact(runId, decision.fact);
|
|
1673
|
-
const leasePrefix = `${runId}::${stepId}::`;
|
|
1674
|
-
for (const k of this.leases.keys()) {
|
|
1675
|
-
if (k.startsWith(leasePrefix)) this.leases.delete(k);
|
|
1676
|
-
}
|
|
1677
|
-
timedOut.push({ runId, stepId, attempt: decision.attempt, fireAt });
|
|
1678
|
-
}
|
|
1679
|
-
return timedOut;
|
|
1680
|
-
}
|
|
1681
|
-
async recordOnce(runId, stepId, scope, value) {
|
|
1682
|
-
this.onces.set(`${runId}::${stepId}::${scope}`, value);
|
|
1683
|
-
}
|
|
1684
|
-
async getOnce(runId, stepId, scope) {
|
|
1685
|
-
return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
|
|
1686
|
-
}
|
|
1687
|
-
async runStep(runId, _stepId, _attempt, body) {
|
|
1688
|
-
const result = await body(void 0);
|
|
1689
|
-
await this.appendFact(runId, result.fact);
|
|
1690
|
-
return result.output;
|
|
1691
|
-
}
|
|
1692
|
-
async upsertSnapshot(args) {
|
|
1693
|
-
if (this.snapshots.has(args.flowHash)) return;
|
|
1694
|
-
this.snapshots.set(args.flowHash, { flowId: args.flowId, dag: args.dag });
|
|
1695
|
-
}
|
|
1696
|
-
async getRef(flowId) {
|
|
1697
|
-
return this.refs.get(flowId) ?? null;
|
|
1698
|
-
}
|
|
1699
|
-
async setRef(flowId, flowHash) {
|
|
1700
|
-
this.refs.set(flowId, flowHash);
|
|
1701
|
-
}
|
|
1702
|
-
async loadSnapshot(flowHash) {
|
|
1703
|
-
return this.snapshots.get(flowHash) ?? null;
|
|
1704
|
-
}
|
|
1705
|
-
async appendGlobalFact(fact) {
|
|
1706
|
-
this.globalFacts.push(fact);
|
|
1707
|
-
}
|
|
1708
|
-
readGlobalFacts() {
|
|
1709
|
-
return this.globalFacts;
|
|
1710
|
-
}
|
|
1711
|
-
async queryRuns(opts) {
|
|
1712
|
-
const where = opts.where ?? {};
|
|
1713
|
-
const wanted = where.status && new Set(where.status);
|
|
1714
|
-
const matches = (summary) => (where.flowId === void 0 || summary.flowId === where.flowId) && (!wanted || wanted.has(summary.status)) && (where.input === void 0 || containsJson(summary.input, where.input));
|
|
1715
|
-
const summaries = [];
|
|
1716
|
-
for (const [runId, factList] of this.facts) {
|
|
1717
|
-
const summary = summarize(runId, factList);
|
|
1718
|
-
if (summary === null) continue;
|
|
1719
|
-
if (matches(summary)) summaries.push(summary);
|
|
1720
|
-
}
|
|
1721
|
-
for (const summary of this.summaries.values()) {
|
|
1722
|
-
if (matches(summary)) summaries.push(summary);
|
|
1723
|
-
}
|
|
1724
|
-
summaries.sort((a, b) => {
|
|
1725
|
-
const t = b.startedAt.getTime() - a.startedAt.getTime();
|
|
1726
|
-
if (t !== 0) return t;
|
|
1727
|
-
return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
|
|
1728
|
-
});
|
|
1729
|
-
if (opts.latest === true) {
|
|
1730
|
-
return { runs: summaries.slice(0, 1), cursor: null };
|
|
1731
|
-
}
|
|
1732
|
-
const limit = clampLimit(opts.limit);
|
|
1733
|
-
let start = 0;
|
|
1734
|
-
if (opts.cursor !== void 0) {
|
|
1735
|
-
const c = decodeCursor(opts.cursor);
|
|
1736
|
-
start = summaries.findIndex(
|
|
1737
|
-
(s) => s.startedAt.getTime() < c.t || s.startedAt.getTime() === c.t && s.runId < c.r
|
|
1738
|
-
);
|
|
1739
|
-
if (start === -1) start = summaries.length;
|
|
1740
|
-
}
|
|
1741
|
-
const page = summaries.slice(start, start + limit);
|
|
1742
|
-
const hasMore = start + limit < summaries.length;
|
|
1743
|
-
const last = page[page.length - 1];
|
|
1744
|
-
const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
|
|
1745
|
-
return { runs: page, cursor };
|
|
1746
|
-
}
|
|
1747
|
-
async describe(runId) {
|
|
1748
|
-
const factList = this.facts.get(runId);
|
|
1749
|
-
if (factList === void 0 || factList.length === 0) return null;
|
|
1750
|
-
const first = factList[0];
|
|
1751
|
-
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
1752
|
-
const state = foldRun(runId, factList);
|
|
1753
|
-
const status = runStatusOf(state);
|
|
1754
|
-
let completedAt;
|
|
1755
|
-
let output;
|
|
1756
|
-
let error;
|
|
1757
|
-
let canceledByRunId;
|
|
1758
|
-
let concurrencyKey;
|
|
1759
|
-
for (let i = factList.length - 1; i >= 0; i--) {
|
|
1760
|
-
const f = factList[i];
|
|
1761
|
-
if (f === void 0) continue;
|
|
1762
|
-
if (f.kind === "flow.completed") {
|
|
1763
|
-
completedAt = f.at;
|
|
1764
|
-
output = f.output;
|
|
1765
|
-
break;
|
|
1766
|
-
}
|
|
1767
|
-
if (f.kind === "flow.failed") {
|
|
1768
|
-
completedAt = f.at;
|
|
1769
|
-
error = f.error;
|
|
1770
|
-
break;
|
|
1771
|
-
}
|
|
1772
|
-
if (f.kind === "flow.canceled") {
|
|
1773
|
-
completedAt = f.at;
|
|
1774
|
-
if (f.cause === "concurrency") {
|
|
1775
|
-
canceledByRunId = f.canceledByRunId;
|
|
1776
|
-
}
|
|
1777
|
-
break;
|
|
1778
|
-
}
|
|
1779
|
-
}
|
|
1780
|
-
const slot = this.keyByActiveRun.get(runId);
|
|
1781
|
-
if (slot !== void 0) {
|
|
1782
|
-
const sep = slot.indexOf("::");
|
|
1783
|
-
if (sep >= 0) concurrencyKey = slot.slice(sep + 2);
|
|
1784
|
-
}
|
|
1785
|
-
if (concurrencyKey === void 0) {
|
|
1786
|
-
for (const f of factList) {
|
|
1787
|
-
if (f.kind === "flow.canceled" && f.cause === "concurrency") {
|
|
1788
|
-
concurrencyKey = f.concurrencyKey;
|
|
1789
|
-
break;
|
|
1790
|
-
}
|
|
1791
|
-
}
|
|
1792
|
-
}
|
|
1793
|
-
const childSet = this.childrenByParent.get(runId);
|
|
1794
|
-
const children = childSet ? Array.from(childSet) : [];
|
|
1795
|
-
const parent = first.parent;
|
|
1796
|
-
const run = {
|
|
1797
|
-
runId,
|
|
1798
|
-
flowId: first.flowId,
|
|
1799
|
-
flowHash: first.flowHash ?? "",
|
|
1800
|
-
status,
|
|
1801
|
-
startedAt: first.at,
|
|
1802
|
-
input: first.input,
|
|
1803
|
-
children,
|
|
1804
|
-
...completedAt !== void 0 ? { completedAt } : {},
|
|
1805
|
-
...output !== void 0 ? { output } : {},
|
|
1806
|
-
...error !== void 0 ? { error } : {},
|
|
1807
|
-
...canceledByRunId !== void 0 ? { canceledByRunId } : {},
|
|
1808
|
-
...concurrencyKey !== void 0 ? { concurrencyKey } : {},
|
|
1809
|
-
...parent !== void 0 ? { parent } : {}
|
|
1810
|
-
};
|
|
1811
|
-
const steps = [];
|
|
1812
|
-
const startedAtByStep = /* @__PURE__ */ new Map();
|
|
1813
|
-
const completedAtByStep = /* @__PURE__ */ new Map();
|
|
1814
|
-
for (const f of factList) {
|
|
1815
|
-
if (f.kind === "step.started" && !startedAtByStep.has(f.stepId)) {
|
|
1816
|
-
startedAtByStep.set(f.stepId, f.at);
|
|
1817
|
-
}
|
|
1818
|
-
if ((f.kind === "step.completed" || f.kind === "step.failed" || f.kind === "step.canceled" || f.kind === "step.skipped") && !completedAtByStep.has(f.stepId)) {
|
|
1819
|
-
completedAtByStep.set(f.stepId, f.at);
|
|
1820
|
-
}
|
|
1821
|
-
}
|
|
1822
|
-
const now = Date.now();
|
|
1823
|
-
for (const [stepId, stepState] of Object.entries(state.steps)) {
|
|
1824
|
-
const status2 = stepStatusOf(stepState);
|
|
1825
|
-
const attempt = attemptOf(stepState);
|
|
1826
|
-
const out = outputOf(stepState);
|
|
1827
|
-
const err = errorOf(stepState);
|
|
1828
|
-
const startedAt = startedAtByStep.get(stepId);
|
|
1829
|
-
const completedAt2 = completedAtByStep.get(stepId);
|
|
1830
|
-
let lease;
|
|
1831
|
-
const leasePrefix = `${runId}::${stepId}::`;
|
|
1832
|
-
let bestExpiry = 0;
|
|
1833
|
-
for (const [key, l] of this.leases) {
|
|
1834
|
-
if (!key.startsWith(leasePrefix)) continue;
|
|
1835
|
-
if (l.expiresAt > now && l.expiresAt > bestExpiry)
|
|
1836
|
-
bestExpiry = l.expiresAt;
|
|
1837
|
-
}
|
|
1838
|
-
if (bestExpiry > 0) lease = { expiresAt: new Date(bestExpiry) };
|
|
1839
|
-
steps.push({
|
|
1840
|
-
stepId,
|
|
1841
|
-
attempt,
|
|
1842
|
-
status: status2,
|
|
1843
|
-
...startedAt !== void 0 ? { startedAt } : {},
|
|
1844
|
-
...completedAt2 !== void 0 ? { completedAt: completedAt2 } : {},
|
|
1845
|
-
...out !== null ? { output: out } : {},
|
|
1846
|
-
...err !== void 0 ? { error: err } : {},
|
|
1847
|
-
...lease !== void 0 ? { lease } : {}
|
|
1848
|
-
});
|
|
1849
|
-
}
|
|
1850
|
-
steps.sort((a, b) => {
|
|
1851
|
-
const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
1852
|
-
const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
1853
|
-
if (ta !== tb) return ta - tb;
|
|
1854
|
-
return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
|
|
1855
|
-
});
|
|
1856
|
-
return { run, steps };
|
|
1857
|
-
}
|
|
1858
|
-
async pruneFacts(opts) {
|
|
1859
|
-
const olderThanMs = opts.olderThan.getTime();
|
|
1860
|
-
const statusSet = new Set(opts.statuses);
|
|
1861
|
-
const victims = [];
|
|
1862
|
-
for (const [runId, factList] of this.facts) {
|
|
1863
|
-
const summary = summarize(runId, factList);
|
|
1864
|
-
if (summary === null) continue;
|
|
1865
|
-
if (summary.completedAt === null) continue;
|
|
1866
|
-
if (!statusSet.has(summary.status)) continue;
|
|
1867
|
-
if (summary.completedAt.getTime() >= olderThanMs) continue;
|
|
1868
|
-
const first = factList[0];
|
|
1869
|
-
const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parent?.runId : void 0;
|
|
1870
|
-
victims.push({
|
|
1871
|
-
runId,
|
|
1872
|
-
summary,
|
|
1873
|
-
factCount: factList.length,
|
|
1874
|
-
parentRunId
|
|
1875
|
-
});
|
|
1876
|
-
}
|
|
1877
|
-
let runsPruned = 0;
|
|
1878
|
-
let factsPruned = 0;
|
|
1879
|
-
for (const v of victims) {
|
|
1880
|
-
this.facts.delete(v.runId);
|
|
1881
|
-
deleteByRunPrefix(this.onces, v.runId);
|
|
1882
|
-
deleteByRunPrefix(this.leases, v.runId);
|
|
1883
|
-
this.childrenByParent.delete(v.runId);
|
|
1884
|
-
if (v.parentRunId !== void 0) {
|
|
1885
|
-
const siblings = this.childrenByParent.get(v.parentRunId);
|
|
1886
|
-
if (siblings !== void 0) {
|
|
1887
|
-
siblings.delete(v.runId);
|
|
1888
|
-
if (siblings.size === 0) this.childrenByParent.delete(v.parentRunId);
|
|
1889
|
-
}
|
|
1890
|
-
}
|
|
1891
|
-
if (opts.keepSummary) {
|
|
1892
|
-
this.summaries.set(v.runId, v.summary);
|
|
1893
|
-
} else {
|
|
1894
|
-
this.summaries.delete(v.runId);
|
|
1895
|
-
}
|
|
1896
|
-
runsPruned += 1;
|
|
1897
|
-
factsPruned += v.factCount;
|
|
1898
|
-
}
|
|
1899
|
-
return { runsPruned, factsPruned };
|
|
1900
|
-
}
|
|
1901
|
-
subscribeStream(runId, stepId, opts) {
|
|
1902
|
-
const state = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1903
|
-
const stepStatus = stepStatusOf(stepStateOf(state, stepId));
|
|
1904
|
-
const runIsTerminal = isTerminalRun(state);
|
|
1905
|
-
if (runIsTerminal || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
|
|
1906
|
-
return EMPTY_CLOSED_STREAM;
|
|
1907
|
-
}
|
|
1908
|
-
return this.streamHub.subscribeStream(runId, stepId, opts);
|
|
1909
|
-
}
|
|
1910
|
-
publishChunk(runId, stepId, chunk) {
|
|
1911
|
-
this.streamHub.publishChunk(runId, stepId, chunk);
|
|
1912
|
-
}
|
|
1913
|
-
};
|
|
1914
|
-
var EMPTY_CLOSED_STREAM = {
|
|
1915
|
-
[Symbol.asyncIterator]() {
|
|
1916
|
-
return { next: async () => ({ value: void 0, done: true }) };
|
|
1917
|
-
}
|
|
1918
|
-
};
|
|
1919
|
-
function deleteByRunPrefix(map, runId) {
|
|
1920
|
-
const prefix = `${runId}::`;
|
|
1921
|
-
for (const key of map.keys()) {
|
|
1922
|
-
if (key.startsWith(prefix)) map.delete(key);
|
|
1923
|
-
}
|
|
1924
|
-
}
|
|
1925
|
-
function summarize(runId, facts) {
|
|
1926
|
-
const first = facts[0];
|
|
1927
|
-
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
1928
|
-
const projected = foldRun(runId, facts);
|
|
1929
|
-
let completedAt = null;
|
|
1930
|
-
for (let i = facts.length - 1; i >= 0; i--) {
|
|
1931
|
-
const f = facts[i];
|
|
1932
|
-
if (f === void 0) continue;
|
|
1933
|
-
if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
|
|
1934
|
-
completedAt = f.at;
|
|
1935
|
-
break;
|
|
1936
|
-
}
|
|
1937
|
-
}
|
|
1938
|
-
return {
|
|
1939
|
-
runId,
|
|
1940
|
-
flowId: first.flowId,
|
|
1941
|
-
status: runStatusOf(projected),
|
|
1942
|
-
startedAt: first.at,
|
|
1943
|
-
completedAt,
|
|
1944
|
-
input: first.input
|
|
1945
|
-
};
|
|
1946
|
-
}
|
|
1947
|
-
var DEFAULT_LIMIT = 50;
|
|
1948
|
-
var MAX_LIMIT = 500;
|
|
1949
|
-
function clampLimit(limit) {
|
|
1950
|
-
if (limit === void 0) return DEFAULT_LIMIT;
|
|
1951
|
-
if (!Number.isInteger(limit) || limit < 1) return DEFAULT_LIMIT;
|
|
1952
|
-
return Math.min(limit, MAX_LIMIT);
|
|
1953
|
-
}
|
|
1954
|
-
function encodeCursor(c) {
|
|
1955
|
-
const bytes = new TextEncoder().encode(JSON.stringify(c));
|
|
1956
|
-
let binary = "";
|
|
1957
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
1958
|
-
binary += String.fromCharCode(bytes[i]);
|
|
1959
|
-
}
|
|
1960
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1961
|
-
}
|
|
1962
|
-
function decodeCursor(s) {
|
|
1963
|
-
try {
|
|
1964
|
-
const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
1965
|
-
const binary = atob(b64);
|
|
1966
|
-
const bytes = new Uint8Array(binary.length);
|
|
1967
|
-
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1968
|
-
const parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
1969
|
-
if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
|
|
1970
|
-
return parsed;
|
|
1971
|
-
}
|
|
1972
|
-
throw new Error("malformed cursor body");
|
|
1973
|
-
} catch (err) {
|
|
1974
|
-
throw new Error(
|
|
1975
|
-
`queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
|
|
1976
|
-
);
|
|
1977
|
-
}
|
|
1978
|
-
}
|
|
1979
|
-
function containsJson(haystack, needle) {
|
|
1980
|
-
if (Array.isArray(needle)) {
|
|
1981
|
-
if (!Array.isArray(haystack)) return false;
|
|
1982
|
-
return needle.every((n) => haystack.some((h) => containsJson(h, n)));
|
|
1983
|
-
}
|
|
1984
|
-
if (needle !== null && typeof needle === "object") {
|
|
1985
|
-
if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
|
|
1986
|
-
return false;
|
|
1987
|
-
return Object.entries(needle).every(
|
|
1988
|
-
([k, v]) => k in haystack && containsJson(haystack[k], v)
|
|
1989
|
-
);
|
|
1990
|
-
}
|
|
1991
|
-
return haystack === needle;
|
|
1992
|
-
}
|
|
1993
|
-
var DEFAULT_QUEUE_LEASE_MS = 6e4;
|
|
1994
|
-
var InMemoryQueue = class {
|
|
1995
|
-
pending = [];
|
|
1996
|
-
leased = /* @__PURE__ */ new Map();
|
|
1997
|
-
leaseMs;
|
|
1998
|
-
constructor(opts = {}) {
|
|
1999
|
-
this.leaseMs = opts.leaseMs ?? DEFAULT_QUEUE_LEASE_MS;
|
|
2000
|
-
}
|
|
2001
|
-
async enqueue(runId, stepId, opts) {
|
|
2002
|
-
const now = Date.now();
|
|
2003
|
-
const item = {
|
|
2004
|
-
receipt: crypto.randomUUID(),
|
|
2005
|
-
runId,
|
|
2006
|
-
stepId,
|
|
2007
|
-
payload: opts?.payload ?? null,
|
|
2008
|
-
attempt: opts?.attempt ?? 1,
|
|
2009
|
-
enqueuedAt: now,
|
|
2010
|
-
visibleAt: now + (opts?.delayMs ?? 0)
|
|
2011
|
-
};
|
|
2012
|
-
this.pending.push(item);
|
|
2013
|
-
}
|
|
2014
|
-
async dequeue(opts) {
|
|
2015
|
-
const now = Date.now();
|
|
2016
|
-
const claimed = [];
|
|
2017
|
-
for (let i = 0; i < this.pending.length && claimed.length < opts.count; i++) {
|
|
2018
|
-
const item = this.pending[i];
|
|
2019
|
-
if (item === void 0) continue;
|
|
2020
|
-
if (item.visibleAt > now) continue;
|
|
2021
|
-
const next = { ...item, visibleAt: now + this.leaseMs };
|
|
2022
|
-
this.pending.splice(i, 1);
|
|
2023
|
-
i--;
|
|
2024
|
-
this.leased.set(item.receipt, next);
|
|
2025
|
-
claimed.push(item);
|
|
2026
|
-
}
|
|
2027
|
-
return claimed;
|
|
2028
|
-
}
|
|
2029
|
-
async ack(receipt) {
|
|
2030
|
-
this.leased.delete(receipt);
|
|
2031
|
-
}
|
|
2032
|
-
async nack(receipt, opts) {
|
|
2033
|
-
const item = this.leased.get(receipt);
|
|
2034
|
-
if (!item) return;
|
|
2035
|
-
this.leased.delete(receipt);
|
|
2036
|
-
const requeued = {
|
|
2037
|
-
...item,
|
|
2038
|
-
visibleAt: Date.now() + (opts?.delayMs ?? 0)
|
|
2039
|
-
};
|
|
2040
|
-
this.pending.push(requeued);
|
|
2041
|
-
}
|
|
2042
|
-
async extend(receipt, leaseMs) {
|
|
2043
|
-
const item = this.leased.get(receipt);
|
|
2044
|
-
if (!item) return;
|
|
2045
|
-
this.leased.set(receipt, { ...item, visibleAt: Date.now() + leaseMs });
|
|
2046
|
-
}
|
|
2047
|
-
};
|
|
2048
|
-
var InMemoryClock = class {
|
|
2049
|
-
timers = /* @__PURE__ */ new Map();
|
|
2050
|
-
trigger;
|
|
2051
|
-
constructor(opts = {}) {
|
|
2052
|
-
this.trigger = opts.trigger;
|
|
2053
|
-
}
|
|
2054
|
-
now() {
|
|
2055
|
-
return /* @__PURE__ */ new Date();
|
|
2056
|
-
}
|
|
2057
|
-
async sleep(ms, signal) {
|
|
2058
|
-
if (signal?.aborted) {
|
|
2059
|
-
throw signal.reason ?? new Error("aborted");
|
|
2060
|
-
}
|
|
2061
|
-
return new Promise((resolve, reject) => {
|
|
2062
|
-
const timer = setTimeout(() => {
|
|
2063
|
-
signal?.removeEventListener("abort", onAbort);
|
|
2064
|
-
resolve();
|
|
2065
|
-
}, ms);
|
|
2066
|
-
const onAbort = () => {
|
|
2067
|
-
clearTimeout(timer);
|
|
2068
|
-
reject(signal?.reason ?? new Error("aborted"));
|
|
2069
|
-
};
|
|
2070
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2071
|
-
});
|
|
2072
|
-
}
|
|
2073
|
-
async schedule(at, runId, stepId) {
|
|
2074
|
-
const key = `${runId}::${stepId}`;
|
|
2075
|
-
const existing = this.timers.get(key);
|
|
2076
|
-
if (existing !== void 0) clearTimeout(existing);
|
|
2077
|
-
const delay = Math.max(0, at.getTime() - Date.now());
|
|
2078
|
-
const handle = setTimeout(() => {
|
|
2079
|
-
this.timers.delete(key);
|
|
2080
|
-
this.trigger?.fire(runId);
|
|
2081
|
-
}, delay);
|
|
2082
|
-
this.timers.set(key, handle);
|
|
2083
|
-
}
|
|
2084
|
-
dispose() {
|
|
2085
|
-
for (const t of this.timers.values()) clearTimeout(t);
|
|
2086
|
-
this.timers.clear();
|
|
2087
|
-
}
|
|
2088
|
-
};
|
|
2089
|
-
var InMemoryTrigger = class {
|
|
2090
|
-
handlers = [];
|
|
2091
|
-
subscribe(handler) {
|
|
2092
|
-
this.handlers.push(handler);
|
|
2093
|
-
return () => {
|
|
2094
|
-
this.handlers = this.handlers.filter((h) => h !== handler);
|
|
2095
|
-
};
|
|
2096
|
-
}
|
|
2097
|
-
fire(runId) {
|
|
2098
|
-
for (const h of this.handlers) h(runId);
|
|
2099
|
-
}
|
|
2100
|
-
};
|
|
2101
|
-
|
|
2102
|
-
// src/run-id.ts
|
|
2103
|
-
var RunId = {
|
|
2104
|
-
parse(s) {
|
|
2105
|
-
if (typeof s !== "string" || s.length === 0) {
|
|
2106
|
-
throw validationError("RunId.parse: must be a non-empty string", [
|
|
2107
|
-
"runId"
|
|
2108
|
-
]);
|
|
2109
|
-
}
|
|
2110
|
-
if (/\s/.test(s)) {
|
|
2111
|
-
throw validationError("RunId.parse: must not contain whitespace", [
|
|
2112
|
-
"runId"
|
|
2113
|
-
]);
|
|
2114
|
-
}
|
|
2115
|
-
return s;
|
|
2116
|
-
},
|
|
2117
|
-
fromTrusted(s) {
|
|
2118
|
-
return s;
|
|
2119
|
-
}
|
|
2120
|
-
};
|
|
2121
|
-
async function deriveChildRunId(key) {
|
|
2122
|
-
const seed = `nagi:subflow:${key.runId}:${key.stepId}:gen${key.generation}`;
|
|
2123
|
-
const digest = await crypto.subtle.digest(
|
|
2124
|
-
"SHA-256",
|
|
2125
|
-
new TextEncoder().encode(seed)
|
|
2126
|
-
);
|
|
2127
|
-
const bytes = new Uint8Array(digest).subarray(0, 16);
|
|
2128
|
-
bytes[6] = (bytes[6] ?? 0) & 15 | 80;
|
|
2129
|
-
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
2130
|
-
const hex2 = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
|
|
2131
|
-
""
|
|
2132
|
-
);
|
|
2133
|
-
const uuid = `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20, 32)}`;
|
|
2134
|
-
return `run-${uuid}`;
|
|
2135
|
-
}
|
|
2136
|
-
|
|
2137
|
-
// src/exec/hooks.ts
|
|
2138
|
-
function makeHooks(deps) {
|
|
2139
|
-
async function fireHook(hook, event, hookName) {
|
|
2140
|
-
if (deps.fireHooks === false) return;
|
|
2141
|
-
if (hook === void 0) return;
|
|
2142
|
-
try {
|
|
2143
|
-
await hook(event);
|
|
2144
|
-
} catch (err) {
|
|
2145
|
-
const { message, stack } = serializeError(err);
|
|
2146
|
-
deps.emitLog({
|
|
2147
|
-
level: "error",
|
|
2148
|
-
msg: `nagi hook "${hookName}" threw \u2014 swallowed`,
|
|
2149
|
-
attrs: { error: message, ...stack !== void 0 ? { stack } : {} }
|
|
2150
|
-
});
|
|
2151
|
-
}
|
|
2152
|
-
}
|
|
2153
|
-
async function fireStepLifecycle(stepHook, flowHook, [stepName, flowName], event) {
|
|
2154
|
-
await fireHook(stepHook, event, stepName);
|
|
2155
|
-
await fireHook(flowHook, event, flowName);
|
|
2156
|
-
}
|
|
2157
|
-
return { fireHook, fireStepLifecycle };
|
|
2158
|
-
}
|
|
2159
|
-
|
|
2160
|
-
// src/scheduler.ts
|
|
2161
|
-
function nextRunnable({
|
|
2162
|
-
flow: flow2,
|
|
2163
|
-
runState,
|
|
2164
|
-
input
|
|
2165
|
-
}) {
|
|
2166
|
-
const runnable = [];
|
|
2167
|
-
const skip = [];
|
|
2168
|
-
for (const [stepId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
2169
|
-
if (stepStateOf(runState, stepId).tag !== "pending") continue;
|
|
2170
|
-
const gate = gateStep(getDef(step), runState, input);
|
|
2171
|
-
switch (gate.kind) {
|
|
2172
|
-
case "run":
|
|
2173
|
-
runnable.push(stepId);
|
|
2174
|
-
break;
|
|
2175
|
-
case "skip":
|
|
2176
|
-
skip.push({ stepId, reason: gate.reason });
|
|
2177
|
-
break;
|
|
2178
|
-
}
|
|
2179
|
-
}
|
|
2180
|
-
return { runnable, skip };
|
|
2181
|
-
}
|
|
2182
|
-
function gateStep(def, runState, input) {
|
|
2183
|
-
const parent = checkParentMatch(def, runState);
|
|
2184
|
-
if (parent !== "ready") return gateFor(parent);
|
|
2185
|
-
const upstream = checkUpstream(def, runState);
|
|
2186
|
-
if (upstream !== "ready") return gateFor(upstream);
|
|
2187
|
-
const when = def.kind === "match" ? void 0 : def.when;
|
|
2188
|
-
if (when) {
|
|
2189
|
-
const needs = resolveNeeds(
|
|
2190
|
-
def,
|
|
2191
|
-
(id) => resolvedOf(stepStateOf(runState, id))
|
|
2192
|
-
);
|
|
2193
|
-
if (!when({ input, needs })) return { kind: "skip", reason: "when-false" };
|
|
2194
|
-
}
|
|
2195
|
-
return { kind: "run" };
|
|
2196
|
-
}
|
|
2197
|
-
function gateFor(status) {
|
|
2198
|
-
switch (status) {
|
|
2199
|
-
case "blocked":
|
|
2200
|
-
return { kind: "block" };
|
|
2201
|
-
case "transitive-skip":
|
|
2202
|
-
return { kind: "skip", reason: "transitive" };
|
|
2203
|
-
}
|
|
2204
|
-
}
|
|
2205
|
-
function checkUpstream(def, runState) {
|
|
2206
|
-
for (const ref of Object.values(def.needs)) {
|
|
2207
|
-
const upstreamState = stepStateOf(runState, ref.step.id);
|
|
2208
|
-
if (upstreamState.tag === "completed") continue;
|
|
2209
|
-
if (ref.optional && upstreamState.tag === "skipped") continue;
|
|
2210
|
-
if (upstreamState.tag === "skipped" || upstreamState.tag === "failed") {
|
|
2211
|
-
return "transitive-skip";
|
|
2212
|
-
}
|
|
2213
|
-
return "blocked";
|
|
2214
|
-
}
|
|
2215
|
-
return "ready";
|
|
2216
|
-
}
|
|
2217
|
-
function checkParentMatch(def, runState) {
|
|
2218
|
-
if (!def.parentMatch) return "ready";
|
|
2219
|
-
const { matchId, armId } = def.parentMatch;
|
|
2220
|
-
const parentState = stepStateOf(runState, matchId);
|
|
2221
|
-
if (parentState.tag === "failed" || parentState.tag === "skipped") {
|
|
2222
|
-
return "transitive-skip";
|
|
2223
|
-
}
|
|
2224
|
-
const selected = runState.selectedArms[matchId] ?? null;
|
|
2225
|
-
if (selected === null) return "blocked";
|
|
2226
|
-
return selected === armId ? "ready" : "transitive-skip";
|
|
616
|
+
const selected = runState.selectedArms[matchId] ?? null;
|
|
617
|
+
if (selected === null) return "blocked";
|
|
618
|
+
return selected === armId ? "ready" : "transitive-skip";
|
|
2227
619
|
}
|
|
2228
620
|
function aggregateMatch(matchId, flow2, runState) {
|
|
2229
621
|
const step = asStepMapWithDefs(flow2.steps)[matchId];
|
|
@@ -2364,12 +756,6 @@ function makeOnce({
|
|
|
2364
756
|
}
|
|
2365
757
|
|
|
2366
758
|
// src/step-exec.ts
|
|
2367
|
-
var DEFAULT_RETRY2 = {
|
|
2368
|
-
maxAttempts: 3,
|
|
2369
|
-
backoff: "exponential",
|
|
2370
|
-
initialDelayMs: 1e3,
|
|
2371
|
-
maxDelayMs: 6e4
|
|
2372
|
-
};
|
|
2373
759
|
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
2374
760
|
var NagiAbortError = class extends Error {
|
|
2375
761
|
runId;
|
|
@@ -2431,6 +817,7 @@ function startCancelWatcher(args) {
|
|
|
2431
817
|
}
|
|
2432
818
|
var DEFAULT_HEARTBEAT_LEASE_MS = 12e4;
|
|
2433
819
|
var DEFAULT_HEARTBEAT_INTERVAL_MS = 4e4;
|
|
820
|
+
var DEFAULT_LEASE_HOLD_WARN_MS = 3e5;
|
|
2434
821
|
function startHeartbeat(args) {
|
|
2435
822
|
const {
|
|
2436
823
|
queue,
|
|
@@ -2441,13 +828,28 @@ function startHeartbeat(args) {
|
|
|
2441
828
|
receipt,
|
|
2442
829
|
intervalMs,
|
|
2443
830
|
leaseMs,
|
|
831
|
+
holdWarnMs,
|
|
2444
832
|
emitLog
|
|
2445
833
|
} = args;
|
|
2446
834
|
let stopped = false;
|
|
2447
835
|
let timer;
|
|
836
|
+
const startedAtMs = Date.now();
|
|
837
|
+
let warnedCrossings = 0;
|
|
2448
838
|
const schedule = () => {
|
|
2449
839
|
timer = setTimeout(() => {
|
|
2450
840
|
void (async () => {
|
|
841
|
+
if (holdWarnMs > 0) {
|
|
842
|
+
const heldMs = Date.now() - startedAtMs;
|
|
843
|
+
const crossings = Math.floor(heldMs / holdWarnMs);
|
|
844
|
+
if (crossings > warnedCrossings) {
|
|
845
|
+
warnedCrossings = crossings;
|
|
846
|
+
emitLog({
|
|
847
|
+
level: "warn",
|
|
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
|
+
}
|
|
2451
853
|
await Promise.all([
|
|
2452
854
|
queue.extend(receipt, leaseMs).catch((err) => {
|
|
2453
855
|
emitLog({
|
|
@@ -2489,7 +891,7 @@ function classifyFailure(args) {
|
|
|
2489
891
|
includeError: isAbort
|
|
2490
892
|
};
|
|
2491
893
|
}
|
|
2492
|
-
const cancel =
|
|
894
|
+
const cancel = findInCauseChain(err, NagiCanceledError);
|
|
2493
895
|
if (cancel !== void 0) {
|
|
2494
896
|
return {
|
|
2495
897
|
tag: "flowCanceled",
|
|
@@ -2497,33 +899,24 @@ function classifyFailure(args) {
|
|
|
2497
899
|
concurrencyKey: cancel.concurrencyKey
|
|
2498
900
|
};
|
|
2499
901
|
}
|
|
902
|
+
if (findInCauseChain(err, NagiNonRetryableError) !== void 0) {
|
|
903
|
+
return { tag: "failed" };
|
|
904
|
+
}
|
|
2500
905
|
if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
|
|
2501
|
-
return { tag: "retry", delayMs:
|
|
906
|
+
return { tag: "retry", delayMs: stepBackoff(policy)(attempt) };
|
|
2502
907
|
}
|
|
2503
908
|
return { tag: "failed" };
|
|
2504
909
|
}
|
|
2505
|
-
function
|
|
910
|
+
function findInCauseChain(err, ctor) {
|
|
2506
911
|
let cursor = err;
|
|
2507
912
|
const seen = /* @__PURE__ */ new Set();
|
|
2508
913
|
while (cursor instanceof Error && !seen.has(cursor)) {
|
|
2509
|
-
if (cursor instanceof
|
|
914
|
+
if (cursor instanceof ctor) return cursor;
|
|
2510
915
|
seen.add(cursor);
|
|
2511
916
|
cursor = cursor.cause;
|
|
2512
917
|
}
|
|
2513
918
|
return void 0;
|
|
2514
919
|
}
|
|
2515
|
-
function computeBackoff(policy, attempt) {
|
|
2516
|
-
const initial = policy.initialDelayMs ?? 1e3;
|
|
2517
|
-
const max = policy.maxDelayMs ?? 6e4;
|
|
2518
|
-
switch (policy.backoff) {
|
|
2519
|
-
case "exponential":
|
|
2520
|
-
return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
|
|
2521
|
-
case "linear":
|
|
2522
|
-
return Math.min(initial * Math.max(1, attempt), max);
|
|
2523
|
-
case "fixed":
|
|
2524
|
-
return Math.min(initial, max);
|
|
2525
|
-
}
|
|
2526
|
-
}
|
|
2527
920
|
function retryAllows(policy, err) {
|
|
2528
921
|
if (!policy.retryOn) return true;
|
|
2529
922
|
return policy.retryOn(err);
|
|
@@ -2577,11 +970,30 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2577
970
|
const { advance } = progression;
|
|
2578
971
|
async function dispatchMessage(message) {
|
|
2579
972
|
const { queue } = deps;
|
|
2580
|
-
const
|
|
973
|
+
const resolution = await deps.resolveFlow(message.runId);
|
|
974
|
+
let flow2;
|
|
975
|
+
switch (resolution.kind) {
|
|
976
|
+
case "current":
|
|
977
|
+
flow2 = resolution.flow;
|
|
978
|
+
break;
|
|
979
|
+
// A terminal run's message must not outlive it: a run canceled AFTER
|
|
980
|
+
// its snapshot went gone would otherwise nack-loop forever, since the
|
|
981
|
+
// hash check fires before admit()'s canceled-phase check ever runs.
|
|
982
|
+
case "gone-terminal":
|
|
983
|
+
await queue.ack(message.receipt);
|
|
984
|
+
return { kind: "done" };
|
|
985
|
+
case "gone-live":
|
|
986
|
+
return { kind: "snapshot-gone", error: resolution.error };
|
|
987
|
+
}
|
|
2581
988
|
const admission = await admit({ flow: flow2, message });
|
|
2582
989
|
if (admission.tag === "skip") {
|
|
2583
990
|
await queue.ack(message.receipt);
|
|
2584
|
-
return;
|
|
991
|
+
return { kind: "done" };
|
|
992
|
+
}
|
|
993
|
+
if (admission.tag === "recover") {
|
|
994
|
+
await advance(message.runId);
|
|
995
|
+
await queue.ack(message.receipt);
|
|
996
|
+
return { kind: "done" };
|
|
2585
997
|
}
|
|
2586
998
|
const { def, state } = admission;
|
|
2587
999
|
await recordStarted({ flow: flow2, message, def, state });
|
|
@@ -2595,6 +1007,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2595
1007
|
receipt: message.receipt,
|
|
2596
1008
|
intervalMs: deps.heartbeat.intervalMs,
|
|
2597
1009
|
leaseMs: deps.heartbeat.leaseMs,
|
|
1010
|
+
holdWarnMs: deps.heartbeat.holdWarnMs,
|
|
2598
1011
|
emitLog: deps.emitLog
|
|
2599
1012
|
});
|
|
2600
1013
|
let outcome;
|
|
@@ -2605,8 +1018,9 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2605
1018
|
} finally {
|
|
2606
1019
|
heartbeat.stop();
|
|
2607
1020
|
}
|
|
2608
|
-
await queue.ack(message.receipt);
|
|
2609
1021
|
await interpret({ flow: flow2, message, def, startedAt, outcome });
|
|
1022
|
+
await queue.ack(message.receipt);
|
|
1023
|
+
return { kind: "done" };
|
|
2610
1024
|
}
|
|
2611
1025
|
async function admit(args) {
|
|
2612
1026
|
const { flow: flow2, message } = args;
|
|
@@ -2624,7 +1038,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2624
1038
|
if (preState.phase.tag === "canceled") return { tag: "skip" };
|
|
2625
1039
|
const preStep = stepStateOf(preState, stepId);
|
|
2626
1040
|
if (preStep.tag === "completed" || preStep.tag === "failed" || preStep.tag === "skipped") {
|
|
2627
|
-
return { tag: "skip" };
|
|
1041
|
+
return isTerminalRun(preState) ? { tag: "skip" } : { tag: "recover" };
|
|
2628
1042
|
}
|
|
2629
1043
|
const claim = await store.claimStep(runId, stepId, attempt);
|
|
2630
1044
|
if (claim === null) return { tag: "skip" };
|
|
@@ -2640,7 +1054,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2640
1054
|
runId,
|
|
2641
1055
|
Facts.stepStarted(runId, stepId, attempt, def.kind, startedAt)
|
|
2642
1056
|
);
|
|
2643
|
-
if (def.kind === "signal" && def.timeoutMs
|
|
1057
|
+
if (def.kind === "signal" && typeof def.timeoutMs === "number") {
|
|
2644
1058
|
await store.upsertTimer(
|
|
2645
1059
|
runId,
|
|
2646
1060
|
stepId,
|
|
@@ -2923,7 +1337,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2923
1337
|
const error = serializeError(err);
|
|
2924
1338
|
const handler = handlerDef(def);
|
|
2925
1339
|
const postState = await store.loadRunState(runId);
|
|
2926
|
-
const policy = handler?.retry
|
|
1340
|
+
const policy = resolveRetry(handler?.retry, deps.defaultRetry);
|
|
2927
1341
|
const outcome = classifyFailure({
|
|
2928
1342
|
attempt,
|
|
2929
1343
|
policy,
|
|
@@ -2961,7 +1375,8 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2961
1375
|
);
|
|
2962
1376
|
await queue.enqueue(runId, stepId, {
|
|
2963
1377
|
attempt: attempt + 1,
|
|
2964
|
-
delayMs: outcome.delayMs
|
|
1378
|
+
delayMs: outcome.delayMs,
|
|
1379
|
+
flowId: flow2.id
|
|
2965
1380
|
});
|
|
2966
1381
|
return { tag: "parked" };
|
|
2967
1382
|
}
|
|
@@ -2995,11 +1410,163 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2995
1410
|
concurrencyKey: outcome.concurrencyKey
|
|
2996
1411
|
})
|
|
2997
1412
|
);
|
|
2998
|
-
return { tag: "parked" };
|
|
1413
|
+
return { tag: "parked" };
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
return { dispatchMessage };
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
// src/flows.ts
|
|
1421
|
+
function requireCurrent(resolution) {
|
|
1422
|
+
if (resolution.kind === "current") return resolution.flow;
|
|
1423
|
+
throw resolution.error;
|
|
1424
|
+
}
|
|
1425
|
+
async function registerFlows(deps) {
|
|
1426
|
+
const { flows, store, clock } = deps;
|
|
1427
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1428
|
+
const hashById = /* @__PURE__ */ new Map();
|
|
1429
|
+
const streamingStepIds = /* @__PURE__ */ new Set();
|
|
1430
|
+
for (const flow2 of flows) {
|
|
1431
|
+
if (byId.has(flow2.id)) {
|
|
1432
|
+
throw new NagiRuntimeError(
|
|
1433
|
+
`Duplicate flow id "${flow2.id}" passed to nagi()`
|
|
1434
|
+
);
|
|
1435
|
+
}
|
|
1436
|
+
byId.set(flow2.id, flow2);
|
|
1437
|
+
for (const [stepId, step] of Object.entries(
|
|
1438
|
+
asStepMapWithDefs(flow2.steps)
|
|
1439
|
+
)) {
|
|
1440
|
+
if (getDef(step).kind === "streaming") streamingStepIds.add(stepId);
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
for (const flow2 of flows) {
|
|
1444
|
+
const dag = await canonicalize(flow2);
|
|
1445
|
+
const flowHash = await sha256Canonical(dag);
|
|
1446
|
+
hashById.set(flow2.id, flowHash);
|
|
1447
|
+
await store.upsertSnapshot({
|
|
1448
|
+
flowHash,
|
|
1449
|
+
flowId: flow2.id,
|
|
1450
|
+
dag
|
|
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
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
function require2(flowId) {
|
|
1466
|
+
const flow2 = byId.get(flowId);
|
|
1467
|
+
if (!flow2) {
|
|
1468
|
+
throw new NagiRuntimeError(
|
|
1469
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
1470
|
+
);
|
|
1471
|
+
}
|
|
1472
|
+
return flow2;
|
|
1473
|
+
}
|
|
1474
|
+
function hashOf(flowId) {
|
|
1475
|
+
const hash = hashById.get(flowId);
|
|
1476
|
+
if (hash === void 0) {
|
|
1477
|
+
throw new NagiRuntimeError(
|
|
1478
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
1479
|
+
);
|
|
1480
|
+
}
|
|
1481
|
+
return hash;
|
|
1482
|
+
}
|
|
1483
|
+
function resolve(state) {
|
|
1484
|
+
const { runId, flowId, flowHash: pinnedHash } = state;
|
|
1485
|
+
const live = byId.get(flowId);
|
|
1486
|
+
if (pinnedHash === void 0) {
|
|
1487
|
+
if (live === void 0) {
|
|
1488
|
+
throw new NagiRuntimeError(
|
|
1489
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
1490
|
+
);
|
|
2999
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 };
|
|
3000
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 };
|
|
3001
1505
|
}
|
|
3002
|
-
|
|
1506
|
+
async function synthesize(gone) {
|
|
1507
|
+
const { runId, flowId, pinnedHash } = gone.error;
|
|
1508
|
+
if (gone.live === void 0) {
|
|
1509
|
+
throw new NagiRuntimeError(
|
|
1510
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
1511
|
+
);
|
|
1512
|
+
}
|
|
1513
|
+
const snapshot = await store.loadSnapshot(pinnedHash);
|
|
1514
|
+
if (snapshot === null) {
|
|
1515
|
+
throw new NagiRuntimeError(
|
|
1516
|
+
`Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Cannot replay with allowDrift.`
|
|
1517
|
+
);
|
|
1518
|
+
}
|
|
1519
|
+
return synthesizeReplayFlow(
|
|
1520
|
+
snapshot.dag,
|
|
1521
|
+
gone.live
|
|
1522
|
+
);
|
|
1523
|
+
}
|
|
1524
|
+
return {
|
|
1525
|
+
get: (flowId) => byId.get(flowId),
|
|
1526
|
+
has: (flowId) => byId.has(flowId),
|
|
1527
|
+
require: require2,
|
|
1528
|
+
hashOf,
|
|
1529
|
+
isStreaming: (stepId) => streamingStepIds.has(stepId),
|
|
1530
|
+
resolve,
|
|
1531
|
+
synthesize
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
function synthesizeReplayFlow(dag, liveFlow) {
|
|
1535
|
+
const liveSteps = asStepMapWithDefs(liveFlow.steps);
|
|
1536
|
+
const synthesized = {};
|
|
1537
|
+
for (const canonStep of dag.steps) {
|
|
1538
|
+
const liveStep = liveSteps[canonStep.id];
|
|
1539
|
+
if (liveStep === void 0) {
|
|
1540
|
+
throw new NagiRuntimeError(
|
|
1541
|
+
`Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
|
|
1542
|
+
);
|
|
1543
|
+
}
|
|
1544
|
+
synthesized[canonStep.id] = attachDef(
|
|
1545
|
+
{ kind: canonStep.kind, id: canonStep.id },
|
|
1546
|
+
getDef(liveStep)
|
|
1547
|
+
);
|
|
1548
|
+
}
|
|
1549
|
+
for (const canonStep of dag.steps) {
|
|
1550
|
+
const shell = synthesized[canonStep.id];
|
|
1551
|
+
if (shell === void 0) continue;
|
|
1552
|
+
const synthesizedNeeds = {};
|
|
1553
|
+
for (const upstreamId of canonStep.needs) {
|
|
1554
|
+
const upstreamShell = synthesized[upstreamId];
|
|
1555
|
+
if (upstreamShell === void 0) {
|
|
1556
|
+
throw new NagiRuntimeError(
|
|
1557
|
+
`Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
|
|
1558
|
+
);
|
|
1559
|
+
}
|
|
1560
|
+
synthesizedNeeds[upstreamId] = upstreamShell;
|
|
1561
|
+
}
|
|
1562
|
+
setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
|
|
1563
|
+
}
|
|
1564
|
+
return {
|
|
1565
|
+
id: liveFlow.id,
|
|
1566
|
+
input: liveFlow.input,
|
|
1567
|
+
steps: synthesized,
|
|
1568
|
+
...compact({ output: liveFlow.output })
|
|
1569
|
+
};
|
|
3003
1570
|
}
|
|
3004
1571
|
|
|
3005
1572
|
// src/exec/progression.ts
|
|
@@ -3046,7 +1613,7 @@ function makeProgression(deps, hooks) {
|
|
|
3046
1613
|
const { fireHook } = hooks;
|
|
3047
1614
|
async function advance(runId) {
|
|
3048
1615
|
const { store, queue } = deps;
|
|
3049
|
-
const flow2 = await deps.
|
|
1616
|
+
const flow2 = requireCurrent(await deps.resolveFlow(runId));
|
|
3050
1617
|
for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
|
|
3051
1618
|
const runState = await store.loadRunState(runId);
|
|
3052
1619
|
const t = nextTransition(flow2, runState);
|
|
@@ -3062,7 +1629,8 @@ function makeProgression(deps, hooks) {
|
|
|
3062
1629
|
return;
|
|
3063
1630
|
case "dispatch":
|
|
3064
1631
|
await recordSkips(runId, t.skip);
|
|
3065
|
-
for (const stepId of t.runnable)
|
|
1632
|
+
for (const stepId of t.runnable)
|
|
1633
|
+
await queue.enqueue(runId, stepId, { flowId: flow2.id });
|
|
3066
1634
|
return;
|
|
3067
1635
|
case "skip":
|
|
3068
1636
|
await recordSkips(runId, t.skip);
|
|
@@ -3194,7 +1762,7 @@ function makeProgression(deps, hooks) {
|
|
|
3194
1762
|
return;
|
|
3195
1763
|
}
|
|
3196
1764
|
const attempt = parentStep.attempt;
|
|
3197
|
-
const parentFlow = await deps.
|
|
1765
|
+
const parentFlow = requireCurrent(await deps.resolveFlow(parentRunId));
|
|
3198
1766
|
await markStepSettled({
|
|
3199
1767
|
flow: parentFlow,
|
|
3200
1768
|
runId: parentRunId,
|
|
@@ -3222,25 +1790,33 @@ function makeDispatcher(deps) {
|
|
|
3222
1790
|
async function sweepTimers(now) {
|
|
3223
1791
|
const timedOut = await deps.store.sweepSignalTimeouts({ now });
|
|
3224
1792
|
for (const { runId, stepId, attempt, fireAt } of timedOut) {
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
3240
|
-
|
|
3241
|
-
|
|
1793
|
+
try {
|
|
1794
|
+
if (deps.hooks?.onStepError) {
|
|
1795
|
+
const flow2 = requireCurrent(await deps.resolveFlow(runId));
|
|
1796
|
+
await hooks.fireHook(
|
|
1797
|
+
deps.hooks.onStepError,
|
|
1798
|
+
{
|
|
1799
|
+
runId,
|
|
1800
|
+
flowId: flow2.id,
|
|
1801
|
+
stepId,
|
|
1802
|
+
attempt,
|
|
1803
|
+
kind: "signal",
|
|
1804
|
+
error: serializeError(
|
|
1805
|
+
new NagiSignalTimeoutError({ runId, stepId, fireAt })
|
|
1806
|
+
),
|
|
1807
|
+
at: now
|
|
1808
|
+
},
|
|
1809
|
+
"onStepError"
|
|
1810
|
+
);
|
|
1811
|
+
}
|
|
1812
|
+
await progression.advance(runId);
|
|
1813
|
+
} catch (err) {
|
|
1814
|
+
deps.emitLog({
|
|
1815
|
+
level: "error",
|
|
1816
|
+
msg: "nagi: signal timeout fired but the run could not be advanced \u2014 re-drive with operator.retry",
|
|
1817
|
+
attrs: { runId, stepId, attempt, error: String(err) }
|
|
1818
|
+
});
|
|
3242
1819
|
}
|
|
3243
|
-
await progression.advance(runId);
|
|
3244
1820
|
}
|
|
3245
1821
|
return timedOut.length;
|
|
3246
1822
|
}
|
|
@@ -3252,61 +1828,6 @@ function makeDispatcher(deps) {
|
|
|
3252
1828
|
};
|
|
3253
1829
|
}
|
|
3254
1830
|
|
|
3255
|
-
// src/flow-registry.ts
|
|
3256
|
-
function makeFlowRegistry(flows) {
|
|
3257
|
-
const byId = /* @__PURE__ */ new Map();
|
|
3258
|
-
const streamingStepIds = /* @__PURE__ */ new Set();
|
|
3259
|
-
for (const flow2 of flows) {
|
|
3260
|
-
if (byId.has(flow2.id)) {
|
|
3261
|
-
throw new NagiRuntimeError(
|
|
3262
|
-
`Duplicate flow id "${flow2.id}" passed to nagi()`
|
|
3263
|
-
);
|
|
3264
|
-
}
|
|
3265
|
-
byId.set(flow2.id, flow2);
|
|
3266
|
-
for (const [stepId, step] of Object.entries(
|
|
3267
|
-
asStepMapWithDefs(flow2.steps)
|
|
3268
|
-
)) {
|
|
3269
|
-
if (getDef(step).kind === "streaming") streamingStepIds.add(stepId);
|
|
3270
|
-
}
|
|
3271
|
-
}
|
|
3272
|
-
return {
|
|
3273
|
-
all: flows,
|
|
3274
|
-
get: (flowId) => byId.get(flowId),
|
|
3275
|
-
has: (flowId) => byId.has(flowId),
|
|
3276
|
-
require(flowId) {
|
|
3277
|
-
const flow2 = byId.get(flowId);
|
|
3278
|
-
if (!flow2) {
|
|
3279
|
-
throw new NagiRuntimeError(
|
|
3280
|
-
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
3281
|
-
);
|
|
3282
|
-
}
|
|
3283
|
-
return flow2;
|
|
3284
|
-
},
|
|
3285
|
-
requireForRun(flowId, runId, pinnedHash, currentHashOf) {
|
|
3286
|
-
const flow2 = byId.get(flowId);
|
|
3287
|
-
if (pinnedHash !== void 0) {
|
|
3288
|
-
const currentHash = flow2 === void 0 ? null : currentHashOf?.(flowId) ?? null;
|
|
3289
|
-
if (flow2 === void 0 || currentHash !== pinnedHash) {
|
|
3290
|
-
throw new NagiFlowSnapshotGoneError({
|
|
3291
|
-
runId,
|
|
3292
|
-
flowId,
|
|
3293
|
-
pinnedHash,
|
|
3294
|
-
currentHash
|
|
3295
|
-
});
|
|
3296
|
-
}
|
|
3297
|
-
return flow2;
|
|
3298
|
-
}
|
|
3299
|
-
if (!flow2) {
|
|
3300
|
-
throw new NagiRuntimeError(
|
|
3301
|
-
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
3302
|
-
);
|
|
3303
|
-
}
|
|
3304
|
-
return flow2;
|
|
3305
|
-
},
|
|
3306
|
-
isStreaming: (stepId) => streamingStepIds.has(stepId)
|
|
3307
|
-
};
|
|
3308
|
-
}
|
|
3309
|
-
|
|
3310
1831
|
// src/operator.ts
|
|
3311
1832
|
var ABORT_SETTLE_DEADLINE_MS = 3e4;
|
|
3312
1833
|
var ABORT_SETTLE_POLL_MS = 50;
|
|
@@ -3322,7 +1843,7 @@ function makeOperator(o) {
|
|
|
3322
1843
|
async function skip(runId, stepId, opts) {
|
|
3323
1844
|
requireActor("operator.skip", opts.actor);
|
|
3324
1845
|
const state = await store.loadRunState(runId);
|
|
3325
|
-
const flow2 = registry.
|
|
1846
|
+
const flow2 = registry.require(state.flowId);
|
|
3326
1847
|
if (!(stepId in flow2.steps)) {
|
|
3327
1848
|
throw validationError(
|
|
3328
1849
|
`operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
@@ -3379,7 +1900,7 @@ function makeOperator(o) {
|
|
|
3379
1900
|
`operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
|
|
3380
1901
|
);
|
|
3381
1902
|
}
|
|
3382
|
-
const flow2 = registry.
|
|
1903
|
+
const flow2 = registry.require(state.flowId);
|
|
3383
1904
|
if (!(stepId in flow2.steps)) {
|
|
3384
1905
|
throw validationError(
|
|
3385
1906
|
`operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
@@ -3432,51 +1953,18 @@ function makeOperator(o) {
|
|
|
3432
1953
|
return { skip, retry, abort };
|
|
3433
1954
|
}
|
|
3434
1955
|
|
|
3435
|
-
// src/replay-synth.ts
|
|
3436
|
-
function synthesizeReplayFlow(dag, liveFlow) {
|
|
3437
|
-
const liveSteps = asStepMapWithDefs(liveFlow.steps);
|
|
3438
|
-
const synthesized = {};
|
|
3439
|
-
for (const canonStep of dag.steps) {
|
|
3440
|
-
const liveStep = liveSteps[canonStep.id];
|
|
3441
|
-
if (liveStep === void 0) {
|
|
3442
|
-
throw new NagiRuntimeError(
|
|
3443
|
-
`Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
|
|
3444
|
-
);
|
|
3445
|
-
}
|
|
3446
|
-
synthesized[canonStep.id] = attachDef(
|
|
3447
|
-
{ kind: canonStep.kind, id: canonStep.id },
|
|
3448
|
-
getDef(liveStep)
|
|
3449
|
-
);
|
|
3450
|
-
}
|
|
3451
|
-
for (const canonStep of dag.steps) {
|
|
3452
|
-
const shell = synthesized[canonStep.id];
|
|
3453
|
-
if (shell === void 0) continue;
|
|
3454
|
-
const synthesizedNeeds = {};
|
|
3455
|
-
for (const upstreamId of canonStep.needs) {
|
|
3456
|
-
const upstreamShell = synthesized[upstreamId];
|
|
3457
|
-
if (upstreamShell === void 0) {
|
|
3458
|
-
throw new NagiRuntimeError(
|
|
3459
|
-
`Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
|
|
3460
|
-
);
|
|
3461
|
-
}
|
|
3462
|
-
synthesizedNeeds[upstreamId] = upstreamShell;
|
|
3463
|
-
}
|
|
3464
|
-
setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
|
|
3465
|
-
}
|
|
3466
|
-
return {
|
|
3467
|
-
id: liveFlow.id,
|
|
3468
|
-
input: liveFlow.input,
|
|
3469
|
-
steps: synthesized,
|
|
3470
|
-
...compact({ output: liveFlow.output })
|
|
3471
|
-
};
|
|
3472
|
-
}
|
|
3473
|
-
|
|
3474
1956
|
// src/replay.ts
|
|
3475
1957
|
function makeReplay(deps) {
|
|
3476
|
-
const { registry,
|
|
1958
|
+
const { registry, store, queue, clock } = deps;
|
|
3477
1959
|
async function replay(runId, opts = { mode: "continue" }) {
|
|
3478
1960
|
const runState = await store.loadRunState(runId);
|
|
3479
|
-
const
|
|
1961
|
+
const resolution = registry.resolve(runState);
|
|
1962
|
+
const liveFlow = resolution.kind === "current" ? resolution.flow : resolution.live;
|
|
1963
|
+
if (liveFlow === void 0) {
|
|
1964
|
+
throw new NagiRuntimeError(
|
|
1965
|
+
`Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
|
|
1966
|
+
);
|
|
1967
|
+
}
|
|
3480
1968
|
if (runState.phase.tag === "canceled") {
|
|
3481
1969
|
throw new NagiRuntimeError(
|
|
3482
1970
|
`Run ${runId} was canceled (superseded by a newer run with the same concurrency key). Replay is not supported for canceled runs \u2014 start a new run instead.`
|
|
@@ -3487,69 +1975,256 @@ function makeReplay(deps) {
|
|
|
3487
1975
|
const baseDeps = fireHooks ? deps : { ...deps, fireHooks: false };
|
|
3488
1976
|
let replayDeps = baseDeps;
|
|
3489
1977
|
let effectiveFlow = liveFlow;
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
|
|
1978
|
+
if (resolution.kind !== "current") {
|
|
1979
|
+
if (!opts.allowDrift) {
|
|
1980
|
+
throw new NagiSnapshotDriftError({
|
|
1981
|
+
runId,
|
|
1982
|
+
expected: resolution.error.pinnedHash,
|
|
1983
|
+
actual: registry.hashOf(liveFlow.id)
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
const synthesized = await registry.synthesize(resolution);
|
|
1987
|
+
replayDeps = {
|
|
1988
|
+
...baseDeps,
|
|
1989
|
+
resolveFlow: async () => ({ kind: "current", flow: synthesized })
|
|
1990
|
+
};
|
|
1991
|
+
effectiveFlow = synthesized;
|
|
1992
|
+
}
|
|
1993
|
+
if (opts.from !== void 0) {
|
|
1994
|
+
if (runState.phase.tag === "running") {
|
|
1995
|
+
throw new NagiRuntimeError(
|
|
1996
|
+
`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.`
|
|
1997
|
+
);
|
|
1998
|
+
}
|
|
1999
|
+
if (!(opts.from in effectiveFlow.steps)) {
|
|
2000
|
+
throw validationError(
|
|
2001
|
+
`replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
|
|
2002
|
+
["from"]
|
|
3510
2003
|
);
|
|
3511
|
-
replayDeps = { ...baseDeps, flowFor: async () => synthesized };
|
|
3512
|
-
effectiveFlow = synthesized;
|
|
3513
2004
|
}
|
|
2005
|
+
const cascade = descendantsOf(effectiveFlow, opts.from);
|
|
2006
|
+
const at = clock.now();
|
|
2007
|
+
for (const stepId of cascade) {
|
|
2008
|
+
const fact = stepId === opts.from ? Facts.stepReset({ runId, stepId, at }) : Facts.stepReset({ runId, stepId, at, cascadedFrom: opts.from });
|
|
2009
|
+
await store.appendFact(runId, fact);
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
const replayDispatcher = makeDispatcher(replayDeps);
|
|
2013
|
+
await replayDispatcher.advance(runId);
|
|
2014
|
+
if (!fireHooks) await drainInline(replayDispatcher, queue);
|
|
2015
|
+
}
|
|
2016
|
+
return { replay };
|
|
2017
|
+
}
|
|
2018
|
+
var MAX_REPLAY_DISPATCHES = 4096;
|
|
2019
|
+
async function drainInline(dispatcher, queue) {
|
|
2020
|
+
for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
|
|
2021
|
+
const messages = await queue.dequeue({ count: 1 });
|
|
2022
|
+
if (messages.length === 0) return;
|
|
2023
|
+
for (const msg of messages) {
|
|
2024
|
+
const result = await dispatcher.dispatchMessage(msg);
|
|
2025
|
+
if (result.kind === "snapshot-gone") throw result.error;
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
// src/run-lifecycle.ts
|
|
2031
|
+
var EXISTS = { kind: "exists" };
|
|
2032
|
+
var ADVANCE = { kind: "advance" };
|
|
2033
|
+
function makeRunLifecycle(deps) {
|
|
2034
|
+
const { store, queue, clock, registry, hooks, flowHooks, dispatcher } = deps;
|
|
2035
|
+
function resolveBoundary(boundary) {
|
|
2036
|
+
switch (boundary.kind) {
|
|
2037
|
+
case "own":
|
|
2038
|
+
return {
|
|
2039
|
+
tryStart: (runId, fact, concurrency) => store.tryStartRun(runId, fact, concurrency),
|
|
2040
|
+
seed: async (_runId, _flowId, t) => t.skip.length > 0 ? ADVANCE : { kind: "enqueue", steps: t.runnable }
|
|
2041
|
+
};
|
|
2042
|
+
case "caller":
|
|
2043
|
+
return {
|
|
2044
|
+
tryStart: (runId, fact, concurrency) => store.tryStartRunOnTx(boundary.tx, runId, fact, concurrency),
|
|
2045
|
+
seed: async (runId, flowId, t) => {
|
|
2046
|
+
const txQueue = deps.queueForTx(boundary.tx);
|
|
2047
|
+
for (const stepId of t.runnable) {
|
|
2048
|
+
await txQueue.enqueue(runId, stepId, { flowId });
|
|
2049
|
+
}
|
|
2050
|
+
return { kind: "enqueued", steps: t.runnable, skip: t.skip };
|
|
2051
|
+
}
|
|
2052
|
+
};
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
async function stage(args) {
|
|
2056
|
+
const { flow: flow2, validatedInput, runId, parent } = args;
|
|
2057
|
+
const { tryStart, seed } = resolveBoundary(args.boundary);
|
|
2058
|
+
const startedAt = clock.now();
|
|
2059
|
+
const fact = Facts.flowStarted({
|
|
2060
|
+
runId,
|
|
2061
|
+
flowId: flow2.id,
|
|
2062
|
+
input: validatedInput,
|
|
2063
|
+
at: startedAt,
|
|
2064
|
+
codeVersion: deps.codeVersion,
|
|
2065
|
+
flowHash: registry.hashOf(flow2.id),
|
|
2066
|
+
...compact({
|
|
2067
|
+
parent: parent !== void 0 ? { runId: parent.runId, stepId: parent.stepId } : void 0
|
|
2068
|
+
})
|
|
2069
|
+
});
|
|
2070
|
+
const concurrency = concurrencyOf(flow2, validatedInput);
|
|
2071
|
+
const { started, canceled } = await tryStart(runId, fact, concurrency);
|
|
2072
|
+
if (!started) return EXISTS;
|
|
2073
|
+
const t = nextTransition(flow2, foldRun(runId, [fact]));
|
|
2074
|
+
const dispatch = t.kind === "dispatch" ? await seed(runId, flow2.id, t) : ADVANCE;
|
|
2075
|
+
return {
|
|
2076
|
+
kind: "started",
|
|
2077
|
+
effects: {
|
|
2078
|
+
superseded: canceled.map((c) => supersededEvent(flow2.id, runId, c)),
|
|
2079
|
+
started: {
|
|
2080
|
+
runId,
|
|
2081
|
+
flowId: flow2.id,
|
|
2082
|
+
input: validatedInput,
|
|
2083
|
+
at: startedAt,
|
|
2084
|
+
...compact({ parent })
|
|
2085
|
+
},
|
|
2086
|
+
dispatch
|
|
2087
|
+
}
|
|
2088
|
+
};
|
|
2089
|
+
}
|
|
2090
|
+
async function applyEffects(effects) {
|
|
2091
|
+
const { superseded, started, dispatch } = effects;
|
|
2092
|
+
const flow2 = registry.require(started.flowId);
|
|
2093
|
+
for (const event of superseded) {
|
|
2094
|
+
await hooks.fireHook(flow2.onError, event, "flow.onError");
|
|
2095
|
+
await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
|
|
2096
|
+
await dispatcher.propagateToParent(event.runId, {
|
|
2097
|
+
kind: "canceled",
|
|
2098
|
+
error: event.error
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
await hooks.fireHook(flow2.onStart, started, "flow.onStart");
|
|
2102
|
+
await hooks.fireHook(flowHooks?.onFlowStart, started, "onFlowStart");
|
|
2103
|
+
switch (dispatch.kind) {
|
|
2104
|
+
case "enqueue":
|
|
2105
|
+
for (const stepId of dispatch.steps) {
|
|
2106
|
+
await queue.enqueue(started.runId, stepId, { flowId: flow2.id });
|
|
2107
|
+
}
|
|
2108
|
+
return;
|
|
2109
|
+
case "enqueued":
|
|
2110
|
+
await recordSkips(started.runId, dispatch.skip);
|
|
2111
|
+
return;
|
|
2112
|
+
case "advance":
|
|
2113
|
+
await dispatcher.advance(started.runId);
|
|
2114
|
+
return;
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
async function recordSkips(runId, skip) {
|
|
2118
|
+
if (skip.length === 0) return;
|
|
2119
|
+
const state = await store.loadRunState(runId);
|
|
2120
|
+
for (const { stepId, reason } of skip) {
|
|
2121
|
+
if (stepStateOf(state, stepId).tag !== "pending") continue;
|
|
2122
|
+
await store.appendFact(
|
|
2123
|
+
runId,
|
|
2124
|
+
Facts.stepSkipped({ runId, stepId, reason, at: clock.now() })
|
|
2125
|
+
);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
async function start(args) {
|
|
2129
|
+
const flow2 = registry.require(args.flowId);
|
|
2130
|
+
const runId = resolveRunId(args.runId);
|
|
2131
|
+
const validatedInput = await validate(flow2.input, args.input);
|
|
2132
|
+
const staged = await stage({
|
|
2133
|
+
flow: flow2,
|
|
2134
|
+
validatedInput,
|
|
2135
|
+
runId,
|
|
2136
|
+
parent: void 0,
|
|
2137
|
+
boundary: args.boundary
|
|
2138
|
+
});
|
|
2139
|
+
return { runId, staged };
|
|
2140
|
+
}
|
|
2141
|
+
async function startChildRun(args) {
|
|
2142
|
+
const { child, childInput, parent, generation } = args;
|
|
2143
|
+
if (!registry.has(child.id)) {
|
|
2144
|
+
throw new NagiRuntimeError(
|
|
2145
|
+
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
2146
|
+
);
|
|
2147
|
+
}
|
|
2148
|
+
const validatedInput = await validate(child.input, childInput);
|
|
2149
|
+
const runId = await deriveChildRunId({
|
|
2150
|
+
runId: parent.runId,
|
|
2151
|
+
stepId: parent.stepId,
|
|
2152
|
+
generation
|
|
2153
|
+
});
|
|
2154
|
+
const staged = await stage({
|
|
2155
|
+
flow: child,
|
|
2156
|
+
validatedInput,
|
|
2157
|
+
runId,
|
|
2158
|
+
parent,
|
|
2159
|
+
boundary: { kind: "own" }
|
|
2160
|
+
});
|
|
2161
|
+
if (staged.kind === "started") await applyEffects(staged.effects);
|
|
2162
|
+
return runId;
|
|
2163
|
+
}
|
|
2164
|
+
async function cancelRunRecursive(runId, args) {
|
|
2165
|
+
const state = await store.loadRunState(runId);
|
|
2166
|
+
if (isTerminalRun(state)) {
|
|
2167
|
+
deps.emitLog({
|
|
2168
|
+
level: "info",
|
|
2169
|
+
msg: "nagi: cancel skipped \u2014 run already terminal",
|
|
2170
|
+
attrs: { runId, status: runStatusOf(state) }
|
|
2171
|
+
});
|
|
2172
|
+
return;
|
|
3514
2173
|
}
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
|
|
3524
|
-
|
|
3525
|
-
);
|
|
3526
|
-
}
|
|
3527
|
-
const cascade = descendantsOf(effectiveFlow, opts.from);
|
|
3528
|
-
const at = clock.now();
|
|
3529
|
-
for (const stepId of cascade) {
|
|
3530
|
-
const fact = stepId === opts.from ? Facts.stepReset({ runId, stepId, at }) : Facts.stepReset({ runId, stepId, at, cascadedFrom: opts.from });
|
|
3531
|
-
await store.appendFact(runId, fact);
|
|
3532
|
-
}
|
|
2174
|
+
const flow2 = registry.get(state.flowId);
|
|
2175
|
+
await store.appendFact(runId, Facts.flowCanceled(runId, args, clock.now()));
|
|
2176
|
+
const error = {
|
|
2177
|
+
name: "NagiCanceledError",
|
|
2178
|
+
message: `Run ${runId} was canceled: ${args.reason}`
|
|
2179
|
+
};
|
|
2180
|
+
if (flow2 !== void 0) {
|
|
2181
|
+
const event = { runId, flowId: flow2.id, error, at: clock.now() };
|
|
2182
|
+
await hooks.fireHook(flow2.onError, event, "flow.onError");
|
|
2183
|
+
await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
|
|
3533
2184
|
}
|
|
3534
|
-
const
|
|
3535
|
-
|
|
3536
|
-
|
|
2185
|
+
for (const childId of await store.listChildren(runId)) {
|
|
2186
|
+
await cancelRunRecursive(childId, {
|
|
2187
|
+
cause: "explicit",
|
|
2188
|
+
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
2189
|
+
note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
2190
|
+
});
|
|
2191
|
+
}
|
|
2192
|
+
await dispatcher.propagateToParent(runId, { kind: "canceled", error });
|
|
3537
2193
|
}
|
|
3538
|
-
return {
|
|
2194
|
+
return { start, stage, applyEffects, startChildRun, cancelRunRecursive };
|
|
3539
2195
|
}
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
|
|
3544
|
-
if (messages.length === 0) return;
|
|
3545
|
-
for (const msg of messages) await dispatcher.dispatchMessage(msg);
|
|
2196
|
+
function resolveRunId(runId) {
|
|
2197
|
+
if (runId === void 0) return `run-${crypto.randomUUID()}`;
|
|
2198
|
+
if (typeof runId !== "string" || runId.length === 0) {
|
|
2199
|
+
throw validationError("opts.runId must be a non-empty string", ["runId"]);
|
|
3546
2200
|
}
|
|
2201
|
+
return runId;
|
|
2202
|
+
}
|
|
2203
|
+
function concurrencyOf(flow2, input) {
|
|
2204
|
+
if (flow2.concurrency === void 0) return void 0;
|
|
2205
|
+
const key = flow2.concurrency.keyFn(input);
|
|
2206
|
+
if (typeof key !== "string" || key.length === 0) {
|
|
2207
|
+
throw validationError(
|
|
2208
|
+
`flow.concurrency.keyFn must return a non-empty string (got ${typeof key === "string" ? '""' : typeof key})`,
|
|
2209
|
+
["concurrency", "keyFn"]
|
|
2210
|
+
);
|
|
2211
|
+
}
|
|
2212
|
+
return { key, mode: flow2.concurrency.mode };
|
|
2213
|
+
}
|
|
2214
|
+
function supersededEvent(flowId, canceledByRunId, c) {
|
|
2215
|
+
const cause = { canceledByRunId, concurrencyKey: c.fact.concurrencyKey };
|
|
2216
|
+
const error = {
|
|
2217
|
+
...serializeError(new NagiCanceledError({ runId: c.runId, ...cause })),
|
|
2218
|
+
cause
|
|
2219
|
+
};
|
|
2220
|
+
return { runId: c.runId, flowId, error, at: c.fact.at };
|
|
3547
2221
|
}
|
|
3548
2222
|
|
|
3549
2223
|
// src/worker.ts
|
|
3550
2224
|
var DEFAULT_CONCURRENCY = 4;
|
|
3551
2225
|
var DEFAULT_POLL_INTERVAL_MS = 1e3;
|
|
3552
2226
|
var DEFAULT_TIMER_SWEEP_INTERVAL_MS = 3e4;
|
|
2227
|
+
var SNAPSHOT_GONE_FALLBACK_NACK_DELAY_MS = 3e4;
|
|
3553
2228
|
function makeWorker(deps, config) {
|
|
3554
2229
|
return new WorkerImpl(deps, config);
|
|
3555
2230
|
}
|
|
@@ -3558,8 +2233,11 @@ var WorkerImpl = class {
|
|
|
3558
2233
|
this.deps = deps;
|
|
3559
2234
|
this.concurrency = Math.max(1, config?.concurrency ?? DEFAULT_CONCURRENCY);
|
|
3560
2235
|
this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
2236
|
+
this.dequeueBackoffMs = dequeueBackoff(this.pollIntervalMs);
|
|
3561
2237
|
this.signal = config?.signal;
|
|
3562
2238
|
this.dispatcher = makeDispatcher(deps);
|
|
2239
|
+
this.snapshotGonePolicy = config?.snapshotGonePolicy ?? defaultSnapshotGonePolicy;
|
|
2240
|
+
this.maxPerFlow = config?.maxConcurrencyPerFlow !== void 0 ? Math.max(1, config.maxConcurrencyPerFlow) : void 0;
|
|
3563
2241
|
this.timerSweepIntervalMs = config?.timerSweepIntervalMs ?? DEFAULT_TIMER_SWEEP_INTERVAL_MS;
|
|
3564
2242
|
this.lastTimerSweepAt = this.deps.clock.now().getTime();
|
|
3565
2243
|
}
|
|
@@ -3567,11 +2245,49 @@ var WorkerImpl = class {
|
|
|
3567
2245
|
inFlight = 0;
|
|
3568
2246
|
concurrency;
|
|
3569
2247
|
pollIntervalMs;
|
|
2248
|
+
dequeueBackoffMs;
|
|
3570
2249
|
signal;
|
|
3571
2250
|
dispatcher;
|
|
3572
2251
|
timerSweepIntervalMs;
|
|
2252
|
+
snapshotGonePolicy;
|
|
2253
|
+
maxPerFlow;
|
|
2254
|
+
inFlightByFlow = /* @__PURE__ */ new Map();
|
|
3573
2255
|
lastTimerSweepAt;
|
|
2256
|
+
// Per-flow blast-radius bound (maxConcurrencyPerFlow). A message over its
|
|
2257
|
+
// flow's cap is DEFERRED — delayed nack, redelivered after ~pollIntervalMs —
|
|
2258
|
+
// not dropped. Messages without flowId (enqueued pre-upgrade) are exempt.
|
|
2259
|
+
// Deferral does raise pgmq read_ct, which the snapshot-gone policy reads;
|
|
2260
|
+
// that only matters if the same flow later goes snapshot-gone, where an
|
|
2261
|
+
// earlier fail is acceptable.
|
|
2262
|
+
admitFlow(msg) {
|
|
2263
|
+
if (this.maxPerFlow === void 0 || msg.flowId === void 0) return true;
|
|
2264
|
+
return (this.inFlightByFlow.get(msg.flowId) ?? 0) < this.maxPerFlow;
|
|
2265
|
+
}
|
|
2266
|
+
// Returns the release fn; caller must invoke it exactly once when done.
|
|
2267
|
+
trackFlow(msg) {
|
|
2268
|
+
const { flowId } = msg;
|
|
2269
|
+
if (flowId === void 0) return () => {
|
|
2270
|
+
};
|
|
2271
|
+
this.inFlightByFlow.set(flowId, (this.inFlightByFlow.get(flowId) ?? 0) + 1);
|
|
2272
|
+
return () => {
|
|
2273
|
+
const n = (this.inFlightByFlow.get(flowId) ?? 1) - 1;
|
|
2274
|
+
if (n <= 0) this.inFlightByFlow.delete(flowId);
|
|
2275
|
+
else this.inFlightByFlow.set(flowId, n);
|
|
2276
|
+
};
|
|
2277
|
+
}
|
|
2278
|
+
async defer(msg) {
|
|
2279
|
+
try {
|
|
2280
|
+
await this.deps.queue.nack(msg.receipt, { delayMs: this.pollIntervalMs });
|
|
2281
|
+
} catch {
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
// MUST settle only via the abort signal. A rejection escaping this loop
|
|
2285
|
+
// silently ends ALL flow processing in a process that otherwise looks
|
|
2286
|
+
// healthy — observed in prod as one transient `pgmq.read` connection
|
|
2287
|
+
// timeout killing the loop, then 37h of fleet-wide stuck runs because
|
|
2288
|
+
// nothing restarts it. Every await below is therefore guarded.
|
|
3574
2289
|
async run() {
|
|
2290
|
+
let dequeueFailures = 0;
|
|
3575
2291
|
while (!this.aborted()) {
|
|
3576
2292
|
await this.maybeSweepTimers();
|
|
3577
2293
|
const slots = this.concurrency - this.inFlight;
|
|
@@ -3579,12 +2295,32 @@ var WorkerImpl = class {
|
|
|
3579
2295
|
await this.sleep(50);
|
|
3580
2296
|
continue;
|
|
3581
2297
|
}
|
|
3582
|
-
|
|
2298
|
+
let messages;
|
|
2299
|
+
try {
|
|
2300
|
+
messages = await this.dequeue(slots);
|
|
2301
|
+
} catch (err) {
|
|
2302
|
+
dequeueFailures++;
|
|
2303
|
+
this.deps.emitLog({
|
|
2304
|
+
level: "error",
|
|
2305
|
+
msg: "worker.dequeue failed; backing off",
|
|
2306
|
+
attrs: {
|
|
2307
|
+
error: String(err),
|
|
2308
|
+
consecutiveFailures: dequeueFailures,
|
|
2309
|
+
backoffMs: this.dequeueBackoffMs(dequeueFailures)
|
|
2310
|
+
}
|
|
2311
|
+
});
|
|
2312
|
+
await this.sleep(this.dequeueBackoffMs(dequeueFailures));
|
|
2313
|
+
continue;
|
|
2314
|
+
}
|
|
2315
|
+
dequeueFailures = 0;
|
|
3583
2316
|
if (messages.length === 0) {
|
|
3584
2317
|
await this.sleep(this.pollIntervalMs);
|
|
3585
2318
|
continue;
|
|
3586
2319
|
}
|
|
3587
|
-
for (const msg of messages)
|
|
2320
|
+
for (const msg of messages) {
|
|
2321
|
+
if (this.admitFlow(msg)) this.fire(msg);
|
|
2322
|
+
else await this.defer(msg);
|
|
2323
|
+
}
|
|
3588
2324
|
}
|
|
3589
2325
|
await this.drain();
|
|
3590
2326
|
}
|
|
@@ -3598,17 +2334,36 @@ var WorkerImpl = class {
|
|
|
3598
2334
|
async runUntilEmpty(opts) {
|
|
3599
2335
|
const deadline = opts?.deadline;
|
|
3600
2336
|
return this.pump({
|
|
3601
|
-
shouldContinue: () => deadline === void 0 ||
|
|
2337
|
+
shouldContinue: () => deadline === void 0 || this.deps.clock.now().getTime() < deadline,
|
|
3602
2338
|
batchSize: () => this.concurrency
|
|
3603
2339
|
});
|
|
3604
2340
|
}
|
|
2341
|
+
// Unlike run(), a dequeue failure here PROPAGATES. These are bounded calls
|
|
2342
|
+
// that hand a result back to an awaiting caller, so a rejection is observed,
|
|
2343
|
+
// not silent — the outage shape run() guards against cannot happen. The
|
|
2344
|
+
// alternatives are both worse: retrying would let runUntilEmpty() hang for
|
|
2345
|
+
// the length of a database outage, and swallowing would report an
|
|
2346
|
+
// unreachable queue as a drained one.
|
|
3605
2347
|
async pump(opts) {
|
|
3606
2348
|
let processed = 0;
|
|
3607
2349
|
while (!this.aborted() && opts.shouldContinue(processed)) {
|
|
3608
2350
|
const messages = await this.dequeue(opts.batchSize(processed));
|
|
3609
2351
|
if (messages.length === 0) break;
|
|
3610
|
-
|
|
3611
|
-
|
|
2352
|
+
const admitted = [];
|
|
2353
|
+
for (const m of messages) {
|
|
2354
|
+
if (this.admitFlow(m)) {
|
|
2355
|
+
admitted.push({ m, release: this.trackFlow(m) });
|
|
2356
|
+
} else {
|
|
2357
|
+
await this.defer(m);
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
await Promise.all(
|
|
2361
|
+
admitted.map(({ m }) => this.dispatchSafely(m))
|
|
2362
|
+
).finally(() => {
|
|
2363
|
+
for (const { release } of admitted) release();
|
|
2364
|
+
});
|
|
2365
|
+
processed += admitted.length;
|
|
2366
|
+
if (admitted.length === 0) break;
|
|
3612
2367
|
}
|
|
3613
2368
|
return { processed };
|
|
3614
2369
|
}
|
|
@@ -3617,31 +2372,17 @@ var WorkerImpl = class {
|
|
|
3617
2372
|
}
|
|
3618
2373
|
fire(msg) {
|
|
3619
2374
|
this.inFlight++;
|
|
2375
|
+
const release = this.trackFlow(msg);
|
|
3620
2376
|
void this.dispatchSafely(msg).finally(() => {
|
|
2377
|
+
release();
|
|
3621
2378
|
this.inFlight = Math.max(0, this.inFlight - 1);
|
|
3622
2379
|
});
|
|
3623
2380
|
}
|
|
3624
2381
|
async dispatchSafely(msg) {
|
|
2382
|
+
let result;
|
|
3625
2383
|
try {
|
|
3626
|
-
await this.dispatcher.dispatchMessage(msg);
|
|
2384
|
+
result = await this.dispatcher.dispatchMessage(msg);
|
|
3627
2385
|
} catch (err) {
|
|
3628
|
-
if (err instanceof NagiFlowSnapshotGoneError) {
|
|
3629
|
-
this.deps.emitLog({
|
|
3630
|
-
level: "warn",
|
|
3631
|
-
msg: "worker.dispatch: flow snapshot gone \u2014 nacking",
|
|
3632
|
-
attrs: {
|
|
3633
|
-
runId: err.runId,
|
|
3634
|
-
flowId: err.flowId,
|
|
3635
|
-
pinnedHash: err.pinnedHash,
|
|
3636
|
-
currentHash: err.currentHash
|
|
3637
|
-
}
|
|
3638
|
-
});
|
|
3639
|
-
try {
|
|
3640
|
-
await this.deps.queue.nack(msg.receipt);
|
|
3641
|
-
} catch {
|
|
3642
|
-
}
|
|
3643
|
-
return;
|
|
3644
|
-
}
|
|
3645
2386
|
this.deps.emitLog({
|
|
3646
2387
|
level: "error",
|
|
3647
2388
|
msg: "worker.dispatch threw uncaught",
|
|
@@ -3651,7 +2392,80 @@ var WorkerImpl = class {
|
|
|
3651
2392
|
await this.deps.queue.nack(msg.receipt);
|
|
3652
2393
|
} catch {
|
|
3653
2394
|
}
|
|
2395
|
+
return;
|
|
2396
|
+
}
|
|
2397
|
+
switch (result.kind) {
|
|
2398
|
+
case "done":
|
|
2399
|
+
return;
|
|
2400
|
+
case "snapshot-gone":
|
|
2401
|
+
try {
|
|
2402
|
+
await this.handleSnapshotGone(msg, result.error);
|
|
2403
|
+
} catch (handleErr) {
|
|
2404
|
+
this.deps.emitLog({
|
|
2405
|
+
level: "error",
|
|
2406
|
+
msg: "worker.dispatch: snapshot-gone handling failed",
|
|
2407
|
+
attrs: { runId: result.error.runId, error: String(handleErr) }
|
|
2408
|
+
});
|
|
2409
|
+
try {
|
|
2410
|
+
await this.deps.queue.nack(msg.receipt, {
|
|
2411
|
+
delayMs: SNAPSHOT_GONE_FALLBACK_NACK_DELAY_MS
|
|
2412
|
+
});
|
|
2413
|
+
} catch {
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
return;
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
// A snapshot-gone message is retried (nack, delayed) only while the policy
|
|
2420
|
+
// says a frozen-version worker might still claim it; past that budget the
|
|
2421
|
+
// run is terminally failed with the snapshot-gone error and the message
|
|
2422
|
+
// acked, so poison messages cannot outlive the deploy that orphaned them.
|
|
2423
|
+
async handleSnapshotGone(msg, err) {
|
|
2424
|
+
const attrs = {
|
|
2425
|
+
runId: err.runId,
|
|
2426
|
+
flowId: err.flowId,
|
|
2427
|
+
pinnedHash: err.pinnedHash,
|
|
2428
|
+
currentHash: err.currentHash,
|
|
2429
|
+
readCount: msg.readCount
|
|
2430
|
+
};
|
|
2431
|
+
const disposition = this.snapshotGonePolicy(msg.readCount);
|
|
2432
|
+
if (disposition.action === "retry") {
|
|
2433
|
+
this.deps.emitLog({
|
|
2434
|
+
level: "warn",
|
|
2435
|
+
msg: "worker.dispatch: flow snapshot gone \u2014 nacking for a frozen-version worker",
|
|
2436
|
+
attrs
|
|
2437
|
+
});
|
|
2438
|
+
try {
|
|
2439
|
+
await this.deps.queue.nack(msg.receipt, {
|
|
2440
|
+
delayMs: disposition.delayMs
|
|
2441
|
+
});
|
|
2442
|
+
} catch {
|
|
2443
|
+
}
|
|
2444
|
+
return;
|
|
2445
|
+
}
|
|
2446
|
+
this.deps.emitLog({
|
|
2447
|
+
level: "error",
|
|
2448
|
+
msg: "worker.dispatch: flow snapshot gone \u2014 redelivery budget exhausted, failing run",
|
|
2449
|
+
attrs
|
|
2450
|
+
});
|
|
2451
|
+
const serialized = serializeError(err);
|
|
2452
|
+
await this.deps.store.appendFact(
|
|
2453
|
+
msg.runId,
|
|
2454
|
+
Facts.flowFailed(msg.runId, serialized, this.deps.clock.now())
|
|
2455
|
+
);
|
|
2456
|
+
try {
|
|
2457
|
+
await this.dispatcher.propagateToParent(msg.runId, {
|
|
2458
|
+
kind: "failed",
|
|
2459
|
+
error: serialized
|
|
2460
|
+
});
|
|
2461
|
+
} catch (propagateErr) {
|
|
2462
|
+
this.deps.emitLog({
|
|
2463
|
+
level: "warn",
|
|
2464
|
+
msg: "worker.dispatch: snapshot-gone fail could not propagate to parent",
|
|
2465
|
+
attrs: { ...attrs, error: String(propagateErr) }
|
|
2466
|
+
});
|
|
3654
2467
|
}
|
|
2468
|
+
await this.deps.queue.ack(msg.receipt);
|
|
3655
2469
|
}
|
|
3656
2470
|
async drain() {
|
|
3657
2471
|
while (this.inFlight > 0) {
|
|
@@ -3694,202 +2508,33 @@ async function nagiImpl(config) {
|
|
|
3694
2508
|
const clock = config.clock ?? new InMemoryClock();
|
|
3695
2509
|
const emitLog = makeEmit(config.onLog);
|
|
3696
2510
|
await config.queue.ensureSchema?.();
|
|
3697
|
-
const
|
|
3698
|
-
const streamTransport = config.streamTransport ?? asStreamTransport(config.store);
|
|
2511
|
+
const streamTransport = config.store.stream;
|
|
3699
2512
|
if (streamTransport === void 0) {
|
|
3700
|
-
for (const f of
|
|
2513
|
+
for (const f of config.flows) {
|
|
3701
2514
|
for (const [stepId, step] of Object.entries(asStepMapWithDefs(f.steps))) {
|
|
3702
2515
|
if (getDef(step).kind !== "streaming") continue;
|
|
3703
2516
|
throw new NagiRuntimeError(
|
|
3704
|
-
`Flow "${f.id}" has a streaming step "${stepId}" (b.streamingTask), but no
|
|
2517
|
+
`Flow "${f.id}" has a streaming step "${stepId}" (b.streamingTask), but the store has no \`stream\` transport \u2014 it cannot carry ephemeral chunks. Use a store that exposes \`stream\` (e.g. the in-memory store) or remove the streaming step.`
|
|
3705
2518
|
);
|
|
3706
2519
|
}
|
|
3707
2520
|
}
|
|
3708
2521
|
}
|
|
3709
|
-
const
|
|
3710
|
-
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
await config.store.upsertSnapshot({
|
|
3715
|
-
flowHash,
|
|
3716
|
-
flowId: f.id,
|
|
3717
|
-
dag
|
|
3718
|
-
});
|
|
3719
|
-
const previousHash = await config.store.getRef(f.id);
|
|
3720
|
-
if (previousHash !== flowHash) {
|
|
3721
|
-
await config.store.setRef(f.id, flowHash);
|
|
3722
|
-
await config.store.appendGlobalFact(
|
|
3723
|
-
Facts.flowRefUpdated({
|
|
3724
|
-
flowId: f.id,
|
|
3725
|
-
from: previousHash,
|
|
3726
|
-
to: flowHash,
|
|
3727
|
-
at: clock.now()
|
|
3728
|
-
})
|
|
3729
|
-
);
|
|
3730
|
-
}
|
|
3731
|
-
}
|
|
2522
|
+
const registry = await registerFlows({
|
|
2523
|
+
flows: config.flows,
|
|
2524
|
+
store: config.store,
|
|
2525
|
+
clock
|
|
2526
|
+
});
|
|
3732
2527
|
const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
|
|
3733
|
-
async function
|
|
3734
|
-
|
|
3735
|
-
return registry.requireForRun(
|
|
3736
|
-
runState.flowId,
|
|
3737
|
-
runId,
|
|
3738
|
-
runState.flowHash,
|
|
3739
|
-
(id) => flowHashById.get(id)
|
|
3740
|
-
);
|
|
2528
|
+
async function resolveFlow(runId) {
|
|
2529
|
+
return registry.resolve(await config.store.loadRunState(runId));
|
|
3741
2530
|
}
|
|
3742
2531
|
function lookupFlow(flowId) {
|
|
3743
2532
|
return registry.get(flowId);
|
|
3744
2533
|
}
|
|
3745
|
-
async function startRunInternal({
|
|
3746
|
-
flow: flow2,
|
|
3747
|
-
validatedInput,
|
|
3748
|
-
runId,
|
|
3749
|
-
parent
|
|
3750
|
-
}) {
|
|
3751
|
-
const startedAt = clock.now();
|
|
3752
|
-
const flowHash = flowHashById.get(flow2.id);
|
|
3753
|
-
const fact = Facts.flowStarted({
|
|
3754
|
-
runId,
|
|
3755
|
-
flowId: flow2.id,
|
|
3756
|
-
input: validatedInput,
|
|
3757
|
-
at: startedAt,
|
|
3758
|
-
codeVersion,
|
|
3759
|
-
...compact({
|
|
3760
|
-
flowHash,
|
|
3761
|
-
parent: parent !== void 0 ? { runId: parent.runId, stepId: parent.stepId } : void 0
|
|
3762
|
-
})
|
|
3763
|
-
});
|
|
3764
|
-
let concurrencyArg;
|
|
3765
|
-
if (flow2.concurrency !== void 0) {
|
|
3766
|
-
const derived = flow2.concurrency.keyFn(validatedInput);
|
|
3767
|
-
if (typeof derived !== "string" || derived.length === 0) {
|
|
3768
|
-
throw validationError(
|
|
3769
|
-
`flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
3770
|
-
["concurrency", "keyFn"]
|
|
3771
|
-
);
|
|
3772
|
-
}
|
|
3773
|
-
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
3774
|
-
}
|
|
3775
|
-
const { started, canceled } = await config.store.tryStartRun(
|
|
3776
|
-
runId,
|
|
3777
|
-
fact,
|
|
3778
|
-
concurrencyArg
|
|
3779
|
-
);
|
|
3780
|
-
if (!started) return { started: false };
|
|
3781
|
-
for (const c of canceled) {
|
|
3782
|
-
const cancelError = new NagiCanceledError({
|
|
3783
|
-
runId: c.runId,
|
|
3784
|
-
canceledByRunId: runId,
|
|
3785
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
3786
|
-
});
|
|
3787
|
-
const serialized = {
|
|
3788
|
-
...serializeError(cancelError),
|
|
3789
|
-
cause: {
|
|
3790
|
-
canceledByRunId: runId,
|
|
3791
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
3792
|
-
}
|
|
3793
|
-
};
|
|
3794
|
-
const errorEvent = {
|
|
3795
|
-
runId: c.runId,
|
|
3796
|
-
flowId: flow2.id,
|
|
3797
|
-
error: serialized,
|
|
3798
|
-
at: c.fact.at
|
|
3799
|
-
};
|
|
3800
|
-
await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
|
|
3801
|
-
await hooks.fireHook(
|
|
3802
|
-
config.hooks?.onFlowError,
|
|
3803
|
-
errorEvent,
|
|
3804
|
-
"onFlowError"
|
|
3805
|
-
);
|
|
3806
|
-
await dispatcher.propagateToParent(c.runId, {
|
|
3807
|
-
kind: "canceled",
|
|
3808
|
-
error: serialized
|
|
3809
|
-
});
|
|
3810
|
-
}
|
|
3811
|
-
const startEvent = parent !== void 0 ? {
|
|
3812
|
-
runId,
|
|
3813
|
-
flowId: flow2.id,
|
|
3814
|
-
input: validatedInput,
|
|
3815
|
-
at: startedAt,
|
|
3816
|
-
parent
|
|
3817
|
-
} : {
|
|
3818
|
-
runId,
|
|
3819
|
-
flowId: flow2.id,
|
|
3820
|
-
input: validatedInput,
|
|
3821
|
-
at: startedAt
|
|
3822
|
-
};
|
|
3823
|
-
await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
|
|
3824
|
-
await hooks.fireHook(config.hooks?.onFlowStart, startEvent, "onFlowStart");
|
|
3825
|
-
await dispatcher.advance(runId);
|
|
3826
|
-
return { started: true };
|
|
3827
|
-
}
|
|
3828
|
-
async function startChildRun(args) {
|
|
3829
|
-
const { child, childInput, parent, generation } = args;
|
|
3830
|
-
if (!registry.has(child.id)) {
|
|
3831
|
-
throw new NagiRuntimeError(
|
|
3832
|
-
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
3833
|
-
);
|
|
3834
|
-
}
|
|
3835
|
-
const validated = await validate(child.input, childInput);
|
|
3836
|
-
const childRunId = await deriveChildRunId({
|
|
3837
|
-
runId: parent.runId,
|
|
3838
|
-
stepId: parent.stepId,
|
|
3839
|
-
generation
|
|
3840
|
-
});
|
|
3841
|
-
await startRunInternal({
|
|
3842
|
-
flow: child,
|
|
3843
|
-
validatedInput: validated,
|
|
3844
|
-
runId: childRunId,
|
|
3845
|
-
parent
|
|
3846
|
-
});
|
|
3847
|
-
return childRunId;
|
|
3848
|
-
}
|
|
3849
|
-
async function cancelRunRecursive(runId, args) {
|
|
3850
|
-
const state = await config.store.loadRunState(runId);
|
|
3851
|
-
if (isTerminalRun(state)) {
|
|
3852
|
-
emitLog({
|
|
3853
|
-
level: "info",
|
|
3854
|
-
msg: "nagi: cancel skipped \u2014 run already terminal",
|
|
3855
|
-
attrs: { runId, status: runStatusOf(state) }
|
|
3856
|
-
});
|
|
3857
|
-
return;
|
|
3858
|
-
}
|
|
3859
|
-
const flow2 = registry.get(state.flowId);
|
|
3860
|
-
const canceledFact = Facts.flowCanceled(runId, args, clock.now());
|
|
3861
|
-
await config.store.appendFact(runId, canceledFact);
|
|
3862
|
-
const cancelError = {
|
|
3863
|
-
name: "NagiCanceledError",
|
|
3864
|
-
message: `Run ${runId} was canceled: ${args.reason}`
|
|
3865
|
-
};
|
|
3866
|
-
if (flow2 !== void 0) {
|
|
3867
|
-
const event = {
|
|
3868
|
-
runId,
|
|
3869
|
-
flowId: flow2.id,
|
|
3870
|
-
error: cancelError,
|
|
3871
|
-
at: clock.now()
|
|
3872
|
-
};
|
|
3873
|
-
await hooks.fireHook(flow2.onError, event, "flow.onError");
|
|
3874
|
-
await hooks.fireHook(config.hooks?.onFlowError, event, "onFlowError");
|
|
3875
|
-
}
|
|
3876
|
-
const children = await config.store.listChildren(runId);
|
|
3877
|
-
for (const childId of children) {
|
|
3878
|
-
await cancelRunRecursive(childId, {
|
|
3879
|
-
cause: "explicit",
|
|
3880
|
-
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
3881
|
-
note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
3882
|
-
});
|
|
3883
|
-
}
|
|
3884
|
-
await dispatcher.propagateToParent(runId, {
|
|
3885
|
-
kind: "canceled",
|
|
3886
|
-
error: cancelError
|
|
3887
|
-
});
|
|
3888
|
-
}
|
|
3889
2534
|
const dispatchDeps = {
|
|
3890
|
-
|
|
2535
|
+
resolveFlow,
|
|
3891
2536
|
lookupFlow,
|
|
3892
|
-
startChildRun,
|
|
2537
|
+
startChildRun: (args) => lifecycle.startChildRun(args),
|
|
3893
2538
|
store: config.store,
|
|
3894
2539
|
queue: config.queue,
|
|
3895
2540
|
clock,
|
|
@@ -3898,7 +2543,8 @@ async function nagiImpl(config) {
|
|
|
3898
2543
|
// a single required config here so the dispatch internals never re-check it.
|
|
3899
2544
|
heartbeat: {
|
|
3900
2545
|
intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
|
|
3901
|
-
leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS
|
|
2546
|
+
leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS,
|
|
2547
|
+
holdWarnMs: config.leaseHoldWarnMs ?? DEFAULT_LEASE_HOLD_WARN_MS
|
|
3902
2548
|
},
|
|
3903
2549
|
...compact({
|
|
3904
2550
|
hooks: config.hooks,
|
|
@@ -3908,6 +2554,18 @@ async function nagiImpl(config) {
|
|
|
3908
2554
|
};
|
|
3909
2555
|
const dispatcher = makeDispatcher(dispatchDeps);
|
|
3910
2556
|
const hooks = makeHooks(dispatchDeps);
|
|
2557
|
+
const lifecycle = makeRunLifecycle({
|
|
2558
|
+
store: config.store,
|
|
2559
|
+
queue: config.queue,
|
|
2560
|
+
clock,
|
|
2561
|
+
registry,
|
|
2562
|
+
codeVersion,
|
|
2563
|
+
queueForTx: (tx) => config.queue.withTx?.(tx) ?? config.queue,
|
|
2564
|
+
hooks,
|
|
2565
|
+
flowHooks: config.hooks,
|
|
2566
|
+
dispatcher,
|
|
2567
|
+
emitLog
|
|
2568
|
+
});
|
|
3911
2569
|
const signals = makeSignals({
|
|
3912
2570
|
dispatcher,
|
|
3913
2571
|
store: config.store,
|
|
@@ -3917,30 +2575,20 @@ async function nagiImpl(config) {
|
|
|
3917
2575
|
emitLog,
|
|
3918
2576
|
...compact({ flowHooks: config.hooks })
|
|
3919
2577
|
});
|
|
3920
|
-
const replayer = makeReplay({
|
|
3921
|
-
...dispatchDeps,
|
|
3922
|
-
registry,
|
|
3923
|
-
hashFor: (id) => flowHashById.get(id)
|
|
3924
|
-
});
|
|
2578
|
+
const replayer = makeReplay({ ...dispatchDeps, registry });
|
|
3925
2579
|
const wf = {
|
|
3926
2580
|
async start(flow2, input, opts) {
|
|
3927
2581
|
return wf.startById(flow2.id, input, opts);
|
|
3928
2582
|
},
|
|
3929
2583
|
async startById(flowId, input, opts) {
|
|
3930
|
-
const
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
runId = opts.runId;
|
|
3939
|
-
} else {
|
|
3940
|
-
runId = mintRunId();
|
|
3941
|
-
}
|
|
3942
|
-
const validated = await validate(flow2.input, input);
|
|
3943
|
-
await startRunInternal({ flow: flow2, validatedInput: validated, runId });
|
|
2584
|
+
const { runId, staged } = await lifecycle.start({
|
|
2585
|
+
flowId,
|
|
2586
|
+
input,
|
|
2587
|
+
runId: opts?.runId,
|
|
2588
|
+
boundary: { kind: "own" }
|
|
2589
|
+
});
|
|
2590
|
+
if (staged.kind === "started")
|
|
2591
|
+
await lifecycle.applyEffects(staged.effects);
|
|
3944
2592
|
return runId;
|
|
3945
2593
|
},
|
|
3946
2594
|
async startStaged(flow2, input, opts) {
|
|
@@ -3953,114 +2601,26 @@ async function nagiImpl(config) {
|
|
|
3953
2601
|
["tx"]
|
|
3954
2602
|
);
|
|
3955
2603
|
}
|
|
3956
|
-
const
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
|
|
3961
|
-
"runId"
|
|
3962
|
-
]);
|
|
3963
|
-
}
|
|
3964
|
-
runId = opts.runId;
|
|
3965
|
-
} else {
|
|
3966
|
-
runId = mintRunId();
|
|
3967
|
-
}
|
|
3968
|
-
const validated = await validate(flow2.input, input);
|
|
3969
|
-
const startedAt = clock.now();
|
|
3970
|
-
const flowHash = flowHashById.get(flow2.id);
|
|
3971
|
-
const fact = Facts.flowStarted({
|
|
3972
|
-
runId,
|
|
3973
|
-
flowId: flow2.id,
|
|
3974
|
-
input: validated,
|
|
3975
|
-
at: startedAt,
|
|
3976
|
-
codeVersion,
|
|
3977
|
-
...compact({ flowHash })
|
|
2604
|
+
const { runId, staged } = await lifecycle.start({
|
|
2605
|
+
flowId,
|
|
2606
|
+
input,
|
|
2607
|
+
runId: opts.runId,
|
|
2608
|
+
boundary: { kind: "caller", tx: opts.tx }
|
|
3978
2609
|
});
|
|
3979
|
-
|
|
3980
|
-
|
|
3981
|
-
const derived = flow2.concurrency.keyFn(validated);
|
|
3982
|
-
if (typeof derived !== "string" || derived.length === 0) {
|
|
3983
|
-
throw validationError(
|
|
3984
|
-
`flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
3985
|
-
["concurrency", "keyFn"]
|
|
3986
|
-
);
|
|
3987
|
-
}
|
|
3988
|
-
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
2610
|
+
if (staged.kind === "exists") {
|
|
2611
|
+
return { runId, started: false, canceled: [], applyOnCommit: noop };
|
|
3989
2612
|
}
|
|
3990
|
-
|
|
3991
|
-
opts.tx,
|
|
3992
|
-
runId,
|
|
3993
|
-
fact,
|
|
3994
|
-
concurrencyArg
|
|
3995
|
-
);
|
|
3996
|
-
if (started) {
|
|
3997
|
-
const seedState = foldRun(runId, [fact]);
|
|
3998
|
-
const transition = nextTransition(flow2, seedState);
|
|
3999
|
-
if (transition.kind === "dispatch") {
|
|
4000
|
-
const txQueue = bindQueueToTx(config.queue, opts.tx);
|
|
4001
|
-
for (const stepId of transition.runnable) {
|
|
4002
|
-
await txQueue.enqueue(runId, stepId);
|
|
4003
|
-
}
|
|
4004
|
-
}
|
|
4005
|
-
}
|
|
4006
|
-
let fired = false;
|
|
4007
|
-
const applyOnCommit = async () => {
|
|
4008
|
-
if (fired) return;
|
|
4009
|
-
fired = true;
|
|
4010
|
-
if (!started) return;
|
|
4011
|
-
for (const c of canceled) {
|
|
4012
|
-
const cancelError = new NagiCanceledError({
|
|
4013
|
-
runId: c.runId,
|
|
4014
|
-
canceledByRunId: runId,
|
|
4015
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
4016
|
-
});
|
|
4017
|
-
const serialized = {
|
|
4018
|
-
...serializeError(cancelError),
|
|
4019
|
-
cause: {
|
|
4020
|
-
canceledByRunId: runId,
|
|
4021
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
4022
|
-
}
|
|
4023
|
-
};
|
|
4024
|
-
const errorEvent = {
|
|
4025
|
-
runId: c.runId,
|
|
4026
|
-
flowId: flow2.id,
|
|
4027
|
-
error: serialized,
|
|
4028
|
-
at: c.fact.at
|
|
4029
|
-
};
|
|
4030
|
-
await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
|
|
4031
|
-
await hooks.fireHook(
|
|
4032
|
-
config.hooks?.onFlowError,
|
|
4033
|
-
errorEvent,
|
|
4034
|
-
"onFlowError"
|
|
4035
|
-
);
|
|
4036
|
-
await dispatcher.propagateToParent(c.runId, {
|
|
4037
|
-
kind: "canceled",
|
|
4038
|
-
error: serialized
|
|
4039
|
-
});
|
|
4040
|
-
}
|
|
4041
|
-
const startEvent = {
|
|
4042
|
-
runId,
|
|
4043
|
-
flowId: flow2.id,
|
|
4044
|
-
input: validated,
|
|
4045
|
-
at: startedAt
|
|
4046
|
-
};
|
|
4047
|
-
await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
|
|
4048
|
-
await hooks.fireHook(
|
|
4049
|
-
config.hooks?.onFlowStart,
|
|
4050
|
-
startEvent,
|
|
4051
|
-
"onFlowStart"
|
|
4052
|
-
);
|
|
4053
|
-
};
|
|
2613
|
+
let applied;
|
|
4054
2614
|
return {
|
|
4055
2615
|
runId,
|
|
4056
|
-
started,
|
|
4057
|
-
canceled:
|
|
4058
|
-
applyOnCommit
|
|
2616
|
+
started: true,
|
|
2617
|
+
canceled: staged.effects.superseded.map((e) => e.runId),
|
|
2618
|
+
applyOnCommit: () => applied ??= lifecycle.applyEffects(staged.effects)
|
|
4059
2619
|
};
|
|
4060
2620
|
},
|
|
4061
2621
|
signal: signals.signal,
|
|
4062
2622
|
async cancel(runId, opts) {
|
|
4063
|
-
await cancelRunRecursive(runId, {
|
|
2623
|
+
await lifecycle.cancelRunRecursive(runId, {
|
|
4064
2624
|
cause: "explicit",
|
|
4065
2625
|
reason: opts?.reason ?? "explicit wf.cancel()"
|
|
4066
2626
|
});
|
|
@@ -4071,7 +2631,7 @@ async function nagiImpl(config) {
|
|
|
4071
2631
|
store: config.store,
|
|
4072
2632
|
clock,
|
|
4073
2633
|
registry,
|
|
4074
|
-
cancelRunRecursive,
|
|
2634
|
+
cancelRunRecursive: lifecycle.cancelRunRecursive,
|
|
4075
2635
|
emitLog
|
|
4076
2636
|
});
|
|
4077
2637
|
},
|
|
@@ -4087,6 +2647,14 @@ async function nagiImpl(config) {
|
|
|
4087
2647
|
async describe(runId) {
|
|
4088
2648
|
return config.store.describe(runId);
|
|
4089
2649
|
},
|
|
2650
|
+
async inspectQueue(runId) {
|
|
2651
|
+
if (config.queue.inspect === void 0) {
|
|
2652
|
+
throw new NagiRuntimeError(
|
|
2653
|
+
"inspectQueue: the configured queue adapter does not implement inspect()."
|
|
2654
|
+
);
|
|
2655
|
+
}
|
|
2656
|
+
return config.queue.inspect(runId);
|
|
2657
|
+
},
|
|
4090
2658
|
async queryRuns(opts = {}) {
|
|
4091
2659
|
if (opts.latest === true) {
|
|
4092
2660
|
if (opts.limit !== void 0 || opts.cursor !== void 0) {
|
|
@@ -4143,12 +2711,6 @@ async function nagiImpl(config) {
|
|
|
4143
2711
|
});
|
|
4144
2712
|
}
|
|
4145
2713
|
};
|
|
4146
|
-
Object.defineProperty(wf, "__dispatchDeps", {
|
|
4147
|
-
value: dispatchDeps,
|
|
4148
|
-
enumerable: false,
|
|
4149
|
-
writable: false,
|
|
4150
|
-
configurable: false
|
|
4151
|
-
});
|
|
4152
2714
|
return wf;
|
|
4153
2715
|
}
|
|
4154
2716
|
async function nagiRun(config) {
|
|
@@ -4213,19 +2775,9 @@ var nagi = Object.assign(
|
|
|
4213
2775
|
nagiImpl,
|
|
4214
2776
|
{ run: nagiRun }
|
|
4215
2777
|
);
|
|
4216
|
-
function
|
|
4217
|
-
return `run-${crypto.randomUUID()}`;
|
|
4218
|
-
}
|
|
4219
|
-
function asStreamTransport(store) {
|
|
4220
|
-
const s = store;
|
|
4221
|
-
return typeof s.subscribeStream === "function" && typeof s.publishChunk === "function" ? s : void 0;
|
|
4222
|
-
}
|
|
4223
|
-
function bindQueueToTx(queue, tx) {
|
|
4224
|
-
const q = queue;
|
|
4225
|
-
if (typeof q.withTx === "function") return q.withTx(tx);
|
|
4226
|
-
return queue;
|
|
2778
|
+
async function noop() {
|
|
4227
2779
|
}
|
|
4228
2780
|
|
|
4229
|
-
export {
|
|
2781
|
+
export { NagiAbortError, RunId, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, optional, sha256Canonical };
|
|
4230
2782
|
//# sourceMappingURL=index.js.map
|
|
4231
2783
|
//# sourceMappingURL=index.js.map
|