@nagi-js/core 0.1.1-rc.1 → 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,221 +1,412 @@
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
  }
6
- function attachDefMut(step, def) {
285
+ function setDef(step, def) {
7
286
  step[DEF] = def;
8
287
  }
9
288
  function getDef(step) {
10
- const def = step[DEF];
11
- if (def === void 0) {
12
- throw new Error(
13
- `Step "${step.id}" has no internal definition. Construct steps via the builder.`
14
- );
15
- }
16
- 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;
17
296
  }
18
297
  function needsStepIds(def) {
19
- const out = [];
20
- for (const upstream of Object.values(def.needs)) {
21
- if (upstream && typeof upstream === "object" && "id" in upstream && typeof upstream.id === "string") {
22
- out.push(upstream.id);
23
- }
24
- }
25
- return out;
298
+ return Object.values(def.needs).map((ref) => ref.step.id);
26
299
  }
27
- function resolveNeeds(def, loadOutput) {
300
+ function resolveNeeds(def, loadResolved) {
28
301
  const result = {};
29
- for (const [localKey, upstream] of Object.entries(def.needs)) {
30
- if (upstream && typeof upstream === "object" && "id" in upstream && typeof upstream.id === "string") {
31
- result[localKey] = loadOutput(upstream.id);
32
- }
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);
33
305
  }
34
306
  return result;
35
307
  }
36
- function matchArms(def) {
37
- return def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
38
- }
39
- function readSelectedArm(matchId, runState) {
40
- for (const fact of runState.facts) {
41
- if (fact.kind === "match.arm-selected" && fact.stepId === matchId) {
42
- return fact.arm;
43
- }
44
- }
45
- return null;
308
+ function asStepMapWithDefs(steps) {
309
+ return steps;
46
310
  }
47
311
  function selectArm(def, args) {
48
- if (def.mode === "discriminator") {
49
- const key = def.on(args);
50
- if (def.arms[key] === void 0) {
51
- const available = Object.keys(def.arms).join(", ");
52
- throw new Error(
53
- `match: discriminator returned "${key}" which has no arm (available: ${available || "<none>"})`
54
- );
55
- }
56
- return key;
57
- }
58
312
  for (const arm of def.arms) {
59
- if (arm.otherwise) return arm.id;
60
- 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;
61
315
  }
62
316
  throw new Error(
63
- `match: no guard arm matched and no { otherwise: true } fallback was provided`
317
+ `match: no arm matched and no { otherwise: true } fallback was provided`
64
318
  );
65
319
  }
66
320
 
67
321
  // src/builder.ts
68
- var BUILDER_BRAND = /* @__PURE__ */ Symbol.for("nagi.builder");
69
- function isBuilder(value) {
70
- return typeof value === "object" && value !== null && value[BUILDER_BRAND] === true;
71
- }
72
- function resolveBuildResult(value) {
73
- if (isBuilder(value)) {
74
- return Object.fromEntries(value.__steps);
75
- }
76
- return value;
77
- }
78
- function isDiscriminator(config) {
79
- return "cases" in config && "on" in config;
80
- }
81
322
  function makeBuilder() {
82
- const chainSteps = /* @__PURE__ */ new Map();
83
323
  function task(config) {
84
324
  const def = {
85
325
  kind: "task",
86
- needs: config.needs ?? {},
87
- ...config.retry !== void 0 ? { retry: config.retry } : {},
88
- ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
89
- ...config.when !== void 0 ? {
90
- when: config.when
91
- } : {},
326
+ needs: normalizeNeeds(config.needs),
92
327
  run: config.run,
93
- ...config.onStart !== void 0 ? { onStart: config.onStart } : {},
94
- ...config.onComplete !== void 0 ? {
95
- onComplete: config.onComplete
96
- } : {},
97
- ...config.onError !== void 0 ? { onError: config.onError } : {},
98
- ...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
+ })
99
337
  };
100
338
  return attachDef({ kind: "task", id: "" }, def);
101
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
+ }
102
357
  function signal(config) {
103
358
  const def = {
104
359
  kind: "signal",
105
- needs: config.needs ?? {},
360
+ needs: normalizeNeeds(config.needs),
106
361
  schema: config.schema,
107
- ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
108
- ...config.when !== void 0 ? {
362
+ ...compact({
363
+ names: config.names,
364
+ timeoutMs: config.timeoutMs,
109
365
  when: config.when
110
- } : {}
366
+ })
111
367
  };
112
368
  return attachDef({ kind: "signal", id: "" }, def);
113
369
  }
114
- function match(config) {
115
- const needs = "needs" in config && config.needs ? config.needs : {};
116
- if (isDiscriminator(config)) {
117
- const arms2 = {};
118
- for (const [caseKey, build] of Object.entries(config.cases)) {
119
- const nested = resolveBuildResult(
120
- build(makeBuilder())
121
- );
122
- arms2[caseKey] = { id: caseKey, stepIds: [], _nested: nested };
123
- }
124
- const def2 = {
125
- kind: "match",
126
- mode: "discriminator",
127
- needs,
128
- on: config.on,
129
- arms: arms2
130
- };
131
- return attachDef({ kind: "match", id: "" }, def2);
132
- }
133
- const guardConfig = config;
134
- const arms = [];
135
- for (let i = 0; i < guardConfig.arms.length; i++) {
136
- const arm = guardConfig.arms[i];
137
- const nested = resolveBuildResult(arm.build(makeBuilder()));
138
- const armId = arm.otherwise ? "otherwise" : `arm${i}`;
139
- arms.push({
140
- id: armId,
141
- ...arm.when !== void 0 ? {
142
- when: arm.when
143
- } : {},
144
- ...arm.otherwise ? { otherwise: true } : {},
145
- stepIds: [],
146
- _nested: nested
147
- });
148
- }
149
- const def = {
150
- kind: "match",
151
- mode: "guard",
152
- needs,
153
- arms
154
- };
155
- return attachDef({ kind: "match", id: "" }, def);
156
- }
157
- function step(key, config) {
158
- if (chainSteps.has(key)) {
159
- throw new Error(
160
- `b.step: duplicate key "${key}" \u2014 each chain entry must have a unique key.`
161
- );
162
- }
163
- const shell = { kind: "task", id: "" };
164
- const needs = {};
165
- if (config.needs) {
166
- for (const sibKey of config.needs) {
167
- const sibling = chainSteps.get(sibKey);
168
- if (sibling === void 0) {
169
- throw new Error(
170
- `b.step("${key}"): unknown sibling "${sibKey}". Available keys so far: ${[...chainSteps.keys()].join(", ") || "<none>"}.`
171
- );
172
- }
173
- needs[sibKey] = sibling;
174
- }
175
- }
370
+ function subflow(child, config) {
176
371
  const def = {
177
- kind: "task",
178
- needs,
179
- ...config.retry !== void 0 ? { retry: config.retry } : {},
180
- ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
181
- ...config.when !== void 0 ? {
372
+ kind: "subflow",
373
+ needs: normalizeNeeds(config.needs),
374
+ childFlowId: child.id,
375
+ buildInput: config.input,
376
+ ...compact({
377
+ timeoutMs: config.timeoutMs,
182
378
  when: config.when
183
- } : {},
184
- run: config.run,
185
- ...config.onStart !== void 0 ? { onStart: config.onStart } : {},
186
- ...config.onComplete !== void 0 ? {
187
- onComplete: config.onComplete
188
- } : {},
189
- ...config.onError !== void 0 ? { onError: config.onError } : {},
190
- ...config.onRetry !== void 0 ? { onRetry: config.onRetry } : {}
379
+ })
191
380
  };
192
- attachDefMut(shell, def);
193
- chainSteps.set(key, shell);
194
- return builder;
381
+ return attachDef(
382
+ { kind: "subflow", id: "" },
383
+ def
384
+ );
195
385
  }
196
- function include(key, s) {
197
- if (chainSteps.has(key)) {
198
- throw new Error(
199
- `b.include: duplicate key "${key}" \u2014 each chain entry must have a unique key.`
200
- );
386
+ function match(config) {
387
+ const needs = normalizeNeeds(config.needs);
388
+ const arms = [];
389
+ for (let i = 0; i < config.arms.length; i++) {
390
+ const arm = config.arms[i];
391
+ const nested = arm.build(makeBuilder());
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 });
201
395
  }
202
- chainSteps.set(key, s);
203
- return builder;
396
+ const def = { kind: "match", needs, arms };
397
+ return attachDef({ kind: "match", id: "" }, def);
204
398
  }
205
- const builder = {
399
+ return {
206
400
  task,
401
+ streamingTask,
207
402
  signal,
208
- match,
209
- step,
210
- include,
211
- [BUILDER_BRAND]: true,
212
- __steps: chainSteps
403
+ subflow,
404
+ match
213
405
  };
214
- return builder;
215
406
  }
216
407
  function flow(config) {
217
408
  const builder = makeBuilder();
218
- const built = resolveBuildResult(config.build(builder));
409
+ const built = config.build(builder);
219
410
  const idByIdentity = /* @__PURE__ */ new Map();
220
411
  collectIds(built, "", idByIdentity);
221
412
  const finalSteps = {};
@@ -227,28 +418,45 @@ function flow(config) {
227
418
  idByIdentity,
228
419
  out: finalSteps
229
420
  });
421
+ assertSignalNameUniqueness(config.id, finalSteps);
230
422
  return {
231
423
  id: config.id,
232
424
  input: config.input,
233
425
  steps: finalSteps,
234
- ...config.output !== void 0 ? { output: config.output } : {},
235
- ...config.onStart !== void 0 ? { onStart: config.onStart } : {},
236
- ...config.onComplete !== void 0 ? {
237
- onComplete: config.onComplete
238
- } : {},
239
- ...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
+ }),
432
+ ...config.concurrency !== void 0 ? { concurrency: normalizeConcurrency(config.concurrency) } : {}
433
+ };
434
+ }
435
+ function optional(step) {
436
+ return { __optional: step };
437
+ }
438
+ function normalizeConcurrency(c) {
439
+ if (typeof c === "object") {
440
+ return {
441
+ keyFn: c.keyFn,
442
+ mode: c.mode ?? "cancel-in-progress"
443
+ };
444
+ }
445
+ const key = c;
446
+ return {
447
+ keyFn: (input) => input[key],
448
+ mode: "cancel-in-progress"
240
449
  };
241
450
  }
