@nagi-js/core 0.1.1-rc.10 → 0.1.1-rc.13
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/index.d.ts +296 -127
- package/dist/index.js +2277 -1511
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,42 +1,318 @@
|
|
|
1
|
+
// src/state.ts
|
|
2
|
+
var PENDING = { tag: "pending" };
|
|
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
|
+
|
|
1
253
|
// src/internal.ts
|
|
2
|
-
|
|
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");
|
|
3
283
|
function attachDef(meta, def) {
|
|
4
284
|
return { kind: meta.kind, id: meta.id, [DEF]: def };
|
|
5
285
|
}
|
|
286
|
+
function setDef(step, def) {
|
|
287
|
+
step[DEF] = def;
|
|
288
|
+
}
|
|
6
289
|
function getDef(step) {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
return def;
|
|
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;
|
|
14
297
|
}
|
|
15
298
|
function needsStepIds(def) {
|
|
16
|
-
return Object.values(def.needs).map((
|
|
299
|
+
return Object.values(def.needs).map((ref) => ref.step.id);
|
|
17
300
|
}
|
|
18
|
-
function resolveNeeds(def,
|
|
301
|
+
function resolveNeeds(def, loadResolved) {
|
|
19
302
|
const result = {};
|
|
20
|
-
for (const [localKey,
|
|
21
|
-
|
|
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);
|
|
22
306
|
}
|
|
23
307
|
return result;
|
|
24
308
|
}
|
|
25
|
-
function
|
|
26
|
-
|
|
27
|
-
for (const fact of runState.facts) {
|
|
28
|
-
if (fact.kind === "match.arm-selected" && fact.stepId === matchId) {
|
|
29
|
-
selected = fact.arm;
|
|
30
|
-
} else if (fact.kind === "step.reset" && fact.stepId === matchId) {
|
|
31
|
-
selected = null;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
return selected;
|
|
309
|
+
function asStepMapWithDefs(steps) {
|
|
310
|
+
return steps;
|
|
35
311
|
}
|
|
36
312
|
function selectArm(def, args) {
|
|
37
313
|
for (const arm of def.arms) {
|
|
38
|
-
if (arm.otherwise) return arm.id;
|
|
39
|
-
if (arm.when
|
|
314
|
+
if (arm.guard.kind === "otherwise") return arm.id;
|
|
315
|
+
if (arm.guard.when(args)) return arm.id;
|
|
40
316
|
}
|
|
41
317
|
throw new Error(
|
|
42
318
|
`match: no arm matched and no { otherwise: true } fallback was provided`
|
|
@@ -48,45 +324,77 @@ function makeBuilder() {
|
|
|
48
324
|
function task(config) {
|
|
49
325
|
const def = {
|
|
50
326
|
kind: "task",
|
|
51
|
-
needs: config.needs
|
|
52
|
-
...config.retry !== void 0 ? { retry: config.retry } : {},
|
|
53
|
-
...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
|
|
54
|
-
...config.when !== void 0 ? {
|
|
55
|
-
when: config.when
|
|
56
|
-
} : {},
|
|
327
|
+
needs: normalizeNeeds(config.needs),
|
|
57
328
|
run: config.run,
|
|
58
|
-
...
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
329
|
+
...compact({
|
|
330
|
+
retry: config.retry,
|
|
331
|
+
timeoutMs: config.timeoutMs,
|
|
332
|
+
when: config.when,
|
|
333
|
+
onStart: config.onStart,
|
|
334
|
+
onComplete: config.onComplete,
|
|
335
|
+
onError: config.onError,
|
|
336
|
+
onRetry: config.onRetry
|
|
337
|
+
})
|
|
64
338
|
};
|
|
65
339
|
return attachDef({ kind: "task", id: "" }, def);
|
|
66
340
|
}
|
|
341
|
+
function activity(config) {
|
|
342
|
+
const def = {
|
|
343
|
+
kind: "activity",
|
|
344
|
+
needs: normalizeNeeds(config.needs),
|
|
345
|
+
run: config.run,
|
|
346
|
+
...compact({
|
|
347
|
+
retry: config.retry,
|
|
348
|
+
timeoutMs: config.timeoutMs,
|
|
349
|
+
when: config.when,
|
|
350
|
+
onStart: config.onStart,
|
|
351
|
+
onComplete: config.onComplete,
|
|
352
|
+
onError: config.onError,
|
|
353
|
+
onRetry: config.onRetry
|
|
354
|
+
})
|
|
355
|
+
};
|
|
356
|
+
return attachDef({ kind: "activity", id: "" }, def);
|
|
357
|
+
}
|
|
358
|
+
function streamingTask(config) {
|
|
359
|
+
const def = {
|
|
360
|
+
kind: "streaming",
|
|
361
|
+
needs: normalizeNeeds(config.needs),
|
|
362
|
+
run: config.run,
|
|
363
|
+
...compact({
|
|
364
|
+
retry: config.retry,
|
|
365
|
+
timeoutMs: config.timeoutMs,
|
|
366
|
+
when: config.when,
|
|
367
|
+
onStart: config.onStart,
|
|
368
|
+
onComplete: config.onComplete,
|
|
369
|
+
onError: config.onError,
|
|
370
|
+
onRetry: config.onRetry
|
|
371
|
+
})
|
|
372
|
+
};
|
|
373
|
+
return attachDef({ kind: "streaming", id: "" }, def);
|
|
374
|
+
}
|
|
67
375
|
function signal(config) {
|
|
68
376
|
const def = {
|
|
69
377
|
kind: "signal",
|
|
70
|
-
needs: config.needs
|
|
378
|
+
needs: normalizeNeeds(config.needs),
|
|
71
379
|
schema: config.schema,
|
|
72
|
-
...
|
|
73
|
-
|
|
74
|
-
|
|
380
|
+
...compact({
|
|
381
|
+
names: config.names,
|
|
382
|
+
timeoutMs: config.timeoutMs,
|
|
75
383
|
when: config.when
|
|
76
|
-
}
|
|
384
|
+
})
|
|
77
385
|
};
|
|
78
386
|
return attachDef({ kind: "signal", id: "" }, def);
|
|
79
387
|
}
|
|
80
388
|
function subflow(child, config) {
|
|
81
389
|
const def = {
|
|
82
390
|
kind: "subflow",
|
|
83
|
-
needs: config.needs
|
|
391
|
+
needs: normalizeNeeds(config.needs),
|
|
84
392
|
childFlowId: child.id,
|
|
85
393
|
buildInput: config.input,
|
|
86
|
-
...
|
|
87
|
-
|
|
394
|
+
...compact({
|
|
395
|
+
timeoutMs: config.timeoutMs,
|
|
88
396
|
when: config.when
|
|
89
|
-
}
|
|
397
|
+
})
|
|
90
398
|
};
|
|
91
399
|
return attachDef(
|
|
92
400
|
{ kind: "subflow", id: "" },
|
|
@@ -94,29 +402,22 @@ function makeBuilder() {
|
|
|
94
402
|
);
|
|
95
403
|
}
|
|
96
404
|
function match(config) {
|
|
97
|
-
const needs = config.needs
|
|
405
|
+
const needs = normalizeNeeds(config.needs);
|
|
98
406
|
const arms = [];
|
|
99
407
|
for (let i = 0; i < config.arms.length; i++) {
|
|
100
408
|
const arm = config.arms[i];
|
|
101
409
|
const nested = arm.build(makeBuilder());
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
...arm.when !== void 0 ? {
|
|
106
|
-
when: arm.when
|
|
107
|
-
} : {},
|
|
108
|
-
...arm.otherwise ? { otherwise: true } : {},
|
|
109
|
-
nested
|
|
110
|
-
});
|
|
410
|
+
const guard = arm.otherwise ? { kind: "otherwise" } : { kind: "when", when: arm.when };
|
|
411
|
+
const armId = guard.kind === "otherwise" ? "otherwise" : `arm${i}`;
|
|
412
|
+
arms.push({ id: armId, guard, nested });
|
|
111
413
|
}
|
|
112
414
|
const def = { kind: "match", needs, arms };
|
|
113
|
-
return attachDef(
|
|
114
|
-
{ kind: "match", id: "" },
|
|
115
|
-
def
|
|
116
|
-
);
|
|
415
|
+
return attachDef({ kind: "match", id: "" }, def);
|
|
117
416
|
}
|
|
118
417
|
return {
|
|
119
418
|
task,
|
|
419
|
+
activity,
|
|
420
|
+
streamingTask,
|
|
120
421
|
signal,
|
|
121
422
|
subflow,
|
|
122
423
|
match
|
|
@@ -141,15 +442,18 @@ function flow(config) {
|
|
|
141
442
|
id: config.id,
|
|
142
443
|
input: config.input,
|
|
143
444
|
steps: finalSteps,
|
|
144
|
-
...
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
onComplete: config.onComplete
|
|
148
|
-
|
|
149
|
-
|
|
445
|
+
...compact({
|
|
446
|
+
output: config.output,
|
|
447
|
+
onStart: config.onStart,
|
|
448
|
+
onComplete: config.onComplete,
|
|
449
|
+
onError: config.onError
|
|
450
|
+
}),
|
|
150
451
|
...config.concurrency !== void 0 ? { concurrency: normalizeConcurrency(config.concurrency) } : {}
|
|
151
452
|
};
|
|
152
453
|
}
|
|
454
|
+
function optional(step) {
|
|
455
|
+
return { __optional: step };
|
|
456
|
+
}
|
|
153
457
|
function normalizeConcurrency(c) {
|
|
154
458
|
if (typeof c === "object") {
|
|
155
459
|
return {
|
|
@@ -167,7 +471,7 @@ function collectIds(map, prefix, idByIdentity) {
|
|
|
167
471
|
for (const [key, step] of Object.entries(map)) {
|
|
168
472
|
const id = prefix ? `${prefix}.${key}` : key;
|
|
169
473
|
idByIdentity.set(step, id);
|
|
170
|
-
const def = step
|
|
474
|
+
const def = peekDef(step);
|
|
171
475
|
if (def?.kind === "match") {
|
|
172
476
|
const pending = def;
|
|
173
477
|
for (const arm of pending.arms) {
|
|
@@ -180,7 +484,7 @@ function walkAndRewrite(args) {
|
|
|
180
484
|
const { flowId, map, prefix, parentMatch, idByIdentity, out } = args;
|
|
181
485
|
for (const [key, step] of Object.entries(map)) {
|
|
182
486
|
const id = prefix ? `${prefix}.${key}` : key;
|
|
183
|
-
const def = step
|
|
487
|
+
const def = peekDef(step);
|
|
184
488
|
if (def === void 0) {
|
|
185
489
|
throw new Error(
|
|
186
490
|
`Flow "${flowId}": step "${id}" has no internal def. Did you return a value not produced by the builder?`
|
|
@@ -192,7 +496,8 @@ function walkAndRewrite(args) {
|
|
|
192
496
|
);
|
|
193
497
|
}
|
|
194
498
|
const rewrittenNeeds = {};
|
|
195
|
-
for (const [localKey,
|
|
499
|
+
for (const [localKey, ref] of Object.entries(def.needs)) {
|
|
500
|
+
const upstream = ref.step;
|
|
196
501
|
const upstreamId = idByIdentity.get(upstream);
|
|
197
502
|
if (upstreamId === void 0) {
|
|
198
503
|
const fromOtherFlow = upstream.id !== "";
|
|
@@ -200,7 +505,10 @@ function walkAndRewrite(args) {
|
|
|
200
505
|
fromOtherFlow ? `Flow "${flowId}": step "${id}" needs an upstream step from a different flow() call (upstream id "${upstream.id}"). Steps cannot be shared between flows.` : `Flow "${flowId}": step "${id}" references an upstream step that was not returned from build(). Add it to the returned object.`
|
|
201
506
|
);
|
|
202
507
|
}
|
|
203
|
-
rewrittenNeeds[localKey] = {
|
|
508
|
+
rewrittenNeeds[localKey] = {
|
|
509
|
+
step: { ...upstream, id: upstreamId },
|
|
510
|
+
optional: ref.optional
|
|
511
|
+
};
|
|
204
512
|
}
|
|
205
513
|
if (def.kind === "match") {
|
|
206
514
|
const pending = def;
|
|
@@ -221,8 +529,7 @@ function walkAndRewrite(args) {
|
|
|
221
529
|
});
|
|
222
530
|
finalizedArms.push({
|
|
223
531
|
id: arm.id,
|
|
224
|
-
|
|
225
|
-
...arm.otherwise ? { otherwise: true } : {},
|
|
532
|
+
guard: arm.guard,
|
|
226
533
|
stepIds: nestedStepIds
|
|
227
534
|
});
|
|
228
535
|
}
|
|
@@ -230,13 +537,16 @@ function walkAndRewrite(args) {
|
|
|
230
537
|
kind: "match",
|
|
231
538
|
needs: rewrittenNeeds,
|
|
232
539
|
arms: finalizedArms,
|
|
233
|
-
...
|
|
540
|
+
...compact({ parentMatch })
|
|
234
541
|
};
|
|
235
542
|
out[id] = attachDef({ kind: "match", id }, finalizedDef2);
|
|
236
543
|
continue;
|
|
237
544
|
}
|
|
238
|
-
const
|
|
239
|
-
|
|
545
|
+
const finalizedDef = {
|
|
546
|
+
...def,
|
|
547
|
+
needs: rewrittenNeeds,
|
|
548
|
+
...compact({ parentMatch })
|
|
549
|
+
};
|
|
240
550
|
out[id] = attachDef({ kind: finalizedDef.kind, id }, finalizedDef);
|
|
241
551
|
}
|
|
242
552
|
}
|
|
@@ -246,7 +556,7 @@ function assertSignalNameUniqueness(flowId, finalSteps) {
|
|
|
246
556
|
owners.set(stepId, `step id "${stepId}"`);
|
|
247
557
|
}
|
|
248
558
|
for (const [stepId, step] of Object.entries(finalSteps)) {
|
|
249
|
-
const def = step
|
|
559
|
+
const def = peekDef(step);
|
|
250
560
|
if (def === void 0 || def.kind !== "signal") continue;
|
|
251
561
|
if (def.names === void 0) continue;
|
|
252
562
|
for (const alias of def.names) {
|
|
@@ -277,10 +587,11 @@ function warnSourceHashOnce() {
|
|
|
277
587
|
);
|
|
278
588
|
}
|
|
279
589
|
async function canonicalize(flow2) {
|
|
280
|
-
const
|
|
590
|
+
const withDefs = asStepMapWithDefs(flow2.steps);
|
|
591
|
+
const ids = Object.keys(withDefs).sort();
|
|
281
592
|
const steps = [];
|
|
282
593
|
for (const id of ids) {
|
|
283
|
-
const step =
|
|
594
|
+
const step = withDefs[id];
|
|
284
595
|
if (step === void 0) continue;
|
|
285
596
|
steps.push(await canonicalizeStep(id, getDef(step)));
|
|
286
597
|
}
|
|
@@ -293,22 +604,25 @@ async function canonicalize(flow2) {
|
|
|
293
604
|
async function canonicalizeStep(id, def) {
|
|
294
605
|
const needs = [...needsStepIds(def)].sort();
|
|
295
606
|
const base = { id, kind: def.kind, needs };
|
|
296
|
-
if (def.kind === "task"
|
|
607
|
+
if (def.kind === "task" || def.kind === "activity" || def.kind === "streaming")
|
|
608
|
+
return canonicalizeTask(base, def);
|
|
297
609
|
if (def.kind === "signal") return canonicalizeSignal(base, def);
|
|
298
610
|
if (def.kind === "subflow") return canonicalizeSubflow(base, def);
|
|
299
611
|
return canonicalizeMatch(base, def);
|
|
300
612
|
}
|
|
613
|
+
async function applyGuardAndTimeout(out, def) {
|
|
614
|
+
if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
|
|
615
|
+
if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
|
|
616
|
+
}
|
|
301
617
|
async function canonicalizeTask(base, def) {
|
|
302
618
|
const out = { ...base };
|
|
303
|
-
|
|
619
|
+
await applyGuardAndTimeout(out, def);
|
|
304
620
|
if (def.retry !== void 0) out.retry = normalizeRetry(def.retry);
|
|
305
|
-
if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
|
|
306
621
|
return out;
|
|
307
622
|
}
|
|
308
623
|
async function canonicalizeSignal(base, def) {
|
|
309
624
|
const out = { ...base };
|
|
310
|
-
|
|
311
|
-
if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
|
|
625
|
+
await applyGuardAndTimeout(out, def);
|
|
312
626
|
out.signalSchema = await canonicalizeSchema(def.schema);
|
|
313
627
|
if (def.names !== void 0) {
|
|
314
628
|
out.signalNames = [...def.names].sort();
|
|
@@ -317,8 +631,7 @@ async function canonicalizeSignal(base, def) {
|
|
|
317
631
|
}
|
|
318
632
|
async function canonicalizeSubflow(base, def) {
|
|
319
633
|
const out = { ...base };
|
|
320
|
-
|
|
321
|
-
if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
|
|
634
|
+
await applyGuardAndTimeout(out, def);
|
|
322
635
|
out.childFlowId = def.childFlowId;
|
|
323
636
|
out.subflowInputHash = await hashFnSource(def.buildInput);
|
|
324
637
|
return out;
|
|
@@ -337,8 +650,8 @@ async function canonicalizeArm(arm) {
|
|
|
337
650
|
id: arm.id,
|
|
338
651
|
stepIds: [...arm.stepIds].sort()
|
|
339
652
|
};
|
|
340
|
-
if (arm.otherwise) out.otherwise = true;
|
|
341
|
-
|
|
653
|
+
if (arm.guard.kind === "otherwise") out.otherwise = true;
|
|
654
|
+
else out.whenHash = await hashFnSource(arm.guard.when);
|
|
342
655
|
return out;
|
|
343
656
|
}
|
|
344
657
|
function normalizeRetry(retry) {
|
|
@@ -503,154 +816,671 @@ function cmp(a, b) {
|
|
|
503
816
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
504
817
|
}
|
|
505
818
|
|
|
506
|
-
// src/
|
|
507
|
-
var
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
snapshots = /* @__PURE__ */ new Map();
|
|
514
|
-
refs = /* @__PURE__ */ new Map();
|
|
515
|
-
globalFacts = [];
|
|
516
|
-
activeByKey = /* @__PURE__ */ new Map();
|
|
517
|
-
keyByActiveRun = /* @__PURE__ */ new Map();
|
|
518
|
-
childrenByParent = /* @__PURE__ */ new Map();
|
|
519
|
-
summaries = /* @__PURE__ */ new Map();
|
|
520
|
-
leaseMs;
|
|
521
|
-
constructor(opts = {}) {
|
|
522
|
-
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
523
|
-
}
|
|
524
|
-
async appendFact(runId, fact) {
|
|
525
|
-
const list = this.facts.get(runId) ?? [];
|
|
526
|
-
list.push(fact);
|
|
527
|
-
this.facts.set(runId, list);
|
|
528
|
-
if (fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled") {
|
|
529
|
-
const slot = this.keyByActiveRun.get(runId);
|
|
530
|
-
if (slot !== void 0) {
|
|
531
|
-
this.keyByActiveRun.delete(runId);
|
|
532
|
-
if (this.activeByKey.get(slot) === runId) {
|
|
533
|
-
this.activeByKey.delete(slot);
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
if (fact.kind === "step.reset") {
|
|
538
|
-
const leasePrefix = `${runId}::${fact.stepId}::`;
|
|
539
|
-
for (const key of this.leases.keys()) {
|
|
540
|
-
if (key.startsWith(leasePrefix)) this.leases.delete(key);
|
|
541
|
-
}
|
|
542
|
-
this.outputs.delete(`${runId}::${fact.stepId}`);
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
async tryStartRun(runId, fact, concurrency) {
|
|
546
|
-
if (this.facts.has(runId) || this.summaries.has(runId)) {
|
|
547
|
-
return { started: false, canceled: [] };
|
|
548
|
-
}
|
|
549
|
-
const canceled = [];
|
|
550
|
-
if (concurrency !== void 0) {
|
|
551
|
-
const slot = `${fact.flowId}::${concurrency.key}`;
|
|
552
|
-
const priorRunId = this.activeByKey.get(slot);
|
|
553
|
-
if (priorRunId !== void 0) {
|
|
554
|
-
const cancelFact = {
|
|
555
|
-
kind: "flow.canceled",
|
|
556
|
-
cause: "concurrency",
|
|
557
|
-
runId: priorRunId,
|
|
558
|
-
at: fact.at,
|
|
559
|
-
canceledByRunId: runId,
|
|
560
|
-
concurrencyKey: concurrency.key
|
|
561
|
-
};
|
|
562
|
-
await this.appendFact(priorRunId, cancelFact);
|
|
563
|
-
canceled.push({ runId: priorRunId, fact: cancelFact });
|
|
564
|
-
}
|
|
565
|
-
this.activeByKey.set(slot, runId);
|
|
566
|
-
this.keyByActiveRun.set(runId, slot);
|
|
567
|
-
}
|
|
568
|
-
this.facts.set(runId, [fact]);
|
|
569
|
-
const parentRunId = fact.parent?.runId;
|
|
570
|
-
if (parentRunId !== void 0) {
|
|
571
|
-
const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
|
|
572
|
-
set.add(runId);
|
|
573
|
-
this.childrenByParent.set(parentRunId, set);
|
|
574
|
-
}
|
|
575
|
-
return { started: true, canceled };
|
|
576
|
-
}
|
|
577
|
-
async listChildren(parentRunId) {
|
|
578
|
-
const set = this.childrenByParent.get(parentRunId);
|
|
579
|
-
if (set === void 0) return [];
|
|
580
|
-
return Array.from(set);
|
|
581
|
-
}
|
|
582
|
-
async loadRunState(runId) {
|
|
583
|
-
return projectRunState(runId, this.facts.get(runId) ?? []);
|
|
584
|
-
}
|
|
585
|
-
async claimStep(runId, stepId, attempt) {
|
|
586
|
-
const key = `${runId}::${stepId}::${attempt}`;
|
|
587
|
-
const now = Date.now();
|
|
588
|
-
const existing = this.leases.get(key);
|
|
589
|
-
if (existing && existing.expiresAt > now) {
|
|
590
|
-
return null;
|
|
591
|
-
}
|
|
592
|
-
const token = `lease-${crypto.randomUUID()}`;
|
|
593
|
-
this.leases.set(key, { token, expiresAt: now + this.leaseMs });
|
|
594
|
-
return token;
|
|
595
|
-
}
|
|
596
|
-
async completeStep(runId, stepId, output, fact) {
|
|
597
|
-
this.outputs.set(`${runId}::${stepId}`, output);
|
|
598
|
-
await this.appendFact(runId, fact);
|
|
599
|
-
}
|
|
600
|
-
async failStep(runId, _stepId, _error, fact) {
|
|
601
|
-
await this.appendFact(runId, fact);
|
|
602
|
-
}
|
|
603
|
-
async getStepOutput(runId, stepId) {
|
|
604
|
-
return this.outputs.get(`${runId}::${stepId}`) ?? null;
|
|
605
|
-
}
|
|
606
|
-
async recordOnce(runId, stepId, scope, value) {
|
|
607
|
-
this.onces.set(`${runId}::${stepId}::${scope}`, value);
|
|
608
|
-
}
|
|
609
|
-
async getOnce(runId, stepId, scope) {
|
|
610
|
-
return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
|
|
611
|
-
}
|
|
612
|
-
async runStep(runId, stepId, _attempt, body) {
|
|
613
|
-
const result = await body(void 0);
|
|
614
|
-
if (result.fact.kind === "step.completed") {
|
|
615
|
-
await this.completeStep(runId, stepId, result.output, result.fact);
|
|
616
|
-
} else if (result.fact.kind === "step.failed") {
|
|
617
|
-
await this.failStep(runId, stepId, result.fact.error, result.fact);
|
|
618
|
-
} else {
|
|
619
|
-
await this.appendFact(runId, result.fact);
|
|
620
|
-
}
|
|
621
|
-
return result.output;
|
|
622
|
-
}
|
|
623
|
-
async upsertSnapshot(args) {
|
|
624
|
-
if (this.snapshots.has(args.flowHash)) return;
|
|
625
|
-
this.snapshots.set(args.flowHash, { flowId: args.flowId, dag: args.dag });
|
|
819
|
+
// src/errors.ts
|
|
820
|
+
var NagiValidationError = class extends Error {
|
|
821
|
+
issues;
|
|
822
|
+
constructor(issues) {
|
|
823
|
+
super(issues.map((i) => i.message).join("; "));
|
|
824
|
+
this.name = "NagiValidationError";
|
|
825
|
+
this.issues = issues;
|
|
626
826
|
}
|
|
627
|
-
|
|
628
|
-
|
|
827
|
+
};
|
|
828
|
+
function validationError(message, path) {
|
|
829
|
+
return new NagiValidationError([{ message, path }]);
|
|
830
|
+
}
|
|
831
|
+
var NagiRuntimeError = class extends Error {
|
|
832
|
+
constructor(message) {
|
|
833
|
+
super(message);
|
|
834
|
+
this.name = "NagiRuntimeError";
|
|
629
835
|
}
|
|
630
|
-
|
|
631
|
-
|
|
836
|
+
};
|
|
837
|
+
var NagiCanceledError = class extends Error {
|
|
838
|
+
runId;
|
|
839
|
+
canceledByRunId;
|
|
840
|
+
concurrencyKey;
|
|
841
|
+
constructor({
|
|
842
|
+
runId,
|
|
843
|
+
canceledByRunId,
|
|
844
|
+
concurrencyKey
|
|
845
|
+
}) {
|
|
846
|
+
super(
|
|
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
|
+
};
|
|
632
857
|
}
|
|
633
|
-
|
|
634
|
-
|
|
858
|
+
};
|
|
859
|
+
var NagiSnapshotDriftError = class extends Error {
|
|
860
|
+
runId;
|
|
861
|
+
expected;
|
|
862
|
+
actual;
|
|
863
|
+
constructor({
|
|
864
|
+
runId,
|
|
865
|
+
expected,
|
|
866
|
+
actual
|
|
867
|
+
}) {
|
|
868
|
+
super(
|
|
869
|
+
`Run ${runId} was pinned to flow hash ${expected.slice(0, 12)}\u2026 but the live flow's hash is ${actual.slice(0, 12)}\u2026. Pass replayOpts.allowDrift = true to replay against the live code anyway.`
|
|
870
|
+
);
|
|
871
|
+
this.name = "NagiSnapshotDriftError";
|
|
872
|
+
this.runId = runId;
|
|
873
|
+
this.expected = expected;
|
|
874
|
+
this.actual = actual;
|
|
635
875
|
}
|
|
636
|
-
|
|
637
|
-
|
|
876
|
+
};
|
|
877
|
+
function serializeError(err) {
|
|
878
|
+
if (err instanceof Error) {
|
|
879
|
+
return {
|
|
880
|
+
name: err.name,
|
|
881
|
+
message: err.message,
|
|
882
|
+
...compact({ stack: err.stack })
|
|
883
|
+
};
|
|
638
884
|
}
|
|
639
|
-
|
|
640
|
-
|
|
885
|
+
return { name: "Error", message: String(err) };
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// src/facts.ts
|
|
889
|
+
var Facts = {
|
|
890
|
+
flowStarted(a) {
|
|
891
|
+
return {
|
|
892
|
+
kind: "flow.started",
|
|
893
|
+
runId: a.runId,
|
|
894
|
+
flowId: a.flowId,
|
|
895
|
+
input: a.input,
|
|
896
|
+
at: a.at,
|
|
897
|
+
...compact({
|
|
898
|
+
codeVersion: a.codeVersion,
|
|
899
|
+
flowHash: a.flowHash,
|
|
900
|
+
parent: a.parent
|
|
901
|
+
})
|
|
902
|
+
};
|
|
903
|
+
},
|
|
904
|
+
flowCompleted(runId, output, at) {
|
|
905
|
+
return { kind: "flow.completed", runId, output, at };
|
|
906
|
+
},
|
|
907
|
+
flowFailed(runId, error, at) {
|
|
908
|
+
return { kind: "flow.failed", runId, error, at };
|
|
909
|
+
},
|
|
910
|
+
flowCanceled(runId, args, at) {
|
|
911
|
+
return { ...args, kind: "flow.canceled", runId, at };
|
|
912
|
+
},
|
|
913
|
+
flowCanceledByConcurrency(a) {
|
|
914
|
+
return {
|
|
915
|
+
kind: "flow.canceled",
|
|
916
|
+
cause: "concurrency",
|
|
917
|
+
runId: a.runId,
|
|
918
|
+
at: a.at,
|
|
919
|
+
canceledByRunId: a.canceledByRunId,
|
|
920
|
+
concurrencyKey: a.concurrencyKey
|
|
921
|
+
};
|
|
922
|
+
},
|
|
923
|
+
stepStarted(runId, stepId, attempt, stepKind, at) {
|
|
924
|
+
return { kind: "step.started", runId, stepId, attempt, stepKind, at };
|
|
925
|
+
},
|
|
926
|
+
stepCompleted(runId, stepId, attempt, output, at) {
|
|
927
|
+
return { kind: "step.completed", runId, stepId, attempt, output, at };
|
|
928
|
+
},
|
|
929
|
+
stepFailed(runId, stepId, attempt, error, at) {
|
|
930
|
+
return { kind: "step.failed", runId, stepId, attempt, error, at };
|
|
931
|
+
},
|
|
932
|
+
stepCanceled(runId, stepId, attempt, at, error) {
|
|
933
|
+
return {
|
|
934
|
+
kind: "step.canceled",
|
|
935
|
+
runId,
|
|
936
|
+
stepId,
|
|
937
|
+
attempt,
|
|
938
|
+
at,
|
|
939
|
+
...compact({ error })
|
|
940
|
+
};
|
|
941
|
+
},
|
|
942
|
+
stepRetried(runId, stepId, attempt, nextAttemptAt, error, at) {
|
|
943
|
+
return {
|
|
944
|
+
kind: "step.retried",
|
|
945
|
+
runId,
|
|
946
|
+
stepId,
|
|
947
|
+
attempt,
|
|
948
|
+
nextAttemptAt,
|
|
949
|
+
error,
|
|
950
|
+
at
|
|
951
|
+
};
|
|
952
|
+
},
|
|
953
|
+
stepSkipped(a) {
|
|
954
|
+
return {
|
|
955
|
+
kind: "step.skipped",
|
|
956
|
+
runId: a.runId,
|
|
957
|
+
stepId: a.stepId,
|
|
958
|
+
reason: a.reason,
|
|
959
|
+
at: a.at,
|
|
960
|
+
...compact({ actor: a.actor, note: a.note })
|
|
961
|
+
};
|
|
962
|
+
},
|
|
963
|
+
stepReset(a) {
|
|
964
|
+
return {
|
|
965
|
+
kind: "step.reset",
|
|
966
|
+
runId: a.runId,
|
|
967
|
+
stepId: a.stepId,
|
|
968
|
+
at: a.at,
|
|
969
|
+
...compact({
|
|
970
|
+
cascadedFrom: a.cascadedFrom,
|
|
971
|
+
actor: a.actor,
|
|
972
|
+
note: a.note
|
|
973
|
+
})
|
|
974
|
+
};
|
|
975
|
+
},
|
|
976
|
+
stepAbortRequested(a) {
|
|
977
|
+
return {
|
|
978
|
+
kind: "step.abort-requested",
|
|
979
|
+
runId: a.runId,
|
|
980
|
+
stepId: a.stepId,
|
|
981
|
+
attempt: a.attempt,
|
|
982
|
+
actor: a.actor,
|
|
983
|
+
at: a.at,
|
|
984
|
+
...compact({ note: a.note })
|
|
985
|
+
};
|
|
986
|
+
},
|
|
987
|
+
matchArmSelected(runId, stepId, arm, at) {
|
|
988
|
+
return { kind: "match.arm-selected", runId, stepId, arm, at };
|
|
989
|
+
},
|
|
990
|
+
signalReceived(a) {
|
|
991
|
+
return {
|
|
992
|
+
kind: "signal.received",
|
|
993
|
+
runId: a.runId,
|
|
994
|
+
stepId: a.stepId,
|
|
995
|
+
payload: a.payload,
|
|
996
|
+
at: a.at,
|
|
997
|
+
...compact({ signalName: a.signalName })
|
|
998
|
+
};
|
|
999
|
+
},
|
|
1000
|
+
signalBuffered(a) {
|
|
1001
|
+
return {
|
|
1002
|
+
kind: "signal.buffered",
|
|
1003
|
+
runId: a.runId,
|
|
1004
|
+
stepId: a.stepId,
|
|
1005
|
+
payload: a.payload,
|
|
1006
|
+
at: a.at,
|
|
1007
|
+
...compact({ signalName: a.signalName })
|
|
1008
|
+
};
|
|
1009
|
+
},
|
|
1010
|
+
flowRefUpdated(a) {
|
|
1011
|
+
return {
|
|
1012
|
+
kind: "flow_ref.updated",
|
|
1013
|
+
flowId: a.flowId,
|
|
1014
|
+
from: a.from,
|
|
1015
|
+
to: a.to,
|
|
1016
|
+
at: a.at
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
// src/validate.ts
|
|
1022
|
+
async function validate(schema, value) {
|
|
1023
|
+
const result = await schema["~standard"].validate(value);
|
|
1024
|
+
if ("issues" in result && result.issues !== void 0) {
|
|
1025
|
+
throw new NagiValidationError(result.issues);
|
|
1026
|
+
}
|
|
1027
|
+
return result.value;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// src/signals.ts
|
|
1031
|
+
var NOOP = { kind: "noop", result: { tag: "noop" } };
|
|
1032
|
+
function decideSignal(args) {
|
|
1033
|
+
const { runState, stepId, at, incoming } = args;
|
|
1034
|
+
const { runId } = runState;
|
|
1035
|
+
const step = stepStateOf(runState, stepId);
|
|
1036
|
+
if (isStepTerminal(step)) return NOOP;
|
|
1037
|
+
if (step.tag === "awaitingSignal") {
|
|
1038
|
+
const source = incoming ?? runState.bufferedSignals[stepId];
|
|
1039
|
+
if (source === void 0) return NOOP;
|
|
1040
|
+
const { attempt } = step;
|
|
1041
|
+
return {
|
|
1042
|
+
kind: "deliver",
|
|
1043
|
+
attempt,
|
|
1044
|
+
received: Facts.signalReceived({
|
|
1045
|
+
runId,
|
|
1046
|
+
stepId,
|
|
1047
|
+
payload: source.payload,
|
|
1048
|
+
at,
|
|
1049
|
+
...compact({ signalName: source.signalName })
|
|
1050
|
+
}),
|
|
1051
|
+
completed: Facts.stepCompleted(
|
|
1052
|
+
runId,
|
|
1053
|
+
stepId,
|
|
1054
|
+
attempt,
|
|
1055
|
+
source.payload,
|
|
1056
|
+
at
|
|
1057
|
+
),
|
|
1058
|
+
result: {
|
|
1059
|
+
tag: "delivered",
|
|
1060
|
+
attempt,
|
|
1061
|
+
payload: source.payload,
|
|
1062
|
+
...compact({ signalName: source.signalName })
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
if (incoming === void 0) return NOOP;
|
|
1067
|
+
if (runState.bufferedSignals[stepId] !== void 0) {
|
|
1068
|
+
return { kind: "buffer", fact: null, result: { tag: "buffered" } };
|
|
1069
|
+
}
|
|
1070
|
+
return {
|
|
1071
|
+
kind: "buffer",
|
|
1072
|
+
fact: Facts.signalBuffered({
|
|
1073
|
+
runId,
|
|
1074
|
+
stepId,
|
|
1075
|
+
payload: incoming.payload,
|
|
1076
|
+
at,
|
|
1077
|
+
...compact({ signalName: incoming.signalName })
|
|
1078
|
+
}),
|
|
1079
|
+
result: { tag: "buffered" }
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
function makeSignals(deps) {
|
|
1083
|
+
const { dispatcher, store, clock, registry, hooks, flowHooks, emitLog } = deps;
|
|
1084
|
+
async function signal(runId, signalName, payload) {
|
|
1085
|
+
const runState = await store.loadRunState(runId);
|
|
1086
|
+
const flow2 = registry.requireForRun(runState.flowId, runId);
|
|
1087
|
+
const resolved = resolveSignalStep(flow2, signalName);
|
|
1088
|
+
if (resolved === null) {
|
|
1089
|
+
throw new NagiRuntimeError(
|
|
1090
|
+
`Flow "${flow2.id}" has no signal step accepting "${signalName}".`
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
const { stepId, def } = resolved;
|
|
1094
|
+
const validated = await validate(def.schema, payload);
|
|
1095
|
+
const carriesAlias = signalName !== stepId;
|
|
1096
|
+
const result = await store.settleSignal({
|
|
1097
|
+
runId,
|
|
1098
|
+
stepId,
|
|
1099
|
+
at: clock.now(),
|
|
1100
|
+
incoming: {
|
|
1101
|
+
payload: validated,
|
|
1102
|
+
...carriesAlias ? { signalName } : {}
|
|
1103
|
+
}
|
|
1104
|
+
});
|
|
1105
|
+
switch (result.tag) {
|
|
1106
|
+
case "delivered":
|
|
1107
|
+
await hooks.fireHook(
|
|
1108
|
+
flowHooks?.onSignalReceived,
|
|
1109
|
+
{
|
|
1110
|
+
runId,
|
|
1111
|
+
flowId: flow2.id,
|
|
1112
|
+
stepId,
|
|
1113
|
+
attempt: result.attempt,
|
|
1114
|
+
kind: "signal",
|
|
1115
|
+
payload: validated,
|
|
1116
|
+
at: clock.now()
|
|
1117
|
+
},
|
|
1118
|
+
"onSignalReceived"
|
|
1119
|
+
);
|
|
1120
|
+
await dispatcher.advance(runId);
|
|
1121
|
+
return;
|
|
1122
|
+
case "buffered":
|
|
1123
|
+
emitLog({
|
|
1124
|
+
level: "info",
|
|
1125
|
+
msg: "nagi: signal buffered before step ready; will apply on dispatch",
|
|
1126
|
+
attrs: { runId, stepId, signalName }
|
|
1127
|
+
});
|
|
1128
|
+
return;
|
|
1129
|
+
case "noop":
|
|
1130
|
+
emitLog({
|
|
1131
|
+
level: "info",
|
|
1132
|
+
msg: "nagi: signal arrived after step resolved",
|
|
1133
|
+
attrs: { runId, stepId, signalName }
|
|
1134
|
+
});
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
return { signal };
|
|
1139
|
+
}
|
|
1140
|
+
function resolveSignalStep(flow2, signalName) {
|
|
1141
|
+
const steps = asStepMapWithDefs(flow2.steps);
|
|
1142
|
+
const direct = steps[signalName];
|
|
1143
|
+
if (direct !== void 0) {
|
|
1144
|
+
const d = getDef(direct);
|
|
1145
|
+
if (d.kind === "signal" && d.names === void 0) {
|
|
1146
|
+
return { stepId: signalName, def: d };
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
for (const [id, s] of Object.entries(steps)) {
|
|
1150
|
+
const d = getDef(s);
|
|
1151
|
+
if (d.kind === "signal" && d.names?.includes(signalName)) {
|
|
1152
|
+
return { stepId: id, def: d };
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
return null;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
// src/stream-hub.ts
|
|
1159
|
+
var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
|
|
1160
|
+
var STREAM_REPLAY_BUFFER_CAP = 256;
|
|
1161
|
+
function makeWake() {
|
|
1162
|
+
let resolve;
|
|
1163
|
+
const promise = new Promise((r) => {
|
|
1164
|
+
resolve = r;
|
|
1165
|
+
});
|
|
1166
|
+
return { promise, resolve };
|
|
1167
|
+
}
|
|
1168
|
+
var Subscriber = class {
|
|
1169
|
+
buffer = [];
|
|
1170
|
+
pendingDropped = 0;
|
|
1171
|
+
closed = false;
|
|
1172
|
+
wake = null;
|
|
1173
|
+
push(event) {
|
|
1174
|
+
if (this.closed) return;
|
|
1175
|
+
if (this.buffer.length >= STREAM_SUBSCRIBER_BUFFER_CAP) {
|
|
1176
|
+
const idx = this.buffer.findIndex((e) => e.kind === "chunk");
|
|
1177
|
+
if (idx === -1) {
|
|
1178
|
+
if (event.kind === "chunk") {
|
|
1179
|
+
this.pendingDropped += 1;
|
|
1180
|
+
this.signal();
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
} else {
|
|
1184
|
+
this.buffer.splice(idx, 1);
|
|
1185
|
+
this.pendingDropped += 1;
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
this.buffer.push(event);
|
|
1189
|
+
this.signal();
|
|
1190
|
+
}
|
|
1191
|
+
close() {
|
|
1192
|
+
if (this.closed) return;
|
|
1193
|
+
this.closed = true;
|
|
1194
|
+
this.signal();
|
|
1195
|
+
}
|
|
1196
|
+
signal() {
|
|
1197
|
+
if (this.wake !== null) {
|
|
1198
|
+
const w = this.wake;
|
|
1199
|
+
this.wake = null;
|
|
1200
|
+
w.resolve();
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
async next() {
|
|
1204
|
+
for (; ; ) {
|
|
1205
|
+
if (this.pendingDropped > 0) {
|
|
1206
|
+
const count = this.pendingDropped;
|
|
1207
|
+
this.pendingDropped = 0;
|
|
1208
|
+
return { kind: "dropped", count };
|
|
1209
|
+
}
|
|
1210
|
+
const head = this.buffer.shift();
|
|
1211
|
+
if (head !== void 0) return head;
|
|
1212
|
+
if (this.closed) return null;
|
|
1213
|
+
const w = makeWake();
|
|
1214
|
+
this.wake = w;
|
|
1215
|
+
await w.promise;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
var InMemoryStreamHub = class _InMemoryStreamHub {
|
|
1220
|
+
channels = /* @__PURE__ */ new Map();
|
|
1221
|
+
static key(runId, stepId) {
|
|
1222
|
+
return `${runId}::${stepId}`;
|
|
1223
|
+
}
|
|
1224
|
+
getOrCreate(runId, stepId) {
|
|
1225
|
+
const key = _InMemoryStreamHub.key(runId, stepId);
|
|
1226
|
+
let channel = this.channels.get(key);
|
|
1227
|
+
if (channel === void 0) {
|
|
1228
|
+
channel = { subscribers: /* @__PURE__ */ new Set(), replay: [], closed: false };
|
|
1229
|
+
this.channels.set(key, channel);
|
|
1230
|
+
}
|
|
1231
|
+
return channel;
|
|
1232
|
+
}
|
|
1233
|
+
publishChunk(runId, stepId, chunk) {
|
|
1234
|
+
const channel = this.getOrCreate(runId, stepId);
|
|
1235
|
+
if (channel.closed) return;
|
|
1236
|
+
const event = { kind: "chunk", chunk };
|
|
1237
|
+
channel.replay.push(event);
|
|
1238
|
+
if (channel.replay.length > STREAM_REPLAY_BUFFER_CAP)
|
|
1239
|
+
channel.replay.shift();
|
|
1240
|
+
for (const sub of channel.subscribers) sub.push(event);
|
|
1241
|
+
}
|
|
1242
|
+
signalRetry(runId, stepId, attempt) {
|
|
1243
|
+
const channel = this.getOrCreate(runId, stepId);
|
|
1244
|
+
if (channel.closed) return;
|
|
1245
|
+
channel.replay.length = 0;
|
|
1246
|
+
const event = { kind: "retry", attempt };
|
|
1247
|
+
for (const sub of channel.subscribers) sub.push(event);
|
|
1248
|
+
}
|
|
1249
|
+
// NB: no-op when no channel exists. InMemoryStore.appendFact fires this for
|
|
1250
|
+
// EVERY step.completed — including non-streaming steps that never published —
|
|
1251
|
+
// so creating a channel here would leak one per such step. Closed-ness is
|
|
1252
|
+
// authoritative in the durable facts, not the hub.
|
|
1253
|
+
closeOk(runId, stepId) {
|
|
1254
|
+
const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
|
|
1255
|
+
if (channel === void 0 || channel.closed) return;
|
|
1256
|
+
channel.closed = true;
|
|
1257
|
+
channel.replay.length = 0;
|
|
1258
|
+
for (const sub of channel.subscribers) sub.close();
|
|
1259
|
+
channel.subscribers.clear();
|
|
1260
|
+
}
|
|
1261
|
+
closeError(runId, stepId, error) {
|
|
1262
|
+
const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
|
|
1263
|
+
if (channel === void 0 || channel.closed) return;
|
|
1264
|
+
channel.closed = true;
|
|
1265
|
+
channel.replay.length = 0;
|
|
1266
|
+
const event = { kind: "error", error };
|
|
1267
|
+
for (const sub of channel.subscribers) {
|
|
1268
|
+
sub.push(event);
|
|
1269
|
+
sub.close();
|
|
1270
|
+
}
|
|
1271
|
+
channel.subscribers.clear();
|
|
1272
|
+
}
|
|
1273
|
+
closeRun(runId) {
|
|
1274
|
+
const prefix = `${runId}::`;
|
|
1275
|
+
for (const [key, channel] of this.channels) {
|
|
1276
|
+
if (!key.startsWith(prefix) || channel.closed) continue;
|
|
1277
|
+
channel.closed = true;
|
|
1278
|
+
channel.replay.length = 0;
|
|
1279
|
+
for (const sub of channel.subscribers) sub.close();
|
|
1280
|
+
channel.subscribers.clear();
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
subscribeStream(runId, stepId, opts) {
|
|
1284
|
+
const channel = this.getOrCreate(runId, stepId);
|
|
1285
|
+
if (channel.closed) {
|
|
1286
|
+
return {
|
|
1287
|
+
[Symbol.asyncIterator]() {
|
|
1288
|
+
return {
|
|
1289
|
+
next: async () => ({ value: void 0, done: true })
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
const sub = new Subscriber();
|
|
1295
|
+
if (opts?.replayBuffered === true) {
|
|
1296
|
+
for (const event of channel.replay) sub.push(event);
|
|
1297
|
+
}
|
|
1298
|
+
channel.subscribers.add(sub);
|
|
1299
|
+
const remove = () => {
|
|
1300
|
+
channel.subscribers.delete(sub);
|
|
1301
|
+
};
|
|
1302
|
+
return {
|
|
1303
|
+
[Symbol.asyncIterator]() {
|
|
1304
|
+
return {
|
|
1305
|
+
next: async () => {
|
|
1306
|
+
const event = await sub.next();
|
|
1307
|
+
if (event === null) {
|
|
1308
|
+
remove();
|
|
1309
|
+
return { value: void 0, done: true };
|
|
1310
|
+
}
|
|
1311
|
+
return { value: event, done: false };
|
|
1312
|
+
},
|
|
1313
|
+
return: async () => {
|
|
1314
|
+
sub.close();
|
|
1315
|
+
remove();
|
|
1316
|
+
return { value: void 0, done: true };
|
|
1317
|
+
}
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
1323
|
+
|
|
1324
|
+
// src/memory.ts
|
|
1325
|
+
var DEFAULT_STORE_LEASE_MS = 6e4;
|
|
1326
|
+
var InMemoryStore = class {
|
|
1327
|
+
facts = /* @__PURE__ */ new Map();
|
|
1328
|
+
onces = /* @__PURE__ */ new Map();
|
|
1329
|
+
leases = /* @__PURE__ */ new Map();
|
|
1330
|
+
snapshots = /* @__PURE__ */ new Map();
|
|
1331
|
+
refs = /* @__PURE__ */ new Map();
|
|
1332
|
+
globalFacts = [];
|
|
1333
|
+
activeByKey = /* @__PURE__ */ new Map();
|
|
1334
|
+
keyByActiveRun = /* @__PURE__ */ new Map();
|
|
1335
|
+
childrenByParent = /* @__PURE__ */ new Map();
|
|
1336
|
+
summaries = /* @__PURE__ */ new Map();
|
|
1337
|
+
streamHub = new InMemoryStreamHub();
|
|
1338
|
+
leaseMs;
|
|
1339
|
+
constructor(opts = {}) {
|
|
1340
|
+
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
1341
|
+
}
|
|
1342
|
+
async appendFact(runId, fact) {
|
|
1343
|
+
const list = this.facts.get(runId) ?? [];
|
|
1344
|
+
list.push(fact);
|
|
1345
|
+
this.facts.set(runId, list);
|
|
1346
|
+
switch (fact.kind) {
|
|
1347
|
+
case "step.completed":
|
|
1348
|
+
this.streamHub.closeOk(runId, fact.stepId);
|
|
1349
|
+
break;
|
|
1350
|
+
case "step.failed":
|
|
1351
|
+
this.streamHub.closeError(runId, fact.stepId, fact.error);
|
|
1352
|
+
break;
|
|
1353
|
+
case "step.retried":
|
|
1354
|
+
this.streamHub.signalRetry(
|
|
1355
|
+
runId,
|
|
1356
|
+
fact.stepId,
|
|
1357
|
+
fact.attempt + 1
|
|
1358
|
+
);
|
|
1359
|
+
break;
|
|
1360
|
+
case "flow.completed":
|
|
1361
|
+
case "flow.failed":
|
|
1362
|
+
case "flow.canceled":
|
|
1363
|
+
this.streamHub.closeRun(runId);
|
|
1364
|
+
break;
|
|
1365
|
+
}
|
|
1366
|
+
if (fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled") {
|
|
1367
|
+
const slot = this.keyByActiveRun.get(runId);
|
|
1368
|
+
if (slot !== void 0) {
|
|
1369
|
+
this.keyByActiveRun.delete(runId);
|
|
1370
|
+
if (this.activeByKey.get(slot) === runId) {
|
|
1371
|
+
this.activeByKey.delete(slot);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
if (fact.kind === "step.reset") {
|
|
1376
|
+
const leasePrefix = `${runId}::${fact.stepId}::`;
|
|
1377
|
+
for (const key of this.leases.keys()) {
|
|
1378
|
+
if (key.startsWith(leasePrefix)) this.leases.delete(key);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
async tryStartRun(runId, fact, concurrency) {
|
|
1383
|
+
if (this.facts.has(runId) || this.summaries.has(runId)) {
|
|
1384
|
+
return { started: false, canceled: [] };
|
|
1385
|
+
}
|
|
1386
|
+
const canceled = [];
|
|
1387
|
+
if (concurrency !== void 0) {
|
|
1388
|
+
const slot = `${fact.flowId}::${concurrency.key}`;
|
|
1389
|
+
const priorRunId = this.activeByKey.get(slot);
|
|
1390
|
+
if (priorRunId !== void 0) {
|
|
1391
|
+
const cancelFact = Facts.flowCanceledByConcurrency({
|
|
1392
|
+
runId: priorRunId,
|
|
1393
|
+
at: fact.at,
|
|
1394
|
+
canceledByRunId: runId,
|
|
1395
|
+
concurrencyKey: concurrency.key
|
|
1396
|
+
});
|
|
1397
|
+
await this.appendFact(priorRunId, cancelFact);
|
|
1398
|
+
canceled.push({ runId: priorRunId, fact: cancelFact });
|
|
1399
|
+
}
|
|
1400
|
+
this.activeByKey.set(slot, runId);
|
|
1401
|
+
this.keyByActiveRun.set(runId, slot);
|
|
1402
|
+
}
|
|
1403
|
+
this.facts.set(runId, [fact]);
|
|
1404
|
+
const parentRunId = fact.parent?.runId;
|
|
1405
|
+
if (parentRunId !== void 0) {
|
|
1406
|
+
const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
|
|
1407
|
+
set.add(runId);
|
|
1408
|
+
this.childrenByParent.set(parentRunId, set);
|
|
1409
|
+
}
|
|
1410
|
+
return { started: true, canceled };
|
|
1411
|
+
}
|
|
1412
|
+
async listChildren(parentRunId) {
|
|
1413
|
+
const set = this.childrenByParent.get(parentRunId);
|
|
1414
|
+
if (set === void 0) return [];
|
|
1415
|
+
return Array.from(set);
|
|
1416
|
+
}
|
|
1417
|
+
async loadRunState(runId) {
|
|
1418
|
+
return foldRun(runId, this.facts.get(runId) ?? []);
|
|
1419
|
+
}
|
|
1420
|
+
async claimStep(runId, stepId, attempt) {
|
|
1421
|
+
const key = `${runId}::${stepId}::${attempt}`;
|
|
1422
|
+
const now = Date.now();
|
|
1423
|
+
const existing = this.leases.get(key);
|
|
1424
|
+
if (existing && existing.expiresAt > now) {
|
|
1425
|
+
return null;
|
|
1426
|
+
}
|
|
1427
|
+
const token = `lease-${crypto.randomUUID()}`;
|
|
1428
|
+
this.leases.set(key, { token, expiresAt: now + this.leaseMs });
|
|
1429
|
+
return token;
|
|
1430
|
+
}
|
|
1431
|
+
async settleStep(runId, _stepId, fact) {
|
|
1432
|
+
await this.appendFact(runId, fact);
|
|
1433
|
+
}
|
|
1434
|
+
async settleSignal(args) {
|
|
1435
|
+
const { runId, stepId, at, incoming } = args;
|
|
1436
|
+
const runState = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1437
|
+
const decision = decideSignal({ runState, stepId, at, incoming });
|
|
1438
|
+
switch (decision.kind) {
|
|
1439
|
+
case "noop":
|
|
1440
|
+
return decision.result;
|
|
1441
|
+
case "buffer":
|
|
1442
|
+
if (decision.fact !== null) await this.appendFact(runId, decision.fact);
|
|
1443
|
+
return decision.result;
|
|
1444
|
+
case "deliver":
|
|
1445
|
+
await this.appendFact(runId, decision.received);
|
|
1446
|
+
await this.appendFact(runId, decision.completed);
|
|
1447
|
+
return decision.result;
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
async recordOnce(runId, stepId, scope, value) {
|
|
1451
|
+
this.onces.set(`${runId}::${stepId}::${scope}`, value);
|
|
1452
|
+
}
|
|
1453
|
+
async getOnce(runId, stepId, scope) {
|
|
1454
|
+
return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
|
|
1455
|
+
}
|
|
1456
|
+
async runStep(runId, _stepId, _attempt, body) {
|
|
1457
|
+
const result = await body(void 0);
|
|
1458
|
+
await this.appendFact(runId, result.fact);
|
|
1459
|
+
return result.output;
|
|
1460
|
+
}
|
|
1461
|
+
async upsertSnapshot(args) {
|
|
1462
|
+
if (this.snapshots.has(args.flowHash)) return;
|
|
1463
|
+
this.snapshots.set(args.flowHash, { flowId: args.flowId, dag: args.dag });
|
|
1464
|
+
}
|
|
1465
|
+
async getRef(flowId) {
|
|
1466
|
+
return this.refs.get(flowId) ?? null;
|
|
1467
|
+
}
|
|
1468
|
+
async setRef(flowId, flowHash) {
|
|
1469
|
+
this.refs.set(flowId, flowHash);
|
|
1470
|
+
}
|
|
1471
|
+
async loadSnapshot(flowHash) {
|
|
1472
|
+
return this.snapshots.get(flowHash) ?? null;
|
|
1473
|
+
}
|
|
1474
|
+
async appendGlobalFact(fact) {
|
|
1475
|
+
this.globalFacts.push(fact);
|
|
1476
|
+
}
|
|
1477
|
+
readGlobalFacts() {
|
|
1478
|
+
return this.globalFacts;
|
|
641
1479
|
}
|
|
642
1480
|
async queryRuns(opts) {
|
|
643
1481
|
const where = opts.where ?? {};
|
|
644
|
-
const
|
|
645
|
-
const matches = (summary) =>
|
|
646
|
-
if (where.flowId !== void 0 && summary.flowId !== where.flowId)
|
|
647
|
-
return false;
|
|
648
|
-
if (statuses !== void 0 && !statuses.includes(summary.status))
|
|
649
|
-
return false;
|
|
650
|
-
if (where.input !== void 0 && !containsJson(summary.input, where.input))
|
|
651
|
-
return false;
|
|
652
|
-
return true;
|
|
653
|
-
};
|
|
1482
|
+
const wanted = where.status && new Set(where.status);
|
|
1483
|
+
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));
|
|
654
1484
|
const summaries = [];
|
|
655
1485
|
for (const [runId, factList] of this.facts) {
|
|
656
1486
|
const summary = summarize(runId, factList);
|
|
@@ -706,7 +1536,6 @@ var InMemoryStore = class {
|
|
|
706
1536
|
let factsPruned = 0;
|
|
707
1537
|
for (const v of victims) {
|
|
708
1538
|
this.facts.delete(v.runId);
|
|
709
|
-
deleteByRunPrefix(this.outputs, v.runId);
|
|
710
1539
|
deleteByRunPrefix(this.onces, v.runId);
|
|
711
1540
|
deleteByRunPrefix(this.leases, v.runId);
|
|
712
1541
|
this.childrenByParent.delete(v.runId);
|
|
@@ -727,6 +1556,23 @@ var InMemoryStore = class {
|
|
|
727
1556
|
}
|
|
728
1557
|
return { runsPruned, factsPruned };
|
|
729
1558
|
}
|
|
1559
|
+
subscribeStream(runId, stepId, opts) {
|
|
1560
|
+
const state = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1561
|
+
const stepStatus = stepStatusOf(stepStateOf(state, stepId));
|
|
1562
|
+
const runIsTerminal = isTerminalRun(state);
|
|
1563
|
+
if (runIsTerminal || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
|
|
1564
|
+
return EMPTY_CLOSED_STREAM;
|
|
1565
|
+
}
|
|
1566
|
+
return this.streamHub.subscribeStream(runId, stepId, opts);
|
|
1567
|
+
}
|
|
1568
|
+
publishChunk(runId, stepId, chunk) {
|
|
1569
|
+
this.streamHub.publishChunk(runId, stepId, chunk);
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
var EMPTY_CLOSED_STREAM = {
|
|
1573
|
+
[Symbol.asyncIterator]() {
|
|
1574
|
+
return { next: async () => ({ value: void 0, done: true }) };
|
|
1575
|
+
}
|
|
730
1576
|
};
|
|
731
1577
|
function deleteByRunPrefix(map, runId) {
|
|
732
1578
|
const prefix = `${runId}::`;
|
|
@@ -737,7 +1583,7 @@ function deleteByRunPrefix(map, runId) {
|
|
|
737
1583
|
function summarize(runId, facts) {
|
|
738
1584
|
const first = facts[0];
|
|
739
1585
|
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
740
|
-
const projected =
|
|
1586
|
+
const projected = foldRun(runId, facts);
|
|
741
1587
|
let completedAt = null;
|
|
742
1588
|
for (let i = facts.length - 1; i >= 0; i--) {
|
|
743
1589
|
const f = facts[i];
|
|
@@ -750,7 +1596,7 @@ function summarize(runId, facts) {
|
|
|
750
1596
|
return {
|
|
751
1597
|
runId,
|
|
752
1598
|
flowId: first.flowId,
|
|
753
|
-
status: projected
|
|
1599
|
+
status: runStatusOf(projected),
|
|
754
1600
|
startedAt: first.at,
|
|
755
1601
|
completedAt,
|
|
756
1602
|
input: first.input
|
|
@@ -802,82 +1648,6 @@ function containsJson(haystack, needle) {
|
|
|
802
1648
|
}
|
|
803
1649
|
return haystack === needle;
|
|
804
1650
|
}
|
|
805
|
-
function projectRunState(runId, facts) {
|
|
806
|
-
let flowId = "";
|
|
807
|
-
let status = "pending";
|
|
808
|
-
let flowHash;
|
|
809
|
-
let codeVersion;
|
|
810
|
-
const steps = {};
|
|
811
|
-
for (const fact of facts) {
|
|
812
|
-
switch (fact.kind) {
|
|
813
|
-
case "flow.started":
|
|
814
|
-
flowId = fact.flowId;
|
|
815
|
-
status = "running";
|
|
816
|
-
flowHash = fact.flowHash;
|
|
817
|
-
codeVersion = fact.codeVersion;
|
|
818
|
-
break;
|
|
819
|
-
case "flow.completed":
|
|
820
|
-
status = "completed";
|
|
821
|
-
break;
|
|
822
|
-
case "flow.failed":
|
|
823
|
-
status = "failed";
|
|
824
|
-
break;
|
|
825
|
-
case "flow.canceled":
|
|
826
|
-
status = "canceled";
|
|
827
|
-
break;
|
|
828
|
-
case "step.started":
|
|
829
|
-
steps[fact.stepId] = {
|
|
830
|
-
stepId: fact.stepId,
|
|
831
|
-
status: "running",
|
|
832
|
-
attempts: fact.attempt
|
|
833
|
-
};
|
|
834
|
-
break;
|
|
835
|
-
case "step.completed":
|
|
836
|
-
steps[fact.stepId] = {
|
|
837
|
-
stepId: fact.stepId,
|
|
838
|
-
status: "completed",
|
|
839
|
-
attempts: fact.attempt,
|
|
840
|
-
output: fact.output
|
|
841
|
-
};
|
|
842
|
-
break;
|
|
843
|
-
case "step.failed":
|
|
844
|
-
steps[fact.stepId] = {
|
|
845
|
-
stepId: fact.stepId,
|
|
846
|
-
status: "failed",
|
|
847
|
-
attempts: fact.attempt,
|
|
848
|
-
error: fact.error
|
|
849
|
-
};
|
|
850
|
-
break;
|
|
851
|
-
case "step.canceled":
|
|
852
|
-
steps[fact.stepId] = {
|
|
853
|
-
stepId: fact.stepId,
|
|
854
|
-
status: "canceled",
|
|
855
|
-
attempts: fact.attempt,
|
|
856
|
-
...fact.error !== void 0 ? { error: fact.error } : {}
|
|
857
|
-
};
|
|
858
|
-
break;
|
|
859
|
-
case "step.skipped":
|
|
860
|
-
steps[fact.stepId] = {
|
|
861
|
-
stepId: fact.stepId,
|
|
862
|
-
status: "skipped",
|
|
863
|
-
attempts: 0
|
|
864
|
-
};
|
|
865
|
-
break;
|
|
866
|
-
case "step.reset":
|
|
867
|
-
delete steps[fact.stepId];
|
|
868
|
-
break;
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
return {
|
|
872
|
-
runId,
|
|
873
|
-
flowId,
|
|
874
|
-
status,
|
|
875
|
-
steps,
|
|
876
|
-
facts,
|
|
877
|
-
...flowHash !== void 0 ? { flowHash } : {},
|
|
878
|
-
...codeVersion !== void 0 ? { codeVersion } : {}
|
|
879
|
-
};
|
|
880
|
-
}
|
|
881
1651
|
var DEFAULT_QUEUE_LEASE_MS = 6e4;
|
|
882
1652
|
var InMemoryQueue = class {
|
|
883
1653
|
pending = [];
|
|
@@ -987,149 +1757,147 @@ var InMemoryTrigger = class {
|
|
|
987
1757
|
}
|
|
988
1758
|
};
|
|
989
1759
|
|
|
990
|
-
// src/
|
|
991
|
-
function
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
})
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
}
|
|
1760
|
+
// src/exec/hooks.ts
|
|
1761
|
+
function makeHooks(deps) {
|
|
1762
|
+
async function fireHook(hook, event, hookName) {
|
|
1763
|
+
if (deps.fireHooks === false) return;
|
|
1764
|
+
if (hook === void 0) return;
|
|
1765
|
+
try {
|
|
1766
|
+
await hook(event);
|
|
1767
|
+
} catch (err) {
|
|
1768
|
+
const { message, stack } = serializeError(err);
|
|
1769
|
+
deps.emitLog({
|
|
1770
|
+
level: "error",
|
|
1771
|
+
msg: `nagi hook "${hookName}" threw \u2014 swallowed`,
|
|
1772
|
+
attrs: { error: message, ...stack !== void 0 ? { stack } : {} }
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
async function fireStepLifecycle(stepHook, flowHook, [stepName, flowName], event) {
|
|
1777
|
+
await fireHook(stepHook, event, stepName);
|
|
1778
|
+
await fireHook(flowHook, event, flowName);
|
|
1779
|
+
}
|
|
1780
|
+
return { fireHook, fireStepLifecycle };
|
|
1006
1781
|
}
|
|
1007
1782
|
|
|
1008
1783
|
// src/scheduler.ts
|
|
1009
|
-
function nextRunnable(
|
|
1010
|
-
|
|
1784
|
+
function nextRunnable({
|
|
1785
|
+
flow: flow2,
|
|
1786
|
+
runState,
|
|
1787
|
+
input
|
|
1788
|
+
}) {
|
|
1011
1789
|
const runnable = [];
|
|
1012
1790
|
const skip = [];
|
|
1013
|
-
for (const [stepId, step] of Object.entries(flow2.steps)) {
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
const upstreamCheck = checkUpstream(def, runState);
|
|
1024
|
-
if (upstreamCheck === "blocked") continue;
|
|
1025
|
-
if (upstreamCheck === "transitive-skip") {
|
|
1026
|
-
skip.push({ stepId, reason: "transitive" });
|
|
1027
|
-
continue;
|
|
1028
|
-
}
|
|
1029
|
-
const when = def.kind === "match" ? void 0 : def.when;
|
|
1030
|
-
if (when) {
|
|
1031
|
-
const needs = resolveNeeds(
|
|
1032
|
-
def,
|
|
1033
|
-
(id) => runState.steps[id]?.output ?? null
|
|
1034
|
-
);
|
|
1035
|
-
const shouldRun = when({ input, needs });
|
|
1036
|
-
if (!shouldRun) {
|
|
1037
|
-
skip.push({ stepId, reason: "when-false" });
|
|
1038
|
-
continue;
|
|
1039
|
-
}
|
|
1791
|
+
for (const [stepId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
1792
|
+
if (stepStateOf(runState, stepId).tag !== "pending") continue;
|
|
1793
|
+
const gate = gateStep(getDef(step), runState, input);
|
|
1794
|
+
switch (gate.kind) {
|
|
1795
|
+
case "run":
|
|
1796
|
+
runnable.push(stepId);
|
|
1797
|
+
break;
|
|
1798
|
+
case "skip":
|
|
1799
|
+
skip.push({ stepId, reason: gate.reason });
|
|
1800
|
+
break;
|
|
1040
1801
|
}
|
|
1041
|
-
runnable.push(stepId);
|
|
1042
1802
|
}
|
|
1043
1803
|
return { runnable, skip };
|
|
1044
1804
|
}
|
|
1805
|
+
function gateStep(def, runState, input) {
|
|
1806
|
+
const parent = checkParentMatch(def, runState);
|
|
1807
|
+
if (parent !== "ready") return gateFor(parent);
|
|
1808
|
+
const upstream = checkUpstream(def, runState);
|
|
1809
|
+
if (upstream !== "ready") return gateFor(upstream);
|
|
1810
|
+
const when = def.kind === "match" ? void 0 : def.when;
|
|
1811
|
+
if (when) {
|
|
1812
|
+
const needs = resolveNeeds(
|
|
1813
|
+
def,
|
|
1814
|
+
(id) => resolvedOf(stepStateOf(runState, id))
|
|
1815
|
+
);
|
|
1816
|
+
if (!when({ input, needs })) return { kind: "skip", reason: "when-false" };
|
|
1817
|
+
}
|
|
1818
|
+
return { kind: "run" };
|
|
1819
|
+
}
|
|
1820
|
+
function gateFor(status) {
|
|
1821
|
+
switch (status) {
|
|
1822
|
+
case "blocked":
|
|
1823
|
+
return { kind: "block" };
|
|
1824
|
+
case "transitive-skip":
|
|
1825
|
+
return { kind: "skip", reason: "transitive" };
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1045
1828
|
function checkUpstream(def, runState) {
|
|
1046
|
-
for (const
|
|
1047
|
-
const upstreamState = runState.
|
|
1048
|
-
if (upstreamState ===
|
|
1049
|
-
if (upstreamState.
|
|
1050
|
-
if (upstreamState.
|
|
1051
|
-
if (manualSkipCascade(upstream.id, runState) === "continue") continue;
|
|
1052
|
-
return "transitive-skip";
|
|
1053
|
-
}
|
|
1054
|
-
if (upstreamState.status === "failed") {
|
|
1829
|
+
for (const ref of Object.values(def.needs)) {
|
|
1830
|
+
const upstreamState = stepStateOf(runState, ref.step.id);
|
|
1831
|
+
if (upstreamState.tag === "completed") continue;
|
|
1832
|
+
if (ref.optional && upstreamState.tag === "skipped") continue;
|
|
1833
|
+
if (upstreamState.tag === "skipped" || upstreamState.tag === "failed") {
|
|
1055
1834
|
return "transitive-skip";
|
|
1056
1835
|
}
|
|
1057
1836
|
return "blocked";
|
|
1058
1837
|
}
|
|
1059
1838
|
return "ready";
|
|
1060
1839
|
}
|
|
1061
|
-
function manualSkipCascade(stepId, runState) {
|
|
1062
|
-
for (let i = runState.facts.length - 1; i >= 0; i--) {
|
|
1063
|
-
const f = runState.facts[i];
|
|
1064
|
-
if (f === void 0) continue;
|
|
1065
|
-
if (f.kind !== "step.skipped") continue;
|
|
1066
|
-
if (f.stepId !== stepId) continue;
|
|
1067
|
-
if (f.reason !== "manual") return "skip";
|
|
1068
|
-
return f.cascade ?? "skip";
|
|
1069
|
-
}
|
|
1070
|
-
return "skip";
|
|
1071
|
-
}
|
|
1072
1840
|
function checkParentMatch(def, runState) {
|
|
1073
1841
|
if (!def.parentMatch) return "ready";
|
|
1074
1842
|
const { matchId, armId } = def.parentMatch;
|
|
1075
|
-
const parentState = runState
|
|
1076
|
-
if (parentState
|
|
1843
|
+
const parentState = stepStateOf(runState, matchId);
|
|
1844
|
+
if (parentState.tag === "failed" || parentState.tag === "skipped") {
|
|
1077
1845
|
return "transitive-skip";
|
|
1078
1846
|
}
|
|
1079
|
-
const selected =
|
|
1847
|
+
const selected = runState.selectedArms[matchId] ?? null;
|
|
1080
1848
|
if (selected === null) return "blocked";
|
|
1081
1849
|
return selected === armId ? "ready" : "transitive-skip";
|
|
1082
1850
|
}
|
|
1083
1851
|
function aggregateMatch(matchId, flow2, runState) {
|
|
1084
|
-
const step = flow2.steps[matchId];
|
|
1852
|
+
const step = asStepMapWithDefs(flow2.steps)[matchId];
|
|
1085
1853
|
if (!step) return { kind: "pending" };
|
|
1086
1854
|
const def = getDef(step);
|
|
1087
1855
|
if (def.kind !== "match") return { kind: "pending" };
|
|
1088
|
-
const selected =
|
|
1856
|
+
const selected = runState.selectedArms[matchId] ?? null;
|
|
1089
1857
|
if (selected === null) return { kind: "pending" };
|
|
1090
1858
|
const arm = def.arms.find((a) => a.id === selected);
|
|
1091
1859
|
if (!arm) return { kind: "pending" };
|
|
1860
|
+
for (const stepId of arm.stepIds) {
|
|
1861
|
+
const state = stepStateOf(runState, stepId);
|
|
1862
|
+
if (state.tag === "failed")
|
|
1863
|
+
return { kind: "fail-fast", error: state.error };
|
|
1864
|
+
}
|
|
1092
1865
|
const output = {};
|
|
1093
|
-
let allTerminal = true;
|
|
1094
|
-
const stripPrefix = `${matchId}.${arm.id}.`;
|
|
1095
1866
|
for (const stepId of arm.stepIds) {
|
|
1096
|
-
const state = runState
|
|
1097
|
-
if (state
|
|
1098
|
-
|
|
1099
|
-
continue;
|
|
1100
|
-
}
|
|
1101
|
-
if (state.status === "failed") {
|
|
1102
|
-
return { kind: "fail-fast", failedStepId: stepId };
|
|
1103
|
-
}
|
|
1104
|
-
const localKey = stepId.startsWith(stripPrefix) ? stepId.slice(stripPrefix.length) : stepId;
|
|
1105
|
-
output[localKey] = state.status === "completed" ? state.output ?? null : null;
|
|
1867
|
+
const state = stepStateOf(runState, stepId);
|
|
1868
|
+
if (!isStepTerminal(state)) return { kind: "pending" };
|
|
1869
|
+
output[stripArmPrefix(matchId, arm.id, stepId)] = outputOf(state);
|
|
1106
1870
|
}
|
|
1107
|
-
if (!allTerminal) return { kind: "pending" };
|
|
1108
1871
|
return { kind: "complete", output };
|
|
1109
1872
|
}
|
|
1873
|
+
function stripArmPrefix(matchId, armId, stepId) {
|
|
1874
|
+
const prefix = `${matchId}.${armId}.`;
|
|
1875
|
+
if (stepId.startsWith(prefix)) return stepId.slice(prefix.length);
|
|
1876
|
+
return stepId;
|
|
1877
|
+
}
|
|
1110
1878
|
function flowTermination(flow2, runState) {
|
|
1111
|
-
let
|
|
1112
|
-
let failed = false;
|
|
1879
|
+
let failure;
|
|
1113
1880
|
for (const stepId of Object.keys(flow2.steps)) {
|
|
1114
|
-
const state = runState
|
|
1115
|
-
if (state
|
|
1116
|
-
|
|
1117
|
-
break;
|
|
1118
|
-
}
|
|
1119
|
-
if (state.status === "failed") failed = true;
|
|
1881
|
+
const state = stepStateOf(runState, stepId);
|
|
1882
|
+
if (!isStepTerminal(state)) return { kind: "running" };
|
|
1883
|
+
if (state.tag === "failed" && failure === void 0) failure = state.error;
|
|
1120
1884
|
}
|
|
1121
|
-
return {
|
|
1885
|
+
if (failure !== void 0) return { kind: "failed", error: failure };
|
|
1886
|
+
return { kind: "succeeded" };
|
|
1122
1887
|
}
|
|
1123
1888
|
function nextTransition(flow2, runState) {
|
|
1124
1889
|
const promotions = readyPromotions(flow2, runState);
|
|
1125
1890
|
if (promotions.length > 0) return { kind: "promote-match", promotions };
|
|
1126
1891
|
const term = flowTermination(flow2, runState);
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1892
|
+
switch (term.kind) {
|
|
1893
|
+
case "succeeded":
|
|
1894
|
+
case "failed": {
|
|
1895
|
+
if (isTerminalRun(runState)) return { kind: "settled" };
|
|
1896
|
+
if (term.kind === "failed") return { kind: "fail", error: term.error };
|
|
1897
|
+
return { kind: "complete", output: computeFlowOutput(flow2, runState) };
|
|
1898
|
+
}
|
|
1131
1899
|
}
|
|
1132
|
-
const input =
|
|
1900
|
+
const input = runState.input;
|
|
1133
1901
|
const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
|
|
1134
1902
|
if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
|
|
1135
1903
|
if (skip.length > 0) return { kind: "skip", skip };
|
|
@@ -1137,24 +1905,19 @@ function nextTransition(flow2, runState) {
|
|
|
1137
1905
|
}
|
|
1138
1906
|
function readyPromotions(flow2, runState) {
|
|
1139
1907
|
const out = [];
|
|
1140
|
-
for (const [matchId, step] of Object.entries(flow2.steps)) {
|
|
1908
|
+
for (const [matchId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
1141
1909
|
const def = getDef(step);
|
|
1142
1910
|
if (def.kind !== "match") continue;
|
|
1143
|
-
const state = runState
|
|
1144
|
-
if (state
|
|
1911
|
+
const state = stepStateOf(runState, matchId);
|
|
1912
|
+
if (state.tag !== "running") continue;
|
|
1145
1913
|
const agg = aggregateMatch(matchId, flow2, runState);
|
|
1146
1914
|
if (agg.kind === "pending") continue;
|
|
1147
|
-
const attempt = state
|
|
1915
|
+
const attempt = attemptOf(state);
|
|
1148
1916
|
if (agg.kind === "fail-fast") {
|
|
1149
|
-
const failedNested = runState.steps[agg.failedStepId];
|
|
1150
|
-
const error = failedNested?.error ?? {
|
|
1151
|
-
name: "Error",
|
|
1152
|
-
message: `match "${matchId}": chosen-arm step "${agg.failedStepId}" failed`
|
|
1153
|
-
};
|
|
1154
1917
|
out.push({
|
|
1155
1918
|
matchId,
|
|
1156
1919
|
attempt,
|
|
1157
|
-
result: { kind: "fail", error }
|
|
1920
|
+
result: { kind: "fail", error: agg.error }
|
|
1158
1921
|
});
|
|
1159
1922
|
} else {
|
|
1160
1923
|
out.push({
|
|
@@ -1166,26 +1929,11 @@ function readyPromotions(flow2, runState) {
|
|
|
1166
1929
|
}
|
|
1167
1930
|
return out;
|
|
1168
1931
|
}
|
|
1169
|
-
function flowFailureError(runState) {
|
|
1170
|
-
const failedStep = Object.values(runState.steps).find(
|
|
1171
|
-
(s) => s.status === "failed"
|
|
1172
|
-
);
|
|
1173
|
-
return failedStep?.error ?? { name: "Error", message: "step failed" };
|
|
1174
|
-
}
|
|
1175
|
-
function isFlowTerminal(facts) {
|
|
1176
|
-
for (let i = facts.length - 1; i >= 0; i--) {
|
|
1177
|
-
const f = facts[i];
|
|
1178
|
-
if (f !== void 0 && (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled")) {
|
|
1179
|
-
return true;
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
return false;
|
|
1183
|
-
}
|
|
1184
1932
|
function computeFlowOutput(flow2, runState) {
|
|
1185
1933
|
if (flow2.output === void 0) return null;
|
|
1186
1934
|
const stepOutputs = {};
|
|
1187
1935
|
for (const [sid, sstate] of Object.entries(runState.steps)) {
|
|
1188
|
-
if (sstate.
|
|
1936
|
+
if (sstate.tag === "completed") stepOutputs[sid] = sstate.output;
|
|
1189
1937
|
}
|
|
1190
1938
|
return flow2.output(stepOutputs);
|
|
1191
1939
|
}
|
|
@@ -1196,7 +1944,7 @@ function descendantsOf(flow2, stepId) {
|
|
|
1196
1944
|
if (bucket) bucket.push(to);
|
|
1197
1945
|
else children.set(from, [to]);
|
|
1198
1946
|
};
|
|
1199
|
-
for (const [id, step] of Object.entries(flow2.steps)) {
|
|
1947
|
+
for (const [id, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
1200
1948
|
const def = getDef(step);
|
|
1201
1949
|
for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
|
|
1202
1950
|
if (def.kind === "match") {
|
|
@@ -1219,214 +1967,64 @@ function descendantsOf(flow2, stepId) {
|
|
|
1219
1967
|
}
|
|
1220
1968
|
return out;
|
|
1221
1969
|
}
|
|
1222
|
-
function extractInput(runState) {
|
|
1223
|
-
for (const fact of runState.facts) {
|
|
1224
|
-
if (fact.kind === "flow.started") return fact.input;
|
|
1225
|
-
}
|
|
1226
|
-
throw new Error(
|
|
1227
|
-
"No flow.started fact in run \u2014 was the run initialized via wf.start?"
|
|
1228
|
-
);
|
|
1229
|
-
}
|
|
1230
1970
|
|
|
1231
|
-
// src/
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
if (hook === void 0) return;
|
|
1235
|
-
try {
|
|
1236
|
-
await hook(event);
|
|
1237
|
-
} catch (err) {
|
|
1238
|
-
const { message, stack } = serializeError(err);
|
|
1239
|
-
deps.logger?.error(`nagi hook "${hookName}" threw \u2014 swallowed`, {
|
|
1240
|
-
error: message,
|
|
1241
|
-
...stack !== void 0 ? { stack } : {}
|
|
1242
|
-
});
|
|
1243
|
-
}
|
|
1971
|
+
// src/idempotency.ts
|
|
1972
|
+
function makeIdempotencyKey(runId, stepId) {
|
|
1973
|
+
return (scope) => `nagi:${runId}:${stepId}:${scope}`;
|
|
1244
1974
|
}
|
|
1975
|
+
function makeOnce({
|
|
1976
|
+
runId,
|
|
1977
|
+
stepId,
|
|
1978
|
+
store
|
|
1979
|
+
}) {
|
|
1980
|
+
return async function once(scope, fn) {
|
|
1981
|
+
const cached = await store.getOnce(runId, stepId, scope);
|
|
1982
|
+
if (cached !== null) return cached;
|
|
1983
|
+
const value = await fn();
|
|
1984
|
+
await store.recordOnce(runId, stepId, scope, value);
|
|
1985
|
+
return value;
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
// src/step-exec.ts
|
|
1245
1990
|
var DEFAULT_RETRY2 = {
|
|
1246
1991
|
maxAttempts: 3,
|
|
1247
1992
|
backoff: "exponential",
|
|
1248
1993
|
initialDelayMs: 1e3,
|
|
1249
1994
|
maxDelayMs: 6e4
|
|
1250
1995
|
};
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
`dispatch: step "${stepId}" not in flow "${flow2.id}"; ack and skip`
|
|
1996
|
+
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
1997
|
+
var NagiAbortError = class extends Error {
|
|
1998
|
+
runId;
|
|
1999
|
+
scope;
|
|
2000
|
+
constructor(runId, scope) {
|
|
2001
|
+
super(
|
|
2002
|
+
scope === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
|
|
1259
2003
|
);
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
const def = getDef(step);
|
|
1264
|
-
const preState = await store.loadRunState(runId);
|
|
1265
|
-
if (preState.status === "canceled") {
|
|
1266
|
-
await queue.ack(message.receipt);
|
|
1267
|
-
return;
|
|
2004
|
+
this.name = "NagiAbortError";
|
|
2005
|
+
this.runId = runId;
|
|
2006
|
+
this.scope = scope;
|
|
1268
2007
|
}
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
2008
|
+
};
|
|
2009
|
+
function resolveExecutionFact(args) {
|
|
2010
|
+
const { postState, runId, stepId, attempt, output, at } = args;
|
|
2011
|
+
if (postState.phase.tag === "canceled") {
|
|
2012
|
+
return {
|
|
2013
|
+
fact: Facts.stepCanceled(runId, stepId, attempt, at),
|
|
2014
|
+
abortedHere: false
|
|
2015
|
+
};
|
|
1273
2016
|
}
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
2017
|
+
if (isAbortRequested(stepStateOf(postState, stepId), attempt)) {
|
|
2018
|
+
return {
|
|
2019
|
+
fact: Facts.stepCanceled(runId, stepId, attempt, at),
|
|
2020
|
+
abortedHere: true
|
|
2021
|
+
};
|
|
1278
2022
|
}
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
stepId,
|
|
1283
|
-
attempt,
|
|
1284
|
-
at: clock.now()
|
|
1285
|
-
});
|
|
1286
|
-
const startEventInput = def.kind === "task" || def.kind === "subflow" ? extractInput(await store.loadRunState(runId)) : null;
|
|
1287
|
-
const startEvent = {
|
|
1288
|
-
runId,
|
|
1289
|
-
flowId: flow2.id,
|
|
1290
|
-
stepId,
|
|
1291
|
-
attempt,
|
|
1292
|
-
kind: def.kind,
|
|
1293
|
-
input: startEventInput,
|
|
1294
|
-
at: clock.now()
|
|
2023
|
+
return {
|
|
2024
|
+
fact: Facts.stepCompleted(runId, stepId, attempt, output, at),
|
|
2025
|
+
abortedHere: false
|
|
1295
2026
|
};
|
|
1296
|
-
const stepOnStart = def.kind === "task" ? def.onStart : void 0;
|
|
1297
|
-
await fireHook(stepOnStart, startEvent, "step.onStart", deps);
|
|
1298
|
-
await fireHook(deps.hooks?.onStepStart, startEvent, "onStepStart", deps);
|
|
1299
|
-
const startedAt = Date.now();
|
|
1300
|
-
try {
|
|
1301
|
-
if (def.kind === "task") {
|
|
1302
|
-
const { output, skipAdvance } = await executeTask({
|
|
1303
|
-
deps,
|
|
1304
|
-
message,
|
|
1305
|
-
def,
|
|
1306
|
-
runId,
|
|
1307
|
-
stepId,
|
|
1308
|
-
attempt
|
|
1309
|
-
});
|
|
1310
|
-
if (skipAdvance) return;
|
|
1311
|
-
const completeEvent = {
|
|
1312
|
-
runId,
|
|
1313
|
-
flowId: flow2.id,
|
|
1314
|
-
stepId,
|
|
1315
|
-
attempt,
|
|
1316
|
-
kind: "task",
|
|
1317
|
-
output,
|
|
1318
|
-
durationMs: Date.now() - startedAt,
|
|
1319
|
-
at: clock.now()
|
|
1320
|
-
};
|
|
1321
|
-
await fireHook(def.onComplete, completeEvent, "step.onComplete", deps);
|
|
1322
|
-
await fireHook(
|
|
1323
|
-
deps.hooks?.onStepComplete,
|
|
1324
|
-
completeEvent,
|
|
1325
|
-
"onStepComplete",
|
|
1326
|
-
deps
|
|
1327
|
-
);
|
|
1328
|
-
await advance(deps, runId);
|
|
1329
|
-
} else if (def.kind === "signal") {
|
|
1330
|
-
await queue.ack(message.receipt);
|
|
1331
|
-
return;
|
|
1332
|
-
} else if (def.kind === "match") {
|
|
1333
|
-
await executeMatch({ deps, message, def, runId, stepId, attempt });
|
|
1334
|
-
await advance(deps, runId);
|
|
1335
|
-
} else if (def.kind === "subflow") {
|
|
1336
|
-
await executeSubflow({ deps, message, def, runId, stepId });
|
|
1337
|
-
await queue.ack(message.receipt);
|
|
1338
|
-
return;
|
|
1339
|
-
}
|
|
1340
|
-
} catch (err) {
|
|
1341
|
-
await handleStepError({
|
|
1342
|
-
deps,
|
|
1343
|
-
flow: flow2,
|
|
1344
|
-
message,
|
|
1345
|
-
def,
|
|
1346
|
-
runId,
|
|
1347
|
-
stepId,
|
|
1348
|
-
attempt,
|
|
1349
|
-
err
|
|
1350
|
-
});
|
|
1351
|
-
}
|
|
1352
|
-
}
|
|
1353
|
-
async function executeTask(args) {
|
|
1354
|
-
const { deps, message, def, runId, stepId, attempt } = args;
|
|
1355
|
-
if (def.kind !== "task") {
|
|
1356
|
-
throw new Error(`executeTask called with non-task def (kind: ${def.kind})`);
|
|
1357
|
-
}
|
|
1358
|
-
const { store, queue, clock } = deps;
|
|
1359
|
-
const runState = await store.loadRunState(runId);
|
|
1360
|
-
const input = extractInput(runState);
|
|
1361
|
-
const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
|
|
1362
|
-
const ac = new AbortController();
|
|
1363
|
-
const watcher = startCancelWatcher({
|
|
1364
|
-
store,
|
|
1365
|
-
runId,
|
|
1366
|
-
stepId,
|
|
1367
|
-
attempt,
|
|
1368
|
-
ac,
|
|
1369
|
-
intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
|
|
1370
|
-
});
|
|
1371
|
-
try {
|
|
1372
|
-
let stepAbortedHere = false;
|
|
1373
|
-
const output = await store.runStep(
|
|
1374
|
-
runId,
|
|
1375
|
-
stepId,
|
|
1376
|
-
attempt,
|
|
1377
|
-
async (tx) => {
|
|
1378
|
-
const ctx = makeStepCtx({
|
|
1379
|
-
runId,
|
|
1380
|
-
stepId,
|
|
1381
|
-
attempt,
|
|
1382
|
-
input,
|
|
1383
|
-
store,
|
|
1384
|
-
clock,
|
|
1385
|
-
tx,
|
|
1386
|
-
signal: ac.signal,
|
|
1387
|
-
...deps.logger !== void 0 ? { logger: deps.logger } : {}
|
|
1388
|
-
});
|
|
1389
|
-
const out = await def.run({ input, needs, ctx });
|
|
1390
|
-
const postState = await store.loadRunState(runId);
|
|
1391
|
-
if (postState.status === "canceled") {
|
|
1392
|
-
const canceledFact = {
|
|
1393
|
-
kind: "step.canceled",
|
|
1394
|
-
runId,
|
|
1395
|
-
stepId,
|
|
1396
|
-
attempt,
|
|
1397
|
-
at: clock.now()
|
|
1398
|
-
};
|
|
1399
|
-
return { output: out, fact: canceledFact };
|
|
1400
|
-
}
|
|
1401
|
-
if (hasAbortRequest(postState.facts, stepId, attempt)) {
|
|
1402
|
-
stepAbortedHere = true;
|
|
1403
|
-
const canceledFact = {
|
|
1404
|
-
kind: "step.canceled",
|
|
1405
|
-
runId,
|
|
1406
|
-
stepId,
|
|
1407
|
-
attempt,
|
|
1408
|
-
at: clock.now()
|
|
1409
|
-
};
|
|
1410
|
-
return { output: out, fact: canceledFact };
|
|
1411
|
-
}
|
|
1412
|
-
const fact = {
|
|
1413
|
-
kind: "step.completed",
|
|
1414
|
-
runId,
|
|
1415
|
-
stepId,
|
|
1416
|
-
attempt,
|
|
1417
|
-
output: out,
|
|
1418
|
-
at: clock.now()
|
|
1419
|
-
};
|
|
1420
|
-
return { output: out, fact };
|
|
1421
|
-
}
|
|
1422
|
-
);
|
|
1423
|
-
await queue.ack(message.receipt);
|
|
1424
|
-
return { output, skipAdvance: stepAbortedHere };
|
|
1425
|
-
} finally {
|
|
1426
|
-
watcher.stop();
|
|
1427
|
-
}
|
|
1428
2027
|
}
|
|
1429
|
-
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
1430
2028
|
function startCancelWatcher(args) {
|
|
1431
2029
|
const { store, runId, stepId, attempt, ac, intervalMs } = args;
|
|
1432
2030
|
let stopped = false;
|
|
@@ -1436,11 +2034,11 @@ function startCancelWatcher(args) {
|
|
|
1436
2034
|
if (stopped) return;
|
|
1437
2035
|
try {
|
|
1438
2036
|
const s = await store.loadRunState(runId);
|
|
1439
|
-
if (s
|
|
2037
|
+
if (isTerminalRun(s)) {
|
|
1440
2038
|
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
|
|
1441
2039
|
return;
|
|
1442
2040
|
}
|
|
1443
|
-
if (
|
|
2041
|
+
if (isAbortRequested(stepStateOf(s, stepId), attempt)) {
|
|
1444
2042
|
if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
|
|
1445
2043
|
return;
|
|
1446
2044
|
}
|
|
@@ -1454,390 +2052,960 @@ function startCancelWatcher(args) {
|
|
|
1454
2052
|
}
|
|
1455
2053
|
};
|
|
1456
2054
|
}
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
2055
|
+
var DEFAULT_HEARTBEAT_LEASE_MS = 12e4;
|
|
2056
|
+
var DEFAULT_HEARTBEAT_INTERVAL_MS = 4e4;
|
|
2057
|
+
function startHeartbeat(args) {
|
|
2058
|
+
const { queue, receipt, intervalMs, leaseMs, emitLog } = args;
|
|
2059
|
+
let stopped = false;
|
|
2060
|
+
let timer;
|
|
2061
|
+
const schedule = () => {
|
|
2062
|
+
timer = setTimeout(() => {
|
|
2063
|
+
void (async () => {
|
|
2064
|
+
try {
|
|
2065
|
+
await queue.extend(receipt, leaseMs);
|
|
2066
|
+
} catch (err) {
|
|
2067
|
+
emitLog({
|
|
2068
|
+
level: "warn",
|
|
2069
|
+
msg: "heartbeat: failed to extend message visibility",
|
|
2070
|
+
attrs: { receipt, error: String(err) }
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
if (!stopped) schedule();
|
|
2074
|
+
})();
|
|
2075
|
+
}, intervalMs);
|
|
2076
|
+
};
|
|
2077
|
+
schedule();
|
|
2078
|
+
return {
|
|
2079
|
+
// Clear the pending timer so a settled step strands nothing on the event
|
|
2080
|
+
// loop — without this every fast step would leak a timer for up to
|
|
2081
|
+
// intervalMs, keeping the process alive and delaying clean shutdown.
|
|
2082
|
+
stop: () => {
|
|
2083
|
+
stopped = true;
|
|
2084
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1464
2085
|
}
|
|
1465
|
-
}
|
|
1466
|
-
return false;
|
|
2086
|
+
};
|
|
1467
2087
|
}
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
this.scope = scope;
|
|
2088
|
+
function classifyFailure(args) {
|
|
2089
|
+
const { attempt, policy, err, runIsCanceled, stepAborted } = args;
|
|
2090
|
+
if (runIsCanceled || stepAborted) {
|
|
2091
|
+
const isAbort = err instanceof NagiAbortError || err instanceof Error && err.name === "AbortError";
|
|
2092
|
+
return {
|
|
2093
|
+
tag: "canceled",
|
|
2094
|
+
advanceAfter: !stepAborted,
|
|
2095
|
+
includeError: isAbort
|
|
2096
|
+
};
|
|
1478
2097
|
}
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
const { deps, message, def, runId, stepId } = args;
|
|
1482
|
-
const { store } = deps;
|
|
1483
|
-
const child = deps.lookupFlow(def.childFlowId);
|
|
1484
|
-
if (child === void 0) {
|
|
1485
|
-
throw new Error(
|
|
1486
|
-
`Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
|
|
1487
|
-
);
|
|
2098
|
+
if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
|
|
2099
|
+
return { tag: "retry", delayMs: computeBackoff(policy, attempt) };
|
|
1488
2100
|
}
|
|
1489
|
-
|
|
1490
|
-
const parentInput = extractInput(runState);
|
|
1491
|
-
const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
|
|
1492
|
-
const childInput = def.buildInput({ input: parentInput, needs });
|
|
1493
|
-
await deps.startChildRun({
|
|
1494
|
-
child,
|
|
1495
|
-
childInput,
|
|
1496
|
-
parent: { runId, stepId, attempt: message.attempt }
|
|
1497
|
-
});
|
|
2101
|
+
return { tag: "failed" };
|
|
1498
2102
|
}
|
|
1499
|
-
|
|
1500
|
-
const
|
|
1501
|
-
const
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
2103
|
+
function computeBackoff(policy, attempt) {
|
|
2104
|
+
const initial = policy.initialDelayMs ?? 1e3;
|
|
2105
|
+
const max = policy.maxDelayMs ?? 6e4;
|
|
2106
|
+
switch (policy.backoff) {
|
|
2107
|
+
case "exponential":
|
|
2108
|
+
return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
|
|
2109
|
+
case "linear":
|
|
2110
|
+
return Math.min(initial * Math.max(1, attempt), max);
|
|
2111
|
+
case "fixed":
|
|
2112
|
+
return Math.min(initial, max);
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
function retryAllows(policy, err) {
|
|
2116
|
+
if (!policy.retryOn) return true;
|
|
2117
|
+
return policy.retryOn(err);
|
|
2118
|
+
}
|
|
2119
|
+
function makeBaseCtx(args) {
|
|
2120
|
+
const { runId, stepId, attempt, input, store, clock, signal, emitLog } = args;
|
|
2121
|
+
const log = (level) => (msg, attrs) => emitLog({ level, msg, attrs: { ...attrs, runId, stepId, attempt } });
|
|
2122
|
+
const logger = {
|
|
2123
|
+
debug: log("debug"),
|
|
2124
|
+
info: log("info"),
|
|
2125
|
+
warn: log("warn"),
|
|
2126
|
+
error: log("error")
|
|
2127
|
+
};
|
|
2128
|
+
return {
|
|
2129
|
+
input,
|
|
1508
2130
|
runId,
|
|
1509
2131
|
stepId,
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
}
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
const
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
2132
|
+
attempt,
|
|
2133
|
+
signal,
|
|
2134
|
+
now: () => clock.now(),
|
|
2135
|
+
logger,
|
|
2136
|
+
once: makeOnce({ runId, stepId, store }),
|
|
2137
|
+
idempotencyKey: makeIdempotencyKey(runId, stepId)
|
|
2138
|
+
};
|
|
2139
|
+
}
|
|
2140
|
+
function makeStepCtx(args) {
|
|
2141
|
+
const { tx, ...base } = args;
|
|
2142
|
+
return { ...makeBaseCtx(base), tx };
|
|
2143
|
+
}
|
|
2144
|
+
function makeActivityCtx(args) {
|
|
2145
|
+
return {
|
|
2146
|
+
...makeBaseCtx(args),
|
|
2147
|
+
get tx() {
|
|
2148
|
+
throw new Error(
|
|
2149
|
+
"nagi: activity steps have no ctx.tx \u2014 they run outside the durable transaction. Write idempotently via your own client, or use a task."
|
|
2150
|
+
);
|
|
2151
|
+
}
|
|
2152
|
+
};
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
// src/exec/message.ts
|
|
2156
|
+
function makeMessage(deps, hooks, progression) {
|
|
2157
|
+
const { fireHook, fireStepLifecycle } = hooks;
|
|
2158
|
+
const { advance } = progression;
|
|
2159
|
+
async function dispatchMessage(message) {
|
|
2160
|
+
const { queue } = deps;
|
|
2161
|
+
const flow2 = await deps.flowFor(message.runId);
|
|
2162
|
+
const admission = await admit({ flow: flow2, message });
|
|
2163
|
+
if (admission.tag === "skip") {
|
|
2164
|
+
await queue.ack(message.receipt);
|
|
2165
|
+
return;
|
|
2166
|
+
}
|
|
2167
|
+
const { def, state } = admission;
|
|
2168
|
+
await recordStarted({ flow: flow2, message, def, state });
|
|
2169
|
+
const startedAt = Date.now();
|
|
2170
|
+
const heartbeat = startHeartbeat({
|
|
2171
|
+
queue,
|
|
2172
|
+
receipt: message.receipt,
|
|
2173
|
+
intervalMs: deps.heartbeat.intervalMs,
|
|
2174
|
+
leaseMs: deps.heartbeat.leaseMs,
|
|
2175
|
+
emitLog: deps.emitLog
|
|
2176
|
+
});
|
|
2177
|
+
let outcome;
|
|
2178
|
+
try {
|
|
2179
|
+
outcome = await execute({ flow: flow2, message, def, state });
|
|
2180
|
+
} catch (err) {
|
|
2181
|
+
outcome = await handleStepError({ flow: flow2, message, def, err });
|
|
2182
|
+
} finally {
|
|
2183
|
+
heartbeat.stop();
|
|
2184
|
+
}
|
|
2185
|
+
await queue.ack(message.receipt);
|
|
2186
|
+
await interpret({ flow: flow2, message, def, startedAt, outcome });
|
|
2187
|
+
}
|
|
2188
|
+
async function admit(args) {
|
|
2189
|
+
const { flow: flow2, message } = args;
|
|
2190
|
+
const { store } = deps;
|
|
2191
|
+
const { runId, stepId, attempt } = message;
|
|
2192
|
+
const step = asStepMapWithDefs(flow2.steps)[stepId];
|
|
2193
|
+
if (!step) {
|
|
2194
|
+
deps.emitLog({
|
|
2195
|
+
level: "warn",
|
|
2196
|
+
msg: `dispatch: step "${stepId}" not in flow "${flow2.id}"; ack and skip`
|
|
2197
|
+
});
|
|
2198
|
+
return { tag: "skip" };
|
|
2199
|
+
}
|
|
2200
|
+
const preState = await store.loadRunState(runId);
|
|
2201
|
+
if (preState.phase.tag === "canceled") return { tag: "skip" };
|
|
2202
|
+
const preStep = stepStateOf(preState, stepId);
|
|
2203
|
+
if (preStep.tag === "completed" || preStep.tag === "failed" || preStep.tag === "skipped") {
|
|
2204
|
+
return { tag: "skip" };
|
|
2205
|
+
}
|
|
2206
|
+
const claim = await store.claimStep(runId, stepId, attempt);
|
|
2207
|
+
if (claim === null) return { tag: "skip" };
|
|
2208
|
+
return { tag: "run", def: getDef(step), state: preState };
|
|
2209
|
+
}
|
|
2210
|
+
async function recordStarted(args) {
|
|
2211
|
+
const { flow: flow2, message, def, state } = args;
|
|
2212
|
+
const { store, clock } = deps;
|
|
2213
|
+
const { runId, stepId, attempt } = message;
|
|
2214
|
+
const handler = handlerDef(def);
|
|
2215
|
+
await store.appendFact(
|
|
1526
2216
|
runId,
|
|
1527
|
-
stepId,
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
2217
|
+
Facts.stepStarted(runId, stepId, attempt, def.kind, clock.now())
|
|
2218
|
+
);
|
|
2219
|
+
const startCarriesInput = def.kind === "task" || def.kind === "activity" || def.kind === "streaming" || def.kind === "subflow";
|
|
2220
|
+
const input = startCarriesInput ? state.input : null;
|
|
2221
|
+
await fireStepLifecycle(
|
|
2222
|
+
handler?.onStart,
|
|
2223
|
+
deps.hooks?.onStepStart,
|
|
2224
|
+
["step.onStart", "onStepStart"],
|
|
2225
|
+
{
|
|
2226
|
+
runId,
|
|
2227
|
+
flowId: flow2.id,
|
|
2228
|
+
stepId,
|
|
2229
|
+
attempt,
|
|
2230
|
+
kind: def.kind,
|
|
2231
|
+
input,
|
|
2232
|
+
at: clock.now()
|
|
2233
|
+
}
|
|
2234
|
+
);
|
|
2235
|
+
}
|
|
2236
|
+
async function execute(args) {
|
|
2237
|
+
const { flow: flow2, message, def, state } = args;
|
|
2238
|
+
const { runId, stepId, attempt } = message;
|
|
2239
|
+
switch (def.kind) {
|
|
2240
|
+
case "task":
|
|
2241
|
+
case "streaming": {
|
|
2242
|
+
const { output, skipAdvance } = await executeTask({
|
|
2243
|
+
def,
|
|
2244
|
+
runId,
|
|
2245
|
+
stepId,
|
|
2246
|
+
attempt,
|
|
2247
|
+
state
|
|
2248
|
+
});
|
|
2249
|
+
return skipAdvance ? { tag: "parked" } : { tag: "completed", output };
|
|
2250
|
+
}
|
|
2251
|
+
case "activity": {
|
|
2252
|
+
const { output, skipAdvance } = await executeActivity({
|
|
2253
|
+
def,
|
|
2254
|
+
runId,
|
|
2255
|
+
stepId,
|
|
2256
|
+
attempt,
|
|
2257
|
+
state
|
|
2258
|
+
});
|
|
2259
|
+
return skipAdvance ? { tag: "parked" } : { tag: "completed", output };
|
|
2260
|
+
}
|
|
2261
|
+
case "signal": {
|
|
2262
|
+
const settled = await deps.store.settleSignal({
|
|
2263
|
+
runId,
|
|
2264
|
+
stepId,
|
|
2265
|
+
at: deps.clock.now()
|
|
2266
|
+
});
|
|
2267
|
+
if (settled.tag === "delivered") {
|
|
2268
|
+
await fireHook(
|
|
2269
|
+
deps.hooks?.onSignalReceived,
|
|
2270
|
+
{
|
|
2271
|
+
runId,
|
|
2272
|
+
flowId: flow2.id,
|
|
2273
|
+
stepId,
|
|
2274
|
+
attempt: settled.attempt,
|
|
2275
|
+
kind: "signal",
|
|
2276
|
+
payload: settled.payload,
|
|
2277
|
+
at: deps.clock.now()
|
|
2278
|
+
},
|
|
2279
|
+
"onSignalReceived"
|
|
2280
|
+
);
|
|
2281
|
+
return { tag: "advance" };
|
|
2282
|
+
}
|
|
2283
|
+
return { tag: "parked" };
|
|
2284
|
+
}
|
|
2285
|
+
case "match":
|
|
2286
|
+
await executeMatch({ def, runId, stepId, state });
|
|
2287
|
+
return { tag: "advance" };
|
|
2288
|
+
case "subflow":
|
|
2289
|
+
await executeSubflow({ def, runId, stepId, attempt, state });
|
|
2290
|
+
return { tag: "parked" };
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
async function interpret(args) {
|
|
2294
|
+
const { flow: flow2, message, def, startedAt, outcome } = args;
|
|
2295
|
+
const { runId, stepId, attempt } = message;
|
|
2296
|
+
switch (outcome.tag) {
|
|
2297
|
+
case "parked":
|
|
2298
|
+
return;
|
|
2299
|
+
case "advance":
|
|
2300
|
+
await advance(runId);
|
|
2301
|
+
return;
|
|
2302
|
+
case "completed":
|
|
2303
|
+
await fireStepLifecycle(
|
|
2304
|
+
handlerDef(def)?.onComplete,
|
|
2305
|
+
deps.hooks?.onStepComplete,
|
|
2306
|
+
["step.onComplete", "onStepComplete"],
|
|
2307
|
+
{
|
|
2308
|
+
runId,
|
|
2309
|
+
flowId: flow2.id,
|
|
2310
|
+
stepId,
|
|
2311
|
+
attempt,
|
|
2312
|
+
kind: def.kind,
|
|
2313
|
+
output: outcome.output,
|
|
2314
|
+
durationMs: Date.now() - startedAt,
|
|
2315
|
+
at: deps.clock.now()
|
|
2316
|
+
}
|
|
2317
|
+
);
|
|
2318
|
+
await advance(runId);
|
|
2319
|
+
return;
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
async function runHandler(def, args) {
|
|
2323
|
+
const { input, needs, ctx, runId, stepId } = args;
|
|
2324
|
+
if (def.kind !== "streaming") {
|
|
2325
|
+
return await def.run({ input, needs, ctx });
|
|
2326
|
+
}
|
|
2327
|
+
let emitActive = true;
|
|
2328
|
+
const streamingCtx = {
|
|
2329
|
+
...ctx,
|
|
2330
|
+
emit: async (chunk) => {
|
|
2331
|
+
if (emitActive)
|
|
2332
|
+
deps.streamTransport?.publishChunk(runId, stepId, chunk);
|
|
2333
|
+
}
|
|
1531
2334
|
};
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
2335
|
+
try {
|
|
2336
|
+
return await def.run({
|
|
2337
|
+
input,
|
|
2338
|
+
needs,
|
|
2339
|
+
ctx: streamingCtx
|
|
2340
|
+
});
|
|
2341
|
+
} finally {
|
|
2342
|
+
emitActive = false;
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
async function executeTask(args) {
|
|
2346
|
+
const { def, runId, stepId, attempt, state } = args;
|
|
2347
|
+
const { store, clock } = deps;
|
|
2348
|
+
const input = state.input;
|
|
2349
|
+
const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
|
|
2350
|
+
const ac = new AbortController();
|
|
2351
|
+
const watcher = startCancelWatcher({
|
|
2352
|
+
store,
|
|
1543
2353
|
runId,
|
|
1544
2354
|
stepId,
|
|
1545
2355
|
attempt,
|
|
1546
|
-
|
|
1547
|
-
|
|
2356
|
+
ac,
|
|
2357
|
+
intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
|
|
1548
2358
|
});
|
|
1549
|
-
|
|
2359
|
+
try {
|
|
2360
|
+
let stepAbortedHere = false;
|
|
2361
|
+
const output = await store.runStep(
|
|
2362
|
+
runId,
|
|
2363
|
+
stepId,
|
|
2364
|
+
attempt,
|
|
2365
|
+
async (tx) => {
|
|
2366
|
+
const ctx = makeStepCtx({
|
|
2367
|
+
runId,
|
|
2368
|
+
stepId,
|
|
2369
|
+
attempt,
|
|
2370
|
+
input,
|
|
2371
|
+
store,
|
|
2372
|
+
clock,
|
|
2373
|
+
tx,
|
|
2374
|
+
signal: ac.signal,
|
|
2375
|
+
emitLog: deps.emitLog
|
|
2376
|
+
});
|
|
2377
|
+
const out = await runHandler(def, {
|
|
2378
|
+
input,
|
|
2379
|
+
needs,
|
|
2380
|
+
ctx,
|
|
2381
|
+
runId,
|
|
2382
|
+
stepId
|
|
2383
|
+
});
|
|
2384
|
+
const postState = await store.loadRunState(runId);
|
|
2385
|
+
const { fact, abortedHere } = resolveExecutionFact({
|
|
2386
|
+
postState,
|
|
2387
|
+
runId,
|
|
2388
|
+
stepId,
|
|
2389
|
+
attempt,
|
|
2390
|
+
output: out,
|
|
2391
|
+
at: clock.now()
|
|
2392
|
+
});
|
|
2393
|
+
stepAbortedHere = abortedHere;
|
|
2394
|
+
return { output: out, fact };
|
|
2395
|
+
}
|
|
2396
|
+
);
|
|
2397
|
+
return { output, skipAdvance: stepAbortedHere };
|
|
2398
|
+
} finally {
|
|
2399
|
+
watcher.stop();
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
async function executeActivity(args) {
|
|
2403
|
+
const { def, runId, stepId, attempt, state } = args;
|
|
2404
|
+
const { store, clock } = deps;
|
|
2405
|
+
const input = state.input;
|
|
2406
|
+
const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
|
|
2407
|
+
const ac = new AbortController();
|
|
2408
|
+
const watcher = startCancelWatcher({
|
|
2409
|
+
store,
|
|
1550
2410
|
runId,
|
|
1551
|
-
flowId: flow2.id,
|
|
1552
2411
|
stepId,
|
|
1553
2412
|
attempt,
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
async function advance(deps, runId) {
|
|
1592
|
-
const { store, queue } = deps;
|
|
1593
|
-
const flow2 = await deps.flowFor(runId);
|
|
1594
|
-
for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
|
|
1595
|
-
const runState = await store.loadRunState(runId);
|
|
1596
|
-
const t = nextTransition(flow2, runState);
|
|
1597
|
-
switch (t.kind) {
|
|
1598
|
-
case "settled":
|
|
1599
|
-
case "waiting":
|
|
1600
|
-
return;
|
|
1601
|
-
case "complete":
|
|
1602
|
-
await finalizeFlowCompletion({ deps, flow: flow2, runId, output: t.output });
|
|
1603
|
-
return;
|
|
1604
|
-
case "fail":
|
|
1605
|
-
await finalizeFlowFailure({ deps, flow: flow2, runId, error: t.error });
|
|
1606
|
-
return;
|
|
1607
|
-
case "dispatch":
|
|
1608
|
-
await recordSkips(deps, runId, t.skip);
|
|
1609
|
-
for (const stepId of t.runnable) await queue.enqueue(runId, stepId);
|
|
1610
|
-
return;
|
|
1611
|
-
case "skip":
|
|
1612
|
-
await recordSkips(deps, runId, t.skip);
|
|
1613
|
-
continue;
|
|
1614
|
-
case "promote-match":
|
|
1615
|
-
await applyPromotions(deps, flow2, runState, t.promotions);
|
|
1616
|
-
continue;
|
|
2413
|
+
ac,
|
|
2414
|
+
intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
|
|
2415
|
+
});
|
|
2416
|
+
try {
|
|
2417
|
+
const ctx = makeActivityCtx({
|
|
2418
|
+
runId,
|
|
2419
|
+
stepId,
|
|
2420
|
+
attempt,
|
|
2421
|
+
input,
|
|
2422
|
+
store,
|
|
2423
|
+
clock,
|
|
2424
|
+
signal: ac.signal,
|
|
2425
|
+
emitLog: deps.emitLog
|
|
2426
|
+
});
|
|
2427
|
+
const out = await runHandler(def, { input, needs, ctx, runId, stepId });
|
|
2428
|
+
let stepAbortedHere = false;
|
|
2429
|
+
const output = await store.runStep(
|
|
2430
|
+
runId,
|
|
2431
|
+
stepId,
|
|
2432
|
+
attempt,
|
|
2433
|
+
async () => {
|
|
2434
|
+
const postState = await store.loadRunState(runId);
|
|
2435
|
+
const { fact, abortedHere } = resolveExecutionFact({
|
|
2436
|
+
postState,
|
|
2437
|
+
runId,
|
|
2438
|
+
stepId,
|
|
2439
|
+
attempt,
|
|
2440
|
+
output: out,
|
|
2441
|
+
at: clock.now()
|
|
2442
|
+
});
|
|
2443
|
+
stepAbortedHere = abortedHere;
|
|
2444
|
+
return { output: out, fact };
|
|
2445
|
+
}
|
|
2446
|
+
);
|
|
2447
|
+
return { output, skipAdvance: stepAbortedHere };
|
|
2448
|
+
} finally {
|
|
2449
|
+
watcher.stop();
|
|
1617
2450
|
}
|
|
1618
2451
|
}
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
2452
|
+
async function executeSubflow(args) {
|
|
2453
|
+
const { def, runId, stepId, attempt, state } = args;
|
|
2454
|
+
const child = deps.lookupFlow(def.childFlowId);
|
|
2455
|
+
if (child === void 0) {
|
|
2456
|
+
throw new Error(
|
|
2457
|
+
`Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
|
|
2458
|
+
);
|
|
2459
|
+
}
|
|
2460
|
+
const parentInput = state.input;
|
|
2461
|
+
const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
|
|
2462
|
+
const childInput = def.buildInput({ input: parentInput, needs });
|
|
2463
|
+
await deps.startChildRun({
|
|
2464
|
+
child,
|
|
2465
|
+
childInput,
|
|
2466
|
+
parent: { runId, stepId, attempt }
|
|
2467
|
+
});
|
|
1626
2468
|
}
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
2469
|
+
async function executeMatch(args) {
|
|
2470
|
+
const { def, runId, stepId, state } = args;
|
|
2471
|
+
const { store, clock } = deps;
|
|
2472
|
+
const input = state.input;
|
|
2473
|
+
const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
|
|
2474
|
+
const armId = selectArm(def, { input, needs });
|
|
2475
|
+
await store.appendFact(
|
|
1633
2476
|
runId,
|
|
1634
|
-
stepId,
|
|
1635
|
-
|
|
1636
|
-
|
|
2477
|
+
Facts.matchArmSelected(runId, stepId, armId, clock.now())
|
|
2478
|
+
);
|
|
2479
|
+
}
|
|
2480
|
+
async function handleStepError(args) {
|
|
2481
|
+
const { flow: flow2, message, def, err } = args;
|
|
2482
|
+
const { store, queue, clock } = deps;
|
|
2483
|
+
const { runId, stepId, attempt } = message;
|
|
2484
|
+
const error = serializeError(err);
|
|
2485
|
+
const handler = handlerDef(def);
|
|
2486
|
+
const postState = await store.loadRunState(runId);
|
|
2487
|
+
const policy = handler?.retry ?? deps.defaultRetry ?? DEFAULT_RETRY2;
|
|
2488
|
+
const outcome = classifyFailure({
|
|
2489
|
+
attempt,
|
|
2490
|
+
policy,
|
|
2491
|
+
err,
|
|
2492
|
+
runIsCanceled: postState.phase.tag === "canceled",
|
|
2493
|
+
stepAborted: isAbortRequested(stepStateOf(postState, stepId), attempt)
|
|
1637
2494
|
});
|
|
2495
|
+
const base = { runId, flowId: flow2.id, stepId, attempt, kind: def.kind };
|
|
2496
|
+
switch (outcome.tag) {
|
|
2497
|
+
case "canceled": {
|
|
2498
|
+
await store.appendFact(
|
|
2499
|
+
runId,
|
|
2500
|
+
Facts.stepCanceled(
|
|
2501
|
+
runId,
|
|
2502
|
+
stepId,
|
|
2503
|
+
attempt,
|
|
2504
|
+
clock.now(),
|
|
2505
|
+
outcome.includeError ? error : void 0
|
|
2506
|
+
)
|
|
2507
|
+
);
|
|
2508
|
+
return outcome.advanceAfter ? { tag: "advance" } : { tag: "parked" };
|
|
2509
|
+
}
|
|
2510
|
+
case "retry": {
|
|
2511
|
+
const at = clock.now();
|
|
2512
|
+
const nextAttemptAt = new Date(at.getTime() + outcome.delayMs);
|
|
2513
|
+
await store.appendFact(
|
|
2514
|
+
runId,
|
|
2515
|
+
Facts.stepRetried(runId, stepId, attempt, nextAttemptAt, error, at)
|
|
2516
|
+
);
|
|
2517
|
+
await fireStepLifecycle(
|
|
2518
|
+
handler?.onRetry,
|
|
2519
|
+
deps.hooks?.onStepRetry,
|
|
2520
|
+
["step.onRetry", "onStepRetry"],
|
|
2521
|
+
{ ...base, error, nextAttemptAt, at }
|
|
2522
|
+
);
|
|
2523
|
+
await queue.enqueue(runId, stepId, {
|
|
2524
|
+
attempt: attempt + 1,
|
|
2525
|
+
delayMs: outcome.delayMs
|
|
2526
|
+
});
|
|
2527
|
+
return { tag: "parked" };
|
|
2528
|
+
}
|
|
2529
|
+
case "failed": {
|
|
2530
|
+
const at = clock.now();
|
|
2531
|
+
await store.settleStep(
|
|
2532
|
+
runId,
|
|
2533
|
+
stepId,
|
|
2534
|
+
Facts.stepFailed(runId, stepId, attempt, error, at)
|
|
2535
|
+
);
|
|
2536
|
+
await fireStepLifecycle(
|
|
2537
|
+
handler?.onError,
|
|
2538
|
+
deps.hooks?.onStepError,
|
|
2539
|
+
["step.onError", "onStepError"],
|
|
2540
|
+
{ ...base, error, at }
|
|
2541
|
+
);
|
|
2542
|
+
return { tag: "advance" };
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
1638
2545
|
}
|
|
2546
|
+
return { dispatchMessage };
|
|
1639
2547
|
}
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
2548
|
+
|
|
2549
|
+
// src/exec/progression.ts
|
|
2550
|
+
var MAX_ADVANCE_ITERS = 1024;
|
|
2551
|
+
function makeProgression(deps, hooks) {
|
|
2552
|
+
const { fireHook } = hooks;
|
|
2553
|
+
async function advance(runId) {
|
|
2554
|
+
const { store, queue } = deps;
|
|
2555
|
+
const flow2 = await deps.flowFor(runId);
|
|
2556
|
+
for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
|
|
2557
|
+
const runState = await store.loadRunState(runId);
|
|
2558
|
+
const t = nextTransition(flow2, runState);
|
|
2559
|
+
switch (t.kind) {
|
|
2560
|
+
case "settled":
|
|
2561
|
+
case "waiting":
|
|
2562
|
+
return;
|
|
2563
|
+
case "complete":
|
|
2564
|
+
await finalizeFlowCompletion({ flow: flow2, runId, output: t.output });
|
|
2565
|
+
return;
|
|
2566
|
+
case "fail":
|
|
2567
|
+
await finalizeFlowFailure({ flow: flow2, runId, error: t.error });
|
|
2568
|
+
return;
|
|
2569
|
+
case "dispatch":
|
|
2570
|
+
await recordSkips(runId, t.skip);
|
|
2571
|
+
for (const stepId of t.runnable) await queue.enqueue(runId, stepId);
|
|
2572
|
+
return;
|
|
2573
|
+
case "skip":
|
|
2574
|
+
await recordSkips(runId, t.skip);
|
|
2575
|
+
continue;
|
|
2576
|
+
case "promote-match":
|
|
2577
|
+
await applyPromotions(flow2, runState, t.promotions);
|
|
2578
|
+
continue;
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
2581
|
+
const cycleError = {
|
|
2582
|
+
name: "NagiCycleError",
|
|
2583
|
+
message: `advance exceeded ${MAX_ADVANCE_ITERS} iterations \u2014 likely a cycle or infinite skip loop in flow "${flow2.id}"`
|
|
2584
|
+
};
|
|
2585
|
+
const finalState = await store.loadRunState(runId);
|
|
2586
|
+
if (!isTerminalRun(finalState)) {
|
|
2587
|
+
await finalizeFlowFailure({ flow: flow2, runId, error: cycleError });
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
async function recordSkips(runId, skip) {
|
|
2591
|
+
const { store, clock } = deps;
|
|
2592
|
+
for (const { stepId, reason } of skip) {
|
|
2593
|
+
await store.appendFact(
|
|
2594
|
+
runId,
|
|
2595
|
+
Facts.stepSkipped({ runId, stepId, reason, at: clock.now() })
|
|
2596
|
+
);
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
async function markStepSettled(args) {
|
|
2600
|
+
const { flow: flow2, runId, stepId, attempt, stepKind, settlement } = args;
|
|
2601
|
+
const at = deps.clock.now();
|
|
2602
|
+
const base = {
|
|
1655
2603
|
runId,
|
|
1656
2604
|
flowId: flow2.id,
|
|
1657
2605
|
stepId,
|
|
1658
2606
|
attempt,
|
|
1659
|
-
kind,
|
|
1660
|
-
output,
|
|
1661
|
-
durationMs: 0,
|
|
2607
|
+
kind: stepKind,
|
|
1662
2608
|
at
|
|
1663
|
-
}
|
|
1664
|
-
"
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
2609
|
+
};
|
|
2610
|
+
if (settlement.kind === "complete") {
|
|
2611
|
+
await deps.store.settleStep(
|
|
2612
|
+
runId,
|
|
2613
|
+
stepId,
|
|
2614
|
+
Facts.stepCompleted(runId, stepId, attempt, settlement.output, at)
|
|
2615
|
+
);
|
|
2616
|
+
await fireHook(
|
|
2617
|
+
deps.hooks?.onStepComplete,
|
|
2618
|
+
{ ...base, output: settlement.output },
|
|
2619
|
+
"onStepComplete"
|
|
2620
|
+
);
|
|
2621
|
+
} else {
|
|
2622
|
+
await deps.store.settleStep(
|
|
2623
|
+
runId,
|
|
2624
|
+
stepId,
|
|
2625
|
+
Facts.stepFailed(runId, stepId, attempt, settlement.error, at)
|
|
2626
|
+
);
|
|
2627
|
+
await fireHook(
|
|
2628
|
+
deps.hooks?.onStepError,
|
|
2629
|
+
{ ...base, error: settlement.error },
|
|
2630
|
+
"onStepError"
|
|
2631
|
+
);
|
|
2632
|
+
}
|
|
2633
|
+
}
|
|
2634
|
+
async function applyPromotions(flow2, runState, promotions) {
|
|
2635
|
+
for (const { matchId, attempt, result } of promotions) {
|
|
2636
|
+
await markStepSettled({
|
|
1685
2637
|
flow: flow2,
|
|
1686
2638
|
runId: runState.runId,
|
|
1687
2639
|
stepId: matchId,
|
|
1688
2640
|
attempt,
|
|
1689
|
-
|
|
1690
|
-
|
|
2641
|
+
stepKind: "match",
|
|
2642
|
+
settlement: result
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
async function finalizeFlowFailure(args) {
|
|
2647
|
+
const { flow: flow2, runId, error } = args;
|
|
2648
|
+
const { store, clock } = deps;
|
|
2649
|
+
await store.appendFact(runId, Facts.flowFailed(runId, error, clock.now()));
|
|
2650
|
+
const event = { runId, flowId: flow2.id, error, at: clock.now() };
|
|
2651
|
+
await fireHook(flow2.onError, event, "flow.onError");
|
|
2652
|
+
await fireHook(deps.hooks?.onFlowError, event, "onFlowError");
|
|
2653
|
+
await propagateToParent(runId, { kind: "failed", error });
|
|
2654
|
+
}
|
|
2655
|
+
async function finalizeFlowCompletion(args) {
|
|
2656
|
+
const { flow: flow2, runId, output } = args;
|
|
2657
|
+
const { store, clock } = deps;
|
|
2658
|
+
await store.appendFact(
|
|
2659
|
+
runId,
|
|
2660
|
+
Facts.flowCompleted(runId, output, clock.now())
|
|
2661
|
+
);
|
|
2662
|
+
const event = { runId, flowId: flow2.id, output, at: clock.now() };
|
|
2663
|
+
await fireHook(flow2.onComplete, event, "flow.onComplete");
|
|
2664
|
+
await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete");
|
|
2665
|
+
await propagateToParent(runId, { kind: "completed", output });
|
|
2666
|
+
}
|
|
2667
|
+
async function propagateToParent(childRunId, outcome) {
|
|
2668
|
+
const { store } = deps;
|
|
2669
|
+
const childState = await store.loadRunState(childRunId);
|
|
2670
|
+
if (childState.parent === void 0) {
|
|
2671
|
+
return;
|
|
2672
|
+
}
|
|
2673
|
+
const { runId: parentRunId, stepId: parentStepId } = childState.parent;
|
|
2674
|
+
const parentState = await store.loadRunState(parentRunId);
|
|
2675
|
+
if (isTerminalRun(parentState)) {
|
|
2676
|
+
deps.emitLog({
|
|
2677
|
+
level: "info",
|
|
2678
|
+
msg: "nagi: subflow wake skipped \u2014 parent run already terminal",
|
|
2679
|
+
attrs: {
|
|
2680
|
+
parentRunId,
|
|
2681
|
+
parentStepId,
|
|
2682
|
+
childRunId,
|
|
2683
|
+
parentStatus: runStatusOf(parentState)
|
|
2684
|
+
}
|
|
1691
2685
|
});
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
2686
|
+
return;
|
|
2687
|
+
}
|
|
2688
|
+
const parentStep = stepStateOf(parentState, parentStepId);
|
|
2689
|
+
if (parentStep.tag !== "awaitingChild") {
|
|
2690
|
+
deps.emitLog({
|
|
2691
|
+
level: "info",
|
|
2692
|
+
msg: "nagi: subflow wake skipped \u2014 parent step not awaiting child",
|
|
2693
|
+
attrs: {
|
|
2694
|
+
parentRunId,
|
|
2695
|
+
parentStepId,
|
|
2696
|
+
childRunId,
|
|
2697
|
+
parentStepStatus: stepStatusOf(parentStep)
|
|
2698
|
+
}
|
|
1701
2699
|
});
|
|
2700
|
+
return;
|
|
1702
2701
|
}
|
|
2702
|
+
const attempt = parentStep.attempt;
|
|
2703
|
+
const parentFlow = await deps.flowFor(parentRunId);
|
|
2704
|
+
await markStepSettled({
|
|
2705
|
+
flow: parentFlow,
|
|
2706
|
+
runId: parentRunId,
|
|
2707
|
+
stepId: parentStepId,
|
|
2708
|
+
attempt,
|
|
2709
|
+
stepKind: "subflow",
|
|
2710
|
+
settlement: outcome.kind === "completed" ? { kind: "complete", output: { childRunId, output: outcome.output } } : { kind: "fail", error: outcome.error }
|
|
2711
|
+
});
|
|
2712
|
+
await advance(parentRunId);
|
|
1703
2713
|
}
|
|
2714
|
+
return { advance, propagateToParent };
|
|
1704
2715
|
}
|
|
1705
|
-
|
|
1706
|
-
|
|
2716
|
+
|
|
2717
|
+
// src/dispatch.ts
|
|
2718
|
+
function makeDispatcher(deps) {
|
|
2719
|
+
const hooks = makeHooks(deps);
|
|
2720
|
+
const progression = makeProgression(deps, hooks);
|
|
2721
|
+
const message = makeMessage(deps, hooks, progression);
|
|
1707
2722
|
return {
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
attempt,
|
|
1712
|
-
signal,
|
|
1713
|
-
now: () => clock.now(),
|
|
1714
|
-
tx,
|
|
1715
|
-
logger: args.logger ?? consoleLogger(),
|
|
1716
|
-
once: makeOnce({ runId, stepId, store }),
|
|
1717
|
-
idempotencyKey: makeIdempotencyKey(runId, stepId)
|
|
2723
|
+
dispatchMessage: message.dispatchMessage,
|
|
2724
|
+
advance: progression.advance,
|
|
2725
|
+
propagateToParent: progression.propagateToParent
|
|
1718
2726
|
};
|
|
1719
2727
|
}
|
|
1720
|
-
|
|
2728
|
+
|
|
2729
|
+
// src/flow-registry.ts
|
|
2730
|
+
function makeFlowRegistry(flows) {
|
|
2731
|
+
const byId = /* @__PURE__ */ new Map();
|
|
2732
|
+
const streamingStepIds = /* @__PURE__ */ new Set();
|
|
2733
|
+
for (const flow2 of flows) {
|
|
2734
|
+
if (byId.has(flow2.id)) {
|
|
2735
|
+
throw new NagiRuntimeError(
|
|
2736
|
+
`Duplicate flow id "${flow2.id}" passed to nagi()`
|
|
2737
|
+
);
|
|
2738
|
+
}
|
|
2739
|
+
byId.set(flow2.id, flow2);
|
|
2740
|
+
for (const [stepId, step] of Object.entries(
|
|
2741
|
+
asStepMapWithDefs(flow2.steps)
|
|
2742
|
+
)) {
|
|
2743
|
+
if (getDef(step).kind === "streaming") streamingStepIds.add(stepId);
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
1721
2746
|
return {
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
2747
|
+
all: flows,
|
|
2748
|
+
get: (flowId) => byId.get(flowId),
|
|
2749
|
+
has: (flowId) => byId.has(flowId),
|
|
2750
|
+
require(flowId) {
|
|
2751
|
+
const flow2 = byId.get(flowId);
|
|
2752
|
+
if (!flow2) {
|
|
2753
|
+
throw new NagiRuntimeError(
|
|
2754
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
2755
|
+
);
|
|
2756
|
+
}
|
|
2757
|
+
return flow2;
|
|
2758
|
+
},
|
|
2759
|
+
requireForRun(flowId, runId) {
|
|
2760
|
+
const flow2 = byId.get(flowId);
|
|
2761
|
+
if (!flow2) {
|
|
2762
|
+
throw new NagiRuntimeError(
|
|
2763
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
2764
|
+
);
|
|
2765
|
+
}
|
|
2766
|
+
return flow2;
|
|
2767
|
+
},
|
|
2768
|
+
isStreaming: (stepId) => streamingStepIds.has(stepId)
|
|
1726
2769
|
};
|
|
1727
2770
|
}
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
return Math.min(initial, max);
|
|
2771
|
+
|
|
2772
|
+
// src/operator.ts
|
|
2773
|
+
var ABORT_SETTLE_DEADLINE_MS = 3e4;
|
|
2774
|
+
var ABORT_SETTLE_POLL_MS = 50;
|
|
2775
|
+
function requireActor(method, actor) {
|
|
2776
|
+
if (typeof actor !== "string" || actor.length === 0) {
|
|
2777
|
+
throw validationError(`${method}: opts.actor must be a non-empty string`, [
|
|
2778
|
+
"actor"
|
|
2779
|
+
]);
|
|
1738
2780
|
}
|
|
1739
2781
|
}
|
|
1740
|
-
function
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
}
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
if (startedFact?.parent === void 0) {
|
|
1777
|
-
return;
|
|
1778
|
-
}
|
|
1779
|
-
const { runId: parentRunId, stepId: parentStepId } = startedFact.parent;
|
|
1780
|
-
const parentState = await store.loadRunState(parentRunId);
|
|
1781
|
-
if (parentState.status === "completed" || parentState.status === "failed" || parentState.status === "canceled") {
|
|
1782
|
-
deps.logger?.info(
|
|
1783
|
-
"nagi: subflow wake skipped \u2014 parent run already terminal",
|
|
1784
|
-
{
|
|
1785
|
-
parentRunId,
|
|
1786
|
-
parentStepId,
|
|
1787
|
-
childRunId,
|
|
1788
|
-
parentStatus: parentState.status
|
|
1789
|
-
}
|
|
2782
|
+
function makeOperator(o) {
|
|
2783
|
+
const { dispatcher, store, clock, registry, cancelRunRecursive, emitLog } = o;
|
|
2784
|
+
async function skip(runId, stepId, opts) {
|
|
2785
|
+
requireActor("operator.skip", opts.actor);
|
|
2786
|
+
const state = await store.loadRunState(runId);
|
|
2787
|
+
const flow2 = registry.requireForRun(state.flowId, runId);
|
|
2788
|
+
if (!(stepId in flow2.steps)) {
|
|
2789
|
+
throw validationError(
|
|
2790
|
+
`operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2791
|
+
["stepId"]
|
|
2792
|
+
);
|
|
2793
|
+
}
|
|
2794
|
+
const stepState = stepStateOf(state, stepId);
|
|
2795
|
+
if (isStepTerminal(stepState)) {
|
|
2796
|
+
emitLog({
|
|
2797
|
+
level: "info",
|
|
2798
|
+
msg: "nagi: operator.skip noop \u2014 step already terminal",
|
|
2799
|
+
attrs: { runId, stepId, status: stepStatusOf(stepState) }
|
|
2800
|
+
});
|
|
2801
|
+
return;
|
|
2802
|
+
}
|
|
2803
|
+
if (isTerminalRun(state)) {
|
|
2804
|
+
throw new NagiRuntimeError(
|
|
2805
|
+
`operator.skip: run ${runId} is already terminal (${runStatusOf(state)}); cannot skip step "${stepId}".`
|
|
2806
|
+
);
|
|
2807
|
+
}
|
|
2808
|
+
await store.appendFact(
|
|
2809
|
+
runId,
|
|
2810
|
+
Facts.stepSkipped({
|
|
2811
|
+
runId,
|
|
2812
|
+
stepId,
|
|
2813
|
+
at: clock.now(),
|
|
2814
|
+
reason: "manual",
|
|
2815
|
+
actor: opts.actor,
|
|
2816
|
+
...compact({ note: opts.note })
|
|
2817
|
+
})
|
|
1790
2818
|
);
|
|
1791
|
-
|
|
1792
|
-
}
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
await
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
2819
|
+
await dispatcher.advance(runId);
|
|
2820
|
+
}
|
|
2821
|
+
async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
|
|
2822
|
+
const start = Date.now();
|
|
2823
|
+
while (Date.now() - start < deadlineMs) {
|
|
2824
|
+
const s = await store.loadRunState(runId);
|
|
2825
|
+
const ss = s.steps[stepId];
|
|
2826
|
+
if (ss === void 0) return;
|
|
2827
|
+
if (isStepTerminal(ss)) return;
|
|
2828
|
+
if (isTerminalRun(s)) return;
|
|
2829
|
+
if (attemptOf(ss) > attempt) return;
|
|
2830
|
+
await new Promise((r) => setTimeout(r, ABORT_SETTLE_POLL_MS));
|
|
2831
|
+
}
|
|
2832
|
+
throw new NagiRuntimeError(
|
|
2833
|
+
`operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
|
|
2834
|
+
);
|
|
2835
|
+
}
|
|
2836
|
+
async function retry(runId, stepId, opts) {
|
|
2837
|
+
requireActor("operator.retry", opts.actor);
|
|
2838
|
+
const state = await store.loadRunState(runId);
|
|
2839
|
+
if (state.phase.tag === "canceled") {
|
|
2840
|
+
throw new NagiRuntimeError(
|
|
2841
|
+
`operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
|
|
2842
|
+
);
|
|
2843
|
+
}
|
|
2844
|
+
const flow2 = registry.requireForRun(state.flowId, runId);
|
|
2845
|
+
if (!(stepId in flow2.steps)) {
|
|
2846
|
+
throw validationError(
|
|
2847
|
+
`operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2848
|
+
["stepId"]
|
|
2849
|
+
);
|
|
2850
|
+
}
|
|
2851
|
+
const stepState = stepStateOf(state, stepId);
|
|
2852
|
+
if (stepState.tag === "running") {
|
|
2853
|
+
await store.appendFact(
|
|
2854
|
+
runId,
|
|
2855
|
+
Facts.stepAbortRequested({
|
|
2856
|
+
runId,
|
|
2857
|
+
stepId,
|
|
2858
|
+
attempt: stepState.attempt,
|
|
2859
|
+
at: clock.now(),
|
|
2860
|
+
actor: opts.actor,
|
|
2861
|
+
...compact({ note: opts.note })
|
|
2862
|
+
})
|
|
2863
|
+
);
|
|
2864
|
+
await waitForStepToSettle(
|
|
2865
|
+
runId,
|
|
2866
|
+
stepId,
|
|
2867
|
+
stepState.attempt,
|
|
2868
|
+
ABORT_SETTLE_DEADLINE_MS
|
|
2869
|
+
);
|
|
2870
|
+
}
|
|
2871
|
+
const cascade = descendantsOf(flow2, stepId);
|
|
2872
|
+
const at = clock.now();
|
|
2873
|
+
for (const id of cascade) {
|
|
2874
|
+
const fact = id === stepId ? Facts.stepReset({
|
|
2875
|
+
runId,
|
|
2876
|
+
stepId: id,
|
|
2877
|
+
at,
|
|
2878
|
+
actor: opts.actor,
|
|
2879
|
+
...compact({ note: opts.note })
|
|
2880
|
+
}) : Facts.stepReset({ runId, stepId: id, at, cascadedFrom: stepId });
|
|
2881
|
+
await store.appendFact(runId, fact);
|
|
2882
|
+
}
|
|
2883
|
+
await dispatcher.advance(runId);
|
|
2884
|
+
}
|
|
2885
|
+
async function abort(runId, opts) {
|
|
2886
|
+
requireActor("operator.abort", opts.actor);
|
|
2887
|
+
await cancelRunRecursive(runId, {
|
|
2888
|
+
cause: "operator",
|
|
2889
|
+
reason: opts.note ?? `aborted by operator ${opts.actor}`,
|
|
2890
|
+
actor: opts.actor,
|
|
2891
|
+
...compact({ note: opts.note })
|
|
1828
2892
|
});
|
|
1829
2893
|
}
|
|
1830
|
-
|
|
2894
|
+
return { skip, retry, abort };
|
|
1831
2895
|
}
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
2896
|
+
|
|
2897
|
+
// src/replay-synth.ts
|
|
2898
|
+
function synthesizeReplayFlow(dag, liveFlow) {
|
|
2899
|
+
const liveSteps = asStepMapWithDefs(liveFlow.steps);
|
|
2900
|
+
const synthesized = {};
|
|
2901
|
+
for (const canonStep of dag.steps) {
|
|
2902
|
+
const liveStep = liveSteps[canonStep.id];
|
|
2903
|
+
if (liveStep === void 0) {
|
|
2904
|
+
throw new NagiRuntimeError(
|
|
2905
|
+
`Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
|
|
2906
|
+
);
|
|
2907
|
+
}
|
|
2908
|
+
synthesized[canonStep.id] = attachDef(
|
|
2909
|
+
{ kind: canonStep.kind, id: canonStep.id },
|
|
2910
|
+
getDef(liveStep)
|
|
2911
|
+
);
|
|
2912
|
+
}
|
|
2913
|
+
for (const canonStep of dag.steps) {
|
|
2914
|
+
const shell = synthesized[canonStep.id];
|
|
2915
|
+
if (shell === void 0) continue;
|
|
2916
|
+
const synthesizedNeeds = {};
|
|
2917
|
+
for (const upstreamId of canonStep.needs) {
|
|
2918
|
+
const upstreamShell = synthesized[upstreamId];
|
|
2919
|
+
if (upstreamShell === void 0) {
|
|
2920
|
+
throw new NagiRuntimeError(
|
|
2921
|
+
`Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
|
|
2922
|
+
);
|
|
2923
|
+
}
|
|
2924
|
+
synthesizedNeeds[upstreamId] = upstreamShell;
|
|
2925
|
+
}
|
|
2926
|
+
setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
|
|
2927
|
+
}
|
|
2928
|
+
return {
|
|
2929
|
+
id: liveFlow.id,
|
|
2930
|
+
input: liveFlow.input,
|
|
2931
|
+
steps: synthesized,
|
|
2932
|
+
...compact({ output: liveFlow.output })
|
|
2933
|
+
};
|
|
2934
|
+
}
|
|
2935
|
+
|
|
2936
|
+
// src/replay.ts
|
|
2937
|
+
function makeReplay(deps) {
|
|
2938
|
+
const { registry, hashFor, store, queue, clock } = deps;
|
|
2939
|
+
async function replay(runId, opts = { mode: "continue" }) {
|
|
2940
|
+
const runState = await store.loadRunState(runId);
|
|
2941
|
+
const liveFlow = registry.requireForRun(runState.flowId, runId);
|
|
2942
|
+
if (runState.phase.tag === "canceled") {
|
|
2943
|
+
throw new NagiRuntimeError(
|
|
2944
|
+
`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.`
|
|
2945
|
+
);
|
|
2946
|
+
}
|
|
2947
|
+
if (opts.mode === "inspect") return;
|
|
2948
|
+
const fireHooks = opts.fireHooks !== false;
|
|
2949
|
+
const baseDeps = fireHooks ? deps : { ...deps, fireHooks: false };
|
|
2950
|
+
let replayDeps = baseDeps;
|
|
2951
|
+
let effectiveFlow = liveFlow;
|
|
2952
|
+
const pinned = runState.flowHash;
|
|
2953
|
+
if (pinned !== void 0) {
|
|
2954
|
+
const liveHash = hashFor(liveFlow.id);
|
|
2955
|
+
if (liveHash !== void 0 && liveHash !== pinned) {
|
|
2956
|
+
if (!opts.allowDrift) {
|
|
2957
|
+
throw new NagiSnapshotDriftError({
|
|
2958
|
+
runId,
|
|
2959
|
+
expected: pinned,
|
|
2960
|
+
actual: liveHash
|
|
2961
|
+
});
|
|
2962
|
+
}
|
|
2963
|
+
const snapshot = await store.loadSnapshot(pinned);
|
|
2964
|
+
if (snapshot === null) {
|
|
2965
|
+
throw new NagiRuntimeError(
|
|
2966
|
+
`Run ${runId} pinned to flow hash ${pinned.slice(0, 12)}\u2026 but no snapshot with that hash was found. Cannot replay with allowDrift.`
|
|
2967
|
+
);
|
|
2968
|
+
}
|
|
2969
|
+
const synthesized = synthesizeReplayFlow(
|
|
2970
|
+
snapshot.dag,
|
|
2971
|
+
liveFlow
|
|
2972
|
+
);
|
|
2973
|
+
replayDeps = { ...baseDeps, flowFor: async () => synthesized };
|
|
2974
|
+
effectiveFlow = synthesized;
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
if (opts.from !== void 0) {
|
|
2978
|
+
if (runState.phase.tag === "running") {
|
|
2979
|
+
throw new NagiRuntimeError(
|
|
2980
|
+
`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.`
|
|
2981
|
+
);
|
|
2982
|
+
}
|
|
2983
|
+
if (!(opts.from in effectiveFlow.steps)) {
|
|
2984
|
+
throw validationError(
|
|
2985
|
+
`replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
|
|
2986
|
+
["from"]
|
|
2987
|
+
);
|
|
2988
|
+
}
|
|
2989
|
+
const cascade = descendantsOf(effectiveFlow, opts.from);
|
|
2990
|
+
const at = clock.now();
|
|
2991
|
+
for (const stepId of cascade) {
|
|
2992
|
+
const fact = stepId === opts.from ? Facts.stepReset({ runId, stepId, at }) : Facts.stepReset({ runId, stepId, at, cascadedFrom: opts.from });
|
|
2993
|
+
await store.appendFact(runId, fact);
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
const replayDispatcher = makeDispatcher(replayDeps);
|
|
2997
|
+
await replayDispatcher.advance(runId);
|
|
2998
|
+
if (!fireHooks) await drainInline(replayDispatcher, queue);
|
|
2999
|
+
}
|
|
3000
|
+
return { replay };
|
|
3001
|
+
}
|
|
3002
|
+
var MAX_REPLAY_DISPATCHES = 4096;
|
|
3003
|
+
async function drainInline(dispatcher, queue) {
|
|
3004
|
+
for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
|
|
3005
|
+
const messages = await queue.dequeue({ count: 1 });
|
|
3006
|
+
if (messages.length === 0) return;
|
|
3007
|
+
for (const msg of messages) await dispatcher.dispatchMessage(msg);
|
|
1839
3008
|
}
|
|
1840
|
-
return { name: "Error", message: String(err) };
|
|
1841
3009
|
}
|
|
1842
3010
|
|
|
1843
3011
|
// src/worker.ts
|
|
@@ -1852,12 +3020,14 @@ var WorkerImpl = class {
|
|
|
1852
3020
|
this.concurrency = Math.max(1, config?.concurrency ?? DEFAULT_CONCURRENCY);
|
|
1853
3021
|
this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
1854
3022
|
this.signal = config?.signal;
|
|
3023
|
+
this.dispatcher = makeDispatcher(deps);
|
|
1855
3024
|
}
|
|
1856
3025
|
deps;
|
|
1857
3026
|
inFlight = 0;
|
|
1858
3027
|
concurrency;
|
|
1859
3028
|
pollIntervalMs;
|
|
1860
3029
|
signal;
|
|
3030
|
+
dispatcher;
|
|
1861
3031
|
async run() {
|
|
1862
3032
|
while (!this.aborted()) {
|
|
1863
3033
|
const slots = this.concurrency - this.inFlight;
|
|
@@ -1876,24 +3046,22 @@ var WorkerImpl = class {
|
|
|
1876
3046
|
}
|
|
1877
3047
|
async runOnce(opts) {
|
|
1878
3048
|
const limit = Math.max(1, opts?.maxSteps ?? this.concurrency);
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
Math.min(remaining, this.concurrency)
|
|
1884
|
-
);
|
|
1885
|
-
if (messages.length === 0) break;
|
|
1886
|
-
await Promise.all(messages.map((m) => this.dispatchSafely(m)));
|
|
1887
|
-
processed += messages.length;
|
|
1888
|
-
}
|
|
1889
|
-
return { processed };
|
|
3049
|
+
return this.pump({
|
|
3050
|
+
shouldContinue: (processed) => processed < limit,
|
|
3051
|
+
batchSize: (processed) => Math.min(limit - processed, this.concurrency)
|
|
3052
|
+
});
|
|
1890
3053
|
}
|
|
1891
3054
|
async runUntilEmpty(opts) {
|
|
1892
3055
|
const deadline = opts?.deadline;
|
|
3056
|
+
return this.pump({
|
|
3057
|
+
shouldContinue: () => deadline === void 0 || Date.now() < deadline,
|
|
3058
|
+
batchSize: () => this.concurrency
|
|
3059
|
+
});
|
|
3060
|
+
}
|
|
3061
|
+
async pump(opts) {
|
|
1893
3062
|
let processed = 0;
|
|
1894
|
-
while (!this.aborted()) {
|
|
1895
|
-
|
|
1896
|
-
const messages = await this.dequeue(this.concurrency);
|
|
3063
|
+
while (!this.aborted() && opts.shouldContinue(processed)) {
|
|
3064
|
+
const messages = await this.dequeue(opts.batchSize(processed));
|
|
1897
3065
|
if (messages.length === 0) break;
|
|
1898
3066
|
await Promise.all(messages.map((m) => this.dispatchSafely(m)));
|
|
1899
3067
|
processed += messages.length;
|
|
@@ -1911,10 +3079,12 @@ var WorkerImpl = class {
|
|
|
1911
3079
|
}
|
|
1912
3080
|
async dispatchSafely(msg) {
|
|
1913
3081
|
try {
|
|
1914
|
-
await dispatchMessage(
|
|
3082
|
+
await this.dispatcher.dispatchMessage(msg);
|
|
1915
3083
|
} catch (err) {
|
|
1916
|
-
this.deps.
|
|
1917
|
-
|
|
3084
|
+
this.deps.emitLog({
|
|
3085
|
+
level: "error",
|
|
3086
|
+
msg: "worker.dispatch threw uncaught",
|
|
3087
|
+
attrs: { error: String(err) }
|
|
1918
3088
|
});
|
|
1919
3089
|
try {
|
|
1920
3090
|
await this.deps.queue.nack(msg.receipt);
|
|
@@ -1939,64 +3109,24 @@ var WorkerImpl = class {
|
|
|
1939
3109
|
};
|
|
1940
3110
|
|
|
1941
3111
|
// src/runtime.ts
|
|
1942
|
-
var NagiValidationError = class extends Error {
|
|
1943
|
-
issues;
|
|
1944
|
-
constructor(issues) {
|
|
1945
|
-
super(issues.map((i) => i.message).join("; "));
|
|
1946
|
-
this.name = "NagiValidationError";
|
|
1947
|
-
this.issues = issues;
|
|
1948
|
-
}
|
|
1949
|
-
};
|
|
1950
|
-
var NagiRuntimeError = class extends Error {
|
|
1951
|
-
constructor(message) {
|
|
1952
|
-
super(message);
|
|
1953
|
-
this.name = "NagiRuntimeError";
|
|
1954
|
-
}
|
|
1955
|
-
};
|
|
1956
|
-
var NagiCanceledError = class extends Error {
|
|
1957
|
-
runId;
|
|
1958
|
-
canceledByRunId;
|
|
1959
|
-
concurrencyKey;
|
|
1960
|
-
constructor(args) {
|
|
1961
|
-
super(
|
|
1962
|
-
`Run ${args.runId} was canceled (superseded by run ${args.canceledByRunId} for concurrency key "${args.concurrencyKey}").`
|
|
1963
|
-
);
|
|
1964
|
-
this.name = "NagiCanceledError";
|
|
1965
|
-
this.runId = args.runId;
|
|
1966
|
-
this.canceledByRunId = args.canceledByRunId;
|
|
1967
|
-
this.concurrencyKey = args.concurrencyKey;
|
|
1968
|
-
this.cause = {
|
|
1969
|
-
canceledByRunId: args.canceledByRunId,
|
|
1970
|
-
concurrencyKey: args.concurrencyKey
|
|
1971
|
-
};
|
|
1972
|
-
}
|
|
1973
|
-
};
|
|
1974
|
-
var NagiSnapshotDriftError = class extends Error {
|
|
1975
|
-
runId;
|
|
1976
|
-
expected;
|
|
1977
|
-
actual;
|
|
1978
|
-
constructor(args) {
|
|
1979
|
-
super(
|
|
1980
|
-
`Run ${args.runId} was pinned to flow hash ${args.expected.slice(0, 12)}\u2026 but the live flow's hash is ${args.actual.slice(0, 12)}\u2026. Pass replayOpts.allowDrift = true to replay against the live code anyway.`
|
|
1981
|
-
);
|
|
1982
|
-
this.name = "NagiSnapshotDriftError";
|
|
1983
|
-
this.runId = args.runId;
|
|
1984
|
-
this.expected = args.expected;
|
|
1985
|
-
this.actual = args.actual;
|
|
1986
|
-
}
|
|
1987
|
-
};
|
|
1988
3112
|
async function nagiImpl(config) {
|
|
1989
3113
|
const clock = config.clock ?? new InMemoryClock();
|
|
3114
|
+
const emitLog = makeEmit(config.onLog);
|
|
1990
3115
|
await config.queue.ensureSchema?.();
|
|
1991
|
-
const
|
|
1992
|
-
const
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
3116
|
+
const registry = makeFlowRegistry(config.flows);
|
|
3117
|
+
const streamTransport = config.streamTransport ?? asStreamTransport(config.store);
|
|
3118
|
+
if (streamTransport === void 0) {
|
|
3119
|
+
for (const f of registry.all) {
|
|
3120
|
+
for (const [stepId, step] of Object.entries(asStepMapWithDefs(f.steps))) {
|
|
3121
|
+
if (getDef(step).kind !== "streaming") continue;
|
|
3122
|
+
throw new NagiRuntimeError(
|
|
3123
|
+
`Flow "${f.id}" has a streaming step "${stepId}" (b.streamingTask), but no StreamTransport is configured \u2014 it cannot transport ephemeral chunks. Pass streamTransport (or a store that implements it, e.g. the in-memory store) or remove the streaming step.`
|
|
3124
|
+
);
|
|
3125
|
+
}
|
|
1998
3126
|
}
|
|
1999
|
-
|
|
3127
|
+
}
|
|
3128
|
+
const flowHashById = /* @__PURE__ */ new Map();
|
|
3129
|
+
for (const f of registry.all) {
|
|
2000
3130
|
const dag = await canonicalize(f);
|
|
2001
3131
|
const flowHash = await sha256Canonical(dag);
|
|
2002
3132
|
flowHashById.set(f.id, flowHash);
|
|
@@ -2008,53 +3138,51 @@ async function nagiImpl(config) {
|
|
|
2008
3138
|
const previousHash = await config.store.getRef(f.id);
|
|
2009
3139
|
if (previousHash !== flowHash) {
|
|
2010
3140
|
await config.store.setRef(f.id, flowHash);
|
|
2011
|
-
await config.store.appendGlobalFact(
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
3141
|
+
await config.store.appendGlobalFact(
|
|
3142
|
+
Facts.flowRefUpdated({
|
|
3143
|
+
flowId: f.id,
|
|
3144
|
+
from: previousHash,
|
|
3145
|
+
to: flowHash,
|
|
3146
|
+
at: clock.now()
|
|
3147
|
+
})
|
|
3148
|
+
);
|
|
2018
3149
|
}
|
|
2019
3150
|
}
|
|
2020
3151
|
const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
|
|
2021
3152
|
async function flowFor(runId) {
|
|
2022
3153
|
const runState = await config.store.loadRunState(runId);
|
|
2023
|
-
|
|
2024
|
-
if (!flow2) {
|
|
2025
|
-
throw new NagiRuntimeError(
|
|
2026
|
-
`Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
|
|
2027
|
-
);
|
|
2028
|
-
}
|
|
2029
|
-
return flow2;
|
|
3154
|
+
return registry.requireForRun(runState.flowId, runId);
|
|
2030
3155
|
}
|
|
2031
3156
|
function lookupFlow(flowId) {
|
|
2032
|
-
return
|
|
3157
|
+
return registry.get(flowId);
|
|
2033
3158
|
}
|
|
2034
|
-
async function startRunInternal(
|
|
2035
|
-
|
|
3159
|
+
async function startRunInternal({
|
|
3160
|
+
flow: flow2,
|
|
3161
|
+
validatedInput,
|
|
3162
|
+
runId,
|
|
3163
|
+
parent
|
|
3164
|
+
}) {
|
|
2036
3165
|
const startedAt = clock.now();
|
|
2037
3166
|
const flowHash = flowHashById.get(flow2.id);
|
|
2038
|
-
const fact = {
|
|
2039
|
-
kind: "flow.started",
|
|
3167
|
+
const fact = Facts.flowStarted({
|
|
2040
3168
|
runId,
|
|
2041
3169
|
flowId: flow2.id,
|
|
2042
3170
|
input: validatedInput,
|
|
2043
3171
|
at: startedAt,
|
|
2044
|
-
...flowHash !== void 0 ? { flowHash } : {},
|
|
2045
3172
|
codeVersion,
|
|
2046
|
-
...
|
|
2047
|
-
|
|
3173
|
+
...compact({
|
|
3174
|
+
flowHash,
|
|
3175
|
+
parent: parent !== void 0 ? { runId: parent.runId, stepId: parent.stepId } : void 0
|
|
3176
|
+
})
|
|
3177
|
+
});
|
|
2048
3178
|
let concurrencyArg;
|
|
2049
3179
|
if (flow2.concurrency !== void 0) {
|
|
2050
3180
|
const derived = flow2.concurrency.keyFn(validatedInput);
|
|
2051
3181
|
if (typeof derived !== "string" || derived.length === 0) {
|
|
2052
|
-
throw
|
|
2053
|
-
{
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
}
|
|
2057
|
-
]);
|
|
3182
|
+
throw validationError(
|
|
3183
|
+
`flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
3184
|
+
["concurrency", "keyFn"]
|
|
3185
|
+
);
|
|
2058
3186
|
}
|
|
2059
3187
|
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
2060
3188
|
}
|
|
@@ -2083,19 +3211,13 @@ async function nagiImpl(config) {
|
|
|
2083
3211
|
error: serialized,
|
|
2084
3212
|
at: c.fact.at
|
|
2085
3213
|
};
|
|
2086
|
-
await fireHook(
|
|
2087
|
-
|
|
2088
|
-
errorEvent,
|
|
2089
|
-
"flow.onError",
|
|
2090
|
-
dispatchDeps
|
|
2091
|
-
);
|
|
2092
|
-
await fireHook(
|
|
3214
|
+
await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
|
|
3215
|
+
await hooks.fireHook(
|
|
2093
3216
|
config.hooks?.onFlowError,
|
|
2094
3217
|
errorEvent,
|
|
2095
|
-
"onFlowError"
|
|
2096
|
-
dispatchDeps
|
|
3218
|
+
"onFlowError"
|
|
2097
3219
|
);
|
|
2098
|
-
await propagateToParent(
|
|
3220
|
+
await dispatcher.propagateToParent(c.runId, {
|
|
2099
3221
|
kind: "canceled",
|
|
2100
3222
|
error: serialized
|
|
2101
3223
|
});
|
|
@@ -2112,24 +3234,14 @@ async function nagiImpl(config) {
|
|
|
2112
3234
|
input: validatedInput,
|
|
2113
3235
|
at: startedAt
|
|
2114
3236
|
};
|
|
2115
|
-
await fireHook(
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
"flow.onStart",
|
|
2119
|
-
dispatchDeps
|
|
2120
|
-
);
|
|
2121
|
-
await fireHook(
|
|
2122
|
-
config.hooks?.onFlowStart,
|
|
2123
|
-
startEvent,
|
|
2124
|
-
"onFlowStart",
|
|
2125
|
-
dispatchDeps
|
|
2126
|
-
);
|
|
2127
|
-
await advance(dispatchDeps, runId);
|
|
3237
|
+
await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
|
|
3238
|
+
await hooks.fireHook(config.hooks?.onFlowStart, startEvent, "onFlowStart");
|
|
3239
|
+
await dispatcher.advance(runId);
|
|
2128
3240
|
return { started: true };
|
|
2129
3241
|
}
|
|
2130
3242
|
async function startChildRun(args) {
|
|
2131
3243
|
const { child, childInput, parent } = args;
|
|
2132
|
-
if (!
|
|
3244
|
+
if (!registry.has(child.id)) {
|
|
2133
3245
|
throw new NagiRuntimeError(
|
|
2134
3246
|
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
2135
3247
|
);
|
|
@@ -2151,20 +3263,16 @@ async function nagiImpl(config) {
|
|
|
2151
3263
|
}
|
|
2152
3264
|
async function cancelRunRecursive(runId, args) {
|
|
2153
3265
|
const state = await config.store.loadRunState(runId);
|
|
2154
|
-
if (state
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
3266
|
+
if (isTerminalRun(state)) {
|
|
3267
|
+
emitLog({
|
|
3268
|
+
level: "info",
|
|
3269
|
+
msg: "nagi: cancel skipped \u2014 run already terminal",
|
|
3270
|
+
attrs: { runId, status: runStatusOf(state) }
|
|
2158
3271
|
});
|
|
2159
3272
|
return;
|
|
2160
3273
|
}
|
|
2161
|
-
const flow2 =
|
|
2162
|
-
const canceledFact =
|
|
2163
|
-
...args,
|
|
2164
|
-
kind: "flow.canceled",
|
|
2165
|
-
runId,
|
|
2166
|
-
at: clock.now()
|
|
2167
|
-
};
|
|
3274
|
+
const flow2 = registry.get(state.flowId);
|
|
3275
|
+
const canceledFact = Facts.flowCanceled(runId, args, clock.now());
|
|
2168
3276
|
await config.store.appendFact(runId, canceledFact);
|
|
2169
3277
|
const cancelError = {
|
|
2170
3278
|
name: "NagiCanceledError",
|
|
@@ -2177,13 +3285,8 @@ async function nagiImpl(config) {
|
|
|
2177
3285
|
error: cancelError,
|
|
2178
3286
|
at: clock.now()
|
|
2179
3287
|
};
|
|
2180
|
-
await fireHook(flow2.onError, event, "flow.onError"
|
|
2181
|
-
await fireHook(
|
|
2182
|
-
config.hooks?.onFlowError,
|
|
2183
|
-
event,
|
|
2184
|
-
"onFlowError",
|
|
2185
|
-
dispatchDeps
|
|
2186
|
-
);
|
|
3288
|
+
await hooks.fireHook(flow2.onError, event, "flow.onError");
|
|
3289
|
+
await hooks.fireHook(config.hooks?.onFlowError, event, "onFlowError");
|
|
2187
3290
|
}
|
|
2188
3291
|
const children = await config.store.listChildren(runId);
|
|
2189
3292
|
for (const childId of children) {
|
|
@@ -2193,7 +3296,7 @@ async function nagiImpl(config) {
|
|
|
2193
3296
|
note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
2194
3297
|
});
|
|
2195
3298
|
}
|
|
2196
|
-
await propagateToParent(
|
|
3299
|
+
await dispatcher.propagateToParent(runId, {
|
|
2197
3300
|
kind: "canceled",
|
|
2198
3301
|
error: cancelError
|
|
2199
3302
|
});
|
|
@@ -2205,29 +3308,46 @@ async function nagiImpl(config) {
|
|
|
2205
3308
|
store: config.store,
|
|
2206
3309
|
queue: config.queue,
|
|
2207
3310
|
clock,
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
3311
|
+
emitLog,
|
|
3312
|
+
// The one fork point for heartbeat tuning: collapse the public optionals to
|
|
3313
|
+
// a single required config here so the dispatch internals never re-check it.
|
|
3314
|
+
heartbeat: {
|
|
3315
|
+
intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
|
|
3316
|
+
leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS
|
|
3317
|
+
},
|
|
3318
|
+
...compact({
|
|
3319
|
+
hooks: config.hooks,
|
|
3320
|
+
defaultRetry: config.defaultRetry,
|
|
3321
|
+
streamTransport
|
|
3322
|
+
})
|
|
2211
3323
|
};
|
|
3324
|
+
const dispatcher = makeDispatcher(dispatchDeps);
|
|
3325
|
+
const hooks = makeHooks(dispatchDeps);
|
|
3326
|
+
const signals = makeSignals({
|
|
3327
|
+
dispatcher,
|
|
3328
|
+
store: config.store,
|
|
3329
|
+
clock,
|
|
3330
|
+
registry,
|
|
3331
|
+
hooks,
|
|
3332
|
+
emitLog,
|
|
3333
|
+
...compact({ flowHooks: config.hooks })
|
|
3334
|
+
});
|
|
3335
|
+
const replayer = makeReplay({
|
|
3336
|
+
...dispatchDeps,
|
|
3337
|
+
registry,
|
|
3338
|
+
hashFor: (id) => flowHashById.get(id)
|
|
3339
|
+
});
|
|
2212
3340
|
const wf = {
|
|
2213
3341
|
async start(flow2, input, opts) {
|
|
2214
3342
|
return wf.startById(flow2.id, input, opts);
|
|
2215
3343
|
},
|
|
2216
3344
|
async startById(flowId, input, opts) {
|
|
2217
|
-
const flow2 =
|
|
2218
|
-
if (!flow2) {
|
|
2219
|
-
throw new NagiRuntimeError(
|
|
2220
|
-
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
2221
|
-
);
|
|
2222
|
-
}
|
|
3345
|
+
const flow2 = registry.require(flowId);
|
|
2223
3346
|
let runId;
|
|
2224
3347
|
if (opts?.runId !== void 0) {
|
|
2225
3348
|
if (typeof opts.runId !== "string" || opts.runId.length === 0) {
|
|
2226
|
-
throw
|
|
2227
|
-
|
|
2228
|
-
message: "opts.runId must be a non-empty string",
|
|
2229
|
-
path: ["runId"]
|
|
2230
|
-
}
|
|
3349
|
+
throw validationError("opts.runId must be a non-empty string", [
|
|
3350
|
+
"runId"
|
|
2231
3351
|
]);
|
|
2232
3352
|
}
|
|
2233
3353
|
runId = opts.runId;
|
|
@@ -2238,89 +3358,7 @@ async function nagiImpl(config) {
|
|
|
2238
3358
|
await startRunInternal({ flow: flow2, validatedInput: validated, runId });
|
|
2239
3359
|
return runId;
|
|
2240
3360
|
},
|
|
2241
|
-
|
|
2242
|
-
const runState = await config.store.loadRunState(runId);
|
|
2243
|
-
const flow2 = flowsById.get(runState.flowId);
|
|
2244
|
-
if (!flow2) {
|
|
2245
|
-
throw new NagiRuntimeError(
|
|
2246
|
-
`Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
|
|
2247
|
-
);
|
|
2248
|
-
}
|
|
2249
|
-
let stepId;
|
|
2250
|
-
let def;
|
|
2251
|
-
const direct = flow2.steps[signalName];
|
|
2252
|
-
if (direct !== void 0) {
|
|
2253
|
-
const d = getDef(direct);
|
|
2254
|
-
if (d.kind === "signal" && d.names === void 0) {
|
|
2255
|
-
stepId = signalName;
|
|
2256
|
-
def = d;
|
|
2257
|
-
}
|
|
2258
|
-
}
|
|
2259
|
-
if (stepId === void 0) {
|
|
2260
|
-
for (const [id, s] of Object.entries(flow2.steps)) {
|
|
2261
|
-
const d = getDef(s);
|
|
2262
|
-
if (d.kind === "signal" && d.names?.includes(signalName)) {
|
|
2263
|
-
stepId = id;
|
|
2264
|
-
def = d;
|
|
2265
|
-
break;
|
|
2266
|
-
}
|
|
2267
|
-
}
|
|
2268
|
-
}
|
|
2269
|
-
if (stepId === void 0 || def === void 0) {
|
|
2270
|
-
throw new NagiRuntimeError(
|
|
2271
|
-
`Flow "${flow2.id}" has no signal step accepting "${signalName}".`
|
|
2272
|
-
);
|
|
2273
|
-
}
|
|
2274
|
-
const stepState = runState.steps[stepId];
|
|
2275
|
-
if (stepState?.status !== "running") {
|
|
2276
|
-
if (stepState?.status === "completed") {
|
|
2277
|
-
config.logger?.info("nagi: signal arrived after step resolved", {
|
|
2278
|
-
runId,
|
|
2279
|
-
stepId,
|
|
2280
|
-
signalName
|
|
2281
|
-
});
|
|
2282
|
-
return;
|
|
2283
|
-
}
|
|
2284
|
-
throw new NagiRuntimeError(
|
|
2285
|
-
`Step "${stepId}" is not waiting for signal (status: ${stepState?.status ?? "pending"}).`
|
|
2286
|
-
);
|
|
2287
|
-
}
|
|
2288
|
-
const validated = await validate(def.schema, payload);
|
|
2289
|
-
const attempt = stepState.attempts > 0 ? stepState.attempts : 1;
|
|
2290
|
-
const carriesAlias = signalName !== stepId;
|
|
2291
|
-
await config.store.appendFact(runId, {
|
|
2292
|
-
kind: "signal.received",
|
|
2293
|
-
runId,
|
|
2294
|
-
stepId,
|
|
2295
|
-
payload: validated,
|
|
2296
|
-
at: clock.now(),
|
|
2297
|
-
...carriesAlias ? { signalName } : {}
|
|
2298
|
-
});
|
|
2299
|
-
const completedFact = {
|
|
2300
|
-
kind: "step.completed",
|
|
2301
|
-
runId,
|
|
2302
|
-
stepId,
|
|
2303
|
-
attempt,
|
|
2304
|
-
output: validated,
|
|
2305
|
-
at: clock.now()
|
|
2306
|
-
};
|
|
2307
|
-
await config.store.completeStep(runId, stepId, validated, completedFact);
|
|
2308
|
-
await fireHook(
|
|
2309
|
-
config.hooks?.onSignalReceived,
|
|
2310
|
-
{
|
|
2311
|
-
runId,
|
|
2312
|
-
flowId: flow2.id,
|
|
2313
|
-
stepId,
|
|
2314
|
-
attempt,
|
|
2315
|
-
kind: "signal",
|
|
2316
|
-
payload: validated,
|
|
2317
|
-
at: clock.now()
|
|
2318
|
-
},
|
|
2319
|
-
"onSignalReceived",
|
|
2320
|
-
dispatchDeps
|
|
2321
|
-
);
|
|
2322
|
-
await advance(dispatchDeps, runId);
|
|
2323
|
-
},
|
|
3361
|
+
signal: signals.signal,
|
|
2324
3362
|
async cancel(runId, opts) {
|
|
2325
3363
|
await cancelRunRecursive(runId, {
|
|
2326
3364
|
cause: "explicit",
|
|
@@ -2329,11 +3367,12 @@ async function nagiImpl(config) {
|
|
|
2329
3367
|
},
|
|
2330
3368
|
operator() {
|
|
2331
3369
|
return makeOperator({
|
|
2332
|
-
|
|
3370
|
+
dispatcher,
|
|
3371
|
+
store: config.store,
|
|
2333
3372
|
clock,
|
|
2334
|
-
|
|
3373
|
+
registry,
|
|
2335
3374
|
cancelRunRecursive,
|
|
2336
|
-
|
|
3375
|
+
emitLog
|
|
2337
3376
|
});
|
|
2338
3377
|
},
|
|
2339
3378
|
worker(workerConfig) {
|
|
@@ -2344,99 +3383,34 @@ async function nagiImpl(config) {
|
|
|
2344
3383
|
}
|
|
2345
3384
|
return makeWorker({ ...dispatchDeps, clock }, workerConfig);
|
|
2346
3385
|
},
|
|
2347
|
-
|
|
2348
|
-
const runState = await config.store.loadRunState(runId);
|
|
2349
|
-
const liveFlow = flowsById.get(runState.flowId);
|
|
2350
|
-
if (!liveFlow) {
|
|
2351
|
-
throw new NagiRuntimeError(
|
|
2352
|
-
`Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
|
|
2353
|
-
);
|
|
2354
|
-
}
|
|
2355
|
-
if (runState.status === "canceled") {
|
|
2356
|
-
throw new NagiRuntimeError(
|
|
2357
|
-
`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.`
|
|
2358
|
-
);
|
|
2359
|
-
}
|
|
2360
|
-
if (opts.mode === "inspect") return;
|
|
2361
|
-
const fireHooks = opts.fireHooks !== false;
|
|
2362
|
-
const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
|
|
2363
|
-
let replayDeps = baseDeps;
|
|
2364
|
-
let effectiveFlow = liveFlow;
|
|
2365
|
-
const pinned = runState.flowHash;
|
|
2366
|
-
if (pinned !== void 0) {
|
|
2367
|
-
const liveHash = flowHashById.get(liveFlow.id);
|
|
2368
|
-
if (liveHash !== void 0 && liveHash !== pinned) {
|
|
2369
|
-
if (!opts.allowDrift) {
|
|
2370
|
-
throw new NagiSnapshotDriftError({
|
|
2371
|
-
runId,
|
|
2372
|
-
expected: pinned,
|
|
2373
|
-
actual: liveHash
|
|
2374
|
-
});
|
|
2375
|
-
}
|
|
2376
|
-
const snapshot = await config.store.loadSnapshot(pinned);
|
|
2377
|
-
if (snapshot === null) {
|
|
2378
|
-
throw new NagiRuntimeError(
|
|
2379
|
-
`Run ${runId} pinned to flow hash ${pinned.slice(0, 12)}\u2026 but no snapshot with that hash was found. Cannot replay with allowDrift.`
|
|
2380
|
-
);
|
|
2381
|
-
}
|
|
2382
|
-
const synthesized = synthesizeReplayFlow(
|
|
2383
|
-
snapshot.dag,
|
|
2384
|
-
liveFlow
|
|
2385
|
-
);
|
|
2386
|
-
replayDeps = { ...baseDeps, flowFor: async () => synthesized };
|
|
2387
|
-
effectiveFlow = synthesized;
|
|
2388
|
-
}
|
|
2389
|
-
}
|
|
2390
|
-
if (opts.from !== void 0) {
|
|
2391
|
-
if (runState.status === "running") {
|
|
2392
|
-
throw new NagiRuntimeError(
|
|
2393
|
-
`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.`
|
|
2394
|
-
);
|
|
2395
|
-
}
|
|
2396
|
-
if (!(opts.from in effectiveFlow.steps)) {
|
|
2397
|
-
throw new NagiValidationError([
|
|
2398
|
-
{
|
|
2399
|
-
message: `replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
|
|
2400
|
-
path: ["from"]
|
|
2401
|
-
}
|
|
2402
|
-
]);
|
|
2403
|
-
}
|
|
2404
|
-
const cascade = descendantsOf(effectiveFlow, opts.from);
|
|
2405
|
-
const at = clock.now();
|
|
2406
|
-
for (const stepId of cascade) {
|
|
2407
|
-
const fact = stepId === opts.from ? { kind: "step.reset", runId, at, stepId } : {
|
|
2408
|
-
kind: "step.reset",
|
|
2409
|
-
runId,
|
|
2410
|
-
at,
|
|
2411
|
-
stepId,
|
|
2412
|
-
cascadedFrom: opts.from
|
|
2413
|
-
};
|
|
2414
|
-
await config.store.appendFact(runId, fact);
|
|
2415
|
-
}
|
|
2416
|
-
}
|
|
2417
|
-
await advance(replayDeps, runId);
|
|
2418
|
-
if (!fireHooks) await drainInline(replayDeps);
|
|
2419
|
-
},
|
|
3386
|
+
replay: replayer.replay,
|
|
2420
3387
|
async queryRuns(opts = {}) {
|
|
2421
3388
|
if (opts.latest === true) {
|
|
2422
3389
|
if (opts.limit !== void 0 || opts.cursor !== void 0) {
|
|
2423
|
-
throw
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
}
|
|
2428
|
-
]);
|
|
3390
|
+
throw validationError(
|
|
3391
|
+
"queryRuns: `latest: true` is incompatible with `limit` / `cursor` \u2014 `latest` returns at most one row.",
|
|
3392
|
+
["latest"]
|
|
3393
|
+
);
|
|
2429
3394
|
}
|
|
2430
3395
|
}
|
|
2431
3396
|
return config.store.queryRuns(opts);
|
|
2432
3397
|
},
|
|
3398
|
+
subscribe(runId, stepId, opts) {
|
|
3399
|
+
if (!registry.isStreaming(stepId)) {
|
|
3400
|
+
throw new NagiRuntimeError(
|
|
3401
|
+
`wf.subscribe: step "${stepId}" is not a streaming step (b.streamingTask) in any registered flow. Only streaming steps can be subscribed to.`
|
|
3402
|
+
);
|
|
3403
|
+
}
|
|
3404
|
+
return streamTransport.subscribeStream(
|
|
3405
|
+
runId,
|
|
3406
|
+
stepId,
|
|
3407
|
+
opts
|
|
3408
|
+
);
|
|
3409
|
+
},
|
|
2433
3410
|
async pruneFacts(opts) {
|
|
2434
3411
|
if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
|
|
2435
|
-
throw
|
|
2436
|
-
|
|
2437
|
-
message: "pruneFacts: `olderThan` must be a valid Date.",
|
|
2438
|
-
path: ["olderThan"]
|
|
2439
|
-
}
|
|
3412
|
+
throw validationError("pruneFacts: `olderThan` must be a valid Date.", [
|
|
3413
|
+
"olderThan"
|
|
2440
3414
|
]);
|
|
2441
3415
|
}
|
|
2442
3416
|
const statuses = opts.statuses ?? [
|
|
@@ -2444,22 +3418,18 @@ async function nagiImpl(config) {
|
|
|
2444
3418
|
];
|
|
2445
3419
|
for (const s of statuses) {
|
|
2446
3420
|
if (s !== "completed" && s !== "failed" && s !== "canceled") {
|
|
2447
|
-
throw
|
|
2448
|
-
{
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
}
|
|
2452
|
-
]);
|
|
3421
|
+
throw validationError(
|
|
3422
|
+
`pruneFacts: status "${s}" is not prunable. Allowed: "completed" | "failed" | "canceled".`,
|
|
3423
|
+
["statuses"]
|
|
3424
|
+
);
|
|
2453
3425
|
}
|
|
2454
3426
|
}
|
|
2455
3427
|
const batchSize = opts.batchSize ?? 1e3;
|
|
2456
3428
|
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
|
2457
|
-
throw
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
}
|
|
2462
|
-
]);
|
|
3429
|
+
throw validationError(
|
|
3430
|
+
"pruneFacts: `batchSize` must be a positive integer.",
|
|
3431
|
+
["batchSize"]
|
|
3432
|
+
);
|
|
2463
3433
|
}
|
|
2464
3434
|
const keepSummary = opts.keepSummary ?? true;
|
|
2465
3435
|
return config.store.pruneFacts({
|
|
@@ -2483,11 +3453,14 @@ async function nagiRun(config) {
|
|
|
2483
3453
|
const internal = new AbortController();
|
|
2484
3454
|
const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
|
|
2485
3455
|
const worker = wf.worker({ ...config.worker, signal });
|
|
3456
|
+
const emitLog = makeEmit(config.onLog);
|
|
2486
3457
|
const loop = worker.run();
|
|
2487
3458
|
loop.catch((err) => {
|
|
2488
3459
|
if (signal.aborted) return;
|
|
2489
|
-
|
|
2490
|
-
|
|
3460
|
+
emitLog({
|
|
3461
|
+
level: "error",
|
|
3462
|
+
msg: "nagi.run: worker exited unexpectedly",
|
|
3463
|
+
attrs: { error: String(err) }
|
|
2491
3464
|
});
|
|
2492
3465
|
});
|
|
2493
3466
|
let stopping;
|
|
@@ -2510,218 +3483,11 @@ var nagi = Object.assign(
|
|
|
2510
3483
|
function mintRunId() {
|
|
2511
3484
|
return `run-${crypto.randomUUID()}`;
|
|
2512
3485
|
}
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
const messages = await deps.queue.dequeue({ count: 1 });
|
|
2517
|
-
if (messages.length === 0) return;
|
|
2518
|
-
for (const msg of messages) await dispatchMessage(deps, msg);
|
|
2519
|
-
}
|
|
2520
|
-
}
|
|
2521
|
-
function makeOperator(o) {
|
|
2522
|
-
const { deps, clock, flowsById, cancelRunRecursive } = o;
|
|
2523
|
-
const store = deps.store;
|
|
2524
|
-
function resolveFlow(flowId, runId) {
|
|
2525
|
-
const flow2 = flowsById.get(flowId);
|
|
2526
|
-
if (!flow2) {
|
|
2527
|
-
throw new NagiRuntimeError(
|
|
2528
|
-
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
2529
|
-
);
|
|
2530
|
-
}
|
|
2531
|
-
return flow2;
|
|
2532
|
-
}
|
|
2533
|
-
async function skip(runId, stepId, opts) {
|
|
2534
|
-
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2535
|
-
throw new NagiValidationError([
|
|
2536
|
-
{
|
|
2537
|
-
message: "operator.skip: opts.actor must be a non-empty string",
|
|
2538
|
-
path: ["actor"]
|
|
2539
|
-
}
|
|
2540
|
-
]);
|
|
2541
|
-
}
|
|
2542
|
-
const cascade = opts.cascade ?? "skip";
|
|
2543
|
-
const state = await store.loadRunState(runId);
|
|
2544
|
-
const flow2 = resolveFlow(state.flowId, runId);
|
|
2545
|
-
if (!(stepId in flow2.steps)) {
|
|
2546
|
-
throw new NagiValidationError([
|
|
2547
|
-
{
|
|
2548
|
-
message: `operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2549
|
-
path: ["stepId"]
|
|
2550
|
-
}
|
|
2551
|
-
]);
|
|
2552
|
-
}
|
|
2553
|
-
const stepState = state.steps[stepId];
|
|
2554
|
-
if (stepState !== void 0 && (stepState.status === "completed" || stepState.status === "failed" || stepState.status === "skipped" || stepState.status === "canceled")) {
|
|
2555
|
-
o.logger?.info("nagi: operator.skip noop \u2014 step already terminal", {
|
|
2556
|
-
runId,
|
|
2557
|
-
stepId,
|
|
2558
|
-
status: stepState.status
|
|
2559
|
-
});
|
|
2560
|
-
return;
|
|
2561
|
-
}
|
|
2562
|
-
if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
|
|
2563
|
-
throw new NagiRuntimeError(
|
|
2564
|
-
`operator.skip: run ${runId} is already terminal (${state.status}); cannot skip step "${stepId}".`
|
|
2565
|
-
);
|
|
2566
|
-
}
|
|
2567
|
-
const fact = {
|
|
2568
|
-
kind: "step.skipped",
|
|
2569
|
-
runId,
|
|
2570
|
-
at: clock.now(),
|
|
2571
|
-
stepId,
|
|
2572
|
-
reason: "manual",
|
|
2573
|
-
actor: opts.actor,
|
|
2574
|
-
cascade,
|
|
2575
|
-
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2576
|
-
};
|
|
2577
|
-
await store.appendFact(runId, fact);
|
|
2578
|
-
await advance(deps, runId);
|
|
2579
|
-
}
|
|
2580
|
-
async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
|
|
2581
|
-
const start = Date.now();
|
|
2582
|
-
while (Date.now() - start < deadlineMs) {
|
|
2583
|
-
const s = await store.loadRunState(runId);
|
|
2584
|
-
const ss = s.steps[stepId];
|
|
2585
|
-
if (ss === void 0) return;
|
|
2586
|
-
if (ss.status === "completed" || ss.status === "failed" || ss.status === "skipped" || ss.status === "canceled") {
|
|
2587
|
-
return;
|
|
2588
|
-
}
|
|
2589
|
-
if (s.status === "completed" || s.status === "failed" || s.status === "canceled") {
|
|
2590
|
-
return;
|
|
2591
|
-
}
|
|
2592
|
-
if (ss.attempts > attempt) return;
|
|
2593
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
2594
|
-
}
|
|
2595
|
-
throw new NagiRuntimeError(
|
|
2596
|
-
`operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
|
|
2597
|
-
);
|
|
2598
|
-
}
|
|
2599
|
-
async function retry(runId, stepId, opts) {
|
|
2600
|
-
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2601
|
-
throw new NagiValidationError([
|
|
2602
|
-
{
|
|
2603
|
-
message: "operator.retry: opts.actor must be a non-empty string",
|
|
2604
|
-
path: ["actor"]
|
|
2605
|
-
}
|
|
2606
|
-
]);
|
|
2607
|
-
}
|
|
2608
|
-
const state = await store.loadRunState(runId);
|
|
2609
|
-
if (state.status === "canceled") {
|
|
2610
|
-
throw new NagiRuntimeError(
|
|
2611
|
-
`operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
|
|
2612
|
-
);
|
|
2613
|
-
}
|
|
2614
|
-
const flow2 = resolveFlow(state.flowId, runId);
|
|
2615
|
-
if (!(stepId in flow2.steps)) {
|
|
2616
|
-
throw new NagiValidationError([
|
|
2617
|
-
{
|
|
2618
|
-
message: `operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
2619
|
-
path: ["stepId"]
|
|
2620
|
-
}
|
|
2621
|
-
]);
|
|
2622
|
-
}
|
|
2623
|
-
const stepState = state.steps[stepId];
|
|
2624
|
-
if (stepState !== void 0 && stepState.status === "running") {
|
|
2625
|
-
const abortFact = {
|
|
2626
|
-
kind: "step.abort-requested",
|
|
2627
|
-
runId,
|
|
2628
|
-
at: clock.now(),
|
|
2629
|
-
stepId,
|
|
2630
|
-
attempt: stepState.attempts,
|
|
2631
|
-
actor: opts.actor,
|
|
2632
|
-
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2633
|
-
};
|
|
2634
|
-
await store.appendFact(runId, abortFact);
|
|
2635
|
-
await waitForStepToSettle(runId, stepId, stepState.attempts, 3e4);
|
|
2636
|
-
}
|
|
2637
|
-
const cascade = descendantsOf(flow2, stepId);
|
|
2638
|
-
const at = clock.now();
|
|
2639
|
-
for (const id of cascade) {
|
|
2640
|
-
const fact = id === stepId ? {
|
|
2641
|
-
kind: "step.reset",
|
|
2642
|
-
runId,
|
|
2643
|
-
at,
|
|
2644
|
-
stepId: id,
|
|
2645
|
-
actor: opts.actor,
|
|
2646
|
-
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2647
|
-
} : {
|
|
2648
|
-
kind: "step.reset",
|
|
2649
|
-
runId,
|
|
2650
|
-
at,
|
|
2651
|
-
stepId: id,
|
|
2652
|
-
cascadedFrom: stepId
|
|
2653
|
-
};
|
|
2654
|
-
await store.appendFact(runId, fact);
|
|
2655
|
-
}
|
|
2656
|
-
await advance(deps, runId);
|
|
2657
|
-
}
|
|
2658
|
-
async function abort(runId, opts) {
|
|
2659
|
-
if (typeof opts.actor !== "string" || opts.actor.length === 0) {
|
|
2660
|
-
throw new NagiValidationError([
|
|
2661
|
-
{
|
|
2662
|
-
message: "operator.abort: opts.actor must be a non-empty string",
|
|
2663
|
-
path: ["actor"]
|
|
2664
|
-
}
|
|
2665
|
-
]);
|
|
2666
|
-
}
|
|
2667
|
-
await cancelRunRecursive(runId, {
|
|
2668
|
-
cause: "operator",
|
|
2669
|
-
reason: opts.note ?? `aborted by operator ${opts.actor}`,
|
|
2670
|
-
actor: opts.actor,
|
|
2671
|
-
...opts.note !== void 0 ? { note: opts.note } : {}
|
|
2672
|
-
});
|
|
2673
|
-
}
|
|
2674
|
-
return { skip, retry, abort };
|
|
2675
|
-
}
|
|
2676
|
-
async function validate(schema, value) {
|
|
2677
|
-
const result = await schema["~standard"].validate(value);
|
|
2678
|
-
if ("issues" in result && result.issues !== void 0) {
|
|
2679
|
-
throw new NagiValidationError(result.issues);
|
|
2680
|
-
}
|
|
2681
|
-
return result.value;
|
|
2682
|
-
}
|
|
2683
|
-
function synthesizeReplayFlow(dag, liveFlow) {
|
|
2684
|
-
const synthesized = {};
|
|
2685
|
-
for (const canonStep of dag.steps) {
|
|
2686
|
-
synthesized[canonStep.id] = attachDef(
|
|
2687
|
-
{ kind: canonStep.kind, id: canonStep.id },
|
|
2688
|
-
{ kind: canonStep.kind }
|
|
2689
|
-
);
|
|
2690
|
-
}
|
|
2691
|
-
for (const canonStep of dag.steps) {
|
|
2692
|
-
const liveStep = liveFlow.steps[canonStep.id];
|
|
2693
|
-
if (liveStep === void 0) {
|
|
2694
|
-
throw new NagiRuntimeError(
|
|
2695
|
-
`Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
|
|
2696
|
-
);
|
|
2697
|
-
}
|
|
2698
|
-
const liveDef = getDef(liveStep);
|
|
2699
|
-
const synthesizedNeeds = {};
|
|
2700
|
-
for (const upstreamId of canonStep.needs) {
|
|
2701
|
-
const upstreamShell = synthesized[upstreamId];
|
|
2702
|
-
if (upstreamShell === void 0) {
|
|
2703
|
-
throw new NagiRuntimeError(
|
|
2704
|
-
`Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
|
|
2705
|
-
);
|
|
2706
|
-
}
|
|
2707
|
-
synthesizedNeeds[upstreamId] = upstreamShell;
|
|
2708
|
-
}
|
|
2709
|
-
const rewiredDef = {
|
|
2710
|
-
...liveDef,
|
|
2711
|
-
needs: synthesizedNeeds
|
|
2712
|
-
};
|
|
2713
|
-
const shell = synthesized[canonStep.id];
|
|
2714
|
-
if (shell === void 0) continue;
|
|
2715
|
-
shell.__def = rewiredDef;
|
|
2716
|
-
}
|
|
2717
|
-
return {
|
|
2718
|
-
id: liveFlow.id,
|
|
2719
|
-
input: liveFlow.input,
|
|
2720
|
-
steps: synthesized,
|
|
2721
|
-
...liveFlow.output !== void 0 ? { output: liveFlow.output } : {}
|
|
2722
|
-
};
|
|
3486
|
+
function asStreamTransport(store) {
|
|
3487
|
+
const s = store;
|
|
3488
|
+
return typeof s.subscribeStream === "function" && typeof s.publishChunk === "function" ? s : void 0;
|
|
2723
3489
|
}
|
|
2724
3490
|
|
|
2725
|
-
export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiCanceledError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
|
|
3491
|
+
export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiCanceledError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, attemptOf, canonicalize, decideSignal, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
|
|
2726
3492
|
//# sourceMappingURL=index.js.map
|
|
2727
3493
|
//# sourceMappingURL=index.js.map
|