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

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