@nagi-js/core 0.1.1-rc.21 → 0.1.1-rc.23

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,11 +1,11 @@
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, NagiStepTimeoutError, peekDef, NagiNonRetryableError, normalizeNeeds } from './chunk-VU2LG4VW.js';
2
- export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, QUERY_RUNS_DEFAULT_LIMIT, QUERY_RUNS_MAX_LIMIT, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, attemptOf, clampQueryLimit, compareRunOrder, decideExpiredLeaseAction, decideSignal, decideTimeout, decodeRunCursor, defaultSnapshotGonePolicy, encodeRunCursor, errorOf, factEffects, isPastCursor, isStepTerminal, isTerminalRun, isTerminalRunEvent, jsonContains, outputOf, foldRun as projectRunState, resolvedOf, rowDeltaOf, runEventOf, runStatusOf, selectExpired, selectPruneBatch, stepStateOf, stepStatusOf, unwrap } from './chunk-VU2LG4VW.js';
1
+ import { InMemoryClock, makeEmit, registerFlows, fingerprintFlows, makeFlowOf, makeSignals, compact, validationError, NagiRuntimeError, NagiSnapshotDriftError, requireCurrent, serializeError, NagiSignalTimeoutError, validate, Facts, foldRun, stepStateOf, isStepTerminal, isTerminalRun, dequeueBackoff, defaultSnapshotGonePolicy, DEFAULT_REAPER_INTERVAL_MS, runStatusOf, runCancelCause, asStepMapWithDefs, needsStepIds, getDef, stepStatusOf, handlerDef, resolveRetry, isAbortRequested, resolveNeeds, stepBackoff, NagiCanceledError, NagiStepTimeoutError, peekDef, attachDef, NagiNonRetryableError, pinRun, normalizeNeeds } from './chunk-DPTPJZEG.js';
2
+ export { DEFAULT_REAPER_INTERVAL_MS, DEFAULT_SWEEP_LIMIT, InMemoryClock, InMemoryQueue, InMemoryRunEventHub, InMemoryStore, InMemoryStreamHub, NagiCanceledError, NagiConcurrencyConflictError, NagiFlowSnapshotGoneError, NagiNonRetryableError, NagiRuntimeError, NagiSignalTimeoutError, NagiSnapshotDriftError, NagiStepTimeoutError, NagiValidationError, STREAM_REPLAY_BUFFER_CAP, STREAM_SUBSCRIBER_BUFFER_CAP, admitsRunEnd, attemptOf, decideExpiredLeaseAction, decideSignal, decideTimeout, defaultSnapshotGonePolicy, errorOf, factConsequences, isRunEnd, isStepTerminal, isStreamOver, isTerminalRun, isTerminalRunEvent, outputOf, foldRun as projectRunState, resolvedOf, runStatusOf, selectExpired, selectPruneBatch, stepStateOf, stepStatusOf, supersede, unwrap } from './chunk-DPTPJZEG.js';
3
3
 
4
4
  // src/builder.ts
