@nagi-js/core 0.1.0 → 0.1.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,6 +3,9 @@ var DEF = "__def";
3
3
  function attachDef(meta, def) {
4
4
  return { kind: meta.kind, id: meta.id, [DEF]: def };
5
5
  }
6
+ function attachDefMut(step, def) {
7
+ step[DEF] = def;
8
+ }
6
9
  function getDef(step) {
7
10
  const def = step[DEF];
8
11
  if (def === void 0) {
@@ -12,6 +15,15 @@ function getDef(step) {
12
15
  }
13
16
  return def;
14
17
  }
18
+ 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;
26
+ }
15
27
  function resolveNeeds(def, loadOutput) {
16
28
  const result = {};
17
29
  for (const [localKey, upstream] of Object.entries(def.needs)) {
@@ -21,6 +33,9 @@ function resolveNeeds(def, loadOutput) {
21
33
  }
22
34
  return result;
23
35
  }
36
+ function matchArms(def) {
37
+ return def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
38
+ }
24
39
  function readSelectedArm(matchId, runState) {
25
40
  for (const fact of runState.facts) {
26
41
  if (fact.kind === "match.arm-selected" && fact.stepId === matchId) {
@@ -50,20 +65,37 @@ function selectArm(def, args) {
50
65
  }
51
66
 
52
67
  // 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
+ }
53
78
  function isDiscriminator(config) {
54
79
  return "cases" in config && "on" in config;
55
80
  }
56
81
  function makeBuilder() {
82
+ const chainSteps = /* @__PURE__ */ new Map();
57
83
  function task(config) {
58
84
  const def = {
59
85
  kind: "task",
60
86
  needs: config.needs ?? {},
61
87
  ...config.retry !== void 0 ? { retry: config.retry } : {},
62
- ...config.timeout !== void 0 ? { timeout: config.timeout } : {},
88
+ ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
63
89
  ...config.when !== void 0 ? {
64
90
  when: config.when
65
91
  } : {},
66
- run: config.run
92
+ 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 } : {}
67
99
  };
68
100
  return attachDef({ kind: "task", id: "" }, def);
69
101
  }
@@ -72,7 +104,7 @@ function makeBuilder() {
72
104
  kind: "signal",
73
105
  needs: config.needs ?? {},
74
106
  schema: config.schema,
75
- ...config.timeout !== void 0 ? { timeout: config.timeout } : {},
107
+ ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
76
108
  ...config.when !== void 0 ? {
77
109
  when: config.when
78
110
  } : {}
@@ -84,8 +116,8 @@ function makeBuilder() {
84
116
  if (isDiscriminator(config)) {
85
117
  const arms2 = {};
86
118
  for (const [caseKey, build] of Object.entries(config.cases)) {
87
- const nested = build(
88
- makeBuilder()
119
+ const nested = resolveBuildResult(
120
+ build(makeBuilder())
89
121
  );
90
122
  arms2[caseKey] = { id: caseKey, stepIds: [], _nested: nested };
91
123
  }
@@ -102,7 +134,7 @@ function makeBuilder() {
102
134
  const arms = [];
103
135
  for (let i = 0; i < guardConfig.arms.length; i++) {
104
136
  const arm = guardConfig.arms[i];
105
- const nested = arm.build(makeBuilder());
137
+ const nested = resolveBuildResult(arm.build(makeBuilder()));
106
138
  const armId = arm.otherwise ? "otherwise" : `arm${i}`;
107
139
  arms.push({
108
140
  id: armId,
@@ -122,11 +154,68 @@ function makeBuilder() {
122
154
  };
123
155
  return attachDef({ kind: "match", id: "" }, def);
124
156
  }
125
- return { task, signal, match };
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
+ }
176
+ 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 ? {
182
+ 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 } : {}
191
+ };
192
+ attachDefMut(shell, def);
193
+ chainSteps.set(key, shell);
194
+ return builder;
195
+ }
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
+ );
201
+ }
202
+ chainSteps.set(key, s);
203
+ return builder;
204
+ }
205
+ const builder = {
206
+ task,
207
+ signal,
208
+ match,
209
+ step,
210
+ include,
211
+ [BUILDER_BRAND]: true,
212
+ __steps: chainSteps
213
+ };
214
+ return builder;
126
215
  }
127
216
  function flow(config) {
128
217
  const builder = makeBuilder();
129
- const built = config.build(builder);
218
+ const built = resolveBuildResult(config.build(builder));
130
219
  const idByIdentity = /* @__PURE__ */ new Map();
131
220
  collectIds(built, "", idByIdentity);
132
221
  const finalSteps = {};
@@ -142,7 +231,12 @@ function flow(config) {
142
231
  id: config.id,
143
232
  input: config.input,
144
233
  steps: finalSteps,
145
- ...config.output !== void 0 ? { output: config.output } : {}
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 } : {}
146
240
  };
147
241
  }
148
242
  function collectIds(map, prefix, idByIdentity) {
@@ -234,6 +328,235 @@ function walkAndRewrite(args) {
234
328
  }
235
329
  }
236
330
 
331
+ // src/canonicalize.ts
332
+ var DEFAULT_RETRY = {
333
+ initialDelayMs: 1e3,
334
+ maxDelayMs: 6e4
335
+ };
336
+ var warnedAboutSourceHash = false;
337
+ function warnSourceHashOnce() {
338
+ if (warnedAboutSourceHash) return;
339
+ warnedAboutSourceHash = true;
340
+ 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."
342
+ );
343
+ }
344
+ async function canonicalize(flow2) {
345
+ const ids = Object.keys(flow2.steps).sort();
346
+ const steps = [];
347
+ for (const id of ids) {
348
+ const step = flow2.steps[id];
349
+ if (step === void 0) continue;
350
+ steps.push(await canonicalizeStep(id, getDef(step)));
351
+ }
352
+ return {
353
+ flowId: flow2.id,
354
+ inputSchema: await canonicalizeSchema(flow2.input),
355
+ steps
356
+ };
357
+ }
358
+ async function canonicalizeStep(id, def) {
359
+ const needs = [...needsStepIds(def)].sort();
360
+ const base = { id, kind: def.kind, needs };
361
+ if (def.kind === "task") return canonicalizeTask(base, def);
362
+ if (def.kind === "signal") return canonicalizeSignal(base, def);
363
+ return canonicalizeMatch(base, def);
364
+ }
365
+ async function canonicalizeTask(base, def) {
366
+ const out = { ...base };
367
+ if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
368
+ if (def.retry !== void 0) out.retry = normalizeRetry(def.retry);
369
+ if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
370
+ return out;
371
+ }
372
+ async function canonicalizeSignal(base, def) {
373
+ 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;
376
+ out.signalSchema = await canonicalizeSchema(def.schema);
377
+ return out;
378
+ }
379
+ async function canonicalizeMatch(base, def) {
380
+ const out = { ...base };
381
+ out.matchMode = def.mode;
382
+ if (def.mode === "discriminator") {
383
+ out.matchOnHash = await hashFnSource(def.on);
384
+ }
385
+ const arms = [];
386
+ for (const arm of matchArms(def)) {
387
+ arms.push(await canonicalizeArm(arm));
388
+ }
389
+ out.matchArms = arms;
390
+ return out;
391
+ }
392
+ async function canonicalizeArm(arm) {
393
+ const out = {
394
+ id: arm.id,
395
+ stepIds: [...arm.stepIds].sort()
396
+ };
397
+ if (arm.otherwise) out.otherwise = true;
398
+ if (arm.when !== void 0) out.whenHash = await hashFnSource(arm.when);
399
+ return out;
400
+ }
401
+ function normalizeRetry(retry) {
402
+ return {
403
+ maxAttempts: retry.maxAttempts,
404
+ backoff: retry.backoff,
405
+ initialDelayMs: retry.initialDelayMs ?? DEFAULT_RETRY.initialDelayMs,
406
+ maxDelayMs: retry.maxDelayMs ?? DEFAULT_RETRY.maxDelayMs
407
+ };
408
+ }
409
+ async function canonicalizeSchema(schema) {
410
+ const props = schema["~standard"];
411
+ return {
412
+ vendor: props.vendor,
413
+ version: props.version,
414
+ validateHash: await hashFnSource(props.validate)
415
+ };
416
+ }
417
+ async function hashFnSource(fn) {
418
+ warnSourceHashOnce();
419
+ return sha256Hex(fn.toString());
420
+ }
421
+ async function sha256Canonical(dag) {
422
+ return sha256Hex(stableStringify(dag));
423
+ }
424
+ function stableStringify(value) {
425
+ if (value === void 0) return "null";
426
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
427
+ if (Array.isArray(value)) {
428
+ return `[${value.map(stableStringify).join(",")}]`;
429
+ }
430
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
431
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
432
+ }
433
+ async function sha256Hex(input) {
434
+ const bytes = new TextEncoder().encode(input);
435
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
436
+ return hex(new Uint8Array(digest));
437
+ }
438
+ function hex(bytes) {
439
+ let s = "";
440
+ for (let i = 0; i < bytes.length; i++) {
441
+ s += bytes[i].toString(16).padStart(2, "0");
442
+ }
443
+ return s;
444
+ }
445
+
446
+ // src/diff.ts
447
+ function diffSnapshots(before, after) {
448
+ const beforeStepsById = new Map(before.steps.map((s) => [s.id, s]));
449
+ const afterStepsById = new Map(after.steps.map((s) => [s.id, s]));
450
+ const addedSteps = [];
451
+ const removedSteps = [];
452
+ for (const id of afterStepsById.keys()) {
453
+ if (!beforeStepsById.has(id)) addedSteps.push(id);
454
+ }
455
+ for (const id of beforeStepsById.keys()) {
456
+ if (!afterStepsById.has(id)) removedSteps.push(id);
457
+ }
458
+ addedSteps.sort();
459
+ removedSteps.sort();
460
+ const changedEdges = [];
461
+ const changedPredicates = [];
462
+ for (const id of afterStepsById.keys()) {
463
+ const beforeStep = beforeStepsById.get(id);
464
+ const afterStep = afterStepsById.get(id);
465
+ if (beforeStep === void 0 || afterStep === void 0) continue;
466
+ diffEdges(id, beforeStep, afterStep, changedEdges);
467
+ diffFields(beforeStep, afterStep, changedPredicates);
468
+ }
469
+ changedEdges.sort(
470
+ (a, b) => a.to !== b.to ? cmp(a.to, b.to) : cmp(a.from, b.from)
471
+ );
472
+ changedPredicates.sort(
473
+ (a, b) => a.stepId !== b.stepId ? cmp(a.stepId, b.stepId) : cmp(a.field, b.field)
474
+ );
475
+ return { addedSteps, removedSteps, changedEdges, changedPredicates };
476
+ }
477
+ function diffEdges(stepId, before, after, out) {
478
+ const beforeSet = new Set(before.needs);
479
+ const afterSet = new Set(after.needs);
480
+ for (const upstream of afterSet) {
481
+ if (!beforeSet.has(upstream)) {
482
+ out.push({
483
+ from: upstream,
484
+ to: stepId,
485
+ before: "absent",
486
+ after: "needed"
487
+ });
488
+ }
489
+ }
490
+ for (const upstream of beforeSet) {
491
+ if (!afterSet.has(upstream)) {
492
+ out.push({
493
+ from: upstream,
494
+ to: stepId,
495
+ before: "needed",
496
+ after: "absent"
497
+ });
498
+ }
499
+ }
500
+ }
501
+ function diffFields(before, after, out) {
502
+ const id = after.id;
503
+ if (before.kind !== after.kind) {
504
+ out.push({ stepId: id, field: "kind" });
505
+ }
506
+ if (before.whenHash !== after.whenHash) {
507
+ out.push({ stepId: id, field: "when" });
508
+ }
509
+ if (!retryEq(before.retry, after.retry)) {
510
+ out.push({ stepId: id, field: "retry" });
511
+ }
512
+ if (before.timeoutMs !== after.timeoutMs) {
513
+ out.push({ stepId: id, field: "timeoutMs" });
514
+ }
515
+ if (!schemaEq(before.signalSchema, after.signalSchema)) {
516
+ out.push({ stepId: id, field: "signalSchema" });
517
+ }
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
+ if (!armsEq(before.matchArms, after.matchArms)) {
525
+ out.push({ stepId: id, field: "matchArms" });
526
+ }
527
+ }
528
+ function retryEq(a, b) {
529
+ if (a === b) return true;
530
+ if (a === void 0 || b === void 0) return false;
531
+ return a.maxAttempts === b.maxAttempts && a.backoff === b.backoff && a.initialDelayMs === b.initialDelayMs && a.maxDelayMs === b.maxDelayMs;
532
+ }
533
+ function schemaEq(a, b) {
534
+ if (a === b) return true;
535
+ if (a === void 0 || b === void 0) return false;
536
+ return a.vendor === b.vendor && a.version === b.version && a.validateHash === b.validateHash;
537
+ }
538
+ function armsEq(a, b) {
539
+ if (a === b) return true;
540
+ if (a === void 0 || b === void 0) return false;
541
+ if (a.length !== b.length) return false;
542
+ for (let i = 0; i < a.length; i++) {
543
+ const x = a[i];
544
+ const y = b[i];
545
+ if (x === void 0 || y === void 0) return false;
546
+ if (x.id !== y.id) return false;
547
+ if (x.otherwise !== y.otherwise) return false;
548
+ if (x.whenHash !== y.whenHash) return false;
549
+ if (x.stepIds.length !== y.stepIds.length) return false;
550
+ for (let j = 0; j < x.stepIds.length; j++) {
551
+ if (x.stepIds[j] !== y.stepIds[j]) return false;
552
+ }
553
+ }
554
+ return true;
555
+ }
556
+ function cmp(a, b) {
557
+ return a < b ? -1 : a > b ? 1 : 0;
558
+ }
559
+
237
560
  // src/memory.ts
238
561
  var DEFAULT_STORE_LEASE_MS = 6e4;
239
562
  var InMemoryStore = class {
@@ -241,6 +564,9 @@ var InMemoryStore = class {
241
564
  outputs = /* @__PURE__ */ new Map();
242
565
  onces = /* @__PURE__ */ new Map();
243
566
  leases = /* @__PURE__ */ new Map();
567
+ snapshots = /* @__PURE__ */ new Map();
568
+ refs = /* @__PURE__ */ new Map();
569
+ globalFacts = [];
244
570
  leaseMs;
245
571
  constructor(opts = {}) {
246
572
  this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
@@ -296,16 +622,40 @@ var InMemoryStore = class {
296
622
  }
297
623
  return result.output;
298
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);
634
+ }
635
+ async loadSnapshot(flowHash) {
636
+ return this.snapshots.get(flowHash) ?? null;
637
+ }
638
+ async appendGlobalFact(fact) {
639
+ this.globalFacts.push(fact);
640
+ }
641
+ /** Test-only: peek at the in-memory global fact log. */
642
+ readGlobalFacts() {
643
+ return this.globalFacts;
644
+ }
299
645
  };
300
646
  function projectRunState(runId, facts) {
301
647
  let flowId = "";
302
648
  let status = "pending";
649
+ let flowHash;
650
+ let codeVersion;
303
651
  const steps = {};
304
652
  for (const fact of facts) {
305
653
  switch (fact.kind) {
306
654
  case "flow.started":
307
655
  flowId = fact.flowId;
308
656
  status = "running";
657
+ flowHash = fact.flowHash;
658
+ codeVersion = fact.codeVersion;
309
659
  break;
310
660
  case "flow.completed":
311
661
  status = "completed";
@@ -345,7 +695,15 @@ function projectRunState(runId, facts) {
345
695
  break;
346
696
  }
347
697
  }
348
- return { runId, flowId, status, steps, facts };
698
+ return {
699
+ runId,
700
+ flowId,
701
+ status,
702
+ steps,
703
+ facts,
704
+ ...flowHash !== void 0 ? { flowHash } : {},
705
+ ...codeVersion !== void 0 ? { codeVersion } : {}
706
+ };
349
707
  }
350
708
  var DEFAULT_QUEUE_LEASE_MS = 6e4;
351
709
  var InMemoryQueue = class {
@@ -589,7 +947,20 @@ function extractInput(runState) {
589
947
  }
590
948
 
591
949
  // src/dispatch.ts
592
- var DEFAULT_RETRY = {
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
+ });
961
+ }
962
+ }
963
+ var DEFAULT_RETRY2 = {
593
964
  maxAttempts: 3,
594
965
  backoff: "exponential",
595
966
  initialDelayMs: 1e3,
@@ -627,7 +998,7 @@ async function dispatchMessage(deps, message) {
627
998
  at: clock.now()
628
999
  });