242
451
  function collectIds(map, prefix, idByIdentity) {
243
452
  for (const [key, step] of Object.entries(map)) {
244
453
  const id = prefix ? `${prefix}.${key}` : key;
245
454
  idByIdentity.set(step, id);
246
- const def = step.__def;
455
+ const def = peekDef(step);
247
456
  if (def?.kind === "match") {
248
- const arms = def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
249
- for (const arm of arms) {
250
- if (arm._nested)
251
- collectIds(arm._nested, `${id}.${arm.id}`, idByIdentity);
457
+ const pending = def;
458
+ for (const arm of pending.arms) {
459
+ collectIds(arm.nested, `${id}.${arm.id}`, idByIdentity);
252
460
  }
253
461
  }
254
462
  }
@@ -257,7 +465,7 @@ function walkAndRewrite(args) {
257
465
  const { flowId, map, prefix, parentMatch, idByIdentity, out } = args;
258
466
  for (const [key, step] of Object.entries(map)) {
259
467
  const id = prefix ? `${prefix}.${key}` : key;
260
- const def = step.__def;
468
+ const def = peekDef(step);
261
469
  if (def === void 0) {
262
470
  throw new Error(
263
471
  `Flow "${flowId}": step "${id}" has no internal def. Did you return a value not produced by the builder?`
@@ -269,7 +477,8 @@ function walkAndRewrite(args) {
269
477
  );
270
478
  }
271
479
  const rewrittenNeeds = {};
272
- for (const [localKey, upstream] of Object.entries(def.needs)) {
480
+ for (const [localKey, ref] of Object.entries(def.needs)) {
481
+ const upstream = ref.step;
273
482
  const upstreamId = idByIdentity.get(upstream);
274
483
  if (upstreamId === void 0) {
275
484
  const fromOtherFlow = upstream.id !== "";
@@ -277,56 +486,73 @@ function walkAndRewrite(args) {
277
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.`
278
487
  );
279
488
  }
280
- rewrittenNeeds[localKey] = { ...upstream, id: upstreamId };
489
+ rewrittenNeeds[localKey] = {
490
+ step: { ...upstream, id: upstreamId },
491
+ optional: ref.optional
492
+ };
281
493
  }
282
494
  if (def.kind === "match") {
283
- const armList = def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
495
+ const pending = def;
284
496
  const finalizedArms = [];
285
- for (const arm of armList) {
497
+ for (const arm of pending.arms) {
286
498
  const armPrefix = `${id}.${arm.id}`;
287
499
  const nestedStepIds = [];
288
- if (arm._nested) {
289
- for (const nestedKey of Object.keys(arm._nested)) {
290
- nestedStepIds.push(`${armPrefix}.${nestedKey}`);
291
- }
292
- walkAndRewrite({
293
- flowId,
294
- map: arm._nested,
295
- prefix: armPrefix,
296
- parentMatch: { matchId: id, armId: arm.id },
297
- idByIdentity,
298
- out
299
- });
500
+ for (const nestedKey of Object.keys(arm.nested)) {
501
+ nestedStepIds.push(`${armPrefix}.${nestedKey}`);
300
502
  }
503
+ walkAndRewrite({
504
+ flowId,
505
+ map: arm.nested,
506
+ prefix: armPrefix,
507
+ parentMatch: { matchId: id, armId: arm.id },
508
+ idByIdentity,
509
+ out
510
+ });
301
511
  finalizedArms.push({
302
512
  id: arm.id,
303
- ...arm.when !== void 0 ? { when: arm.when } : {},
304
- ...arm.otherwise ? { otherwise: true } : {},
513
+ guard: arm.guard,
305
514
  stepIds: nestedStepIds
306
515
  });
307
516
  }
308
- const finalizedDef2 = def.mode === "discriminator" ? {
309
- kind: "match",
310
- mode: "discriminator",
311
- needs: rewrittenNeeds,
312
- on: def.on,
313
- arms: Object.fromEntries(finalizedArms.map((a) => [a.id, a])),
314
- ...parentMatch ? { parentMatch } : {}
315
- } : {
517
+ const finalizedDef2 = {
316
518
  kind: "match",
317
- mode: "guard",
318
519
  needs: rewrittenNeeds,
319
520
  arms: finalizedArms,
320
- ...parentMatch ? { parentMatch } : {}
521
+ ...compact({ parentMatch })
321
522
  };
322
523
  out[id] = attachDef({ kind: "match", id }, finalizedDef2);
323
524
  continue;
324
525
  }
325
- const baseRewritten = { ...def, needs: rewrittenNeeds };
326
- const finalizedDef = parentMatch ? { ...baseRewritten, parentMatch } : baseRewritten;
526
+ const finalizedDef = {
527
+ ...def,
528
+ needs: rewrittenNeeds,
529
+ ...compact({ parentMatch })
530
+ };
327
531
  out[id] = attachDef({ kind: finalizedDef.kind, id }, finalizedDef);
328
532
  }
329
533
  }
534
+ function assertSignalNameUniqueness(flowId, finalSteps) {
535
+ const owners = /* @__PURE__ */ new Map();
536
+ for (const stepId of Object.keys(finalSteps)) {
537
+ owners.set(stepId, `step id "${stepId}"`);
538
+ }
539
+ for (const [stepId, step] of Object.entries(finalSteps)) {
540
+ const def = peekDef(step);
541
+ if (def === void 0 || def.kind !== "signal") continue;
542
+ if (def.names === void 0) continue;
543
+ for (const alias of def.names) {
544
+ if (alias === stepId) continue;
545
+ const prior = owners.get(alias);
546
+ const here = `alias of step "${stepId}"`;
547
+ if (prior !== void 0 && prior !== here) {
548
+ throw new Error(
549
+ `Flow "${flowId}": signal name "${alias}" is declared as both ${prior} and ${here}. Pick one \u2014 signal names share a namespace with step ids.`
550
+ );
551
+ }
552
+ owners.set(alias, here);
553
+ }
554
+ }
555
+ }
330
556
 
331
557
  // src/canonicalize.ts
332
558
  var DEFAULT_RETRY = {
@@ -338,14 +564,15 @@ function warnSourceHashOnce() {
338
564
  if (warnedAboutSourceHash) return;
339
565
  warnedAboutSourceHash = true;
340
566
  console.warn(
341
- "[nagi] canonicalize: hashing `when`/schema source via Function.prototype.toString(). Cosmetic source changes (minification, whitespace, identifier renames) will flip the flow hash even when behavior is unchanged. See RFC 0001."
567
+ "[nagi] canonicalize: hashing `when`/schema source via Function.prototype.toString(). Cosmetic source changes (minification, whitespace, identifier renames) will flip the flow hash even when behavior is unchanged."
342
568
  );
343
569
  }
344
570
  async function canonicalize(flow2) {
345
- const ids = Object.keys(flow2.steps).sort();
571
+ const withDefs = asStepMapWithDefs(flow2.steps);
572
+ const ids = Object.keys(withDefs).sort();
346
573
  const steps = [];
347
574
  for (const id of ids) {
348
- const step = flow2.steps[id];
575
+ const step = withDefs[id];
349
576
  if (step === void 0) continue;
350
577
  steps.push(await canonicalizeStep(id, getDef(step)));
351
578
  }
@@ -358,32 +585,42 @@ async function canonicalize(flow2) {
358
585
  async function canonicalizeStep(id, def) {
359
586
  const needs = [...needsStepIds(def)].sort();
360
587
  const base = { id, kind: def.kind, needs };
361
- if (def.kind === "task") return canonicalizeTask(base, def);
588
+ if (def.kind === "task" || def.kind === "streaming")
589
+ return canonicalizeTask(base, def);
362
590
  if (def.kind === "signal") return canonicalizeSignal(base, def);
591
+ if (def.kind === "subflow") return canonicalizeSubflow(base, def);
363
592
  return canonicalizeMatch(base, def);
364
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
+ }
365
598
  async function canonicalizeTask(base, def) {
366
599
  const out = { ...base };
367
- if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
600
+ await applyGuardAndTimeout(out, def);
368
601
  if (def.retry !== void 0) out.retry = normalizeRetry(def.retry);
369
- if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
370
602
  return out;
371
603
  }
372
604
  async function canonicalizeSignal(base, def) {
373
605
  const out = { ...base };
374
- if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
375
- if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
606
+ await applyGuardAndTimeout(out, def);
376
607
  out.signalSchema = await canonicalizeSchema(def.schema);
608
+ if (def.names !== void 0) {
609
+ out.signalNames = [...def.names].sort();
610
+ }
611
+ return out;
612
+ }
613
+ async function canonicalizeSubflow(base, def) {
614
+ const out = { ...base };
615
+ await applyGuardAndTimeout(out, def);
616
+ out.childFlowId = def.childFlowId;
617
+ out.subflowInputHash = await hashFnSource(def.buildInput);
377
618
  return out;
378
619
  }
379
620
  async function canonicalizeMatch(base, def) {
380
621
  const out = { ...base };
381
- out.matchMode = def.mode;
382
- if (def.mode === "discriminator") {
383
- out.matchOnHash = await hashFnSource(def.on);
384
- }
385
622
  const arms = [];
386
- for (const arm of matchArms(def)) {
623
+ for (const arm of def.arms) {
387
624
  arms.push(await canonicalizeArm(arm));
388
625
  }
389
626
  out.matchArms = arms;
@@ -394,8 +631,8 @@ async function canonicalizeArm(arm) {
394
631
  id: arm.id,
395
632
  stepIds: [...arm.stepIds].sort()
396
633
  };
397
- if (arm.otherwise) out.otherwise = true;
398
- 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);
399
636
  return out;
400
637
  }
401
638
  function normalizeRetry(retry) {
@@ -421,6 +658,15 @@ async function hashFnSource(fn) {
421
658
  async function sha256Canonical(dag) {
422
659
  return sha256Hex(stableStringify(dag));
423
660
  }
661
+ async function fingerprintFlows(flows) {
662
+ const entries = [];
663
+ for (const f of flows) {
664
+ const dag = await canonicalize(f);
665
+ entries.push([f.id, await sha256Canonical(dag)]);
666
+ }
667
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
668
+ return sha256Hex(stableStringify(entries));
669
+ }
424
670
  function stableStringify(value) {
425
671
  if (value === void 0) return "null";
426
672
  if (value === null || typeof value !== "object") return JSON.stringify(value);
@@ -515,12 +761,6 @@ function diffFields(before, after, out) {
515
761
  if (!schemaEq(before.signalSchema, after.signalSchema)) {
516
762
  out.push({ stepId: id, field: "signalSchema" });
517
763
  }
518
- if (before.matchMode !== after.matchMode) {
519
- out.push({ stepId: id, field: "matchMode" });
520
- }
521
- if (before.matchOnHash !== after.matchOnHash) {
522
- out.push({ stepId: id, field: "matchOn" });
523
- }
524
764
  if (!armsEq(before.matchArms, after.matchArms)) {
525
765
  out.push({ stepId: id, field: "matchArms" });
526
766
  }
@@ -557,154 +797,838 @@ function cmp(a, b) {
557
797
  return a < b ? -1 : a > b ? 1 : 0;
558
798
  }
559
799
 
560
- // src/memory.ts
561
- var DEFAULT_STORE_LEASE_MS = 6e4;
562
- var InMemoryStore = class {
563
- facts = /* @__PURE__ */ new Map();
564
- outputs = /* @__PURE__ */ new Map();
565
- onces = /* @__PURE__ */ new Map();
566
- leases = /* @__PURE__ */ new Map();
567
- snapshots = /* @__PURE__ */ new Map();
568
- refs = /* @__PURE__ */ new Map();
569
- globalFacts = [];
570
- leaseMs;
571
- constructor(opts = {}) {
572
- this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
573
- }
574
- async appendFact(runId, fact) {
575
- const list = this.facts.get(runId) ?? [];
576
- list.push(fact);
577
- this.facts.set(runId, list);
578
- }
579
- async tryStartRun(runId, fact) {
580
- if (this.facts.has(runId)) {
581
- return { started: false };
582
- }
583
- this.facts.set(runId, [fact]);
584
- return { started: true };
585
- }
586
- async loadRunState(runId) {
587
- return projectRunState(runId, this.facts.get(runId) ?? []);
588
- }
589
- async claimStep(runId, stepId, attempt) {
590
- const key = `${runId}::${stepId}::${attempt}`;
591
- const now = Date.now();
592
- const existing = this.leases.get(key);
593
- if (existing && existing.expiresAt > now) {
594
- return null;
595
- }
596
- const token = `lease-${crypto.randomUUID()}`;
597
- this.leases.set(key, { token, expiresAt: now + this.leaseMs });
598
- return token;
599
- }
600
- async completeStep(runId, stepId, output, fact) {
601
- this.outputs.set(`${runId}::${stepId}`, output);
602
- await this.appendFact(runId, fact);
603
- }
604
- async failStep(runId, _stepId, _error, fact) {
605
- await this.appendFact(runId, fact);
606
- }
607
- async getStepOutput(runId, stepId) {
608
- return this.outputs.get(`${runId}::${stepId}`) ?? null;
609
- }
610
- async recordOnce(runId, stepId, scope, value) {
611
- this.onces.set(`${runId}::${stepId}::${scope}`, value);
612
- }
613
- async getOnce(runId, stepId, scope) {
614
- return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
615
- }
616
- async runStep(runId, stepId, _attempt, body) {
617
- const result = await body(void 0);
618
- if (result.fact.kind === "step.completed") {
619
- await this.completeStep(runId, stepId, result.output, result.fact);
620
- } else {
621
- await this.failStep(runId, stepId, result.fact.error, result.fact);
622
- }
623
- return result.output;
624
- }
625
- async upsertSnapshot(args) {
626
- if (this.snapshots.has(args.flowHash)) return;
627
- this.snapshots.set(args.flowHash, { flowId: args.flowId, dag: args.dag });
628
- }
629
- async getRef(flowId) {
630
- return this.refs.get(flowId) ?? null;
631
- }
632
- async setRef(flowId, flowHash) {
633
- this.refs.set(flowId, flowHash);
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;
634
807
  }
635
- async loadSnapshot(flowHash) {
636
- return this.snapshots.get(flowHash) ?? null;
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";
637
816
  }
638
- async appendGlobalFact(fact) {
639
- this.globalFacts.push(fact);
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
+ };
640
838
  }
641
- /** Test-only: peek at the in-memory global fact log. */
642
- readGlobalFacts() {
643
- return this.globalFacts;
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;
644
856
  }
645
857
  };
646
- function projectRunState(runId, facts) {
647
- let flowId = "";
648
- let status = "pending";
649
- let flowHash;
650
- let codeVersion;
651
- const steps = {};
652
- for (const fact of facts) {
653
- switch (fact.kind) {
654
- case "flow.started":
655
- flowId = fact.flowId;
656
- status = "running";
657
- flowHash = fact.flowHash;
658
- codeVersion = fact.codeVersion;
659
- break;
660
- case "flow.completed":
661
- status = "completed";
662
- break;
663
- case "flow.failed":
664
- status = "failed";
665
- break;
666
- case "step.started":
667
- steps[fact.stepId] = {
668
- stepId: fact.stepId,
669
- status: "running",
670
- attempts: fact.attempt
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
+ };
865
+ }
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
+ };
999
+ }
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
+ }
671
1299
  };
672
- break;
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) {
673
1328
  case "step.completed":
674
- steps[fact.stepId] = {
675
- stepId: fact.stepId,
676
- status: "completed",
677
- attempts: fact.attempt,
678
- output: fact.output
679
- };
1329
+ this.streamHub.closeOk(runId, fact.stepId);
680
1330
  break;
681
1331
  case "step.failed":
682
- steps[fact.stepId] = {
683
- stepId: fact.stepId,
684
- status: "failed",
685
- attempts: fact.attempt,
686
- error: fact.error
687
- };
1332
+ this.streamHub.closeError(runId, fact.stepId, fact.error);
688
1333
  break;
689
- case "step.skipped":
690
- steps[fact.stepId] = {
691
- stepId: fact.stepId,
692
- status: "skipped",
693
- attempts: 0
694
- };
1334
+ case "step.retried":
1335
+ this.streamHub.signalRetry(
1336
+ runId,
1337
+ fact.stepId,
1338
+ fact.attempt + 1
1339
+ );
695
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);
1414
+ }
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
+ }
1430
+ }
1431
+ async recordOnce(runId, stepId, scope, value) {
1432
+ this.onces.set(`${runId}::${stepId}::${scope}`, value);
1433
+ }
1434
+ async getOnce(runId, stepId, scope) {
1435
+ return this.onces.get(`${runId}::${stepId}::${scope}`) ?? null;
1436
+ }
1437
+ async runStep(runId, _stepId, _attempt, body) {
1438
+ const result = await body(void 0);
1439
+ await this.appendFact(runId, result.fact);
1440
+ return result.output;
1441
+ }
1442
+ async upsertSnapshot(args) {
1443
+ if (this.snapshots.has(args.flowHash)) return;
1444
+ this.snapshots.set(args.flowHash, { flowId: args.flowId, dag: args.dag });
1445
+ }
1446
+ async getRef(flowId) {
1447
+ return this.refs.get(flowId) ?? null;
1448
+ }
1449
+ async setRef(flowId, flowHash) {
1450
+ this.refs.set(flowId, flowHash);
1451
+ }
1452
+ async loadSnapshot(flowHash) {
1453
+ return this.snapshots.get(flowHash) ?? null;
1454
+ }
1455
+ async appendGlobalFact(fact) {
1456
+ this.globalFacts.push(fact);
1457
+ }
1458
+ readGlobalFacts() {
1459
+ return this.globalFacts;
1460
+ }
1461
+ async queryRuns(opts) {
1462
+ const where = opts.where ?? {};
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));
1465
+ const summaries = [];
1466
+ for (const [runId, factList] of this.facts) {
1467
+ const summary = summarize(runId, factList);
1468
+ if (summary === null) continue;
1469
+ if (matches(summary)) summaries.push(summary);
1470
+ }
1471
+ for (const summary of this.summaries.values()) {
1472
+ if (matches(summary)) summaries.push(summary);
1473
+ }
1474
+ summaries.sort((a, b) => {
1475
+ const t = b.startedAt.getTime() - a.startedAt.getTime();
1476
+ if (t !== 0) return t;
1477
+ return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
1478
+ });
1479
+ if (opts.latest === true) {
1480
+ return { runs: summaries.slice(0, 1), cursor: null };
1481
+ }
1482
+ const limit = clampLimit(opts.limit);
1483
+ let start = 0;
1484
+ if (opts.cursor !== void 0) {
1485
+ const c = decodeCursor(opts.cursor);
1486
+ start = summaries.findIndex(
1487
+ (s) => s.startedAt.getTime() < c.t || s.startedAt.getTime() === c.t && s.runId < c.r
1488
+ );
1489
+ if (start === -1) start = summaries.length;
1490
+ }
1491
+ const page = summaries.slice(start, start + limit);
1492
+ const hasMore = start + limit < summaries.length;
1493
+ const last = page[page.length - 1];
1494
+ const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
1495
+ return { runs: page, cursor };
1496
+ }
1497
+ async pruneFacts(opts) {
1498
+ const olderThanMs = opts.olderThan.getTime();
1499
+ const statusSet = new Set(opts.statuses);
1500
+ const victims = [];
1501
+ for (const [runId, factList] of this.facts) {
1502
+ const summary = summarize(runId, factList);
1503
+ if (summary === null) continue;
1504
+ if (summary.completedAt === null) continue;
1505
+ if (!statusSet.has(summary.status)) continue;
1506
+ if (summary.completedAt.getTime() >= olderThanMs) continue;
1507
+ const first = factList[0];
1508
+ const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parent?.runId : void 0;
1509
+ victims.push({
1510
+ runId,
1511
+ summary,
1512
+ factCount: factList.length,
1513
+ parentRunId
1514
+ });
1515
+ }
1516
+ let runsPruned = 0;
1517
+ let factsPruned = 0;
1518
+ for (const v of victims) {
1519
+ this.facts.delete(v.runId);
1520
+ deleteByRunPrefix(this.onces, v.runId);
1521
+ deleteByRunPrefix(this.leases, v.runId);
1522
+ this.childrenByParent.delete(v.runId);
1523
+ if (v.parentRunId !== void 0) {
1524
+ const siblings = this.childrenByParent.get(v.parentRunId);
1525
+ if (siblings !== void 0) {
1526
+ siblings.delete(v.runId);
1527
+ if (siblings.size === 0) this.childrenByParent.delete(v.parentRunId);
1528
+ }
1529
+ }
1530
+ if (opts.keepSummary) {
1531
+ this.summaries.set(v.runId, v.summary);
1532
+ } else {
1533
+ this.summaries.delete(v.runId);
1534
+ }
1535
+ runsPruned += 1;
1536
+ factsPruned += v.factCount;
1537
+ }
1538
+ return { runsPruned, factsPruned };
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
+ }
1557
+ };
1558
+ function deleteByRunPrefix(map, runId) {
1559
+ const prefix = `${runId}::`;
1560
+ for (const key of map.keys()) {
1561
+ if (key.startsWith(prefix)) map.delete(key);
1562
+ }
1563
+ }
1564
+ function summarize(runId, facts) {
1565
+ const first = facts[0];
1566
+ if (first === void 0 || first.kind !== "flow.started") return null;
1567
+ const projected = foldRun(runId, facts);
1568
+ let completedAt = null;
1569
+ for (let i = facts.length - 1; i >= 0; i--) {
1570
+ const f = facts[i];
1571
+ if (f === void 0) continue;
1572
+ if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
1573
+ completedAt = f.at;
1574
+ break;
696
1575
  }
697
1576
  }
698
1577
  return {
699
1578
  runId,
700
- flowId,
701
- status,
702
- steps,
703
- facts,
704
- ...flowHash !== void 0 ? { flowHash } : {},
705
- ...codeVersion !== void 0 ? { codeVersion } : {}
1579
+ flowId: first.flowId,
1580
+ status: runStatusOf(projected),
1581
+ startedAt: first.at,
1582
+ completedAt,
1583
+ input: first.input
706
1584
  };
707
1585
  }
1586
+ var DEFAULT_LIMIT = 50;
1587
+ var MAX_LIMIT = 500;
1588
+ function clampLimit(limit) {
1589
+ if (limit === void 0) return DEFAULT_LIMIT;
1590
+ if (!Number.isInteger(limit) || limit < 1) return DEFAULT_LIMIT;
1591
+ return Math.min(limit, MAX_LIMIT);
1592
+ }
1593
+ function encodeCursor(c) {
1594
+ const bytes = new TextEncoder().encode(JSON.stringify(c));
1595
+ let binary = "";
1596
+ for (let i = 0; i < bytes.length; i++) {
1597
+ binary += String.fromCharCode(bytes[i]);
1598
+ }
1599
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1600
+ }
1601
+ function decodeCursor(s) {
1602
+ try {
1603
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
1604
+ const binary = atob(b64);
1605
+ const bytes = new Uint8Array(binary.length);
1606
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1607
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
1608
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
1609
+ return parsed;
1610
+ }
1611
+ throw new Error("malformed cursor body");
1612
+ } catch (err) {
1613
+ throw new Error(
1614
+ `queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
1615
+ );
1616
+ }
1617
+ }
1618
+ function containsJson(haystack, needle) {
1619
+ if (Array.isArray(needle)) {
1620
+ if (!Array.isArray(haystack)) return false;
1621
+ return needle.every((n) => haystack.some((h) => containsJson(h, n)));
1622
+ }
1623
+ if (needle !== null && typeof needle === "object") {
1624
+ if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
1625
+ return false;
1626
+ return Object.entries(needle).every(
1627
+ ([k, v]) => k in haystack && containsJson(haystack[k], v)
1628
+ );
1629
+ }
1630
+ return haystack === needle;
1631
+ }
708
1632
  var DEFAULT_QUEUE_LEASE_MS = 6e4;
709
1633
  var InMemoryQueue = class {
710
1634
  pending = [];
@@ -796,7 +1720,6 @@ var InMemoryClock = class {
796
1720
  }, delay);
797
1721
  this.timers.set(key, handle);
798
1722
  }
799
- /** Clear any pending scheduled timers. Call from test teardown. */
800
1723
  dispose() {
801
1724
  for (const t of this.timers.values()) clearTimeout(t);
802
1725
  this.timers.clear();
@@ -810,76 +1733,85 @@ var InMemoryTrigger = class {
810
1733
  this.handlers = this.handlers.filter((h) => h !== handler);
811
1734
  };
812
1735
  }
813
- /**
814
- * Test-only: synchronously dispatch a wake-up to all subscribers.
815
- * Real triggers fire from a Store change (NOTIFY/LISTEN, polling, etc.).
816
- */
817
1736
  fire(runId) {
818
1737
  for (const h of this.handlers) h(runId);
819
1738
  }
820
1739
  };
821
1740
 
822
- // src/idempotency.ts
823
- function makeIdempotencyKey(runId, stepId) {
824
- return (scope) => `nagi:${runId}:${stepId}:${scope}`;
825
- }
826
- function makeOnce(args) {
827
- const { runId, stepId, store } = args;
828
- return async function once(scope, fn) {
829
- const cached = await store.getOnce(runId, stepId, scope);
830
- if (cached !== null) return cached;
831
- const value = await fn();
832
- await store.recordOnce(runId, stepId, scope, value);
833
- return value;
834
- };
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 };
835
1762
  }
836
1763
 
837
1764
  // src/scheduler.ts
838
- function nextRunnable(args) {
839
- const { flow: flow2, runState, input } = args;
1765
+ function nextRunnable({
1766
+ flow: flow2,
1767
+ runState,
1768
+ input
1769
+ }) {
840
1770
  const runnable = [];
841
1771
  const skip = [];
842
- for (const [stepId, step] of Object.entries(flow2.steps)) {
843
- const state = runState.steps[stepId];
844
- if (state !== void 0 && state.status !== "pending") continue;
845
- const def = getDef(step);
846
- const parentGate = checkParentMatch(def, runState);
847
- if (parentGate === "blocked") continue;
848
- if (parentGate === "transitive-skip") {
849
- skip.push({ stepId, reason: "transitive" });
850
- continue;
851
- }
852
- const upstreamCheck = checkUpstream(def, runState);
853
- if (upstreamCheck === "blocked") continue;
854
- if (upstreamCheck === "transitive-skip") {
855
- skip.push({ stepId, reason: "transitive" });
856
- continue;
857
- }
858
- const when = def.kind === "match" ? void 0 : def.when;
859
- if (when) {
860
- const needs = resolveNeeds(
861
- def,
862
- (id) => runState.steps[id]?.output ?? null
863
- );
864
- const shouldRun = when({ input, needs });
865
- if (!shouldRun) {
866
- skip.push({ stepId, reason: "when-false" });
867
- continue;
868
- }
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;
869
1782
  }
870
- runnable.push(stepId);
871
1783
  }
872
1784
  return { runnable, skip };
873
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
+ }
874
1809
  function checkUpstream(def, runState) {
875
- for (const upstream of Object.values(def.needs)) {
876
- if (!upstream || typeof upstream !== "object" || !("id" in upstream) || typeof upstream.id !== "string") {
877
- continue;
878
- }
879
- const upstreamState = runState.steps[upstream.id];
880
- if (upstreamState === void 0) return "blocked";
881
- if (upstreamState.status === "completed") continue;
882
- if (upstreamState.status === "skipped" || 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") {
883
1815
  return "transitive-skip";
884
1816
  }
885
1817
  return "blocked";
@@ -889,506 +1821,1057 @@ function checkUpstream(def, runState) {
889
1821
  function checkParentMatch(def, runState) {
890
1822
  if (!def.parentMatch) return "ready";
891
1823
  const { matchId, armId } = def.parentMatch;
892
- const parentState = runState.steps[matchId];
893
- if (parentState?.status === "failed" || parentState?.status === "skipped") {
1824
+ const parentState = stepStateOf(runState, matchId);
1825
+ if (parentState.tag === "failed" || parentState.tag === "skipped") {
894
1826
  return "transitive-skip";
895
1827
  }
896
- const selected = readSelectedArm(matchId, runState);
1828
+ const selected = runState.selectedArms[matchId] ?? null;
897
1829
  if (selected === null) return "blocked";
898
1830
  return selected === armId ? "ready" : "transitive-skip";
899
1831
  }
900
1832
  function aggregateMatch(matchId, flow2, runState) {
901
- const step = flow2.steps[matchId];
1833
+ const step = asStepMapWithDefs(flow2.steps)[matchId];
902
1834
  if (!step) return { kind: "pending" };
903
1835
  const def = getDef(step);
904
1836
  if (def.kind !== "match") return { kind: "pending" };
905
- const selected = readSelectedArm(matchId, runState);
1837
+ const selected = runState.selectedArms[matchId] ?? null;
906
1838
  if (selected === null) return { kind: "pending" };
907
- const arm = def.mode === "discriminator" ? def.arms[selected] : def.arms.find((a) => a.id === selected);
1839
+ const arm = def.arms.find((a) => a.id === selected);
908
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
+ }
909
1846
  const output = {};
910
- let allTerminal = true;
911
- const stripPrefix = `${matchId}.${arm.id}.`;
912
1847
  for (const stepId of arm.stepIds) {
913
- const state = runState.steps[stepId];
914
- if (state === void 0 || state.status === "pending" || state.status === "running") {
915
- allTerminal = false;
916
- continue;
917
- }
918
- if (state.status === "failed") {
919
- return { kind: "fail-fast", failedStepId: stepId };
920
- }
921
- const localKey = stepId.startsWith(stripPrefix) ? stepId.slice(stripPrefix.length) : stepId;
922
- 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);
923
1851
  }
924
- if (!allTerminal) return { kind: "pending" };
925
1852
  return { kind: "complete", output };
926
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
+ }
927
1859
  function flowTermination(flow2, runState) {
928
- let done = true;
929
- let failed = false;
1860
+ let failure;
930
1861
  for (const stepId of Object.keys(flow2.steps)) {
931
- const state = runState.steps[stepId];
932
- if (state === void 0 || state.status === "pending" || state.status === "running") {
933
- done = false;
934
- break;
1862
+ const state = stepStateOf(runState, stepId);
1863
+ if (!isStepTerminal(state)) return { kind: "running" };
1864
+ if (state.tag === "failed" && failure === void 0) failure = state.error;
1865
+ }
1866
+ if (failure !== void 0) return { kind: "failed", error: failure };
1867
+ return { kind: "succeeded" };
1868
+ }
1869
+ function nextTransition(flow2, runState) {
1870
+ const promotions = readyPromotions(flow2, runState);
1871
+ if (promotions.length > 0) return { kind: "promote-match", promotions };
1872
+ const term = flowTermination(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) };
935
1879
  }
936
- if (state.status === "failed") failed = true;
937
1880
  }
938
- return { done, failed };
1881
+ const input = runState.input;
1882
+ const { runnable, skip } = nextRunnable({ flow: flow2, runState, input });
1883
+ if (runnable.length > 0) return { kind: "dispatch", runnable, skip };
1884
+ if (skip.length > 0) return { kind: "skip", skip };
1885
+ return { kind: "waiting" };
939
1886
  }
940
- function extractInput(runState) {
941
- for (const fact of runState.facts) {
942
- if (fact.kind === "flow.started") return fact.input;
1887
+ function readyPromotions(flow2, runState) {
1888
+ const out = [];
1889
+ for (const [matchId, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
1890
+ const def = getDef(step);
1891
+ if (def.kind !== "match") continue;
1892
+ const state = stepStateOf(runState, matchId);
1893
+ if (state.tag !== "running") continue;
1894
+ const agg = aggregateMatch(matchId, flow2, runState);
1895
+ if (agg.kind === "pending") continue;
1896
+ const attempt = attemptOf(state);
1897
+ if (agg.kind === "fail-fast") {
1898
+ out.push({
1899
+ matchId,
1900
+ attempt,
1901
+ result: { kind: "fail", error: agg.error }
1902
+ });
1903
+ } else {
1904
+ out.push({
1905
+ matchId,
1906
+ attempt,
1907
+ result: { kind: "complete", output: agg.output }
1908
+ });
1909
+ }
943
1910
  }
944
- throw new Error(
945
- "No flow.started fact in run \u2014 was the run initialized via wf.start?"
946
- );
1911
+ return out;
947
1912
  }
948
-
949
- // src/dispatch.ts
950
- async function fireHook(hook, event, hookName, deps) {
951
- if (deps.fireHooks === false) return;
952
- if (hook === void 0) return;
953
- try {
954
- await hook(event);
955
- } catch (err) {
956
- const { message, stack } = serializeError(err);
957
- deps.logger?.error(`nagi hook "${hookName}" threw \u2014 swallowed`, {
958
- error: message,
959
- ...stack !== void 0 ? { stack } : {}
960
- });
1913
+ function computeFlowOutput(flow2, runState) {
1914
+ if (flow2.output === void 0) return null;
1915
+ const stepOutputs = {};
1916
+ for (const [sid, sstate] of Object.entries(runState.steps)) {
1917
+ if (sstate.tag === "completed") stepOutputs[sid] = sstate.output;
961
1918
  }
1919
+ return flow2.output(stepOutputs);
962
1920
  }
1921
+ function descendantsOf(flow2, stepId) {
1922
+ const children = /* @__PURE__ */ new Map();
1923
+ const addEdge = (from, to) => {
1924
+ const bucket = children.get(from);
1925
+ if (bucket) bucket.push(to);
1926
+ else children.set(from, [to]);
1927
+ };
1928
+ for (const [id, step] of Object.entries(asStepMapWithDefs(flow2.steps))) {
1929
+ const def = getDef(step);
1930
+ for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
1931
+ if (def.kind === "match") {
1932
+ for (const arm of def.arms) {
1933
+ for (const armStepId of arm.stepIds) addEdge(id, armStepId);
1934
+ }
1935
+ }
1936
+ }
1937
+ const out = [stepId];
1938
+ const seen = /* @__PURE__ */ new Set([stepId]);
1939
+ for (let i = 0; i < out.length; i++) {
1940
+ const current = out[i];
1941
+ if (current === void 0) continue;
1942
+ for (const child of children.get(current) ?? []) {
1943
+ if (seen.has(child)) continue;
1944
+ if (!(child in flow2.steps)) continue;
1945
+ seen.add(child);
1946
+ out.push(child);
1947
+ }
1948
+ }
1949
+ return out;
1950
+ }
1951
+
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
+ };
1968
+ }
1969
+
1970
+ // src/step-exec.ts
963
1971
  var DEFAULT_RETRY2 = {
964
1972
  maxAttempts: 3,
965
1973
  backoff: "exponential",
966
1974
  initialDelayMs: 1e3,
967
1975
  maxDelayMs: 6e4
968
1976
  };
969
- async function dispatchMessage(deps, message) {
970
- const { store, queue, clock } = deps;
971
- const { runId, stepId, attempt } = message;
972
- const flow2 = await deps.flowFor(runId);
973
- const step = flow2.steps[stepId];
974
- if (!step) {
975
- deps.logger?.warn(
976
- `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.`
977
1984
  );
978
- await queue.ack(message.receipt);
979
- return;
1985
+ this.name = "NagiAbortError";
1986
+ this.runId = runId;
1987
+ this.scope = scope;
980
1988
  }
981
- const def = getDef(step);
982
- const preState = await store.loadRunState(runId);
983
- const preStep = preState.steps[stepId];
984
- if (preStep && (preStep.status === "completed" || preStep.status === "failed" || preStep.status === "skipped")) {
985
- await queue.ack(message.receipt);
986
- 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
+ };
987
1997
  }
988
- const claim = await store.claimStep(runId, stepId, attempt);
989
- if (claim === null) {
990
- await queue.ack(message.receipt);
991
- return;
1998
+ if (isAbortRequested(stepStateOf(postState, stepId), attempt)) {
1999
+ return {
2000
+ fact: Facts.stepCanceled(runId, stepId, attempt, at),
2001
+ abortedHere: true
2002
+ };
992
2003
  }
993
- await store.appendFact(runId, {
994
- kind: "step.started",
995
- runId,
996
- stepId,
997
- attempt,
998
- at: clock.now()
999
- });
1000
- const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
1001
- const startEvent = {
2004
+ return {
2005
+ fact: Facts.stepCompleted(runId, stepId, attempt, output, at),
2006
+ abortedHere: false
2007
+ };
2008
+ }
2009
+ function startCancelWatcher(args) {
2010
+ const { store, runId, stepId, attempt, ac, intervalMs } = args;
2011
+ let stopped = false;
2012
+ void (async () => {
2013
+ while (!stopped) {
2014
+ await new Promise((r) => setTimeout(r, intervalMs));
2015
+ if (stopped) return;
2016
+ try {
2017
+ const s = await store.loadRunState(runId);
2018
+ if (isTerminalRun(s)) {
2019
+ if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
2020
+ return;
2021
+ }
2022
+ if (isAbortRequested(stepStateOf(s, stepId), attempt)) {
2023
+ if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
2024
+ return;
2025
+ }
2026
+ } catch {
2027
+ }
2028
+ }
2029
+ })();
2030
+ return {
2031
+ stop: () => {
2032
+ stopped = true;
2033
+ }
2034
+ };
2035
+ }
2036
+ function classifyFailure(args) {
2037
+ const { attempt, policy, err, runIsCanceled, stepAborted } = args;
2038
+ if (runIsCanceled || stepAborted) {
2039
+ const isAbort = err instanceof NagiAbortError || err instanceof Error && err.name === "AbortError";
2040
+ return {
2041
+ tag: "canceled",
2042
+ advanceAfter: !stepAborted,
2043
+ includeError: isAbort
2044
+ };
2045
+ }
2046
+ if (attempt < policy.maxAttempts && retryAllows(policy, err)) {
2047
+ return { tag: "retry", delayMs: computeBackoff(policy, attempt) };
2048
+ }
2049
+ return { tag: "failed" };
2050
+ }
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);
2061
+ }
2062
+ }
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,
1002
2078
  runId,
1003
- flowId: flow2.id,
1004
2079
  stepId,
1005
2080
  attempt,
1006
- kind: def.kind,
1007
- input: startEventInput,
1008
- at: clock.now()
2081
+ signal,
2082
+ now: () => clock.now(),
2083
+ tx,
2084
+ logger,
2085
+ once: makeOnce({ runId, stepId, store }),
2086
+ idempotencyKey: makeIdempotencyKey(runId, stepId)
1009
2087
  };
1010
- const stepOnStart = def.kind === "task" ? def.onStart : void 0;
1011
- await fireHook(stepOnStart, startEvent, "step.onStart", deps);
1012
- await fireHook(deps.hooks?.onStepStart, startEvent, "onStepStart", deps);
1013
- const startedAt = Date.now();
1014
- try {
1015
- if (def.kind === "task") {
1016
- const output = await executeTask({
1017
- deps,
1018
- message,
1019
- def,
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
+ {
1020
2152
  runId,
2153
+ flowId: flow2.id,
1021
2154
  stepId,
1022
- attempt
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
1023
2256
  });
1024
- const completeEvent = {
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(
1025
2278
  runId,
1026
- flowId: flow2.id,
1027
2279
  stepId,
1028
2280
  attempt,
1029
- kind: "task",
1030
- output,
1031
- durationMs: Date.now() - startedAt,
1032
- at: clock.now()
1033
- };
1034
- await fireHook(def.onComplete, completeEvent, "step.onComplete", deps);
1035
- await fireHook(
1036
- deps.hooks?.onStepComplete,
1037
- completeEvent,
1038
- "onStepComplete",
1039
- deps
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
+ }
1040
2312
  );
1041
- await advance(deps, runId);
1042
- } else if (def.kind === "signal") {
1043
- await queue.ack(message.receipt);
1044
- return;
1045
- } else if (def.kind === "match") {
1046
- await executeMatch({ deps, message, def, runId, stepId, attempt });
1047
- await advance(deps, runId);
2313
+ return { output, skipAdvance: stepAbortedHere };
2314
+ } finally {
2315
+ watcher.stop();
1048
2316
  }
1049
- } catch (err) {
1050
- await handleStepError({
1051
- deps,
1052
- flow: flow2,
1053
- message,
1054
- def,
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(
1055
2342
  runId,
1056
- stepId,
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({
1057
2355
  attempt,
1058
- err
2356
+ policy,
2357
+ err,
2358
+ runIsCanceled: postState.phase.tag === "canceled",
2359
+ stepAborted: isAbortRequested(stepStateOf(postState, stepId), attempt)
1059
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
+ }
1060
2411
  }
2412
+ return { dispatchMessage };
1061
2413
  }
1062
- async function executeTask(args) {
1063
- const { deps, message, def, runId, stepId, attempt } = args;
1064
- if (def.kind !== "task") {
1065
- throw new Error(`executeTask called with non-task def (kind: ${def.kind})`);
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
+ }
1066
2455
  }
1067
- const { store, queue, clock } = deps;
1068
- const runState = await store.loadRunState(runId);
1069
- const input = extractInput(runState);
1070
- const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
1071
- const output = await store.runStep(
1072
- runId,
1073
- stepId,
1074
- attempt,
1075
- async (tx) => {
1076
- const ctx = makeStepCtx({
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,
2470
+ flowId: flow2.id,
2471
+ stepId,
2472
+ attempt,
2473
+ kind: stepKind,
2474
+ at
2475
+ };
2476
+ if (settlement.kind === "complete") {
2477
+ await deps.store.settleStep(
1077
2478
  runId,
1078
2479
  stepId,
1079
- attempt,
1080
- input,
1081
- store,
1082
- clock,
1083
- tx,
1084
- ...deps.logger !== void 0 ? { logger: deps.logger } : {}
1085
- });
1086
- const out = await def.run({ input, needs, ctx });
1087
- const fact = {
1088
- kind: "step.completed",
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
+ );
2487
+ } else {
2488
+ await deps.store.settleStep(
1089
2489
  runId,
1090
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({
2503
+ flow: flow2,
2504
+ runId: runState.runId,
2505
+ stepId: matchId,
1091
2506
  attempt,
1092
- output: out,
1093
- at: clock.now()
1094
- };
1095
- return { output: out, fact };
2507
+ stepKind: "match",
2508
+ settlement: result
2509
+ });
1096
2510
  }
1097
- );
1098
- await queue.ack(message.receipt);
1099
- return output;
1100
- }
1101
- async function executeMatch(args) {
1102
- const { deps, message, def, runId, stepId } = args;
1103
- const { store, queue, clock } = deps;
1104
- const runState = await store.loadRunState(runId);
1105
- const input = extractInput(runState);
1106
- const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
1107
- const armId = selectArm(def, { input, needs });
1108
- await store.appendFact(runId, {
1109
- kind: "match.arm-selected",
1110
- runId,
1111
- stepId,
1112
- arm: armId,
1113
- at: clock.now()
1114
- });
1115
- await queue.ack(message.receipt);
1116
- }
1117
- async function handleStepError(args) {
1118
- const { deps, flow: flow2, message, def, runId, stepId, attempt, err } = args;
1119
- const { store, queue, clock } = deps;
1120
- const error = serializeError(err);
1121
- const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY2;
1122
- const shouldRetry = attempt < policy.maxAttempts && retryAllows(policy, err);
1123
- if (shouldRetry) {
1124
- const delayMs = computeBackoff(policy, attempt);
1125
- await store.appendFact(runId, {
1126
- kind: "step.retried",
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(
1127
2525
  runId,
1128
- stepId,
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,
1129
2574
  attempt,
1130
- nextAttemptAt: new Date(Date.now() + delayMs),
1131
- at: clock.now()
2575
+ stepKind: "subflow",
2576
+ settlement: outcome.kind === "completed" ? { kind: "complete", output: { childRunId, output: outcome.output } } : { kind: "fail", error: outcome.error }
1132
2577
  });
1133
- const retryEvent = {
1134
- runId,
1135
- flowId: flow2.id,
1136
- stepId,
1137
- attempt,
1138
- kind: def.kind,
1139
- error,
1140
- nextAttemptAt: new Date(Date.now() + delayMs),
1141
- at: clock.now()
1142
- };
1143
- const stepOnRetry = def.kind === "task" ? def.onRetry : void 0;
1144
- await fireHook(stepOnRetry, retryEvent, "step.onRetry", deps);
1145
- await fireHook(deps.hooks?.onStepRetry, retryEvent, "onStepRetry", deps);
1146
- await queue.enqueue(runId, stepId, { attempt: attempt + 1, delayMs });
1147
- await queue.ack(message.receipt);
1148
- return;
2578
+ await advance(parentRunId);
1149
2579
  }
1150
- const fact = {
1151
- kind: "step.failed",
1152
- runId,
1153
- stepId,
1154
- attempt,
1155
- error,
1156
- at: clock.now()
1157
- };
1158
- await store.failStep(runId, stepId, error, fact);
1159
- const errorEvent = {
1160
- runId,
1161
- flowId: flow2.id,
1162
- stepId,
1163
- attempt,
1164
- kind: def.kind,
1165
- error,
1166
- at: clock.now()
2580
+ return { advance, propagateToParent };
2581
+ }
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);
2588
+ return {
2589
+ dispatchMessage: message.dispatchMessage,
2590
+ advance: progression.advance,
2591
+ propagateToParent: progression.propagateToParent
1167
2592
  };
1168
- const stepOnError = def.kind === "task" ? def.onError : void 0;
1169
- await fireHook(stepOnError, errorEvent, "step.onError", deps);
1170
- await fireHook(deps.hooks?.onStepError, errorEvent, "onStepError", deps);
1171
- await queue.ack(message.receipt);
1172
- await advance(deps, runId);
1173
2593
  }
1174
- var MAX_ADVANCE_ITERS = 1024;
1175
- async function advance(deps, runId) {
1176
- const { store, queue, clock } = deps;
1177
- const flow2 = await deps.flowFor(runId);
1178
- for (let iter = 0; iter < MAX_ADVANCE_ITERS; iter++) {
1179
- const runState = await store.loadRunState(runId);
1180
- const promoted = await promoteMatches({ deps, flow: flow2, runState });
1181
- if (promoted) continue;
1182
- const termination = flowTermination(flow2, runState);
1183
- if (termination.done) {
1184
- if (isFlowTerminal(runState.facts)) return;
1185
- if (termination.failed) {
1186
- const failedStep = Object.values(runState.steps).find(
1187
- (s) => s.status === "failed"
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
+ }
2612
+ return {
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().`
1188
2630
  );
1189
- const flowError = failedStep?.error ?? {
1190
- name: "Error",
1191
- message: "step failed"
1192
- };
1193
- await finalizeFlowFailure({ deps, flow: flow2, runId, error: flowError });
1194
- } else {
1195
- await finalizeFlowCompletion({ deps, flow: flow2, runId, runState });
1196
2631
  }
2632
+ return flow2;
2633
+ },
2634
+ isStreaming: (stepId) => streamingStepIds.has(stepId)
2635
+ };
2636
+ }
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
+ ]);
2646
+ }
2647
+ }
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
+ });
1197
2667
  return;
1198
2668
  }
1199
- const input = extractInput(runState);
1200
- const decision = nextRunnable({ flow: flow2, runState, input });
1201
- if (decision.skip.length === 0 && decision.runnable.length === 0) return;
1202
- for (const { stepId, reason } of decision.skip) {
1203
- await store.appendFact(runId, {
1204
- kind: "step.skipped",
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({
1205
2677
  runId,
1206
2678
  stepId,
1207
- reason,
1208
- at: clock.now()
1209
- });
2679
+ at: clock.now(),
2680
+ reason: "manual",
2681
+ actor: opts.actor,
2682
+ ...compact({ note: opts.note })
2683
+ })
2684
+ );
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));
1210
2697
  }
1211
- for (const stepId of decision.runnable) {
1212
- await queue.enqueue(runId, stepId);
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
+ );
1213
2709
  }
1214
- if (decision.runnable.length > 0) {
1215
- return;
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
+ );
1216
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 })
2758
+ });
1217
2759
  }
1218
- const cycleError = {
1219
- name: "NagiCycleError",
1220
- message: `advance exceeded ${MAX_ADVANCE_ITERS} iterations \u2014 likely a cycle or infinite skip loop in flow "${flow2.id}"`
1221
- };
1222
- const facts = (await store.loadRunState(runId)).facts;
1223
- if (!isFlowTerminal(facts)) {
1224
- await finalizeFlowFailure({ deps, flow: flow2, runId, error: cycleError });
1225
- }
2760
+ return { skip, retry, abort };
1226
2761
  }
1227
- async function promoteMatches(args) {
1228
- const { deps, flow: flow2, runState } = args;
1229
- const { store, clock } = deps;
1230
- let promoted = false;
1231
- for (const [matchId, step] of Object.entries(flow2.steps)) {
1232
- const def = getDef(step);
1233
- if (def.kind !== "match") continue;
1234
- const state = runState.steps[matchId];
1235
- if (state?.status !== "running") continue;
1236
- const agg = aggregateMatch(matchId, flow2, runState);
1237
- if (agg.kind === "pending") continue;
1238
- const attempt = state.attempts > 0 ? state.attempts : 1;
1239
- if (agg.kind === "fail-fast") {
1240
- const failedNested = runState.steps[agg.failedStepId];
1241
- const error = failedNested?.error ?? {
1242
- name: "Error",
1243
- message: `match "${matchId}": chosen-arm step "${agg.failedStepId}" failed`
1244
- };
1245
- const fact2 = {
1246
- kind: "step.failed",
1247
- runId: runState.runId,
1248
- stepId: matchId,
1249
- attempt,
1250
- error,
1251
- at: clock.now()
1252
- };
1253
- await store.failStep(runState.runId, matchId, error, fact2);
1254
- await fireHook(
1255
- deps.hooks?.onStepError,
1256
- {
1257
- runId: runState.runId,
1258
- flowId: flow2.id,
1259
- stepId: matchId,
1260
- attempt,
1261
- kind: "match",
1262
- error,
1263
- at: clock.now()
1264
- },
1265
- "onStepError",
1266
- deps
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.`
1267
2772
  );
1268
- promoted = true;
1269
- continue;
1270
2773
  }
1271
- const fact = {
1272
- kind: "step.completed",
1273
- runId: runState.runId,
1274
- stepId: matchId,
1275
- attempt,
1276
- output: agg.output,
1277
- at: clock.now()
1278
- };
1279
- await store.completeStep(runState.runId, matchId, agg.output, fact);
1280
- await fireHook(
1281
- deps.hooks?.onStepComplete,
1282
- {
1283
- runId: runState.runId,
1284
- flowId: flow2.id,
1285
- stepId: matchId,
1286
- attempt,
1287
- kind: "match",
1288
- output: agg.output,
1289
- durationMs: 0,
1290
- at: clock.now()
1291
- },
1292
- "onStepComplete",
1293
- deps
2774
+ synthesized[canonStep.id] = attachDef(
2775
+ { kind: canonStep.kind, id: canonStep.id },
2776
+ getDef(liveStep)
1294
2777
  );
1295
- promoted = true;
1296
2778
  }
1297
- return promoted;
1298
- }
1299
- function makeStepCtx(args) {
1300
- const { runId, stepId, attempt, input, store, clock, tx } = args;
1301
- const ac = new AbortController();
1302
- return {
1303
- input,
1304
- runId,
1305
- stepId,
1306
- attempt,
1307
- signal: ac.signal,
1308
- now: () => clock.now(),
1309
- // `tx` is supplied by `Store.runStep` — for adapters with no real
1310
- // transaction (in-memory) it is `undefined as Tx`, and handlers that
1311
- // touch `ctx.tx` will throw on the first call. Adapters that need
1312
- // typed transactional clients (e.g. `@nagi-js/postgres`) augment
1313
- // `Register.tx` and pass a real Kysely transaction here.
1314
- tx,
1315
- logger: args.logger ?? consoleLogger(),
1316
- once: makeOnce({ runId, stepId, store }),
1317
- idempotencyKey: makeIdempotencyKey(runId, stepId)
1318
- };
1319
- }
1320
- function consoleLogger() {
1321
- return {
1322
- debug: (m, a) => console.debug(m, a),
1323
- info: (m, a) => console.info(m, a),
1324
- warn: (m, a) => console.warn(m, a),
1325
- error: (m, a) => console.error(m, a)
1326
- };
1327
- }
1328
- function computeBackoff(policy, attempt) {
1329
- const initial = policy.initialDelayMs ?? 1e3;
1330
- const max = policy.maxDelayMs ?? 6e4;
1331
- switch (policy.backoff) {
1332
- case "exponential":
1333
- return Math.min(initial * 2 ** Math.max(0, attempt - 1), max);
1334
- case "linear":
1335
- return Math.min(initial * Math.max(1, attempt), max);
1336
- case "fixed":
1337
- return Math.min(initial, max);
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 });
1338
2793
  }
2794
+ return {
2795
+ id: liveFlow.id,
2796
+ input: liveFlow.input,
2797
+ steps: synthesized,
2798
+ ...compact({ output: liveFlow.output })
2799
+ };
1339
2800
  }
1340
- function retryAllows(policy, err) {
1341
- if (!policy.retryOn) return true;
1342
- return policy.retryOn(err);
1343
- }
1344
- function isFlowTerminal(facts) {
1345
- const last = facts[facts.length - 1];
1346
- return last !== void 0 && (last.kind === "flow.completed" || last.kind === "flow.failed");
1347
- }
1348
- async function finalizeFlowFailure(args) {
1349
- const { deps, flow: flow2, runId, error } = args;
1350
- const { store, clock } = deps;
1351
- await store.appendFact(runId, {
1352
- kind: "flow.failed",
1353
- runId,
1354
- error,
1355
- at: clock.now()
1356
- });
1357
- const event = { runId, flowId: flow2.id, error, at: clock.now() };
1358
- await fireHook(flow2.onError, event, "flow.onError", deps);
1359
- await fireHook(deps.hooks?.onFlowError, event, "onFlowError", deps);
1360
- }
1361
- async function finalizeFlowCompletion(args) {
1362
- const { deps, flow: flow2, runId, runState } = args;
1363
- const { store, clock } = deps;
1364
- const output = computeFlowOutput(flow2, runState);
1365
- await store.appendFact(runId, {
1366
- kind: "flow.completed",
1367
- runId,
1368
- output,
1369
- at: clock.now()
1370
- });
1371
- const event = { runId, flowId: flow2.id, output, at: clock.now() };
1372
- await fireHook(flow2.onComplete, event, "flow.onComplete", deps);
1373
- await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete", deps);
1374
- }
1375
- function computeFlowOutput(flow2, runState) {
1376
- if (flow2.output === void 0) return null;
1377
- const stepOutputs = {};
1378
- for (const [sid, sstate] of Object.entries(runState.steps)) {
1379
- if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
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);
1380
2865
  }
1381
- return flow2.output(stepOutputs);
2866
+ return { replay };
1382
2867
  }
1383
- function serializeError(err) {
1384
- if (err instanceof Error) {
1385
- return {
1386
- name: err.name,
1387
- message: err.message,
1388
- ...err.stack !== void 0 ? { stack: err.stack } : {}
1389
- };
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);
1390
2874
  }
1391
- return { name: "Error", message: String(err) };
1392
2875
  }
1393
2876
 
1394
2877
  // src/worker.ts
@@ -1403,12 +2886,14 @@ var WorkerImpl = class {
1403
2886
  this.concurrency = Math.max(1, config?.concurrency ?? DEFAULT_CONCURRENCY);
1404
2887
  this.pollIntervalMs = config?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
1405
2888
  this.signal = config?.signal;
2889
+ this.dispatcher = makeDispatcher(deps);
1406
2890
  }
1407
2891
  deps;
1408
2892
  inFlight = 0;
1409
2893
  concurrency;
1410
2894
  pollIntervalMs;
1411
2895
  signal;
2896
+ dispatcher;
1412
2897
  async run() {
1413
2898
  while (!this.aborted()) {
1414
2899
  const slots = this.concurrency - this.inFlight;
@@ -1427,24 +2912,22 @@ var WorkerImpl = class {
1427
2912
  }
1428
2913
  async runOnce(opts) {
1429
2914
  const limit = Math.max(1, opts?.maxSteps ?? this.concurrency);
1430
- let processed = 0;
1431
- while (processed < limit && !this.aborted()) {
1432
- const remaining = limit - processed;
1433
- const messages = await this.dequeue(
1434
- Math.min(remaining, this.concurrency)
1435
- );
1436
- if (messages.length === 0) break;
1437
- await Promise.all(messages.map((m) => this.dispatchSafely(m)));
1438
- processed += messages.length;
1439
- }
1440
- return { processed };
2915
+ return this.pump({
2916
+ shouldContinue: (processed) => processed < limit,
2917
+ batchSize: (processed) => Math.min(limit - processed, this.concurrency)
2918
+ });
1441
2919
  }
1442
2920
  async runUntilEmpty(opts) {
1443
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) {
1444
2928
  let processed = 0;
1445
- while (!this.aborted()) {
1446
- if (deadline !== void 0 && Date.now() >= deadline) break;
1447
- const messages = await this.dequeue(this.concurrency);
2929
+ while (!this.aborted() && opts.shouldContinue(processed)) {
2930
+ const messages = await this.dequeue(opts.batchSize(processed));
1448
2931
  if (messages.length === 0) break;
1449
2932
  await Promise.all(messages.map((m) => this.dispatchSafely(m)));
1450
2933
  processed += messages.length;
@@ -1462,10 +2945,12 @@ var WorkerImpl = class {
1462
2945
  }
1463
2946
  async dispatchSafely(msg) {
1464
2947
  try {
1465
- await dispatchMessage(this.deps, msg);
2948
+ await this.dispatcher.dispatchMessage(msg);
1466
2949
  } catch (err) {
1467
- this.deps.logger?.error("worker.dispatch threw uncaught", {
1468
- error: String(err)
2950
+ this.deps.emitLog({
2951
+ level: "error",
2952
+ msg: "worker.dispatch threw uncaught",
2953
+ attrs: { error: String(err) }
1469
2954
  });
1470
2955
  try {
1471
2956
  await this.deps.queue.nack(msg.receipt);
@@ -1490,45 +2975,24 @@ var WorkerImpl = class {
1490
2975
  };
1491
2976
 
1492
2977
  // src/runtime.ts
1493
- var NagiValidationError = class extends Error {
1494
- issues;
1495
- constructor(issues) {
1496
- super(issues.map((i) => i.message).join("; "));
1497
- this.name = "NagiValidationError";
1498
- this.issues = issues;
1499
- }
1500
- };
1501
- var NagiRuntimeError = class extends Error {
1502
- constructor(message) {
1503
- super(message);
1504
- this.name = "NagiRuntimeError";
1505
- }
1506
- };
1507
- var NagiSnapshotDriftError = class extends Error {
1508
- runId;
1509
- expected;
1510
- actual;
1511
- constructor(args) {
1512
- super(
1513
- `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.`
1514
- );
1515
- this.name = "NagiSnapshotDriftError";
1516
- this.runId = args.runId;
1517
- this.expected = args.expected;
1518
- this.actual = args.actual;
1519
- }
1520
- };
1521
- async function nagi(config) {
2978
+ async function nagiImpl(config) {
1522
2979
  const clock = config.clock ?? new InMemoryClock();
1523
- const flowsById = /* @__PURE__ */ new Map();
1524
- const flowHashById = /* @__PURE__ */ new Map();
1525
- for (const f of config.flows) {
1526
- if (flowsById.has(f.id)) {
1527
- throw new NagiRuntimeError(
1528
- `Duplicate flow id "${f.id}" passed to nagi()`
1529
- );
2980
+ const emitLog = makeEmit(config.onLog);
2981
+ await config.queue.ensureSchema?.();
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
+ }
1530
2992
  }
1531
- flowsById.set(f.id, f);
2993
+ }
2994
+ const flowHashById = /* @__PURE__ */ new Map();
2995
+ for (const f of registry.all) {
1532
2996
  const dag = await canonicalize(f);
1533
2997
  const flowHash = await sha256Canonical(dag);
1534
2998
  flowHashById.set(f.id, flowHash);
@@ -1540,49 +3004,210 @@ async function nagi(config) {
1540
3004
  const previousHash = await config.store.getRef(f.id);
1541
3005
  if (previousHash !== flowHash) {
1542
3006
  await config.store.setRef(f.id, flowHash);
1543
- await config.store.appendGlobalFact({
1544
- kind: "flow_ref.updated",
1545
- flowId: f.id,
1546
- from: previousHash,
1547
- to: flowHash,
1548
- at: clock.now()
1549
- });
3007
+ await config.store.appendGlobalFact(
3008
+ Facts.flowRefUpdated({
3009
+ flowId: f.id,
3010
+ from: previousHash,
3011
+ to: flowHash,
3012
+ at: clock.now()
3013
+ })
3014
+ );
1550
3015
  }
1551
3016
  }
3017
+ const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
1552
3018
  async function flowFor(runId) {
1553
3019
  const runState = await config.store.loadRunState(runId);
1554
- const flow2 = flowsById.get(runState.flowId);
1555
- if (!flow2) {
3020
+ return registry.requireForRun(runState.flowId, runId);
3021
+ }
3022
+ function lookupFlow(flowId) {
3023
+ return registry.get(flowId);
3024
+ }
3025
+ async function startRunInternal({
3026
+ flow: flow2,
3027
+ validatedInput,
3028
+ runId,
3029
+ parent
3030
+ }) {
3031
+ const startedAt = clock.now();
3032
+ const flowHash = flowHashById.get(flow2.id);
3033
+ const fact = Facts.flowStarted({
3034
+ runId,
3035
+ flowId: flow2.id,
3036
+ input: validatedInput,
3037
+ at: startedAt,
3038
+ codeVersion,
3039
+ ...compact({
3040
+ flowHash,
3041
+ parent: parent !== void 0 ? { runId: parent.runId, stepId: parent.stepId } : void 0
3042
+ })
3043
+ });
3044
+ let concurrencyArg;
3045
+ if (flow2.concurrency !== void 0) {
3046
+ const derived = flow2.concurrency.keyFn(validatedInput);
3047
+ if (typeof derived !== "string" || derived.length === 0) {
3048
+ throw validationError(
3049
+ `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
3050
+ ["concurrency", "keyFn"]
3051
+ );
3052
+ }
3053
+ concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
3054
+ }
3055
+ const { started, canceled } = await config.store.tryStartRun(
3056
+ runId,
3057
+ fact,
3058
+ concurrencyArg
3059
+ );
3060
+ if (!started) return { started: false };
3061
+ for (const c of canceled) {
3062
+ const cancelError = new NagiCanceledError({
3063
+ runId: c.runId,
3064
+ canceledByRunId: runId,
3065
+ concurrencyKey: c.fact.concurrencyKey
3066
+ });
3067
+ const serialized = {
3068
+ ...serializeError(cancelError),
3069
+ cause: {
3070
+ canceledByRunId: runId,
3071
+ concurrencyKey: c.fact.concurrencyKey
3072
+ }
3073
+ };
3074
+ const errorEvent = {
3075
+ runId: c.runId,
3076
+ flowId: flow2.id,
3077
+ error: serialized,
3078
+ at: c.fact.at
3079
+ };
3080
+ await hooks.fireHook(flow2.onError, errorEvent, "flow.onError");
3081
+ await hooks.fireHook(
3082
+ config.hooks?.onFlowError,
3083
+ errorEvent,
3084
+ "onFlowError"
3085
+ );
3086
+ await dispatcher.propagateToParent(c.runId, {
3087
+ kind: "canceled",
3088
+ error: serialized
3089
+ });
3090
+ }
3091
+ const startEvent = parent !== void 0 ? {
3092
+ runId,
3093
+ flowId: flow2.id,
3094
+ input: validatedInput,
3095
+ at: startedAt,
3096
+ parent
3097
+ } : {
3098
+ runId,
3099
+ flowId: flow2.id,
3100
+ input: validatedInput,
3101
+ at: startedAt
3102
+ };
3103
+ await hooks.fireHook(flow2.onStart, startEvent, "flow.onStart");
3104
+ await hooks.fireHook(config.hooks?.onFlowStart, startEvent, "onFlowStart");
3105
+ await dispatcher.advance(runId);
3106
+ return { started: true };
3107
+ }
3108
+ async function startChildRun(args) {
3109
+ const { child, childInput, parent } = args;
3110
+ if (!registry.has(child.id)) {
3111
+ throw new NagiRuntimeError(
3112
+ `Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
3113
+ );
3114
+ }
3115
+ const validated = await validate(child.input, childInput);
3116
+ const childRunId = mintRunId();
3117
+ const { started } = await startRunInternal({
3118
+ flow: child,
3119
+ validatedInput: validated,
3120
+ runId: childRunId,
3121
+ parent
3122
+ });
3123
+ if (!started) {
1556
3124
  throw new NagiRuntimeError(
1557
- `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
3125
+ `startChildRun: minted child runId collided with an existing run (${childRunId})`
1558
3126
  );
1559
3127
  }
1560
- return flow2;
3128
+ return childRunId;
3129
+ }
3130
+ async function cancelRunRecursive(runId, args) {
3131
+ const state = await config.store.loadRunState(runId);
3132
+ if (isTerminalRun(state)) {
3133
+ emitLog({
3134
+ level: "info",
3135
+ msg: "nagi: cancel skipped \u2014 run already terminal",
3136
+ attrs: { runId, status: runStatusOf(state) }
3137
+ });
3138
+ return;
3139
+ }
3140
+ const flow2 = registry.get(state.flowId);
3141
+ const canceledFact = Facts.flowCanceled(runId, args, clock.now());
3142
+ await config.store.appendFact(runId, canceledFact);
3143
+ const cancelError = {
3144
+ name: "NagiCanceledError",
3145
+ message: `Run ${runId} was canceled: ${args.reason}`
3146
+ };
3147
+ if (flow2 !== void 0) {
3148
+ const event = {
3149
+ runId,
3150
+ flowId: flow2.id,
3151
+ error: cancelError,
3152
+ at: clock.now()
3153
+ };
3154
+ await hooks.fireHook(flow2.onError, event, "flow.onError");
3155
+ await hooks.fireHook(config.hooks?.onFlowError, event, "onFlowError");
3156
+ }
3157
+ const children = await config.store.listChildren(runId);
3158
+ for (const childId of children) {
3159
+ await cancelRunRecursive(childId, {
3160
+ cause: "explicit",
3161
+ reason: `parent ${runId} canceled: ${args.reason}`,
3162
+ note: args.cause === "operator" ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
3163
+ });
3164
+ }
3165
+ await dispatcher.propagateToParent(runId, {
3166
+ kind: "canceled",
3167
+ error: cancelError
3168
+ });
1561
3169
  }
1562
3170
  const dispatchDeps = {
1563
3171
  flowFor,
3172
+ lookupFlow,
3173
+ startChildRun,
1564
3174
  store: config.store,
1565
3175
  queue: config.queue,
1566
3176
  clock,
1567
- ...config.hooks !== void 0 ? { hooks: config.hooks } : {},
1568
- ...config.logger !== void 0 ? { logger: config.logger } : {},
1569
- ...config.defaultRetry !== void 0 ? { defaultRetry: config.defaultRetry } : {}
3177
+ emitLog,
3178
+ ...compact({
3179
+ hooks: config.hooks,
3180
+ defaultRetry: config.defaultRetry,
3181
+ streamTransport
3182
+ })
1570
3183
  };
1571
- return {
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
+ });
3200
+ const wf = {
1572
3201
  async start(flow2, input, opts) {
1573
- if (!flowsById.has(flow2.id)) {
1574
- throw new NagiRuntimeError(
1575
- `Flow "${flow2.id}" not registered with nagi(). Pass it to flows[].`
1576
- );
1577
- }
3202
+ return wf.startById(flow2.id, input, opts);
3203
+ },
3204
+ async startById(flowId, input, opts) {
3205
+ const flow2 = registry.require(flowId);
1578
3206
  let runId;
1579
3207
  if (opts?.runId !== void 0) {
1580
3208
  if (typeof opts.runId !== "string" || opts.runId.length === 0) {
1581
- throw new NagiValidationError([
1582
- {
1583
- message: "opts.runId must be a non-empty string",
1584
- path: ["runId"]
1585
- }
3209
+ throw validationError("opts.runId must be a non-empty string", [
3210
+ "runId"
1586
3211
  ]);
1587
3212
  }
1588
3213
  runId = opts.runId;
@@ -1590,106 +3215,25 @@ async function nagi(config) {
1590
3215
  runId = mintRunId();
1591
3216
  }
1592
3217
  const validated = await validate(flow2.input, input);
1593
- const startedAt = clock.now();
1594
- const flowHash = flowHashById.get(flow2.id);
1595
- const fact = {
1596
- kind: "flow.started",
1597
- runId,
1598
- flowId: flow2.id,
1599
- input: validated,
1600
- at: startedAt,
1601
- ...flowHash !== void 0 ? { flowHash } : {},
1602
- ...config.codeVersion !== void 0 ? { codeVersion: config.codeVersion } : {}
1603
- };
1604
- const { started } = await config.store.tryStartRun(runId, fact);
1605
- if (!started) {
1606
- return runId;
1607
- }
1608
- const startEvent = {
1609
- runId,
1610
- flowId: flow2.id,
1611
- input: validated,
1612
- at: startedAt
1613
- };
1614
- await fireHook(
1615
- flow2.onStart,
1616
- startEvent,
1617
- "flow.onStart",
1618
- dispatchDeps
1619
- );
1620
- await fireHook(
1621
- config.hooks?.onFlowStart,
1622
- startEvent,
1623
- "onFlowStart",
1624
- dispatchDeps
1625
- );
1626
- await advance(dispatchDeps, runId);
3218
+ await startRunInternal({ flow: flow2, validatedInput: validated, runId });
1627
3219
  return runId;
1628
3220
  },
1629
- async signal(runId, stepName, payload) {
1630
- const runState = await config.store.loadRunState(runId);
1631
- const flow2 = flowsById.get(runState.flowId);
1632
- if (!flow2) {
1633
- throw new NagiRuntimeError(
1634
- `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
1635
- );
1636
- }
1637
- const step = flow2.steps[stepName];
1638
- if (!step) {
1639
- throw new NagiRuntimeError(
1640
- `Flow "${flow2.id}" has no step named "${stepName}".`
1641
- );
1642
- }
1643
- const def = getDef(step);
1644
- if (def.kind !== "signal") {
1645
- throw new NagiRuntimeError(
1646
- `Step "${stepName}" is a ${def.kind}, not a signal.`
1647
- );
1648
- }
1649
- const stepState = runState.steps[stepName];
1650
- if (stepState?.status !== "running") {
1651
- throw new NagiRuntimeError(
1652
- `Step "${stepName}" is not waiting for signal (status: ${stepState?.status ?? "pending"}).`
1653
- );
1654
- }
1655
- const validated = await validate(def.schema, payload);
1656
- const attempt = stepState.attempts > 0 ? stepState.attempts : 1;
1657
- await config.store.appendFact(runId, {
1658
- kind: "signal.received",
1659
- runId,
1660
- stepId: stepName,
1661
- payload: validated,
1662
- at: clock.now()
3221
+ signal: signals.signal,
3222
+ async cancel(runId, opts) {
3223
+ await cancelRunRecursive(runId, {
3224
+ cause: "explicit",
3225
+ reason: opts?.reason ?? "explicit wf.cancel()"
3226
+ });
3227
+ },
3228
+ operator() {
3229
+ return makeOperator({
3230
+ dispatcher,
3231
+ store: config.store,
3232
+ clock,
3233
+ registry,
3234
+ cancelRunRecursive,
3235
+ emitLog
1663
3236
  });
1664
- const completedFact = {
1665
- kind: "step.completed",
1666
- runId,
1667
- stepId: stepName,
1668
- attempt,
1669
- output: validated,
1670
- at: clock.now()
1671
- };
1672
- await config.store.completeStep(
1673
- runId,
1674
- stepName,
1675
- validated,
1676
- completedFact
1677
- );
1678
- await fireHook(
1679
- config.hooks?.onSignalReceived,
1680
- {
1681
- runId,
1682
- flowId: flow2.id,
1683
- stepId: stepName,
1684
- attempt,
1685
- kind: "signal",
1686
- payload: validated,
1687
- at: clock.now()
1688
- },
1689
- "onSignalReceived",
1690
- dispatchDeps
1691
- );
1692
- await advance(dispatchDeps, runId);
1693
3237
  },
1694
3238
  worker(workerConfig) {
1695
3239
  if (config.flows.length === 0) {
@@ -1699,107 +3243,111 @@ async function nagi(config) {
1699
3243
  }
1700
3244
  return makeWorker({ ...dispatchDeps, clock }, workerConfig);
1701
3245
  },
1702
- async replay(runId, opts = { mode: "continue" }) {
1703
- const runState = await config.store.loadRunState(runId);
1704
- const liveFlow = flowsById.get(runState.flowId);
1705
- if (!liveFlow) {
3246
+ replay: replayer.replay,
3247
+ async queryRuns(opts = {}) {
3248
+ if (opts.latest === true) {
3249
+ if (opts.limit !== void 0 || opts.cursor !== void 0) {
3250
+ throw validationError(
3251
+ "queryRuns: `latest: true` is incompatible with `limit` / `cursor` \u2014 `latest` returns at most one row.",
3252
+ ["latest"]
3253
+ );
3254
+ }
3255
+ }
3256
+ return config.store.queryRuns(opts);
3257
+ },
3258
+ subscribe(runId, stepId, opts) {
3259
+ if (!registry.isStreaming(stepId)) {
1706
3260
  throw new NagiRuntimeError(
1707
- `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
3261
+ `wf.subscribe: step "${stepId}" is not a streaming step (b.streamingTask) in any registered flow. Only streaming steps can be subscribed to.`
1708
3262
  );
1709
3263
  }
1710
- if (opts.mode === "inspect") return;
1711
- const fireHooks = opts.fireHooks !== false;
1712
- const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
1713
- let replayDeps = baseDeps;
1714
- const pinned = runState.flowHash;
1715
- if (pinned !== void 0) {
1716
- const liveHash = flowHashById.get(liveFlow.id);
1717
- if (liveHash !== void 0 && liveHash !== pinned) {
1718
- if (!opts.allowDrift) {
1719
- throw new NagiSnapshotDriftError({
1720
- runId,
1721
- expected: pinned,
1722
- actual: liveHash
1723
- });
1724
- }
1725
- const snapshot = await config.store.loadSnapshot(pinned);
1726
- if (snapshot === null) {
1727
- throw new NagiRuntimeError(
1728
- `Run ${runId} pinned to flow hash ${pinned.slice(0, 12)}\u2026 but no snapshot with that hash was found. Cannot replay with allowDrift.`
1729
- );
1730
- }
1731
- const synthesized = synthesizeReplayFlow(
1732
- snapshot.dag,
1733
- liveFlow
3264
+ return streamTransport.subscribeStream(
3265
+ runId,
3266
+ stepId,
3267
+ opts
3268
+ );
3269
+ },
3270
+ async pruneFacts(opts) {
3271
+ if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
3272
+ throw validationError("pruneFacts: `olderThan` must be a valid Date.", [
3273
+ "olderThan"
3274
+ ]);
3275
+ }
3276
+ const statuses = opts.statuses ?? [
3277
+ "completed"
3278
+ ];
3279
+ for (const s of statuses) {
3280
+ if (s !== "completed" && s !== "failed" && s !== "canceled") {
3281
+ throw validationError(
3282
+ `pruneFacts: status "${s}" is not prunable. Allowed: "completed" | "failed" | "canceled".`,
3283
+ ["statuses"]
1734
3284
  );
1735
- replayDeps = { ...baseDeps, flowFor: async () => synthesized };
1736
3285
  }
1737
3286
  }
1738
- await advance(replayDeps, runId);
1739
- if (!fireHooks) await drainInline(replayDeps);
3287
+ const batchSize = opts.batchSize ?? 1e3;
3288
+ if (!Number.isInteger(batchSize) || batchSize < 1) {
3289
+ throw validationError(
3290
+ "pruneFacts: `batchSize` must be a positive integer.",
3291
+ ["batchSize"]
3292
+ );
3293
+ }
3294
+ const keepSummary = opts.keepSummary ?? true;
3295
+ return config.store.pruneFacts({
3296
+ olderThan: opts.olderThan,
3297
+ statuses,
3298
+ batchSize,
3299
+ keepSummary
3300
+ });
1740
3301
  }
1741
3302
  };
3303
+ Object.defineProperty(wf, "__dispatchDeps", {
3304
+ value: dispatchDeps,
3305
+ enumerable: false,
3306
+ writable: false,
3307
+ configurable: false
3308
+ });
3309
+ return wf;
3310
+ }
3311
+ async function nagiRun(config) {
3312
+ const wf = await nagiImpl(config);
3313
+ const internal = new AbortController();
3314
+ const signal = config.signal ? AbortSignal.any([internal.signal, config.signal]) : internal.signal;
3315
+ const worker = wf.worker({ ...config.worker, signal });
3316
+ const emitLog = makeEmit(config.onLog);
3317
+ const loop = worker.run();
3318
+ loop.catch((err) => {
3319
+ if (signal.aborted) return;
3320
+ emitLog({
3321
+ level: "error",
3322
+ msg: "nagi.run: worker exited unexpectedly",
3323
+ attrs: { error: String(err) }
3324
+ });
3325
+ });
3326
+ let stopping;
3327
+ const stop = () => {
3328
+ stopping ??= (async () => {
3329
+ internal.abort();
3330
+ try {
3331
+ await loop;
3332
+ } catch {
3333
+ }
3334
+ })();
3335
+ return stopping;
3336
+ };
3337
+ return { wf, stop };
1742
3338
  }
3339
+ var nagi = Object.assign(
3340
+ nagiImpl,
3341
+ { run: nagiRun }
3342
+ );
1743
3343
  function mintRunId() {
1744
3344
  return `run-${crypto.randomUUID()}`;
1745
3345
  }
1746
- var MAX_REPLAY_DISPATCHES = 4096;
1747
- async function drainInline(deps) {
1748
- for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
1749
- const messages = await deps.queue.dequeue({ count: 1 });
1750
- if (messages.length === 0) return;
1751
- for (const msg of messages) await dispatchMessage(deps, msg);
1752
- }
1753
- }
1754
- async function validate(schema, value) {
1755
- const result = await schema["~standard"].validate(value);
1756
- if ("issues" in result && result.issues !== void 0) {
1757
- throw new NagiValidationError(result.issues);
1758
- }
1759
- return result.value;
1760
- }
1761
- function synthesizeReplayFlow(dag, liveFlow) {
1762
- const synthesized = {};
1763
- for (const canonStep of dag.steps) {
1764
- synthesized[canonStep.id] = attachDef(
1765
- { kind: canonStep.kind, id: canonStep.id },
1766
- { kind: canonStep.kind }
1767
- );
1768
- }
1769
- for (const canonStep of dag.steps) {
1770
- const liveStep = liveFlow.steps[canonStep.id];
1771
- if (liveStep === void 0) {
1772
- throw new NagiRuntimeError(
1773
- `Drift-allowed replay: step "${canonStep.id}" exists in snapshot but is missing from the live flow "${liveFlow.id}". Cannot synthesize a handler.`
1774
- );
1775
- }
1776
- const liveDef = getDef(liveStep);
1777
- const synthesizedNeeds = {};
1778
- for (const upstreamId of canonStep.needs) {
1779
- const upstreamShell = synthesized[upstreamId];
1780
- if (upstreamShell === void 0) {
1781
- throw new NagiRuntimeError(
1782
- `Drift-allowed replay: step "${canonStep.id}" needs upstream "${upstreamId}" which the snapshot does not declare.`
1783
- );
1784
- }
1785
- synthesizedNeeds[upstreamId] = upstreamShell;
1786
- }
1787
- const rewiredDef = {
1788
- ...liveDef,
1789
- needs: synthesizedNeeds
1790
- };
1791
- const shell = synthesized[canonStep.id];
1792
- if (shell === void 0) continue;
1793
- shell.__def = rewiredDef;
1794
- }
1795
- return {
1796
- id: liveFlow.id,
1797
- input: liveFlow.input,
1798
- steps: synthesized,
1799
- ...liveFlow.output !== void 0 ? { output: liveFlow.output } : {}
1800
- };
3346
+ function asStreamTransport(store) {
3347
+ const s = store;
3348
+ return typeof s.subscribeStream === "function" && typeof s.publishChunk === "function" ? s : void 0;
1801
3349
  }
1802
3350
 
1803
- export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, 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 };
1804
3352
  //# sourceMappingURL=index.js.map
1805
3353
  //# sourceMappingURL=index.js.map