5
5
  function makeBuilder() {
6
- function task(config) {
6
+ function handler(kind, config) {
7
7
  const def = {
8
- kind: "task",
8
+ kind,
9
9
  needs: normalizeNeeds(config.needs),
10
10
  run: config.run,
11
11
  ...compact({
@@ -18,41 +18,7 @@ function makeBuilder() {
18
18
  onRetry: config.onRetry
19
19
  })
20
20
  };
21
- return attachDef({ kind: "task", id: "" }, def);
22
- }
23
- function activity(config) {
24
- const def = {
25
- kind: "activity",
26
- needs: normalizeNeeds(config.needs),
27
- run: config.run,
28
- ...compact({
29
- retry: config.retry,
30
- timeoutMs: config.timeoutMs,
31
- when: config.when,
32
- onStart: config.onStart,
33
- onComplete: config.onComplete,
34
- onError: config.onError,
35
- onRetry: config.onRetry
36
- })
37
- };
38
- return attachDef({ kind: "activity", id: "" }, def);
39
- }
40
- function streamingTask(config) {
41
- const def = {
42
- kind: "streaming",
43
- needs: normalizeNeeds(config.needs),
44
- run: config.run,
45
- ...compact({
46
- retry: config.retry,
47
- timeoutMs: config.timeoutMs,
48
- when: config.when,
49
- onStart: config.onStart,
50
- onComplete: config.onComplete,
51
- onError: config.onError,
52
- onRetry: config.onRetry
53
- })
54
- };
55
- return attachDef({ kind: "streaming", id: "" }, def);
21
+ return attachDef({ kind, id: "" }, def);
56
22
  }
57
23
  function signal(config) {
58
24
  const def = {
@@ -82,42 +48,18 @@ function makeBuilder() {
82
48
  def
83
49
  );
84
50
  }
85
- function match(config) {
86
- const needs = normalizeNeeds(config.needs);
87
- const arms = [];
88
- for (let i = 0; i < config.arms.length; i++) {
89
- const arm = config.arms[i];
90
- const nested = arm.build(makeBuilder());
91
- const guard = arm.otherwise ? { kind: "otherwise" } : { kind: "when", when: arm.when };
92
- const armId = guard.kind === "otherwise" ? "otherwise" : `arm${i}`;
93
- arms.push({ id: armId, guard, nested });
94
- }
95
- const def = { kind: "match", needs, arms };
96
- return attachDef({ kind: "match", id: "" }, def);
97
- }
98
51
  return {
99
- task,
100
- activity,
101
- streamingTask,
52
+ task: (config) => handler("task", config),
53
+ activity: (config) => handler("activity", config),
54
+ streamingTask: (config) => handler("streaming", config),
102
55
  signal,
103
- subflow,
104
- match
56
+ subflow
105
57
  };
106
58
  }
107
59
  function flow(config) {
108
60
  const builder = makeBuilder();
109
61
  const built = config.build(builder);
110
- const idByIdentity = /* @__PURE__ */ new Map();
111
- collectIds(built, "", idByIdentity);
112
- const finalSteps = {};
113
- walkAndRewrite({
114
- flowId: config.id,
115
- map: built,
116
- prefix: "",
117
- parentMatch: void 0,
118
- idByIdentity,
119
- out: finalSteps
120
- });
62
+ const finalSteps = rewriteSteps(config.id, built);
121
63
  assertSignalNameUniqueness(config.id, finalSteps);
122
64
  return {
123
65
  id: config.id,
@@ -148,23 +90,11 @@ function normalizeConcurrency(c) {
148
90
  mode: "cancel-in-progress"
149
91
  };
150
92
  }
151
- function collectIds(map, prefix, idByIdentity) {
152
- for (const [key, step] of Object.entries(map)) {
153
- const id = prefix ? `${prefix}.${key}` : key;
154
- idByIdentity.set(step, id);
155
- const def = peekDef(step);
156
- if (def?.kind === "match") {
157
- const pending = def;
158
- for (const arm of pending.arms) {
159
- collectIds(arm.nested, `${id}.${arm.id}`, idByIdentity);
160
- }
161
- }
162
- }
163
- }
164
- function walkAndRewrite(args) {
165
- const { flowId, map, prefix, parentMatch, idByIdentity, out } = args;
166
- for (const [key, step] of Object.entries(map)) {
167
- const id = prefix ? `${prefix}.${key}` : key;
93
+ function rewriteSteps(flowId, map) {
94
+ const idByIdentity = /* @__PURE__ */ new Map();
95
+ for (const [id, step] of Object.entries(map)) idByIdentity.set(step, id);
96
+ const out = {};
97
+ for (const [id, step] of Object.entries(map)) {
168
98
  const def = peekDef(step);
169
99
  if (def === void 0) {
170
100
  throw new Error(
@@ -191,45 +121,10 @@ function walkAndRewrite(args) {
191
121
  optional: ref.optional
192
122
  };
193
123
  }
194
- if (def.kind === "match") {
195
- const pending = def;
196
- const finalizedArms = [];
197
- for (const arm of pending.arms) {
198
- const armPrefix = `${id}.${arm.id}`;
199
- const nestedStepIds = [];
200
- for (const nestedKey of Object.keys(arm.nested)) {
201
- nestedStepIds.push(`${armPrefix}.${nestedKey}`);
202
- }
203
- walkAndRewrite({
204
- flowId,
205
- map: arm.nested,
206
- prefix: armPrefix,
207
- parentMatch: { matchId: id, armId: arm.id },
208
- idByIdentity,
209
- out
210
- });
211
- finalizedArms.push({
212
- id: arm.id,
213
- guard: arm.guard,
214
- stepIds: nestedStepIds
215
- });
216
- }
217
- const finalizedDef2 = {
218
- kind: "match",
219
- needs: rewrittenNeeds,
220
- arms: finalizedArms,
221
- ...compact({ parentMatch })
222
- };
223
- out[id] = attachDef({ kind: "match", id }, finalizedDef2);
224
- continue;
225
- }
226
- const finalizedDef = {
227
- ...def,
228
- needs: rewrittenNeeds,
229
- ...compact({ parentMatch })
230
- };
124
+ const finalizedDef = { ...def, needs: rewrittenNeeds };
231
125
  out[id] = attachDef({ kind: finalizedDef.kind, id }, finalizedDef);
232
126
  }
127
+ return out;
233
128
  }
234
129
  function assertSignalNameUniqueness(flowId, finalSteps) {
235
130
  const owners = /* @__PURE__ */ new Map();
@@ -254,246 +149,6 @@ function assertSignalNameUniqueness(flowId, finalSteps) {
254
149
  }
255
150
  }
256
151
 
257
- // src/canonicalize.ts
258
- var warnedAboutSourceHash = false;
259
- function warnSourceHashOnce() {
260
- if (warnedAboutSourceHash) return;
261
- warnedAboutSourceHash = true;
262
- console.warn(
263
- "[nagi] canonicalize: hashing `when`/schema source via Function.prototype.toString(). Cosmetic source changes (minification, whitespace, identifier renames) will flip the flow hash even when behavior is unchanged."
264
- );
265
- }
266
- async function canonicalize(flow2) {
267
- const withDefs = asStepMapWithDefs(flow2.steps);
268
- const ids = Object.keys(withDefs).sort();
269
- const steps = [];
270
- for (const id of ids) {
271
- const step = withDefs[id];
272
- if (step === void 0) continue;
273
- steps.push(await canonicalizeStep(id, getDef(step)));
274
- }
275
- return {
276
- flowId: flow2.id,
277
- inputSchema: await canonicalizeSchema(flow2.input),
278
- steps
279
- };
280
- }
281
- async function canonicalizeStep(id, def) {
282
- const needs = [...needsStepIds(def)].sort();
283
- const base = { id, kind: def.kind, needs };
284
- if (def.kind === "task" || def.kind === "activity" || def.kind === "streaming")
285
- return canonicalizeTask(base, def);
286
- if (def.kind === "signal") return canonicalizeSignal(base, def);
287
- if (def.kind === "subflow") return canonicalizeSubflow(base, def);
288
- return canonicalizeMatch(base, def);
289
- }
290
- async function applyGuardAndTimeout(out, def) {
291
- if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
292
- if (def.timeoutMs !== void 0 && def.timeoutMs !== "unbounded")
293
- out.timeoutMs = def.timeoutMs;
294
- }
295
- async function canonicalizeTask(base, def) {
296
- const out = { ...base };
297
- await applyGuardAndTimeout(out, def);
298
- if (def.retry !== void 0) out.retry = normalizeRetry(def.retry);
299
- return out;
300
- }
301
- async function canonicalizeSignal(base, def) {
302
- const out = { ...base };
303
- await applyGuardAndTimeout(out, def);
304
- out.signalSchema = await canonicalizeSchema(def.schema);
305
- if (def.names !== void 0) {
306
- out.signalNames = [...def.names].sort();
307
- }
308
- return out;
309
- }
310
- async function canonicalizeSubflow(base, def) {
311
- const out = { ...base };
312
- await applyGuardAndTimeout(out, def);
313
- out.childFlowId = def.childFlowId;
314
- out.subflowInputHash = await hashFnSource(def.buildInput);
315
- return out;
316
- }
317
- async function canonicalizeMatch(base, def) {
318
- const out = { ...base };
319
- const arms = [];
320
- for (const arm of def.arms) {
321
- arms.push(await canonicalizeArm(arm));
322
- }
323
- out.matchArms = arms;
324
- return out;
325
- }
326
- async function canonicalizeArm(arm) {
327
- const out = {
328
- id: arm.id,
329
- stepIds: [...arm.stepIds].sort()
330
- };
331
- if (arm.guard.kind === "otherwise") out.otherwise = true;
332
- else out.whenHash = await hashFnSource(arm.guard.when);
333
- return out;
334
- }
335
- function normalizeRetry(retry) {
336
- return {
337
- maxAttempts: retry.maxAttempts,
338
- backoff: retry.backoff,
339
- initialDelayMs: retry.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs,
340
- maxDelayMs: retry.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs
341
- };
342
- }
343
- async function canonicalizeSchema(schema) {
344
- const props = schema["~standard"];
345
- return {
346
- vendor: props.vendor,
347
- version: props.version,
348
- validateHash: await hashFnSource(props.validate)
349
- };
350
- }
351
- async function hashFnSource(fn) {
352
- warnSourceHashOnce();
353
- return sha256Hex(fn.toString());
354
- }
355
- async function sha256Canonical(dag) {
356
- return sha256Hex(stableStringify(dag));
357
- }
358
- async function fingerprintFlows(flows) {
359
- const entries = [];
360
- for (const f of flows) {
361
- const dag = await canonicalize(f);
362
- entries.push([f.id, await sha256Canonical(dag)]);
363
- }
364
- entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
365
- return sha256Hex(stableStringify(entries));
366
- }
367
- function stableStringify(value) {
368
- if (value === void 0) return "null";
369
- if (value === null || typeof value !== "object") return JSON.stringify(value);
370
- if (Array.isArray(value)) {
371
- return `[${value.map(stableStringify).join(",")}]`;
372
- }
373
- const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
374
- return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
375
- }
376
- async function sha256Hex(input) {
377
- const bytes = new TextEncoder().encode(input);
378
- const digest = await crypto.subtle.digest("SHA-256", bytes);
379
- return hex(new Uint8Array(digest));
380
- }
381
- function hex(bytes) {
382
- let s = "";
383
- for (let i = 0; i < bytes.length; i++) {
384
- s += bytes[i].toString(16).padStart(2, "0");
385
- }
386
- return s;
387
- }
388
-
389
- // src/diff.ts
390
- function diffSnapshots(before, after) {
391
- const beforeStepsById = new Map(before.steps.map((s) => [s.id, s]));
392
- const afterStepsById = new Map(after.steps.map((s) => [s.id, s]));
393
- const addedSteps = [];
394
- const removedSteps = [];
395
- for (const id of afterStepsById.keys()) {
396
- if (!beforeStepsById.has(id)) addedSteps.push(id);
397
- }
398
- for (const id of beforeStepsById.keys()) {
399
- if (!afterStepsById.has(id)) removedSteps.push(id);
400
- }
401
- addedSteps.sort();
402
- removedSteps.sort();
403
- const changedEdges = [];
404
- const changedPredicates = [];
405
- for (const id of afterStepsById.keys()) {
406
- const beforeStep = beforeStepsById.get(id);
407
- const afterStep = afterStepsById.get(id);
408
- if (beforeStep === void 0 || afterStep === void 0) continue;
409
- diffEdges(id, beforeStep, afterStep, changedEdges);
410
- diffFields(beforeStep, afterStep, changedPredicates);
411
- }
412
- changedEdges.sort(
413
- (a, b) => a.to !== b.to ? cmp(a.to, b.to) : cmp(a.from, b.from)
414
- );
415
- changedPredicates.sort(
416
- (a, b) => a.stepId !== b.stepId ? cmp(a.stepId, b.stepId) : cmp(a.field, b.field)
417
- );
418
- return { addedSteps, removedSteps, changedEdges, changedPredicates };
419
- }
420
- function diffEdges(stepId, before, after, out) {
421
- const beforeSet = new Set(before.needs);
422
- const afterSet = new Set(after.needs);
423
- for (const upstream of afterSet) {
424
- if (!beforeSet.has(upstream)) {
425
- out.push({
426
- from: upstream,
427
- to: stepId,
428
- before: "absent",
429
- after: "needed"
430
- });
431
- }
432
- }
433
- for (const upstream of beforeSet) {
434
- if (!afterSet.has(upstream)) {
435
- out.push({
436
- from: upstream,
437
- to: stepId,
438
- before: "needed",
439
- after: "absent"
440
- });
441
- }
442
- }
443
- }
444
- function diffFields(before, after, out) {
445
- const id = after.id;
446
- if (before.kind !== after.kind) {
447
- out.push({ stepId: id, field: "kind" });
448
- }
449
- if (before.whenHash !== after.whenHash) {
450
- out.push({ stepId: id, field: "when" });
451
- }
452
- if (!retryEq(before.retry, after.retry)) {
453
- out.push({ stepId: id, field: "retry" });
454
- }
455
- if (before.timeoutMs !== after.timeoutMs) {
456
- out.push({ stepId: id, field: "timeoutMs" });
457
- }
458
- if (!schemaEq(before.signalSchema, after.signalSchema)) {
459
- out.push({ stepId: id, field: "signalSchema" });
460
- }
461
- if (!armsEq(before.matchArms, after.matchArms)) {
462
- out.push({ stepId: id, field: "matchArms" });
463
- }
464
- }
465
- function retryEq(a, b) {
466
- if (a === b) return true;
467
- if (a === void 0 || b === void 0) return false;
468
- return a.maxAttempts === b.maxAttempts && a.backoff === b.backoff && a.initialDelayMs === b.initialDelayMs && a.maxDelayMs === b.maxDelayMs;
469
- }
470
- function schemaEq(a, b) {
471
- if (a === b) return true;
472
- if (a === void 0 || b === void 0) return false;
473
- return a.vendor === b.vendor && a.version === b.version && a.validateHash === b.validateHash;
474
- }
475
- function armsEq(a, b) {
476
- if (a === b) return true;
477
- if (a === void 0 || b === void 0) return false;
478
- if (a.length !== b.length) return false;
479
- for (let i = 0; i < a.length; i++) {
480
- const x = a[i];
481
- const y = b[i];
482
- if (x === void 0 || y === void 0) return false;
483
- if (x.id !== y.id) return false;
484
- if (x.otherwise !== y.otherwise) return false;
485
- if (x.whenHash !== y.whenHash) return false;
486
- if (x.stepIds.length !== y.stepIds.length) return false;
487
- for (let j = 0; j < x.stepIds.length; j++) {
488
- if (x.stepIds[j] !== y.stepIds[j]) return false;
489
- }
490
- }
491
- return true;
492
- }
493
- function cmp(a, b) {
494
- return a < b ? -1 : a > b ? 1 : 0;
495
- }
496
-
497
152
  // src/run-id.ts
498
153
  var RunId = {
499
154
  parse(s) {
@@ -522,17 +177,17 @@ async function deriveChildRunId(key) {
522
177
  const bytes = new Uint8Array(digest).subarray(0, 16);
523
178
  bytes[6] = (bytes[6] ?? 0) & 15 | 80;
524
179
  bytes[8] = (bytes[8] ?? 0) & 63 | 128;
525
- const hex2 = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
180
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
526
181
  ""
527
182
  );
528
- const uuid = `${hex2.slice(0, 8)}-${hex2.slice(8, 12)}-${hex2.slice(12, 16)}-${hex2.slice(16, 20)}-${hex2.slice(20, 32)}`;
183
+ const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
529
184
  return `run-${uuid}`;
530
185
  }
531
186
 
532
187
  // src/exec/hooks.ts
533
188
  function makeHooks(deps) {
534
189
  async function fireHook(hook, event, hookName) {
535
- if (deps.fireHooks === false) return;
190
+ if (!deps.fireHooks) return;
536
191
  if (hook === void 0) return;
537
192
  try {
538
193
  await hook(event);
@@ -552,197 +207,6 @@ function makeHooks(deps) {
552
207
  return { fireHook, fireStepLifecycle };
553
208
  }
554
209
 
555
- // src/scheduler.ts
556
- function nextRunnable({
557
- flow: flow2,
558
- runState,
559
- input
560
- }) {
561
- const runnable = [];
562
- const skip = [];
563
- for (const [stepId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
564
- if (stepStateOf(runState, stepId).tag !== "pending") continue;
565
- const gate = gateStep(getDef(step), runState, input);
566
- switch (gate.kind) {
567
- case "run":
568
- runnable.push(stepId);
569
- break;
570
- case "skip":
571
- skip.push({ stepId, reason: gate.reason });
572
- break;
573
- }
574
- }
575
- return { runnable, skip };
576
- }
577
- function gateStep(def, runState, input) {
578
- const parent = checkParentMatch(def, runState);
579
- if (parent !== "ready") return gateFor(parent);
580
- const upstream = checkUpstream(def, runState);
581
- if (upstream !== "ready") return gateFor(upstream);
582
- const when = def.kind === "match" ? void 0 : def.when;
583
- if (when) {
584
- const needs = resolveNeeds(
585
- def,
586
- (id) => resolvedOf(stepStateOf(runState, id))
587
- );
588
- if (!when({ input, needs })) return { kind: "skip", reason: "when-false" };
589
- }
590
- return { kind: "run" };
591
- }
592
- function gateFor(status) {
593
- switch (status) {
594
- case "blocked":
595
- return { kind: "block" };
596
- case "transitive-skip":
597
- return { kind: "skip", reason: "transitive" };
598
- }
599
- }
600
- function checkUpstream(def, runState) {
601
- for (const ref of Object.values(def.needs)) {
602
- const upstreamState = stepStateOf(runState, ref.step.id);
603
- if (upstreamState.tag === "completed") continue;
604
- if (ref.optional && upstreamState.tag === "skipped") continue;
605
- if (upstreamState.tag === "skipped" || upstreamState.tag === "failed") {
606
- return "transitive-skip";
607
- }
608
- return "blocked";
609
- }
610
- return "ready";
611
- }
612
- function checkParentMatch(def, runState) {
613
- if (!def.parentMatch) return "ready";
614
- const { matchId, armId } = def.parentMatch;
615
- const parentState = stepStateOf(runState, matchId);
616
- if (parentState.tag === "failed" || parentState.tag === "skipped") {
617
- return "transitive-skip";
618
- }
619
- const selected = runState.selectedArms[matchId] ?? null;
620
- if (selected === null) return "blocked";
621
- return selected === armId ? "ready" : "transitive-skip";
622
- }
623
- function aggregateMatch(matchId, flow2, runState) {
624
- const step = asStepMapWithDefs(flow2.steps)[matchId];
625
- if (!step) return { kind: "pending" };
626
- const def = getDef(step);
627
- if (def.kind !== "match") return { kind: "pending" };
628
- const selected = runState.selectedArms[matchId] ?? null;
629
- if (selected === null) return { kind: "pending" };
630
- const arm = def.arms.find((a) => a.id === selected);
631
- if (!arm) return { kind: "pending" };
632
- for (const stepId of arm.stepIds) {
633
- const state = stepStateOf(runState, stepId);
634
- if (state.tag === "failed")
635
- return { kind: "fail-fast", error: state.error };
636
- }
637
- const output = {};
638
- for (const stepId of arm.stepIds) {
639
- const state = stepStateOf(runState, stepId);
640
- if (!isStepTerminal(state)) return { kind: "pending" };
641
- output[stripArmPrefix(matchId, arm.id, stepId)] = outputOf(state);
642
- }
643
- return { kind: "complete", output };
644
- }
645
- function stripArmPrefix(matchId, armId, stepId) {
646
- const prefix = `${matchId}.${armId}.`;
647
- if (stepId.startsWith(prefix)) return stepId.slice(prefix.length);
648
- return stepId;
649
- }
650
- function flowTermination(flow2, runState) {
651
- let failure;
652
- for (const stepId of Object.keys(flow2.steps)) {
653
- const state = stepStateOf(runState, stepId);
654
- if (!isStepTerminal(state)) return { kind: "running" };
655
- if (state.tag === "failed" && failure === void 0) failure = state.error;
656
- }
657
- if (failure !== void 0) return { kind: "failed", error: failure };
658
- return { kind: "succeeded" };
659
- }
660
- function nextTransition(flow2, runState) {
661
- const promotions = readyPromotions(flow2, runState);
662
- if (promotions.length > 0) return { kind: "promote-match", promotions };
663
- const term = flowTermination(flow2, runState);
664
- switch (term.kind) {
665
- case "succeeded":
666
- case "failed": {
667
- if (isTerminalRun(runState)) return { kind: "settled" };
668
- if (term.kind === "failed") return { kind: "fail", error: term.error };
669
- return { kind: "complete", output: computeFlowOutput(flow2, runState) };
670
- }
671
- }
672
- const input = runState.input;
673
- const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
674
- if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
675
- if (skip.length > 0) return { kind: "skip", skip };
676
- return { kind: "waiting" };
677
- }
678
- function readyPromotions(flow2, runState) {
679
- const out = [];
680
- for (const [matchId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
681
- const def = getDef(step);
682
- if (def.kind !== "match") continue;
683
- const state = stepStateOf(runState, matchId);
684
- if (state.tag !== "running") continue;
685
- const agg = aggregateMatch(matchId, flow2, runState);
686
- if (agg.kind === "pending") continue;
687
- const attempt = attemptOf(state);
688
- if (agg.kind === "fail-fast") {
689
- out.push({
690
- matchId,
691
- attempt,
692
- result: { kind: "fail", error: agg.error }
693
- });
694
- } else {
695
- out.push({
696
- matchId,
697
- attempt,
698
- result: { kind: "complete", output: agg.output }
699
- });
700
- }
701
- }
702
- return out;
703
- }
704
- function computeFlowOutput(flow2, runState) {
705
- if (flow2.output === void 0) return null;
706
- const stepOutputs = {};
707
- for (const [sid, sstate] of Object.entries(runState.steps)) {
708
- if (sstate.tag === "completed") stepOutputs[sid] = sstate.output;
709
- }
710
- return flow2.output(stepOutputs);
711
- }
712
- function resetSetOf(flow2, stepId, scope) {
713
- return scope === "step" ? [stepId] : descendantsOf(flow2, stepId);
714
- }
715
- function descendantsOf(flow2, stepId) {
716
- const children = /* @__PURE__ */ new Map();
717
- const addEdge = (from, to) => {
718
- const bucket = children.get(from);
719
- if (bucket) bucket.push(to);
720
- else children.set(from, [to]);
721
- };
722
- for (const [id, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
723
- const def = getDef(step);
724
- for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
725
- if (def.kind === "match") {
726
- for (const arm of def.arms) {
727
- for (const armStepId of arm.stepIds) addEdge(id, armStepId);
728
- }
729
- }
730
- }
731
- const out = [stepId];
732
- const seen = /* @__PURE__ */ new Set([stepId]);
733
- for (let i = 0; i < out.length; i++) {
734
- const current = out[i];
735
- if (current === void 0) continue;
736
- for (const child of children.get(current) ?? []) {
737
- if (seen.has(child)) continue;
738
- if (!(child in flow2.steps)) continue;
739
- seen.add(child);
740
- out.push(child);
741
- }
742
- }
743
- return out;
744
- }
745
-
746
210
  // src/idempotency.ts
747
211
  function makeIdempotencyKey(runId, stepId) {
748
212
  return (scope) => `nagi:${runId}:${stepId}:${scope}`;
@@ -754,7 +218,7 @@ function makeOnce({
754
218
  }) {
755
219
  return async function once(scope, fn) {
756
220
  const cached = await store.getOnce(runId, stepId, scope);
757
- if (cached !== null) return cached;
221
+ if (cached.tag === "hit") return cached.value;
758
222
  const value = await fn();
759
223
  await store.recordOnce(runId, stepId, scope, value);
760
224
  return value;
@@ -768,7 +232,7 @@ var NagiAbortError = class extends Error {
768
232
  kind;
769
233
  constructor(runId, kind) {
770
234
  super(
771
- kind === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
235
+ kind === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by replay({ from }) \u2014 ctx.signal aborted.`
772
236
  );
773
237
  this.name = "AbortError";
774
238
  this.runId = runId;
@@ -794,33 +258,49 @@ function resolveExecutionFact(args) {
794
258
  abortedHere: false
795
259
  };
796
260
  }
797
- function startCancelWatcher(args) {
798
- const { store, runId, stepId, attempt, ac, intervalMs } = args;
261
+ function every(intervalMs, tick) {
799
262
  let stopped = false;
800
- void (async () => {
801
- while (!stopped) {
802
- await new Promise((r) => setTimeout(r, intervalMs));
803
- if (stopped) return;
804
- try {
805
- const s = await store.loadRunState(runId);
806
- if (isTerminalRun(s)) {
807
- if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
808
- return;
809
- }
810
- if (isAbortRequested(stepStateOf(s, stepId), attempt)) {
811
- if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
812
- return;
263
+ let timer;
264
+ let running = Promise.resolve();
265
+ const schedule = () => {
266
+ timer = setTimeout(() => {
267
+ running = (async () => {
268
+ let next;
269
+ try {
270
+ next = await tick();
271
+ } catch {
813
272
  }
814
- } catch {
815
- }
816
- }
817
- })();
273
+ if (!stopped && next !== "stop") schedule();
274
+ })();
275
+ }, intervalMs);
276
+ };
277
+ schedule();
818
278
  return {
819
- stop: () => {
279
+ stop: async () => {
820
280
  stopped = true;
281
+ clearTimeout(timer);
282
+ await running;
821
283
  }
822
284
  };
823
285
  }
286
+ function startCancelWatcher(args) {
287
+ const { store, runId, stepId, attempt, ac, intervalMs } = args;
288
+ return every(intervalMs, async () => {
289
+ try {
290
+ const s = await store.loadRunState(runId);
291
+ if (isTerminalRun(s)) {
292
+ if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
293
+ return "stop";
294
+ }
295
+ if (isAbortRequested(stepStateOf(s, stepId), attempt)) {
296
+ if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
297
+ return "stop";
298
+ }
299
+ } catch {
300
+ }
301
+ return void 0;
302
+ });
303
+ }
824
304
  function startDeadline(args) {
825
305
  const { runId, stepId, attempt, timeoutMs, ac } = args;
826
306
  const timer = setTimeout(() => {
@@ -846,59 +326,43 @@ function startHeartbeat(args) {
846
326
  attempt,
847
327
  receipt,
848
328
  intervalMs,
849
- leaseMs,
850
- holdWarnMs,
851
- emitLog
852
- } = args;
853
- let stopped = false;
854
- let timer;
855
- const startedAtMs = Date.now();
856
- let warnedCrossings = 0;
857
- const schedule = () => {
858
- timer = setTimeout(() => {
859
- void (async () => {
860
- if (holdWarnMs > 0) {
861
- const heldMs = Date.now() - startedAtMs;
862
- const crossings = Math.floor(heldMs / holdWarnMs);
863
- if (crossings > warnedCrossings) {
864
- warnedCrossings = crossings;
865
- emitLog({
866
- level: "warn",
867
- msg: "heartbeat: step is holding a worker slot unusually long \u2014 slow handler, or an in-step wait that should be a b.signal step?",
868
- attrs: { runId, stepId, attempt, heldMs }
869
- });
870
- }
871
- }
872
- await Promise.all([
873
- queue.extend(receipt, leaseMs).catch((err) => {
874
- emitLog({
875
- level: "warn",
876
- msg: "heartbeat: failed to extend message visibility",
877
- attrs: { receipt, error: String(err) }
878
- });
879
- }),
880
- store.extendLease(runId, stepId, attempt, leaseMs).catch((err) => {
881
- emitLog({
882
- level: "warn",
883
- msg: "heartbeat: failed to extend store lease",
884
- attrs: { runId, stepId, attempt, error: String(err) }
885
- });
886
- })
887
- ]);
888
- if (!stopped) schedule();
889
- })();
890
- }, intervalMs);
891
- };
892
- schedule();
893
- return {
894
- // Clear the pending timer so a settled step strands nothing on the event
895
- // loop — without this every fast step would leak a timer for up to
896
- // intervalMs, keeping the process alive and delaying clean shutdown.
897
- stop: () => {
898
- stopped = true;
899
- if (timer !== void 0) clearTimeout(timer);
329
+ leaseMs,
330
+ holdWarnMs,
331
+ emitLog
332
+ } = args;
333
+ const startedAtMs = Date.now();
334
+ let warnedCrossings = 0;
335
+ return every(intervalMs, async () => {
336
+ if (holdWarnMs > 0) {
337
+ const heldMs = Date.now() - startedAtMs;
338
+ const crossings = Math.floor(heldMs / holdWarnMs);
339
+ if (crossings > warnedCrossings) {
340
+ warnedCrossings = crossings;
341
+ emitLog({
342
+ level: "warn",
343
+ msg: "heartbeat: step is holding a worker slot unusually long \u2014 slow handler, or an in-step wait that should be a b.signal step?",
344
+ attrs: { runId, stepId, attempt, heldMs }
345
+ });
346
+ }
900
347
  }
901
- };
348
+ await Promise.all([
349
+ queue.extend(receipt, leaseMs).catch((err) => {
350
+ emitLog({
351
+ level: "warn",
352
+ msg: "heartbeat: failed to extend message visibility",
353
+ attrs: { receipt, error: String(err) }
354
+ });
355
+ }),
356
+ store.extendLease(runId, stepId, attempt, leaseMs).catch((err) => {
357
+ emitLog({
358
+ level: "warn",
359
+ msg: "heartbeat: failed to extend store lease",
360
+ attrs: { runId, stepId, attempt, error: String(err) }
361
+ });
362
+ })
363
+ ]);
364
+ return void 0;
365
+ });
902
366
  }
903
367
  function classifyFailure(args) {
904
368
  const { attempt, policy, err, runIsCanceled, stepAborted } = args;
@@ -977,19 +441,23 @@ function makeActivityCtx(args) {
977
441
  }
978
442
 
979
443
  // src/exec/message.ts
980
- function subflowGeneration(state, stepId) {
981
- let n = 0;
982
- for (const f of state.facts) {
983
- if (f.kind === "step.reset" && f.stepId === stepId) n++;
444
+ function startInput(def, input) {
445
+ switch (def.kind) {
446
+ case "task":
447
+ case "activity":
448
+ case "streaming":
449
+ case "subflow":
450
+ return input;
451
+ case "signal":
452
+ return null;
984
453
  }
985
- return n;
986
454
  }
987
455
  function makeMessage(deps, hooks, progression) {
988
456
  const { fireHook, fireStepLifecycle } = hooks;
989
457
  const { advance } = progression;
990
458
  async function dispatchMessage(message) {
991
459
  const { queue } = deps;
992
- const resolution = await deps.resolveFlow(message.runId);
460
+ const resolution = await deps.flowOf(message.runId);
993
461
  let flow2;
994
462
  switch (resolution.kind) {
995
463
  case "current":
@@ -1035,7 +503,7 @@ function makeMessage(deps, hooks, progression) {
1035
503
  } catch (err) {
1036
504
  outcome = await handleStepError({ flow: flow2, message, def, err });
1037
505
  } finally {
1038
- heartbeat.stop();
506
+ await heartbeat.stop();
1039
507
  }
1040
508
  await interpret({ flow: flow2, message, def, startedAt, outcome });
1041
509
  await queue.ack(message.receipt);
@@ -1080,8 +548,7 @@ function makeMessage(deps, hooks, progression) {
1080
548
  new Date(startedAt.getTime() + def.timeoutMs)
1081
549
  );
1082
550
  }
1083
- const startCarriesInput = def.kind === "task" || def.kind === "activity" || def.kind === "streaming" || def.kind === "subflow";
1084
- const input = startCarriesInput ? state.input : null;
551
+ const input = startInput(def, state.input);
1085
552
  await fireStepLifecycle(
1086
553
  handler?.onStart,
1087
554
  deps.hooks?.onStepStart,
@@ -1102,26 +569,9 @@ function makeMessage(deps, hooks, progression) {
1102
569
  const { runId, stepId, attempt } = message;
1103
570
  switch (def.kind) {
1104
571
  case "task":
1105
- case "streaming": {
1106
- const { output, skipAdvance } = await executeTask({
1107
- def,
1108
- runId,
1109
- stepId,
1110
- attempt,
1111
- state
1112
- });
1113
- return skipAdvance ? { tag: "parked" } : { tag: "completed", output };
1114
- }
1115
- case "activity": {
1116
- const { output, skipAdvance } = await executeActivity({
1117
- def,
1118
- runId,
1119
- stepId,
1120
- attempt,
1121
- state
1122
- });
1123
- return skipAdvance ? { tag: "parked" } : { tag: "completed", output };
1124
- }
572
+ case "activity":
573
+ case "streaming":
574
+ return await executeHandler({ def, runId, stepId, attempt, state });
1125
575
  case "signal": {
1126
576
  const settled = await deps.store.settleSignal({
1127
577
  runId,
@@ -1146,11 +596,8 @@ function makeMessage(deps, hooks, progression) {
1146
596
  }
1147
597
  return { tag: "parked" };
1148
598
  }
1149
- case "match":
1150
- await executeMatch({ def, runId, stepId, state });
1151
- return { tag: "advance" };
1152
599
  case "subflow":
1153
- return await executeSubflow({ def, runId, stepId, attempt, state });
600
+ return await executeSubflow({ def, runId, stepId, state });
1154
601
  }
1155
602
  }
1156
603
  async function interpret(args) {
@@ -1182,34 +629,25 @@ function makeMessage(deps, hooks, progression) {
1182
629
  return;
1183
630
  }
1184
631
  }
1185
- async function runHandler(def, args) {
1186
- const { input, needs, ctx, runId, stepId } = args;
1187
- if (def.kind !== "streaming") {
1188
- return await def.run({ input, needs, ctx });
1189
- }
632
+ async function withEmit(runId, stepId, base, body) {
1190
633
  let emitActive = true;
1191
- const streamingCtx = {
1192
- ...ctx,
1193
- emit: async (chunk) => {
1194
- if (emitActive)
1195
- deps.streamTransport?.publishChunk(runId, stepId, chunk);
1196
- }
1197
- };
1198
634
  try {
1199
- return await def.run({
1200
- input,
1201
- needs,
1202
- ctx: streamingCtx
635
+ return await body({
636
+ ...base,
637
+ emit: async (chunk) => {
638
+ if (emitActive)
639
+ deps.streamTransport?.publishChunk(runId, stepId, chunk);
640
+ }
1203
641
  });
1204
642
  } finally {
1205
643
  emitActive = false;
1206
644
  }
1207
645
  }
1208
- async function executeTask(args) {
646
+ async function executeHandler(args) {
1209
647
  const { def, runId, stepId, attempt, state } = args;
1210
648
  const { store, clock } = deps;
1211
649
  const input = state.input;
1212
- const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
650
+ const needs = resolveNeeds(def, state);
1213
651
  const ac = new AbortController();
1214
652
  const watcher = startCancelWatcher({
1215
653
  store,
@@ -1217,7 +655,7 @@ function makeMessage(deps, hooks, progression) {
1217
655
  stepId,
1218
656
  attempt,
1219
657
  ac,
1220
- intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
658
+ intervalMs: CANCEL_POLL_INTERVAL_MS
1221
659
  });
1222
660
  const deadline = def.timeoutMs === void 0 ? void 0 : startDeadline({
1223
661
  runId,
@@ -1226,121 +664,83 @@ function makeMessage(deps, hooks, progression) {
1226
664
  timeoutMs: def.timeoutMs,
1227
665
  ac
1228
666
  });
1229
- try {
1230
- let stepAbortedHere = false;
1231
- const output = await store.runStep(
1232
- runId,
1233
- stepId,
1234
- attempt,
1235
- async (tx) => {
1236
- const ctx = makeStepCtx({
1237
- runId,
1238
- stepId,
1239
- attempt,
1240
- input,
1241
- store,
1242
- clock,
1243
- tx,
1244
- signal: ac.signal,
1245
- emitLog: deps.emitLog
1246
- });
1247
- const out = await runHandler(def, {
1248
- input,
1249
- needs,
1250
- ctx,
1251
- runId,
1252
- stepId
1253
- });
1254
- const postState = await store.loadRunState(runId);
1255
- const { fact, abortedHere } = resolveExecutionFact({
1256
- postState,
1257
- runId,
1258
- stepId,
1259
- attempt,
1260
- output: out,
1261
- at: clock.now()
1262
- });
1263
- stepAbortedHere = abortedHere;
1264
- return { output: out, fact };
1265
- }
1266
- );
1267
- return { output, skipAdvance: stepAbortedHere };
1268
- } catch (err) {
1269
- throw unwrapDeadline(err, ac.signal);
1270
- } finally {
1271
- watcher.stop();
1272
- deadline?.stop();
1273
- }
1274
- }
1275
- async function executeActivity(args) {
1276
- const { def, runId, stepId, attempt, state } = args;
1277
- const { store, clock } = deps;
1278
- const input = state.input;
1279
- const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
1280
- const ac = new AbortController();
1281
- const watcher = startCancelWatcher({
1282
- store,
1283
- runId,
1284
- stepId,
1285
- attempt,
1286
- ac,
1287
- intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
1288
- });
1289
- const deadline = def.timeoutMs === void 0 ? void 0 : startDeadline({
667
+ const ctxArgs = {
1290
668
  runId,
1291
669
  stepId,
1292
670
  attempt,
1293
- timeoutMs: def.timeoutMs,
1294
- ac
1295
- });
1296
- try {
1297
- const ctx = makeActivityCtx({
671
+ input,
672
+ store,
673
+ clock,
674
+ signal: ac.signal,
675
+ emitLog: deps.emitLog
676
+ };
677
+ let abortedHere = false;
678
+ const settle = async (output) => {
679
+ const resolved = resolveExecutionFact({
680
+ postState: await store.loadRunState(runId),
1298
681
  runId,
1299
682
  stepId,
1300
683
  attempt,
1301
- input,
1302
- store,
1303
- clock,
1304
- signal: ac.signal,
1305
- emitLog: deps.emitLog
684
+ output,
685
+ at: clock.now()
1306
686
  });
1307
- const out = await runHandler(def, { input, needs, ctx, runId, stepId });
1308
- let stepAbortedHere = false;
1309
- const output = await store.runStep(
1310
- runId,
1311
- stepId,
1312
- attempt,
1313
- async () => {
1314
- const postState = await store.loadRunState(runId);
1315
- const { fact, abortedHere } = resolveExecutionFact({
1316
- postState,
687
+ abortedHere = resolved.abortedHere;
688
+ return { output, fact: resolved.fact };
689
+ };
690
+ const inTx = (body) => store.runStep(
691
+ runId,
692
+ stepId,
693
+ attempt,
694
+ async (tx) => settle(await body(makeStepCtx({ ...ctxArgs, tx })))
695
+ );
696
+ try {
697
+ let output;
698
+ switch (def.kind) {
699
+ case "task":
700
+ output = await inTx((ctx) => def.run({ input, needs, ctx }));
701
+ break;
702
+ case "streaming":
703
+ output = await inTx(
704
+ (base) => withEmit(
705
+ runId,
706
+ stepId,
707
+ base,
708
+ (ctx) => def.run({ input, needs, ctx })
709
+ )
710
+ );
711
+ break;
712
+ // The body runs OUTSIDE the durable transaction (RFC 0013): an external
713
+ // effect must not hold a tx for minutes. Only the terminal fact commits,
714
+ // in a short runStep tx, through the same settle as a task.
715
+ case "activity": {
716
+ const ctx = makeActivityCtx(ctxArgs);
717
+ const out = await def.run({ input, needs, ctx });
718
+ output = await store.runStep(
1317
719
  runId,
1318
720
  stepId,
1319
721
  attempt,
1320
- output: out,
1321
- at: clock.now()
1322
- });
1323
- stepAbortedHere = abortedHere;
1324
- return { output: out, fact };
722
+ () => settle(out)
723
+ );
724
+ break;
1325
725
  }
1326
- );
1327
- return { output, skipAdvance: stepAbortedHere };
726
+ }
727
+ return abortedHere ? { tag: "parked" } : { tag: "completed", output };
1328
728
  } catch (err) {
1329
729
  throw unwrapDeadline(err, ac.signal);
1330
730
  } finally {
1331
- watcher.stop();
731
+ await watcher.stop();
1332
732
  deadline?.stop();
1333
733
  }
1334
734
  }
1335
735
  async function executeSubflow(args) {
1336
- const { def, runId, stepId, attempt, state } = args;
736
+ const { def, runId, stepId, state } = args;
1337
737
  const child = deps.lookupFlow(def.childFlowId);
1338
738
  if (child === void 0) {
1339
739
  throw new Error(
1340
740
  `Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
1341
741
  );
1342
742
  }
1343
- const generation = subflowGeneration(state, stepId);
743
+ const generation = state.resetCounts[stepId] ?? 0;
1344
744
  const childRunId = await deriveChildRunId({ runId, stepId, generation });
1345
745
  const childState = await deps.store.loadRunState(childRunId);
1346
746
  if (isTerminalRun(childState)) {
@@ -1348,27 +748,16 @@ function makeMessage(deps, hooks, progression) {
1348
748
  return { tag: "parked" };
1349
749
  }
1350
750
  const parentInput = state.input;
1351
- const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
751
+ const needs = resolveNeeds(def, state);
1352
752
  const childInput = def.buildInput({ input: parentInput, needs });
1353
753
  await deps.startChildRun({
1354
754
  child,
1355
755
  childInput,
1356
- parent: { runId, stepId, attempt },
756
+ parent: { runId, stepId },
1357
757
  generation
1358
758
  });
1359
759
  return { tag: "parked" };
1360
760
  }
1361
- async function executeMatch(args) {
1362
- const { def, runId, stepId, state } = args;
1363
- const { store, clock } = deps;
1364
- const input = state.input;
1365
- const needs = resolveNeeds(def, (id) => resolvedOf(stepStateOf(state, id)));
1366
- const armId = selectArm(def, { input, needs });
1367
- await store.appendFact(
1368
- runId,
1369
- Facts.matchArmSelected(runId, stepId, armId, clock.now())
1370
- );
1371
- }
1372
761
  async function handleStepError(args) {
1373
762
  const { flow: flow2, message, def, err } = args;
1374
763
  const { store, queue, clock } = deps;
@@ -1421,9 +810,8 @@ function makeMessage(deps, hooks, progression) {
1421
810
  }
1422
811
  case "failed": {
1423
812
  const at = clock.now();
1424
- await store.settleStep(
813
+ await store.appendFact(
1425
814
  runId,
1426
- stepId,
1427
815
  Facts.stepFailed(runId, stepId, attempt, error, at)
1428
816
  );
1429
817
  await fireStepLifecycle(
@@ -1435,19 +823,20 @@ function makeMessage(deps, hooks, progression) {
1435
823
  return { tag: "advance" };
1436
824
  }
1437
825
  case "flowCanceled": {
1438
- const at = clock.now();
1439
826
  await store.appendFact(
1440
827
  runId,
1441
- Facts.stepCanceled(runId, stepId, attempt, at, error)
828
+ Facts.stepCanceled(runId, stepId, attempt, clock.now(), error)
1442
829
  );
1443
- await store.appendFact(
1444
- runId,
1445
- Facts.flowCanceledByConcurrency({
1446
- runId,
1447
- at,
1448
- canceledByRunId: outcome.canceledByRunId,
1449
- concurrencyKey: outcome.concurrencyKey
1450
- })
830
+ await progression.terminate(
831
+ { kind: "resolved", runId, flow: flow2 },
832
+ {
833
+ tag: "canceled",
834
+ cause: {
835
+ kind: "concurrency",
836
+ canceledByRunId: outcome.canceledByRunId,
837
+ concurrencyKey: outcome.concurrencyKey
838
+ }
839
+ }
1451
840
  );
1452
841
  return { tag: "parked" };
1453
842
  }
@@ -1456,191 +845,135 @@ function makeMessage(deps, hooks, progression) {
1456
845
  return { dispatchMessage };
1457
846
  }
1458
847
 
1459
- // src/flows.ts
1460
- function requireCurrent(resolution) {
1461
- if (resolution.kind === "current") return resolution.flow;
1462
- throw resolution.error;
1463
- }
1464
- async function registerFlows(deps) {
1465
- const { flows, store, clock } = deps;
1466
- const byId = /* @__PURE__ */ new Map();
1467
- const hashById = /* @__PURE__ */ new Map();
1468
- const streamingStepIds = /* @__PURE__ */ new Set();
1469
- for (const flow2 of flows) {
1470
- if (byId.has(flow2.id)) {
1471
- throw new NagiRuntimeError(
1472
- `Duplicate flow id "${flow2.id}" passed to nagi()`
1473
- );
1474
- }
1475
- byId.set(flow2.id, flow2);
1476
- for (const [stepId, step] of Object.entries(
1477
- asStepMapWithDefs(flow2.steps)
1478
- )) {
1479
- if (getDef(step).kind === "streaming") streamingStepIds.add(stepId);
848
+ // src/scheduler.ts
849
+ function nextRunnable({
850
+ flow: flow2,
851
+ runState,
852
+ input
853
+ }) {
854
+ const runnable = [];
855
+ const skip = [];
856
+ for (const [stepId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
857
+ if (stepStateOf(runState, stepId).tag !== "pending") continue;
858
+ const gate = gateStep(getDef(step), runState, input);
859
+ switch (gate.kind) {
860
+ case "run":
861
+ runnable.push(stepId);
862
+ break;
863
+ case "skip":
864
+ skip.push({ stepId, reason: gate.reason });
865
+ break;
1480
866
  }
1481
867
  }
1482
- for (const flow2 of flows) {
1483
- const dag = await canonicalize(flow2);
1484
- const flowHash = await sha256Canonical(dag);
1485
- hashById.set(flow2.id, flowHash);
1486
- await store.upsertSnapshot({
1487
- flowHash,
1488
- flowId: flow2.id,
1489
- dag
1490
- });
1491
- const previousHash = await store.getRef(flow2.id);
1492
- if (previousHash !== flowHash) {
1493
- await store.setRef(flow2.id, flowHash);
1494
- await store.appendGlobalFact(
1495
- Facts.flowRefUpdated({
1496
- flowId: flow2.id,
1497
- from: previousHash,
1498
- to: flowHash,
1499
- at: clock.now()
1500
- })
1501
- );
1502
- }
868
+ return { runnable, skip };
869
+ }
870
+ function gateStep(def, runState, input) {
871
+ const upstream = checkUpstream(def, runState);
872
+ if (upstream !== "ready") return gateFor(upstream);
873
+ if (def.when) {
874
+ const needs = resolveNeeds(def, runState);
875
+ if (!def.when({ input, needs }))
876
+ return { kind: "skip", reason: "when-false" };
1503
877
  }
1504
- function require2(flowId) {
1505
- const flow2 = byId.get(flowId);
1506
- if (!flow2) {
1507
- throw new NagiRuntimeError(
1508
- `Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
1509
- );
1510
- }
1511
- return flow2;
878
+ return { kind: "run" };
879
+ }
880
+ function gateFor(status) {
881
+ switch (status) {
882
+ case "blocked":
883
+ return { kind: "block" };
884
+ case "transitive-skip":
885
+ return { kind: "skip", reason: "transitive" };
1512
886
  }
1513
- function hashOf(flowId) {
1514
- const hash = hashById.get(flowId);
1515
- if (hash === void 0) {
1516
- throw new NagiRuntimeError(
1517
- `Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
1518
- );
887
+ }
888
+ function checkUpstream(def, runState) {
889
+ for (const ref of Object.values(def.needs)) {
890
+ const upstreamState = stepStateOf(runState, ref.step.id);
891
+ if (upstreamState.tag === "completed") continue;
892
+ if (ref.optional && upstreamState.tag === "skipped") continue;
893
+ if (upstreamState.tag === "skipped" || upstreamState.tag === "failed") {
894
+ return "transitive-skip";
1519
895
  }
1520
- return hash;
896
+ return "blocked";
1521
897
  }
1522
- function resolve(state) {
1523
- const { runId, flowId, flowHash: pinnedHash } = state;
1524
- const live = byId.get(flowId);
1525
- if (pinnedHash === void 0) {
1526
- if (live === void 0) {
1527
- throw new NagiRuntimeError(
1528
- `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
1529
- );
1530
- }
1531
- return { kind: "current", flow: live };
1532
- }
1533
- const currentHash = live === void 0 ? null : hashOf(flowId);
1534
- if (live !== void 0 && currentHash === pinnedHash) {
1535
- return { kind: "current", flow: live };
1536
- }
1537
- const error = new NagiFlowSnapshotGoneError({
1538
- runId,
1539
- flowId,
1540
- pinnedHash,
1541
- currentHash
1542
- });
1543
- return isTerminalRun(state) ? { kind: "gone-terminal", error, live } : { kind: "gone-live", error, live };
1544
- }
1545
- const synthesizedByHash = /* @__PURE__ */ new Map();
1546
- function synthesize(gone) {
1547
- const { pinnedHash } = gone.error;
1548
- const cached = synthesizedByHash.get(pinnedHash);
1549
- if (cached !== void 0) return cached;
1550
- const pending = synthesizeUncached(gone);
1551
- synthesizedByHash.set(pinnedHash, pending);
1552
- pending.catch(() => synthesizedByHash.delete(pinnedHash));
1553
- return pending;
1554
- }
1555
- async function synthesizeUncached(gone) {
1556
- const { runId, flowId, pinnedHash } = gone.error;
1557
- if (gone.live === void 0) {
1558
- throw new NagiRuntimeError(
1559
- `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
1560
- );
1561
- }
1562
- const snapshot = await store.loadSnapshot(pinnedHash);
1563
- if (snapshot === null) {
1564
- throw new NagiRuntimeError(
1565
- `Run ${runId} pinned to flow hash ${pinnedHash.slice(0, 12)}\u2026 but no snapshot with that hash was found. Nothing can resume it.`
1566
- );
1567
- }
1568
- return synthesizeReplayFlow(
1569
- snapshot.dag,
1570
- gone.live
1571
- );
898
+ return "ready";
899
+ }
900
+ function flowTermination(flow2, runState) {
901
+ let failure;
902
+ for (const stepId of Object.keys(flow2.steps)) {
903
+ const state = stepStateOf(runState, stepId);
904
+ if (!isStepTerminal(state)) return { kind: "running" };
905
+ if (state.tag === "failed" && failure === void 0) failure = state.error;
1572
906
  }
1573
- return {
1574
- get: (flowId) => byId.get(flowId),
1575
- has: (flowId) => byId.has(flowId),
1576
- require: require2,
1577
- hashOf,
1578
- isStreaming: (stepId) => streamingStepIds.has(stepId),
1579
- resolve,
1580
- synthesize
1581
- };
907
+ if (failure !== void 0) return { kind: "failed", error: failure };
908
+ return { kind: "succeeded" };
1582
909
  }
1583
- function synthesizeReplayFlow(dag, liveFlow) {
1584
- const liveSteps = asStepMapWithDefs(liveFlow.steps);
1585
- const synthesized = {};
1586
- for (const canonStep of dag.steps) {
1587
- const liveStep = liveSteps[canonStep.id];
1588
- if (liveStep === void 0) {
1589
- throw new NagiRuntimeError(
1590
- `Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
1591
- );
910
+ function nextTransition(flow2, runState) {
911
+ const term = flowTermination(flow2, runState);
912
+ switch (term.kind) {
913
+ case "succeeded":
914
+ case "failed": {
915
+ if (isTerminalRun(runState)) return { kind: "settled" };
916
+ if (term.kind === "failed") return { kind: "fail", error: term.error };
917
+ return { kind: "complete", output: computeFlowOutput(flow2, runState) };
1592
918
  }
1593
- synthesized[canonStep.id] = attachDef(
1594
- { kind: canonStep.kind, id: canonStep.id },
1595
- getDef(liveStep)
1596
- );
1597
919
  }
1598
- for (const canonStep of dag.steps) {
1599
- const shell = synthesized[canonStep.id];
1600
- if (shell === void 0) continue;
1601
- const synthesizedNeeds = {};
1602
- for (const upstreamId of canonStep.needs) {
1603
- const upstreamShell = synthesized[upstreamId];
1604
- if (upstreamShell === void 0) {
1605
- throw new NagiRuntimeError(
1606
- `Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
1607
- );
1608
- }
1609
- synthesizedNeeds[upstreamId] = upstreamShell;
1610
- }
1611
- setDef(shell, { ...getDef(shell), needs: synthesizedNeeds });
920
+ const input = runState.input;
921
+ const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
922
+ if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
923
+ if (skip.length > 0) return { kind: "skip", skip };
924
+ return { kind: "waiting" };
925
+ }
926
+ function computeFlowOutput(flow2, runState) {
927
+ if (flow2.output === void 0) return null;
928
+ const stepOutputs = {};
929
+ for (const [sid, sstate] of Object.entries(runState.steps)) {
930
+ if (sstate.tag === "completed") stepOutputs[sid] = sstate.output;
1612
931
  }
1613
- return {
1614
- id: liveFlow.id,
1615
- input: liveFlow.input,
1616
- steps: synthesized,
1617
- ...compact({ output: liveFlow.output })
932
+ return flow2.output(stepOutputs);
933
+ }
934
+ function resetFactsOf(flow2, origin) {
935
+ const { runId, stepId, at } = origin;
936
+ const set = origin.scope === "step" ? [stepId] : descendantsOf(flow2, stepId);
937
+ return set.map(
938
+ (id) => id === stepId ? Facts.stepReset(origin) : Facts.stepReset({ runId, stepId: id, at, cascadedFrom: stepId })
939
+ );
940
+ }
941
+ function descendantsOf(flow2, stepId) {
942
+ const children = /* @__PURE__ */ new Map();
943
+ const addEdge = (from, to) => {
944
+ const bucket = children.get(from);
945
+ if (bucket) bucket.push(to);
946
+ else children.set(from, [to]);
1618
947
  };
948
+ for (const [id, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
949
+ for (const upstreamId of needsStepIds(getDef(step)))
950
+ addEdge(upstreamId, id);
951
+ }
952
+ const out = [stepId];
953
+ const seen = /* @__PURE__ */ new Set([stepId]);
954
+ for (let i = 0; i < out.length; i++) {
955
+ const current = out[i];
956
+ if (current === void 0) continue;
957
+ for (const child of children.get(current) ?? []) {
958
+ if (seen.has(child)) continue;
959
+ seen.add(child);
960
+ out.push(child);
961
+ }
962
+ }
963
+ return out;
1619
964
  }
1620
965
 
1621
966
  // src/exec/progression.ts
1622
967
  var MAX_ADVANCE_ITERS = 1024;
1623
- function subflowOutcomeOf(childRunId, child) {
1624
- switch (child.phase.tag) {
1625
- case "completed":
1626
- return { kind: "completed", output: child.phase.output };
1627
- case "failed":
1628
- return { kind: "failed", error: child.phase.error };
1629
- case "canceled":
1630
- return {
1631
- kind: "canceled",
1632
- error: cancelCauseToError(childRunId, child.phase.cause)
1633
- };
1634
- default:
1635
- return void 0;
1636
- }
968
+ function terminalErrorOf(runId, end) {
969
+ return end.tag === "failed" ? end.error : cancelCauseToError(runId, end.cause);
1637
970
  }
1638
971
  function cancelCauseToError(runId, cause) {
1639
972
  switch (cause.kind) {
1640
973
  case "concurrency":
1641
974
  return {
1642
975
  name: "NagiCanceledError",
1643
- message: `Run ${runId} was canceled (superseded by ${cause.canceledByRunId})`,
976
+ message: new NagiCanceledError({ runId, ...cause }).message,
1644
977
  cause: {
1645
978
  canceledByRunId: cause.canceledByRunId,
1646
979
  concurrencyKey: cause.concurrencyKey
@@ -1651,18 +984,31 @@ function cancelCauseToError(runId, cause) {
1651
984
  name: "NagiCanceledError",
1652
985
  message: `Run ${runId} was canceled: ${cause.reason}`
1653
986
  };
1654
- case "operator":
1655
- return {
1656
- name: "NagiCanceledError",
1657
- message: `Run ${runId} was canceled by ${cause.actor}: ${cause.reason}`
1658
- };
1659
987
  }
1660
988
  }
989
+ function endFact(runId, end, at) {
990
+ switch (end.tag) {
991
+ case "completed":
992
+ return Facts.flowCompleted(runId, end.output, at);
993
+ case "failed":
994
+ return Facts.flowFailed(runId, end.error, at);
995
+ case "canceled":
996
+ return Facts.flowCanceledByConcurrency({
997
+ runId,
998
+ at,
999
+ canceledByRunId: end.cause.canceledByRunId,
1000
+ concurrencyKey: end.cause.concurrencyKey
1001
+ });
1002
+ }
1003
+ }
1004
+ function endingRunOf(runId, resolution) {
1005
+ return resolution.kind === "current" ? { kind: "resolved", runId, flow: resolution.flow } : { kind: "gone", runId, flowId: resolution.error.flowId };
1006
+ }
1661
1007
  function makeProgression(deps, hooks) {
1662
1008
  const { fireHook } = hooks;
1663
1009
  async function advance(runId) {
1664
1010
  const { store, queue } = deps;
1665
- const flow2 = requireCurrent(await deps.resolveFlow(runId));
1011
+ const flow2 = requireCurrent(await deps.flowOf(runId));
1666
1012
  for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
1667
1013
  const runState = await store.loadRunState(runId);
1668
1014
  const t = nextTransition(flow2, runState);
@@ -1671,10 +1017,16 @@ function makeProgression(deps, hooks) {
1671
1017
  case "waiting":
1672
1018
  return;
1673
1019
  case "complete":
1674
- await finalizeFlowCompletion({ flow: flow2, runId, output: t.output });
1020
+ await terminate(
1021
+ { kind: "resolved", runId, flow: flow2 },
1022
+ { tag: "completed", output: t.output }
1023
+ );
1675
1024
  return;
1676
1025
  case "fail":
1677
- await finalizeFlowFailure({ flow: flow2, runId, error: t.error });
1026
+ await terminate(
1027
+ { kind: "resolved", runId, flow: flow2 },
1028
+ { tag: "failed", error: t.error }
1029
+ );
1678
1030
  return;
1679
1031
  case "dispatch":
1680
1032
  await recordSkips(runId, t.skip);
@@ -1684,19 +1036,16 @@ function makeProgression(deps, hooks) {
1684
1036
  case "skip":
1685
1037
  await recordSkips(runId, t.skip);
1686
1038
  continue;
1687
- case "promote-match":
1688
- await applyPromotions(flow2, runState, t.promotions);
1689
- continue;
1690
1039
  }
1691
1040
  }
1692
1041
  const cycleError = {
1693
1042
  name: "NagiCycleError",
1694
1043
  message: `advance exceeded ${MAX_ADVANCE_ITERS} iterations \u2014 likely a cycle or infinite skip loop in flow "${flow2.id}"`
1695
1044
  };
1696
- const finalState = await store.loadRunState(runId);
1697
- if (!isTerminalRun(finalState)) {
1698
- await finalizeFlowFailure({ flow: flow2, runId, error: cycleError });
1699
- }
1045
+ await terminate(
1046
+ { kind: "resolved", runId, flow: flow2 },
1047
+ { tag: "failed", error: cycleError }
1048
+ );
1700
1049
  }
1701
1050
  async function recordSkips(runId, skip) {
1702
1051
  const { store, clock } = deps;
@@ -1707,21 +1056,20 @@ function makeProgression(deps, hooks) {
1707
1056
  );
1708
1057
  }
1709
1058
  }
1710
- async function markStepSettled(args) {
1711
- const { flow: flow2, runId, stepId, attempt, stepKind, settlement } = args;
1059
+ async function settleSubflowStep(args) {
1060
+ const { flow: flow2, runId, stepId, attempt, settlement } = args;
1712
1061
  const at = deps.clock.now();
1713
1062
  const base = {
1714
1063
  runId,
1715
1064
  flowId: flow2.id,
1716
1065
  stepId,
1717
1066
  attempt,
1718
- kind: stepKind,
1067
+ kind: "subflow",
1719
1068
  at
1720
1069
  };
1721
1070
  if (settlement.kind === "complete") {
1722
- await deps.store.settleStep(
1071
+ await deps.store.appendFact(
1723
1072
  runId,
1724
- stepId,
1725
1073
  Facts.stepCompleted(runId, stepId, attempt, settlement.output, at)
1726
1074
  );
1727
1075
  await fireHook(
@@ -1730,9 +1078,8 @@ function makeProgression(deps, hooks) {
1730
1078
  "onStepComplete"
1731
1079
  );
1732
1080
  } else {
1733
- await deps.store.settleStep(
1081
+ await deps.store.appendFact(
1734
1082
  runId,
1735
- stepId,
1736
1083
  Facts.stepFailed(runId, stepId, attempt, settlement.error, at)
1737
1084
  );
1738
1085
  await fireHook(
@@ -1742,40 +1089,62 @@ function makeProgression(deps, hooks) {
1742
1089
  );
1743
1090
  }
1744
1091
  }
1745
- async function applyPromotions(flow2, runState, promotions) {
1746
- for (const { matchId, attempt, result } of promotions) {
1747
- await markStepSettled({
1748
- flow: flow2,
1749
- runId: runState.runId,
1750
- stepId: matchId,
1751
- attempt,
1752
- stepKind: "match",
1753
- settlement: result
1092
+ async function terminate(run, end) {
1093
+ const at = deps.clock.now();
1094
+ if (!await deps.store.endRun(run.runId, endFact(run.runId, end, at))) {
1095
+ deps.emitLog({
1096
+ level: "info",
1097
+ msg: "nagi: run end skipped \u2014 run already terminal",
1098
+ attrs: { runId: run.runId, end: end.tag }
1754
1099
  });
1100
+ return;
1755
1101
  }
1102
+ await fireTerminalHooks(run, end, at);
1103
+ await propagateToParent(run.runId, end);
1756
1104
  }
1757
- async function finalizeFlowFailure(args) {
1758
- const { flow: flow2, runId, error } = args;
1759
- const { store, clock } = deps;
1760
- await store.appendFact(runId, Facts.flowFailed(runId, error, clock.now()));
1761
- const event = { runId, flowId: flow2.id, error, at: clock.now() };
1762
- await fireHook(flow2.onError, event, "flow.onError");
1763
- await fireHook(deps.hooks?.onFlowError, event, "onFlowError");
1764
- await propagateToParent(runId, { kind: "failed", error });
1105
+ async function settleSuperseded(run, fact) {
1106
+ const end = { tag: "canceled", cause: runCancelCause(fact) };
1107
+ await fireTerminalHooks(run, end, fact.at);
1108
+ await propagateToParent(run.runId, end);
1765
1109
  }
1766
- async function finalizeFlowCompletion(args) {
1767
- const { flow: flow2, runId, output } = args;
1110
+ async function cancel(runId, args) {
1768
1111
  const { store, clock } = deps;
1769
- await store.appendFact(
1770
- runId,
1771
- Facts.flowCompleted(runId, output, clock.now())
1772
- );
1773
- const event = { runId, flowId: flow2.id, output, at: clock.now() };
1774
- await fireHook(flow2.onComplete, event, "flow.onComplete");
1775
- await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete");
1776
- await propagateToParent(runId, { kind: "completed", output });
1112
+ const run = endingRunOf(runId, await deps.flowOf(runId));
1113
+ const at = clock.now();
1114
+ if (!await store.endRun(runId, Facts.flowCanceled(runId, args, at))) {
1115
+ deps.emitLog({
1116
+ level: "info",
1117
+ msg: "nagi: cancel skipped \u2014 run already terminal",
1118
+ attrs: { runId, status: runStatusOf(await store.loadRunState(runId)) }
1119
+ });
1120
+ return;
1121
+ }
1122
+ const end = { tag: "canceled", cause: runCancelCause(args) };
1123
+ await fireTerminalHooks(run, end, at);
1124
+ for (const childId of await store.listChildren(runId)) {
1125
+ await cancel(childId, {
1126
+ cause: "explicit",
1127
+ reason: `parent ${runId} canceled: ${args.reason}`,
1128
+ note: `cascade from parent ${runId}`
1129
+ });
1130
+ }
1131
+ await propagateToParent(runId, end);
1132
+ }
1133
+ async function fireTerminalHooks(run, end, at) {
1134
+ const { runId } = run;
1135
+ const flow2 = run.kind === "resolved" ? run.flow : void 0;
1136
+ const flowId = run.kind === "resolved" ? run.flow.id : run.flowId;
1137
+ if (end.tag === "completed") {
1138
+ const event2 = { runId, flowId, output: end.output, at };
1139
+ await fireHook(flow2?.onComplete, event2, "flow.onComplete");
1140
+ await fireHook(deps.hooks?.onFlowComplete, event2, "onFlowComplete");
1141
+ return;
1142
+ }
1143
+ const event = { runId, flowId, error: terminalErrorOf(runId, end), at };
1144
+ await fireHook(flow2?.onError, event, "flow.onError");
1145
+ await fireHook(deps.hooks?.onFlowError, event, "onFlowError");
1777
1146
  }
1778
- async function propagateToParent(childRunId, outcome) {
1147
+ async function propagateToParent(childRunId, end) {
1779
1148
  const { store } = deps;
1780
1149
  const childState = await store.loadRunState(childRunId);
1781
1150
  if (childState.parent === void 0) {
@@ -1811,24 +1180,22 @@ function makeProgression(deps, hooks) {
1811
1180
  return;
1812
1181
  }
1813
1182
  const attempt = parentStep.attempt;
1814
- const parentFlow = requireCurrent(await deps.resolveFlow(parentRunId));
1815
- await markStepSettled({
1183
+ const parentFlow = requireCurrent(await deps.flowOf(parentRunId));
1184
+ await settleSubflowStep({
1816
1185
  flow: parentFlow,
1817
1186
  runId: parentRunId,
1818
1187
  stepId: parentStepId,
1819
1188
  attempt,
1820
- stepKind: "subflow",
1821
- settlement: outcome.kind === "completed" ? { kind: "complete", output: { childRunId, output: outcome.output } } : { kind: "fail", error: outcome.error }
1189
+ settlement: end.tag === "completed" ? { kind: "complete", output: { childRunId, output: end.output } } : { kind: "fail", error: terminalErrorOf(childRunId, end) }
1822
1190
  });
1823
1191
  await advance(parentRunId);
1824
1192
  }
1825
1193
  async function wakeParentFromChild(childRunId) {
1826
- const child = await deps.store.loadRunState(childRunId);
1827
- const outcome = subflowOutcomeOf(childRunId, child);
1828
- if (outcome === void 0) return;
1829
- await propagateToParent(childRunId, outcome);
1194
+ const { phase } = await deps.store.loadRunState(childRunId);
1195
+ if (phase.tag === "pending" || phase.tag === "running") return;
1196
+ await propagateToParent(childRunId, phase);
1830
1197
  }
1831
- return { advance, propagateToParent, wakeParentFromChild };
1198
+ return { advance, terminate, settleSuperseded, cancel, wakeParentFromChild };
1832
1199
  }
1833
1200
 
1834
1201
  // src/dispatch.ts
@@ -1841,7 +1208,7 @@ function makeDispatcher(deps) {
1841
1208
  for (const { runId, stepId, attempt, fireAt } of timedOut) {
1842
1209
  try {
1843
1210
  if (deps.hooks?.onStepError) {
1844
- const flow2 = requireCurrent(await deps.resolveFlow(runId));
1211
+ const flow2 = requireCurrent(await deps.flowOf(runId));
1845
1212
  await hooks.fireHook(
1846
1213
  deps.hooks.onStepError,
1847
1214
  {
@@ -1862,7 +1229,7 @@ function makeDispatcher(deps) {
1862
1229
  } catch (err) {
1863
1230
  deps.emitLog({
1864
1231
  level: "error",
1865
- msg: "nagi: signal timeout fired but the run could not be advanced \u2014 re-drive with operator.retry",
1232
+ msg: "nagi: signal timeout fired but the run could not be advanced \u2014 re-drive with replay({ from })",
1866
1233
  attrs: { runId, stepId, attempt, error: String(err) }
1867
1234
  });
1868
1235
  }
@@ -1872,220 +1239,183 @@ function makeDispatcher(deps) {
1872
1239
  return {
1873
1240
  dispatchMessage: message.dispatchMessage,
1874
1241
  advance: progression.advance,
1875
- propagateToParent: progression.propagateToParent,
1242
+ terminate: progression.terminate,
1243
+ settleSuperseded: progression.settleSuperseded,
1244
+ cancel: progression.cancel,
1876
1245
  sweepTimers
1877
1246
  };
1878
1247
  }
1879
1248
 
1880
- // src/operator.ts
1881
- var ABORT_SETTLE_DEADLINE_MS = 3e4;
1882
- var ABORT_SETTLE_POLL_MS = 50;
1883
- function requireActor(method, actor) {
1884
- if (typeof actor !== "string" || actor.length === 0) {
1885
- throw validationError(`${method}: opts.actor must be a non-empty string`, [
1886
- "actor"
1887
- ]);
1888
- }
1889
- }
1890
- function makeOperator(o) {
1891
- const { dispatcher, store, clock, registry, cancelRunRecursive, emitLog } = o;
1892
- async function skip(runId, stepId, opts) {
1893
- requireActor("operator.skip", opts.actor);
1894
- const state = await store.loadRunState(runId);
1895
- const flow2 = registry.require(state.flowId);
1896
- if (!(stepId in flow2.steps)) {
1897
- throw validationError(
1898
- `operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
1899
- ["stepId"]
1900
- );
1901
- }
1902
- const stepState = stepStateOf(state, stepId);
1903
- if (isStepTerminal(stepState)) {
1904
- emitLog({
1905
- level: "info",
1906
- msg: "nagi: operator.skip noop \u2014 step already terminal",
1907
- attrs: { runId, stepId, status: stepStatusOf(stepState) }
1908
- });
1909
- return;
1910
- }
1911
- if (isTerminalRun(state)) {
1912
- throw new NagiRuntimeError(
1913
- `operator.skip: run ${runId} is already terminal (${runStatusOf(state)}); cannot skip step "${stepId}".`
1914
- );
1915
- }
1916
- await store.appendFact(
1917
- runId,
1918
- Facts.stepSkipped({
1919
- runId,
1920
- stepId,
1921
- at: clock.now(),
1922
- reason: "manual",
1923
- actor: opts.actor,
1924
- ...compact({ note: opts.note })
1925
- })
1926
- );
1927
- await dispatcher.advance(runId);
1928
- }
1929
- async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
1930
- const start = Date.now();
1931
- while (Date.now() - start < deadlineMs) {
1932
- const s = await store.loadRunState(runId);
1933
- const ss = s.steps[stepId];
1934
- if (ss === void 0) return;
1935
- if (isStepTerminal(ss)) return;
1936
- if (isTerminalRun(s)) return;
1937
- if (attemptOf(ss) > attempt) return;
1938
- await new Promise((r) => setTimeout(r, ABORT_SETTLE_POLL_MS));
1939
- }
1940
- throw new NagiRuntimeError(
1941
- `operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
1942
- );
1943
- }
1944
- async function retry(runId, stepId, opts) {
1945
- requireActor("operator.retry", opts.actor);
1946
- const state = await store.loadRunState(runId);
1947
- if (state.phase.tag === "canceled") {
1948
- throw new NagiRuntimeError(
1949
- `operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
1950
- );
1951
- }
1952
- const flow2 = registry.require(state.flowId);
1953
- if (!(stepId in flow2.steps)) {
1954
- throw validationError(
1955
- `operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
1956
- ["stepId"]
1957
- );
1958
- }
1959
- const stepState = stepStateOf(state, stepId);
1960
- if (stepState.tag === "running") {
1961
- await store.appendFact(
1962
- runId,
1963
- Facts.stepAbortRequested({
1964
- runId,
1965
- stepId,
1966
- attempt: stepState.attempt,
1967
- at: clock.now(),
1968
- actor: opts.actor,
1969
- ...compact({ note: opts.note })
1970
- })
1971
- );
1972
- await waitForStepToSettle(
1973
- runId,
1974
- stepId,
1975
- stepState.attempt,
1976
- ABORT_SETTLE_DEADLINE_MS
1977
- );
1978
- }
1979
- const resetSet = resetSetOf(flow2, stepId, opts.scope);
1980
- const at = clock.now();
1981
- for (const id of resetSet) {
1982
- const fact = id === stepId ? Facts.stepReset({
1983
- runId,
1984
- stepId: id,
1985
- at,
1986
- actor: opts.actor,
1987
- ...compact({ scope: opts.scope, note: opts.note })
1988
- }) : Facts.stepReset({ runId, stepId: id, at, cascadedFrom: stepId });
1989
- await store.appendFact(runId, fact);
1990
- }
1991
- await dispatcher.advance(runId);
1992
- }
1993
- async function abort(runId, opts) {
1994
- requireActor("operator.abort", opts.actor);
1995
- await cancelRunRecursive(runId, {
1996
- cause: "operator",
1997
- reason: opts.note ?? `aborted by operator ${opts.actor}`,
1998
- actor: opts.actor,
1999
- ...compact({ note: opts.note })
2000
- });
2001
- }
2002
- return { skip, retry, abort };
2003
- }
2004
-
2005
1249
  // src/replay.ts
2006
1250
  function makeReplay(deps) {
2007
1251
  const { registry, store, queue, clock, driftPolicy } = deps;
2008
1252
  async function replay(runId, opts = { mode: "continue" }) {
2009
- const runState = await store.loadRunState(runId);
2010
- const resolution = registry.resolve(runState);
2011
- const liveFlow = resolution.kind === "current" ? resolution.flow : resolution.live;
2012
- if (liveFlow === void 0) {
1253
+ const drift = opts.allowDrift === true ? "synthesize" : driftPolicy;
1254
+ const resolution = await deps.flowOfUnder(runId, drift);
1255
+ if (resolution.kind !== "current" && resolution.live === void 0) {
2013
1256
  throw new NagiRuntimeError(
2014
- `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
1257
+ `Run ${runId} references flow "${resolution.error.flowId}" which is not registered with nagi().`
2015
1258
  );
2016
1259
  }
1260
+ const runState = await store.loadRunState(runId);
2017
1261
  if (runState.phase.tag === "canceled") {
2018
1262
  throw new NagiRuntimeError(
2019
- `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.`
1263
+ `Run ${runId} was canceled. Replay is not supported for canceled runs \u2014 start a new run instead.`
2020
1264
  );
2021
1265
  }
2022
1266
  if (opts.mode === "inspect") return;
2023
- const fireHooks = opts.fireHooks !== false;
2024
- const baseDeps = fireHooks ? deps : { ...deps, fireHooks: false };
2025
- let replayDeps = baseDeps;
2026
- let effectiveFlow = liveFlow;
2027
1267
  if (resolution.kind !== "current") {
2028
- if (!opts.allowDrift && driftPolicy === "freeze") {
1268
+ if (drift === "freeze") {
2029
1269
  throw new NagiSnapshotDriftError({
2030
1270
  runId,
2031
1271
  expected: resolution.error.pinnedHash,
2032
- actual: registry.hashOf(liveFlow.id)
1272
+ actual: registry.hashOf(resolution.error.flowId)
2033
1273
  });
2034
1274
  }
2035
- const synthesized = await registry.synthesize(resolution);
2036
- replayDeps = {
2037
- ...baseDeps,
2038
- resolveFlow: async () => ({ kind: "current", flow: synthesized })
2039
- };
2040
- effectiveFlow = synthesized;
1275
+ throw resolution.error;
2041
1276
  }
1277
+ const { flow: flow2 } = resolution;
2042
1278
  if (opts.from !== void 0) {
2043
- if (runState.phase.tag === "running") {
2044
- throw new NagiRuntimeError(
2045
- `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.`
2046
- );
2047
- }
2048
- if (!(opts.from in effectiveFlow.steps)) {
1279
+ if (!(opts.from in flow2.steps)) {
2049
1280
  throw validationError(
2050
- `replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
1281
+ `replay({ from }): step "${opts.from}" is not a step in flow "${flow2.id}".`,
2051
1282
  ["from"]
2052
1283
  );
2053
1284
  }
2054
- const resetSet = resetSetOf(effectiveFlow, opts.from, opts.scope);
2055
- const at = clock.now();
2056
- for (const stepId of resetSet) {
2057
- const fact = stepId === opts.from ? Facts.stepReset({
1285
+ await abortInFlight(runState, opts.from);
1286
+ const resets = resetFactsOf(flow2, {
1287
+ runId,
1288
+ stepId: opts.from,
1289
+ at: clock.now(),
1290
+ ...compact({ scope: opts.scope })
1291
+ });
1292
+ for (const fact of resets) await store.appendFact(runId, fact);
1293
+ }
1294
+ const run = { runId, flow: flow2 };
1295
+ if (opts.fireHooks !== false) {
1296
+ await deps.dispatcherFor({ kind: "enqueue", run }).advance(runId);
1297
+ return;
1298
+ }
1299
+ const inline = makeInlineQueue(queue);
1300
+ const dispatcher = deps.dispatcherFor({
1301
+ kind: "inline",
1302
+ run,
1303
+ queue: inline
1304
+ });
1305
+ try {
1306
+ await dispatcher.advance(runId);
1307
+ await drainInline(dispatcher, inline);
1308
+ } finally {
1309
+ await inline.handOff();
1310
+ }
1311
+ }
1312
+ async function abortInFlight(state, stepId) {
1313
+ if (stepStateOf(state, stepId).tag !== "running") return;
1314
+ const { runId } = state;
1315
+ let aborted = 0;
1316
+ const start = Date.now();
1317
+ for (let s = state; ; s = await store.loadRunState(runId)) {
1318
+ const step = stepStateOf(s, stepId);
1319
+ if (step.tag === "pending" || isStepTerminal(step) || isTerminalRun(s)) {
1320
+ return;
1321
+ }
1322
+ if (step.tag === "running" && step.attempt > aborted) {
1323
+ aborted = step.attempt;
1324
+ await store.appendFact(
2058
1325
  runId,
2059
- stepId,
2060
- at,
2061
- ...compact({ scope: opts.scope })
2062
- }) : Facts.stepReset({ runId, stepId, at, cascadedFrom: opts.from });
2063
- await store.appendFact(runId, fact);
1326
+ Facts.stepAbortRequested({
1327
+ runId,
1328
+ stepId,
1329
+ attempt: step.attempt,
1330
+ at: clock.now()
1331
+ })
1332
+ );
1333
+ }
1334
+ if (Date.now() - start >= ABORT_SETTLE_DEADLINE_MS) {
1335
+ throw new NagiRuntimeError(
1336
+ `replay({ from }): timed out after ${ABORT_SETTLE_DEADLINE_MS}ms waiting for step "${stepId}" (attempt ${aborted}) to honor abort signal. Handler may be ignoring ctx.signal.`
1337
+ );
2064
1338
  }
1339
+ await new Promise((r) => setTimeout(r, ABORT_SETTLE_POLL_MS));
2065
1340
  }
2066
- const replayDispatcher = makeDispatcher(replayDeps);
2067
- await replayDispatcher.advance(runId);
2068
- if (!fireHooks) await drainInline(replayDispatcher, queue);
2069
1341
  }
2070
1342
  return { replay };
2071
1343
  }
1344
+ var ABORT_SETTLE_DEADLINE_MS = 3e4;
1345
+ var ABORT_SETTLE_POLL_MS = 50;
2072
1346
  var MAX_REPLAY_DISPATCHES = 4096;
2073
- async function drainInline(dispatcher, queue) {
1347
+ async function drainInline(dispatcher, inline) {
2074
1348
  for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
2075
- const messages = await queue.dequeue({ count: 1 });
2076
- if (messages.length === 0) return;
2077
- for (const msg of messages) {
2078
- const result = await dispatcher.dispatchMessage(msg);
2079
- if (result.kind === "snapshot-gone") throw result.error;
1349
+ const [msg] = await inline.dequeue({ count: 1 });
1350
+ if (msg === void 0) return;
1351
+ const result = await dispatcher.dispatchMessage(msg);
1352
+ if (result.kind === "snapshot-gone") throw result.error;
1353
+ }
1354
+ }
1355
+ function makeInlineQueue(shared) {
1356
+ const ready = [];
1357
+ const leased = /* @__PURE__ */ new Map();
1358
+ let seq = 0;
1359
+ const toShared = (m, delayMs) => shared.enqueue(m.runId, m.stepId, {
1360
+ attempt: m.attempt,
1361
+ payload: m.payload,
1362
+ ...compact({ flowId: m.flowId, delayMs })
1363
+ });
1364
+ return {
1365
+ async enqueue(runId, stepId, opts) {
1366
+ if ((opts?.delayMs ?? 0) > 0) {
1367
+ await shared.enqueue(runId, stepId, opts);
1368
+ return;
1369
+ }
1370
+ ready.push({
1371
+ receipt: `inline-${seq++}`,
1372
+ runId,
1373
+ stepId,
1374
+ payload: opts?.payload ?? null,
1375
+ attempt: opts?.attempt ?? 1,
1376
+ readCount: 0,
1377
+ ...compact({ flowId: opts?.flowId })
1378
+ });
1379
+ },
1380
+ async dequeue({ count }) {
1381
+ const out = ready.splice(0, count).map((m) => ({ ...m, readCount: m.readCount + 1 }));
1382
+ for (const m of out) leased.set(m.receipt, m);
1383
+ return out;
1384
+ },
1385
+ async ack(receipt) {
1386
+ leased.delete(receipt);
1387
+ },
1388
+ async nack(receipt, opts) {
1389
+ const m = leased.get(receipt);
1390
+ if (m === void 0) return;
1391
+ leased.delete(receipt);
1392
+ if ((opts?.delayMs ?? 0) > 0) await toShared(m, opts?.delayMs);
1393
+ else ready.push(m);
1394
+ },
1395
+ async extend() {
1396
+ },
1397
+ async handOff() {
1398
+ const rest = [...leased.values(), ...ready.splice(0)];
1399
+ leased.clear();
1400
+ for (const m of rest) await toShared(m);
2080
1401
  }
2081
- }
1402
+ };
2082
1403
  }
2083
1404
 
2084
1405
  // src/run-lifecycle.ts
2085
1406
  var EXISTS = { kind: "exists" };
2086
1407
  var ADVANCE = { kind: "advance" };
2087
1408
  function makeRunLifecycle(deps) {
2088
- const { store, queue, clock, registry, hooks, flowHooks, dispatcher } = deps;
1409
+ const {
1410
+ store,
1411
+ queue,
1412
+ clock,
1413
+ registry,
1414
+ flowOf,
1415
+ hooks,
1416
+ flowHooks,
1417
+ dispatcher
1418
+ } = deps;
2089
1419
  function resolveBoundary(boundary) {
2090
1420
  switch (boundary.kind) {
2091
1421
  case "own":
@@ -2118,7 +1448,7 @@ function makeRunLifecycle(deps) {
2118
1448
  codeVersion: deps.codeVersion,
2119
1449
  flowHash: registry.hashOf(flow2.id),
2120
1450
  ...compact({
2121
- parent: parent !== void 0 ? { runId: parent.runId, stepId: parent.stepId } : void 0
1451
+ parent
2122
1452
  })
2123
1453
  });
2124
1454
  const concurrency = concurrencyOf(flow2, validatedInput);
@@ -2129,7 +1459,8 @@ function makeRunLifecycle(deps) {
2129
1459
  return {
2130
1460
  kind: "started",
2131
1461
  effects: {
2132
- superseded: canceled.map((c) => supersededEvent(flow2.id, runId, c)),
1462
+ flow: flow2,
1463
+ superseded: canceled,
2133
1464
  started: {
2134
1465
  runId,
2135
1466
  flowId: flow2.id,
@@ -2142,15 +1473,12 @@ function makeRunLifecycle(deps) {
2142
1473
  };
2143
1474
  }
2144
1475
  async function applyEffects(effects) {
2145
- const { superseded, started, dispatch } = effects;
2146
- const flow2 = registry.require(started.flowId);
2147
- for (const event of superseded) {
2148
- await hooks.fireHook(flow2.onError, event, "flow.onError");
2149
- await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
2150
- await dispatcher.propagateToParent(event.runId, {
2151
- kind: "canceled",
2152
- error: event.error
2153
- });
1476
+ const { flow: flow2, superseded, started, dispatch } = effects;
1477
+ for (const { runId, fact } of superseded) {
1478
+ await dispatcher.settleSuperseded(
1479
+ endingRunOf(runId, await flowOf(runId)),
1480
+ fact
1481
+ );
2154
1482
  }
2155
1483
  await hooks.fireHook(flow2.onStart, started, "flow.onStart");
2156
1484
  await hooks.fireHook(flowHooks?.onFlowStart, started, "onFlowStart");
@@ -2215,37 +1543,7 @@ function makeRunLifecycle(deps) {
2215
1543
  if (staged.kind === "started") await applyEffects(staged.effects);
2216
1544
  return runId;
2217
1545
  }
2218
- async function cancelRunRecursive(runId, args) {
2219
- const state = await store.loadRunState(runId);
2220
- if (isTerminalRun(state)) {
2221
- deps.emitLog({
2222
- level: "info",
2223
- msg: "nagi: cancel skipped \u2014 run already terminal",
2224
- attrs: { runId, status: runStatusOf(state) }
2225
- });
2226
- return;
2227
- }
2228
- const flow2 = registry.get(state.flowId);
2229
- await store.appendFact(runId, Facts.flowCanceled(runId, args, clock.now()));
2230
- const error = {
2231
- name: "NagiCanceledError",
2232
- message: `Run ${runId} was canceled: ${args.reason}`
2233
- };
2234
- if (flow2 !== void 0) {
2235
- const event = { runId, flowId: flow2.id, error, at: clock.now() };
2236
- await hooks.fireHook(flow2.onError, event, "flow.onError");
2237
- await hooks.fireHook(flowHooks?.onFlowError, event, "onFlowError");
2238
- }
2239
- for (const childId of await store.listChildren(runId)) {
2240
- await cancelRunRecursive(childId, {
2241
- cause: "explicit",
2242
- reason: `parent ${runId} canceled: ${args.reason}`,
2243
- note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
2244
- });
2245
- }
2246
- await dispatcher.propagateToParent(runId, { kind: "canceled", error });
2247
- }
2248
- return { start, stage, applyEffects, startChildRun, cancelRunRecursive };
1546
+ return { start, stage, applyEffects, startChildRun };
2249
1547
  }
2250
1548
  function resolveRunId(runId) {
2251
1549
  if (runId === void 0) return `run-${crypto.randomUUID()}`;
@@ -2265,14 +1563,6 @@ function concurrencyOf(flow2, input) {
2265
1563
  }
2266
1564
  return { key, mode: flow2.concurrency.mode };
2267
1565
  }
2268
- function supersededEvent(flowId, canceledByRunId, c) {
2269
- const cause = { canceledByRunId, concurrencyKey: c.fact.concurrencyKey };
2270
- const error = {
2271
- ...serializeError(new NagiCanceledError({ runId: c.runId, ...cause })),
2272
- cause
2273
- };
2274
- return { runId: c.runId, flowId, error, at: c.fact.at };
2275
- }
2276
1566
 
2277
1567
  // src/worker.ts
2278
1568
  var DEFAULT_CONCURRENCY = 4;
@@ -2292,21 +1582,34 @@ var WorkerImpl = class {
2292
1582
  this.dispatcher = makeDispatcher(deps);
2293
1583
  this.snapshotGonePolicy = config?.snapshotGonePolicy ?? defaultSnapshotGonePolicy;
2294
1584
  this.maxPerFlow = config?.maxConcurrencyPerFlow !== void 0 ? Math.max(1, config.maxConcurrencyPerFlow) : void 0;
2295
- this.timerSweepIntervalMs = config?.timerSweepIntervalMs ?? DEFAULT_TIMER_SWEEP_INTERVAL_MS;
2296
- this.lastTimerSweepAt = this.deps.clock.now().getTime();
1585
+ const bootAt = deps.clock.now().getTime();
1586
+ const sweeps = [
1587
+ {
1588
+ label: "signal-timeout",
1589
+ intervalMs: config?.timerSweepIntervalMs ?? DEFAULT_TIMER_SWEEP_INTERVAL_MS,
1590
+ run: (now) => this.dispatcher.sweepTimers(now),
1591
+ lastAt: bootAt
1592
+ },
1593
+ {
1594
+ label: "lease-reaper",
1595
+ intervalMs: config?.reaperIntervalMs ?? DEFAULT_REAPER_INTERVAL_MS,
1596
+ run: (now) => deps.store.sweepLeases({ now, queue: deps.queue }),
1597
+ lastAt: bootAt
1598
+ }
1599
+ ];
1600
+ this.sweeps = sweeps.filter((s) => s.intervalMs > 0);
2297
1601
  }
2298
1602
  deps;
2299
- inFlight = 0;
1603
+ inFlight = /* @__PURE__ */ new Set();
2300
1604
  concurrency;
2301
1605
  pollIntervalMs;
2302
1606
  dequeueBackoffMs;
2303
1607
  signal;
2304
1608
  dispatcher;
2305
- timerSweepIntervalMs;
1609
+ sweeps;
2306
1610
  snapshotGonePolicy;
2307
1611
  maxPerFlow;
2308
1612
  inFlightByFlow = /* @__PURE__ */ new Map();
2309
- lastTimerSweepAt;
2310
1613
  // Per-flow blast-radius bound (maxConcurrencyPerFlow). A message over its
2311
1614
  // flow's cap is DEFERRED — delayed nack, redelivered after ~pollIntervalMs —
2312
1615
  // not dropped. Messages without flowId (enqueued pre-upgrade) are exempt.
@@ -2343,8 +1646,8 @@ var WorkerImpl = class {
2343
1646
  async run() {
2344
1647
  let dequeueFailures = 0;
2345
1648
  while (!this.aborted()) {
2346
- await this.maybeSweepTimers();
2347
- const slots = this.concurrency - this.inFlight;
1649
+ await this.runDueSweeps();
1650
+ const slots = this.concurrency - this.inFlight.size;
2348
1651
  if (slots <= 0) {
2349
1652
  await this.sleep(50);
2350
1653
  continue;
@@ -2425,12 +1728,12 @@ var WorkerImpl = class {
2425
1728
  return this.deps.queue.dequeue({ count: Math.max(1, count) });
2426
1729
  }
2427
1730
  fire(msg) {
2428
- this.inFlight++;
2429
1731
  const release = this.trackFlow(msg);
2430
- void this.dispatchSafely(msg).finally(() => {
1732
+ const dispatch = this.dispatchSafely(msg).finally(() => {
2431
1733
  release();
2432
- this.inFlight = Math.max(0, this.inFlight - 1);
1734
+ this.inFlight.delete(dispatch);
2433
1735
  });
1736
+ this.inFlight.add(dispatch);
2434
1737
  }
2435
1738
  async dispatchSafely(msg) {
2436
1739
  let result;
@@ -2502,48 +1805,46 @@ var WorkerImpl = class {
2502
1805
  msg: "worker.dispatch: flow snapshot gone \u2014 redelivery budget exhausted, failing run",
2503
1806
  attrs
2504
1807
  });
2505
- const serialized = serializeError(err);
2506
- await this.deps.store.appendFact(
2507
- msg.runId,
2508
- Facts.flowFailed(msg.runId, serialized, this.deps.clock.now())
2509
- );
2510
1808
  try {
2511
- await this.dispatcher.propagateToParent(msg.runId, {
2512
- kind: "failed",
2513
- error: serialized
2514
- });
2515
- } catch (propagateErr) {
1809
+ await this.dispatcher.terminate(
1810
+ { kind: "gone", runId: msg.runId, flowId: err.flowId },
1811
+ { tag: "failed", error: serializeError(err) }
1812
+ );
1813
+ } catch (terminateErr) {
1814
+ const state = await this.deps.store.loadRunState(msg.runId);
1815
+ if (!isTerminalRun(state)) throw terminateErr;
2516
1816
  this.deps.emitLog({
2517
1817
  level: "warn",
2518
1818
  msg: "worker.dispatch: snapshot-gone fail could not propagate to parent",
2519
- attrs: { ...attrs, error: String(propagateErr) }
1819
+ attrs: { ...attrs, error: String(terminateErr) }
2520
1820
  });
2521
1821
  }
2522
1822
  await this.deps.queue.ack(msg.receipt);
2523
1823
  }
2524
1824
  async drain() {
2525
- while (this.inFlight > 0) {
2526
- await this.deps.clock.sleep(50);
1825
+ while (this.inFlight.size > 0) {
1826
+ await Promise.allSettled(this.inFlight);
2527
1827
  }
2528
1828
  }
2529
- // Sweep elapsed signal timeouts on cadence. Runs inline in the dispatch loop
2530
- // (not fired concurrently) so two sweeps never overlap; at 30s with a handful
2531
- // of timers the cost is negligible. Errors are logged, never thrown — a failed
2532
- // sweep must not kill the worker; the next tick retries.
2533
- async maybeSweepTimers() {
2534
- if (this.timerSweepIntervalMs <= 0) return;
1829
+ // Runs inline in the dispatch loop (not fired concurrently) so two passes of
1830
+ // a sweep never overlap within a worker; across workers the store's sweeps
1831
+ // are safe to race (row locks / take-before-await). Errors are logged, never
1832
+ // thrown — a failed sweep must not kill the worker; the next tick retries.
1833
+ async runDueSweeps() {
1834
+ if (this.sweeps.length === 0) return;
2535
1835
  const now = this.deps.clock.now();
2536
- if (now.getTime() - this.lastTimerSweepAt < this.timerSweepIntervalMs)
2537
- return;
2538
- this.lastTimerSweepAt = now.getTime();
2539
- try {
2540
- await this.dispatcher.sweepTimers(now);
2541
- } catch (err) {
2542
- this.deps.emitLog({
2543
- level: "warn",
2544
- msg: "worker: signal-timeout sweep failed",
2545
- attrs: { error: String(err) }
2546
- });
1836
+ for (const sweep of this.sweeps) {
1837
+ if (now.getTime() - sweep.lastAt < sweep.intervalMs) continue;
1838
+ sweep.lastAt = now.getTime();
1839
+ try {
1840
+ await sweep.run(now);
1841
+ } catch (err) {
1842
+ this.deps.emitLog({
1843
+ level: "warn",
1844
+ msg: `worker: ${sweep.label} sweep failed`,
1845
+ attrs: { error: String(err) }
1846
+ });
1847
+ }
2547
1848
  }
2548
1849
  }
2549
1850
  aborted() {
@@ -2572,16 +1873,6 @@ async function nagiImpl(config) {
2572
1873
  }
2573
1874
  return events;
2574
1875
  };
2575
- if (streamTransport === void 0) {
2576
- for (const f of config.flows) {
2577
- for (const [stepId, step] of Object.entries(asStepMapWithDefs(f.steps))) {
2578
- if (getDef(step).kind !== "streaming") continue;
2579
- throw new NagiRuntimeError(
2580
- `Flow "${f.id}" has a streaming step "${stepId}" (b.streamingTask), but the store has no \`stream\` transport \u2014 it cannot carry ephemeral chunks. The in-memory store always exposes one; postgresStore() needs a \`listener\`. Otherwise remove the streaming step.`
2581
- );
2582
- }
2583
- }
2584
- }
2585
1876
  const registry = await registerFlows({
2586
1877
  flows: config.flows,
2587
1878
  store: config.store,
@@ -2589,76 +1880,77 @@ async function nagiImpl(config) {
2589
1880
  });
2590
1881
  const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
2591
1882
  const driftPolicy = config.driftPolicy ?? "freeze";
2592
- async function resolveFlow(runId) {
2593
- const resolution = registry.resolve(await config.store.loadRunState(runId));
2594
- if (resolution.kind !== "gone-live" || driftPolicy === "freeze") {
2595
- return resolution;
2596
- }
2597
- try {
2598
- return { kind: "current", flow: await registry.synthesize(resolution) };
2599
- } catch (err) {
2600
- if (!(err instanceof NagiRuntimeError)) throw err;
2601
- emitLog({
2602
- level: "warn",
2603
- msg: "resolveFlow: drift synthesis failed \u2014 treating run as snapshot-gone",
2604
- attrs: {
2605
- runId: resolution.error.runId,
2606
- flowId: resolution.error.flowId,
2607
- pinnedHash: resolution.error.pinnedHash,
2608
- error: err.message
2609
- }
2610
- });
2611
- return resolution;
2612
- }
2613
- }
2614
- function lookupFlow(flowId) {
2615
- return registry.get(flowId);
1883
+ const flowOfUnder = makeFlowOf({ registry, store: config.store, emitLog });
1884
+ const flowOf = (runId) => flowOfUnder(runId, driftPolicy);
1885
+ function makeEngine(env) {
1886
+ const deps = {
1887
+ flowOf: env.flowOf,
1888
+ lookupFlow: (flowId) => registry.get(flowId),
1889
+ startChildRun: (args) => lifecycle2.startChildRun(args),
1890
+ store: config.store,
1891
+ queue: env.queue,
1892
+ clock,
1893
+ emitLog,
1894
+ fireHooks: env.fireHooks,
1895
+ // The one fork point for heartbeat tuning: collapse the public optionals to
1896
+ // a single required config here so the dispatch internals never re-check it.
1897
+ heartbeat: {
1898
+ intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
1899
+ leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS,
1900
+ holdWarnMs: config.leaseHoldWarnMs ?? DEFAULT_LEASE_HOLD_WARN_MS
1901
+ },
1902
+ ...compact({
1903
+ hooks: config.hooks,
1904
+ defaultRetry: config.defaultRetry,
1905
+ streamTransport
1906
+ })
1907
+ };
1908
+ const dispatcher2 = makeDispatcher(deps);
1909
+ const hooks2 = makeHooks(deps);
1910
+ const lifecycle2 = makeRunLifecycle({
1911
+ store: config.store,
1912
+ queue: env.queue,
1913
+ clock,
1914
+ registry,
1915
+ flowOf: env.flowOf,
1916
+ codeVersion,
1917
+ queueForTx: (tx) => config.queue.withTx?.(tx) ?? config.queue,
1918
+ hooks: hooks2,
1919
+ flowHooks: config.hooks,
1920
+ dispatcher: dispatcher2
1921
+ });
1922
+ return { deps, dispatcher: dispatcher2, hooks: hooks2, lifecycle: lifecycle2 };
2616
1923
  }
2617
- const dispatchDeps = {
2618
- resolveFlow,
2619
- lookupFlow,
2620
- startChildRun: (args) => lifecycle.startChildRun(args),
2621
- store: config.store,
2622
- queue: config.queue,
2623
- clock,
2624
- emitLog,
2625
- // The one fork point for heartbeat tuning: collapse the public optionals to
2626
- // a single required config here so the dispatch internals never re-check it.
2627
- heartbeat: {
2628
- intervalMs: config.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
2629
- leaseMs: config.heartbeatLeaseMs ?? DEFAULT_HEARTBEAT_LEASE_MS,
2630
- holdWarnMs: config.leaseHoldWarnMs ?? DEFAULT_LEASE_HOLD_WARN_MS
2631
- },
2632
- ...compact({
2633
- hooks: config.hooks,
2634
- defaultRetry: config.defaultRetry,
2635
- streamTransport
2636
- })
2637
- };
2638
- const dispatcher = makeDispatcher(dispatchDeps);
2639
- const hooks = makeHooks(dispatchDeps);
2640
- const lifecycle = makeRunLifecycle({
2641
- store: config.store,
2642
- queue: config.queue,
2643
- clock,
2644
- registry,
2645
- codeVersion,
2646
- queueForTx: (tx) => config.queue.withTx?.(tx) ?? config.queue,
2647
- hooks,
2648
- flowHooks: config.hooks,
1924
+ const {
1925
+ deps: dispatchDeps,
2649
1926
  dispatcher,
2650
- emitLog
2651
- });
1927
+ hooks,
1928
+ lifecycle
1929
+ } = makeEngine({ flowOf, queue: config.queue, fireHooks: true });
2652
1930
  const signals = makeSignals({
2653
1931
  dispatcher,
2654
1932
  store: config.store,
2655
1933
  clock,
2656
- registry,
1934
+ // A signal only settles facts; under "freeze" a frozen-version worker may
1935
+ // still own the run and apply it, so its steps are named from the pinned
1936
+ // shape whatever this process may run.
1937
+ flowOf: (runId) => flowOfUnder(runId, "synthesize"),
2657
1938
  hooks,
2658
1939
  emitLog,
2659
1940
  ...compact({ flowHooks: config.hooks })
2660
1941
  });
2661
- const replayer = makeReplay({ ...dispatchDeps, registry, driftPolicy });
1942
+ const replayer = makeReplay({
1943
+ store: config.store,
1944
+ queue: config.queue,
1945
+ clock,
1946
+ registry,
1947
+ driftPolicy,
1948
+ flowOfUnder,
1949
+ dispatcherFor: (scope) => makeEngine({
1950
+ flowOf: pinRun(scope.run.runId, scope.run.flow, flowOf),
1951
+ ...scope.kind === "enqueue" ? { queue: config.queue, fireHooks: true } : { queue: scope.queue, fireHooks: false }
1952
+ }).dispatcher
1953
+ });
2662
1954
  const wf = {
2663
1955
  async start(flow2, input, opts) {
2664
1956
  return wf.startById(flow2.id, input, opts);
@@ -2703,28 +1995,26 @@ async function nagiImpl(config) {
2703
1995
  },
2704
1996
  signal: signals.signal,
2705
1997
  async cancel(runId, opts) {
2706
- await lifecycle.cancelRunRecursive(runId, {
1998
+ await dispatcher.cancel(runId, {
2707
1999
  cause: "explicit",
2708
2000
  reason: opts?.reason ?? "explicit wf.cancel()"
2709
2001
  });
2710
2002
  },
2711
- operator() {
2712
- return makeOperator({
2713
- dispatcher,
2714
- store: config.store,
2715
- clock,
2716
- registry,
2717
- cancelRunRecursive: lifecycle.cancelRunRecursive,
2718
- emitLog
2719
- });
2720
- },
2721
2003
  worker(workerConfig) {
2722
2004
  if (config.flows.length === 0) {
2723
2005
  throw new NagiRuntimeError(
2724
2006
  "nagi(): no flows registered \u2014 cannot create a worker."
2725
2007
  );
2726
2008
  }
2727
- return makeWorker({ ...dispatchDeps, clock }, workerConfig);
2009
+ return makeWorker(
2010
+ { ...dispatchDeps, clock },
2011
+ {
2012
+ ...workerConfig,
2013
+ ...compact({
2014
+ reaperIntervalMs: workerConfig?.reaperIntervalMs ?? config.reaperIntervalMs
2015
+ })
2016
+ }
2017
+ );
2728
2018
  },
2729
2019
  replay: replayer.replay,
2730
2020
  async describe(runId) {
@@ -2738,17 +2028,6 @@ async function nagiImpl(config) {
2738
2028
  }
2739
2029
  return config.queue.inspect(runId);
2740
2030
  },
2741
- async queryRuns(opts = {}) {
2742
- if (opts.latest === true) {
2743
- if (opts.limit !== void 0 || opts.cursor !== void 0) {
2744
- throw validationError(
2745
- "queryRuns: `latest: true` is incompatible with `limit` / `cursor` \u2014 `latest` returns at most one row.",
2746
- ["latest"]
2747
- );
2748
- }
2749
- }
2750
- return config.store.queryRuns(opts);
2751
- },
2752
2031
  subscribe(runId, stepId, opts) {
2753
2032
  if (!registry.isStreaming(stepId)) {
2754
2033
  throw new NagiRuntimeError(
@@ -2807,42 +2086,15 @@ async function nagiRun(config) {
2807
2086
  const internal = new AbortController();
2808
2087
  const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
2809
2088
  const worker = wf.worker({ ...config.worker, signal });
2810
- const emitLog = makeEmit(config.onLog);
2811
- const clock = config.clock ?? new InMemoryClock();
2812
2089
  const loop = worker.run();
2813
2090
  loop.catch((err) => {
2814
2091
  if (signal.aborted) return;
2815
- emitLog({
2092
+ makeEmit(config.onLog)({
2816
2093
  level: "error",
2817
2094
  msg: "nagi.run: worker exited unexpectedly",
2818
2095
  attrs: { error: String(err) }
2819
2096
  });
2820
2097
  });
2821
- const reaperIntervalMs = config.reaperIntervalMs ?? DEFAULT_REAPER_INTERVAL_MS;
2822
- const reaper = reaperIntervalMs > 0 ? (async () => {
2823
- while (!signal.aborted) {
2824
- try {
2825
- await clock.sleep(reaperIntervalMs, signal);
2826
- } catch {
2827
- return;
2828
- }
2829
- if (signal.aborted) return;
2830
- try {
2831
- await config.store.sweepLeases({
2832
- now: clock.now(),
2833
- queue: config.queue
2834
- });
2835
- } catch (err) {
2836
- emitLog({
2837
- level: "warn",
2838
- msg: "nagi.run: lease reaper sweep failed",
2839
- attrs: { error: String(err) }
2840
- });
2841
- }
2842
- }
2843
- })() : Promise.resolve();
2844
- reaper.catch(() => {
2845
- });
2846
2098
  let stopping;
2847
2099
  const stop = () => {
2848
2100
  stopping ??= (async () => {
@@ -2851,10 +2103,6 @@ async function nagiRun(config) {
2851
2103
  await loop;
2852
2104
  } catch {
2853
2105
  }
2854
- try {
2855
- await reaper;
2856
- } catch {
2857
- }
2858
2106
  })();
2859
2107
  return stopping;
2860
2108
  };
@@ -2867,6 +2115,6 @@ var nagi = Object.assign(
2867
2115
  async function noop() {
2868
2116
  }
2869
2117
 
2870
- export { NagiAbortError, RunId, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, optional, sha256Canonical };
2118
+ export { NagiAbortError, RunId, flow, nagi, optional };
2871
2119
  //# sourceMappingURL=index.js.map
2872
2120
  //# sourceMappingURL=index.js.map