629
1000
  const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
630
- await deps.hooks?.onStepStart?.({
1001
+ const startEvent = {
631
1002
  runId,
632
1003
  flowId: flow2.id,
633
1004
  stepId,
@@ -635,7 +1006,10 @@ async function dispatchMessage(deps, message) {
635
1006
  kind: def.kind,
636
1007
  input: startEventInput,
637
1008
  at: clock.now()
638
- });
1009
+ };
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);
639
1013
  const startedAt = Date.now();
640
1014
  try {
641
1015
  if (def.kind === "task") {
@@ -647,7 +1021,7 @@ async function dispatchMessage(deps, message) {
647
1021
  stepId,
648
1022
  attempt
649
1023
  });
650
- await deps.hooks?.onStepComplete?.({
1024
+ const completeEvent = {
651
1025
  runId,
652
1026
  flowId: flow2.id,
653
1027
  stepId,
@@ -656,7 +1030,14 @@ async function dispatchMessage(deps, message) {
656
1030
  output,
657
1031
  durationMs: Date.now() - startedAt,
658
1032
  at: clock.now()
659
- });
1033
+ };
1034
+ await fireHook(def.onComplete, completeEvent, "step.onComplete", deps);
1035
+ await fireHook(
1036
+ deps.hooks?.onStepComplete,
1037
+ completeEvent,
1038
+ "onStepComplete",
1039
+ deps
1040
+ );
660
1041
  await advance(deps, runId);
661
1042
  } else if (def.kind === "signal") {
662
1043
  await queue.ack(message.receipt);
@@ -737,7 +1118,7 @@ async function handleStepError(args) {
737
1118
  const { deps, flow: flow2, message, def, runId, stepId, attempt, err } = args;
738
1119
  const { store, queue, clock } = deps;
739
1120
  const error = serializeError(err);
740
- const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY;
1121
+ const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY2;
741
1122
  const shouldRetry = attempt < policy.maxAttempts && retryAllows(policy, err);
742
1123
  if (shouldRetry) {
743
1124
  const delayMs = computeBackoff(policy, attempt);
@@ -749,7 +1130,7 @@ async function handleStepError(args) {
749
1130
  nextAttemptAt: new Date(Date.now() + delayMs),
750
1131
  at: clock.now()
751
1132
  });
752
- await deps.hooks?.onStepRetry?.({
1133
+ const retryEvent = {
753
1134
  runId,
754
1135
  flowId: flow2.id,
755
1136
  stepId,
@@ -758,7 +1139,10 @@ async function handleStepError(args) {
758
1139
  error,
759
1140
  nextAttemptAt: new Date(Date.now() + delayMs),
760
1141
  at: clock.now()
761
- });
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);
762
1146
  await queue.enqueue(runId, stepId, { attempt: attempt + 1, delayMs });
763
1147
  await queue.ack(message.receipt);
764
1148
  return;
@@ -772,7 +1156,7 @@ async function handleStepError(args) {
772
1156
  at: clock.now()
773
1157
  };
774
1158
  await store.failStep(runId, stepId, error, fact);
775
- await deps.hooks?.onStepError?.({
1159
+ const errorEvent = {
776
1160
  runId,
777
1161
  flowId: flow2.id,
778
1162
  stepId,
@@ -780,7 +1164,10 @@ async function handleStepError(args) {
780
1164
  kind: def.kind,
781
1165
  error,
782
1166
  at: clock.now()
783
- });
1167
+ };
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);
784
1171
  await queue.ack(message.receipt);
785
1172
  await advance(deps, runId);
786
1173
  }
@@ -794,53 +1181,18 @@ async function advance(deps, runId) {
794
1181
  if (promoted) continue;
795
1182
  const termination = flowTermination(flow2, runState);
796
1183
  if (termination.done) {
797
- const last2 = runState.facts[runState.facts.length - 1];
798
- const flowAlreadyTerminal = last2 !== void 0 && (last2.kind === "flow.completed" || last2.kind === "flow.failed");
799
- if (!flowAlreadyTerminal) {
800
- if (termination.failed) {
801
- const failedStep = Object.values(runState.steps).find(
802
- (s) => s.status === "failed"
803
- );
804
- await store.appendFact(runId, {
805
- kind: "flow.failed",
806
- runId,
807
- error: failedStep?.error ?? {
808
- name: "Error",
809
- message: "step failed"
810
- },
811
- at: clock.now()
812
- });
813
- await deps.hooks?.onFlowError?.({
814
- runId,
815
- flowId: flow2.id,
816
- error: failedStep?.error ?? {
817
- name: "Error",
818
- message: "step failed"
819
- },
820
- at: clock.now()
821
- });
822
- } else {
823
- let flowOutput = null;
824
- if (flow2.output !== void 0) {
825
- const stepOutputs = {};
826
- for (const [sid, sstate] of Object.entries(runState.steps)) {
827
- if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
828
- }
829
- flowOutput = flow2.output(stepOutputs);
830
- }
831
- await store.appendFact(runId, {
832
- kind: "flow.completed",
833
- runId,
834
- output: flowOutput,
835
- at: clock.now()
836
- });
837
- await deps.hooks?.onFlowComplete?.({
838
- runId,
839
- flowId: flow2.id,
840
- output: flowOutput,
841
- at: clock.now()
842
- });
843
- }
1184
+ if (isFlowTerminal(runState.facts)) return;
1185
+ if (termination.failed) {
1186
+ const failedStep = Object.values(runState.steps).find(
1187
+ (s) => s.status === "failed"
1188
+ );
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 });
844
1196
  }
845
1197
  return;
846
1198
  }
@@ -867,21 +1219,9 @@ async function advance(deps, runId) {
867
1219
  name: "NagiCycleError",
868
1220
  message: `advance exceeded ${MAX_ADVANCE_ITERS} iterations \u2014 likely a cycle or infinite skip loop in flow "${flow2.id}"`
869
1221
  };
870
- const last = (await store.loadRunState(runId)).facts.slice(-1)[0];
871
- const alreadyTerminal = last !== void 0 && (last.kind === "flow.completed" || last.kind === "flow.failed");
872
- if (!alreadyTerminal) {
873
- await store.appendFact(runId, {
874
- kind: "flow.failed",
875
- runId,
876
- error: cycleError,
877
- at: clock.now()
878
- });
879
- await deps.hooks?.onFlowError?.({
880
- runId,
881
- flowId: flow2.id,
882
- error: cycleError,
883
- at: clock.now()
884
- });
1222
+ const facts = (await store.loadRunState(runId)).facts;
1223
+ if (!isFlowTerminal(facts)) {
1224
+ await finalizeFlowFailure({ deps, flow: flow2, runId, error: cycleError });
885
1225
  }
886
1226
  }
887
1227
  async function promoteMatches(args) {
@@ -911,15 +1251,20 @@ async function promoteMatches(args) {
911
1251
  at: clock.now()
912
1252
  };
913
1253
  await store.failStep(runState.runId, matchId, error, fact2);
914
- await deps.hooks?.onStepError?.({
915
- runId: runState.runId,
916
- flowId: flow2.id,
917
- stepId: matchId,
918
- attempt,
919
- kind: "match",
920
- error,
921
- at: clock.now()
922
- });
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
1267
+ );
923
1268
  promoted = true;
924
1269
  continue;
925
1270
  }
@@ -932,16 +1277,21 @@ async function promoteMatches(args) {
932
1277
  at: clock.now()
933
1278
  };
934
1279
  await store.completeStep(runState.runId, matchId, agg.output, fact);
935
- await deps.hooks?.onStepComplete?.({
936
- runId: runState.runId,
937
- flowId: flow2.id,
938
- stepId: matchId,
939
- attempt,
940
- kind: "match",
941
- output: agg.output,
942
- durationMs: 0,
943
- at: clock.now()
944
- });
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
1294
+ );
945
1295
  promoted = true;
946
1296
  }
