@nagi-js/core 0.1.1-rc.18 → 0.1.1-rc.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-VQTYTI6X.js +1833 -0
- package/dist/chunk-VQTYTI6X.js.map +1 -0
- package/dist/index.d.ts +48 -870
- package/dist/index.js +607 -2310
- package/dist/index.js.map +1 -1
- package/dist/testing.d.ts +15 -0
- package/dist/testing.js +1335 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-DfxwD2MH.d.ts +905 -0
- package/package.json +6 -1
package/dist/index.js
CHANGED
|
@@ -1,330 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
function stepStateOf(runState, stepId) {
|
|
4
|
-
return runState.steps[stepId] ?? PENDING;
|
|
5
|
-
}
|
|
6
|
-
function runStatusOf(state) {
|
|
7
|
-
return state.phase.tag;
|
|
8
|
-
}
|
|
9
|
-
function stepStatusOf(s) {
|
|
10
|
-
switch (s.tag) {
|
|
11
|
-
case "pending":
|
|
12
|
-
return "pending";
|
|
13
|
-
case "running":
|
|
14
|
-
case "awaitingSignal":
|
|
15
|
-
case "awaitingChild":
|
|
16
|
-
case "backoff":
|
|
17
|
-
case "aborting":
|
|
18
|
-
return "running";
|
|
19
|
-
case "completed":
|
|
20
|
-
return "completed";
|
|
21
|
-
case "failed":
|
|
22
|
-
return "failed";
|
|
23
|
-
case "skipped":
|
|
24
|
-
return "skipped";
|
|
25
|
-
case "canceled":
|
|
26
|
-
return "canceled";
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
function outputOf(s) {
|
|
30
|
-
return s.tag === "completed" ? s.output : null;
|
|
31
|
-
}
|
|
32
|
-
function errorOf(s) {
|
|
33
|
-
if (s.tag === "failed" || s.tag === "backoff") return s.error;
|
|
34
|
-
if (s.tag === "canceled" && s.cause.kind === "aborted") return s.cause.error;
|
|
35
|
-
return void 0;
|
|
36
|
-
}
|
|
37
|
-
function attemptOf(s) {
|
|
38
|
-
switch (s.tag) {
|
|
39
|
-
case "running":
|
|
40
|
-
case "awaitingSignal":
|
|
41
|
-
case "awaitingChild":
|
|
42
|
-
case "aborting":
|
|
43
|
-
case "completed":
|
|
44
|
-
case "failed":
|
|
45
|
-
return s.attempt;
|
|
46
|
-
case "backoff":
|
|
47
|
-
return s.failedAttempt;
|
|
48
|
-
case "pending":
|
|
49
|
-
case "skipped":
|
|
50
|
-
case "canceled":
|
|
51
|
-
return 0;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
function resolvedOf(s) {
|
|
55
|
-
if (s.tag === "completed") return { tag: "value", value: s.output };
|
|
56
|
-
if (s.tag === "skipped") return { tag: "skipped" };
|
|
57
|
-
return { tag: "value", value: null };
|
|
58
|
-
}
|
|
59
|
-
function unwrap(r) {
|
|
60
|
-
if (r.tag === "skipped") {
|
|
61
|
-
throw new Error("nagi: upstream was skipped \u2014 its value is unavailable");
|
|
62
|
-
}
|
|
63
|
-
return r.value;
|
|
64
|
-
}
|
|
65
|
-
function isTerminalRun(state) {
|
|
66
|
-
return state.phase.tag !== "pending" && state.phase.tag !== "running";
|
|
67
|
-
}
|
|
68
|
-
function isAbortRequested(s, attempt) {
|
|
69
|
-
return s.tag === "aborting" && s.attempt === attempt;
|
|
70
|
-
}
|
|
71
|
-
function isStepTerminal(s) {
|
|
72
|
-
return s.tag === "completed" || s.tag === "failed" || s.tag === "skipped" || s.tag === "canceled";
|
|
73
|
-
}
|
|
74
|
-
function keep(prev) {
|
|
75
|
-
return { next: prev, anomaly: true };
|
|
76
|
-
}
|
|
77
|
-
function startTarget(stepKind, attempt) {
|
|
78
|
-
switch (stepKind) {
|
|
79
|
-
case "signal":
|
|
80
|
-
return { tag: "awaitingSignal", attempt };
|
|
81
|
-
case "subflow":
|
|
82
|
-
return { tag: "awaitingChild", attempt };
|
|
83
|
-
case "task":
|
|
84
|
-
case "activity":
|
|
85
|
-
case "streaming":
|
|
86
|
-
case "match":
|
|
87
|
-
return { tag: "running", attempt };
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
function stepTransition(prev, fact) {
|
|
91
|
-
switch (fact.kind) {
|
|
92
|
-
case "step.started":
|
|
93
|
-
if (prev.tag === "pending" || prev.tag === "backoff")
|
|
94
|
-
return {
|
|
95
|
-
next: startTarget(fact.stepKind, fact.attempt),
|
|
96
|
-
anomaly: false
|
|
97
|
-
};
|
|
98
|
-
return keep(prev);
|
|
99
|
-
// Terminal facts carry authoritative outcomes, so they settle a step from
|
|
100
|
-
// any non-terminal state; only a terminal→terminal contradiction is flagged.
|
|
101
|
-
case "step.completed":
|
|
102
|
-
if (isStepTerminal(prev)) return keep(prev);
|
|
103
|
-
return {
|
|
104
|
-
next: { tag: "completed", attempt: fact.attempt, output: fact.output },
|
|
105
|
-
anomaly: false
|
|
106
|
-
};
|
|
107
|
-
case "step.failed":
|
|
108
|
-
if (isStepTerminal(prev)) return keep(prev);
|
|
109
|
-
return {
|
|
110
|
-
next: { tag: "failed", attempt: fact.attempt, error: fact.error },
|
|
111
|
-
anomaly: false
|
|
112
|
-
};
|
|
113
|
-
case "step.canceled": {
|
|
114
|
-
if (isStepTerminal(prev)) return keep(prev);
|
|
115
|
-
const cause = prev.tag === "aborting" ? { kind: "aborted", ...compact({ error: fact.error }) } : { kind: "run-canceled" };
|
|
116
|
-
return { next: { tag: "canceled", cause }, anomaly: false };
|
|
117
|
-
}
|
|
118
|
-
case "step.retried":
|
|
119
|
-
if (prev.tag === "running")
|
|
120
|
-
return {
|
|
121
|
-
next: {
|
|
122
|
-
tag: "backoff",
|
|
123
|
-
failedAttempt: fact.attempt,
|
|
124
|
-
retryAt: fact.nextAttemptAt,
|
|
125
|
-
error: fact.error
|
|
126
|
-
},
|
|
127
|
-
anomaly: false
|
|
128
|
-
};
|
|
129
|
-
return keep(prev);
|
|
130
|
-
case "step.skipped":
|
|
131
|
-
if (!isStepTerminal(prev))
|
|
132
|
-
return {
|
|
133
|
-
next: {
|
|
134
|
-
tag: "skipped",
|
|
135
|
-
reason: fact.reason
|
|
136
|
-
},
|
|
137
|
-
anomaly: false
|
|
138
|
-
};
|
|
139
|
-
return keep(prev);
|
|
140
|
-
case "step.abort-requested":
|
|
141
|
-
if (prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild")
|
|
142
|
-
return {
|
|
143
|
-
next: { tag: "aborting", attempt: fact.attempt },
|
|
144
|
-
anomaly: false
|
|
145
|
-
};
|
|
146
|
-
return keep(prev);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
function runCancelCause(fact) {
|
|
150
|
-
switch (fact.cause) {
|
|
151
|
-
case "concurrency":
|
|
152
|
-
return {
|
|
153
|
-
kind: "concurrency",
|
|
154
|
-
canceledByRunId: fact.canceledByRunId,
|
|
155
|
-
concurrencyKey: fact.concurrencyKey
|
|
156
|
-
};
|
|
157
|
-
case "explicit":
|
|
158
|
-
return {
|
|
159
|
-
kind: "explicit",
|
|
160
|
-
reason: fact.reason,
|
|
161
|
-
...compact({ note: fact.note })
|
|
162
|
-
};
|
|
163
|
-
case "operator":
|
|
164
|
-
return {
|
|
165
|
-
kind: "operator",
|
|
166
|
-
actor: fact.actor,
|
|
167
|
-
reason: fact.reason,
|
|
168
|
-
...compact({ note: fact.note })
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
function foldRun(runId, facts) {
|
|
173
|
-
let flowId = "";
|
|
174
|
-
let input = null;
|
|
175
|
-
let phase = { tag: "pending" };
|
|
176
|
-
let parent;
|
|
177
|
-
let flowHash;
|
|
178
|
-
let codeVersion;
|
|
179
|
-
const steps = {};
|
|
180
|
-
const selectedArms = {};
|
|
181
|
-
const bufferedSignals = {};
|
|
182
|
-
const anomalies = [];
|
|
183
|
-
for (const fact of facts) {
|
|
184
|
-
switch (fact.kind) {
|
|
185
|
-
case "flow.started":
|
|
186
|
-
flowId = fact.flowId;
|
|
187
|
-
input = fact.input;
|
|
188
|
-
phase = { tag: "running" };
|
|
189
|
-
parent = fact.parent;
|
|
190
|
-
flowHash = fact.flowHash;
|
|
191
|
-
codeVersion = fact.codeVersion;
|
|
192
|
-
break;
|
|
193
|
-
case "flow.completed":
|
|
194
|
-
phase = { tag: "completed", output: fact.output };
|
|
195
|
-
break;
|
|
196
|
-
case "flow.failed":
|
|
197
|
-
phase = { tag: "failed", error: fact.error };
|
|
198
|
-
break;
|
|
199
|
-
case "flow.canceled":
|
|
200
|
-
phase = { tag: "canceled", cause: runCancelCause(fact) };
|
|
201
|
-
break;
|
|
202
|
-
case "match.arm-selected":
|
|
203
|
-
selectedArms[fact.stepId] = fact.arm;
|
|
204
|
-
break;
|
|
205
|
-
case "step.reset":
|
|
206
|
-
steps[fact.stepId] = PENDING;
|
|
207
|
-
delete selectedArms[fact.stepId];
|
|
208
|
-
delete bufferedSignals[fact.stepId];
|
|
209
|
-
if (phase.tag === "completed" || phase.tag === "failed") {
|
|
210
|
-
phase = { tag: "running" };
|
|
211
|
-
}
|
|
212
|
-
break;
|
|
213
|
-
case "step.started":
|
|
214
|
-
case "step.completed":
|
|
215
|
-
case "step.failed":
|
|
216
|
-
case "step.canceled":
|
|
217
|
-
case "step.retried":
|
|
218
|
-
case "step.skipped":
|
|
219
|
-
case "step.abort-requested": {
|
|
220
|
-
const prev = steps[fact.stepId] ?? PENDING;
|
|
221
|
-
const t = stepTransition(prev, fact);
|
|
222
|
-
if (t.anomaly) {
|
|
223
|
-
anomalies.push({
|
|
224
|
-
at: fact.at,
|
|
225
|
-
stepId: fact.stepId,
|
|
226
|
-
from: prev.tag,
|
|
227
|
-
fact: fact.kind
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
|
-
steps[fact.stepId] = t.next;
|
|
231
|
-
break;
|
|
232
|
-
}
|
|
233
|
-
case "signal.buffered":
|
|
234
|
-
if (!(fact.stepId in bufferedSignals)) {
|
|
235
|
-
bufferedSignals[fact.stepId] = {
|
|
236
|
-
payload: fact.payload,
|
|
237
|
-
...compact({ signalName: fact.signalName })
|
|
238
|
-
};
|
|
239
|
-
}
|
|
240
|
-
break;
|
|
241
|
-
case "signal.received":
|
|
242
|
-
delete bufferedSignals[fact.stepId];
|
|
243
|
-
break;
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
return {
|
|
247
|
-
runId,
|
|
248
|
-
flowId,
|
|
249
|
-
input,
|
|
250
|
-
phase,
|
|
251
|
-
steps,
|
|
252
|
-
selectedArms,
|
|
253
|
-
bufferedSignals,
|
|
254
|
-
anomalies,
|
|
255
|
-
facts,
|
|
256
|
-
...compact({ parent, flowHash, codeVersion })
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// src/internal.ts
|
|
261
|
-
function isOptional(ref) {
|
|
262
|
-
return "__optional" in ref;
|
|
263
|
-
}
|
|
264
|
-
function normalizeNeeds(needs) {
|
|
265
|
-
const out = {};
|
|
266
|
-
if (needs === void 0) return out;
|
|
267
|
-
for (const [key, ref] of Object.entries(needs)) {
|
|
268
|
-
out[key] = isOptional(ref) ? { step: ref.__optional, optional: true } : { step: ref, optional: false };
|
|
269
|
-
}
|
|
270
|
-
return out;
|
|
271
|
-
}
|
|
272
|
-
function makeEmit(onLog) {
|
|
273
|
-
if (!onLog) return () => {
|
|
274
|
-
};
|
|
275
|
-
return (entry) => {
|
|
276
|
-
try {
|
|
277
|
-
onLog(entry);
|
|
278
|
-
} catch {
|
|
279
|
-
}
|
|
280
|
-
};
|
|
281
|
-
}
|
|
282
|
-
function compact(obj) {
|
|
283
|
-
const out = {};
|
|
284
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
285
|
-
if (value !== void 0) out[key] = value;
|
|
286
|
-
}
|
|
287
|
-
return out;
|
|
288
|
-
}
|
|
289
|
-
var DEF = /* @__PURE__ */ Symbol("nagi.def");
|
|
290
|
-
function attachDef(meta, def) {
|
|
291
|
-
return { kind: meta.kind, id: meta.id, [DEF]: def };
|
|
292
|
-
}
|
|
293
|
-
function setDef(step, def) {
|
|
294
|
-
step[DEF] = def;
|
|
295
|
-
}
|
|
296
|
-
function getDef(step) {
|
|
297
|
-
return step[DEF];
|
|
298
|
-
}
|
|
299
|
-
function peekDef(step) {
|
|
300
|
-
return step[DEF];
|
|
301
|
-
}
|
|
302
|
-
function handlerDef(def) {
|
|
303
|
-
return def.kind === "task" || def.kind === "activity" || def.kind === "streaming" ? def : void 0;
|
|
304
|
-
}
|
|
305
|
-
function needsStepIds(def) {
|
|
306
|
-
return Object.values(def.needs).map((ref) => ref.step.id);
|
|
307
|
-
}
|
|
308
|
-
function resolveNeeds(def, loadResolved) {
|
|
309
|
-
const result = {};
|
|
310
|
-
for (const [localKey, ref] of Object.entries(def.needs)) {
|
|
311
|
-
const resolved = loadResolved(ref.step.id);
|
|
312
|
-
result[localKey] = ref.optional ? resolved : unwrap(resolved);
|
|
313
|
-
}
|
|
314
|
-
return result;
|
|
315
|
-
}
|
|
316
|
-
function asStepMapWithDefs(steps) {
|
|
317
|
-
return steps;
|
|
318
|
-
}
|
|
319
|
-
function selectArm(def, args) {
|
|
320
|
-
for (const arm of def.arms) {
|
|
321
|
-
if (arm.guard.kind === "otherwise") return arm.id;
|
|
322
|
-
if (arm.guard.when(args)) return arm.id;
|
|
323
|
-
}
|
|
324
|
-
throw new Error(
|
|
325
|
-
`match: no arm matched and no { otherwise: true } fallback was provided`
|
|
326
|
-
);
|
|
327
|
-
}
|
|
1
|
+
import { InMemoryClock, makeEmit, asStepMapWithDefs, getDef, NagiRuntimeError, compact, makeSignals, DEFAULT_REAPER_INTERVAL_MS, Facts, validationError, NagiFlowSnapshotGoneError, isTerminalRun, runStatusOf, validate, foldRun, needsStepIds, attachDef, setDef, stepStateOf, serializeError, NagiCanceledError, NagiSignalTimeoutError, dequeueBackoff, defaultSnapshotGonePolicy, isStepTerminal, stepStatusOf, NagiSnapshotDriftError, attemptOf, DEFAULT_RETRY, outputOf, resolveNeeds, resolvedOf, handlerDef, resolveRetry, isAbortRequested, selectArm, stepBackoff, peekDef, NagiNonRetryableError, normalizeNeeds } from './chunk-VQTYTI6X.js';
|
|
2
|
+
export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryStore, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, QUERY_RUNS_DEFAULT_LIMIT, QUERY_RUNS_MAX_LIMIT, attemptOf, clampQueryLimit, compareRunOrder, decideExpiredLeaseAction, decideSignal, decideTimeout, decodeRunCursor, defaultSnapshotGonePolicy, encodeRunCursor, errorOf, factEffects, isPastCursor, isStepTerminal, isTerminalRun, jsonContains, outputOf, foldRun as projectRunState, resolvedOf, rowDeltaOf, runStatusOf, selectExpired, selectPruneBatch, stepStateOf, stepStatusOf, unwrap } from './chunk-VQTYTI6X.js';
|
|
328
3
|
|
|
329
4
|
// src/builder.ts
|
|
330
5
|
function makeBuilder() {
|
|
@@ -577,10 +252,6 @@ function assertSignalNameUniqueness(flowId, finalSteps) {
|
|
|
577
252
|
}
|
|
578
253
|
|
|
579
254
|
// src/canonicalize.ts
|
|
580
|
-
var DEFAULT_RETRY = {
|
|
581
|
-
initialDelayMs: 1e3,
|
|
582
|
-
maxDelayMs: 6e4
|
|
583
|
-
};
|
|
584
255
|
var warnedAboutSourceHash = false;
|
|
585
256
|
function warnSourceHashOnce() {
|
|
586
257
|
if (warnedAboutSourceHash) return;
|
|
@@ -820,1457 +491,131 @@ function cmp(a, b) {
|
|
|
820
491
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
821
492
|
}
|
|
822
493
|
|
|
823
|
-
// src/
|
|
824
|
-
var
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
494
|
+
// src/run-id.ts
|
|
495
|
+
var RunId = {
|
|
496
|
+
parse(s) {
|
|
497
|
+
if (typeof s !== "string" || s.length === 0) {
|
|
498
|
+
throw validationError("RunId.parse: must be a non-empty string", [
|
|
499
|
+
"runId"
|
|
500
|
+
]);
|
|
501
|
+
}
|
|
502
|
+
if (/\s/.test(s)) {
|
|
503
|
+
throw validationError("RunId.parse: must not contain whitespace", [
|
|
504
|
+
"runId"
|
|
505
|
+
]);
|
|
506
|
+
}
|
|
507
|
+
return s;
|
|
508
|
+
},
|
|
509
|
+
fromTrusted(s) {
|
|
510
|
+
return s;
|
|
830
511
|
}
|
|
831
512
|
};
|
|
832
|
-
function
|
|
833
|
-
|
|
513
|
+
async function deriveChildRunId(key) {
|
|
514
|
+
const seed = `nagi:subflow:${key.runId}:${key.stepId}:gen${key.generation}`;
|
|
515
|
+
const digest = await crypto.subtle.digest(
|
|
516
|
+
"SHA-256",
|
|
517
|
+
new TextEncoder().encode(seed)
|
|
518
|
+
);
|
|
519
|
+
const bytes = new Uint8Array(digest).subarray(0, 16);
|
|
520
|
+
bytes[6] = (bytes[6] ?? 0) & 15 | 80;
|
|
521
|
+
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
522
|
+
const hex2 = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
|
|
523
|
+
""
|
|
524
|
+
);
|
|
525
|
+
const uuid = `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20, 32)}`;
|
|
526
|
+
return `run-${uuid}`;
|
|
834
527
|
}
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
constructor({
|
|
852
|
-
runId,
|
|
853
|
-
canceledByRunId,
|
|
854
|
-
concurrencyKey
|
|
855
|
-
}) {
|
|
856
|
-
super(
|
|
857
|
-
`Run ${runId} was canceled (superseded by run ${canceledByRunId} for concurrency key "${concurrencyKey}").`
|
|
858
|
-
);
|
|
859
|
-
this.name = "NagiCanceledError";
|
|
860
|
-
this.runId = runId;
|
|
861
|
-
this.canceledByRunId = canceledByRunId;
|
|
862
|
-
this.concurrencyKey = concurrencyKey;
|
|
863
|
-
this.cause = {
|
|
864
|
-
canceledByRunId,
|
|
865
|
-
concurrencyKey
|
|
866
|
-
};
|
|
867
|
-
}
|
|
868
|
-
};
|
|
869
|
-
var NagiSignalTimeoutError = class extends Error {
|
|
870
|
-
runId;
|
|
871
|
-
stepId;
|
|
872
|
-
fireAt;
|
|
873
|
-
constructor({
|
|
874
|
-
runId,
|
|
875
|
-
stepId,
|
|
876
|
-
fireAt
|
|
877
|
-
}) {
|
|
878
|
-
super(
|
|
879
|
-
`Signal step "${stepId}" (run ${runId}) timed out \u2014 no signal arrived before its deadline ${fireAt.toISOString()}.`
|
|
880
|
-
);
|
|
881
|
-
this.name = "NagiSignalTimeoutError";
|
|
882
|
-
this.runId = runId;
|
|
883
|
-
this.stepId = stepId;
|
|
884
|
-
this.fireAt = fireAt;
|
|
528
|
+
|
|
529
|
+
// src/exec/hooks.ts
|
|
530
|
+
function makeHooks(deps) {
|
|
531
|
+
async function fireHook(hook, event, hookName) {
|
|
532
|
+
if (deps.fireHooks === false) return;
|
|
533
|
+
if (hook === void 0) return;
|
|
534
|
+
try {
|
|
535
|
+
await hook(event);
|
|
536
|
+
} catch (err) {
|
|
537
|
+
const { message, stack } = serializeError(err);
|
|
538
|
+
deps.emitLog({
|
|
539
|
+
level: "error",
|
|
540
|
+
msg: `nagi hook "${hookName}" threw \u2014 swallowed`,
|
|
541
|
+
attrs: { error: message, ...stack !== void 0 ? { stack } : {} }
|
|
542
|
+
});
|
|
543
|
+
}
|
|
885
544
|
}
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
flowId;
|
|
890
|
-
pinnedHash;
|
|
891
|
-
currentHash;
|
|
892
|
-
constructor({
|
|
893
|
-
runId,
|
|
894
|
-
flowId,
|
|
895
|
-
pinnedHash,
|
|
896
|
-
currentHash
|
|
897
|
-
}) {
|
|
898
|
-
super(
|
|
899
|
-
currentHash === null ? `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but flow "${flowId}" is not registered with the current nagi(). Pin a worker on the prior code version or migrate the run.` : `Run ${runId} is pinned to flow "${flowId}" hash ${pinnedHash.slice(0, 12)}\u2026, but the current registry has hash ${currentHash.slice(0, 12)}\u2026. Pin a worker on the prior code version or migrate the run.`
|
|
900
|
-
);
|
|
901
|
-
this.name = "NagiFlowSnapshotGoneError";
|
|
902
|
-
this.runId = runId;
|
|
903
|
-
this.flowId = flowId;
|
|
904
|
-
this.pinnedHash = pinnedHash;
|
|
905
|
-
this.currentHash = currentHash;
|
|
545
|
+
async function fireStepLifecycle(stepHook, flowHook, [stepName, flowName], event) {
|
|
546
|
+
await fireHook(stepHook, event, stepName);
|
|
547
|
+
await fireHook(flowHook, event, flowName);
|
|
906
548
|
}
|
|
907
|
-
};
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
);
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
549
|
+
return { fireHook, fireStepLifecycle };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// src/scheduler.ts
|
|
553
|
+
function nextRunnable({
|
|
554
|
+
flow: flow2,
|
|
555
|
+
runState,
|
|
556
|
+
input
|
|
557
|
+
}) {
|
|
558
|
+
const runnable = [];
|
|
559
|
+
const skip = [];
|
|
560
|
+
for (const [stepId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
561
|
+
if (stepStateOf(runState, stepId).tag !== "pending") continue;
|
|
562
|
+
const gate = gateStep(getDef(step), runState, input);
|
|
563
|
+
switch (gate.kind) {
|
|
564
|
+
case "run":
|
|
565
|
+
runnable.push(stepId);
|
|
566
|
+
break;
|
|
567
|
+
case "skip":
|
|
568
|
+
skip.push({ stepId, reason: gate.reason });
|
|
569
|
+
break;
|
|
570
|
+
}
|
|
924
571
|
}
|
|
925
|
-
};
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
572
|
+
return { runnable, skip };
|
|
573
|
+
}
|
|
574
|
+
function gateStep(def, runState, input) {
|
|
575
|
+
const parent = checkParentMatch(def, runState);
|
|
576
|
+
if (parent !== "ready") return gateFor(parent);
|
|
577
|
+
const upstream = checkUpstream(def, runState);
|
|
578
|
+
if (upstream !== "ready") return gateFor(upstream);
|
|
579
|
+
const when = def.kind === "match" ? void 0 : def.when;
|
|
580
|
+
if (when) {
|
|
581
|
+
const needs = resolveNeeds(
|
|
582
|
+
def,
|
|
583
|
+
(id) => resolvedOf(stepStateOf(runState, id))
|
|
937
584
|
);
|
|
938
|
-
|
|
939
|
-
this.runId = runId;
|
|
940
|
-
this.expected = expected;
|
|
941
|
-
this.actual = actual;
|
|
942
|
-
}
|
|
943
|
-
};
|
|
944
|
-
function serializeError(err) {
|
|
945
|
-
if (err instanceof Error) {
|
|
946
|
-
return {
|
|
947
|
-
name: err.name,
|
|
948
|
-
message: err.message,
|
|
949
|
-
...compact({ stack: err.stack })
|
|
950
|
-
};
|
|
585
|
+
if (!when({ input, needs })) return { kind: "skip", reason: "when-false" };
|
|
951
586
|
}
|
|
952
|
-
return {
|
|
587
|
+
return { kind: "run" };
|
|
953
588
|
}
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
589
|
+
function gateFor(status) {
|
|
590
|
+
switch (status) {
|
|
591
|
+
case "blocked":
|
|
592
|
+
return { kind: "block" };
|
|
593
|
+
case "transitive-skip":
|
|
594
|
+
return { kind: "skip", reason: "transitive" };
|
|
960
595
|
}
|
|
961
|
-
|
|
962
|
-
|
|
596
|
+
}
|
|
597
|
+
function checkUpstream(def, runState) {
|
|
598
|
+
for (const ref of Object.values(def.needs)) {
|
|
599
|
+
const upstreamState = stepStateOf(runState, ref.step.id);
|
|
600
|
+
if (upstreamState.tag === "completed") continue;
|
|
601
|
+
if (ref.optional && upstreamState.tag === "skipped") continue;
|
|
602
|
+
if (upstreamState.tag === "skipped" || upstreamState.tag === "failed") {
|
|
603
|
+
return "transitive-skip";
|
|
604
|
+
}
|
|
605
|
+
return "blocked";
|
|
963
606
|
}
|
|
964
|
-
|
|
965
|
-
|
|
607
|
+
return "ready";
|
|
608
|
+
}
|
|
609
|
+
function checkParentMatch(def, runState) {
|
|
610
|
+
if (!def.parentMatch) return "ready";
|
|
611
|
+
const { matchId, armId } = def.parentMatch;
|
|
612
|
+
const parentState = stepStateOf(runState, matchId);
|
|
613
|
+
if (parentState.tag === "failed" || parentState.tag === "skipped") {
|
|
614
|
+
return "transitive-skip";
|
|
966
615
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
backoffMs: 0
|
|
971
|
-
};
|
|
972
|
-
}
|
|
973
|
-
var DEFAULT_REAPER_INTERVAL_MS = 3e4;
|
|
974
|
-
|
|
975
|
-
// src/facts.ts
|
|
976
|
-
var Facts = {
|
|
977
|
-
flowStarted(a) {
|
|
978
|
-
return {
|
|
979
|
-
kind: "flow.started",
|
|
980
|
-
runId: a.runId,
|
|
981
|
-
flowId: a.flowId,
|
|
982
|
-
input: a.input,
|
|
983
|
-
at: a.at,
|
|
984
|
-
...compact({
|
|
985
|
-
codeVersion: a.codeVersion,
|
|
986
|
-
flowHash: a.flowHash,
|
|
987
|
-
parent: a.parent
|
|
988
|
-
})
|
|
989
|
-
};
|
|
990
|
-
},
|
|
991
|
-
flowCompleted(runId, output, at) {
|
|
992
|
-
return { kind: "flow.completed", runId, output, at };
|
|
993
|
-
},
|
|
994
|
-
flowFailed(runId, error, at) {
|
|
995
|
-
return { kind: "flow.failed", runId, error, at };
|
|
996
|
-
},
|
|
997
|
-
flowCanceled(runId, args, at) {
|
|
998
|
-
return { ...args, kind: "flow.canceled", runId, at };
|
|
999
|
-
},
|
|
1000
|
-
flowCanceledByConcurrency(a) {
|
|
1001
|
-
return {
|
|
1002
|
-
kind: "flow.canceled",
|
|
1003
|
-
cause: "concurrency",
|
|
1004
|
-
runId: a.runId,
|
|
1005
|
-
at: a.at,
|
|
1006
|
-
canceledByRunId: a.canceledByRunId,
|
|
1007
|
-
concurrencyKey: a.concurrencyKey
|
|
1008
|
-
};
|
|
1009
|
-
},
|
|
1010
|
-
stepStarted(runId, stepId, attempt, stepKind, at) {
|
|
1011
|
-
return { kind: "step.started", runId, stepId, attempt, stepKind, at };
|
|
1012
|
-
},
|
|
1013
|
-
stepCompleted(runId, stepId, attempt, output, at) {
|
|
1014
|
-
return { kind: "step.completed", runId, stepId, attempt, output, at };
|
|
1015
|
-
},
|
|
1016
|
-
stepFailed(runId, stepId, attempt, error, at) {
|
|
1017
|
-
return { kind: "step.failed", runId, stepId, attempt, error, at };
|
|
1018
|
-
},
|
|
1019
|
-
stepCanceled(runId, stepId, attempt, at, error) {
|
|
1020
|
-
return {
|
|
1021
|
-
kind: "step.canceled",
|
|
1022
|
-
runId,
|
|
1023
|
-
stepId,
|
|
1024
|
-
attempt,
|
|
1025
|
-
at,
|
|
1026
|
-
...compact({ error })
|
|
1027
|
-
};
|
|
1028
|
-
},
|
|
1029
|
-
stepRetried(runId, stepId, attempt, nextAttemptAt, error, at) {
|
|
1030
|
-
return {
|
|
1031
|
-
kind: "step.retried",
|
|
1032
|
-
runId,
|
|
1033
|
-
stepId,
|
|
1034
|
-
attempt,
|
|
1035
|
-
nextAttemptAt,
|
|
1036
|
-
error,
|
|
1037
|
-
at
|
|
1038
|
-
};
|
|
1039
|
-
},
|
|
1040
|
-
stepSkipped(a) {
|
|
1041
|
-
return {
|
|
1042
|
-
kind: "step.skipped",
|
|
1043
|
-
runId: a.runId,
|
|
1044
|
-
stepId: a.stepId,
|
|
1045
|
-
reason: a.reason,
|
|
1046
|
-
at: a.at,
|
|
1047
|
-
...compact({ actor: a.actor, note: a.note })
|
|
1048
|
-
};
|
|
1049
|
-
},
|
|
1050
|
-
stepReset(a) {
|
|
1051
|
-
return {
|
|
1052
|
-
kind: "step.reset",
|
|
1053
|
-
runId: a.runId,
|
|
1054
|
-
stepId: a.stepId,
|
|
1055
|
-
at: a.at,
|
|
1056
|
-
...compact({
|
|
1057
|
-
cascadedFrom: a.cascadedFrom,
|
|
1058
|
-
actor: a.actor,
|
|
1059
|
-
note: a.note
|
|
1060
|
-
})
|
|
1061
|
-
};
|
|
1062
|
-
},
|
|
1063
|
-
stepAbortRequested(a) {
|
|
1064
|
-
return {
|
|
1065
|
-
kind: "step.abort-requested",
|
|
1066
|
-
runId: a.runId,
|
|
1067
|
-
stepId: a.stepId,
|
|
1068
|
-
attempt: a.attempt,
|
|
1069
|
-
actor: a.actor,
|
|
1070
|
-
at: a.at,
|
|
1071
|
-
...compact({ note: a.note })
|
|
1072
|
-
};
|
|
1073
|
-
},
|
|
1074
|
-
matchArmSelected(runId, stepId, arm, at) {
|
|
1075
|
-
return { kind: "match.arm-selected", runId, stepId, arm, at };
|
|
1076
|
-
},
|
|
1077
|
-
signalReceived(a) {
|
|
1078
|
-
return {
|
|
1079
|
-
kind: "signal.received",
|
|
1080
|
-
runId: a.runId,
|
|
1081
|
-
stepId: a.stepId,
|
|
1082
|
-
payload: a.payload,
|
|
1083
|
-
at: a.at,
|
|
1084
|
-
...compact({ signalName: a.signalName })
|
|
1085
|
-
};
|
|
1086
|
-
},
|
|
1087
|
-
signalBuffered(a) {
|
|
1088
|
-
return {
|
|
1089
|
-
kind: "signal.buffered",
|
|
1090
|
-
runId: a.runId,
|
|
1091
|
-
stepId: a.stepId,
|
|
1092
|
-
payload: a.payload,
|
|
1093
|
-
at: a.at,
|
|
1094
|
-
...compact({ signalName: a.signalName })
|
|
1095
|
-
};
|
|
1096
|
-
},
|
|
1097
|
-
leaseReaped(a) {
|
|
1098
|
-
return {
|
|
1099
|
-
kind: "lease.reaped",
|
|
1100
|
-
runId: a.runId,
|
|
1101
|
-
stepId: a.stepId,
|
|
1102
|
-
attempt: a.attempt,
|
|
1103
|
-
at: a.at,
|
|
1104
|
-
reapedAt: a.reapedAt,
|
|
1105
|
-
reason: "expired"
|
|
1106
|
-
};
|
|
1107
|
-
},
|
|
1108
|
-
flowRefUpdated(a) {
|
|
1109
|
-
return {
|
|
1110
|
-
kind: "flow_ref.updated",
|
|
1111
|
-
flowId: a.flowId,
|
|
1112
|
-
from: a.from,
|
|
1113
|
-
to: a.to,
|
|
1114
|
-
at: a.at
|
|
1115
|
-
};
|
|
1116
|
-
}
|
|
1117
|
-
};
|
|
1118
|
-
|
|
1119
|
-
// src/validate.ts
|
|
1120
|
-
async function validate(schema, value) {
|
|
1121
|
-
const result = await schema["~standard"].validate(value);
|
|
1122
|
-
if ("issues" in result && result.issues !== void 0) {
|
|
1123
|
-
throw new NagiValidationError(result.issues);
|
|
1124
|
-
}
|
|
1125
|
-
return result.value;
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
// src/signals.ts
|
|
1129
|
-
var NOOP = { kind: "noop", result: { tag: "noop" } };
|
|
1130
|
-
function decideSignal(args) {
|
|
1131
|
-
const { runState, stepId, at, incoming } = args;
|
|
1132
|
-
const { runId } = runState;
|
|
1133
|
-
const step = stepStateOf(runState, stepId);
|
|
1134
|
-
if (isStepTerminal(step)) return NOOP;
|
|
1135
|
-
if (step.tag === "awaitingSignal") {
|
|
1136
|
-
const source = incoming ?? runState.bufferedSignals[stepId];
|
|
1137
|
-
if (source === void 0) return NOOP;
|
|
1138
|
-
const { attempt } = step;
|
|
1139
|
-
return {
|
|
1140
|
-
kind: "deliver",
|
|
1141
|
-
attempt,
|
|
1142
|
-
received: Facts.signalReceived({
|
|
1143
|
-
runId,
|
|
1144
|
-
stepId,
|
|
1145
|
-
payload: source.payload,
|
|
1146
|
-
at,
|
|
1147
|
-
...compact({ signalName: source.signalName })
|
|
1148
|
-
}),
|
|
1149
|
-
completed: Facts.stepCompleted(
|
|
1150
|
-
runId,
|
|
1151
|
-
stepId,
|
|
1152
|
-
attempt,
|
|
1153
|
-
source.payload,
|
|
1154
|
-
at
|
|
1155
|
-
),
|
|
1156
|
-
result: {
|
|
1157
|
-
tag: "delivered",
|
|
1158
|
-
attempt,
|
|
1159
|
-
payload: source.payload,
|
|
1160
|
-
...compact({ signalName: source.signalName })
|
|
1161
|
-
}
|
|
1162
|
-
};
|
|
1163
|
-
}
|
|
1164
|
-
if (incoming === void 0) return NOOP;
|
|
1165
|
-
if (runState.bufferedSignals[stepId] !== void 0) {
|
|
1166
|
-
return { kind: "buffer", fact: null, result: { tag: "buffered" } };
|
|
1167
|
-
}
|
|
1168
|
-
return {
|
|
1169
|
-
kind: "buffer",
|
|
1170
|
-
fact: Facts.signalBuffered({
|
|
1171
|
-
runId,
|
|
1172
|
-
stepId,
|
|
1173
|
-
payload: incoming.payload,
|
|
1174
|
-
at,
|
|
1175
|
-
...compact({ signalName: incoming.signalName })
|
|
1176
|
-
}),
|
|
1177
|
-
result: { tag: "buffered" }
|
|
1178
|
-
};
|
|
1179
|
-
}
|
|
1180
|
-
function decideTimeout(args) {
|
|
1181
|
-
const { runState, stepId, fireAt, at } = args;
|
|
1182
|
-
const step = stepStateOf(runState, stepId);
|
|
1183
|
-
if (step.tag !== "awaitingSignal") return { kind: "noop" };
|
|
1184
|
-
const error = serializeError(
|
|
1185
|
-
new NagiSignalTimeoutError({ runId: runState.runId, stepId, fireAt })
|
|
1186
|
-
);
|
|
1187
|
-
return {
|
|
1188
|
-
kind: "fail",
|
|
1189
|
-
attempt: step.attempt,
|
|
1190
|
-
fact: Facts.stepFailed(runState.runId, stepId, step.attempt, error, at)
|
|
1191
|
-
};
|
|
1192
|
-
}
|
|
1193
|
-
function makeSignals(deps) {
|
|
1194
|
-
const { dispatcher, store, clock, registry, hooks, flowHooks, emitLog } = deps;
|
|
1195
|
-
async function signal(runId, signalName, payload) {
|
|
1196
|
-
const runState = await store.loadRunState(runId);
|
|
1197
|
-
const flow2 = registry.requireForRun(runState.flowId, runId);
|
|
1198
|
-
const resolved = resolveSignalStep(flow2, signalName);
|
|
1199
|
-
if (resolved === null) {
|
|
1200
|
-
throw new NagiRuntimeError(
|
|
1201
|
-
`Flow "${flow2.id}" has no signal step accepting "${signalName}".`
|
|
1202
|
-
);
|
|
1203
|
-
}
|
|
1204
|
-
const { stepId, def } = resolved;
|
|
1205
|
-
const validated = await validate(def.schema, payload);
|
|
1206
|
-
const carriesAlias = signalName !== stepId;
|
|
1207
|
-
const result = await store.settleSignal({
|
|
1208
|
-
runId,
|
|
1209
|
-
stepId,
|
|
1210
|
-
at: clock.now(),
|
|
1211
|
-
incoming: {
|
|
1212
|
-
payload: validated,
|
|
1213
|
-
...carriesAlias ? { signalName } : {}
|
|
1214
|
-
}
|
|
1215
|
-
});
|
|
1216
|
-
switch (result.tag) {
|
|
1217
|
-
case "delivered":
|
|
1218
|
-
await hooks.fireHook(
|
|
1219
|
-
flowHooks?.onSignalReceived,
|
|
1220
|
-
{
|
|
1221
|
-
runId,
|
|
1222
|
-
flowId: flow2.id,
|
|
1223
|
-
stepId,
|
|
1224
|
-
attempt: result.attempt,
|
|
1225
|
-
kind: "signal",
|
|
1226
|
-
payload: validated,
|
|
1227
|
-
at: clock.now()
|
|
1228
|
-
},
|
|
1229
|
-
"onSignalReceived"
|
|
1230
|
-
);
|
|
1231
|
-
await dispatcher.advance(runId);
|
|
1232
|
-
return;
|
|
1233
|
-
case "buffered":
|
|
1234
|
-
emitLog({
|
|
1235
|
-
level: "info",
|
|
1236
|
-
msg: "nagi: signal buffered before step ready; will apply on dispatch",
|
|
1237
|
-
attrs: { runId, stepId, signalName }
|
|
1238
|
-
});
|
|
1239
|
-
return;
|
|
1240
|
-
case "noop":
|
|
1241
|
-
emitLog({
|
|
1242
|
-
level: "info",
|
|
1243
|
-
msg: "nagi: signal arrived after step resolved",
|
|
1244
|
-
attrs: { runId, stepId, signalName }
|
|
1245
|
-
});
|
|
1246
|
-
return;
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
return { signal };
|
|
1250
|
-
}
|
|
1251
|
-
function resolveSignalStep(flow2, signalName) {
|
|
1252
|
-
const steps = asStepMapWithDefs(flow2.steps);
|
|
1253
|
-
const direct = steps[signalName];
|
|
1254
|
-
if (direct !== void 0) {
|
|
1255
|
-
const d = getDef(direct);
|
|
1256
|
-
if (d.kind === "signal" && d.names === void 0) {
|
|
1257
|
-
return { stepId: signalName, def: d };
|
|
1258
|
-
}
|
|
1259
|
-
}
|
|
1260
|
-
for (const [id, s] of Object.entries(steps)) {
|
|
1261
|
-
const d = getDef(s);
|
|
1262
|
-
if (d.kind === "signal" && d.names?.includes(signalName)) {
|
|
1263
|
-
return { stepId: id, def: d };
|
|
1264
|
-
}
|
|
1265
|
-
}
|
|
1266
|
-
return null;
|
|
1267
|
-
}
|
|
1268
|
-
|
|
1269
|
-
// src/stream-hub.ts
|
|
1270
|
-
var STREAM_SUBSCRIBER_BUFFER_CAP = 256;
|
|
1271
|
-
var STREAM_REPLAY_BUFFER_CAP = 256;
|
|
1272
|
-
function makeWake() {
|
|
1273
|
-
let resolve;
|
|
1274
|
-
const promise = new Promise((r) => {
|
|
1275
|
-
resolve = r;
|
|
1276
|
-
});
|
|
1277
|
-
return { promise, resolve };
|
|
1278
|
-
}
|
|
1279
|
-
var Subscriber = class {
|
|
1280
|
-
buffer = [];
|
|
1281
|
-
pendingDropped = 0;
|
|
1282
|
-
closed = false;
|
|
1283
|
-
wake = null;
|
|
1284
|
-
push(event) {
|
|
1285
|
-
if (this.closed) return;
|
|
1286
|
-
if (this.buffer.length >= STREAM_SUBSCRIBER_BUFFER_CAP) {
|
|
1287
|
-
const idx = this.buffer.findIndex((e) => e.kind === "chunk");
|
|
1288
|
-
if (idx === -1) {
|
|
1289
|
-
if (event.kind === "chunk") {
|
|
1290
|
-
this.pendingDropped += 1;
|
|
1291
|
-
this.signal();
|
|
1292
|
-
return;
|
|
1293
|
-
}
|
|
1294
|
-
} else {
|
|
1295
|
-
this.buffer.splice(idx, 1);
|
|
1296
|
-
this.pendingDropped += 1;
|
|
1297
|
-
}
|
|
1298
|
-
}
|
|
1299
|
-
this.buffer.push(event);
|
|
1300
|
-
this.signal();
|
|
1301
|
-
}
|
|
1302
|
-
close() {
|
|
1303
|
-
if (this.closed) return;
|
|
1304
|
-
this.closed = true;
|
|
1305
|
-
this.signal();
|
|
1306
|
-
}
|
|
1307
|
-
signal() {
|
|
1308
|
-
if (this.wake !== null) {
|
|
1309
|
-
const w = this.wake;
|
|
1310
|
-
this.wake = null;
|
|
1311
|
-
w.resolve();
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
|
-
async next() {
|
|
1315
|
-
for (; ; ) {
|
|
1316
|
-
if (this.pendingDropped > 0) {
|
|
1317
|
-
const count = this.pendingDropped;
|
|
1318
|
-
this.pendingDropped = 0;
|
|
1319
|
-
return { kind: "dropped", count };
|
|
1320
|
-
}
|
|
1321
|
-
const head = this.buffer.shift();
|
|
1322
|
-
if (head !== void 0) return head;
|
|
1323
|
-
if (this.closed) return null;
|
|
1324
|
-
const w = makeWake();
|
|
1325
|
-
this.wake = w;
|
|
1326
|
-
await w.promise;
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
};
|
|
1330
|
-
var InMemoryStreamHub = class _InMemoryStreamHub {
|
|
1331
|
-
channels = /* @__PURE__ */ new Map();
|
|
1332
|
-
static key(runId, stepId) {
|
|
1333
|
-
return `${runId}::${stepId}`;
|
|
1334
|
-
}
|
|
1335
|
-
getOrCreate(runId, stepId) {
|
|
1336
|
-
const key = _InMemoryStreamHub.key(runId, stepId);
|
|
1337
|
-
let channel = this.channels.get(key);
|
|
1338
|
-
if (channel === void 0) {
|
|
1339
|
-
channel = { subscribers: /* @__PURE__ */ new Set(), replay: [], closed: false };
|
|
1340
|
-
this.channels.set(key, channel);
|
|
1341
|
-
}
|
|
1342
|
-
return channel;
|
|
1343
|
-
}
|
|
1344
|
-
publishChunk(runId, stepId, chunk) {
|
|
1345
|
-
const channel = this.getOrCreate(runId, stepId);
|
|
1346
|
-
if (channel.closed) return;
|
|
1347
|
-
const event = { kind: "chunk", chunk };
|
|
1348
|
-
channel.replay.push(event);
|
|
1349
|
-
if (channel.replay.length > STREAM_REPLAY_BUFFER_CAP)
|
|
1350
|
-
channel.replay.shift();
|
|
1351
|
-
for (const sub of channel.subscribers) sub.push(event);
|
|
1352
|
-
}
|
|
1353
|
-
signalRetry(runId, stepId, attempt) {
|
|
1354
|
-
const channel = this.getOrCreate(runId, stepId);
|
|
1355
|
-
if (channel.closed) return;
|
|
1356
|
-
channel.replay.length = 0;
|
|
1357
|
-
const event = { kind: "retry", attempt };
|
|
1358
|
-
for (const sub of channel.subscribers) sub.push(event);
|
|
1359
|
-
}
|
|
1360
|
-
// NB: no-op when no channel exists. InMemoryStore.appendFact fires this for
|
|
1361
|
-
// EVERY step.completed — including non-streaming steps that never published —
|
|
1362
|
-
// so creating a channel here would leak one per such step. Closed-ness is
|
|
1363
|
-
// authoritative in the durable facts, not the hub.
|
|
1364
|
-
closeOk(runId, stepId) {
|
|
1365
|
-
const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
|
|
1366
|
-
if (channel === void 0 || channel.closed) return;
|
|
1367
|
-
channel.closed = true;
|
|
1368
|
-
channel.replay.length = 0;
|
|
1369
|
-
for (const sub of channel.subscribers) sub.close();
|
|
1370
|
-
channel.subscribers.clear();
|
|
1371
|
-
}
|
|
1372
|
-
closeError(runId, stepId, error) {
|
|
1373
|
-
const channel = this.channels.get(_InMemoryStreamHub.key(runId, stepId));
|
|
1374
|
-
if (channel === void 0 || channel.closed) return;
|
|
1375
|
-
channel.closed = true;
|
|
1376
|
-
channel.replay.length = 0;
|
|
1377
|
-
const event = { kind: "error", error };
|
|
1378
|
-
for (const sub of channel.subscribers) {
|
|
1379
|
-
sub.push(event);
|
|
1380
|
-
sub.close();
|
|
1381
|
-
}
|
|
1382
|
-
channel.subscribers.clear();
|
|
1383
|
-
}
|
|
1384
|
-
closeRun(runId) {
|
|
1385
|
-
const prefix = `${runId}::`;
|
|
1386
|
-
for (const [key, channel] of this.channels) {
|
|
1387
|
-
if (!key.startsWith(prefix) || channel.closed) continue;
|
|
1388
|
-
channel.closed = true;
|
|
1389
|
-
channel.replay.length = 0;
|
|
1390
|
-
for (const sub of channel.subscribers) sub.close();
|
|
1391
|
-
channel.subscribers.clear();
|
|
1392
|
-
}
|
|
1393
|
-
}
|
|
1394
|
-
subscribeStream(runId, stepId, opts) {
|
|
1395
|
-
const channel = this.getOrCreate(runId, stepId);
|
|
1396
|
-
if (channel.closed) {
|
|
1397
|
-
return {
|
|
1398
|
-
[Symbol.asyncIterator]() {
|
|
1399
|
-
return {
|
|
1400
|
-
next: async () => ({ value: void 0, done: true })
|
|
1401
|
-
};
|
|
1402
|
-
}
|
|
1403
|
-
};
|
|
1404
|
-
}
|
|
1405
|
-
const sub = new Subscriber();
|
|
1406
|
-
if (opts?.replayBuffered === true) {
|
|
1407
|
-
for (const event of channel.replay) sub.push(event);
|
|
1408
|
-
}
|
|
1409
|
-
channel.subscribers.add(sub);
|
|
1410
|
-
const remove = () => {
|
|
1411
|
-
channel.subscribers.delete(sub);
|
|
1412
|
-
};
|
|
1413
|
-
return {
|
|
1414
|
-
[Symbol.asyncIterator]() {
|
|
1415
|
-
return {
|
|
1416
|
-
next: async () => {
|
|
1417
|
-
const event = await sub.next();
|
|
1418
|
-
if (event === null) {
|
|
1419
|
-
remove();
|
|
1420
|
-
return { value: void 0, done: true };
|
|
1421
|
-
}
|
|
1422
|
-
return { value: event, done: false };
|
|
1423
|
-
},
|
|
1424
|
-
return: async () => {
|
|
1425
|
-
sub.close();
|
|
1426
|
-
remove();
|
|
1427
|
-
return { value: void 0, done: true };
|
|
1428
|
-
}
|
|
1429
|
-
};
|
|
1430
|
-
}
|
|
1431
|
-
};
|
|
1432
|
-
}
|
|
1433
|
-
};
|
|
1434
|
-
|
|
1435
|
-
// src/memory.ts
|
|
1436
|
-
var DEFAULT_STORE_LEASE_MS = 6e4;
|
|
1437
|
-
var InMemoryStore = class {
|
|
1438
|
-
facts = /* @__PURE__ */ new Map();
|
|
1439
|
-
onces = /* @__PURE__ */ new Map();
|
|
1440
|
-
leases = /* @__PURE__ */ new Map();
|
|
1441
|
-
snapshots = /* @__PURE__ */ new Map();
|
|
1442
|
-
refs = /* @__PURE__ */ new Map();
|
|
1443
|
-
globalFacts = [];
|
|
1444
|
-
activeByKey = /* @__PURE__ */ new Map();
|
|
1445
|
-
keyByActiveRun = /* @__PURE__ */ new Map();
|
|
1446
|
-
// Kept past terminal facts so a reopened run can re-take its slot.
|
|
1447
|
-
slotByRun = /* @__PURE__ */ new Map();
|
|
1448
|
-
childrenByParent = /* @__PURE__ */ new Map();
|
|
1449
|
-
summaries = /* @__PURE__ */ new Map();
|
|
1450
|
-
streamHub = new InMemoryStreamHub();
|
|
1451
|
-
// Durable signal-timeout deadlines, keyed `${runId}::${stepId}` → fire_at.
|
|
1452
|
-
// The Postgres analogue is the nagi.timer table; this is its in-memory twin
|
|
1453
|
-
// (distinct from the InMemoryClock's setTimeout-based scheduler timers).
|
|
1454
|
-
signalTimers = /* @__PURE__ */ new Map();
|
|
1455
|
-
leaseMs;
|
|
1456
|
-
constructor(opts = {}) {
|
|
1457
|
-
this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
|
|
1458
|
-
}
|
|
1459
|
-
async appendFact(runId, fact) {
|
|
1460
|
-
const list = this.facts.get(runId) ?? [];
|
|
1461
|
-
if (fact.kind === "step.reset") {
|
|
1462
|
-
const prior = foldRun(runId, list);
|
|
1463
|
-
if (prior.phase.tag === "completed" || prior.phase.tag === "failed") {
|
|
1464
|
-
const slot = this.slotByRun.get(runId);
|
|
1465
|
-
if (slot !== void 0) {
|
|
1466
|
-
const holder = this.activeByKey.get(slot);
|
|
1467
|
-
if (holder !== void 0 && holder !== runId) {
|
|
1468
|
-
throw new NagiConcurrencyConflictError({
|
|
1469
|
-
runId,
|
|
1470
|
-
flowId: prior.flowId,
|
|
1471
|
-
concurrencyKey: slot.slice(slot.indexOf("::") + 2)
|
|
1472
|
-
});
|
|
1473
|
-
}
|
|
1474
|
-
this.activeByKey.set(slot, runId);
|
|
1475
|
-
this.keyByActiveRun.set(runId, slot);
|
|
1476
|
-
}
|
|
1477
|
-
}
|
|
1478
|
-
}
|
|
1479
|
-
list.push(fact);
|
|
1480
|
-
this.facts.set(runId, list);
|
|
1481
|
-
switch (fact.kind) {
|
|
1482
|
-
case "step.completed":
|
|
1483
|
-
this.streamHub.closeOk(runId, fact.stepId);
|
|
1484
|
-
break;
|
|
1485
|
-
case "step.failed":
|
|
1486
|
-
this.streamHub.closeError(runId, fact.stepId, fact.error);
|
|
1487
|
-
break;
|
|
1488
|
-
case "step.retried":
|
|
1489
|
-
this.streamHub.signalRetry(
|
|
1490
|
-
runId,
|
|
1491
|
-
fact.stepId,
|
|
1492
|
-
fact.attempt + 1
|
|
1493
|
-
);
|
|
1494
|
-
break;
|
|
1495
|
-
case "flow.completed":
|
|
1496
|
-
case "flow.failed":
|
|
1497
|
-
case "flow.canceled":
|
|
1498
|
-
this.streamHub.closeRun(runId);
|
|
1499
|
-
break;
|
|
1500
|
-
}
|
|
1501
|
-
if (fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled") {
|
|
1502
|
-
const slot = this.keyByActiveRun.get(runId);
|
|
1503
|
-
if (slot !== void 0) {
|
|
1504
|
-
this.keyByActiveRun.delete(runId);
|
|
1505
|
-
if (this.activeByKey.get(slot) === runId) {
|
|
1506
|
-
this.activeByKey.delete(slot);
|
|
1507
|
-
}
|
|
1508
|
-
}
|
|
1509
|
-
}
|
|
1510
|
-
if (fact.kind === "step.reset") {
|
|
1511
|
-
const leasePrefix = `${runId}::${fact.stepId}::`;
|
|
1512
|
-
for (const key of this.leases.keys()) {
|
|
1513
|
-
if (key.startsWith(leasePrefix)) this.leases.delete(key);
|
|
1514
|
-
}
|
|
1515
|
-
this.signalTimers.delete(`${runId}::${fact.stepId}`);
|
|
1516
|
-
}
|
|
1517
|
-
}
|
|
1518
|
-
async tryStartRun(runId, fact, concurrency) {
|
|
1519
|
-
if (this.facts.has(runId) || this.summaries.has(runId)) {
|
|
1520
|
-
return { started: false, canceled: [] };
|
|
1521
|
-
}
|
|
1522
|
-
const canceled = [];
|
|
1523
|
-
if (concurrency !== void 0) {
|
|
1524
|
-
const slot = `${fact.flowId}::${concurrency.key}`;
|
|
1525
|
-
const priorRunId = this.activeByKey.get(slot);
|
|
1526
|
-
if (priorRunId !== void 0) {
|
|
1527
|
-
const cancelFact = Facts.flowCanceledByConcurrency({
|
|
1528
|
-
runId: priorRunId,
|
|
1529
|
-
at: fact.at,
|
|
1530
|
-
canceledByRunId: runId,
|
|
1531
|
-
concurrencyKey: concurrency.key
|
|
1532
|
-
});
|
|
1533
|
-
await this.appendFact(priorRunId, cancelFact);
|
|
1534
|
-
canceled.push({ runId: priorRunId, fact: cancelFact });
|
|
1535
|
-
}
|
|
1536
|
-
this.activeByKey.set(slot, runId);
|
|
1537
|
-
this.keyByActiveRun.set(runId, slot);
|
|
1538
|
-
this.slotByRun.set(runId, slot);
|
|
1539
|
-
}
|
|
1540
|
-
this.facts.set(runId, [fact]);
|
|
1541
|
-
const parentRunId = fact.parent?.runId;
|
|
1542
|
-
if (parentRunId !== void 0) {
|
|
1543
|
-
const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
|
|
1544
|
-
set.add(runId);
|
|
1545
|
-
this.childrenByParent.set(parentRunId, set);
|
|
1546
|
-
}
|
|
1547
|
-
return { started: true, canceled };
|
|
1548
|
-
}
|
|
1549
|
-
// In-memory has no real tx; we share the underlying maps with tryStartRun,
|
|
1550
|
-
// so the implementation is intentionally a straight delegate. The `tx`
|
|
1551
|
-
// parameter is accepted for shape-compat with the Store contract.
|
|
1552
|
-
async tryStartRunOnTx(_tx, runId, fact, concurrency) {
|
|
1553
|
-
return this.tryStartRun(runId, fact, concurrency);
|
|
1554
|
-
}
|
|
1555
|
-
async listChildren(parentRunId) {
|
|
1556
|
-
const set = this.childrenByParent.get(parentRunId);
|
|
1557
|
-
if (set === void 0) return [];
|
|
1558
|
-
return Array.from(set);
|
|
1559
|
-
}
|
|
1560
|
-
// Does a non-terminal child exist for this (parentRunId, stepId)? Used by the
|
|
1561
|
-
// reaper to leave a subflow step parked while its child still runs (instead
|
|
1562
|
-
// of re-dispatching it at attempt+1). childrenByParent is keyed by parent run
|
|
1563
|
-
// only, so filter on the child's parent.stepId.
|
|
1564
|
-
hasActiveChild(parentRunId, parentStepId) {
|
|
1565
|
-
const childIds = this.childrenByParent.get(parentRunId);
|
|
1566
|
-
if (childIds === void 0) return false;
|
|
1567
|
-
for (const childId of childIds) {
|
|
1568
|
-
const factList = this.facts.get(childId);
|
|
1569
|
-
if (factList === void 0) continue;
|
|
1570
|
-
const child = foldRun(childId, factList);
|
|
1571
|
-
if (child.parent?.stepId === parentStepId && !isTerminalRun(child)) {
|
|
1572
|
-
return true;
|
|
1573
|
-
}
|
|
1574
|
-
}
|
|
1575
|
-
return false;
|
|
1576
|
-
}
|
|
1577
|
-
async loadRunState(runId) {
|
|
1578
|
-
return foldRun(runId, this.facts.get(runId) ?? []);
|
|
1579
|
-
}
|
|
1580
|
-
async claimStep(runId, stepId, attempt) {
|
|
1581
|
-
const key = `${runId}::${stepId}::${attempt}`;
|
|
1582
|
-
const now = Date.now();
|
|
1583
|
-
const existing = this.leases.get(key);
|
|
1584
|
-
if (existing && existing.expiresAt > now) {
|
|
1585
|
-
return null;
|
|
1586
|
-
}
|
|
1587
|
-
const token = `lease-${crypto.randomUUID()}`;
|
|
1588
|
-
this.leases.set(key, { token, expiresAt: now + this.leaseMs });
|
|
1589
|
-
return token;
|
|
1590
|
-
}
|
|
1591
|
-
async extendLease(runId, stepId, attempt, leaseMs) {
|
|
1592
|
-
const key = `${runId}::${stepId}::${attempt}`;
|
|
1593
|
-
const existing = this.leases.get(key);
|
|
1594
|
-
if (existing === void 0) return;
|
|
1595
|
-
this.leases.set(key, {
|
|
1596
|
-
token: existing.token,
|
|
1597
|
-
expiresAt: Date.now() + leaseMs
|
|
1598
|
-
});
|
|
1599
|
-
}
|
|
1600
|
-
async sweepLeases(args) {
|
|
1601
|
-
const { now, queue, limit = 100 } = args;
|
|
1602
|
-
const reaped = [];
|
|
1603
|
-
const candidates = [];
|
|
1604
|
-
for (const [key, lease] of this.leases) {
|
|
1605
|
-
if (candidates.length >= limit) break;
|
|
1606
|
-
const parts = key.split("::");
|
|
1607
|
-
if (parts.length !== 3) continue;
|
|
1608
|
-
const [runId, stepId, attemptStr] = parts;
|
|
1609
|
-
candidates.push({
|
|
1610
|
-
key,
|
|
1611
|
-
runId,
|
|
1612
|
-
stepId,
|
|
1613
|
-
attempt: Number(attemptStr),
|
|
1614
|
-
expiresAt: new Date(lease.expiresAt)
|
|
1615
|
-
});
|
|
1616
|
-
}
|
|
1617
|
-
for (const c of candidates) {
|
|
1618
|
-
const factList = this.facts.get(c.runId);
|
|
1619
|
-
const state = factList ? foldRun(c.runId, factList) : null;
|
|
1620
|
-
const ss = state ? stepStateOf(state, c.stepId) : null;
|
|
1621
|
-
const stepStatus = ss === null ? "pending" : stepStatusOf(ss);
|
|
1622
|
-
const decision = decideExpiredLeaseAction({
|
|
1623
|
-
lease: {
|
|
1624
|
-
runId: c.runId,
|
|
1625
|
-
stepId: c.stepId,
|
|
1626
|
-
attempt: c.attempt,
|
|
1627
|
-
expiresAt: c.expiresAt
|
|
1628
|
-
},
|
|
1629
|
-
stepStatus,
|
|
1630
|
-
childActive: this.hasActiveChild(c.runId, c.stepId),
|
|
1631
|
-
now
|
|
1632
|
-
});
|
|
1633
|
-
if (decision.tag === "skip") continue;
|
|
1634
|
-
this.leases.delete(c.key);
|
|
1635
|
-
await this.appendFact(
|
|
1636
|
-
c.runId,
|
|
1637
|
-
Facts.leaseReaped({
|
|
1638
|
-
runId: c.runId,
|
|
1639
|
-
stepId: c.stepId,
|
|
1640
|
-
attempt: c.attempt,
|
|
1641
|
-
at: now,
|
|
1642
|
-
reapedAt: now
|
|
1643
|
-
})
|
|
1644
|
-
);
|
|
1645
|
-
await queue.enqueue(c.runId, c.stepId, {
|
|
1646
|
-
attempt: decision.nextAttempt,
|
|
1647
|
-
delayMs: decision.backoffMs,
|
|
1648
|
-
...state?.flowId !== void 0 ? { flowId: state.flowId } : {}
|
|
1649
|
-
});
|
|
1650
|
-
reaped.push({
|
|
1651
|
-
runId: c.runId,
|
|
1652
|
-
stepId: c.stepId,
|
|
1653
|
-
attempt: c.attempt,
|
|
1654
|
-
nextAttempt: decision.nextAttempt
|
|
1655
|
-
});
|
|
1656
|
-
}
|
|
1657
|
-
return reaped;
|
|
1658
|
-
}
|
|
1659
|
-
async settleStep(runId, _stepId, fact) {
|
|
1660
|
-
await this.appendFact(runId, fact);
|
|
1661
|
-
}
|
|
1662
|
-
async settleSignal(args) {
|
|
1663
|
-
const { runId, stepId, at, incoming } = args;
|
|
1664
|
-
const runState = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1665
|
-
const decision = decideSignal({ runState, stepId, at, incoming });
|
|
1666
|
-
switch (decision.kind) {
|
|
1667
|
-
case "noop":
|
|
1668
|
-
return decision.result;
|
|
1669
|
-
case "buffer":
|
|
1670
|
-
if (decision.fact !== null) await this.appendFact(runId, decision.fact);
|
|
1671
|
-
return decision.result;
|
|
1672
|
-
case "deliver":
|
|
1673
|
-
await this.appendFact(runId, decision.received);
|
|
1674
|
-
await this.appendFact(runId, decision.completed);
|
|
1675
|
-
this.signalTimers.delete(`${runId}::${stepId}`);
|
|
1676
|
-
return decision.result;
|
|
1677
|
-
}
|
|
1678
|
-
}
|
|
1679
|
-
async upsertTimer(runId, stepId, fireAt) {
|
|
1680
|
-
const key = `${runId}::${stepId}`;
|
|
1681
|
-
if (!this.signalTimers.has(key)) this.signalTimers.set(key, fireAt);
|
|
1682
|
-
}
|
|
1683
|
-
async sweepSignalTimeouts(args) {
|
|
1684
|
-
const { now, limit = 100 } = args;
|
|
1685
|
-
const timedOut = [];
|
|
1686
|
-
const due = [];
|
|
1687
|
-
for (const [key, fireAt] of this.signalTimers) {
|
|
1688
|
-
if (due.length >= limit) break;
|
|
1689
|
-
if (fireAt > now) continue;
|
|
1690
|
-
const sep = key.indexOf("::");
|
|
1691
|
-
due.push({
|
|
1692
|
-
key,
|
|
1693
|
-
runId: key.slice(0, sep),
|
|
1694
|
-
stepId: key.slice(sep + 2)
|
|
1695
|
-
});
|
|
1696
|
-
}
|
|
1697
|
-
for (const { key, runId, stepId } of due) {
|
|
1698
|
-
const fireAt = this.signalTimers.get(key);
|
|
1699
|
-
if (fireAt === void 0) continue;
|
|
1700
|
-
const runState = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1701
|
-
const decision = decideTimeout({ runState, stepId, fireAt, at: now });
|
|
1702
|
-
this.signalTimers.delete(key);
|
|
1703
|
-
if (decision.kind === "noop") continue;
|
|
1704
|
-
await this.appendFact(runId, decision.fact);
|
|
1705
|
-
const leasePrefix = `${runId}::${stepId}::`;
|
|
1706
|
-
for (const k of this.leases.keys()) {
|
|
1707
|
-
if (k.startsWith(leasePrefix)) this.leases.delete(k);
|
|
1708
|
-
}
|
|
1709
|
-
timedOut.push({ runId, stepId, attempt: decision.attempt, fireAt });
|
|
1710
|
-
}
|
|
1711
|
-
return timedOut;
|
|
1712
|
-
}
|
|
1713
|
-
async recordOnce(runId, stepId, scope, value) {
|
|
1714
|
-
this.onces.set(`${runId}::${stepId}::${scope}`, value);
|
|
1715
|
-
}
|
|
1716
|
-
async getOnce(runId, stepId, scope) {
|
|
1717
|
-
return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
|
|
1718
|
-
}
|
|
1719
|
-
async runStep(runId, _stepId, _attempt, body) {
|
|
1720
|
-
const result = await body(void 0);
|
|
1721
|
-
await this.appendFact(runId, result.fact);
|
|
1722
|
-
return result.output;
|
|
1723
|
-
}
|
|
1724
|
-
async upsertSnapshot(args) {
|
|
1725
|
-
if (this.snapshots.has(args.flowHash)) return;
|
|
1726
|
-
this.snapshots.set(args.flowHash, { flowId: args.flowId, dag: args.dag });
|
|
1727
|
-
}
|
|
1728
|
-
async getRef(flowId) {
|
|
1729
|
-
return this.refs.get(flowId) ?? null;
|
|
1730
|
-
}
|
|
1731
|
-
async setRef(flowId, flowHash) {
|
|
1732
|
-
this.refs.set(flowId, flowHash);
|
|
1733
|
-
}
|
|
1734
|
-
async loadSnapshot(flowHash) {
|
|
1735
|
-
return this.snapshots.get(flowHash) ?? null;
|
|
1736
|
-
}
|
|
1737
|
-
async appendGlobalFact(fact) {
|
|
1738
|
-
this.globalFacts.push(fact);
|
|
1739
|
-
}
|
|
1740
|
-
readGlobalFacts() {
|
|
1741
|
-
return this.globalFacts;
|
|
1742
|
-
}
|
|
1743
|
-
async queryRuns(opts) {
|
|
1744
|
-
const where = opts.where ?? {};
|
|
1745
|
-
const wanted = where.status && new Set(where.status);
|
|
1746
|
-
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));
|
|
1747
|
-
const summaries = [];
|
|
1748
|
-
for (const [runId, factList] of this.facts) {
|
|
1749
|
-
const summary = summarize(runId, factList);
|
|
1750
|
-
if (summary === null) continue;
|
|
1751
|
-
if (matches(summary)) summaries.push(summary);
|
|
1752
|
-
}
|
|
1753
|
-
for (const summary of this.summaries.values()) {
|
|
1754
|
-
if (matches(summary)) summaries.push(summary);
|
|
1755
|
-
}
|
|
1756
|
-
summaries.sort((a, b) => {
|
|
1757
|
-
const t = b.startedAt.getTime() - a.startedAt.getTime();
|
|
1758
|
-
if (t !== 0) return t;
|
|
1759
|
-
return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
|
|
1760
|
-
});
|
|
1761
|
-
if (opts.latest === true) {
|
|
1762
|
-
return { runs: summaries.slice(0, 1), cursor: null };
|
|
1763
|
-
}
|
|
1764
|
-
const limit = clampLimit(opts.limit);
|
|
1765
|
-
let start = 0;
|
|
1766
|
-
if (opts.cursor !== void 0) {
|
|
1767
|
-
const c = decodeCursor(opts.cursor);
|
|
1768
|
-
start = summaries.findIndex(
|
|
1769
|
-
(s) => s.startedAt.getTime() < c.t || s.startedAt.getTime() === c.t && s.runId < c.r
|
|
1770
|
-
);
|
|
1771
|
-
if (start === -1) start = summaries.length;
|
|
1772
|
-
}
|
|
1773
|
-
const page = summaries.slice(start, start + limit);
|
|
1774
|
-
const hasMore = start + limit < summaries.length;
|
|
1775
|
-
const last = page[page.length - 1];
|
|
1776
|
-
const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
|
|
1777
|
-
return { runs: page, cursor };
|
|
1778
|
-
}
|
|
1779
|
-
async describe(runId) {
|
|
1780
|
-
const factList = this.facts.get(runId);
|
|
1781
|
-
if (factList === void 0 || factList.length === 0) return null;
|
|
1782
|
-
const first = factList[0];
|
|
1783
|
-
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
1784
|
-
const state = foldRun(runId, factList);
|
|
1785
|
-
const status = runStatusOf(state);
|
|
1786
|
-
let completedAt;
|
|
1787
|
-
let output;
|
|
1788
|
-
let error;
|
|
1789
|
-
let canceledByRunId;
|
|
1790
|
-
let concurrencyKey;
|
|
1791
|
-
for (let i = isTerminalRun(state) ? factList.length - 1 : -1; i >= 0; i--) {
|
|
1792
|
-
const f = factList[i];
|
|
1793
|
-
if (f === void 0) continue;
|
|
1794
|
-
if (f.kind === "flow.completed") {
|
|
1795
|
-
completedAt = f.at;
|
|
1796
|
-
output = f.output;
|
|
1797
|
-
break;
|
|
1798
|
-
}
|
|
1799
|
-
if (f.kind === "flow.failed") {
|
|
1800
|
-
completedAt = f.at;
|
|
1801
|
-
error = f.error;
|
|
1802
|
-
break;
|
|
1803
|
-
}
|
|
1804
|
-
if (f.kind === "flow.canceled") {
|
|
1805
|
-
completedAt = f.at;
|
|
1806
|
-
if (f.cause === "concurrency") {
|
|
1807
|
-
canceledByRunId = f.canceledByRunId;
|
|
1808
|
-
}
|
|
1809
|
-
break;
|
|
1810
|
-
}
|
|
1811
|
-
}
|
|
1812
|
-
const slot = this.keyByActiveRun.get(runId);
|
|
1813
|
-
if (slot !== void 0) {
|
|
1814
|
-
const sep = slot.indexOf("::");
|
|
1815
|
-
if (sep >= 0) concurrencyKey = slot.slice(sep + 2);
|
|
1816
|
-
}
|
|
1817
|
-
if (concurrencyKey === void 0) {
|
|
1818
|
-
for (const f of factList) {
|
|
1819
|
-
if (f.kind === "flow.canceled" && f.cause === "concurrency") {
|
|
1820
|
-
concurrencyKey = f.concurrencyKey;
|
|
1821
|
-
break;
|
|
1822
|
-
}
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
const childSet = this.childrenByParent.get(runId);
|
|
1826
|
-
const children = childSet ? Array.from(childSet) : [];
|
|
1827
|
-
const parent = first.parent;
|
|
1828
|
-
const run = {
|
|
1829
|
-
runId,
|
|
1830
|
-
flowId: first.flowId,
|
|
1831
|
-
flowHash: first.flowHash ?? "",
|
|
1832
|
-
status,
|
|
1833
|
-
startedAt: first.at,
|
|
1834
|
-
input: first.input,
|
|
1835
|
-
children,
|
|
1836
|
-
...completedAt !== void 0 ? { completedAt } : {},
|
|
1837
|
-
...output !== void 0 ? { output } : {},
|
|
1838
|
-
...error !== void 0 ? { error } : {},
|
|
1839
|
-
...canceledByRunId !== void 0 ? { canceledByRunId } : {},
|
|
1840
|
-
...concurrencyKey !== void 0 ? { concurrencyKey } : {},
|
|
1841
|
-
...parent !== void 0 ? { parent } : {}
|
|
1842
|
-
};
|
|
1843
|
-
const steps = [];
|
|
1844
|
-
const startedAtByStep = /* @__PURE__ */ new Map();
|
|
1845
|
-
const completedAtByStep = /* @__PURE__ */ new Map();
|
|
1846
|
-
for (const f of factList) {
|
|
1847
|
-
if (f.kind === "step.started" && !startedAtByStep.has(f.stepId)) {
|
|
1848
|
-
startedAtByStep.set(f.stepId, f.at);
|
|
1849
|
-
}
|
|
1850
|
-
if ((f.kind === "step.completed" || f.kind === "step.failed" || f.kind === "step.canceled" || f.kind === "step.skipped") && !completedAtByStep.has(f.stepId)) {
|
|
1851
|
-
completedAtByStep.set(f.stepId, f.at);
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
const now = Date.now();
|
|
1855
|
-
for (const [stepId, stepState] of Object.entries(state.steps)) {
|
|
1856
|
-
const status2 = stepStatusOf(stepState);
|
|
1857
|
-
const attempt = attemptOf(stepState);
|
|
1858
|
-
const out = outputOf(stepState);
|
|
1859
|
-
const err = errorOf(stepState);
|
|
1860
|
-
const startedAt = startedAtByStep.get(stepId);
|
|
1861
|
-
const completedAt2 = completedAtByStep.get(stepId);
|
|
1862
|
-
let lease;
|
|
1863
|
-
const leasePrefix = `${runId}::${stepId}::`;
|
|
1864
|
-
let bestExpiry = 0;
|
|
1865
|
-
for (const [key, l] of this.leases) {
|
|
1866
|
-
if (!key.startsWith(leasePrefix)) continue;
|
|
1867
|
-
if (l.expiresAt > now && l.expiresAt > bestExpiry)
|
|
1868
|
-
bestExpiry = l.expiresAt;
|
|
1869
|
-
}
|
|
1870
|
-
if (bestExpiry > 0) lease = { expiresAt: new Date(bestExpiry) };
|
|
1871
|
-
steps.push({
|
|
1872
|
-
stepId,
|
|
1873
|
-
attempt,
|
|
1874
|
-
status: status2,
|
|
1875
|
-
...startedAt !== void 0 ? { startedAt } : {},
|
|
1876
|
-
...completedAt2 !== void 0 ? { completedAt: completedAt2 } : {},
|
|
1877
|
-
...out !== null ? { output: out } : {},
|
|
1878
|
-
...err !== void 0 ? { error: err } : {},
|
|
1879
|
-
...lease !== void 0 ? { lease } : {}
|
|
1880
|
-
});
|
|
1881
|
-
}
|
|
1882
|
-
steps.sort((a, b) => {
|
|
1883
|
-
const ta = a.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
1884
|
-
const tb = b.startedAt?.getTime() ?? Number.POSITIVE_INFINITY;
|
|
1885
|
-
if (ta !== tb) return ta - tb;
|
|
1886
|
-
return a.stepId < b.stepId ? -1 : a.stepId > b.stepId ? 1 : 0;
|
|
1887
|
-
});
|
|
1888
|
-
return { run, steps };
|
|
1889
|
-
}
|
|
1890
|
-
async pruneFacts(opts) {
|
|
1891
|
-
const olderThanMs = opts.olderThan.getTime();
|
|
1892
|
-
const statusSet = new Set(opts.statuses);
|
|
1893
|
-
const victims = [];
|
|
1894
|
-
for (const [runId, factList] of this.facts) {
|
|
1895
|
-
const summary = summarize(runId, factList);
|
|
1896
|
-
if (summary === null) continue;
|
|
1897
|
-
if (summary.completedAt === null) continue;
|
|
1898
|
-
if (!statusSet.has(summary.status)) continue;
|
|
1899
|
-
if (summary.completedAt.getTime() >= olderThanMs) continue;
|
|
1900
|
-
const first = factList[0];
|
|
1901
|
-
const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parent?.runId : void 0;
|
|
1902
|
-
victims.push({
|
|
1903
|
-
runId,
|
|
1904
|
-
summary,
|
|
1905
|
-
factCount: factList.length,
|
|
1906
|
-
parentRunId
|
|
1907
|
-
});
|
|
1908
|
-
}
|
|
1909
|
-
let runsPruned = 0;
|
|
1910
|
-
let factsPruned = 0;
|
|
1911
|
-
for (const v of victims) {
|
|
1912
|
-
this.facts.delete(v.runId);
|
|
1913
|
-
deleteByRunPrefix(this.onces, v.runId);
|
|
1914
|
-
deleteByRunPrefix(this.leases, v.runId);
|
|
1915
|
-
this.childrenByParent.delete(v.runId);
|
|
1916
|
-
if (v.parentRunId !== void 0) {
|
|
1917
|
-
const siblings = this.childrenByParent.get(v.parentRunId);
|
|
1918
|
-
if (siblings !== void 0) {
|
|
1919
|
-
siblings.delete(v.runId);
|
|
1920
|
-
if (siblings.size === 0) this.childrenByParent.delete(v.parentRunId);
|
|
1921
|
-
}
|
|
1922
|
-
}
|
|
1923
|
-
if (opts.keepSummary) {
|
|
1924
|
-
this.summaries.set(v.runId, v.summary);
|
|
1925
|
-
} else {
|
|
1926
|
-
this.summaries.delete(v.runId);
|
|
1927
|
-
}
|
|
1928
|
-
runsPruned += 1;
|
|
1929
|
-
factsPruned += v.factCount;
|
|
1930
|
-
}
|
|
1931
|
-
return { runsPruned, factsPruned };
|
|
1932
|
-
}
|
|
1933
|
-
subscribeStream(runId, stepId, opts) {
|
|
1934
|
-
const state = foldRun(runId, this.facts.get(runId) ?? []);
|
|
1935
|
-
const stepStatus = stepStatusOf(stepStateOf(state, stepId));
|
|
1936
|
-
const runIsTerminal = isTerminalRun(state);
|
|
1937
|
-
if (runIsTerminal || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
|
|
1938
|
-
return EMPTY_CLOSED_STREAM;
|
|
1939
|
-
}
|
|
1940
|
-
return this.streamHub.subscribeStream(runId, stepId, opts);
|
|
1941
|
-
}
|
|
1942
|
-
publishChunk(runId, stepId, chunk) {
|
|
1943
|
-
this.streamHub.publishChunk(runId, stepId, chunk);
|
|
1944
|
-
}
|
|
1945
|
-
};
|
|
1946
|
-
var EMPTY_CLOSED_STREAM = {
|
|
1947
|
-
[Symbol.asyncIterator]() {
|
|
1948
|
-
return { next: async () => ({ value: void 0, done: true }) };
|
|
1949
|
-
}
|
|
1950
|
-
};
|
|
1951
|
-
function deleteByRunPrefix(map, runId) {
|
|
1952
|
-
const prefix = `${runId}::`;
|
|
1953
|
-
for (const key of map.keys()) {
|
|
1954
|
-
if (key.startsWith(prefix)) map.delete(key);
|
|
1955
|
-
}
|
|
1956
|
-
}
|
|
1957
|
-
function summarize(runId, facts) {
|
|
1958
|
-
const first = facts[0];
|
|
1959
|
-
if (first === void 0 || first.kind !== "flow.started") return null;
|
|
1960
|
-
const projected = foldRun(runId, facts);
|
|
1961
|
-
let completedAt = null;
|
|
1962
|
-
for (let i = isTerminalRun(projected) ? facts.length - 1 : -1; i >= 0; i--) {
|
|
1963
|
-
const f = facts[i];
|
|
1964
|
-
if (f === void 0) continue;
|
|
1965
|
-
if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
|
|
1966
|
-
completedAt = f.at;
|
|
1967
|
-
break;
|
|
1968
|
-
}
|
|
1969
|
-
}
|
|
1970
|
-
return {
|
|
1971
|
-
runId,
|
|
1972
|
-
flowId: first.flowId,
|
|
1973
|
-
status: runStatusOf(projected),
|
|
1974
|
-
startedAt: first.at,
|
|
1975
|
-
completedAt,
|
|
1976
|
-
input: first.input
|
|
1977
|
-
};
|
|
1978
|
-
}
|
|
1979
|
-
var DEFAULT_LIMIT = 50;
|
|
1980
|
-
var MAX_LIMIT = 500;
|
|
1981
|
-
function clampLimit(limit) {
|
|
1982
|
-
if (limit === void 0) return DEFAULT_LIMIT;
|
|
1983
|
-
if (!Number.isInteger(limit) || limit < 1) return DEFAULT_LIMIT;
|
|
1984
|
-
return Math.min(limit, MAX_LIMIT);
|
|
1985
|
-
}
|
|
1986
|
-
function encodeCursor(c) {
|
|
1987
|
-
const bytes = new TextEncoder().encode(JSON.stringify(c));
|
|
1988
|
-
let binary = "";
|
|
1989
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
1990
|
-
binary += String.fromCharCode(bytes[i]);
|
|
1991
|
-
}
|
|
1992
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1993
|
-
}
|
|
1994
|
-
function decodeCursor(s) {
|
|
1995
|
-
try {
|
|
1996
|
-
const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
1997
|
-
const binary = atob(b64);
|
|
1998
|
-
const bytes = new Uint8Array(binary.length);
|
|
1999
|
-
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
2000
|
-
const parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
2001
|
-
if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
|
|
2002
|
-
return parsed;
|
|
2003
|
-
}
|
|
2004
|
-
throw new Error("malformed cursor body");
|
|
2005
|
-
} catch (err) {
|
|
2006
|
-
throw new Error(
|
|
2007
|
-
`queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
|
|
2008
|
-
);
|
|
2009
|
-
}
|
|
2010
|
-
}
|
|
2011
|
-
function containsJson(haystack, needle) {
|
|
2012
|
-
if (Array.isArray(needle)) {
|
|
2013
|
-
if (!Array.isArray(haystack)) return false;
|
|
2014
|
-
return needle.every((n) => haystack.some((h) => containsJson(h, n)));
|
|
2015
|
-
}
|
|
2016
|
-
if (needle !== null && typeof needle === "object") {
|
|
2017
|
-
if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
|
|
2018
|
-
return false;
|
|
2019
|
-
return Object.entries(needle).every(
|
|
2020
|
-
([k, v]) => k in haystack && containsJson(haystack[k], v)
|
|
2021
|
-
);
|
|
2022
|
-
}
|
|
2023
|
-
return haystack === needle;
|
|
2024
|
-
}
|
|
2025
|
-
var DEFAULT_QUEUE_LEASE_MS = 6e4;
|
|
2026
|
-
var InMemoryQueue = class {
|
|
2027
|
-
pending = [];
|
|
2028
|
-
leased = /* @__PURE__ */ new Map();
|
|
2029
|
-
leaseMs;
|
|
2030
|
-
constructor(opts = {}) {
|
|
2031
|
-
this.leaseMs = opts.leaseMs ?? DEFAULT_QUEUE_LEASE_MS;
|
|
2032
|
-
}
|
|
2033
|
-
async enqueue(runId, stepId, opts) {
|
|
2034
|
-
const now = Date.now();
|
|
2035
|
-
const item = {
|
|
2036
|
-
receipt: crypto.randomUUID(),
|
|
2037
|
-
runId,
|
|
2038
|
-
stepId,
|
|
2039
|
-
payload: opts?.payload ?? null,
|
|
2040
|
-
attempt: opts?.attempt ?? 1,
|
|
2041
|
-
readCount: 0,
|
|
2042
|
-
enqueuedAt: now,
|
|
2043
|
-
visibleAt: now + (opts?.delayMs ?? 0),
|
|
2044
|
-
...opts?.flowId !== void 0 ? { flowId: opts.flowId } : {}
|
|
2045
|
-
};
|
|
2046
|
-
this.pending.push(item);
|
|
2047
|
-
}
|
|
2048
|
-
async dequeue(opts) {
|
|
2049
|
-
const now = Date.now();
|
|
2050
|
-
const claimed = [];
|
|
2051
|
-
for (let i = 0; i < this.pending.length && claimed.length < opts.count; i++) {
|
|
2052
|
-
const item = this.pending[i];
|
|
2053
|
-
if (item === void 0) continue;
|
|
2054
|
-
if (item.visibleAt > now) continue;
|
|
2055
|
-
const delivered = {
|
|
2056
|
-
...item,
|
|
2057
|
-
readCount: item.readCount + 1,
|
|
2058
|
-
visibleAt: now + this.leaseMs
|
|
2059
|
-
};
|
|
2060
|
-
this.pending.splice(i, 1);
|
|
2061
|
-
i--;
|
|
2062
|
-
this.leased.set(item.receipt, delivered);
|
|
2063
|
-
claimed.push(delivered);
|
|
2064
|
-
}
|
|
2065
|
-
return claimed;
|
|
2066
|
-
}
|
|
2067
|
-
async ack(receipt) {
|
|
2068
|
-
this.leased.delete(receipt);
|
|
2069
|
-
}
|
|
2070
|
-
async nack(receipt, opts) {
|
|
2071
|
-
const item = this.leased.get(receipt);
|
|
2072
|
-
if (!item) return;
|
|
2073
|
-
this.leased.delete(receipt);
|
|
2074
|
-
const requeued = {
|
|
2075
|
-
...item,
|
|
2076
|
-
visibleAt: Date.now() + (opts?.delayMs ?? 0)
|
|
2077
|
-
};
|
|
2078
|
-
this.pending.push(requeued);
|
|
2079
|
-
}
|
|
2080
|
-
async extend(receipt, leaseMs) {
|
|
2081
|
-
const item = this.leased.get(receipt);
|
|
2082
|
-
if (!item) return;
|
|
2083
|
-
this.leased.set(receipt, { ...item, visibleAt: Date.now() + leaseMs });
|
|
2084
|
-
}
|
|
2085
|
-
async inspect(runId) {
|
|
2086
|
-
const all = [...this.pending, ...this.leased.values()];
|
|
2087
|
-
return all.filter((m) => m.runId === runId).map((m) => ({
|
|
2088
|
-
stepId: m.stepId,
|
|
2089
|
-
attempt: m.attempt,
|
|
2090
|
-
readCount: m.readCount,
|
|
2091
|
-
visibleAt: new Date(m.visibleAt)
|
|
2092
|
-
}));
|
|
2093
|
-
}
|
|
2094
|
-
};
|
|
2095
|
-
var InMemoryClock = class {
|
|
2096
|
-
timers = /* @__PURE__ */ new Map();
|
|
2097
|
-
trigger;
|
|
2098
|
-
constructor(opts = {}) {
|
|
2099
|
-
this.trigger = opts.trigger;
|
|
2100
|
-
}
|
|
2101
|
-
now() {
|
|
2102
|
-
return /* @__PURE__ */ new Date();
|
|
2103
|
-
}
|
|
2104
|
-
async sleep(ms, signal) {
|
|
2105
|
-
if (signal?.aborted) {
|
|
2106
|
-
throw signal.reason ?? new Error("aborted");
|
|
2107
|
-
}
|
|
2108
|
-
return new Promise((resolve, reject) => {
|
|
2109
|
-
const timer = setTimeout(() => {
|
|
2110
|
-
signal?.removeEventListener("abort", onAbort);
|
|
2111
|
-
resolve();
|
|
2112
|
-
}, ms);
|
|
2113
|
-
const onAbort = () => {
|
|
2114
|
-
clearTimeout(timer);
|
|
2115
|
-
reject(signal?.reason ?? new Error("aborted"));
|
|
2116
|
-
};
|
|
2117
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2118
|
-
});
|
|
2119
|
-
}
|
|
2120
|
-
async schedule(at, runId, stepId) {
|
|
2121
|
-
const key = `${runId}::${stepId}`;
|
|
2122
|
-
const existing = this.timers.get(key);
|
|
2123
|
-
if (existing !== void 0) clearTimeout(existing);
|
|
2124
|
-
const delay = Math.max(0, at.getTime() - Date.now());
|
|
2125
|
-
const handle = setTimeout(() => {
|
|
2126
|
-
this.timers.delete(key);
|
|
2127
|
-
this.trigger?.fire(runId);
|
|
2128
|
-
}, delay);
|
|
2129
|
-
this.timers.set(key, handle);
|
|
2130
|
-
}
|
|
2131
|
-
dispose() {
|
|
2132
|
-
for (const t of this.timers.values()) clearTimeout(t);
|
|
2133
|
-
this.timers.clear();
|
|
2134
|
-
}
|
|
2135
|
-
};
|
|
2136
|
-
var InMemoryTrigger = class {
|
|
2137
|
-
handlers = [];
|
|
2138
|
-
subscribe(handler) {
|
|
2139
|
-
this.handlers.push(handler);
|
|
2140
|
-
return () => {
|
|
2141
|
-
this.handlers = this.handlers.filter((h) => h !== handler);
|
|
2142
|
-
};
|
|
2143
|
-
}
|
|
2144
|
-
fire(runId) {
|
|
2145
|
-
for (const h of this.handlers) h(runId);
|
|
2146
|
-
}
|
|
2147
|
-
};
|
|
2148
|
-
|
|
2149
|
-
// src/run-id.ts
|
|
2150
|
-
var RunId = {
|
|
2151
|
-
parse(s) {
|
|
2152
|
-
if (typeof s !== "string" || s.length === 0) {
|
|
2153
|
-
throw validationError("RunId.parse: must be a non-empty string", [
|
|
2154
|
-
"runId"
|
|
2155
|
-
]);
|
|
2156
|
-
}
|
|
2157
|
-
if (/\s/.test(s)) {
|
|
2158
|
-
throw validationError("RunId.parse: must not contain whitespace", [
|
|
2159
|
-
"runId"
|
|
2160
|
-
]);
|
|
2161
|
-
}
|
|
2162
|
-
return s;
|
|
2163
|
-
},
|
|
2164
|
-
fromTrusted(s) {
|
|
2165
|
-
return s;
|
|
2166
|
-
}
|
|
2167
|
-
};
|
|
2168
|
-
async function deriveChildRunId(key) {
|
|
2169
|
-
const seed = `nagi:subflow:${key.runId}:${key.stepId}:gen${key.generation}`;
|
|
2170
|
-
const digest = await crypto.subtle.digest(
|
|
2171
|
-
"SHA-256",
|
|
2172
|
-
new TextEncoder().encode(seed)
|
|
2173
|
-
);
|
|
2174
|
-
const bytes = new Uint8Array(digest).subarray(0, 16);
|
|
2175
|
-
bytes[6] = (bytes[6] ?? 0) & 15 | 80;
|
|
2176
|
-
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
2177
|
-
const hex2 = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
|
|
2178
|
-
""
|
|
2179
|
-
);
|
|
2180
|
-
const uuid = `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20, 32)}`;
|
|
2181
|
-
return `run-${uuid}`;
|
|
2182
|
-
}
|
|
2183
|
-
|
|
2184
|
-
// src/exec/hooks.ts
|
|
2185
|
-
function makeHooks(deps) {
|
|
2186
|
-
async function fireHook(hook, event, hookName) {
|
|
2187
|
-
if (deps.fireHooks === false) return;
|
|
2188
|
-
if (hook === void 0) return;
|
|
2189
|
-
try {
|
|
2190
|
-
await hook(event);
|
|
2191
|
-
} catch (err) {
|
|
2192
|
-
const { message, stack } = serializeError(err);
|
|
2193
|
-
deps.emitLog({
|
|
2194
|
-
level: "error",
|
|
2195
|
-
msg: `nagi hook "${hookName}" threw \u2014 swallowed`,
|
|
2196
|
-
attrs: { error: message, ...stack !== void 0 ? { stack } : {} }
|
|
2197
|
-
});
|
|
2198
|
-
}
|
|
2199
|
-
}
|
|
2200
|
-
async function fireStepLifecycle(stepHook, flowHook, [stepName, flowName], event) {
|
|
2201
|
-
await fireHook(stepHook, event, stepName);
|
|
2202
|
-
await fireHook(flowHook, event, flowName);
|
|
2203
|
-
}
|
|
2204
|
-
return { fireHook, fireStepLifecycle };
|
|
2205
|
-
}
|
|
2206
|
-
|
|
2207
|
-
// src/scheduler.ts
|
|
2208
|
-
function nextRunnable({
|
|
2209
|
-
flow: flow2,
|
|
2210
|
-
runState,
|
|
2211
|
-
input
|
|
2212
|
-
}) {
|
|
2213
|
-
const runnable = [];
|
|
2214
|
-
const skip = [];
|
|
2215
|
-
for (const [stepId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
|
|
2216
|
-
if (stepStateOf(runState, stepId).tag !== "pending") continue;
|
|
2217
|
-
const gate = gateStep(getDef(step), runState, input);
|
|
2218
|
-
switch (gate.kind) {
|
|
2219
|
-
case "run":
|
|
2220
|
-
runnable.push(stepId);
|
|
2221
|
-
break;
|
|
2222
|
-
case "skip":
|
|
2223
|
-
skip.push({ stepId, reason: gate.reason });
|
|
2224
|
-
break;
|
|
2225
|
-
}
|
|
2226
|
-
}
|
|
2227
|
-
return { runnable, skip };
|
|
2228
|
-
}
|
|
2229
|
-
function gateStep(def, runState, input) {
|
|
2230
|
-
const parent = checkParentMatch(def, runState);
|
|
2231
|
-
if (parent !== "ready") return gateFor(parent);
|
|
2232
|
-
const upstream = checkUpstream(def, runState);
|
|
2233
|
-
if (upstream !== "ready") return gateFor(upstream);
|
|
2234
|
-
const when = def.kind === "match" ? void 0 : def.when;
|
|
2235
|
-
if (when) {
|
|
2236
|
-
const needs = resolveNeeds(
|
|
2237
|
-
def,
|
|
2238
|
-
(id) => resolvedOf(stepStateOf(runState, id))
|
|
2239
|
-
);
|
|
2240
|
-
if (!when({ input, needs })) return { kind: "skip", reason: "when-false" };
|
|
2241
|
-
}
|
|
2242
|
-
return { kind: "run" };
|
|
2243
|
-
}
|
|
2244
|
-
function gateFor(status) {
|
|
2245
|
-
switch (status) {
|
|
2246
|
-
case "blocked":
|
|
2247
|
-
return { kind: "block" };
|
|
2248
|
-
case "transitive-skip":
|
|
2249
|
-
return { kind: "skip", reason: "transitive" };
|
|
2250
|
-
}
|
|
2251
|
-
}
|
|
2252
|
-
function checkUpstream(def, runState) {
|
|
2253
|
-
for (const ref of Object.values(def.needs)) {
|
|
2254
|
-
const upstreamState = stepStateOf(runState, ref.step.id);
|
|
2255
|
-
if (upstreamState.tag === "completed") continue;
|
|
2256
|
-
if (ref.optional && upstreamState.tag === "skipped") continue;
|
|
2257
|
-
if (upstreamState.tag === "skipped" || upstreamState.tag === "failed") {
|
|
2258
|
-
return "transitive-skip";
|
|
2259
|
-
}
|
|
2260
|
-
return "blocked";
|
|
2261
|
-
}
|
|
2262
|
-
return "ready";
|
|
2263
|
-
}
|
|
2264
|
-
function checkParentMatch(def, runState) {
|
|
2265
|
-
if (!def.parentMatch) return "ready";
|
|
2266
|
-
const { matchId, armId } = def.parentMatch;
|
|
2267
|
-
const parentState = stepStateOf(runState, matchId);
|
|
2268
|
-
if (parentState.tag === "failed" || parentState.tag === "skipped") {
|
|
2269
|
-
return "transitive-skip";
|
|
2270
|
-
}
|
|
2271
|
-
const selected = runState.selectedArms[matchId] ?? null;
|
|
2272
|
-
if (selected === null) return "blocked";
|
|
2273
|
-
return selected === armId ? "ready" : "transitive-skip";
|
|
616
|
+
const selected = runState.selectedArms[matchId] ?? null;
|
|
617
|
+
if (selected === null) return "blocked";
|
|
618
|
+
return selected === armId ? "ready" : "transitive-skip";
|
|
2274
619
|
}
|
|
2275
620
|
function aggregateMatch(matchId, flow2, runState) {
|
|
2276
621
|
const step = asStepMapWithDefs(flow2.steps)[matchId];
|
|
@@ -2411,12 +756,6 @@ function makeOnce({
|
|
|
2411
756
|
}
|
|
2412
757
|
|
|
2413
758
|
// src/step-exec.ts
|
|
2414
|
-
var DEFAULT_RETRY2 = {
|
|
2415
|
-
maxAttempts: 3,
|
|
2416
|
-
backoff: "exponential",
|
|
2417
|
-
initialDelayMs: 1e3,
|
|
2418
|
-
maxDelayMs: 6e4
|
|
2419
|
-
};
|
|
2420
759
|
var CANCEL_POLL_INTERVAL_MS = 250;
|
|
2421
760
|
var NagiAbortError = class extends Error {
|
|
2422
761
|
runId;
|
|
@@ -2564,7 +903,7 @@ function classifyFailure(args) {
|
|
|
2564
903
|
return { tag: "failed" };
|
|
2565
904
|
}
|
|
2566
905
|
if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
|
|
2567
|
-
return { tag: "retry", delayMs:
|
|
906
|
+
return { tag: "retry", delayMs: stepBackoff(policy)(attempt) };
|
|
2568
907
|
}
|
|
2569
908
|
return { tag: "failed" };
|
|
2570
909
|
}
|
|
@@ -2578,18 +917,6 @@ function findInCauseChain(err, ctor) {
|
|
|
2578
917
|
}
|
|
2579
918
|
return void 0;
|
|
2580
919
|
}
|
|
2581
|
-
function computeBackoff(policy, attempt) {
|
|
2582
|
-
const initial = policy.initialDelayMs ?? 1e3;
|
|
2583
|
-
const max = policy.maxDelayMs ?? 6e4;
|
|
2584
|
-
switch (policy.backoff) {
|
|
2585
|
-
case "exponential":
|
|
2586
|
-
return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
|
|
2587
|
-
case "linear":
|
|
2588
|
-
return Math.min(initial * Math.max(1, attempt), max);
|
|
2589
|
-
case "fixed":
|
|
2590
|
-
return Math.min(initial, max);
|
|
2591
|
-
}
|
|
2592
|
-
}
|
|
2593
920
|
function retryAllows(policy, err) {
|
|
2594
921
|
if (!policy.retryOn) return true;
|
|
2595
922
|
return policy.retryOn(err);
|
|
@@ -2643,25 +970,30 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2643
970
|
const { advance } = progression;
|
|
2644
971
|
async function dispatchMessage(message) {
|
|
2645
972
|
const { queue } = deps;
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
973
|
+
const resolution = await deps.resolveFlow(message.runId);
|
|
974
|
+
let flow2;
|
|
975
|
+
switch (resolution.kind) {
|
|
976
|
+
case "current":
|
|
977
|
+
flow2 = resolution.flow;
|
|
978
|
+
break;
|
|
979
|
+
// A terminal run's message must not outlive it: a run canceled AFTER
|
|
980
|
+
// its snapshot went gone would otherwise nack-loop forever, since the
|
|
981
|
+
// hash check fires before admit()'s canceled-phase check ever runs.
|
|
982
|
+
case "gone-terminal":
|
|
2651
983
|
await queue.ack(message.receipt);
|
|
2652
|
-
return;
|
|
2653
|
-
|
|
2654
|
-
|
|
984
|
+
return { kind: "done" };
|
|
985
|
+
case "gone-live":
|
|
986
|
+
return { kind: "snapshot-gone", error: resolution.error };
|
|
2655
987
|
}
|
|
2656
988
|
const admission = await admit({ flow: flow2, message });
|
|
2657
989
|
if (admission.tag === "skip") {
|
|
2658
990
|
await queue.ack(message.receipt);
|
|
2659
|
-
return;
|
|
991
|
+
return { kind: "done" };
|
|
2660
992
|
}
|
|
2661
993
|
if (admission.tag === "recover") {
|
|
2662
994
|
await advance(message.runId);
|
|
2663
995
|
await queue.ack(message.receipt);
|
|
2664
|
-
return;
|
|
996
|
+
return { kind: "done" };
|
|
2665
997
|
}
|
|
2666
998
|
const { def, state } = admission;
|
|
2667
999
|
await recordStarted({ flow: flow2, message, def, state });
|
|
@@ -2688,6 +1020,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
2688
1020
|
}
|
|
2689
1021
|
await interpret({ flow: flow2, message, def, startedAt, outcome });
|
|
2690
1022
|
await queue.ack(message.receipt);
|
|
1023
|
+
return { kind: "done" };
|
|
2691
1024
|
}
|
|
2692
1025
|
async function admit(args) {
|
|
2693
1026
|
const { flow: flow2, message } = args;
|
|
@@ -3004,7 +1337,7 @@ function makeMessage(deps, hooks, progression) {
|
|
|
3004
1337
|
const error = serializeError(err);
|
|
3005
1338
|
const handler = handlerDef(def);
|
|
3006
1339
|
const postState = await store.loadRunState(runId);
|
|
3007
|
-
const policy = handler?.retry
|
|
1340
|
+
const policy = resolveRetry(handler?.retry, deps.defaultRetry);
|
|
3008
1341
|
const outcome = classifyFailure({
|
|
3009
1342
|
attempt,
|
|
3010
1343
|
policy,
|
|
@@ -3084,6 +1417,158 @@ function makeMessage(deps, hooks, progression) {
|
|
|
3084
1417
|
return { dispatchMessage };
|
|
3085
1418
|
}
|
|
3086
1419
|
|
|
1420
|
+
// src/flows.ts
|
|
1421
|
+
function requireCurrent(resolution) {
|
|
1422
|
+
if (resolution.kind === "current") return resolution.flow;
|
|
1423
|
+
throw resolution.error;
|
|
1424
|
+
}
|
|
1425
|
+
async function registerFlows(deps) {
|
|
1426
|
+
const { flows, store, clock } = deps;
|
|
1427
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1428
|
+
const hashById = /* @__PURE__ */ new Map();
|
|
1429
|
+
const streamingStepIds = /* @__PURE__ */ new Set();
|
|
1430
|
+
for (const flow2 of flows) {
|
|
1431
|
+
if (byId.has(flow2.id)) {
|
|
1432
|
+
throw new NagiRuntimeError(
|
|
1433
|
+
`Duplicate flow id "${flow2.id}" passed to nagi()`
|
|
1434
|
+
);
|
|
1435
|
+
}
|
|
1436
|
+
byId.set(flow2.id, flow2);
|
|
1437
|
+
for (const [stepId, step] of Object.entries(
|
|
1438
|
+
asStepMapWithDefs(flow2.steps)
|
|
1439
|
+
)) {
|
|
1440
|
+
if (getDef(step).kind === "streaming") streamingStepIds.add(stepId);
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
for (const flow2 of flows) {
|
|
1444
|
+
const dag = await canonicalize(flow2);
|
|
1445
|
+
const flowHash = await sha256Canonical(dag);
|
|
1446
|
+
hashById.set(flow2.id, flowHash);
|
|
1447
|
+
await store.upsertSnapshot({
|
|
1448
|
+
flowHash,
|
|
1449
|
+
flowId: flow2.id,
|
|
1450
|
+
dag
|
|
1451
|
+
});
|
|
1452
|
+
const previousHash = await store.getRef(flow2.id);
|
|
1453
|
+
if (previousHash !== flowHash) {
|
|
1454
|
+
await store.setRef(flow2.id, flowHash);
|
|
1455
|
+
await store.appendGlobalFact(
|
|
1456
|
+
Facts.flowRefUpdated({
|
|
1457
|
+
flowId: flow2.id,
|
|
1458
|
+
from: previousHash,
|
|
1459
|
+
to: flowHash,
|
|
1460
|
+
at: clock.now()
|
|
1461
|
+
})
|
|
1462
|
+
);
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
function require2(flowId) {
|
|
1466
|
+
const flow2 = byId.get(flowId);
|
|
1467
|
+
if (!flow2) {
|
|
1468
|
+
throw new NagiRuntimeError(
|
|
1469
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
1470
|
+
);
|
|
1471
|
+
}
|
|
1472
|
+
return flow2;
|
|
1473
|
+
}
|
|
1474
|
+
function hashOf(flowId) {
|
|
1475
|
+
const hash = hashById.get(flowId);
|
|
1476
|
+
if (hash === void 0) {
|
|
1477
|
+
throw new NagiRuntimeError(
|
|
1478
|
+
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
1479
|
+
);
|
|
1480
|
+
}
|
|
1481
|
+
return hash;
|
|
1482
|
+
}
|
|
1483
|
+
function resolve(state) {
|
|
1484
|
+
const { runId, flowId, flowHash: pinnedHash } = state;
|
|
1485
|
+
const live = byId.get(flowId);
|
|
1486
|
+
if (pinnedHash === void 0) {
|
|
1487
|
+
if (live === void 0) {
|
|
1488
|
+
throw new NagiRuntimeError(
|
|
1489
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
1490
|
+
);
|
|
1491
|
+
}
|
|
1492
|
+
return { kind: "current", flow: live };
|
|
1493
|
+
}
|
|
1494
|
+
const currentHash = live === void 0 ? null : hashOf(flowId);
|
|
1495
|
+
if (live !== void 0 && currentHash === pinnedHash) {
|
|
1496
|
+
return { kind: "current", flow: live };
|
|
1497
|
+
}
|
|
1498
|
+
const error = new NagiFlowSnapshotGoneError({
|
|
1499
|
+
runId,
|
|
1500
|
+
flowId,
|
|
1501
|
+
pinnedHash,
|
|
1502
|
+
currentHash
|
|
1503
|
+
});
|
|
1504
|
+
return isTerminalRun(state) ? { kind: "gone-terminal", error, live } : { kind: "gone-live", error, live };
|
|
1505
|
+
}
|
|
1506
|
+
async function synthesize(gone) {
|
|
1507
|
+
const { runId, flowId, pinnedHash } = gone.error;
|
|
1508
|
+
if (gone.live === void 0) {
|
|
1509
|
+
throw new NagiRuntimeError(
|
|
1510
|
+
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
1511
|
+
);
|
|
1512
|
+
}
|
|
1513
|
+
const snapshot = await store.loadSnapshot(pinnedHash);
|
|
1514
|
+
if (snapshot === null) {
|
|
1515
|
+
throw new NagiRuntimeError(
|
|
1516
|
+
`Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Cannot replay with allowDrift.`
|
|
1517
|
+
);
|
|
1518
|
+
}
|
|
1519
|
+
return synthesizeReplayFlow(
|
|
1520
|
+
snapshot.dag,
|
|
1521
|
+
gone.live
|
|
1522
|
+
);
|
|
1523
|
+
}
|
|
1524
|
+
return {
|
|
1525
|
+
get: (flowId) => byId.get(flowId),
|
|
1526
|
+
has: (flowId) => byId.has(flowId),
|
|
1527
|
+
require: require2,
|
|
1528
|
+
hashOf,
|
|
1529
|
+
isStreaming: (stepId) => streamingStepIds.has(stepId),
|
|
1530
|
+
resolve,
|
|
1531
|
+
synthesize
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
function synthesizeReplayFlow(dag, liveFlow) {
|
|
1535
|
+
const liveSteps = asStepMapWithDefs(liveFlow.steps);
|
|
1536
|
+
const synthesized = {};
|
|
1537
|
+
for (const canonStep of dag.steps) {
|
|
1538
|
+
const liveStep = liveSteps[canonStep.id];
|
|
1539
|
+
if (liveStep === void 0) {
|
|
1540
|
+
throw new NagiRuntimeError(
|
|
1541
|
+
`Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
|
|
1542
|
+
);
|
|
1543
|
+
}
|
|
1544
|
+
synthesized[canonStep.id] = attachDef(
|
|
1545
|
+
{ kind: canonStep.kind, id: canonStep.id },
|
|
1546
|
+
getDef(liveStep)
|
|
1547
|
+
);
|
|
1548
|
+
}
|
|
1549
|
+
for (const canonStep of dag.steps) {
|
|
1550
|
+
const shell = synthesized[canonStep.id];
|
|
1551
|
+
if (shell === void 0) continue;
|
|
1552
|
+
const synthesizedNeeds = {};
|
|
1553
|
+
for (const upstreamId of canonStep.needs) {
|
|
1554
|
+
const upstreamShell = synthesized[upstreamId];
|
|
1555
|
+
if (upstreamShell === void 0) {
|
|
1556
|
+
throw new NagiRuntimeError(
|
|
1557
|
+
`Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
|
|
1558
|
+
);
|
|
1559
|
+
}
|
|
1560
|
+
synthesizedNeeds[upstreamId] = upstreamShell;
|
|
1561
|
+
}
|
|
1562
|
+
setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
|
|
1563
|
+
}
|
|
1564
|
+
return {
|
|
1565
|
+
id: liveFlow.id,
|
|
1566
|
+
input: liveFlow.input,
|
|
1567
|
+
steps: synthesized,
|
|
1568
|
+
...compact({ output: liveFlow.output })
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
|
|
3087
1572
|
// src/exec/progression.ts
|
|
3088
1573
|
var MAX_ADVANCE_ITERS = 1024;
|
|
3089
1574
|
function subflowOutcomeOf(childRunId, child) {
|
|
@@ -3128,7 +1613,7 @@ function makeProgression(deps, hooks) {
|
|
|
3128
1613
|
const { fireHook } = hooks;
|
|
3129
1614
|
async function advance(runId) {
|
|
3130
1615
|
const { store, queue } = deps;
|
|
3131
|
-
const flow2 = await deps.
|
|
1616
|
+
const flow2 = requireCurrent(await deps.resolveFlow(runId));
|
|
3132
1617
|
for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
|
|
3133
1618
|
const runState = await store.loadRunState(runId);
|
|
3134
1619
|
const t = nextTransition(flow2, runState);
|
|
@@ -3277,7 +1762,7 @@ function makeProgression(deps, hooks) {
|
|
|
3277
1762
|
return;
|
|
3278
1763
|
}
|
|
3279
1764
|
const attempt = parentStep.attempt;
|
|
3280
|
-
const parentFlow = await deps.
|
|
1765
|
+
const parentFlow = requireCurrent(await deps.resolveFlow(parentRunId));
|
|
3281
1766
|
await markStepSettled({
|
|
3282
1767
|
flow: parentFlow,
|
|
3283
1768
|
runId: parentRunId,
|
|
@@ -3307,7 +1792,7 @@ function makeDispatcher(deps) {
|
|
|
3307
1792
|
for (const { runId, stepId, attempt, fireAt } of timedOut) {
|
|
3308
1793
|
try {
|
|
3309
1794
|
if (deps.hooks?.onStepError) {
|
|
3310
|
-
const flow2 = await deps.
|
|
1795
|
+
const flow2 = requireCurrent(await deps.resolveFlow(runId));
|
|
3311
1796
|
await hooks.fireHook(
|
|
3312
1797
|
deps.hooks.onStepError,
|
|
3313
1798
|
{
|
|
@@ -3343,61 +1828,6 @@ function makeDispatcher(deps) {
|
|
|
3343
1828
|
};
|
|
3344
1829
|
}
|
|
3345
1830
|
|
|
3346
|
-
// src/flow-registry.ts
|
|
3347
|
-
function makeFlowRegistry(flows) {
|
|
3348
|
-
const byId = /* @__PURE__ */ new Map();
|
|
3349
|
-
const streamingStepIds = /* @__PURE__ */ new Set();
|
|
3350
|
-
for (const flow2 of flows) {
|
|
3351
|
-
if (byId.has(flow2.id)) {
|
|
3352
|
-
throw new NagiRuntimeError(
|
|
3353
|
-
`Duplicate flow id "${flow2.id}" passed to nagi()`
|
|
3354
|
-
);
|
|
3355
|
-
}
|
|
3356
|
-
byId.set(flow2.id, flow2);
|
|
3357
|
-
for (const [stepId, step] of Object.entries(
|
|
3358
|
-
asStepMapWithDefs(flow2.steps)
|
|
3359
|
-
)) {
|
|
3360
|
-
if (getDef(step).kind === "streaming") streamingStepIds.add(stepId);
|
|
3361
|
-
}
|
|
3362
|
-
}
|
|
3363
|
-
return {
|
|
3364
|
-
all: flows,
|
|
3365
|
-
get: (flowId) => byId.get(flowId),
|
|
3366
|
-
has: (flowId) => byId.has(flowId),
|
|
3367
|
-
require(flowId) {
|
|
3368
|
-
const flow2 = byId.get(flowId);
|
|
3369
|
-
if (!flow2) {
|
|
3370
|
-
throw new NagiRuntimeError(
|
|
3371
|
-
`Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
|
|
3372
|
-
);
|
|
3373
|
-
}
|
|
3374
|
-
return flow2;
|
|
3375
|
-
},
|
|
3376
|
-
requireForRun(flowId, runId, pinnedHash, currentHashOf) {
|
|
3377
|
-
const flow2 = byId.get(flowId);
|
|
3378
|
-
if (pinnedHash !== void 0) {
|
|
3379
|
-
const currentHash = flow2 === void 0 ? null : currentHashOf?.(flowId) ?? null;
|
|
3380
|
-
if (flow2 === void 0 || currentHash !== pinnedHash) {
|
|
3381
|
-
throw new NagiFlowSnapshotGoneError({
|
|
3382
|
-
runId,
|
|
3383
|
-
flowId,
|
|
3384
|
-
pinnedHash,
|
|
3385
|
-
currentHash
|
|
3386
|
-
});
|
|
3387
|
-
}
|
|
3388
|
-
return flow2;
|
|
3389
|
-
}
|
|
3390
|
-
if (!flow2) {
|
|
3391
|
-
throw new NagiRuntimeError(
|
|
3392
|
-
`Run ${runId} references flow "${flowId}" which is not registered with nagi().`
|
|
3393
|
-
);
|
|
3394
|
-
}
|
|
3395
|
-
return flow2;
|
|
3396
|
-
},
|
|
3397
|
-
isStreaming: (stepId) => streamingStepIds.has(stepId)
|
|
3398
|
-
};
|
|
3399
|
-
}
|
|
3400
|
-
|
|
3401
1831
|
// src/operator.ts
|
|
3402
1832
|
var ABORT_SETTLE_DEADLINE_MS = 3e4;
|
|
3403
1833
|
var ABORT_SETTLE_POLL_MS = 50;
|
|
@@ -3413,7 +1843,7 @@ function makeOperator(o) {
|
|
|
3413
1843
|
async function skip(runId, stepId, opts) {
|
|
3414
1844
|
requireActor("operator.skip", opts.actor);
|
|
3415
1845
|
const state = await store.loadRunState(runId);
|
|
3416
|
-
const flow2 = registry.
|
|
1846
|
+
const flow2 = registry.require(state.flowId);
|
|
3417
1847
|
if (!(stepId in flow2.steps)) {
|
|
3418
1848
|
throw validationError(
|
|
3419
1849
|
`operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
@@ -3470,7 +1900,7 @@ function makeOperator(o) {
|
|
|
3470
1900
|
`operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
|
|
3471
1901
|
);
|
|
3472
1902
|
}
|
|
3473
|
-
const flow2 = registry.
|
|
1903
|
+
const flow2 = registry.require(state.flowId);
|
|
3474
1904
|
if (!(stepId in flow2.steps)) {
|
|
3475
1905
|
throw validationError(
|
|
3476
1906
|
`operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
|
|
@@ -3523,118 +1953,271 @@ function makeOperator(o) {
|
|
|
3523
1953
|
return { skip, retry, abort };
|
|
3524
1954
|
}
|
|
3525
1955
|
|
|
3526
|
-
// src/replay
|
|
3527
|
-
function
|
|
3528
|
-
const
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
const
|
|
3532
|
-
|
|
1956
|
+
// src/replay.ts
|
|
1957
|
+
function makeReplay(deps) {
|
|
1958
|
+
const { registry, store, queue, clock } = deps;
|
|
1959
|
+
async function replay(runId, opts = { mode: "continue" }) {
|
|
1960
|
+
const runState = await store.loadRunState(runId);
|
|
1961
|
+
const resolution = registry.resolve(runState);
|
|
1962
|
+
const liveFlow = resolution.kind === "current" ? resolution.flow : resolution.live;
|
|
1963
|
+
if (liveFlow === void 0) {
|
|
3533
1964
|
throw new NagiRuntimeError(
|
|
3534
|
-
`
|
|
1965
|
+
`Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
|
|
3535
1966
|
);
|
|
3536
1967
|
}
|
|
3537
|
-
|
|
3538
|
-
|
|
3539
|
-
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
const
|
|
3544
|
-
|
|
3545
|
-
|
|
3546
|
-
|
|
3547
|
-
|
|
3548
|
-
if (
|
|
1968
|
+
if (runState.phase.tag === "canceled") {
|
|
1969
|
+
throw new NagiRuntimeError(
|
|
1970
|
+
`Run ${runId} was canceled (superseded by a newer run with the same concurrency key). Replay is not supported for canceled runs \u2014 start a new run instead.`
|
|
1971
|
+
);
|
|
1972
|
+
}
|
|
1973
|
+
if (opts.mode === "inspect") return;
|
|
1974
|
+
const fireHooks = opts.fireHooks !== false;
|
|
1975
|
+
const baseDeps = fireHooks ? deps : { ...deps, fireHooks: false };
|
|
1976
|
+
let replayDeps = baseDeps;
|
|
1977
|
+
let effectiveFlow = liveFlow;
|
|
1978
|
+
if (resolution.kind !== "current") {
|
|
1979
|
+
if (!opts.allowDrift) {
|
|
1980
|
+
throw new NagiSnapshotDriftError({
|
|
1981
|
+
runId,
|
|
1982
|
+
expected: resolution.error.pinnedHash,
|
|
1983
|
+
actual: registry.hashOf(liveFlow.id)
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
const synthesized = await registry.synthesize(resolution);
|
|
1987
|
+
replayDeps = {
|
|
1988
|
+
...baseDeps,
|
|
1989
|
+
resolveFlow: async () => ({ kind: "current", flow: synthesized })
|
|
1990
|
+
};
|
|
1991
|
+
effectiveFlow = synthesized;
|
|
1992
|
+
}
|
|
1993
|
+
if (opts.from !== void 0) {
|
|
1994
|
+
if (runState.phase.tag === "running") {
|
|
3549
1995
|
throw new NagiRuntimeError(
|
|
3550
|
-
`
|
|
1996
|
+
`Run ${runId} is still running \u2014 replay({ from }) would race in-flight workers. Wait for the run to settle (completed / failed) before resetting from a step.`
|
|
3551
1997
|
);
|
|
3552
1998
|
}
|
|
3553
|
-
|
|
1999
|
+
if (!(opts.from in effectiveFlow.steps)) {
|
|
2000
|
+
throw validationError(
|
|
2001
|
+
`replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
|
|
2002
|
+
["from"]
|
|
2003
|
+
);
|
|
2004
|
+
}
|
|
2005
|
+
const cascade = descendantsOf(effectiveFlow, opts.from);
|
|
2006
|
+
const at = clock.now();
|
|
2007
|
+
for (const stepId of cascade) {
|
|
2008
|
+
const fact = stepId === opts.from ? Facts.stepReset({ runId, stepId, at }) : Facts.stepReset({ runId, stepId, at, cascadedFrom: opts.from });
|
|
2009
|
+
await store.appendFact(runId, fact);
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
const replayDispatcher = makeDispatcher(replayDeps);
|
|
2013
|
+
await replayDispatcher.advance(runId);
|
|
2014
|
+
if (!fireHooks) await drainInline(replayDispatcher, queue);
|
|
2015
|
+
}
|
|
2016
|
+
return { replay };
|
|
2017
|
+
}
|
|
2018
|
+
var MAX_REPLAY_DISPATCHES = 4096;
|
|
2019
|
+
async function drainInline(dispatcher, queue) {
|
|
2020
|
+
for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
|
|
2021
|
+
const messages = await queue.dequeue({ count: 1 });
|
|
2022
|
+
if (messages.length === 0) return;
|
|
2023
|
+
for (const msg of messages) {
|
|
2024
|
+
const result = await dispatcher.dispatchMessage(msg);
|
|
2025
|
+
if (result.kind === "snapshot-gone") throw result.error;
|
|
3554
2026
|
}
|
|
3555
|
-
setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
|
|
3556
2027
|
}
|
|
3557
|
-
return {
|
|
3558
|
-
id: liveFlow.id,
|
|
3559
|
-
input: liveFlow.input,
|
|
3560
|
-
steps: synthesized,
|
|
3561
|
-
...compact({ output: liveFlow.output })
|
|
3562
|
-
};
|
|
3563
2028
|
}
|
|
3564
2029
|
|
|
3565
|
-
// src/
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
|
|
2030
|
+
// src/run-lifecycle.ts
|
|
2031
|
+
var EXISTS = { kind: "exists" };
|
|
2032
|
+
var ADVANCE = { kind: "advance" };
|
|
2033
|
+
function makeRunLifecycle(deps) {
|
|
2034
|
+
const { store, queue, clock, registry, hooks, flowHooks, dispatcher } = deps;
|
|
2035
|
+
function resolveBoundary(boundary) {
|
|
2036
|
+
switch (boundary.kind) {
|
|
2037
|
+
case "own":
|
|
2038
|
+
return {
|
|
2039
|
+
tryStart: (runId, fact, concurrency) => store.tryStartRun(runId, fact, concurrency),
|
|
2040
|
+
seed: async (_runId, _flowId, t) => t.skip.length > 0 ? ADVANCE : { kind: "enqueue", steps: t.runnable }
|
|
2041
|
+
};
|
|
2042
|
+
case "caller":
|
|
2043
|
+
return {
|
|
2044
|
+
tryStart: (runId, fact, concurrency) => store.tryStartRunOnTx(boundary.tx, runId, fact, concurrency),
|
|
2045
|
+
seed: async (runId, flowId, t) => {
|
|
2046
|
+
const txQueue = deps.queueForTx(boundary.tx);
|
|
2047
|
+
for (const stepId of t.runnable) {
|
|
2048
|
+
await txQueue.enqueue(runId, stepId, { flowId });
|
|
2049
|
+
}
|
|
2050
|
+
return { kind: "enqueued", steps: t.runnable, skip: t.skip };
|
|
2051
|
+
}
|
|
2052
|
+
};
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
async function stage(args) {
|
|
2056
|
+
const { flow: flow2, validatedInput, runId, parent } = args;
|
|
2057
|
+
const { tryStart, seed } = resolveBoundary(args.boundary);
|
|
2058
|
+
const startedAt = clock.now();
|
|
2059
|
+
const fact = Facts.flowStarted({
|
|
2060
|
+
runId,
|
|
2061
|
+
flowId: flow2.id,
|
|
2062
|
+
input: validatedInput,
|
|
2063
|
+
at: startedAt,
|
|
2064
|
+
codeVersion: deps.codeVersion,
|
|
2065
|
+
flowHash: registry.hashOf(flow2.id),
|
|
2066
|
+
...compact({
|
|
2067
|
+
parent: parent !== void 0 ? { runId: parent.runId, stepId: parent.stepId } : void 0
|
|
2068
|
+
})
|
|
2069
|
+
});
|
|
2070
|
+
const concurrency = concurrencyOf(flow2, validatedInput);
|
|
2071
|
+
const { started, canceled } = await tryStart(runId, fact, concurrency);
|
|
2072
|
+
if (!started) return EXISTS;
|
|
2073
|
+
const t = nextTransition(flow2, foldRun(runId, [fact]));
|
|
2074
|
+
const dispatch = t.kind === "dispatch" ? await seed(runId, flow2.id, t) : ADVANCE;
|
|
2075
|
+
return {
|
|
2076
|
+
kind: "started",
|
|
2077
|
+
effects: {
|
|
2078
|
+
superseded: canceled.map((c) => supersededEvent(flow2.id, runId, c)),
|
|
2079
|
+
started: {
|
|
2080
|
+
runId,
|
|
2081
|
+
flowId: flow2.id,
|
|
2082
|
+
input: validatedInput,
|
|
2083
|
+
at: startedAt,
|
|
2084
|
+
...compact({ parent })
|
|
2085
|
+
},
|
|
2086
|
+
dispatch
|
|
2087
|
+
}
|
|
2088
|
+
};
|
|
2089
|
+
}
|
|
2090
|
+
async function applyEffects(effects) {
|
|
2091
|
+
const { superseded, started, dispatch } = effects;
|
|
2092
|
+
const flow2 = registry.require(started.flowId);
|
|
2093
|
+
for (const event of superseded) {
|
|
2094
|
+
await hooks.fireHook(flow2.onError, event, "flow.onError");
|
|
2095
|
+
await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
|
|
2096
|
+
await dispatcher.propagateToParent(event.runId, {
|
|
2097
|
+
kind: "canceled",
|
|
2098
|
+
error: event.error
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
await hooks.fireHook(flow2.onStart, started, "flow.onStart");
|
|
2102
|
+
await hooks.fireHook(flowHooks?.onFlowStart, started, "onFlowStart");
|
|
2103
|
+
switch (dispatch.kind) {
|
|
2104
|
+
case "enqueue":
|
|
2105
|
+
for (const stepId of dispatch.steps) {
|
|
2106
|
+
await queue.enqueue(started.runId, stepId, { flowId: flow2.id });
|
|
2107
|
+
}
|
|
2108
|
+
return;
|
|
2109
|
+
case "enqueued":
|
|
2110
|
+
await recordSkips(started.runId, dispatch.skip);
|
|
2111
|
+
return;
|
|
2112
|
+
case "advance":
|
|
2113
|
+
await dispatcher.advance(started.runId);
|
|
2114
|
+
return;
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
async function recordSkips(runId, skip) {
|
|
2118
|
+
if (skip.length === 0) return;
|
|
2119
|
+
const state = await store.loadRunState(runId);
|
|
2120
|
+
for (const { stepId, reason } of skip) {
|
|
2121
|
+
if (stepStateOf(state, stepId).tag !== "pending") continue;
|
|
2122
|
+
await store.appendFact(
|
|
2123
|
+
runId,
|
|
2124
|
+
Facts.stepSkipped({ runId, stepId, reason, at: clock.now() })
|
|
2125
|
+
);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
async function start(args) {
|
|
2129
|
+
const flow2 = registry.require(args.flowId);
|
|
2130
|
+
const runId = resolveRunId(args.runId);
|
|
2131
|
+
const validatedInput = await validate(flow2.input, args.input);
|
|
2132
|
+
const staged = await stage({
|
|
2133
|
+
flow: flow2,
|
|
2134
|
+
validatedInput,
|
|
2135
|
+
runId,
|
|
2136
|
+
parent: void 0,
|
|
2137
|
+
boundary: args.boundary
|
|
2138
|
+
});
|
|
2139
|
+
return { runId, staged };
|
|
2140
|
+
}
|
|
2141
|
+
async function startChildRun(args) {
|
|
2142
|
+
const { child, childInput, parent, generation } = args;
|
|
2143
|
+
if (!registry.has(child.id)) {
|
|
3572
2144
|
throw new NagiRuntimeError(
|
|
3573
|
-
`
|
|
2145
|
+
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
3574
2146
|
);
|
|
3575
2147
|
}
|
|
3576
|
-
|
|
3577
|
-
const
|
|
3578
|
-
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
|
|
3582
|
-
|
|
3583
|
-
|
|
3584
|
-
|
|
3585
|
-
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
|
|
3601
|
-
);
|
|
3602
|
-
replayDeps = { ...baseDeps, flowFor: async () => synthesized };
|
|
3603
|
-
effectiveFlow = synthesized;
|
|
3604
|
-
}
|
|
2148
|
+
const validatedInput = await validate(child.input, childInput);
|
|
2149
|
+
const runId = await deriveChildRunId({
|
|
2150
|
+
runId: parent.runId,
|
|
2151
|
+
stepId: parent.stepId,
|
|
2152
|
+
generation
|
|
2153
|
+
});
|
|
2154
|
+
const staged = await stage({
|
|
2155
|
+
flow: child,
|
|
2156
|
+
validatedInput,
|
|
2157
|
+
runId,
|
|
2158
|
+
parent,
|
|
2159
|
+
boundary: { kind: "own" }
|
|
2160
|
+
});
|
|
2161
|
+
if (staged.kind === "started") await applyEffects(staged.effects);
|
|
2162
|
+
return runId;
|
|
2163
|
+
}
|
|
2164
|
+
async function cancelRunRecursive(runId, args) {
|
|
2165
|
+
const state = await store.loadRunState(runId);
|
|
2166
|
+
if (isTerminalRun(state)) {
|
|
2167
|
+
deps.emitLog({
|
|
2168
|
+
level: "info",
|
|
2169
|
+
msg: "nagi: cancel skipped \u2014 run already terminal",
|
|
2170
|
+
attrs: { runId, status: runStatusOf(state) }
|
|
2171
|
+
});
|
|
2172
|
+
return;
|
|
3605
2173
|
}
|
|
3606
|
-
|
|
3607
|
-
|
|
3608
|
-
|
|
3609
|
-
|
|
3610
|
-
|
|
3611
|
-
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
|
|
3615
|
-
|
|
3616
|
-
);
|
|
3617
|
-
}
|
|
3618
|
-
const cascade = descendantsOf(effectiveFlow, opts.from);
|
|
3619
|
-
const at = clock.now();
|
|
3620
|
-
for (const stepId of cascade) {
|
|
3621
|
-
const fact = stepId === opts.from ? Facts.stepReset({ runId, stepId, at }) : Facts.stepReset({ runId, stepId, at, cascadedFrom: opts.from });
|
|
3622
|
-
await store.appendFact(runId, fact);
|
|
3623
|
-
}
|
|
2174
|
+
const flow2 = registry.get(state.flowId);
|
|
2175
|
+
await store.appendFact(runId, Facts.flowCanceled(runId, args, clock.now()));
|
|
2176
|
+
const error = {
|
|
2177
|
+
name: "NagiCanceledError",
|
|
2178
|
+
message: `Run ${runId} was canceled: ${args.reason}`
|
|
2179
|
+
};
|
|
2180
|
+
if (flow2 !== void 0) {
|
|
2181
|
+
const event = { runId, flowId: flow2.id, error, at: clock.now() };
|
|
2182
|
+
await hooks.fireHook(flow2.onError, event, "flow.onError");
|
|
2183
|
+
await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
|
|
3624
2184
|
}
|
|
3625
|
-
const
|
|
3626
|
-
|
|
3627
|
-
|
|
2185
|
+
for (const childId of await store.listChildren(runId)) {
|
|
2186
|
+
await cancelRunRecursive(childId, {
|
|
2187
|
+
cause: "explicit",
|
|
2188
|
+
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
2189
|
+
note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
2190
|
+
});
|
|
2191
|
+
}
|
|
2192
|
+
await dispatcher.propagateToParent(runId, { kind: "canceled", error });
|
|
3628
2193
|
}
|
|
3629
|
-
return {
|
|
2194
|
+
return { start, stage, applyEffects, startChildRun, cancelRunRecursive };
|
|
3630
2195
|
}
|
|
3631
|
-
|
|
3632
|
-
|
|
3633
|
-
|
|
3634
|
-
|
|
3635
|
-
if (messages.length === 0) return;
|
|
3636
|
-
for (const msg of messages) await dispatcher.dispatchMessage(msg);
|
|
2196
|
+
function resolveRunId(runId) {
|
|
2197
|
+
if (runId === void 0) return `run-${crypto.randomUUID()}`;
|
|
2198
|
+
if (typeof runId !== "string" || runId.length === 0) {
|
|
2199
|
+
throw validationError("opts.runId must be a non-empty string", ["runId"]);
|
|
3637
2200
|
}
|
|
2201
|
+
return runId;
|
|
2202
|
+
}
|
|
2203
|
+
function concurrencyOf(flow2, input) {
|
|
2204
|
+
if (flow2.concurrency === void 0) return void 0;
|
|
2205
|
+
const key = flow2.concurrency.keyFn(input);
|
|
2206
|
+
if (typeof key !== "string" || key.length === 0) {
|
|
2207
|
+
throw validationError(
|
|
2208
|
+
`flow.concurrency.keyFn must return a non-empty string (got ${typeof key === "string" ? '""' : typeof key})`,
|
|
2209
|
+
["concurrency", "keyFn"]
|
|
2210
|
+
);
|
|
2211
|
+
}
|
|
2212
|
+
return { key, mode: flow2.concurrency.mode };
|
|
2213
|
+
}
|
|
2214
|
+
function supersededEvent(flowId, canceledByRunId, c) {
|
|
2215
|
+
const cause = { canceledByRunId, concurrencyKey: c.fact.concurrencyKey };
|
|
2216
|
+
const error = {
|
|
2217
|
+
...serializeError(new NagiCanceledError({ runId: c.runId, ...cause })),
|
|
2218
|
+
cause
|
|
2219
|
+
};
|
|
2220
|
+
return { runId: c.runId, flowId, error, at: c.fact.at };
|
|
3638
2221
|
}
|
|
3639
2222
|
|
|
3640
2223
|
// src/worker.ts
|
|
@@ -3642,15 +2225,6 @@ var DEFAULT_CONCURRENCY = 4;
|
|
|
3642
2225
|
var DEFAULT_POLL_INTERVAL_MS = 1e3;
|
|
3643
2226
|
var DEFAULT_TIMER_SWEEP_INTERVAL_MS = 3e4;
|
|
3644
2227
|
var SNAPSHOT_GONE_FALLBACK_NACK_DELAY_MS = 3e4;
|
|
3645
|
-
var MAX_DEQUEUE_BACKOFF_MS = 3e4;
|
|
3646
|
-
var MIN_DEQUEUE_BACKOFF_MS = 50;
|
|
3647
|
-
var defaultSnapshotGonePolicy = (readCount) => {
|
|
3648
|
-
if (readCount > 60) return { action: "fail" };
|
|
3649
|
-
return {
|
|
3650
|
-
action: "retry",
|
|
3651
|
-
delayMs: Math.min(readCount * readCount * 1e3, 3e5)
|
|
3652
|
-
};
|
|
3653
|
-
};
|
|
3654
2228
|
function makeWorker(deps, config) {
|
|
3655
2229
|
return new WorkerImpl(deps, config);
|
|
3656
2230
|
}
|
|
@@ -3659,6 +2233,7 @@ var WorkerImpl = class {
|
|
|
3659
2233
|
this.deps = deps;
|
|
3660
2234
|
this.concurrency = Math.max(1, config?.concurrency ?? DEFAULT_CONCURRENCY);
|
|
3661
2235
|
this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
2236
|
+
this.dequeueBackoffMs = dequeueBackoff(this.pollIntervalMs);
|
|
3662
2237
|
this.signal = config?.signal;
|
|
3663
2238
|
this.dispatcher = makeDispatcher(deps);
|
|
3664
2239
|
this.snapshotGonePolicy = config?.snapshotGonePolicy ?? defaultSnapshotGonePolicy;
|
|
@@ -3670,6 +2245,7 @@ var WorkerImpl = class {
|
|
|
3670
2245
|
inFlight = 0;
|
|
3671
2246
|
concurrency;
|
|
3672
2247
|
pollIntervalMs;
|
|
2248
|
+
dequeueBackoffMs;
|
|
3673
2249
|
signal;
|
|
3674
2250
|
dispatcher;
|
|
3675
2251
|
timerSweepIntervalMs;
|
|
@@ -3758,7 +2334,7 @@ var WorkerImpl = class {
|
|
|
3758
2334
|
async runUntilEmpty(opts) {
|
|
3759
2335
|
const deadline = opts?.deadline;
|
|
3760
2336
|
return this.pump({
|
|
3761
|
-
shouldContinue: () => deadline === void 0 ||
|
|
2337
|
+
shouldContinue: () => deadline === void 0 || this.deps.clock.now().getTime() < deadline,
|
|
3762
2338
|
batchSize: () => this.concurrency
|
|
3763
2339
|
});
|
|
3764
2340
|
}
|
|
@@ -3794,18 +2370,6 @@ var WorkerImpl = class {
|
|
|
3794
2370
|
async dequeue(count) {
|
|
3795
2371
|
return this.deps.queue.dequeue({ count: Math.max(1, count) });
|
|
3796
2372
|
}
|
|
3797
|
-
// Exponential, capped, reset on the first success: a one-off blip costs one
|
|
3798
|
-
// poll interval, a real outage settles to a 30s cadence instead of hammering
|
|
3799
|
-
// a down database and flooding logs. Anchored on pollIntervalMs (default 1s,
|
|
3800
|
-
// so the default curve is 1s -> 30s) and floored so a 0/near-0 poll interval
|
|
3801
|
-
// cannot turn a persistent failure into a tight loop.
|
|
3802
|
-
dequeueBackoffMs(consecutiveFailures) {
|
|
3803
|
-
const base = Math.max(this.pollIntervalMs, MIN_DEQUEUE_BACKOFF_MS);
|
|
3804
|
-
return Math.min(
|
|
3805
|
-
base * 2 ** (consecutiveFailures - 1),
|
|
3806
|
-
MAX_DEQUEUE_BACKOFF_MS
|
|
3807
|
-
);
|
|
3808
|
-
}
|
|
3809
2373
|
fire(msg) {
|
|
3810
2374
|
this.inFlight++;
|
|
3811
2375
|
const release = this.trackFlow(msg);
|
|
@@ -3815,17 +2379,32 @@ var WorkerImpl = class {
|
|
|
3815
2379
|
});
|
|
3816
2380
|
}
|
|
3817
2381
|
async dispatchSafely(msg) {
|
|
2382
|
+
let result;
|
|
3818
2383
|
try {
|
|
3819
|
-
await this.dispatcher.dispatchMessage(msg);
|
|
2384
|
+
result = await this.dispatcher.dispatchMessage(msg);
|
|
3820
2385
|
} catch (err) {
|
|
3821
|
-
|
|
2386
|
+
this.deps.emitLog({
|
|
2387
|
+
level: "error",
|
|
2388
|
+
msg: "worker.dispatch threw uncaught",
|
|
2389
|
+
attrs: { error: String(err) }
|
|
2390
|
+
});
|
|
2391
|
+
try {
|
|
2392
|
+
await this.deps.queue.nack(msg.receipt);
|
|
2393
|
+
} catch {
|
|
2394
|
+
}
|
|
2395
|
+
return;
|
|
2396
|
+
}
|
|
2397
|
+
switch (result.kind) {
|
|
2398
|
+
case "done":
|
|
2399
|
+
return;
|
|
2400
|
+
case "snapshot-gone":
|
|
3822
2401
|
try {
|
|
3823
|
-
await this.handleSnapshotGone(msg,
|
|
2402
|
+
await this.handleSnapshotGone(msg, result.error);
|
|
3824
2403
|
} catch (handleErr) {
|
|
3825
2404
|
this.deps.emitLog({
|
|
3826
2405
|
level: "error",
|
|
3827
2406
|
msg: "worker.dispatch: snapshot-gone handling failed",
|
|
3828
|
-
attrs: { runId:
|
|
2407
|
+
attrs: { runId: result.error.runId, error: String(handleErr) }
|
|
3829
2408
|
});
|
|
3830
2409
|
try {
|
|
3831
2410
|
await this.deps.queue.nack(msg.receipt, {
|
|
@@ -3835,23 +2414,12 @@ var WorkerImpl = class {
|
|
|
3835
2414
|
}
|
|
3836
2415
|
}
|
|
3837
2416
|
return;
|
|
3838
|
-
}
|
|
3839
|
-
this.deps.emitLog({
|
|
3840
|
-
level: "error",
|
|
3841
|
-
msg: "worker.dispatch threw uncaught",
|
|
3842
|
-
attrs: { error: String(err) }
|
|
3843
|
-
});
|
|
3844
|
-
try {
|
|
3845
|
-
await this.deps.queue.nack(msg.receipt);
|
|
3846
|
-
} catch {
|
|
3847
|
-
}
|
|
3848
2417
|
}
|
|
3849
2418
|
}
|
|
3850
2419
|
// A snapshot-gone message is retried (nack, delayed) only while the policy
|
|
3851
2420
|
// says a frozen-version worker might still claim it; past that budget the
|
|
3852
2421
|
// run is terminally failed with the snapshot-gone error and the message
|
|
3853
2422
|
// acked, so poison messages cannot outlive the deploy that orphaned them.
|
|
3854
|
-
// (Terminal runs never reach here — dispatchMessage acks them itself.)
|
|
3855
2423
|
async handleSnapshotGone(msg, err) {
|
|
3856
2424
|
const attrs = {
|
|
3857
2425
|
runId: err.runId,
|
|
@@ -3940,202 +2508,33 @@ async function nagiImpl(config) {
|
|
|
3940
2508
|
const clock = config.clock ?? new InMemoryClock();
|
|
3941
2509
|
const emitLog = makeEmit(config.onLog);
|
|
3942
2510
|
await config.queue.ensureSchema?.();
|
|
3943
|
-
const
|
|
3944
|
-
const streamTransport = config.streamTransport ?? asStreamTransport(config.store);
|
|
2511
|
+
const streamTransport = config.store.stream;
|
|
3945
2512
|
if (streamTransport === void 0) {
|
|
3946
|
-
for (const f of
|
|
2513
|
+
for (const f of config.flows) {
|
|
3947
2514
|
for (const [stepId, step] of Object.entries(asStepMapWithDefs(f.steps))) {
|
|
3948
2515
|
if (getDef(step).kind !== "streaming") continue;
|
|
3949
2516
|
throw new NagiRuntimeError(
|
|
3950
|
-
`Flow "${f.id}" has a streaming step "${stepId}" (b.streamingTask), but no
|
|
2517
|
+
`Flow "${f.id}" has a streaming step "${stepId}" (b.streamingTask), but the store has no \`stream\` transport \u2014 it cannot carry ephemeral chunks. Use a store that exposes \`stream\` (e.g. the in-memory store) or remove the streaming step.`
|
|
3951
2518
|
);
|
|
3952
2519
|
}
|
|
3953
2520
|
}
|
|
3954
2521
|
}
|
|
3955
|
-
const
|
|
3956
|
-
|
|
3957
|
-
|
|
3958
|
-
|
|
3959
|
-
|
|
3960
|
-
await config.store.upsertSnapshot({
|
|
3961
|
-
flowHash,
|
|
3962
|
-
flowId: f.id,
|
|
3963
|
-
dag
|
|
3964
|
-
});
|
|
3965
|
-
const previousHash = await config.store.getRef(f.id);
|
|
3966
|
-
if (previousHash !== flowHash) {
|
|
3967
|
-
await config.store.setRef(f.id, flowHash);
|
|
3968
|
-
await config.store.appendGlobalFact(
|
|
3969
|
-
Facts.flowRefUpdated({
|
|
3970
|
-
flowId: f.id,
|
|
3971
|
-
from: previousHash,
|
|
3972
|
-
to: flowHash,
|
|
3973
|
-
at: clock.now()
|
|
3974
|
-
})
|
|
3975
|
-
);
|
|
3976
|
-
}
|
|
3977
|
-
}
|
|
2522
|
+
const registry = await registerFlows({
|
|
2523
|
+
flows: config.flows,
|
|
2524
|
+
store: config.store,
|
|
2525
|
+
clock
|
|
2526
|
+
});
|
|
3978
2527
|
const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
|
|
3979
|
-
async function
|
|
3980
|
-
|
|
3981
|
-
return registry.requireForRun(
|
|
3982
|
-
runState.flowId,
|
|
3983
|
-
runId,
|
|
3984
|
-
runState.flowHash,
|
|
3985
|
-
(id) => flowHashById.get(id)
|
|
3986
|
-
);
|
|
2528
|
+
async function resolveFlow(runId) {
|
|
2529
|
+
return registry.resolve(await config.store.loadRunState(runId));
|
|
3987
2530
|
}
|
|
3988
2531
|
function lookupFlow(flowId) {
|
|
3989
2532
|
return registry.get(flowId);
|
|
3990
2533
|
}
|
|
3991
|
-
async function startRunInternal({
|
|
3992
|
-
flow: flow2,
|
|
3993
|
-
validatedInput,
|
|
3994
|
-
runId,
|
|
3995
|
-
parent
|
|
3996
|
-
}) {
|
|
3997
|
-
const startedAt = clock.now();
|
|
3998
|
-
const flowHash = flowHashById.get(flow2.id);
|
|
3999
|
-
const fact = Facts.flowStarted({
|
|
4000
|
-
runId,
|
|
4001
|
-
flowId: flow2.id,
|
|
4002
|
-
input: validatedInput,
|
|
4003
|
-
at: startedAt,
|
|
4004
|
-
codeVersion,
|
|
4005
|
-
...compact({
|
|
4006
|
-
flowHash,
|
|
4007
|
-
parent: parent !== void 0 ? { runId: parent.runId, stepId: parent.stepId } : void 0
|
|
4008
|
-
})
|
|
4009
|
-
});
|
|
4010
|
-
let concurrencyArg;
|
|
4011
|
-
if (flow2.concurrency !== void 0) {
|
|
4012
|
-
const derived = flow2.concurrency.keyFn(validatedInput);
|
|
4013
|
-
if (typeof derived !== "string" || derived.length === 0) {
|
|
4014
|
-
throw validationError(
|
|
4015
|
-
`flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
4016
|
-
["concurrency", "keyFn"]
|
|
4017
|
-
);
|
|
4018
|
-
}
|
|
4019
|
-
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
4020
|
-
}
|
|
4021
|
-
const { started, canceled } = await config.store.tryStartRun(
|
|
4022
|
-
runId,
|
|
4023
|
-
fact,
|
|
4024
|
-
concurrencyArg
|
|
4025
|
-
);
|
|
4026
|
-
if (!started) return { started: false };
|
|
4027
|
-
for (const c of canceled) {
|
|
4028
|
-
const cancelError = new NagiCanceledError({
|
|
4029
|
-
runId: c.runId,
|
|
4030
|
-
canceledByRunId: runId,
|
|
4031
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
4032
|
-
});
|
|
4033
|
-
const serialized = {
|
|
4034
|
-
...serializeError(cancelError),
|
|
4035
|
-
cause: {
|
|
4036
|
-
canceledByRunId: runId,
|
|
4037
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
4038
|
-
}
|
|
4039
|
-
};
|
|
4040
|
-
const errorEvent = {
|
|
4041
|
-
runId: c.runId,
|
|
4042
|
-
flowId: flow2.id,
|
|
4043
|
-
error: serialized,
|
|
4044
|
-
at: c.fact.at
|
|
4045
|
-
};
|
|
4046
|
-
await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
|
|
4047
|
-
await hooks.fireHook(
|
|
4048
|
-
config.hooks?.onFlowError,
|
|
4049
|
-
errorEvent,
|
|
4050
|
-
"onFlowError"
|
|
4051
|
-
);
|
|
4052
|
-
await dispatcher.propagateToParent(c.runId, {
|
|
4053
|
-
kind: "canceled",
|
|
4054
|
-
error: serialized
|
|
4055
|
-
});
|
|
4056
|
-
}
|
|
4057
|
-
const startEvent = parent !== void 0 ? {
|
|
4058
|
-
runId,
|
|
4059
|
-
flowId: flow2.id,
|
|
4060
|
-
input: validatedInput,
|
|
4061
|
-
at: startedAt,
|
|
4062
|
-
parent
|
|
4063
|
-
} : {
|
|
4064
|
-
runId,
|
|
4065
|
-
flowId: flow2.id,
|
|
4066
|
-
input: validatedInput,
|
|
4067
|
-
at: startedAt
|
|
4068
|
-
};
|
|
4069
|
-
await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
|
|
4070
|
-
await hooks.fireHook(config.hooks?.onFlowStart, startEvent, "onFlowStart");
|
|
4071
|
-
await dispatcher.advance(runId);
|
|
4072
|
-
return { started: true };
|
|
4073
|
-
}
|
|
4074
|
-
async function startChildRun(args) {
|
|
4075
|
-
const { child, childInput, parent, generation } = args;
|
|
4076
|
-
if (!registry.has(child.id)) {
|
|
4077
|
-
throw new NagiRuntimeError(
|
|
4078
|
-
`Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
|
|
4079
|
-
);
|
|
4080
|
-
}
|
|
4081
|
-
const validated = await validate(child.input, childInput);
|
|
4082
|
-
const childRunId = await deriveChildRunId({
|
|
4083
|
-
runId: parent.runId,
|
|
4084
|
-
stepId: parent.stepId,
|
|
4085
|
-
generation
|
|
4086
|
-
});
|
|
4087
|
-
await startRunInternal({
|
|
4088
|
-
flow: child,
|
|
4089
|
-
validatedInput: validated,
|
|
4090
|
-
runId: childRunId,
|
|
4091
|
-
parent
|
|
4092
|
-
});
|
|
4093
|
-
return childRunId;
|
|
4094
|
-
}
|
|
4095
|
-
async function cancelRunRecursive(runId, args) {
|
|
4096
|
-
const state = await config.store.loadRunState(runId);
|
|
4097
|
-
if (isTerminalRun(state)) {
|
|
4098
|
-
emitLog({
|
|
4099
|
-
level: "info",
|
|
4100
|
-
msg: "nagi: cancel skipped \u2014 run already terminal",
|
|
4101
|
-
attrs: { runId, status: runStatusOf(state) }
|
|
4102
|
-
});
|
|
4103
|
-
return;
|
|
4104
|
-
}
|
|
4105
|
-
const flow2 = registry.get(state.flowId);
|
|
4106
|
-
const canceledFact = Facts.flowCanceled(runId, args, clock.now());
|
|
4107
|
-
await config.store.appendFact(runId, canceledFact);
|
|
4108
|
-
const cancelError = {
|
|
4109
|
-
name: "NagiCanceledError",
|
|
4110
|
-
message: `Run ${runId} was canceled: ${args.reason}`
|
|
4111
|
-
};
|
|
4112
|
-
if (flow2 !== void 0) {
|
|
4113
|
-
const event = {
|
|
4114
|
-
runId,
|
|
4115
|
-
flowId: flow2.id,
|
|
4116
|
-
error: cancelError,
|
|
4117
|
-
at: clock.now()
|
|
4118
|
-
};
|
|
4119
|
-
await hooks.fireHook(flow2.onError, event, "flow.onError");
|
|
4120
|
-
await hooks.fireHook(config.hooks?.onFlowError, event, "onFlowError");
|
|
4121
|
-
}
|
|
4122
|
-
const children = await config.store.listChildren(runId);
|
|
4123
|
-
for (const childId of children) {
|
|
4124
|
-
await cancelRunRecursive(childId, {
|
|
4125
|
-
cause: "explicit",
|
|
4126
|
-
reason: `parent ${runId} canceled: ${args.reason}`,
|
|
4127
|
-
note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
|
|
4128
|
-
});
|
|
4129
|
-
}
|
|
4130
|
-
await dispatcher.propagateToParent(runId, {
|
|
4131
|
-
kind: "canceled",
|
|
4132
|
-
error: cancelError
|
|
4133
|
-
});
|
|
4134
|
-
}
|
|
4135
2534
|
const dispatchDeps = {
|
|
4136
|
-
|
|
2535
|
+
resolveFlow,
|
|
4137
2536
|
lookupFlow,
|
|
4138
|
-
startChildRun,
|
|
2537
|
+
startChildRun: (args) => lifecycle.startChildRun(args),
|
|
4139
2538
|
store: config.store,
|
|
4140
2539
|
queue: config.queue,
|
|
4141
2540
|
clock,
|
|
@@ -4155,6 +2554,18 @@ async function nagiImpl(config) {
|
|
|
4155
2554
|
};
|
|
4156
2555
|
const dispatcher = makeDispatcher(dispatchDeps);
|
|
4157
2556
|
const hooks = makeHooks(dispatchDeps);
|
|
2557
|
+
const lifecycle = makeRunLifecycle({
|
|
2558
|
+
store: config.store,
|
|
2559
|
+
queue: config.queue,
|
|
2560
|
+
clock,
|
|
2561
|
+
registry,
|
|
2562
|
+
codeVersion,
|
|
2563
|
+
queueForTx: (tx) => config.queue.withTx?.(tx) ?? config.queue,
|
|
2564
|
+
hooks,
|
|
2565
|
+
flowHooks: config.hooks,
|
|
2566
|
+
dispatcher,
|
|
2567
|
+
emitLog
|
|
2568
|
+
});
|
|
4158
2569
|
const signals = makeSignals({
|
|
4159
2570
|
dispatcher,
|
|
4160
2571
|
store: config.store,
|
|
@@ -4164,30 +2575,20 @@ async function nagiImpl(config) {
|
|
|
4164
2575
|
emitLog,
|
|
4165
2576
|
...compact({ flowHooks: config.hooks })
|
|
4166
2577
|
});
|
|
4167
|
-
const replayer = makeReplay({
|
|
4168
|
-
...dispatchDeps,
|
|
4169
|
-
registry,
|
|
4170
|
-
hashFor: (id) => flowHashById.get(id)
|
|
4171
|
-
});
|
|
2578
|
+
const replayer = makeReplay({ ...dispatchDeps, registry });
|
|
4172
2579
|
const wf = {
|
|
4173
2580
|
async start(flow2, input, opts) {
|
|
4174
2581
|
return wf.startById(flow2.id, input, opts);
|
|
4175
2582
|
},
|
|
4176
2583
|
async startById(flowId, input, opts) {
|
|
4177
|
-
const
|
|
4178
|
-
|
|
4179
|
-
|
|
4180
|
-
|
|
4181
|
-
|
|
4182
|
-
|
|
4183
|
-
|
|
4184
|
-
|
|
4185
|
-
runId = opts.runId;
|
|
4186
|
-
} else {
|
|
4187
|
-
runId = mintRunId();
|
|
4188
|
-
}
|
|
4189
|
-
const validated = await validate(flow2.input, input);
|
|
4190
|
-
await startRunInternal({ flow: flow2, validatedInput: validated, runId });
|
|
2584
|
+
const { runId, staged } = await lifecycle.start({
|
|
2585
|
+
flowId,
|
|
2586
|
+
input,
|
|
2587
|
+
runId: opts?.runId,
|
|
2588
|
+
boundary: { kind: "own" }
|
|
2589
|
+
});
|
|
2590
|
+
if (staged.kind === "started")
|
|
2591
|
+
await lifecycle.applyEffects(staged.effects);
|
|
4191
2592
|
return runId;
|
|
4192
2593
|
},
|
|
4193
2594
|
async startStaged(flow2, input, opts) {
|
|
@@ -4200,114 +2601,26 @@ async function nagiImpl(config) {
|
|
|
4200
2601
|
["tx"]
|
|
4201
2602
|
);
|
|
4202
2603
|
}
|
|
4203
|
-
const
|
|
4204
|
-
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4208
|
-
"runId"
|
|
4209
|
-
]);
|
|
4210
|
-
}
|
|
4211
|
-
runId = opts.runId;
|
|
4212
|
-
} else {
|
|
4213
|
-
runId = mintRunId();
|
|
4214
|
-
}
|
|
4215
|
-
const validated = await validate(flow2.input, input);
|
|
4216
|
-
const startedAt = clock.now();
|
|
4217
|
-
const flowHash = flowHashById.get(flow2.id);
|
|
4218
|
-
const fact = Facts.flowStarted({
|
|
4219
|
-
runId,
|
|
4220
|
-
flowId: flow2.id,
|
|
4221
|
-
input: validated,
|
|
4222
|
-
at: startedAt,
|
|
4223
|
-
codeVersion,
|
|
4224
|
-
...compact({ flowHash })
|
|
2604
|
+
const { runId, staged } = await lifecycle.start({
|
|
2605
|
+
flowId,
|
|
2606
|
+
input,
|
|
2607
|
+
runId: opts.runId,
|
|
2608
|
+
boundary: { kind: "caller", tx: opts.tx }
|
|
4225
2609
|
});
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
const derived = flow2.concurrency.keyFn(validated);
|
|
4229
|
-
if (typeof derived !== "string" || derived.length === 0) {
|
|
4230
|
-
throw validationError(
|
|
4231
|
-
`flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
|
|
4232
|
-
["concurrency", "keyFn"]
|
|
4233
|
-
);
|
|
4234
|
-
}
|
|
4235
|
-
concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
|
|
4236
|
-
}
|
|
4237
|
-
const { started, canceled } = await config.store.tryStartRunOnTx(
|
|
4238
|
-
opts.tx,
|
|
4239
|
-
runId,
|
|
4240
|
-
fact,
|
|
4241
|
-
concurrencyArg
|
|
4242
|
-
);
|
|
4243
|
-
if (started) {
|
|
4244
|
-
const seedState = foldRun(runId, [fact]);
|
|
4245
|
-
const transition = nextTransition(flow2, seedState);
|
|
4246
|
-
if (transition.kind === "dispatch") {
|
|
4247
|
-
const txQueue = bindQueueToTx(config.queue, opts.tx);
|
|
4248
|
-
for (const stepId of transition.runnable) {
|
|
4249
|
-
await txQueue.enqueue(runId, stepId, { flowId: flow2.id });
|
|
4250
|
-
}
|
|
4251
|
-
}
|
|
2610
|
+
if (staged.kind === "exists") {
|
|
2611
|
+
return { runId, started: false, canceled: [], applyOnCommit: noop };
|
|
4252
2612
|
}
|
|
4253
|
-
let
|
|
4254
|
-
const applyOnCommit = async () => {
|
|
4255
|
-
if (fired) return;
|
|
4256
|
-
fired = true;
|
|
4257
|
-
if (!started) return;
|
|
4258
|
-
for (const c of canceled) {
|
|
4259
|
-
const cancelError = new NagiCanceledError({
|
|
4260
|
-
runId: c.runId,
|
|
4261
|
-
canceledByRunId: runId,
|
|
4262
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
4263
|
-
});
|
|
4264
|
-
const serialized = {
|
|
4265
|
-
...serializeError(cancelError),
|
|
4266
|
-
cause: {
|
|
4267
|
-
canceledByRunId: runId,
|
|
4268
|
-
concurrencyKey: c.fact.concurrencyKey
|
|
4269
|
-
}
|
|
4270
|
-
};
|
|
4271
|
-
const errorEvent = {
|
|
4272
|
-
runId: c.runId,
|
|
4273
|
-
flowId: flow2.id,
|
|
4274
|
-
error: serialized,
|
|
4275
|
-
at: c.fact.at
|
|
4276
|
-
};
|
|
4277
|
-
await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
|
|
4278
|
-
await hooks.fireHook(
|
|
4279
|
-
config.hooks?.onFlowError,
|
|
4280
|
-
errorEvent,
|
|
4281
|
-
"onFlowError"
|
|
4282
|
-
);
|
|
4283
|
-
await dispatcher.propagateToParent(c.runId, {
|
|
4284
|
-
kind: "canceled",
|
|
4285
|
-
error: serialized
|
|
4286
|
-
});
|
|
4287
|
-
}
|
|
4288
|
-
const startEvent = {
|
|
4289
|
-
runId,
|
|
4290
|
-
flowId: flow2.id,
|
|
4291
|
-
input: validated,
|
|
4292
|
-
at: startedAt
|
|
4293
|
-
};
|
|
4294
|
-
await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
|
|
4295
|
-
await hooks.fireHook(
|
|
4296
|
-
config.hooks?.onFlowStart,
|
|
4297
|
-
startEvent,
|
|
4298
|
-
"onFlowStart"
|
|
4299
|
-
);
|
|
4300
|
-
};
|
|
2613
|
+
let applied;
|
|
4301
2614
|
return {
|
|
4302
2615
|
runId,
|
|
4303
|
-
started,
|
|
4304
|
-
canceled:
|
|
4305
|
-
applyOnCommit
|
|
2616
|
+
started: true,
|
|
2617
|
+
canceled: staged.effects.superseded.map((e) => e.runId),
|
|
2618
|
+
applyOnCommit: () => applied ??= lifecycle.applyEffects(staged.effects)
|
|
4306
2619
|
};
|
|
4307
2620
|
},
|
|
4308
2621
|
signal: signals.signal,
|
|
4309
2622
|
async cancel(runId, opts) {
|
|
4310
|
-
await cancelRunRecursive(runId, {
|
|
2623
|
+
await lifecycle.cancelRunRecursive(runId, {
|
|
4311
2624
|
cause: "explicit",
|
|
4312
2625
|
reason: opts?.reason ?? "explicit wf.cancel()"
|
|
4313
2626
|
});
|
|
@@ -4318,7 +2631,7 @@ async function nagiImpl(config) {
|
|
|
4318
2631
|
store: config.store,
|
|
4319
2632
|
clock,
|
|
4320
2633
|
registry,
|
|
4321
|
-
cancelRunRecursive,
|
|
2634
|
+
cancelRunRecursive: lifecycle.cancelRunRecursive,
|
|
4322
2635
|
emitLog
|
|
4323
2636
|
});
|
|
4324
2637
|
},
|
|
@@ -4398,12 +2711,6 @@ async function nagiImpl(config) {
|
|
|
4398
2711
|
});
|
|
4399
2712
|
}
|
|
4400
2713
|
};
|
|
4401
|
-
Object.defineProperty(wf, "__dispatchDeps", {
|
|
4402
|
-
value: dispatchDeps,
|
|
4403
|
-
enumerable: false,
|
|
4404
|
-
writable: false,
|
|
4405
|
-
configurable: false
|
|
4406
|
-
});
|
|
4407
2714
|
return wf;
|
|
4408
2715
|
}
|
|
4409
2716
|
async function nagiRun(config) {
|
|
@@ -4468,19 +2775,9 @@ var nagi = Object.assign(
|
|
|
4468
2775
|
nagiImpl,
|
|
4469
2776
|
{ run: nagiRun }
|
|
4470
2777
|
);
|
|
4471
|
-
function
|
|
4472
|
-
return `run-${crypto.randomUUID()}`;
|
|
4473
|
-
}
|
|
4474
|
-
function asStreamTransport(store) {
|
|
4475
|
-
const s = store;
|
|
4476
|
-
return typeof s.subscribeStream === "function" && typeof s.publishChunk === "function" ? s : void 0;
|
|
4477
|
-
}
|
|
4478
|
-
function bindQueueToTx(queue, tx) {
|
|
4479
|
-
const q = queue;
|
|
4480
|
-
if (typeof q.withTx === "function") return q.withTx(tx);
|
|
4481
|
-
return queue;
|
|
2778
|
+
async function noop() {
|
|
4482
2779
|
}
|
|
4483
2780
|
|
|
4484
|
-
export {
|
|
2781
|
+
export { NagiAbortError, RunId, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, optional, sha256Canonical };
|
|
4485
2782
|
//# sourceMappingURL=index.js.map
|
|
4486
2783
|
//# sourceMappingURL=index.js.map
|