@nagi-js/core 0.1.1-rc.0 → 0.1.1-rc.10

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
@@ -3,9 +3,6 @@ var DEF = "__def";
3
3
  function attachDef(meta, def) {
4
4
  return { kind: meta.kind, id: meta.id, [DEF]: def };
5
5
  }
6
- function attachDefMut(step, def) {
7
- step[DEF] = def;
8
- }
9
6
  function getDef(step) {
10
7
  const def = step[DEF];
11
8
  if (def === void 0) {
@@ -16,70 +13,38 @@ function getDef(step) {
16
13
  return def;
17
14
  }
18
15
  function needsStepIds(def) {
19
- const out = [];
20
- for (const upstream of Object.values(def.needs)) {
21
- if (upstream && typeof upstream === "object" && "id" in upstream && typeof upstream.id === "string") {
22
- out.push(upstream.id);
23
- }
24
- }
25
- return out;
16
+ return Object.values(def.needs).map((upstream) => upstream.id);
26
17
  }
27
18
  function resolveNeeds(def, loadOutput) {
28
19
  const result = {};
29
20
  for (const [localKey, upstream] of Object.entries(def.needs)) {
30
- if (upstream && typeof upstream === "object" && "id" in upstream && typeof upstream.id === "string") {
31
- result[localKey] = loadOutput(upstream.id);
32
- }
21
+ result[localKey] = loadOutput(upstream.id);
33
22
  }
34
23
  return result;
35
24
  }
36
- function matchArms(def) {
37
- return def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
38
- }
39
25
  function readSelectedArm(matchId, runState) {
26
+ let selected = null;
40
27
  for (const fact of runState.facts) {
41
28
  if (fact.kind === "match.arm-selected" && fact.stepId === matchId) {
42
- return fact.arm;
29
+ selected = fact.arm;
30
+ } else if (fact.kind === "step.reset" && fact.stepId === matchId) {
31
+ selected = null;
43
32
  }
44
33
  }
45
- return null;
34
+ return selected;
46
35
  }
47
36
  function selectArm(def, args) {
48
- if (def.mode === "discriminator") {
49
- const key = def.on(args);
50
- if (def.arms[key] === void 0) {
51
- const available = Object.keys(def.arms).join(", ");
52
- throw new Error(
53
- `match: discriminator returned "${key}" which has no arm (available: ${available || "<none>"})`
54
- );
55
- }
56
- return key;
57
- }
58
37
  for (const arm of def.arms) {
59
38
  if (arm.otherwise) return arm.id;
60
39
  if (arm.when?.(args)) return arm.id;
61
40
  }
62
41
  throw new Error(
63
- `match: no guard arm matched and no { otherwise: true } fallback was provided`
42
+ `match: no arm matched and no { otherwise: true } fallback was provided`
64
43
  );
65
44
  }
66
45
 
67
46
  // src/builder.ts
68
- var BUILDER_BRAND = /* @__PURE__ */ Symbol.for("nagi.builder");
69
- function isBuilder(value) {
70
- return typeof value === "object" && value !== null && value[BUILDER_BRAND] === true;
71
- }
72
- function resolveBuildResult(value) {
73
- if (isBuilder(value)) {
74
- return Object.fromEntries(value.__steps);
75
- }
76
- return value;
77
- }
78
- function isDiscriminator(config) {
79
- return "cases" in config && "on" in config;
80
- }
81
47
  function makeBuilder() {
82
- const chainSteps = /* @__PURE__ */ new Map();
83
48
  function task(config) {
84
49
  const def = {
85
50
  kind: "task",
@@ -89,7 +54,13 @@ function makeBuilder() {
89
54
  ...config.when !== void 0 ? {
90
55
  when: config.when
91
56
  } : {},
92
- run: config.run
57
+ run: config.run,
58
+ ...config.onStart !== void 0 ? { onStart: config.onStart } : {},
59
+ ...config.onComplete !== void 0 ? {
60
+ onComplete: config.onComplete
61
+ } : {},
62
+ ...config.onError !== void 0 ? { onError: config.onError } : {},
63
+ ...config.onRetry !== void 0 ? { onRetry: config.onRetry } : {}
93
64
  };
94
65
  return attachDef({ kind: "task", id: "" }, def);
95
66
  }
@@ -98,6 +69,7 @@ function makeBuilder() {
98
69
  kind: "signal",
99
70
  needs: config.needs ?? {},
100
71
  schema: config.schema,
72
+ ...config.names !== void 0 ? { names: config.names } : {},
101
73
  ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
102
74
  ...config.when !== void 0 ? {
103
75
  when: config.when
@@ -105,30 +77,28 @@ function makeBuilder() {
105
77
  };
106
78
  return attachDef({ kind: "signal", id: "" }, def);
107
79
  }
80
+ function subflow(child, config) {
81
+ const def = {
82
+ kind: "subflow",
83
+ needs: config.needs ?? {},
84
+ childFlowId: child.id,
85
+ buildInput: config.input,
86
+ ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
87
+ ...config.when !== void 0 ? {
88
+ when: config.when
89
+ } : {}
90
+ };
91
+ return attachDef(
92
+ { kind: "subflow", id: "" },
93
+ def
94
+ );
95
+ }
108
96
  function match(config) {
109
- const needs = "needs" in config && config.needs ? config.needs : {};
110
- if (isDiscriminator(config)) {
111
- const arms2 = {};
112
- for (const [caseKey, build] of Object.entries(config.cases)) {
113
- const nested = resolveBuildResult(
114
- build(makeBuilder())
115
- );
116
- arms2[caseKey] = { id: caseKey, stepIds: [], _nested: nested };
117
- }
118
- const def2 = {
119
- kind: "match",
120
- mode: "discriminator",
121
- needs,
122
- on: config.on,
123
- arms: arms2
124
- };
125
- return attachDef({ kind: "match", id: "" }, def2);
126
- }
127
- const guardConfig = config;
97
+ const needs = config.needs ?? {};
128
98
  const arms = [];
129
- for (let i = 0; i < guardConfig.arms.length; i++) {
130
- const arm = guardConfig.arms[i];
131
- const nested = resolveBuildResult(arm.build(makeBuilder()));
99
+ for (let i = 0; i < config.arms.length; i++) {
100
+ const arm = config.arms[i];
101
+ const nested = arm.build(makeBuilder());
132
102
  const armId = arm.otherwise ? "otherwise" : `arm${i}`;
133
103
  arms.push({
134
104
  id: armId,
@@ -136,74 +106,25 @@ function makeBuilder() {
136
106
  when: arm.when
137
107
  } : {},
138
108
  ...arm.otherwise ? { otherwise: true } : {},
139
- stepIds: [],
140
- _nested: nested
109
+ nested
141
110
  });
142
111
  }
143
- const def = {
144
- kind: "match",
145
- mode: "guard",
146
- needs,
147
- arms
148
- };
149
- return attachDef({ kind: "match", id: "" }, def);
150
- }
151
- function step(key, config) {
152
- if (chainSteps.has(key)) {
153
- throw new Error(
154
- `b.step: duplicate key "${key}" \u2014 each chain entry must have a unique key.`
155
- );
156
- }
157
- const shell = { kind: "task", id: "" };
158
- const needs = {};
159
- if (config.needs) {
160
- for (const sibKey of config.needs) {
161
- const sibling = chainSteps.get(sibKey);
162
- if (sibling === void 0) {
163
- throw new Error(
164
- `b.step("${key}"): unknown sibling "${sibKey}". Available keys so far: ${[...chainSteps.keys()].join(", ") || "<none>"}.`
165
- );
166
- }
167
- needs[sibKey] = sibling;
168
- }
169
- }
170
- const def = {
171
- kind: "task",
172
- needs,
173
- ...config.retry !== void 0 ? { retry: config.retry } : {},
174
- ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
175
- ...config.when !== void 0 ? {
176
- when: config.when
177
- } : {},
178
- run: config.run
179
- };
180
- attachDefMut(shell, def);
181
- chainSteps.set(key, shell);
182
- return builder;
183
- }
184
- function include(key, s) {
185
- if (chainSteps.has(key)) {
186
- throw new Error(
187
- `b.include: duplicate key "${key}" \u2014 each chain entry must have a unique key.`
188
- );
189
- }
190
- chainSteps.set(key, s);
191
- return builder;
112
+ const def = { kind: "match", needs, arms };
113
+ return attachDef(
114
+ { kind: "match", id: "" },
115
+ def
116
+ );
192
117
  }
193
- const builder = {
118
+ return {
194
119
  task,
195
120
  signal,
196
- match,
197
- step,
198
- include,
199
- [BUILDER_BRAND]: true,
200
- __steps: chainSteps
121
+ subflow,
122
+ match
201
123
  };
202
- return builder;
203
124
  }
204
125
  function flow(config) {
205
126
  const builder = makeBuilder();
206
- const built = resolveBuildResult(config.build(builder));
127
+ const built = config.build(builder);
207
128
  const idByIdentity = /* @__PURE__ */ new Map();
208
129
  collectIds(built, "", idByIdentity);
209
130
  const finalSteps = {};
@@ -215,11 +136,31 @@ function flow(config) {
215
136
  idByIdentity,
216
137
  out: finalSteps
217
138
  });
139
+ assertSignalNameUniqueness(config.id, finalSteps);
218
140
  return {
219
141
  id: config.id,
220
142
  input: config.input,
221
143
  steps: finalSteps,
222
- ...config.output !== void 0 ? { output: config.output } : {}
144
+ ...config.output !== void 0 ? { output: config.output } : {},
145
+ ...config.onStart !== void 0 ? { onStart: config.onStart } : {},
146
+ ...config.onComplete !== void 0 ? {
147
+ onComplete: config.onComplete
148
+ } : {},
149
+ ...config.onError !== void 0 ? { onError: config.onError } : {},
150
+ ...config.concurrency !== void 0 ? { concurrency: normalizeConcurrency(config.concurrency) } : {}
151
+ };
152
+ }
153
+ function normalizeConcurrency(c) {
154
+ if (typeof c === "object") {
155
+ return {
156
+ keyFn: c.keyFn,
157
+ mode: c.mode ?? "cancel-in-progress"
158
+ };
159
+ }
160
+ const key = c;
161
+ return {
162
+ keyFn: (input) => input[key],
163
+ mode: "cancel-in-progress"
223
164
  };
224
165
  }
225
166
  function collectIds(map, prefix, idByIdentity) {
@@ -228,10 +169,9 @@ function collectIds(map, prefix, idByIdentity) {
228
169
  idByIdentity.set(step, id);
229
170
  const def = step.__def;
230
171
  if (def?.kind === "match") {
231
- const arms = def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
232
- for (const arm of arms) {
233
- if (arm._nested)
234
- collectIds(arm._nested, `${id}.${arm.id}`, idByIdentity);
172
+ const pending = def;
173
+ for (const arm of pending.arms) {
174
+ collectIds(arm.nested, `${id}.${arm.id}`, idByIdentity);
235
175
  }
236
176
  }
237
177
  }
@@ -263,24 +203,22 @@ function walkAndRewrite(args) {
263
203
  rewrittenNeeds[localKey] = { ...upstream, id: upstreamId };
264
204
  }
265
205
  if (def.kind === "match") {
266
- const armList = def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
206
+ const pending = def;
267
207
  const finalizedArms = [];
268
- for (const arm of armList) {
208
+ for (const arm of pending.arms) {
269
209
  const armPrefix = `${id}.${arm.id}`;
270
210
  const nestedStepIds = [];
271
- if (arm._nested) {
272
- for (const nestedKey of Object.keys(arm._nested)) {
273
- nestedStepIds.push(`${armPrefix}.${nestedKey}`);
274
- }
275
- walkAndRewrite({
276
- flowId,
277
- map: arm._nested,
278
- prefix: armPrefix,
279
- parentMatch: { matchId: id, armId: arm.id },
280
- idByIdentity,
281
- out
282
- });
211
+ for (const nestedKey of Object.keys(arm.nested)) {
212
+ nestedStepIds.push(`${armPrefix}.${nestedKey}`);
283
213
  }
214
+ walkAndRewrite({
215
+ flowId,
216
+ map: arm.nested,
217
+ prefix: armPrefix,
218
+ parentMatch: { matchId: id, armId: arm.id },
219
+ idByIdentity,
220
+ out
221
+ });
284
222
  finalizedArms.push({
285
223
  id: arm.id,
286
224
  ...arm.when !== void 0 ? { when: arm.when } : {},
@@ -288,16 +226,8 @@ function walkAndRewrite(args) {
288
226
  stepIds: nestedStepIds
289
227
  });
290
228
  }
291
- const finalizedDef2 = def.mode === "discriminator" ? {
229
+ const finalizedDef2 = {
292
230
  kind: "match",
293
- mode: "discriminator",
294
- needs: rewrittenNeeds,
295
- on: def.on,
296
- arms: Object.fromEntries(finalizedArms.map((a) => [a.id, a])),
297
- ...parentMatch ? { parentMatch } : {}
298
- } : {
299
- kind: "match",
300
- mode: "guard",
301
231
  needs: rewrittenNeeds,
302
232
  arms: finalizedArms,
303
233
  ...parentMatch ? { parentMatch } : {}
@@ -310,6 +240,28 @@ function walkAndRewrite(args) {
310
240
  out[id] = attachDef({ kind: finalizedDef.kind, id }, finalizedDef);
311
241
  }
312
242
  }
243
+ function assertSignalNameUniqueness(flowId, finalSteps) {
244
+ const owners = /* @__PURE__ */ new Map();
245
+ for (const stepId of Object.keys(finalSteps)) {
246
+ owners.set(stepId, `step id "${stepId}"`);
247
+ }
248
+ for (const [stepId, step] of Object.entries(finalSteps)) {
249
+ const def = step.__def;
250
+ if (def === void 0 || def.kind !== "signal") continue;
251
+ if (def.names === void 0) continue;
252
+ for (const alias of def.names) {
253
+ if (alias === stepId) continue;
254
+ const prior = owners.get(alias);
255
+ const here = `alias of step "${stepId}"`;
256
+ if (prior !== void 0 && prior !== here) {
257
+ throw new Error(
258
+ `Flow "${flowId}": signal name "${alias}" is declared as both ${prior} and ${here}. Pick one \u2014 signal names share a namespace with step ids.`
259
+ );
260
+ }
261
+ owners.set(alias, here);
262
+ }
263
+ }
264
+ }
313
265
 
314
266
  // src/canonicalize.ts
315
267
  var DEFAULT_RETRY = {
@@ -321,7 +273,7 @@ function warnSourceHashOnce() {
321
273
  if (warnedAboutSourceHash) return;
322
274
  warnedAboutSourceHash = true;
323
275
  console.warn(
324
- "[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. See RFC 0001."
276
+ "[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."
325
277
  );
326
278
  }
327
279
  async function canonicalize(flow2) {
@@ -343,6 +295,7 @@ async function canonicalizeStep(id, def) {
343
295
  const base = { id, kind: def.kind, needs };
344
296
  if (def.kind === "task") return canonicalizeTask(base, def);
345
297
  if (def.kind === "signal") return canonicalizeSignal(base, def);
298
+ if (def.kind === "subflow") return canonicalizeSubflow(base, def);
346
299
  return canonicalizeMatch(base, def);
347
300
  }
348
301
  async function canonicalizeTask(base, def) {
@@ -357,16 +310,23 @@ async function canonicalizeSignal(base, def) {
357
310
  if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
358
311
  if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
359
312
  out.signalSchema = await canonicalizeSchema(def.schema);
313
+ if (def.names !== void 0) {
314
+ out.signalNames = [...def.names].sort();
315
+ }
316
+ return out;
317
+ }
318
+ async function canonicalizeSubflow(base, def) {
319
+ const out = { ...base };
320
+ if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
321
+ if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
322
+ out.childFlowId = def.childFlowId;
323
+ out.subflowInputHash = await hashFnSource(def.buildInput);
360
324
  return out;
361
325
  }
362
326
  async function canonicalizeMatch(base, def) {
363
327
  const out = { ...base };
364
- out.matchMode = def.mode;
365
- if (def.mode === "discriminator") {
366
- out.matchOnHash = await hashFnSource(def.on);
367
- }
368
328
  const arms = [];
369
- for (const arm of matchArms(def)) {
329
+ for (const arm of def.arms) {
370
330
  arms.push(await canonicalizeArm(arm));
371
331
  }
372
332
  out.matchArms = arms;
@@ -404,6 +364,15 @@ async function hashFnSource(fn) {
404
364
  async function sha256Canonical(dag) {
405
365
  return sha256Hex(stableStringify(dag));
406
366
  }
367
+ async function fingerprintFlows(flows) {
368
+ const entries = [];
369
+ for (const f of flows) {
370
+ const dag = await canonicalize(f);
371
+ entries.push([f.id, await sha256Canonical(dag)]);
372
+ }
373
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
374
+ return sha256Hex(stableStringify(entries));
375
+ }
407
376
  function stableStringify(value) {
408
377
  if (value === void 0) return "null";
409
378
  if (value === null || typeof value !== "object") return JSON.stringify(value);
@@ -498,12 +467,6 @@ function diffFields(before, after, out) {
498
467
  if (!schemaEq(before.signalSchema, after.signalSchema)) {
499
468
  out.push({ stepId: id, field: "signalSchema" });
500
469
  }
501
- if (before.matchMode !== after.matchMode) {
502
- out.push({ stepId: id, field: "matchMode" });
503
- }
504
- if (before.matchOnHash !== after.matchOnHash) {
505
- out.push({ stepId: id, field: "matchOn" });
506
- }
507
470
  if (!armsEq(before.matchArms, after.matchArms)) {
508
471
  out.push({ stepId: id, field: "matchArms" });
509
472
  }
@@ -550,6 +513,10 @@ var InMemoryStore = class {
550
513
  snapshots = /* @__PURE__ */ new Map();
551
514
  refs = /* @__PURE__ */ new Map();
552
515
  globalFacts = [];
516
+ activeByKey = /* @__PURE__ */ new Map();
517
+ keyByActiveRun = /* @__PURE__ */ new Map();
518
+ childrenByParent = /* @__PURE__ */ new Map();
519
+ summaries = /* @__PURE__ */ new Map();
553
520
  leaseMs;
554
521
  constructor(opts = {}) {
555
522
  this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
@@ -558,13 +525,59 @@ var InMemoryStore = class {
558
525
  const list = this.facts.get(runId) ?? [];
559
526
  list.push(fact);
560
527
  this.facts.set(runId, list);
528
+ if (fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled") {
529
+ const slot = this.keyByActiveRun.get(runId);
530
+ if (slot !== void 0) {
531
+ this.keyByActiveRun.delete(runId);
532
+ if (this.activeByKey.get(slot) === runId) {
533
+ this.activeByKey.delete(slot);
534
+ }
535
+ }
536
+ }
537
+ if (fact.kind === "step.reset") {
538
+ const leasePrefix = `${runId}::${fact.stepId}::`;
539
+ for (const key of this.leases.keys()) {
540
+ if (key.startsWith(leasePrefix)) this.leases.delete(key);
541
+ }
542
+ this.outputs.delete(`${runId}::${fact.stepId}`);
543
+ }
561
544
  }
562
- async tryStartRun(runId, fact) {
563
- if (this.facts.has(runId)) {
564
- return { started: false };
545
+ async tryStartRun(runId, fact, concurrency) {
546
+ if (this.facts.has(runId) || this.summaries.has(runId)) {
547
+ return { started: false, canceled: [] };
548
+ }
549
+ const canceled = [];
550
+ if (concurrency !== void 0) {
551
+ const slot = `${fact.flowId}::${concurrency.key}`;
552
+ const priorRunId = this.activeByKey.get(slot);
553
+ if (priorRunId !== void 0) {
554
+ const cancelFact = {
555
+ kind: "flow.canceled",
556
+ cause: "concurrency",
557
+ runId: priorRunId,
558
+ at: fact.at,
559
+ canceledByRunId: runId,
560
+ concurrencyKey: concurrency.key
561
+ };
562
+ await this.appendFact(priorRunId, cancelFact);
563
+ canceled.push({ runId: priorRunId, fact: cancelFact });
564
+ }
565
+ this.activeByKey.set(slot, runId);
566
+ this.keyByActiveRun.set(runId, slot);
565
567
  }
566
568
  this.facts.set(runId, [fact]);
567
- return { started: true };
569
+ const parentRunId = fact.parent?.runId;
570
+ if (parentRunId !== void 0) {
571
+ const set = this.childrenByParent.get(parentRunId) ?? /* @__PURE__ */ new Set();
572
+ set.add(runId);
573
+ this.childrenByParent.set(parentRunId, set);
574
+ }
575
+ return { started: true, canceled };
576
+ }
577
+ async listChildren(parentRunId) {
578
+ const set = this.childrenByParent.get(parentRunId);
579
+ if (set === void 0) return [];
580
+ return Array.from(set);
568
581
  }
569
582
  async loadRunState(runId) {
570
583
  return projectRunState(runId, this.facts.get(runId) ?? []);
@@ -600,8 +613,10 @@ var InMemoryStore = class {
600
613
  const result = await body(void 0);
601
614
  if (result.fact.kind === "step.completed") {
602
615
  await this.completeStep(runId, stepId, result.output, result.fact);
603
- } else {
616
+ } else if (result.fact.kind === "step.failed") {
604
617
  await this.failStep(runId, stepId, result.fact.error, result.fact);
618
+ } else {
619
+ await this.appendFact(runId, result.fact);
605
620
  }
606
621
  return result.output;
607
622
  }
@@ -621,11 +636,172 @@ var InMemoryStore = class {
621
636
  async appendGlobalFact(fact) {
622
637
  this.globalFacts.push(fact);
623
638
  }
624
- /** Test-only: peek at the in-memory global fact log. */
625
639
  readGlobalFacts() {
626
640
  return this.globalFacts;
627
641
  }
642
+ async queryRuns(opts) {
643
+ const where = opts.where ?? {};
644
+ const statuses = where.status === void 0 ? void 0 : Array.isArray(where.status) ? where.status : [where.status];
645
+ const matches = (summary) => {
646
+ if (where.flowId !== void 0 && summary.flowId !== where.flowId)
647
+ return false;
648
+ if (statuses !== void 0 && !statuses.includes(summary.status))
649
+ return false;
650
+ if (where.input !== void 0 && !containsJson(summary.input, where.input))
651
+ return false;
652
+ return true;
653
+ };
654
+ const summaries = [];
655
+ for (const [runId, factList] of this.facts) {
656
+ const summary = summarize(runId, factList);
657
+ if (summary === null) continue;
658
+ if (matches(summary)) summaries.push(summary);
659
+ }
660
+ for (const summary of this.summaries.values()) {
661
+ if (matches(summary)) summaries.push(summary);
662
+ }
663
+ summaries.sort((a, b) => {
664
+ const t = b.startedAt.getTime() - a.startedAt.getTime();
665
+ if (t !== 0) return t;
666
+ return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
667
+ });
668
+ if (opts.latest === true) {
669
+ return { runs: summaries.slice(0, 1), cursor: null };
670
+ }
671
+ const limit = clampLimit(opts.limit);
672
+ let start = 0;
673
+ if (opts.cursor !== void 0) {
674
+ const c = decodeCursor(opts.cursor);
675
+ start = summaries.findIndex(
676
+ (s) => s.startedAt.getTime() < c.t || s.startedAt.getTime() === c.t && s.runId < c.r
677
+ );
678
+ if (start === -1) start = summaries.length;
679
+ }
680
+ const page = summaries.slice(start, start + limit);
681
+ const hasMore = start + limit < summaries.length;
682
+ const last = page[page.length - 1];
683
+ const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
684
+ return { runs: page, cursor };
685
+ }
686
+ async pruneFacts(opts) {
687
+ const olderThanMs = opts.olderThan.getTime();
688
+ const statusSet = new Set(opts.statuses);
689
+ const victims = [];
690
+ for (const [runId, factList] of this.facts) {
691
+ const summary = summarize(runId, factList);
692
+ if (summary === null) continue;
693
+ if (summary.completedAt === null) continue;
694
+ if (!statusSet.has(summary.status)) continue;
695
+ if (summary.completedAt.getTime() >= olderThanMs) continue;
696
+ const first = factList[0];
697
+ const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parent?.runId : void 0;
698
+ victims.push({
699
+ runId,
700
+ summary,
701
+ factCount: factList.length,
702
+ parentRunId
703
+ });
704
+ }
705
+ let runsPruned = 0;
706
+ let factsPruned = 0;
707
+ for (const v of victims) {
708
+ this.facts.delete(v.runId);
709
+ deleteByRunPrefix(this.outputs, v.runId);
710
+ deleteByRunPrefix(this.onces, v.runId);
711
+ deleteByRunPrefix(this.leases, v.runId);
712
+ this.childrenByParent.delete(v.runId);
713
+ if (v.parentRunId !== void 0) {
714
+ const siblings = this.childrenByParent.get(v.parentRunId);
715
+ if (siblings !== void 0) {
716
+ siblings.delete(v.runId);
717
+ if (siblings.size === 0) this.childrenByParent.delete(v.parentRunId);
718
+ }
719
+ }
720
+ if (opts.keepSummary) {
721
+ this.summaries.set(v.runId, v.summary);
722
+ } else {
723
+ this.summaries.delete(v.runId);
724
+ }
725
+ runsPruned += 1;
726
+ factsPruned += v.factCount;
727
+ }
728
+ return { runsPruned, factsPruned };
729
+ }
628
730
  };
731
+ function deleteByRunPrefix(map, runId) {
732
+ const prefix = `${runId}::`;
733
+ for (const key of map.keys()) {
734
+ if (key.startsWith(prefix)) map.delete(key);
735
+ }
736
+ }
737
+ function summarize(runId, facts) {
738
+ const first = facts[0];
739
+ if (first === void 0 || first.kind !== "flow.started") return null;
740
+ const projected = projectRunState(runId, facts);
741
+ let completedAt = null;
742
+ for (let i = facts.length - 1; i >= 0; i--) {
743
+ const f = facts[i];
744
+ if (f === void 0) continue;
745
+ if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
746
+ completedAt = f.at;
747
+ break;
748
+ }
749
+ }
750
+ return {
751
+ runId,
752
+ flowId: first.flowId,
753
+ status: projected.status,
754
+ startedAt: first.at,
755
+ completedAt,
756
+ input: first.input
757
+ };
758
+ }
759
+ var DEFAULT_LIMIT = 50;
760
+ var MAX_LIMIT = 500;
761
+ function clampLimit(limit) {
762
+ if (limit === void 0) return DEFAULT_LIMIT;
763
+ if (!Number.isInteger(limit) || limit < 1) return DEFAULT_LIMIT;
764
+ return Math.min(limit, MAX_LIMIT);
765
+ }
766
+ function encodeCursor(c) {
767
+ const bytes = new TextEncoder().encode(JSON.stringify(c));
768
+ let binary = "";
769
+ for (let i = 0; i < bytes.length; i++) {
770
+ binary += String.fromCharCode(bytes[i]);
771
+ }
772
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
773
+ }
774
+ function decodeCursor(s) {
775
+ try {
776
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
777
+ const binary = atob(b64);
778
+ const bytes = new Uint8Array(binary.length);
779
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
780
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
781
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
782
+ return parsed;
783
+ }
784
+ throw new Error("malformed cursor body");
785
+ } catch (err) {
786
+ throw new Error(
787
+ `queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
788
+ );
789
+ }
790
+ }
791
+ function containsJson(haystack, needle) {
792
+ if (Array.isArray(needle)) {
793
+ if (!Array.isArray(haystack)) return false;
794
+ return needle.every((n) => haystack.some((h) => containsJson(h, n)));
795
+ }
796
+ if (needle !== null && typeof needle === "object") {
797
+ if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
798
+ return false;
799
+ return Object.entries(needle).every(
800
+ ([k, v]) => k in haystack && containsJson(haystack[k], v)
801
+ );
802
+ }
803
+ return haystack === needle;
804
+ }
629
805
  function projectRunState(runId, facts) {
630
806
  let flowId = "";
631
807
  let status = "pending";
@@ -646,6 +822,9 @@ function projectRunState(runId, facts) {
646
822
  case "flow.failed":
647
823
  status = "failed";
648
824
  break;
825
+ case "flow.canceled":
826
+ status = "canceled";
827
+ break;
649
828
  case "step.started":
650
829
  steps[fact.stepId] = {
651
830
  stepId: fact.stepId,
@@ -669,6 +848,14 @@ function projectRunState(runId, facts) {
669
848
  error: fact.error
670
849
  };
671
850
  break;
851
+ case "step.canceled":
852
+ steps[fact.stepId] = {
853
+ stepId: fact.stepId,
854
+ status: "canceled",
855
+ attempts: fact.attempt,
856
+ ...fact.error !== void 0 ? { error: fact.error } : {}
857
+ };
858
+ break;
672
859
  case "step.skipped":
673
860
  steps[fact.stepId] = {
674
861
  stepId: fact.stepId,
@@ -676,6 +863,9 @@ function projectRunState(runId, facts) {
676
863
  attempts: 0
677
864
  };
678
865
  break;
866
+ case "step.reset":
867
+ delete steps[fact.stepId];
868
+ break;
679
869
  }
680
870
  }
681
871
  return {
@@ -779,7 +969,6 @@ var InMemoryClock = class {
779
969
  }, delay);
780
970
  this.timers.set(key, handle);
781
971
  }
782
- /** Clear any pending scheduled timers. Call from test teardown. */
783
972
  dispose() {
784
973
  for (const t of this.timers.values()) clearTimeout(t);
785
974
  this.timers.clear();
@@ -793,10 +982,6 @@ var InMemoryTrigger = class {
793
982
  this.handlers = this.handlers.filter((h) => h !== handler);
794
983
  };
795
984
  }
796
- /**
797
- * Test-only: synchronously dispatch a wake-up to all subscribers.
798
- * Real triggers fire from a Store change (NOTIFY/LISTEN, polling, etc.).
799
- */
800
985
  fire(runId) {
801
986
  for (const h of this.handlers) h(runId);
802
987
  }
@@ -806,8 +991,11 @@ var InMemoryTrigger = class {
806
991
  function makeIdempotencyKey(runId, stepId) {
807
992
  return (scope) => `nagi:${runId}:${stepId}:${scope}`;
808
993
  }
809
- function makeOnce(args) {
810
- const { runId, stepId, store } = args;
994
+ function makeOnce({
995
+ runId,
996
+ stepId,
997
+ store
998
+ }) {
811
999
  return async function once(scope, fn) {
812
1000
  const cached = await store.getOnce(runId, stepId, scope);
813
1001
  if (cached !== null) return cached;
@@ -856,19 +1044,31 @@ function nextRunnable(args) {
856
1044
  }
857
1045
  function checkUpstream(def, runState) {
858
1046
  for (const upstream of Object.values(def.needs)) {
859
- if (!upstream || typeof upstream !== "object" || !("id" in upstream) || typeof upstream.id !== "string") {
860
- continue;
861
- }
862
1047
  const upstreamState = runState.steps[upstream.id];
863
1048
  if (upstreamState === void 0) return "blocked";
864
1049
  if (upstreamState.status === "completed") continue;
865
- if (upstreamState.status === "skipped" || upstreamState.status === "failed") {
1050
+ if (upstreamState.status === "skipped") {
1051
+ if (manualSkipCascade(upstream.id, runState) === "continue") continue;
1052
+ return "transitive-skip";
1053
+ }
1054
+ if (upstreamState.status === "failed") {
866
1055
  return "transitive-skip";
867
1056
  }
868
1057
  return "blocked";
869
1058
  }
870
1059
  return "ready";
871
1060
  }
1061
+ function manualSkipCascade(stepId, runState) {
1062
+ for (let i = runState.facts.length - 1; i >= 0; i--) {
1063
+ const f = runState.facts[i];
1064
+ if (f === void 0) continue;
1065
+ if (f.kind !== "step.skipped") continue;
1066
+ if (f.stepId !== stepId) continue;
1067
+ if (f.reason !== "manual") return "skip";
1068
+ return f.cascade ?? "skip";
1069
+ }
1070
+ return "skip";
1071
+ }
872
1072
  function checkParentMatch(def, runState) {
873
1073
  if (!def.parentMatch) return "ready";
874
1074
  const { matchId, armId } = def.parentMatch;
@@ -887,7 +1087,7 @@ function aggregateMatch(matchId, flow2, runState) {
887
1087
  if (def.kind !== "match") return { kind: "pending" };
888
1088
  const selected = readSelectedArm(matchId, runState);
889
1089
  if (selected === null) return { kind: "pending" };
890
- const arm = def.mode === "discriminator" ? def.arms[selected] : def.arms.find((a) => a.id === selected);
1090
+ const arm = def.arms.find((a) => a.id === selected);
891
1091
  if (!arm) return { kind: "pending" };
892
1092
  const output = {};
893
1093
  let allTerminal = true;
@@ -920,6 +1120,105 @@ function flowTermination(flow2, runState) {
920
1120
  }
921
1121
  return { done, failed };
922
1122
  }
1123
+ function nextTransition(flow2, runState) {
1124
+ const promotions = readyPromotions(flow2, runState);
1125
+ if (promotions.length > 0) return { kind: "promote-match", promotions };
1126
+ const term = flowTermination(flow2, runState);
1127
+ if (term.done) {
1128
+ if (isFlowTerminal(runState.facts)) return { kind: "settled" };
1129
+ if (term.failed) return { kind: "fail", error: flowFailureError(runState) };
1130
+ return { kind: "complete", output: computeFlowOutput(flow2, runState) };
1131
+ }
1132
+ const input = extractInput(runState);
1133
+ const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
1134
+ if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
1135
+ if (skip.length > 0) return { kind: "skip", skip };
1136
+ return { kind: "waiting" };
1137
+ }
1138
+ function readyPromotions(flow2, runState) {
1139
+ const out = [];
1140
+ for (const [matchId, step] of Object.entries(flow2.steps)) {
1141
+ const def = getDef(step);
1142
+ if (def.kind !== "match") continue;
1143
+ const state = runState.steps[matchId];
1144
+ if (state?.status !== "running") continue;
1145
+ const agg = aggregateMatch(matchId, flow2, runState);
1146
+ if (agg.kind === "pending") continue;
1147
+ const attempt = state.attempts > 0 ? state.attempts : 1;
1148
+ if (agg.kind === "fail-fast") {
1149
+ const failedNested = runState.steps[agg.failedStepId];
1150
+ const error = failedNested?.error ?? {
1151
+ name: "Error",
1152
+ message: `match "${matchId}": chosen-arm step "${agg.failedStepId}" failed`
1153
+ };
1154
+ out.push({
1155
+ matchId,
1156
+ attempt,
1157
+ result: { kind: "fail", error }
1158
+ });
1159
+ } else {
1160
+ out.push({
1161
+ matchId,
1162
+ attempt,
1163
+ result: { kind: "complete", output: agg.output }
1164
+ });
1165
+ }
1166
+ }
1167
+ return out;
1168
+ }
1169
+ function flowFailureError(runState) {
1170
+ const failedStep = Object.values(runState.steps).find(
1171
+ (s) => s.status === "failed"
1172
+ );
1173
+ return failedStep?.error ?? { name: "Error", message: "step failed" };
1174
+ }
1175
+ function isFlowTerminal(facts) {
1176
+ for (let i = facts.length - 1; i >= 0; i--) {
1177
+ const f = facts[i];
1178
+ if (f !== void 0 && (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled")) {
1179
+ return true;
1180
+ }
1181
+ }
1182
+ return false;
1183
+ }
1184
+ function computeFlowOutput(flow2, runState) {
1185
+ if (flow2.output === void 0) return null;
1186
+ const stepOutputs = {};
1187
+ for (const [sid, sstate] of Object.entries(runState.steps)) {
1188
+ if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
1189
+ }
1190
+ return flow2.output(stepOutputs);
1191
+ }
1192
+ function descendantsOf(flow2, stepId) {
1193
+ const children = /* @__PURE__ */ new Map();
1194
+ const addEdge = (from, to) => {
1195
+ const bucket = children.get(from);
1196
+ if (bucket) bucket.push(to);
1197
+ else children.set(from, [to]);
1198
+ };
1199
+ for (const [id, step] of Object.entries(flow2.steps)) {
1200
+ const def = getDef(step);
1201
+ for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
1202
+ if (def.kind === "match") {
1203
+ for (const arm of def.arms) {
1204
+ for (const armStepId of arm.stepIds) addEdge(id, armStepId);
1205
+ }
1206
+ }
1207
+ }
1208
+ const out = [stepId];
1209
+ const seen = /* @__PURE__ */ new Set([stepId]);
1210
+ for (let i = 0; i < out.length; i++) {
1211
+ const current = out[i];
1212
+ if (current === void 0) continue;
1213
+ for (const child of children.get(current) ?? []) {
1214
+ if (seen.has(child)) continue;
1215
+ if (!(child in flow2.steps)) continue;
1216
+ seen.add(child);
1217
+ out.push(child);
1218
+ }
1219
+ }
1220
+ return out;
1221
+ }
923
1222
  function extractInput(runState) {
924
1223
  for (const fact of runState.facts) {
925
1224
  if (fact.kind === "flow.started") return fact.input;
@@ -930,6 +1229,19 @@ function extractInput(runState) {
930
1229
  }
931
1230
 
932
1231
  // src/dispatch.ts
1232
+ async function fireHook(hook, event, hookName, deps) {
1233
+ if (deps.fireHooks === false) return;
1234
+ if (hook === void 0) return;
1235
+ try {
1236
+ await hook(event);
1237
+ } catch (err) {
1238
+ const { message, stack } = serializeError(err);
1239
+ deps.logger?.error(`nagi hook "${hookName}" threw \u2014 swallowed`, {
1240
+ error: message,
1241
+ ...stack !== void 0 ? { stack } : {}
1242
+ });
1243
+ }
1244
+ }
933
1245
  var DEFAULT_RETRY2 = {
934
1246
  maxAttempts: 3,
935
1247
  backoff: "exponential",
@@ -950,6 +1262,10 @@ async function dispatchMessage(deps, message) {
950
1262
  }
951
1263
  const def = getDef(step);
952
1264
  const preState = await store.loadRunState(runId);
1265
+ if (preState.status === "canceled") {
1266
+ await queue.ack(message.receipt);
1267
+ return;
1268
+ }
953
1269
  const preStep = preState.steps[stepId];
954
1270
  if (preStep && (preStep.status === "completed" || preStep.status === "failed" || preStep.status === "skipped")) {
955
1271
  await queue.ack(message.receipt);
@@ -967,8 +1283,8 @@ async function dispatchMessage(deps, message) {
967
1283
  attempt,
968
1284
  at: clock.now()
969
1285
  });
970
- const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
971
- await deps.hooks?.onStepStart?.({
1286
+ const startEventInput = def.kind === "task" || def.kind === "subflow" ? extractInput(await store.loadRunState(runId)) : null;
1287
+ const startEvent = {
972
1288
  runId,
973
1289
  flowId: flow2.id,
974
1290
  stepId,
@@ -976,11 +1292,14 @@ async function dispatchMessage(deps, message) {
976
1292
  kind: def.kind,
977
1293
  input: startEventInput,
978
1294
  at: clock.now()
979
- });
1295
+ };
1296
+ const stepOnStart = def.kind === "task" ? def.onStart : void 0;
1297
+ await fireHook(stepOnStart, startEvent, "step.onStart", deps);
1298
+ await fireHook(deps.hooks?.onStepStart, startEvent, "onStepStart", deps);
980
1299
  const startedAt = Date.now();
981
1300
  try {
982
1301
  if (def.kind === "task") {
983
- const output = await executeTask({
1302
+ const { output, skipAdvance } = await executeTask({
984
1303
  deps,
985
1304
  message,
986
1305
  def,
@@ -988,7 +1307,8 @@ async function dispatchMessage(deps, message) {
988
1307
  stepId,
989
1308
  attempt
990
1309
  });
991
- await deps.hooks?.onStepComplete?.({
1310
+ if (skipAdvance) return;
1311
+ const completeEvent = {
992
1312
  runId,
993
1313
  flowId: flow2.id,
994
1314
  stepId,
@@ -997,7 +1317,14 @@ async function dispatchMessage(deps, message) {
997
1317
  output,
998
1318
  durationMs: Date.now() - startedAt,
999
1319
  at: clock.now()
1000
- });
1320
+ };
1321
+ await fireHook(def.onComplete, completeEvent, "step.onComplete", deps);
1322
+ await fireHook(
1323
+ deps.hooks?.onStepComplete,
1324
+ completeEvent,
1325
+ "onStepComplete",
1326
+ deps
1327
+ );
1001
1328
  await advance(deps, runId);
1002
1329
  } else if (def.kind === "signal") {
1003
1330
  await queue.ack(message.receipt);
@@ -1005,6 +1332,10 @@ async function dispatchMessage(deps, message) {
1005
1332
  } else if (def.kind === "match") {
1006
1333
  await executeMatch({ deps, message, def, runId, stepId, attempt });
1007
1334
  await advance(deps, runId);
1335
+ } else if (def.kind === "subflow") {
1336
+ await executeSubflow({ deps, message, def, runId, stepId });
1337
+ await queue.ack(message.receipt);
1338
+ return;
1008
1339
  }
1009
1340
  } catch (err) {
1010
1341
  await handleStepError({
@@ -1028,69 +1359,194 @@ async function executeTask(args) {
1028
1359
  const runState = await store.loadRunState(runId);
1029
1360
  const input = extractInput(runState);
1030
1361
  const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
1031
- const output = await store.runStep(
1362
+ const ac = new AbortController();
1363
+ const watcher = startCancelWatcher({
1364
+ store,
1032
1365
  runId,
1033
1366
  stepId,
1034
1367
  attempt,
1035
- async (tx) => {
1036
- const ctx = makeStepCtx({
1037
- runId,
1038
- stepId,
1039
- attempt,
1040
- input,
1041
- store,
1042
- clock,
1043
- tx,
1044
- ...deps.logger !== void 0 ? { logger: deps.logger } : {}
1045
- });
1046
- const out = await def.run({ input, needs, ctx });
1047
- const fact = {
1048
- kind: "step.completed",
1049
- runId,
1050
- stepId,
1051
- attempt,
1052
- output: out,
1053
- at: clock.now()
1054
- };
1055
- return { output: out, fact };
1056
- }
1057
- );
1058
- await queue.ack(message.receipt);
1059
- return output;
1060
- }
1061
- async function executeMatch(args) {
1062
- const { deps, message, def, runId, stepId } = args;
1063
- const { store, queue, clock } = deps;
1064
- const runState = await store.loadRunState(runId);
1065
- const input = extractInput(runState);
1066
- const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
1067
- const armId = selectArm(def, { input, needs });
1068
- await store.appendFact(runId, {
1069
- kind: "match.arm-selected",
1070
- runId,
1071
- stepId,
1072
- arm: armId,
1073
- at: clock.now()
1368
+ ac,
1369
+ intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
1074
1370
  });
1075
- await queue.ack(message.receipt);
1076
- }
1077
- async function handleStepError(args) {
1078
- const { deps, flow: flow2, message, def, runId, stepId, attempt, err } = args;
1079
- const { store, queue, clock } = deps;
1080
- const error = serializeError(err);
1081
- const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY2;
1082
- const shouldRetry = attempt < policy.maxAttempts && retryAllows(policy, err);
1083
- if (shouldRetry) {
1084
- const delayMs = computeBackoff(policy, attempt);
1085
- await store.appendFact(runId, {
1086
- kind: "step.retried",
1371
+ try {
1372
+ let stepAbortedHere = false;
1373
+ const output = await store.runStep(
1374
+ runId,
1375
+ stepId,
1376
+ attempt,
1377
+ async (tx) => {
1378
+ const ctx = makeStepCtx({
1379
+ runId,
1380
+ stepId,
1381
+ attempt,
1382
+ input,
1383
+ store,
1384
+ clock,
1385
+ tx,
1386
+ signal: ac.signal,
1387
+ ...deps.logger !== void 0 ? { logger: deps.logger } : {}
1388
+ });
1389
+ const out = await def.run({ input, needs, ctx });
1390
+ const postState = await store.loadRunState(runId);
1391
+ if (postState.status === "canceled") {
1392
+ const canceledFact = {
1393
+ kind: "step.canceled",
1394
+ runId,
1395
+ stepId,
1396
+ attempt,
1397
+ at: clock.now()
1398
+ };
1399
+ return { output: out, fact: canceledFact };
1400
+ }
1401
+ if (hasAbortRequest(postState.facts, stepId, attempt)) {
1402
+ stepAbortedHere = true;
1403
+ const canceledFact = {
1404
+ kind: "step.canceled",
1405
+ runId,
1406
+ stepId,
1407
+ attempt,
1408
+ at: clock.now()
1409
+ };
1410
+ return { output: out, fact: canceledFact };
1411
+ }
1412
+ const fact = {
1413
+ kind: "step.completed",
1414
+ runId,
1415
+ stepId,
1416
+ attempt,
1417
+ output: out,
1418
+ at: clock.now()
1419
+ };
1420
+ return { output: out, fact };
1421
+ }
1422
+ );
1423
+ await queue.ack(message.receipt);
1424
+ return { output, skipAdvance: stepAbortedHere };
1425
+ } finally {
1426
+ watcher.stop();
1427
+ }
1428
+ }
1429
+ var CANCEL_POLL_INTERVAL_MS = 250;
1430
+ function startCancelWatcher(args) {
1431
+ const { store, runId, stepId, attempt, ac, intervalMs } = args;
1432
+ let stopped = false;
1433
+ void (async () => {
1434
+ while (!stopped) {
1435
+ await new Promise((r) => setTimeout(r, intervalMs));
1436
+ if (stopped) return;
1437
+ try {
1438
+ const s = await store.loadRunState(runId);
1439
+ if (s.status === "canceled" || s.status === "failed" || s.status === "completed") {
1440
+ if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
1441
+ return;
1442
+ }
1443
+ if (hasAbortRequest(s.facts, stepId, attempt)) {
1444
+ if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
1445
+ return;
1446
+ }
1447
+ } catch {
1448
+ }
1449
+ }
1450
+ })();
1451
+ return {
1452
+ stop: () => {
1453
+ stopped = true;
1454
+ }
1455
+ };
1456
+ }
1457
+ function hasAbortRequest(facts, stepId, attempt) {
1458
+ for (let i = facts.length - 1; i >= 0; i--) {
1459
+ const f = facts[i];
1460
+ if (f === void 0) continue;
1461
+ if (f.kind === "step.reset" && f.stepId === stepId) return false;
1462
+ if (f.kind === "step.abort-requested" && f.stepId === stepId && f.attempt === attempt) {
1463
+ return true;
1464
+ }
1465
+ }
1466
+ return false;
1467
+ }
1468
+ var NagiAbortError = class extends Error {
1469
+ runId;
1470
+ scope;
1471
+ constructor(runId, scope) {
1472
+ super(
1473
+ scope === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
1474
+ );
1475
+ this.name = "NagiAbortError";
1476
+ this.runId = runId;
1477
+ this.scope = scope;
1478
+ }
1479
+ };
1480
+ async function executeSubflow(args) {
1481
+ const { deps, message, def, runId, stepId } = args;
1482
+ const { store } = deps;
1483
+ const child = deps.lookupFlow(def.childFlowId);
1484
+ if (child === void 0) {
1485
+ throw new Error(
1486
+ `Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
1487
+ );
1488
+ }
1489
+ const runState = await store.loadRunState(runId);
1490
+ const parentInput = extractInput(runState);
1491
+ const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
1492
+ const childInput = def.buildInput({ input: parentInput, needs });
1493
+ await deps.startChildRun({
1494
+ child,
1495
+ childInput,
1496
+ parent: { runId, stepId, attempt: message.attempt }
1497
+ });
1498
+ }
1499
+ async function executeMatch(args) {
1500
+ const { deps, message, def, runId, stepId } = args;
1501
+ const { store, queue, clock } = deps;
1502
+ const runState = await store.loadRunState(runId);
1503
+ const input = extractInput(runState);
1504
+ const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
1505
+ const armId = selectArm(def, { input, needs });
1506
+ await store.appendFact(runId, {
1507
+ kind: "match.arm-selected",
1508
+ runId,
1509
+ stepId,
1510
+ arm: armId,
1511
+ at: clock.now()
1512
+ });
1513
+ await queue.ack(message.receipt);
1514
+ }
1515
+ async function handleStepError(args) {
1516
+ const { deps, flow: flow2, message, def, runId, stepId, attempt, err } = args;
1517
+ const { store, queue, clock } = deps;
1518
+ const error = serializeError(err);
1519
+ const postState = await store.loadRunState(runId);
1520
+ const runIsCanceled = postState.status === "canceled";
1521
+ const stepAborted = hasAbortRequest(postState.facts, stepId, attempt);
1522
+ if (runIsCanceled || stepAborted) {
1523
+ const isAbort = err instanceof NagiAbortError || err instanceof Error && err.name === "AbortError";
1524
+ const canceledFact = {
1525
+ kind: "step.canceled",
1526
+ runId,
1527
+ stepId,
1528
+ attempt,
1529
+ ...isAbort ? { error } : {},
1530
+ at: clock.now()
1531
+ };
1532
+ await store.appendFact(runId, canceledFact);
1533
+ await queue.ack(message.receipt);
1534
+ if (!stepAborted) await advance(deps, runId);
1535
+ return;
1536
+ }
1537
+ const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY2;
1538
+ const shouldRetry = attempt < policy.maxAttempts && retryAllows(policy, err);
1539
+ if (shouldRetry) {
1540
+ const delayMs = computeBackoff(policy, attempt);
1541
+ await store.appendFact(runId, {
1542
+ kind: "step.retried",
1087
1543
  runId,
1088
1544
  stepId,
1089
1545
  attempt,
1090
1546
  nextAttemptAt: new Date(Date.now() + delayMs),
1091
1547
  at: clock.now()
1092
1548
  });
1093
- await deps.hooks?.onStepRetry?.({
1549
+ const retryEvent = {
1094
1550
  runId,
1095
1551
  flowId: flow2.id,
1096
1552
  stepId,
@@ -1099,7 +1555,10 @@ async function handleStepError(args) {
1099
1555
  error,
1100
1556
  nextAttemptAt: new Date(Date.now() + delayMs),
1101
1557
  at: clock.now()
1102
- });
1558
+ };
1559
+ const stepOnRetry = def.kind === "task" ? def.onRetry : void 0;
1560
+ await fireHook(stepOnRetry, retryEvent, "step.onRetry", deps);
1561
+ await fireHook(deps.hooks?.onStepRetry, retryEvent, "onStepRetry", deps);
1103
1562
  await queue.enqueue(runId, stepId, { attempt: attempt + 1, delayMs });
1104
1563
  await queue.ack(message.receipt);
1105
1564
  return;
@@ -1113,7 +1572,7 @@ async function handleStepError(args) {
1113
1572
  at: clock.now()
1114
1573
  };
1115
1574
  await store.failStep(runId, stepId, error, fact);
1116
- await deps.hooks?.onStepError?.({
1575
+ const errorEvent = {
1117
1576
  runId,
1118
1577
  flowId: flow2.id,
1119
1578
  stepId,
@@ -1121,187 +1580,137 @@ async function handleStepError(args) {
1121
1580
  kind: def.kind,
1122
1581
  error,
1123
1582
  at: clock.now()
1124
- });
1583
+ };
1584
+ const stepOnError = def.kind === "task" ? def.onError : void 0;
1585
+ await fireHook(stepOnError, errorEvent, "step.onError", deps);
1586
+ await fireHook(deps.hooks?.onStepError, errorEvent, "onStepError", deps);
1125
1587
  await queue.ack(message.receipt);
1126
1588
  await advance(deps, runId);
1127
1589
  }
1128
1590
  var MAX_ADVANCE_ITERS = 1024;
1129
1591
  async function advance(deps, runId) {
1130
- const { store, queue, clock } = deps;
1592
+ const { store, queue } = deps;
1131
1593
  const flow2 = await deps.flowFor(runId);
1132
1594
  for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
1133
1595
  const runState = await store.loadRunState(runId);
1134
- const promoted = await promoteMatches({ deps, flow: flow2, runState });
1135
- if (promoted) continue;
1136
- const termination = flowTermination(flow2, runState);
1137
- if (termination.done) {
1138
- const last2 = runState.facts[runState.facts.length - 1];
1139
- const flowAlreadyTerminal = last2 !== void 0 && (last2.kind === "flow.completed" || last2.kind === "flow.failed");
1140
- if (!flowAlreadyTerminal) {
1141
- if (termination.failed) {
1142
- const failedStep = Object.values(runState.steps).find(
1143
- (s) => s.status === "failed"
1144
- );
1145
- await store.appendFact(runId, {
1146
- kind: "flow.failed",
1147
- runId,
1148
- error: failedStep?.error ?? {
1149
- name: "Error",
1150
- message: "step failed"
1151
- },
1152
- at: clock.now()
1153
- });
1154
- await deps.hooks?.onFlowError?.({
1155
- runId,
1156
- flowId: flow2.id,
1157
- error: failedStep?.error ?? {
1158
- name: "Error",
1159
- message: "step failed"
1160
- },
1161
- at: clock.now()
1162
- });
1163
- } else {
1164
- let flowOutput = null;
1165
- if (flow2.output !== void 0) {
1166
- const stepOutputs = {};
1167
- for (const [sid, sstate] of Object.entries(runState.steps)) {
1168
- if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
1169
- }
1170
- flowOutput = flow2.output(stepOutputs);
1171
- }
1172
- await store.appendFact(runId, {
1173
- kind: "flow.completed",
1174
- runId,
1175
- output: flowOutput,
1176
- at: clock.now()
1177
- });
1178
- await deps.hooks?.onFlowComplete?.({
1179
- runId,
1180
- flowId: flow2.id,
1181
- output: flowOutput,
1182
- at: clock.now()
1183
- });
1184
- }
1185
- }
1186
- return;
1187
- }
1188
- const input = extractInput(runState);
1189
- const decision = nextRunnable({ flow: flow2, runState, input });
1190
- if (decision.skip.length === 0 && decision.runnable.length === 0) return;
1191
- for (const { stepId, reason } of decision.skip) {
1192
- await store.appendFact(runId, {
1193
- kind: "step.skipped",
1194
- runId,
1195
- stepId,
1196
- reason,
1197
- at: clock.now()
1198
- });
1199
- }
1200
- for (const stepId of decision.runnable) {
1201
- await queue.enqueue(runId, stepId);
1202
- }
1203
- if (decision.runnable.length > 0) {
1204
- return;
1596
+ const t = nextTransition(flow2, runState);
1597
+ switch (t.kind) {
1598
+ case "settled":
1599
+ case "waiting":
1600
+ return;
1601
+ case "complete":
1602
+ await finalizeFlowCompletion({ deps, flow: flow2, runId, output: t.output });
1603
+ return;
1604
+ case "fail":
1605
+ await finalizeFlowFailure({ deps, flow: flow2, runId, error: t.error });
1606
+ return;
1607
+ case "dispatch":
1608
+ await recordSkips(deps, runId, t.skip);
1609
+ for (const stepId of t.runnable) await queue.enqueue(runId, stepId);
1610
+ return;
1611
+ case "skip":
1612
+ await recordSkips(deps, runId, t.skip);
1613
+ continue;
1614
+ case "promote-match":
1615
+ await applyPromotions(deps, flow2, runState, t.promotions);
1616
+ continue;
1205
1617
  }
1206
1618
  }
1207
1619
  const cycleError = {
1208
1620
  name: "NagiCycleError",
1209
1621
  message: `advance exceeded ${MAX_ADVANCE_ITERS} iterations \u2014 likely a cycle or infinite skip loop in flow "${flow2.id}"`
1210
1622
  };
1211
- const last = (await store.loadRunState(runId)).facts.slice(-1)[0];
1212
- const alreadyTerminal = last !== void 0 && (last.kind === "flow.completed" || last.kind === "flow.failed");
1213
- if (!alreadyTerminal) {
1623
+ const facts = (await store.loadRunState(runId)).facts;
1624
+ if (!isFlowTerminal(facts)) {
1625
+ await finalizeFlowFailure({ deps, flow: flow2, runId, error: cycleError });
1626
+ }
1627
+ }
1628
+ async function recordSkips(deps, runId, skip) {
1629
+ const { store, clock } = deps;
1630
+ for (const { stepId, reason } of skip) {
1214
1631
  await store.appendFact(runId, {
1215
- kind: "flow.failed",
1632
+ kind: "step.skipped",
1216
1633
  runId,
1217
- error: cycleError,
1634
+ stepId,
1635
+ reason,
1218
1636
  at: clock.now()
1219
1637
  });
1220
- await deps.hooks?.onFlowError?.({
1638
+ }
1639
+ }
1640
+ async function markStepComplete(args) {
1641
+ const { deps, flow: flow2, runId, stepId, attempt, kind, output } = args;
1642
+ const at = deps.clock.now();
1643
+ const fact = {
1644
+ kind: "step.completed",
1645
+ runId,
1646
+ stepId,
1647
+ attempt,
1648
+ output,
1649
+ at
1650
+ };
1651
+ await deps.store.completeStep(runId, stepId, output, fact);
1652
+ await fireHook(
1653
+ deps.hooks?.onStepComplete,
1654
+ {
1221
1655
  runId,
1222
1656
  flowId: flow2.id,
1223
- error: cycleError,
1224
- at: clock.now()
1225
- });
1226
- }
1657
+ stepId,
1658
+ attempt,
1659
+ kind,
1660
+ output,
1661
+ durationMs: 0,
1662
+ at
1663
+ },
1664
+ "onStepComplete",
1665
+ deps
1666
+ );
1227
1667
  }
1228
- async function promoteMatches(args) {
1229
- const { deps, flow: flow2, runState } = args;
1230
- const { store, clock } = deps;
1231
- let promoted = false;
1232
- for (const [matchId, step] of Object.entries(flow2.steps)) {
1233
- const def = getDef(step);
1234
- if (def.kind !== "match") continue;
1235
- const state = runState.steps[matchId];
1236
- if (state?.status !== "running") continue;
1237
- const agg = aggregateMatch(matchId, flow2, runState);
1238
- if (agg.kind === "pending") continue;
1239
- const attempt = state.attempts > 0 ? state.attempts : 1;
1240
- if (agg.kind === "fail-fast") {
1241
- const failedNested = runState.steps[agg.failedStepId];
1242
- const error = failedNested?.error ?? {
1243
- name: "Error",
1244
- message: `match "${matchId}": chosen-arm step "${agg.failedStepId}" failed`
1245
- };
1246
- const fact2 = {
1247
- kind: "step.failed",
1668
+ async function markStepFail(args) {
1669
+ const { deps, flow: flow2, runId, stepId, attempt, kind, error } = args;
1670
+ const at = deps.clock.now();
1671
+ const fact = { kind: "step.failed", runId, stepId, attempt, error, at };
1672
+ await deps.store.failStep(runId, stepId, error, fact);
1673
+ await fireHook(
1674
+ deps.hooks?.onStepError,
1675
+ { runId, flowId: flow2.id, stepId, attempt, kind, error, at },
1676
+ "onStepError",
1677
+ deps
1678
+ );
1679
+ }
1680
+ async function applyPromotions(deps, flow2, runState, promotions) {
1681
+ for (const { matchId, attempt, result } of promotions) {
1682
+ if (result.kind === "fail") {
1683
+ await markStepFail({
1684
+ deps,
1685
+ flow: flow2,
1248
1686
  runId: runState.runId,
1249
1687
  stepId: matchId,
1250
1688
  attempt,
1251
- error,
1252
- at: clock.now()
1253
- };
1254
- await store.failStep(runState.runId, matchId, error, fact2);
1255
- await deps.hooks?.onStepError?.({
1689
+ kind: "match",
1690
+ error: result.error
1691
+ });
1692
+ } else {
1693
+ await markStepComplete({
1694
+ deps,
1695
+ flow: flow2,
1256
1696
  runId: runState.runId,
1257
- flowId: flow2.id,
1258
1697
  stepId: matchId,
1259
1698
  attempt,
1260
1699
  kind: "match",
1261
- error,
1262
- at: clock.now()
1700
+ output: result.output
1263
1701
  });
1264
- promoted = true;
1265
- continue;
1266
1702
  }
1267
- const fact = {
1268
- kind: "step.completed",
1269
- runId: runState.runId,
1270
- stepId: matchId,
1271
- attempt,
1272
- output: agg.output,
1273
- at: clock.now()
1274
- };
1275
- await store.completeStep(runState.runId, matchId, agg.output, fact);
1276
- await deps.hooks?.onStepComplete?.({
1277
- runId: runState.runId,
1278
- flowId: flow2.id,
1279
- stepId: matchId,
1280
- attempt,
1281
- kind: "match",
1282
- output: agg.output,
1283
- durationMs: 0,
1284
- at: clock.now()
1285
- });
1286
- promoted = true;
1287
1703
  }
1288
- return promoted;
1289
1704
  }
1290
1705
  function makeStepCtx(args) {
1291
- const { runId, stepId, attempt, input, store, clock, tx } = args;
1292
- const ac = new AbortController();
1706
+ const { runId, stepId, attempt, input, store, clock, tx, signal } = args;
1293
1707
  return {
1294
1708
  input,
1295
1709
  runId,
1296
1710
  stepId,
1297
1711
  attempt,
1298
- signal: ac.signal,
1712
+ signal,
1299
1713
  now: () => clock.now(),
1300
- // `tx` is supplied by `Store.runStep` — for adapters with no real
1301
- // transaction (in-memory) it is `undefined as Tx`, and handlers that
1302
- // touch `ctx.tx` will throw on the first call. Adapters that need
1303
- // typed transactional clients (e.g. `@nagi-js/postgres`) augment
1304
- // `Register.tx` and pass a real Kysely transaction here.
1305
1714
  tx,
1306
1715
  logger: args.logger ?? consoleLogger(),
1307
1716
  once: makeOnce({ runId, stepId, store }),
@@ -1332,6 +1741,94 @@ function retryAllows(policy, err) {
1332
1741
  if (!policy.retryOn) return true;
1333
1742
  return policy.retryOn(err);
1334
1743
  }
1744
+ async function finalizeFlowFailure(args) {
1745
+ const { deps, flow: flow2, runId, error } = args;
1746
+ const { store, clock } = deps;
1747
+ await store.appendFact(runId, {
1748
+ kind: "flow.failed",
1749
+ runId,
1750
+ error,
1751
+ at: clock.now()
1752
+ });
1753
+ const event = { runId, flowId: flow2.id, error, at: clock.now() };
1754
+ await fireHook(flow2.onError, event, "flow.onError", deps);
1755
+ await fireHook(deps.hooks?.onFlowError, event, "onFlowError", deps);
1756
+ await propagateToParent(deps, runId, { kind: "failed", error });
1757
+ }
1758
+ async function finalizeFlowCompletion(args) {
1759
+ const { deps, flow: flow2, runId, output } = args;
1760
+ const { store, clock } = deps;
1761
+ await store.appendFact(runId, {
1762
+ kind: "flow.completed",
1763
+ runId,
1764
+ output,
1765
+ at: clock.now()
1766
+ });
1767
+ const event = { runId, flowId: flow2.id, output, at: clock.now() };
1768
+ await fireHook(flow2.onComplete, event, "flow.onComplete", deps);
1769
+ await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete", deps);
1770
+ await propagateToParent(deps, runId, { kind: "completed", output });
1771
+ }
1772
+ async function propagateToParent(deps, childRunId, outcome) {
1773
+ const { store } = deps;
1774
+ const childState = await store.loadRunState(childRunId);
1775
+ const startedFact = childState.facts.find((f) => f.kind === "flow.started");
1776
+ if (startedFact?.parent === void 0) {
1777
+ return;
1778
+ }
1779
+ const { runId: parentRunId, stepId: parentStepId } = startedFact.parent;
1780
+ const parentState = await store.loadRunState(parentRunId);
1781
+ if (parentState.status === "completed" || parentState.status === "failed" || parentState.status === "canceled") {
1782
+ deps.logger?.info(
1783
+ "nagi: subflow wake skipped \u2014 parent run already terminal",
1784
+ {
1785
+ parentRunId,
1786
+ parentStepId,
1787
+ childRunId,
1788
+ parentStatus: parentState.status
1789
+ }
1790
+ );
1791
+ return;
1792
+ }
1793
+ const parentStep = parentState.steps[parentStepId];
1794
+ if (parentStep?.status !== "running") {
1795
+ deps.logger?.info("nagi: subflow wake skipped \u2014 parent step not running", {
1796
+ parentRunId,
1797
+ parentStepId,
1798
+ childRunId,
1799
+ parentStepStatus: parentStep?.status ?? "missing"
1800
+ });
1801
+ return;
1802
+ }
1803
+ const attempt = parentStep.attempts > 0 ? parentStep.attempts : 1;
1804
+ const parentFlow = await deps.flowFor(parentRunId);
1805
+ if (outcome.kind === "completed") {
1806
+ const subflowOutput = {
1807
+ childRunId,
1808
+ output: outcome.output
1809
+ };
1810
+ await markStepComplete({
1811
+ deps,
1812
+ flow: parentFlow,
1813
+ runId: parentRunId,
1814
+ stepId: parentStepId,
1815
+ attempt,
1816
+ kind: "subflow",
1817
+ output: subflowOutput
1818
+ });
1819
+ } else {
1820
+ await markStepFail({
1821
+ deps,
1822
+ flow: parentFlow,
1823
+ runId: parentRunId,
1824
+ stepId: parentStepId,
1825
+ attempt,
1826
+ kind: "subflow",
1827
+ error: outcome.error
1828
+ });
1829
+ }
1830
+ await advance(deps, parentRunId);
1831
+ }
1335
1832
  function serializeError(err) {
1336
1833
  if (err instanceof Error) {
1337
1834
  return {
@@ -1456,6 +1953,24 @@ var NagiRuntimeError = class extends Error {
1456
1953
  this.name = "NagiRuntimeError";
1457
1954
  }
1458
1955
  };
1956
+ var NagiCanceledError = class extends Error {
1957
+ runId;
1958
+ canceledByRunId;
1959
+ concurrencyKey;
1960
+ constructor(args) {
1961
+ super(
1962
+ `Run ${args.runId} was canceled (superseded by run ${args.canceledByRunId} for concurrency key "${args.concurrencyKey}").`
1963
+ );
1964
+ this.name = "NagiCanceledError";
1965
+ this.runId = args.runId;
1966
+ this.canceledByRunId = args.canceledByRunId;
1967
+ this.concurrencyKey = args.concurrencyKey;
1968
+ this.cause = {
1969
+ canceledByRunId: args.canceledByRunId,
1970
+ concurrencyKey: args.concurrencyKey
1971
+ };
1972
+ }
1973
+ };
1459
1974
  var NagiSnapshotDriftError = class extends Error {
1460
1975
  runId;
1461
1976
  expected;
@@ -1470,8 +1985,9 @@ var NagiSnapshotDriftError = class extends Error {
1470
1985
  this.actual = args.actual;
1471
1986
  }
1472
1987
  };
1473
- async function nagi(config) {
1988
+ async function nagiImpl(config) {
1474
1989
  const clock = config.clock ?? new InMemoryClock();
1990
+ await config.queue.ensureSchema?.();
1475
1991
  const flowsById = /* @__PURE__ */ new Map();
1476
1992
  const flowHashById = /* @__PURE__ */ new Map();
1477
1993
  for (const f of config.flows) {
@@ -1501,6 +2017,7 @@ async function nagi(config) {
1501
2017
  });
1502
2018
  }
1503
2019
  }
2020
+ const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
1504
2021
  async function flowFor(runId) {
1505
2022
  const runState = await config.store.loadRunState(runId);
1506
2023
  const flow2 = flowsById.get(runState.flowId);
@@ -1511,8 +2028,180 @@ async function nagi(config) {
1511
2028
  }
1512
2029
  return flow2;
1513
2030
  }
2031
+ function lookupFlow(flowId) {
2032
+ return flowsById.get(flowId);
2033
+ }
2034
+ async function startRunInternal(args) {
2035
+ const { flow: flow2, validatedInput, runId, parent } = args;
2036
+ const startedAt = clock.now();
2037
+ const flowHash = flowHashById.get(flow2.id);
2038
+ const fact = {
2039
+ kind: "flow.started",
2040
+ runId,
2041
+ flowId: flow2.id,
2042
+ input: validatedInput,
2043
+ at: startedAt,
2044
+ ...flowHash !== void 0 ? { flowHash } : {},
2045
+ codeVersion,
2046
+ ...parent !== void 0 ? { parent: { runId: parent.runId, stepId: parent.stepId } } : {}
2047
+ };
2048
+ let concurrencyArg;
2049
+ if (flow2.concurrency !== void 0) {
2050
+ const derived = flow2.concurrency.keyFn(validatedInput);
2051
+ if (typeof derived !== "string" || derived.length === 0) {
2052
+ throw new NagiValidationError([
2053
+ {
2054
+ message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
2055
+ path: ["concurrency", "keyFn"]
2056
+ }
2057
+ ]);
2058
+ }
2059
+ concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
2060
+ }
2061
+ const { started, canceled } = await config.store.tryStartRun(
2062
+ runId,
2063
+ fact,
2064
+ concurrencyArg
2065
+ );
2066
+ if (!started) return { started: false };
2067
+ for (const c of canceled) {
2068
+ const cancelError = new NagiCanceledError({
2069
+ runId: c.runId,
2070
+ canceledByRunId: runId,
2071
+ concurrencyKey: c.fact.concurrencyKey
2072
+ });
2073
+ const serialized = {
2074
+ ...serializeError(cancelError),
2075
+ cause: {
2076
+ canceledByRunId: runId,
2077
+ concurrencyKey: c.fact.concurrencyKey
2078
+ }
2079
+ };
2080
+ const errorEvent = {
2081
+ runId: c.runId,
2082
+ flowId: flow2.id,
2083
+ error: serialized,
2084
+ at: c.fact.at
2085
+ };
2086
+ await fireHook(
2087
+ flow2.onError,
2088
+ errorEvent,
2089
+ "flow.onError",
2090
+ dispatchDeps
2091
+ );
2092
+ await fireHook(
2093
+ config.hooks?.onFlowError,
2094
+ errorEvent,
2095
+ "onFlowError",
2096
+ dispatchDeps
2097
+ );
2098
+ await propagateToParent(dispatchDeps, c.runId, {
2099
+ kind: "canceled",
2100
+ error: serialized
2101
+ });
2102
+ }
2103
+ const startEvent = parent !== void 0 ? {
2104
+ runId,
2105
+ flowId: flow2.id,
2106
+ input: validatedInput,
2107
+ at: startedAt,
2108
+ parent
2109
+ } : {
2110
+ runId,
2111
+ flowId: flow2.id,
2112
+ input: validatedInput,
2113
+ at: startedAt
2114
+ };
2115
+ await fireHook(
2116
+ flow2.onStart,
2117
+ startEvent,
2118
+ "flow.onStart",
2119
+ dispatchDeps
2120
+ );
2121
+ await fireHook(
2122
+ config.hooks?.onFlowStart,
2123
+ startEvent,
2124
+ "onFlowStart",
2125
+ dispatchDeps
2126
+ );
2127
+ await advance(dispatchDeps, runId);
2128
+ return { started: true };
2129
+ }
2130
+ async function startChildRun(args) {
2131
+ const { child, childInput, parent } = args;
2132
+ if (!flowsById.has(child.id)) {
2133
+ throw new NagiRuntimeError(
2134
+ `Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
2135
+ );
2136
+ }
2137
+ const validated = await validate(child.input, childInput);
2138
+ const childRunId = mintRunId();
2139
+ const { started } = await startRunInternal({
2140
+ flow: child,
2141
+ validatedInput: validated,
2142
+ runId: childRunId,
2143
+ parent
2144
+ });
2145
+ if (!started) {
2146
+ throw new NagiRuntimeError(
2147
+ `startChildRun: minted child runId collided with an existing run (${childRunId})`
2148
+ );
2149
+ }
2150
+ return childRunId;
2151
+ }
2152
+ async function cancelRunRecursive(runId, args) {
2153
+ const state = await config.store.loadRunState(runId);
2154
+ if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
2155
+ config.logger?.info("nagi: cancel skipped \u2014 run already terminal", {
2156
+ runId,
2157
+ status: state.status
2158
+ });
2159
+ return;
2160
+ }
2161
+ const flow2 = flowsById.get(state.flowId);
2162
+ const canceledFact = {
2163
+ ...args,
2164
+ kind: "flow.canceled",
2165
+ runId,
2166
+ at: clock.now()
2167
+ };
2168
+ await config.store.appendFact(runId, canceledFact);
2169
+ const cancelError = {
2170
+ name: "NagiCanceledError",
2171
+ message: `Run ${runId} was canceled: ${args.reason}`
2172
+ };
2173
+ if (flow2 !== void 0) {
2174
+ const event = {
2175
+ runId,
2176
+ flowId: flow2.id,
2177
+ error: cancelError,
2178
+ at: clock.now()
2179
+ };
2180
+ await fireHook(flow2.onError, event, "flow.onError", dispatchDeps);
2181
+ await fireHook(
2182
+ config.hooks?.onFlowError,
2183
+ event,
2184
+ "onFlowError",
2185
+ dispatchDeps
2186
+ );
2187
+ }
2188
+ const children = await config.store.listChildren(runId);
2189
+ for (const childId of children) {
2190
+ await cancelRunRecursive(childId, {
2191
+ cause: "explicit",
2192
+ reason: `parent ${runId} canceled: ${args.reason}`,
2193
+ note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
2194
+ });
2195
+ }
2196
+ await propagateToParent(dispatchDeps, runId, {
2197
+ kind: "canceled",
2198
+ error: cancelError
2199
+ });
2200
+ }
1514
2201
  const dispatchDeps = {
1515
2202
  flowFor,
2203
+ lookupFlow,
2204
+ startChildRun,
1516
2205
  store: config.store,
1517
2206
  queue: config.queue,
1518
2207
  clock,
@@ -1520,11 +2209,15 @@ async function nagi(config) {
1520
2209
  ...config.logger !== void 0 ? { logger: config.logger } : {},
1521
2210
  ...config.defaultRetry !== void 0 ? { defaultRetry: config.defaultRetry } : {}
1522
2211
  };
1523
- return {
2212
+ const wf = {
1524
2213
  async start(flow2, input, opts) {
1525
- if (!flowsById.has(flow2.id)) {
2214
+ return wf.startById(flow2.id, input, opts);
2215
+ },
2216
+ async startById(flowId, input, opts) {
2217
+ const flow2 = flowsById.get(flowId);
2218
+ if (!flow2) {
1526
2219
  throw new NagiRuntimeError(
1527
- `Flow "${flow2.id}" not registered with nagi(). Pass it to flows[].`
2220
+ `Flow "${flowId}" not registered with nagi(). Pass it to flows[].`
1528
2221
  );
1529
2222
  }
1530
2223
  let runId;
@@ -1542,31 +2235,10 @@ async function nagi(config) {
1542
2235
  runId = mintRunId();
1543
2236
  }
1544
2237
  const validated = await validate(flow2.input, input);
1545
- const startedAt = clock.now();
1546
- const flowHash = flowHashById.get(flow2.id);
1547
- const fact = {
1548
- kind: "flow.started",
1549
- runId,
1550
- flowId: flow2.id,
1551
- input: validated,
1552
- at: startedAt,
1553
- ...flowHash !== void 0 ? { flowHash } : {},
1554
- ...config.codeVersion !== void 0 ? { codeVersion: config.codeVersion } : {}
1555
- };
1556
- const { started } = await config.store.tryStartRun(runId, fact);
1557
- if (!started) {
1558
- return runId;
1559
- }
1560
- await config.hooks?.onFlowStart?.({
1561
- runId,
1562
- flowId: flow2.id,
1563
- input: validated,
1564
- at: startedAt
1565
- });
1566
- await advance(dispatchDeps, runId);
2238
+ await startRunInternal({ flow: flow2, validatedInput: validated, runId });
1567
2239
  return runId;
1568
2240
  },
1569
- async signal(runId, stepName, payload) {
2241
+ async signal(runId, signalName, payload) {
1570
2242
  const runState = await config.store.loadRunState(runId);
1571
2243
  const flow2 = flowsById.get(runState.flowId);
1572
2244
  if (!flow2) {
@@ -1574,58 +2246,96 @@ async function nagi(config) {
1574
2246
  `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
1575
2247
  );
1576
2248
  }
1577
- const step = flow2.steps[stepName];
1578
- if (!step) {
1579
- throw new NagiRuntimeError(
1580
- `Flow "${flow2.id}" has no step named "${stepName}".`
1581
- );
2249
+ let stepId;
2250
+ let def;
2251
+ const direct = flow2.steps[signalName];
2252
+ if (direct !== void 0) {
2253
+ const d = getDef(direct);
2254
+ if (d.kind === "signal" && d.names === void 0) {
2255
+ stepId = signalName;
2256
+ def = d;
2257
+ }
2258
+ }
2259
+ if (stepId === void 0) {
2260
+ for (const [id, s] of Object.entries(flow2.steps)) {
2261
+ const d = getDef(s);
2262
+ if (d.kind === "signal" && d.names?.includes(signalName)) {
2263
+ stepId = id;
2264
+ def = d;
2265
+ break;
2266
+ }
2267
+ }
1582
2268
  }
1583
- const def = getDef(step);
1584
- if (def.kind !== "signal") {
2269
+ if (stepId === void 0 || def === void 0) {
1585
2270
  throw new NagiRuntimeError(
1586
- `Step "${stepName}" is a ${def.kind}, not a signal.`
2271
+ `Flow "${flow2.id}" has no signal step accepting "${signalName}".`
1587
2272
  );
1588
2273
  }
1589
- const stepState = runState.steps[stepName];
2274
+ const stepState = runState.steps[stepId];
1590
2275
  if (stepState?.status !== "running") {
2276
+ if (stepState?.status === "completed") {
2277
+ config.logger?.info("nagi: signal arrived after step resolved", {
2278
+ runId,
2279
+ stepId,
2280
+ signalName
2281
+ });
2282
+ return;
2283
+ }
1591
2284
  throw new NagiRuntimeError(
1592
- `Step "${stepName}" is not waiting for signal (status: ${stepState?.status ?? "pending"}).`
2285
+ `Step "${stepId}" is not waiting for signal (status: ${stepState?.status ?? "pending"}).`
1593
2286
  );
1594
2287
  }
1595
2288
  const validated = await validate(def.schema, payload);
1596
2289
  const attempt = stepState.attempts > 0 ? stepState.attempts : 1;
2290
+ const carriesAlias = signalName !== stepId;
1597
2291
  await config.store.appendFact(runId, {
1598
2292
  kind: "signal.received",
1599
2293
  runId,
1600
- stepId: stepName,
2294
+ stepId,
1601
2295
  payload: validated,
1602
- at: clock.now()
2296
+ at: clock.now(),
2297
+ ...carriesAlias ? { signalName } : {}
1603
2298
  });
1604
2299
  const completedFact = {
1605
2300
  kind: "step.completed",
1606
2301
  runId,
1607
- stepId: stepName,
2302
+ stepId,
1608
2303
  attempt,
1609
2304
  output: validated,
1610
2305
  at: clock.now()
1611
2306
  };
1612
- await config.store.completeStep(
1613
- runId,
1614
- stepName,
1615
- validated,
1616
- completedFact
2307
+ await config.store.completeStep(runId, stepId, validated, completedFact);
2308
+ await fireHook(
2309
+ config.hooks?.onSignalReceived,
2310
+ {
2311
+ runId,
2312
+ flowId: flow2.id,
2313
+ stepId,
2314
+ attempt,
2315
+ kind: "signal",
2316
+ payload: validated,
2317
+ at: clock.now()
2318
+ },
2319
+ "onSignalReceived",
2320
+ dispatchDeps
1617
2321
  );
1618
- await config.hooks?.onSignalReceived?.({
1619
- runId,
1620
- flowId: flow2.id,
1621
- stepId: stepName,
1622
- attempt,
1623
- kind: "signal",
1624
- payload: validated,
1625
- at: clock.now()
1626
- });
1627
2322
  await advance(dispatchDeps, runId);
1628
2323
  },
2324
+ async cancel(runId, opts) {
2325
+ await cancelRunRecursive(runId, {
2326
+ cause: "explicit",
2327
+ reason: opts?.reason ?? "explicit wf.cancel()"
2328
+ });
2329
+ },
2330
+ operator() {
2331
+ return makeOperator({
2332
+ deps: dispatchDeps,
2333
+ clock,
2334
+ flowsById,
2335
+ cancelRunRecursive,
2336
+ ...config.logger !== void 0 ? { logger: config.logger } : {}
2337
+ });
2338
+ },
1629
2339
  worker(workerConfig) {
1630
2340
  if (config.flows.length === 0) {
1631
2341
  throw new NagiRuntimeError(
@@ -1642,7 +2352,16 @@ async function nagi(config) {
1642
2352
  `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
1643
2353
  );
1644
2354
  }
2355
+ if (runState.status === "canceled") {
2356
+ throw new NagiRuntimeError(
2357
+ `Run ${runId} was canceled (superseded by a newer run with the same concurrency key). Replay is not supported for canceled runs \u2014 start a new run instead.`
2358
+ );
2359
+ }
1645
2360
  if (opts.mode === "inspect") return;
2361
+ const fireHooks = opts.fireHooks !== false;
2362
+ const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
2363
+ let replayDeps = baseDeps;
2364
+ let effectiveFlow = liveFlow;
1646
2365
  const pinned = runState.flowHash;
1647
2366
  if (pinned !== void 0) {
1648
2367
  const liveHash = flowHashById.get(liveFlow.id);
@@ -1664,21 +2383,296 @@ async function nagi(config) {
1664
2383
  snapshot.dag,
1665
2384
  liveFlow
1666
2385
  );
1667
- const driftDeps = {
1668
- ...dispatchDeps,
1669
- flowFor: async () => synthesized
2386
+ replayDeps = { ...baseDeps, flowFor: async () => synthesized };
2387
+ effectiveFlow = synthesized;
2388
+ }
2389
+ }
2390
+ if (opts.from !== void 0) {
2391
+ if (runState.status === "running") {
2392
+ throw new NagiRuntimeError(
2393
+ `Run ${runId} is still running \u2014 replay({ from }) would race in-flight workers. Wait for the run to settle (completed / failed) before resetting from a step.`
2394
+ );
2395
+ }
2396
+ if (!(opts.from in effectiveFlow.steps)) {
2397
+ throw new NagiValidationError([
2398
+ {
2399
+ message: `replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
2400
+ path: ["from"]
2401
+ }
2402
+ ]);
2403
+ }
2404
+ const cascade = descendantsOf(effectiveFlow, opts.from);
2405
+ const at = clock.now();
2406
+ for (const stepId of cascade) {
2407
+ const fact = stepId === opts.from ? { kind: "step.reset", runId, at, stepId } : {
2408
+ kind: "step.reset",
2409
+ runId,
2410
+ at,
2411
+ stepId,
2412
+ cascadedFrom: opts.from
1670
2413
  };
1671
- await advance(driftDeps, runId);
1672
- return;
2414
+ await config.store.appendFact(runId, fact);
1673
2415
  }
1674
2416
  }
1675
- await advance(dispatchDeps, runId);
2417
+ await advance(replayDeps, runId);
2418
+ if (!fireHooks) await drainInline(replayDeps);
2419
+ },
2420
+ async queryRuns(opts = {}) {
2421
+ if (opts.latest === true) {
2422
+ if (opts.limit !== void 0 || opts.cursor !== void 0) {
2423
+ throw new NagiValidationError([
2424
+ {
2425
+ message: "queryRuns: `latest: true` is incompatible with `limit` / `cursor` \u2014 `latest` returns at most one row.",
2426
+ path: ["latest"]
2427
+ }
2428
+ ]);
2429
+ }
2430
+ }
2431
+ return config.store.queryRuns(opts);
2432
+ },
2433
+ async pruneFacts(opts) {
2434
+ if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
2435
+ throw new NagiValidationError([
2436
+ {
2437
+ message: "pruneFacts: `olderThan` must be a valid Date.",
2438
+ path: ["olderThan"]
2439
+ }
2440
+ ]);
2441
+ }
2442
+ const statuses = opts.statuses ?? [
2443
+ "completed"
2444
+ ];
2445
+ for (const s of statuses) {
2446
+ if (s !== "completed" && s !== "failed" && s !== "canceled") {
2447
+ throw new NagiValidationError([
2448
+ {
2449
+ message: `pruneFacts: status "${s}" is not prunable. Allowed: "completed" | "failed" | "canceled".`,
2450
+ path: ["statuses"]
2451
+ }
2452
+ ]);
2453
+ }
2454
+ }
2455
+ const batchSize = opts.batchSize ?? 1e3;
2456
+ if (!Number.isInteger(batchSize) || batchSize < 1) {
2457
+ throw new NagiValidationError([
2458
+ {
2459
+ message: "pruneFacts: `batchSize` must be a positive integer.",
2460
+ path: ["batchSize"]
2461
+ }
2462
+ ]);
2463
+ }
2464
+ const keepSummary = opts.keepSummary ?? true;
2465
+ return config.store.pruneFacts({
2466
+ olderThan: opts.olderThan,
2467
+ statuses,
2468
+ batchSize,
2469
+ keepSummary
2470
+ });
1676
2471
  }
1677
2472
  };
2473
+ Object.defineProperty(wf, "__dispatchDeps", {
2474
+ value: dispatchDeps,
2475
+ enumerable: false,
2476
+ writable: false,
2477
+ configurable: false
2478
+ });
2479
+ return wf;
2480
+ }
2481
+ async function nagiRun(config) {
2482
+ const wf = await nagiImpl(config);
2483
+ const internal = new AbortController();
2484
+ const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
2485
+ const worker = wf.worker({ ...config.worker, signal });
2486
+ const loop = worker.run();
2487
+ loop.catch((err) => {
2488
+ if (signal.aborted) return;
2489
+ config.logger?.error("nagi.run: worker exited unexpectedly", {
2490
+ error: String(err)
2491
+ });
2492
+ });
2493
+ let stopping;
2494
+ const stop = () => {
2495
+ stopping ??= (async () => {
2496
+ internal.abort();
2497
+ try {
2498
+ await loop;
2499
+ } catch {
2500
+ }
2501
+ })();
2502
+ return stopping;
2503
+ };
2504
+ return { wf, stop };
1678
2505
  }
2506
+ var nagi = Object.assign(
2507
+ nagiImpl,
2508
+ { run: nagiRun }
2509
+ );
1679
2510
  function mintRunId() {
1680
2511
  return `run-${crypto.randomUUID()}`;
1681
2512
  }
2513
+ var MAX_REPLAY_DISPATCHES = 4096;
2514
+ async function drainInline(deps) {
2515
+ for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
2516
+ const messages = await deps.queue.dequeue({ count: 1 });
2517
+ if (messages.length === 0) return;
2518
+ for (const msg of messages) await dispatchMessage(deps, msg);
2519
+ }
2520
+ }
2521
+ function makeOperator(o) {
2522
+ const { deps, clock, flowsById, cancelRunRecursive } = o;
2523
+ const store = deps.store;
2524
+ function resolveFlow(flowId, runId) {
2525
+ const flow2 = flowsById.get(flowId);
2526
+ if (!flow2) {
2527
+ throw new NagiRuntimeError(
2528
+ `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
2529
+ );
2530
+ }
2531
+ return flow2;
2532
+ }
2533
+ async function skip(runId, stepId, opts) {
2534
+ if (typeof opts.actor !== "string" || opts.actor.length === 0) {
2535
+ throw new NagiValidationError([
2536
+ {
2537
+ message: "operator.skip: opts.actor must be a non-empty string",
2538
+ path: ["actor"]
2539
+ }
2540
+ ]);
2541
+ }
2542
+ const cascade = opts.cascade ?? "skip";
2543
+ const state = await store.loadRunState(runId);
2544
+ const flow2 = resolveFlow(state.flowId, runId);
2545
+ if (!(stepId in flow2.steps)) {
2546
+ throw new NagiValidationError([
2547
+ {
2548
+ message: `operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
2549
+ path: ["stepId"]
2550
+ }
2551
+ ]);
2552
+ }
2553
+ const stepState = state.steps[stepId];
2554
+ if (stepState !== void 0 && (stepState.status === "completed" || stepState.status === "failed" || stepState.status === "skipped" || stepState.status === "canceled")) {
2555
+ o.logger?.info("nagi: operator.skip noop \u2014 step already terminal", {
2556
+ runId,
2557
+ stepId,
2558
+ status: stepState.status
2559
+ });
2560
+ return;
2561
+ }
2562
+ if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
2563
+ throw new NagiRuntimeError(
2564
+ `operator.skip: run ${runId} is already terminal (${state.status}); cannot skip step "${stepId}".`
2565
+ );
2566
+ }
2567
+ const fact = {
2568
+ kind: "step.skipped",
2569
+ runId,
2570
+ at: clock.now(),
2571
+ stepId,
2572
+ reason: "manual",
2573
+ actor: opts.actor,
2574
+ cascade,
2575
+ ...opts.note !== void 0 ? { note: opts.note } : {}
2576
+ };
2577
+ await store.appendFact(runId, fact);
2578
+ await advance(deps, runId);
2579
+ }
2580
+ async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
2581
+ const start = Date.now();
2582
+ while (Date.now() - start < deadlineMs) {
2583
+ const s = await store.loadRunState(runId);
2584
+ const ss = s.steps[stepId];
2585
+ if (ss === void 0) return;
2586
+ if (ss.status === "completed" || ss.status === "failed" || ss.status === "skipped" || ss.status === "canceled") {
2587
+ return;
2588
+ }
2589
+ if (s.status === "completed" || s.status === "failed" || s.status === "canceled") {
2590
+ return;
2591
+ }
2592
+ if (ss.attempts > attempt) return;
2593
+ await new Promise((r) => setTimeout(r, 50));
2594
+ }
2595
+ throw new NagiRuntimeError(
2596
+ `operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
2597
+ );
2598
+ }
2599
+ async function retry(runId, stepId, opts) {
2600
+ if (typeof opts.actor !== "string" || opts.actor.length === 0) {
2601
+ throw new NagiValidationError([
2602
+ {
2603
+ message: "operator.retry: opts.actor must be a non-empty string",
2604
+ path: ["actor"]
2605
+ }
2606
+ ]);
2607
+ }
2608
+ const state = await store.loadRunState(runId);
2609
+ if (state.status === "canceled") {
2610
+ throw new NagiRuntimeError(
2611
+ `operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
2612
+ );
2613
+ }
2614
+ const flow2 = resolveFlow(state.flowId, runId);
2615
+ if (!(stepId in flow2.steps)) {
2616
+ throw new NagiValidationError([
2617
+ {
2618
+ message: `operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
2619
+ path: ["stepId"]
2620
+ }
2621
+ ]);
2622
+ }
2623
+ const stepState = state.steps[stepId];
2624
+ if (stepState !== void 0 && stepState.status === "running") {
2625
+ const abortFact = {
2626
+ kind: "step.abort-requested",
2627
+ runId,
2628
+ at: clock.now(),
2629
+ stepId,
2630
+ attempt: stepState.attempts,
2631
+ actor: opts.actor,
2632
+ ...opts.note !== void 0 ? { note: opts.note } : {}
2633
+ };
2634
+ await store.appendFact(runId, abortFact);
2635
+ await waitForStepToSettle(runId, stepId, stepState.attempts, 3e4);
2636
+ }
2637
+ const cascade = descendantsOf(flow2, stepId);
2638
+ const at = clock.now();
2639
+ for (const id of cascade) {
2640
+ const fact = id === stepId ? {
2641
+ kind: "step.reset",
2642
+ runId,
2643
+ at,
2644
+ stepId: id,
2645
+ actor: opts.actor,
2646
+ ...opts.note !== void 0 ? { note: opts.note } : {}
2647
+ } : {
2648
+ kind: "step.reset",
2649
+ runId,
2650
+ at,
2651
+ stepId: id,
2652
+ cascadedFrom: stepId
2653
+ };
2654
+ await store.appendFact(runId, fact);
2655
+ }
2656
+ await advance(deps, runId);
2657
+ }
2658
+ async function abort(runId, opts) {
2659
+ if (typeof opts.actor !== "string" || opts.actor.length === 0) {
2660
+ throw new NagiValidationError([
2661
+ {
2662
+ message: "operator.abort: opts.actor must be a non-empty string",
2663
+ path: ["actor"]
2664
+ }
2665
+ ]);
2666
+ }
2667
+ await cancelRunRecursive(runId, {
2668
+ cause: "operator",
2669
+ reason: opts.note ?? `aborted by operator ${opts.actor}`,
2670
+ actor: opts.actor,
2671
+ ...opts.note !== void 0 ? { note: opts.note } : {}
2672
+ });
2673
+ }
2674
+ return { skip, retry, abort };
2675
+ }
1682
2676
  async function validate(schema, value) {
1683
2677
  const result = await schema["~standard"].validate(value);
1684
2678
  if ("issues" in result && result.issues !== void 0) {
@@ -1728,6 +2722,6 @@ function synthesizeReplayFlow(dag, liveFlow) {
1728
2722
  };
1729
2723
  }
1730
2724
 
1731
- export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, flow, nagi, projectRunState, sha256Canonical };
2725
+ export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiCanceledError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
1732
2726
  //# sourceMappingURL=index.js.map
1733
2727
  //# sourceMappingURL=index.js.map