947
1297
  return promoted;
@@ -991,6 +1341,45 @@ function retryAllows(policy, err) {
991
1341
  if (!policy.retryOn) return true;
992
1342
  return policy.retryOn(err);
993
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;
1380
+ }
1381
+ return flow2.output(stepOutputs);
1382
+ }
994
1383
  function serializeError(err) {
995
1384
  if (err instanceof Error) {
996
1385
  return {
@@ -1115,9 +1504,24 @@ var NagiRuntimeError = class extends Error {
1115
1504
  this.name = "NagiRuntimeError";
1116
1505
  }
1117
1506
  };
1118
- function nagi(config) {
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) {
1119
1522
  const clock = config.clock ?? new InMemoryClock();
1120
1523
  const flowsById = /* @__PURE__ */ new Map();
1524
+ const flowHashById = /* @__PURE__ */ new Map();
1121
1525
  for (const f of config.flows) {
1122
1526
  if (flowsById.has(f.id)) {
1123
1527
  throw new NagiRuntimeError(
@@ -1125,6 +1529,25 @@ function nagi(config) {
1125
1529
  );
1126
1530
  }
1127
1531
  flowsById.set(f.id, f);
1532
+ const dag = await canonicalize(f);
1533
+ const flowHash = await sha256Canonical(dag);
1534
+ flowHashById.set(f.id, flowHash);
1535
+ await config.store.upsertSnapshot({
1536
+ flowHash,
1537
+ flowId: f.id,
1538
+ dag
1539
+ });
1540
+ const previousHash = await config.store.getRef(f.id);
1541
+ if (previousHash !== flowHash) {
1542
+ 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
+ });
1550
+ }
1128
1551
  }
1129
1552
  async function flowFor(runId) {
1130
1553
  const runState = await config.store.loadRunState(runId);
@@ -1168,23 +1591,38 @@ function nagi(config) {
1168
1591
  }
1169
1592
  const validated = await validate(flow2.input, input);
1170
1593
  const startedAt = clock.now();
1594
+ const flowHash = flowHashById.get(flow2.id);
1171
1595
  const fact = {
1172
1596
  kind: "flow.started",
1173
1597
  runId,
1174
1598
  flowId: flow2.id,
1175
1599
  input: validated,
1176
- at: startedAt
1600
+ at: startedAt,
1601
+ ...flowHash !== void 0 ? { flowHash } : {},
1602
+ ...config.codeVersion !== void 0 ? { codeVersion: config.codeVersion } : {}
1177
1603
  };
1178
1604
  const { started } = await config.store.tryStartRun(runId, fact);
1179
1605
  if (!started) {
1180
1606
  return runId;
1181
1607
  }
1182
- await config.hooks?.onFlowStart?.({
1608
+ const startEvent = {
1183
1609
  runId,
1184
1610
  flowId: flow2.id,
1185
1611
  input: validated,
1186
1612
  at: startedAt
1187
- });
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
+ );
1188
1626
  await advance(dispatchDeps, runId);
1189
1627
  return runId;
1190
1628
  },
@@ -1237,15 +1675,20 @@ function nagi(config) {
1237
1675
  validated,
1238
1676
  completedFact
1239
1677
  );
1240
- await config.hooks?.onSignalReceived?.({
1241
- runId,
1242
- flowId: flow2.id,
1243
- stepId: stepName,
1244
- attempt,
1245
- kind: "signal",
1246
- payload: validated,
1247
- at: clock.now()
1248
- });
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
+ );
1249
1692
  await advance(dispatchDeps, runId);
1250
1693
  },
