@nagi-js/core 0.1.1-rc.18 → 0.1.1-rc.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,330 +1,5 @@
1
- // src/state.ts
2
- var PENDING = { tag: "pending" };
3
- function stepStateOf(runState, stepId) {
4
- return runState.steps[stepId] ?? PENDING;
5
- }
6
- function runStatusOf(state) {
7
- return state.phase.tag;
8
- }
9
- function stepStatusOf(s) {
10
- switch (s.tag) {
11
- case "pending":
12
- return "pending";
13
- case "running":
14
- case "awaitingSignal":
15
- case "awaitingChild":
16
- case "backoff":
17
- case "aborting":
18
- return "running";
19
- case "completed":
20
- return "completed";
21
- case "failed":
22
- return "failed";
23
- case "skipped":
24
- return "skipped";
25
- case "canceled":
26
- return "canceled";
27
- }
28
- }
29
- function outputOf(s) {
30
- return s.tag === "completed" ? s.output : null;
31
- }
32
- function errorOf(s) {
33
- if (s.tag === "failed" || s.tag === "backoff") return s.error;
34
- if (s.tag === "canceled" && s.cause.kind === "aborted") return s.cause.error;
35
- return void 0;
36
- }
37
- function attemptOf(s) {
38
- switch (s.tag) {
39
- case "running":
40
- case "awaitingSignal":
41
- case "awaitingChild":
42
- case "aborting":
43
- case "completed":
44
- case "failed":
45
- return s.attempt;
46
- case "backoff":
47
- return s.failedAttempt;
48
- case "pending":
49
- case "skipped":
50
- case "canceled":
51
- return 0;
52
- }
53
- }
54
- function resolvedOf(s) {
55
- if (s.tag === "completed") return { tag: "value", value: s.output };
56
- if (s.tag === "skipped") return { tag: "skipped" };
57
- return { tag: "value", value: null };
58
- }
59
- function unwrap(r) {
60
- if (r.tag === "skipped") {
61
- throw new Error("nagi: upstream was skipped \u2014 its value is unavailable");
62
- }
63
- return r.value;
64
- }
65
- function isTerminalRun(state) {
66
- return state.phase.tag !== "pending" && state.phase.tag !== "running";
67
- }
68
- function isAbortRequested(s, attempt) {
69
- return s.tag === "aborting" && s.attempt === attempt;
70
- }
71
- function isStepTerminal(s) {
72
- return s.tag === "completed" || s.tag === "failed" || s.tag === "skipped" || s.tag === "canceled";
73
- }
74
- function keep(prev) {
75
- return { next: prev, anomaly: true };
76
- }
77
- function startTarget(stepKind, attempt) {
78
- switch (stepKind) {
79
- case "signal":
80
- return { tag: "awaitingSignal", attempt };
81
- case "subflow":
82
- return { tag: "awaitingChild", attempt };
83
- case "task":
84
- case "activity":
85
- case "streaming":
86
- case "match":
87
- return { tag: "running", attempt };
88
- }
89
- }
90
- function stepTransition(prev, fact) {
91
- switch (fact.kind) {
92
- case "step.started":
93
- if (prev.tag === "pending" || prev.tag === "backoff")
94
- return {
95
- next: startTarget(fact.stepKind, fact.attempt),
96
- anomaly: false
97
- };
98
- return keep(prev);
99
- // Terminal facts carry authoritative outcomes, so they settle a step from
100
- // any non-terminal state; only a terminal→terminal contradiction is flagged.
101
- case "step.completed":
102
- if (isStepTerminal(prev)) return keep(prev);
103
- return {
104
- next: { tag: "completed", attempt: fact.attempt, output: fact.output },
105
- anomaly: false
106
- };
107
- case "step.failed":
108
- if (isStepTerminal(prev)) return keep(prev);
109
- return {
110
- next: { tag: "failed", attempt: fact.attempt, error: fact.error },
111
- anomaly: false
112
- };
113
- case "step.canceled": {
114
- if (isStepTerminal(prev)) return keep(prev);
115
- const cause = prev.tag === "aborting" ? { kind: "aborted", ...compact({ error: fact.error }) } : { kind: "run-canceled" };
116
- return { next: { tag: "canceled", cause }, anomaly: false };
117
- }
118
- case "step.retried":
119
- if (prev.tag === "running")
120
- return {
121
- next: {
122
- tag: "backoff",
123
- failedAttempt: fact.attempt,
124
- retryAt: fact.nextAttemptAt,
125
- error: fact.error
126
- },
127
- anomaly: false
128
- };
129
- return keep(prev);
130
- case "step.skipped":
131
- if (!isStepTerminal(prev))
132
- return {
133
- next: {
134
- tag: "skipped",
135
- reason: fact.reason
136
- },
137
- anomaly: false
138
- };
139
- return keep(prev);
140
- case "step.abort-requested":
141
- if (prev.tag === "running" || prev.tag === "awaitingSignal" || prev.tag === "awaitingChild")
142
- return {
143
- next: { tag: "aborting", attempt: fact.attempt },
144
- anomaly: false
145
- };
146
- return keep(prev);
147
- }
148
- }
149
- function runCancelCause(fact) {
150
- switch (fact.cause) {
151
- case "concurrency":
152
- return {
153
- kind: "concurrency",
154
- canceledByRunId: fact.canceledByRunId,
155
- concurrencyKey: fact.concurrencyKey
156
- };
157
- case "explicit":
158
- return {
159
- kind: "explicit",
160
- reason: fact.reason,
161
- ...compact({ note: fact.note })
162
- };
163
- case "operator":
164
- return {
165
- kind: "operator",
166
- actor: fact.actor,
167
- reason: fact.reason,
168
- ...compact({ note: fact.note })
169
- };
170
- }
171
- }
172
- function foldRun(runId, facts) {
173
- let flowId = "";
174
- let input = null;
175
- let phase = { tag: "pending" };
176
- let parent;
177
- let flowHash;
178
- let codeVersion;
179
- const steps = {};
180
- const selectedArms = {};
181
- const bufferedSignals = {};
182
- const anomalies = [];
183
- for (const fact of facts) {
184
- switch (fact.kind) {
185
- case "flow.started":
186
- flowId = fact.flowId;
187
- input = fact.input;
188
- phase = { tag: "running" };
189
- parent = fact.parent;
190
- flowHash = fact.flowHash;
191
- codeVersion = fact.codeVersion;
192
- break;
193
- case "flow.completed":
194
- phase = { tag: "completed", output: fact.output };
195
- break;
196
- case "flow.failed":
197
- phase = { tag: "failed", error: fact.error };
198
- break;
199
- case "flow.canceled":
200
- phase = { tag: "canceled", cause: runCancelCause(fact) };
201
- break;
202
- case "match.arm-selected":
203
- selectedArms[fact.stepId] = fact.arm;
204
- break;
205
- case "step.reset":
206
- steps[fact.stepId] = PENDING;
207
- delete selectedArms[fact.stepId];
208
- 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, stepStateOf, serializeError, NagiCanceledError, NagiSignalTimeoutError, dequeueBackoff, defaultSnapshotGonePolicy, isStepTerminal, stepStatusOf, NagiSnapshotDriftError, attachDef, setDef, 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/errors.ts
824
- var NagiValidationError = class extends Error {
825
- issues;
826
- constructor(issues) {
827
- super(issues.map((i) => i.message).join("; "));
828
- this.name = "NagiValidationError";
829
- this.issues = issues;
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 validationError(message, path) {
833
- return new NagiValidationError([{ message, path }]);
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
- var NagiRuntimeError = class extends Error {
836
- constructor(message) {
837
- super(message);
838
- this.name = "NagiRuntimeError";
839
- }
840
- };
841
- var NagiNonRetryableError = class extends Error {
842
- constructor(message, opts) {
843
- super(message, opts);
844
- this.name = "NagiNonRetryableError";
845
- }
846
- };
847
- var NagiCanceledError = class extends Error {
848
- runId;
849
- canceledByRunId;
850
- concurrencyKey;
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
- var NagiFlowSnapshotGoneError = class extends Error {
888
- runId;
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
- var NagiConcurrencyConflictError = class extends Error {
909
- runId;
910
- flowId;
911
- concurrencyKey;
912
- constructor({
913
- runId,
914
- flowId,
915
- concurrencyKey
916
- }) {
917
- super(
918
- `Run ${runId}: concurrent start lost the race on flow "${flowId}" concurrency key "${concurrencyKey}" \u2014 retry the caller transaction.`
919
- );
920
- this.name = "NagiConcurrencyConflictError";
921
- this.runId = runId;
922
- this.flowId = flowId;
923
- this.concurrencyKey = concurrencyKey;
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
- var NagiSnapshotDriftError = class extends Error {
927
- runId;
928
- expected;
929
- actual;
930
- constructor({
931
- runId,
932
- expected,
933
- actual
934
- }) {
935
- super(
936
- `Run ${runId} was pinned to flow hash ${expected.slice(0, 12)}\u2026 but the live flow's hash is ${actual.slice(0, 12)}\u2026. Pass replayOpts.allowDrift = true to replay against the live code anyway.`
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
- this.name = "NagiSnapshotDriftError";
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 { name: "Error", message: String(err) };
587
+ return { kind: "run" };
953
588
  }
954
-
955
- // src/lease-reaper.ts
956
- function decideExpiredLeaseAction(args) {
957
- const { lease, stepStatus, childActive, now } = args;
958
- if (stepStatus === "completed" || stepStatus === "failed" || stepStatus === "canceled" || stepStatus === "skipped") {
959
- return { tag: "skip", reason: "terminal" };
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
- if (childActive) {
962
- return { tag: "skip", reason: "child-active" };
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
- if (lease.expiresAt > now) {
965
- return { tag: "skip", reason: "still-live" };
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
- return {
968
- tag: "reap",
969
- nextAttempt: lease.attempt + 1,
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: computeBackoff(policy, attempt) };
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;
973
+ const resolution = await deps.resolveFlow(message.runId);
2646
974
  let flow2;
2647
- try {
2648
- flow2 = await deps.flowFor(message.runId);
2649
- } catch (err) {
2650
- if (err instanceof NagiFlowSnapshotGoneError && isTerminalRun(await deps.store.loadRunState(message.runId))) {
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
- throw err;
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 ?? deps.defaultRetry ?? DEFAULT_RETRY2;
1340
+ const policy = resolveRetry(handler?.retry, deps.defaultRetry);
3008
1341
  const outcome = classifyFailure({
3009
1342
  attempt,
3010
1343
  policy,
@@ -3084,6 +1417,168 @@ 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
+ const synthesizedByHash = /* @__PURE__ */ new Map();
1507
+ function synthesize(gone) {
1508
+ const { pinnedHash } = gone.error;
1509
+ const cached = synthesizedByHash.get(pinnedHash);
1510
+ if (cached !== void 0) return cached;
1511
+ const pending = synthesizeUncached(gone);
1512
+ synthesizedByHash.set(pinnedHash, pending);
1513
+ pending.catch(() => synthesizedByHash.delete(pinnedHash));
1514
+ return pending;
1515
+ }
1516
+ async function synthesizeUncached(gone) {
1517
+ const { runId, flowId, pinnedHash } = gone.error;
1518
+ if (gone.live === void 0) {
1519
+ throw new NagiRuntimeError(
1520
+ `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
1521
+ );
1522
+ }
1523
+ const snapshot = await store.loadSnapshot(pinnedHash);
1524
+ if (snapshot === null) {
1525
+ throw new NagiRuntimeError(
1526
+ `Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Nothing can resume it.`
1527
+ );
1528
+ }
1529
+ return synthesizeReplayFlow(
1530
+ snapshot.dag,
1531
+ gone.live
1532
+ );
1533
+ }
1534
+ return {
1535
+ get: (flowId) => byId.get(flowId),
1536
+ has: (flowId) => byId.has(flowId),
1537
+ require: require2,
1538
+ hashOf,
1539
+ isStreaming: (stepId) => streamingStepIds.has(stepId),
1540
+ resolve,
1541
+ synthesize
1542
+ };
1543
+ }
1544
+ function synthesizeReplayFlow(dag, liveFlow) {
1545
+ const liveSteps = asStepMapWithDefs(liveFlow.steps);
1546
+ const synthesized = {};
1547
+ for (const canonStep of dag.steps) {
1548
+ const liveStep = liveSteps[canonStep.id];
1549
+ if (liveStep === void 0) {
1550
+ throw new NagiRuntimeError(
1551
+ `Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
1552
+ );
1553
+ }
1554
+ synthesized[canonStep.id] = attachDef(
1555
+ { kind: canonStep.kind, id: canonStep.id },
1556
+ getDef(liveStep)
1557
+ );
1558
+ }
1559
+ for (const canonStep of dag.steps) {
1560
+ const shell = synthesized[canonStep.id];
1561
+ if (shell === void 0) continue;
1562
+ const synthesizedNeeds = {};
1563
+ for (const upstreamId of canonStep.needs) {
1564
+ const upstreamShell = synthesized[upstreamId];
1565
+ if (upstreamShell === void 0) {
1566
+ throw new NagiRuntimeError(
1567
+ `Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
1568
+ );
1569
+ }
1570
+ synthesizedNeeds[upstreamId] = upstreamShell;
1571
+ }
1572
+ setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
1573
+ }
1574
+ return {
1575
+ id: liveFlow.id,
1576
+ input: liveFlow.input,
1577
+ steps: synthesized,
1578
+ ...compact({ output: liveFlow.output })
1579
+ };
1580
+ }
1581
+
3087
1582
  // src/exec/progression.ts
3088
1583
  var MAX_ADVANCE_ITERS = 1024;
3089
1584
  function subflowOutcomeOf(childRunId, child) {
@@ -3128,7 +1623,7 @@ function makeProgression(deps, hooks) {
3128
1623
  const { fireHook } = hooks;
3129
1624
  async function advance(runId) {
3130
1625
  const { store, queue } = deps;
3131
- const flow2 = await deps.flowFor(runId);
1626
+ const flow2 = requireCurrent(await deps.resolveFlow(runId));
3132
1627
  for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
3133
1628
  const runState = await store.loadRunState(runId);
3134
1629
  const t = nextTransition(flow2, runState);
@@ -3277,7 +1772,7 @@ function makeProgression(deps, hooks) {
3277
1772
  return;
3278
1773
  }
3279
1774
  const attempt = parentStep.attempt;
3280
- const parentFlow = await deps.flowFor(parentRunId);
1775
+ const parentFlow = requireCurrent(await deps.resolveFlow(parentRunId));
3281
1776
  await markStepSettled({
3282
1777
  flow: parentFlow,
3283
1778
  runId: parentRunId,
@@ -3307,7 +1802,7 @@ function makeDispatcher(deps) {
3307
1802
  for (const { runId, stepId, attempt, fireAt } of timedOut) {
3308
1803
  try {
3309
1804
  if (deps.hooks?.onStepError) {
3310
- const flow2 = await deps.flowFor(runId);
1805
+ const flow2 = requireCurrent(await deps.resolveFlow(runId));
3311
1806
  await hooks.fireHook(
3312
1807
  deps.hooks.onStepError,
3313
1808
  {
@@ -3343,61 +1838,6 @@ function makeDispatcher(deps) {
3343
1838
  };
3344
1839
  }
3345
1840
 
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
1841
  // src/operator.ts
3402
1842
  var ABORT_SETTLE_DEADLINE_MS = 3e4;
3403
1843
  var ABORT_SETTLE_POLL_MS = 50;
@@ -3413,7 +1853,7 @@ function makeOperator(o) {
3413
1853
  async function skip(runId, stepId, opts) {
3414
1854
  requireActor("operator.skip", opts.actor);
3415
1855
  const state = await store.loadRunState(runId);
3416
- const flow2 = registry.requireForRun(state.flowId, runId);
1856
+ const flow2 = registry.require(state.flowId);
3417
1857
  if (!(stepId in flow2.steps)) {
3418
1858
  throw validationError(
3419
1859
  `operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
@@ -3470,7 +1910,7 @@ function makeOperator(o) {
3470
1910
  `operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
3471
1911
  );
3472
1912
  }
3473
- const flow2 = registry.requireForRun(state.flowId, runId);
1913
+ const flow2 = registry.require(state.flowId);
3474
1914
  if (!(stepId in flow2.steps)) {
3475
1915
  throw validationError(
3476
1916
  `operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
@@ -3523,118 +1963,271 @@ function makeOperator(o) {
3523
1963
  return { skip, retry, abort };
3524
1964
  }
3525
1965
 
3526
- // src/replay-synth.ts
3527
- function synthesizeReplayFlow(dag, liveFlow) {
3528
- const liveSteps = asStepMapWithDefs(liveFlow.steps);
3529
- const synthesized = {};
3530
- for (const canonStep of dag.steps) {
3531
- const liveStep = liveSteps[canonStep.id];
3532
- if (liveStep === void 0) {
1966
+ // src/replay.ts
1967
+ function makeReplay(deps) {
1968
+ const { registry, store, queue, clock, driftPolicy } = deps;
1969
+ async function replay(runId, opts = { mode: "continue" }) {
1970
+ const runState = await store.loadRunState(runId);
1971
+ const resolution = registry.resolve(runState);
1972
+ const liveFlow = resolution.kind === "current" ? resolution.flow : resolution.live;
1973
+ if (liveFlow === void 0) {
3533
1974
  throw new NagiRuntimeError(
3534
- `Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
1975
+ `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
3535
1976
  );
3536
1977
  }
3537
- synthesized[canonStep.id] = attachDef(
3538
- { kind: canonStep.kind, id: canonStep.id },
3539
- getDef(liveStep)
3540
- );
3541
- }
3542
- for (const canonStep of dag.steps) {
3543
- const shell = synthesized[canonStep.id];
3544
- if (shell === void 0) continue;
3545
- const synthesizedNeeds = {};
3546
- for (const upstreamId of canonStep.needs) {
3547
- const upstreamShell = synthesized[upstreamId];
3548
- if (upstreamShell === void 0) {
1978
+ if (runState.phase.tag === "canceled") {
1979
+ throw new NagiRuntimeError(
1980
+ `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.`
1981
+ );
1982
+ }
1983
+ if (opts.mode === "inspect") return;
1984
+ const fireHooks = opts.fireHooks !== false;
1985
+ const baseDeps = fireHooks ? deps : { ...deps, fireHooks: false };
1986
+ let replayDeps = baseDeps;
1987
+ let effectiveFlow = liveFlow;
1988
+ if (resolution.kind !== "current") {
1989
+ if (!opts.allowDrift && driftPolicy === "freeze") {
1990
+ throw new NagiSnapshotDriftError({
1991
+ runId,
1992
+ expected: resolution.error.pinnedHash,
1993
+ actual: registry.hashOf(liveFlow.id)
1994
+ });
1995
+ }
1996
+ const synthesized = await registry.synthesize(resolution);
1997
+ replayDeps = {
1998
+ ...baseDeps,
1999
+ resolveFlow: async () => ({ kind: "current", flow: synthesized })
2000
+ };
2001
+ effectiveFlow = synthesized;
2002
+ }
2003
+ if (opts.from !== void 0) {
2004
+ if (runState.phase.tag === "running") {
3549
2005
  throw new NagiRuntimeError(
3550
- `Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
2006
+ `Run ${runId} is still running \u2014 replay({ from }) would race in-flight workers. Wait for the run to settle (completed / failed) before resetting from a step.`
3551
2007
  );
3552
2008
  }
3553
- synthesizedNeeds[upstreamId] = upstreamShell;
2009
+ if (!(opts.from in effectiveFlow.steps)) {
2010
+ throw validationError(
2011
+ `replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
2012
+ ["from"]
2013
+ );
2014
+ }
2015
+ const cascade = descendantsOf(effectiveFlow, opts.from);
2016
+ const at = clock.now();
2017
+ for (const stepId of cascade) {
2018
+ const fact = stepId === opts.from ? Facts.stepReset({ runId, stepId, at }) : Facts.stepReset({ runId, stepId, at, cascadedFrom: opts.from });
2019
+ await store.appendFact(runId, fact);
2020
+ }
2021
+ }
2022
+ const replayDispatcher = makeDispatcher(replayDeps);
2023
+ await replayDispatcher.advance(runId);
2024
+ if (!fireHooks) await drainInline(replayDispatcher, queue);
2025
+ }
2026
+ return { replay };
2027
+ }
2028
+ var MAX_REPLAY_DISPATCHES = 4096;
2029
+ async function drainInline(dispatcher, queue) {
2030
+ for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
2031
+ const messages = await queue.dequeue({ count: 1 });
2032
+ if (messages.length === 0) return;
2033
+ for (const msg of messages) {
2034
+ const result = await dispatcher.dispatchMessage(msg);
2035
+ if (result.kind === "snapshot-gone") throw result.error;
3554
2036
  }
3555
- setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
3556
2037
  }
3557
- return {
3558
- id: liveFlow.id,
3559
- input: liveFlow.input,
3560
- steps: synthesized,
3561
- ...compact({ output: liveFlow.output })
3562
- };
3563
2038
  }
3564
2039
 
3565
- // src/replay.ts
3566
- function makeReplay(deps) {
3567
- const { registry, hashFor, store, queue, clock } = deps;
3568
- async function replay(runId, opts = { mode: "continue" }) {
3569
- const runState = await store.loadRunState(runId);
3570
- const liveFlow = registry.requireForRun(runState.flowId, runId);
3571
- if (runState.phase.tag === "canceled") {
2040
+ // src/run-lifecycle.ts
2041
+ var EXISTS = { kind: "exists" };
2042
+ var ADVANCE = { kind: "advance" };
2043
+ function makeRunLifecycle(deps) {
2044
+ const { store, queue, clock, registry, hooks, flowHooks, dispatcher } = deps;
2045
+ function resolveBoundary(boundary) {
2046
+ switch (boundary.kind) {
2047
+ case "own":
2048
+ return {
2049
+ tryStart: (runId, fact, concurrency) => store.tryStartRun(runId, fact, concurrency),
2050
+ seed: async (_runId, _flowId, t) => t.skip.length > 0 ? ADVANCE : { kind: "enqueue", steps: t.runnable }
2051
+ };
2052
+ case "caller":
2053
+ return {
2054
+ tryStart: (runId, fact, concurrency) => store.tryStartRunOnTx(boundary.tx, runId, fact, concurrency),
2055
+ seed: async (runId, flowId, t) => {
2056
+ const txQueue = deps.queueForTx(boundary.tx);
2057
+ for (const stepId of t.runnable) {
2058
+ await txQueue.enqueue(runId, stepId, { flowId });
2059
+ }
2060
+ return { kind: "enqueued", steps: t.runnable, skip: t.skip };
2061
+ }
2062
+ };
2063
+ }
2064
+ }
2065
+ async function stage(args) {
2066
+ const { flow: flow2, validatedInput, runId, parent } = args;
2067
+ const { tryStart, seed } = resolveBoundary(args.boundary);
2068
+ const startedAt = clock.now();
2069
+ const fact = Facts.flowStarted({
2070
+ runId,
2071
+ flowId: flow2.id,
2072
+ input: validatedInput,
2073
+ at: startedAt,
2074
+ codeVersion: deps.codeVersion,
2075
+ flowHash: registry.hashOf(flow2.id),
2076
+ ...compact({
2077
+ parent: parent !== void 0 ? { runId: parent.runId, stepId: parent.stepId } : void 0
2078
+ })
2079
+ });
2080
+ const concurrency = concurrencyOf(flow2, validatedInput);
2081
+ const { started, canceled } = await tryStart(runId, fact, concurrency);
2082
+ if (!started) return EXISTS;
2083
+ const t = nextTransition(flow2, foldRun(runId, [fact]));
2084
+ const dispatch = t.kind === "dispatch" ? await seed(runId, flow2.id, t) : ADVANCE;
2085
+ return {
2086
+ kind: "started",
2087
+ effects: {
2088
+ superseded: canceled.map((c) => supersededEvent(flow2.id, runId, c)),
2089
+ started: {
2090
+ runId,
2091
+ flowId: flow2.id,
2092
+ input: validatedInput,
2093
+ at: startedAt,
2094
+ ...compact({ parent })
2095
+ },
2096
+ dispatch
2097
+ }
2098
+ };
2099
+ }
2100
+ async function applyEffects(effects) {
2101
+ const { superseded, started, dispatch } = effects;
2102
+ const flow2 = registry.require(started.flowId);
2103
+ for (const event of superseded) {
2104
+ await hooks.fireHook(flow2.onError, event, "flow.onError");
2105
+ await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
2106
+ await dispatcher.propagateToParent(event.runId, {
2107
+ kind: "canceled",
2108
+ error: event.error
2109
+ });
2110
+ }
2111
+ await hooks.fireHook(flow2.onStart, started, "flow.onStart");
2112
+ await hooks.fireHook(flowHooks?.onFlowStart, started, "onFlowStart");
2113
+ switch (dispatch.kind) {
2114
+ case "enqueue":
2115
+ for (const stepId of dispatch.steps) {
2116
+ await queue.enqueue(started.runId, stepId, { flowId: flow2.id });
2117
+ }
2118
+ return;
2119
+ case "enqueued":
2120
+ await recordSkips(started.runId, dispatch.skip);
2121
+ return;
2122
+ case "advance":
2123
+ await dispatcher.advance(started.runId);
2124
+ return;
2125
+ }
2126
+ }
2127
+ async function recordSkips(runId, skip) {
2128
+ if (skip.length === 0) return;
2129
+ const state = await store.loadRunState(runId);
2130
+ for (const { stepId, reason } of skip) {
2131
+ if (stepStateOf(state, stepId).tag !== "pending") continue;
2132
+ await store.appendFact(
2133
+ runId,
2134
+ Facts.stepSkipped({ runId, stepId, reason, at: clock.now() })
2135
+ );
2136
+ }
2137
+ }
2138
+ async function start(args) {
2139
+ const flow2 = registry.require(args.flowId);
2140
+ const runId = resolveRunId(args.runId);
2141
+ const validatedInput = await validate(flow2.input, args.input);
2142
+ const staged = await stage({
2143
+ flow: flow2,
2144
+ validatedInput,
2145
+ runId,
2146
+ parent: void 0,
2147
+ boundary: args.boundary
2148
+ });
2149
+ return { runId, staged };
2150
+ }
2151
+ async function startChildRun(args) {
2152
+ const { child, childInput, parent, generation } = args;
2153
+ if (!registry.has(child.id)) {
3572
2154
  throw new NagiRuntimeError(
3573
- `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.`
2155
+ `Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
3574
2156
  );
3575
2157
  }
3576
- if (opts.mode === "inspect") return;
3577
- const fireHooks = opts.fireHooks !== false;
3578
- const baseDeps = fireHooks ? deps : { ...deps, fireHooks: false };
3579
- let replayDeps = baseDeps;
3580
- let effectiveFlow = liveFlow;
3581
- const pinned = runState.flowHash;
3582
- if (pinned !== void 0) {
3583
- const liveHash = hashFor(liveFlow.id);
3584
- if (liveHash !== void 0 && liveHash !== pinned) {
3585
- if (!opts.allowDrift) {
3586
- throw new NagiSnapshotDriftError({
3587
- runId,
3588
- expected: pinned,
3589
- actual: liveHash
3590
- });
3591
- }
3592
- const snapshot = await store.loadSnapshot(pinned);
3593
- if (snapshot === null) {
3594
- throw new NagiRuntimeError(
3595
- `Run ${runId} pinned to flow hash ${pinned.slice(0, 12)}\u2026 but no snapshot with that hash was found. Cannot replay with allowDrift.`
3596
- );
3597
- }
3598
- const synthesized = synthesizeReplayFlow(
3599
- snapshot.dag,
3600
- liveFlow
3601
- );
3602
- replayDeps = { ...baseDeps, flowFor: async () => synthesized };
3603
- effectiveFlow = synthesized;
3604
- }
2158
+ const validatedInput = await validate(child.input, childInput);
2159
+ const runId = await deriveChildRunId({
2160
+ runId: parent.runId,
2161
+ stepId: parent.stepId,
2162
+ generation
2163
+ });
2164
+ const staged = await stage({
2165
+ flow: child,
2166
+ validatedInput,
2167
+ runId,
2168
+ parent,
2169
+ boundary: { kind: "own" }
2170
+ });
2171
+ if (staged.kind === "started") await applyEffects(staged.effects);
2172
+ return runId;
2173
+ }
2174
+ async function cancelRunRecursive(runId, args) {
2175
+ const state = await store.loadRunState(runId);
2176
+ if (isTerminalRun(state)) {
2177
+ deps.emitLog({
2178
+ level: "info",
2179
+ msg: "nagi: cancel skipped \u2014 run already terminal",
2180
+ attrs: { runId, status: runStatusOf(state) }
2181
+ });
2182
+ return;
3605
2183
  }
3606
- if (opts.from !== void 0) {
3607
- if (runState.phase.tag === "running") {
3608
- throw new NagiRuntimeError(
3609
- `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.`
3610
- );
3611
- }
3612
- if (!(opts.from in effectiveFlow.steps)) {
3613
- throw validationError(
3614
- `replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
3615
- ["from"]
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
- }
2184
+ const flow2 = registry.get(state.flowId);
2185
+ await store.appendFact(runId, Facts.flowCanceled(runId, args, clock.now()));
2186
+ const error = {
2187
+ name: "NagiCanceledError",
2188
+ message: `Run ${runId} was canceled: ${args.reason}`
2189
+ };
2190
+ if (flow2 !== void 0) {
2191
+ const event = { runId, flowId: flow2.id, error, at: clock.now() };
2192
+ await hooks.fireHook(flow2.onError, event, "flow.onError");
2193
+ await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
3624
2194
  }
3625
- const replayDispatcher = makeDispatcher(replayDeps);
3626
- await replayDispatcher.advance(runId);
3627
- if (!fireHooks) await drainInline(replayDispatcher, queue);
2195
+ for (const childId of await store.listChildren(runId)) {
2196
+ await cancelRunRecursive(childId, {
2197
+ cause: "explicit",
2198
+ reason: `parent ${runId} canceled: ${args.reason}`,
2199
+ note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
2200
+ });
2201
+ }
2202
+ await dispatcher.propagateToParent(runId, { kind: "canceled", error });
3628
2203
  }
3629
- return { replay };
2204
+ return { start, stage, applyEffects, startChildRun, cancelRunRecursive };
3630
2205
  }
3631
- var MAX_REPLAY_DISPATCHES = 4096;
3632
- async function drainInline(dispatcher, queue) {
3633
- for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
3634
- const messages = await queue.dequeue({ count: 1 });
3635
- if (messages.length === 0) return;
3636
- for (const msg of messages) await dispatcher.dispatchMessage(msg);
2206
+ function resolveRunId(runId) {
2207
+ if (runId === void 0) return `run-${crypto.randomUUID()}`;
2208
+ if (typeof runId !== "string" || runId.length === 0) {
2209
+ throw validationError("opts.runId must be a non-empty string", ["runId"]);
2210
+ }
2211
+ return runId;
2212
+ }
2213
+ function concurrencyOf(flow2, input) {
2214
+ if (flow2.concurrency === void 0) return void 0;
2215
+ const key = flow2.concurrency.keyFn(input);
2216
+ if (typeof key !== "string" || key.length === 0) {
2217
+ throw validationError(
2218
+ `flow.concurrency.keyFn must return a non-empty string (got ${typeof key === "string" ? '""' : typeof key})`,
2219
+ ["concurrency", "keyFn"]
2220
+ );
3637
2221
  }
2222
+ return { key, mode: flow2.concurrency.mode };
2223
+ }
2224
+ function supersededEvent(flowId, canceledByRunId, c) {
2225
+ const cause = { canceledByRunId, concurrencyKey: c.fact.concurrencyKey };
2226
+ const error = {
2227
+ ...serializeError(new NagiCanceledError({ runId: c.runId, ...cause })),
2228
+ cause
2229
+ };
2230
+ return { runId: c.runId, flowId, error, at: c.fact.at };
3638
2231
  }
3639
2232
 
3640
2233
  // src/worker.ts
@@ -3642,15 +2235,6 @@ var DEFAULT_CONCURRENCY = 4;
3642
2235
  var DEFAULT_POLL_INTERVAL_MS = 1e3;
3643
2236
  var DEFAULT_TIMER_SWEEP_INTERVAL_MS = 3e4;
3644
2237
  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
2238
  function makeWorker(deps, config) {
3655
2239
  return new WorkerImpl(deps, config);
3656
2240
  }
@@ -3659,6 +2243,7 @@ var WorkerImpl = class {
3659
2243
  this.deps = deps;
3660
2244
  this.concurrency = Math.max(1, config?.concurrency ?? DEFAULT_CONCURRENCY);
3661
2245
  this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
2246
+ this.dequeueBackoffMs = dequeueBackoff(this.pollIntervalMs);
3662
2247
  this.signal = config?.signal;
3663
2248
  this.dispatcher = makeDispatcher(deps);
3664
2249
  this.snapshotGonePolicy = config?.snapshotGonePolicy ?? defaultSnapshotGonePolicy;
@@ -3670,6 +2255,7 @@ var WorkerImpl = class {
3670
2255
  inFlight = 0;
3671
2256
  concurrency;
3672
2257
  pollIntervalMs;
2258
+ dequeueBackoffMs;
3673
2259
  signal;
3674
2260
  dispatcher;
3675
2261
  timerSweepIntervalMs;
@@ -3758,7 +2344,7 @@ var WorkerImpl = class {
3758
2344
  async runUntilEmpty(opts) {
3759
2345
  const deadline = opts?.deadline;
3760
2346
  return this.pump({
3761
- shouldContinue: () => deadline === void 0 || Date.now() < deadline,
2347
+ shouldContinue: () => deadline === void 0 || this.deps.clock.now().getTime() < deadline,
3762
2348
  batchSize: () => this.concurrency
3763
2349
  });
3764
2350
  }
@@ -3794,18 +2380,6 @@ var WorkerImpl = class {
3794
2380
  async dequeue(count) {
3795
2381
  return this.deps.queue.dequeue({ count: Math.max(1, count) });
3796
2382
  }
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
2383
  fire(msg) {
3810
2384
  this.inFlight++;
3811
2385
  const release = this.trackFlow(msg);
@@ -3815,17 +2389,32 @@ var WorkerImpl = class {
3815
2389
  });
3816
2390
  }
3817
2391
  async dispatchSafely(msg) {
2392
+ let result;
3818
2393
  try {
3819
- await this.dispatcher.dispatchMessage(msg);
2394
+ result = await this.dispatcher.dispatchMessage(msg);
3820
2395
  } catch (err) {
3821
- if (err instanceof NagiFlowSnapshotGoneError) {
2396
+ this.deps.emitLog({
2397
+ level: "error",
2398
+ msg: "worker.dispatch threw uncaught",
2399
+ attrs: { error: String(err) }
2400
+ });
2401
+ try {
2402
+ await this.deps.queue.nack(msg.receipt);
2403
+ } catch {
2404
+ }
2405
+ return;
2406
+ }
2407
+ switch (result.kind) {
2408
+ case "done":
2409
+ return;
2410
+ case "snapshot-gone":
3822
2411
  try {
3823
- await this.handleSnapshotGone(msg, err);
2412
+ await this.handleSnapshotGone(msg, result.error);
3824
2413
  } catch (handleErr) {
3825
2414
  this.deps.emitLog({
3826
2415
  level: "error",
3827
2416
  msg: "worker.dispatch: snapshot-gone handling failed",
3828
- attrs: { runId: err.runId, error: String(handleErr) }
2417
+ attrs: { runId: result.error.runId, error: String(handleErr) }
3829
2418
  });
3830
2419
  try {
3831
2420
  await this.deps.queue.nack(msg.receipt, {
@@ -3835,23 +2424,12 @@ var WorkerImpl = class {
3835
2424
  }
3836
2425
  }
3837
2426
  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
2427
  }
3849
2428
  }
3850
2429
  // A snapshot-gone message is retried (nack, delayed) only while the policy
3851
2430
  // says a frozen-version worker might still claim it; past that budget the
3852
2431
  // run is terminally failed with the snapshot-gone error and the message
3853
2432
  // acked, so poison messages cannot outlive the deploy that orphaned them.
3854
- // (Terminal runs never reach here — dispatchMessage acks them itself.)
3855
2433
  async handleSnapshotGone(msg, err) {
3856
2434
  const attrs = {
3857
2435
  runId: err.runId,
@@ -3940,202 +2518,53 @@ async function nagiImpl(config) {
3940
2518
  const clock = config.clock ?? new InMemoryClock();
3941
2519
  const emitLog = makeEmit(config.onLog);
3942
2520
  await config.queue.ensureSchema?.();
3943
- const registry = makeFlowRegistry(config.flows);
3944
- const streamTransport = config.streamTransport ?? asStreamTransport(config.store);
2521
+ const streamTransport = config.store.stream;
3945
2522
  if (streamTransport === void 0) {
3946
- for (const f of registry.all) {
2523
+ for (const f of config.flows) {
3947
2524
  for (const [stepId, step] of Object.entries(asStepMapWithDefs(f.steps))) {
3948
2525
  if (getDef(step).kind !== "streaming") continue;
3949
2526
  throw new NagiRuntimeError(
3950
- `Flow "${f.id}" has a streaming step "${stepId}" (b.streamingTask), but no StreamTransport is configured \u2014 it cannot transport ephemeral chunks. Pass streamTransport (or a store that implements it, e.g. the in-memory store) or remove the streaming step.`
2527
+ `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
2528
  );
3952
2529
  }
3953
2530
  }
3954
2531
  }
3955
- const flowHashById = /* @__PURE__ */ new Map();
3956
- for (const f of registry.all) {
3957
- const dag = await canonicalize(f);
3958
- const flowHash = await sha256Canonical(dag);
3959
- flowHashById.set(f.id, flowHash);
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
- }
2532
+ const registry = await registerFlows({
2533
+ flows: config.flows,
2534
+ store: config.store,
2535
+ clock
2536
+ });
3978
2537
  const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
3979
- async function flowFor(runId) {
3980
- const runState = await config.store.loadRunState(runId);
3981
- return registry.requireForRun(
3982
- runState.flowId,
3983
- runId,
3984
- runState.flowHash,
3985
- (id) => flowHashById.get(id)
3986
- );
3987
- }
3988
- function lookupFlow(flowId) {
3989
- return registry.get(flowId);
3990
- }
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 };
2538
+ const driftPolicy = config.driftPolicy ?? "freeze";
2539
+ async function resolveFlow(runId) {
2540
+ const resolution = registry.resolve(await config.store.loadRunState(runId));
2541
+ if (resolution.kind !== "gone-live" || driftPolicy === "freeze") {
2542
+ return resolution;
4020
2543
  }
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
2544
+ try {
2545
+ return { kind: "current", flow: await registry.synthesize(resolution) };
2546
+ } catch (err) {
2547
+ if (!(err instanceof NagiRuntimeError)) throw err;
2548
+ emitLog({
2549
+ level: "warn",
2550
+ msg: "resolveFlow: drift synthesis failed \u2014 treating run as snapshot-gone",
2551
+ attrs: {
2552
+ runId: resolution.error.runId,
2553
+ flowId: resolution.error.flowId,
2554
+ pinnedHash: resolution.error.pinnedHash,
2555
+ error: err.message
4038
2556
  }
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
2557
  });
2558
+ return resolution;
4056
2559
  }
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
2560
  }
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
- });
2561
+ function lookupFlow(flowId) {
2562
+ return registry.get(flowId);
4134
2563
  }
4135
2564
  const dispatchDeps = {
4136
- flowFor,
2565
+ resolveFlow,
4137
2566
  lookupFlow,
4138
- startChildRun,
2567
+ startChildRun: (args) => lifecycle.startChildRun(args),
4139
2568
  store: config.store,
4140
2569
  queue: config.queue,
4141
2570
  clock,
@@ -4155,6 +2584,18 @@ async function nagiImpl(config) {
4155
2584
  };
4156
2585
  const dispatcher = makeDispatcher(dispatchDeps);
4157
2586
  const hooks = makeHooks(dispatchDeps);
2587
+ const lifecycle = makeRunLifecycle({
2588
+ store: config.store,
2589
+ queue: config.queue,
2590
+ clock,
2591
+ registry,
2592
+ codeVersion,
2593
+ queueForTx: (tx) => config.queue.withTx?.(tx) ?? config.queue,
2594
+ hooks,
2595
+ flowHooks: config.hooks,
2596
+ dispatcher,
2597
+ emitLog
2598
+ });
4158
2599
  const signals = makeSignals({
4159
2600
  dispatcher,
4160
2601
  store: config.store,
@@ -4164,30 +2605,20 @@ async function nagiImpl(config) {
4164
2605
  emitLog,
4165
2606
  ...compact({ flowHooks: config.hooks })
4166
2607
  });
4167
- const replayer = makeReplay({
4168
- ...dispatchDeps,
4169
- registry,
4170
- hashFor: (id) => flowHashById.get(id)
4171
- });
2608
+ const replayer = makeReplay({ ...dispatchDeps, registry, driftPolicy });
4172
2609
  const wf = {
4173
2610
  async start(flow2, input, opts) {
4174
2611
  return wf.startById(flow2.id, input, opts);
4175
2612
  },
4176
2613
  async startById(flowId, input, opts) {
4177
- const flow2 = registry.require(flowId);
4178
- let runId;
4179
- if (opts?.runId !== void 0) {
4180
- if (typeof opts.runId !== "string" || opts.runId.length === 0) {
4181
- throw validationError("opts.runId must be a non-empty string", [
4182
- "runId"
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 });
2614
+ const { runId, staged } = await lifecycle.start({
2615
+ flowId,
2616
+ input,
2617
+ runId: opts?.runId,
2618
+ boundary: { kind: "own" }
2619
+ });
2620
+ if (staged.kind === "started")
2621
+ await lifecycle.applyEffects(staged.effects);
4191
2622
  return runId;
4192
2623
  },
4193
2624
  async startStaged(flow2, input, opts) {
@@ -4200,114 +2631,26 @@ async function nagiImpl(config) {
4200
2631
  ["tx"]
4201
2632
  );
4202
2633
  }
4203
- const flow2 = registry.require(flowId);
4204
- let runId;
4205
- if (opts.runId !== void 0) {
4206
- if (typeof opts.runId !== "string" || opts.runId.length === 0) {
4207
- throw validationError("opts.runId must be a non-empty string", [
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 })
2634
+ const { runId, staged } = await lifecycle.start({
2635
+ flowId,
2636
+ input,
2637
+ runId: opts.runId,
2638
+ boundary: { kind: "caller", tx: opts.tx }
4225
2639
  });
4226
- let concurrencyArg;
4227
- if (flow2.concurrency !== void 0) {
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
- }
2640
+ if (staged.kind === "exists") {
2641
+ return { runId, started: false, canceled: [], applyOnCommit: noop };
4252
2642
  }
4253
- let fired = false;
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
- };
2643
+ let applied;
4301
2644
  return {
4302
2645
  runId,
4303
- started,
4304
- canceled: canceled.map((c) => c.runId),
4305
- applyOnCommit
2646
+ started: true,
2647
+ canceled: staged.effects.superseded.map((e) => e.runId),
2648
+ applyOnCommit: () => applied ??= lifecycle.applyEffects(staged.effects)
4306
2649
  };
4307
2650
  },
4308
2651
  signal: signals.signal,
4309
2652
  async cancel(runId, opts) {
4310
- await cancelRunRecursive(runId, {
2653
+ await lifecycle.cancelRunRecursive(runId, {
4311
2654
  cause: "explicit",
4312
2655
  reason: opts?.reason ?? "explicit wf.cancel()"
4313
2656
  });
@@ -4318,7 +2661,7 @@ async function nagiImpl(config) {
4318
2661
  store: config.store,
4319
2662
  clock,
4320
2663
  registry,
4321
- cancelRunRecursive,
2664
+ cancelRunRecursive: lifecycle.cancelRunRecursive,
4322
2665
  emitLog
4323
2666
  });
4324
2667
  },
@@ -4398,12 +2741,6 @@ async function nagiImpl(config) {
4398
2741
  });
4399
2742
  }
4400
2743
  };
4401
- Object.defineProperty(wf, "__dispatchDeps", {
4402
- value: dispatchDeps,
4403
- enumerable: false,
4404
- writable: false,
4405
- configurable: false
4406
- });
4407
2744
  return wf;
4408
2745
  }
4409
2746
  async function nagiRun(config) {
@@ -4468,19 +2805,9 @@ var nagi = Object.assign(
4468
2805
  nagiImpl,
4469
2806
  { run: nagiRun }
4470
2807
  );
4471
- function mintRunId() {
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;
2808
+ async function noop() {
4482
2809
  }
4483
2810
 
4484
- export { DEFAULT_REAPER_INTERVAL_MS, InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiAbortError, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiValidationError, RunId, attemptOf, canonicalize, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, diffSnapshots, errorOf, fingerprintFlows, flow, isStepTerminal, isTerminalRun, nagi, optional, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, sha256Canonical, stepStateOf, stepStatusOf, unwrap };
2811
+ export { NagiAbortError, RunId, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, optional, sha256Canonical };
4485
2812
  //# sourceMappingURL=index.js.map
4486
2813
  //# sourceMappingURL=index.js.map