1251
1694
  worker(workerConfig) {
@@ -1258,20 +1701,56 @@ function nagi(config) {
1258
1701
  },
1259
1702
  async replay(runId, opts = { mode: "continue" }) {
1260
1703
  const runState = await config.store.loadRunState(runId);
1261
- const flow2 = flowsById.get(runState.flowId);
1262
- if (!flow2) {
1704
+ const liveFlow = flowsById.get(runState.flowId);
1705
+ if (!liveFlow) {
1263
1706
  throw new NagiRuntimeError(
1264
1707
  `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
1265
1708
  );
1266
1709
  }
1267
1710
  if (opts.mode === "inspect") return;
1268
- await advance(dispatchDeps, runId);
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
1734
+ );
1735
+ replayDeps = { ...baseDeps, flowFor: async () => synthesized };
1736
+ }
1737
+ }
1738
+ await advance(replayDeps, runId);
1739
+ if (!fireHooks) await drainInline(replayDeps);
1269
1740
  }
1270
1741
  };
1271
1742
  }
1272
1743
  function mintRunId() {
1273
1744
  return `run-${crypto.randomUUID()}`;
1274
1745
  }
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
+ }
1275
1754
  async function validate(schema, value) {
1276
1755
  const result = await schema["~standard"].validate(value);
1277
1756
  if ("issues" in result && result.issues !== void 0) {
@@ -1279,7 +1758,48 @@ async function validate(schema, value) {
1279
1758
  }
1280
1759
  return result.value;
1281
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
+ };
1801
+ }
1282
1802
 
1283
- export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiRuntimeError, NagiValidationError, flow, nagi, projectRunState };
1803
+ export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, flow, nagi, projectRunState, sha256Canonical };
1284
1804
  //# sourceMappingURL=index.js.map
1285
1805
  //# sourceMappingURL=index.js.map