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

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
@@ -89,7 +89,13 @@ function makeBuilder() {
89
89
  ...config.when !== void 0 ? {
90
90
  when: config.when
91
91
  } : {},
92
- 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 } : {}
93
99
  };
94
100
  return attachDef({ kind: "task", id: "" }, def);
95
101
  }
@@ -175,7 +181,13 @@ function makeBuilder() {
175
181
  ...config.when !== void 0 ? {
176
182
  when: config.when
177
183
  } : {},
178
- run: config.run
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 } : {}
179
191
  };
180
192
  attachDefMut(shell, def);
181
193
  chainSteps.set(key, shell);
@@ -219,7 +231,13 @@ function flow(config) {
219
231
  id: config.id,
220
232
  input: config.input,
221
233
  steps: finalSteps,
222
- ...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 } : {},
240
+ ...config.concurrency !== void 0 ? { concurrency: config.concurrency } : {}
223
241
  };
224
242
  }
225
243
  function collectIds(map, prefix, idByIdentity) {
@@ -404,6 +422,15 @@ async function hashFnSource(fn) {
404
422
  async function sha256Canonical(dag) {
405
423
  return sha256Hex(stableStringify(dag));
406
424
  }
425
+ async function fingerprintFlows(flows) {
426
+ const entries = [];
427
+ for (const f of flows) {
428
+ const dag = await canonicalize(f);
429
+ entries.push([f.id, await sha256Canonical(dag)]);
430
+ }
431
+ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
432
+ return sha256Hex(stableStringify(entries));
433
+ }
407
434
  function stableStringify(value) {
408
435
  if (value === void 0) return "null";
409
436
  if (value === null || typeof value !== "object") return JSON.stringify(value);
@@ -550,6 +577,14 @@ var InMemoryStore = class {
550
577
  snapshots = /* @__PURE__ */ new Map();
551
578
  refs = /* @__PURE__ */ new Map();
552
579
  globalFacts = [];
580
+ /**
581
+ * The runId currently holding the active slot for `flowId::concurrencyKey`.
582
+ * Updated on `tryStartRun` (set when concurrency is supplied) and on
583
+ * terminal facts (cleared via {@link keyByActiveRun}).
584
+ */
585
+ activeByKey = /* @__PURE__ */ new Map();
586
+ /** Reverse lookup so terminal facts can free the slot in O(1). */
587
+ keyByActiveRun = /* @__PURE__ */ new Map();
553
588
  leaseMs;
554
589
  constructor(opts = {}) {
555
590
  this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
@@ -558,13 +593,40 @@ var InMemoryStore = class {
558
593
  const list = this.facts.get(runId) ?? [];
559
594
  list.push(fact);
560
595
  this.facts.set(runId, list);
596
+ if (fact.kind === "flow.completed" || fact.kind === "flow.failed" || fact.kind === "flow.canceled") {
597
+ const slot = this.keyByActiveRun.get(runId);
598
+ if (slot !== void 0) {
599
+ this.keyByActiveRun.delete(runId);
600
+ if (this.activeByKey.get(slot) === runId) {
601
+ this.activeByKey.delete(slot);
602
+ }
603
+ }
604
+ }
561
605
  }
562
- async tryStartRun(runId, fact) {
606
+ async tryStartRun(runId, fact, concurrency) {
563
607
  if (this.facts.has(runId)) {
564
- return { started: false };
608
+ return { started: false, canceled: [] };
609
+ }
610
+ const canceled = [];
611
+ if (concurrency !== void 0) {
612
+ const slot = `${fact.flowId}::${concurrency.key}`;
613
+ const priorRunId = this.activeByKey.get(slot);
614
+ if (priorRunId !== void 0) {
615
+ const cancelFact = {
616
+ kind: "flow.canceled",
617
+ runId: priorRunId,
618
+ at: fact.at,
619
+ canceledByRunId: runId,
620
+ concurrencyKey: concurrency.key
621
+ };
622
+ await this.appendFact(priorRunId, cancelFact);
623
+ canceled.push({ runId: priorRunId, fact: cancelFact });
624
+ }
625
+ this.activeByKey.set(slot, runId);
626
+ this.keyByActiveRun.set(runId, slot);
565
627
  }
566
628
  this.facts.set(runId, [fact]);
567
- return { started: true };
629
+ return { started: true, canceled };
568
630
  }
569
631
  async loadRunState(runId) {
570
632
  return projectRunState(runId, this.facts.get(runId) ?? []);
@@ -646,6 +708,9 @@ function projectRunState(runId, facts) {
646
708
  case "flow.failed":
647
709
  status = "failed";
648
710
  break;
711
+ case "flow.canceled":
712
+ status = "canceled";
713
+ break;
649
714
  case "step.started":
650
715
  steps[fact.stepId] = {
651
716
  stepId: fact.stepId,
@@ -930,6 +995,19 @@ function extractInput(runState) {
930
995
  }
931
996
 
932
997
  // src/dispatch.ts
998
+ async function fireHook(hook, event, hookName, deps) {
999
+ if (deps.fireHooks === false) return;
1000
+ if (hook === void 0) return;
1001
+ try {
1002
+ await hook(event);
1003
+ } catch (err) {
1004
+ const { message, stack } = serializeError(err);
1005
+ deps.logger?.error(`nagi hook "${hookName}" threw \u2014 swallowed`, {
1006
+ error: message,
1007
+ ...stack !== void 0 ? { stack } : {}
1008
+ });
1009
+ }
1010
+ }
933
1011
  var DEFAULT_RETRY2 = {
934
1012
  maxAttempts: 3,
935
1013
  backoff: "exponential",
@@ -950,6 +1028,10 @@ async function dispatchMessage(deps, message) {
950
1028
  }
951
1029
  const def = getDef(step);
952
1030
  const preState = await store.loadRunState(runId);
1031
+ if (preState.status === "canceled") {
1032
+ await queue.ack(message.receipt);
1033
+ return;
1034
+ }
953
1035
  const preStep = preState.steps[stepId];
954
1036
  if (preStep && (preStep.status === "completed" || preStep.status === "failed" || preStep.status === "skipped")) {
955
1037
  await queue.ack(message.receipt);
@@ -968,7 +1050,7 @@ async function dispatchMessage(deps, message) {
968
1050
  at: clock.now()
969
1051
  });
970
1052
  const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
971
- await deps.hooks?.onStepStart?.({
1053
+ const startEvent = {
972
1054
  runId,
973
1055
  flowId: flow2.id,
974
1056
  stepId,
@@ -976,7 +1058,10 @@ async function dispatchMessage(deps, message) {
976
1058
  kind: def.kind,
977
1059
  input: startEventInput,
978
1060
  at: clock.now()
979
- });
1061
+ };
1062
+ const stepOnStart = def.kind === "task" ? def.onStart : void 0;
1063
+ await fireHook(stepOnStart, startEvent, "step.onStart", deps);
1064
+ await fireHook(deps.hooks?.onStepStart, startEvent, "onStepStart", deps);
980
1065
  const startedAt = Date.now();
981
1066
  try {
982
1067
  if (def.kind === "task") {
@@ -988,7 +1073,7 @@ async function dispatchMessage(deps, message) {
988
1073
  stepId,
989
1074
  attempt
990
1075
  });
991
- await deps.hooks?.onStepComplete?.({
1076
+ const completeEvent = {
992
1077
  runId,
993
1078
  flowId: flow2.id,
994
1079
  stepId,
@@ -997,7 +1082,14 @@ async function dispatchMessage(deps, message) {
997
1082
  output,
998
1083
  durationMs: Date.now() - startedAt,
999
1084
  at: clock.now()
1000
- });
1085
+ };
1086
+ await fireHook(def.onComplete, completeEvent, "step.onComplete", deps);
1087
+ await fireHook(
1088
+ deps.hooks?.onStepComplete,
1089
+ completeEvent,
1090
+ "onStepComplete",
1091
+ deps
1092
+ );
1001
1093
  await advance(deps, runId);
1002
1094
  } else if (def.kind === "signal") {
1003
1095
  await queue.ack(message.receipt);
@@ -1090,7 +1182,7 @@ async function handleStepError(args) {
1090
1182
  nextAttemptAt: new Date(Date.now() + delayMs),
1091
1183
  at: clock.now()
1092
1184
  });
1093
- await deps.hooks?.onStepRetry?.({
1185
+ const retryEvent = {
1094
1186
  runId,
1095
1187
  flowId: flow2.id,
1096
1188
  stepId,
@@ -1099,7 +1191,10 @@ async function handleStepError(args) {
1099
1191
  error,
1100
1192
  nextAttemptAt: new Date(Date.now() + delayMs),
1101
1193
  at: clock.now()
1102
- });
1194
+ };
1195
+ const stepOnRetry = def.kind === "task" ? def.onRetry : void 0;
1196
+ await fireHook(stepOnRetry, retryEvent, "step.onRetry", deps);
1197
+ await fireHook(deps.hooks?.onStepRetry, retryEvent, "onStepRetry", deps);
1103
1198
  await queue.enqueue(runId, stepId, { attempt: attempt + 1, delayMs });
1104
1199
  await queue.ack(message.receipt);
1105
1200
  return;
@@ -1113,7 +1208,7 @@ async function handleStepError(args) {
1113
1208
  at: clock.now()
1114
1209
  };
1115
1210
  await store.failStep(runId, stepId, error, fact);
1116
- await deps.hooks?.onStepError?.({
1211
+ const errorEvent = {
1117
1212
  runId,
1118
1213
  flowId: flow2.id,
1119
1214
  stepId,
@@ -1121,7 +1216,10 @@ async function handleStepError(args) {
1121
1216
  kind: def.kind,
1122
1217
  error,
1123
1218
  at: clock.now()
1124
- });
1219
+ };
1220
+ const stepOnError = def.kind === "task" ? def.onError : void 0;
1221
+ await fireHook(stepOnError, errorEvent, "step.onError", deps);
1222
+ await fireHook(deps.hooks?.onStepError, errorEvent, "onStepError", deps);
1125
1223
  await queue.ack(message.receipt);
1126
1224
  await advance(deps, runId);
1127
1225
  }
@@ -1135,53 +1233,18 @@ async function advance(deps, runId) {
1135
1233
  if (promoted) continue;
1136
1234
  const termination = flowTermination(flow2, runState);
1137
1235
  if (termination.done) {
1138
- const last2 = runState.facts[runState.facts.length - 1];
1139
- const flowAlreadyTerminal = last2 !== void 0 && (last2.kind === "flow.completed" || last2.kind === "flow.failed");
1140
- if (!flowAlreadyTerminal) {
1141
- if (termination.failed) {
1142
- const failedStep = Object.values(runState.steps).find(
1143
- (s) => s.status === "failed"
1144
- );
1145
- await store.appendFact(runId, {
1146
- kind: "flow.failed",
1147
- runId,
1148
- error: failedStep?.error ?? {
1149
- name: "Error",
1150
- message: "step failed"
1151
- },
1152
- at: clock.now()
1153
- });
1154
- await deps.hooks?.onFlowError?.({
1155
- runId,
1156
- flowId: flow2.id,
1157
- error: failedStep?.error ?? {
1158
- name: "Error",
1159
- message: "step failed"
1160
- },
1161
- at: clock.now()
1162
- });
1163
- } else {
1164
- let flowOutput = null;
1165
- if (flow2.output !== void 0) {
1166
- const stepOutputs = {};
1167
- for (const [sid, sstate] of Object.entries(runState.steps)) {
1168
- if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
1169
- }
1170
- flowOutput = flow2.output(stepOutputs);
1171
- }
1172
- await store.appendFact(runId, {
1173
- kind: "flow.completed",
1174
- runId,
1175
- output: flowOutput,
1176
- at: clock.now()
1177
- });
1178
- await deps.hooks?.onFlowComplete?.({
1179
- runId,
1180
- flowId: flow2.id,
1181
- output: flowOutput,
1182
- at: clock.now()
1183
- });
1184
- }
1236
+ if (isFlowTerminal(runState.facts)) return;
1237
+ if (termination.failed) {
1238
+ const failedStep = Object.values(runState.steps).find(
1239
+ (s) => s.status === "failed"
1240
+ );
1241
+ const flowError = failedStep?.error ?? {
1242
+ name: "Error",
1243
+ message: "step failed"
1244
+ };
1245
+ await finalizeFlowFailure({ deps, flow: flow2, runId, error: flowError });
1246
+ } else {
1247
+ await finalizeFlowCompletion({ deps, flow: flow2, runId, runState });
1185
1248
  }
1186
1249
  return;
1187
1250
  }
@@ -1208,21 +1271,9 @@ async function advance(deps, runId) {
1208
1271
  name: "NagiCycleError",
1209
1272
  message: `advance exceeded ${MAX_ADVANCE_ITERS} iterations \u2014 likely a cycle or infinite skip loop in flow "${flow2.id}"`
1210
1273
  };
1211
- const last = (await store.loadRunState(runId)).facts.slice(-1)[0];
1212
- const alreadyTerminal = last !== void 0 && (last.kind === "flow.completed" || last.kind === "flow.failed");
1213
- if (!alreadyTerminal) {
1214
- await store.appendFact(runId, {
1215
- kind: "flow.failed",
1216
- runId,
1217
- error: cycleError,
1218
- at: clock.now()
1219
- });
1220
- await deps.hooks?.onFlowError?.({
1221
- runId,
1222
- flowId: flow2.id,
1223
- error: cycleError,
1224
- at: clock.now()
1225
- });
1274
+ const facts = (await store.loadRunState(runId)).facts;
1275
+ if (!isFlowTerminal(facts)) {
1276
+ await finalizeFlowFailure({ deps, flow: flow2, runId, error: cycleError });
1226
1277
  }
1227
1278
  }
1228
1279
  async function promoteMatches(args) {
@@ -1252,15 +1303,20 @@ async function promoteMatches(args) {
1252
1303
  at: clock.now()
1253
1304
  };
1254
1305
  await store.failStep(runState.runId, matchId, error, fact2);
1255
- await deps.hooks?.onStepError?.({
1256
- runId: runState.runId,
1257
- flowId: flow2.id,
1258
- stepId: matchId,
1259
- attempt,
1260
- kind: "match",
1261
- error,
1262
- at: clock.now()
1263
- });
1306
+ await fireHook(
1307
+ deps.hooks?.onStepError,
1308
+ {
1309
+ runId: runState.runId,
1310
+ flowId: flow2.id,
1311
+ stepId: matchId,
1312
+ attempt,
1313
+ kind: "match",
1314
+ error,
1315
+ at: clock.now()
1316
+ },
1317
+ "onStepError",
1318
+ deps
1319
+ );
1264
1320
  promoted = true;
1265
1321
  continue;
1266
1322
  }
@@ -1273,16 +1329,21 @@ async function promoteMatches(args) {
1273
1329
  at: clock.now()
1274
1330
  };
1275
1331
  await store.completeStep(runState.runId, matchId, agg.output, fact);
1276
- await deps.hooks?.onStepComplete?.({
1277
- runId: runState.runId,
1278
- flowId: flow2.id,
1279
- stepId: matchId,
1280
- attempt,
1281
- kind: "match",
1282
- output: agg.output,
1283
- durationMs: 0,
1284
- at: clock.now()
1285
- });
1332
+ await fireHook(
1333
+ deps.hooks?.onStepComplete,
1334
+ {
1335
+ runId: runState.runId,
1336
+ flowId: flow2.id,
1337
+ stepId: matchId,
1338
+ attempt,
1339
+ kind: "match",
1340
+ output: agg.output,
1341
+ durationMs: 0,
1342
+ at: clock.now()
1343
+ },
1344
+ "onStepComplete",
1345
+ deps
1346
+ );
1286
1347
  promoted = true;
1287
1348
  }
1288
1349
  return promoted;
@@ -1332,6 +1393,50 @@ function retryAllows(policy, err) {
1332
1393
  if (!policy.retryOn) return true;
1333
1394
  return policy.retryOn(err);
1334
1395
  }
1396
+ function isFlowTerminal(facts) {
1397
+ for (let i = facts.length - 1; i >= 0; i--) {
1398
+ const f = facts[i];
1399
+ if (f !== void 0 && (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled")) {
1400
+ return true;
1401
+ }
1402
+ }
1403
+ return false;
1404
+ }
1405
+ async function finalizeFlowFailure(args) {
1406
+ const { deps, flow: flow2, runId, error } = args;
1407
+ const { store, clock } = deps;
1408
+ await store.appendFact(runId, {
1409
+ kind: "flow.failed",
1410
+ runId,
1411
+ error,
1412
+ at: clock.now()
1413
+ });
1414
+ const event = { runId, flowId: flow2.id, error, at: clock.now() };
1415
+ await fireHook(flow2.onError, event, "flow.onError", deps);
1416
+ await fireHook(deps.hooks?.onFlowError, event, "onFlowError", deps);
1417
+ }
1418
+ async function finalizeFlowCompletion(args) {
1419
+ const { deps, flow: flow2, runId, runState } = args;
1420
+ const { store, clock } = deps;
1421
+ const output = computeFlowOutput(flow2, runState);
1422
+ await store.appendFact(runId, {
1423
+ kind: "flow.completed",
1424
+ runId,
1425
+ output,
1426
+ at: clock.now()
1427
+ });
1428
+ const event = { runId, flowId: flow2.id, output, at: clock.now() };
1429
+ await fireHook(flow2.onComplete, event, "flow.onComplete", deps);
1430
+ await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete", deps);
1431
+ }
1432
+ function computeFlowOutput(flow2, runState) {
1433
+ if (flow2.output === void 0) return null;
1434
+ const stepOutputs = {};
1435
+ for (const [sid, sstate] of Object.entries(runState.steps)) {
1436
+ if (sstate.output !== void 0) stepOutputs[sid] = sstate.output;
1437
+ }
1438
+ return flow2.output(stepOutputs);
1439
+ }
1335
1440
  function serializeError(err) {
1336
1441
  if (err instanceof Error) {
1337
1442
  return {
@@ -1456,6 +1561,24 @@ var NagiRuntimeError = class extends Error {
1456
1561
  this.name = "NagiRuntimeError";
1457
1562
  }
1458
1563
  };
1564
+ var NagiCanceledError = class extends Error {
1565
+ runId;
1566
+ canceledByRunId;
1567
+ concurrencyKey;
1568
+ constructor(args) {
1569
+ super(
1570
+ `Run ${args.runId} was canceled (superseded by run ${args.canceledByRunId} for concurrency key "${args.concurrencyKey}").`
1571
+ );
1572
+ this.name = "NagiCanceledError";
1573
+ this.runId = args.runId;
1574
+ this.canceledByRunId = args.canceledByRunId;
1575
+ this.concurrencyKey = args.concurrencyKey;
1576
+ this.cause = {
1577
+ canceledByRunId: args.canceledByRunId,
1578
+ concurrencyKey: args.concurrencyKey
1579
+ };
1580
+ }
1581
+ };
1459
1582
  var NagiSnapshotDriftError = class extends Error {
1460
1583
  runId;
1461
1584
  expected;
@@ -1501,6 +1624,7 @@ async function nagi(config) {
1501
1624
  });
1502
1625
  }
1503
1626
  }
1627
+ const codeVersion = config.codeVersion ?? await fingerprintFlows(config.flows);
1504
1628
  async function flowFor(runId) {
1505
1629
  const runState = await config.store.loadRunState(runId);
1506
1630
  const flow2 = flowsById.get(runState.flowId);
@@ -1551,18 +1675,81 @@ async function nagi(config) {
1551
1675
  input: validated,
1552
1676
  at: startedAt,
1553
1677
  ...flowHash !== void 0 ? { flowHash } : {},
1554
- ...config.codeVersion !== void 0 ? { codeVersion: config.codeVersion } : {}
1678
+ codeVersion
1555
1679
  };
1556
- const { started } = await config.store.tryStartRun(runId, fact);
1680
+ let concurrencyArg;
1681
+ if (flow2.concurrency !== void 0) {
1682
+ const derived = flow2.concurrency.keyFn(validated);
1683
+ if (typeof derived !== "string" || derived.length === 0) {
1684
+ throw new NagiValidationError([
1685
+ {
1686
+ message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
1687
+ path: ["concurrency", "keyFn"]
1688
+ }
1689
+ ]);
1690
+ }
1691
+ concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
1692
+ }
1693
+ const { started, canceled } = await config.store.tryStartRun(
1694
+ runId,
1695
+ fact,
1696
+ concurrencyArg
1697
+ );
1557
1698
  if (!started) {
1558
1699
  return runId;
1559
1700
  }
1560
- await config.hooks?.onFlowStart?.({
1701
+ for (const c of canceled) {
1702
+ const cancelError = new NagiCanceledError({
1703
+ runId: c.runId,
1704
+ canceledByRunId: runId,
1705
+ concurrencyKey: c.fact.concurrencyKey
1706
+ });
1707
+ const serialized = {
1708
+ name: cancelError.name,
1709
+ message: cancelError.message,
1710
+ ...cancelError.stack !== void 0 ? { stack: cancelError.stack } : {},
1711
+ cause: {
1712
+ canceledByRunId: runId,
1713
+ concurrencyKey: c.fact.concurrencyKey
1714
+ }
1715
+ };
1716
+ const errorEvent = {
1717
+ runId: c.runId,
1718
+ flowId: flow2.id,
1719
+ error: serialized,
1720
+ at: c.fact.at
1721
+ };
1722
+ await fireHook(
1723
+ flow2.onError,
1724
+ errorEvent,
1725
+ "flow.onError",
1726
+ dispatchDeps
1727
+ );
1728
+ await fireHook(
1729
+ config.hooks?.onFlowError,
1730
+ errorEvent,
1731
+ "onFlowError",
1732
+ dispatchDeps
1733
+ );
1734
+ }
1735
+ const startEvent = {
1561
1736
  runId,
1562
1737
  flowId: flow2.id,
1563
1738
  input: validated,
1564
1739
  at: startedAt
1565
- });
1740
+ };
1741
+ await fireHook(
1742
+ flow2.onStart,
1743
+ startEvent,
1744
+ "flow.onStart",
1745
+ dispatchDeps
1746
+ );
1747
+ await fireHook(
1748
+ config.hooks?.onFlowStart,
1749
+ startEvent,
1750
+ "onFlowStart",
1751
+ dispatchDeps
1752
+ );
1566
1753
  await advance(dispatchDeps, runId);
1567
1754
  return runId;
1568
1755
  },
@@ -1615,15 +1802,20 @@ async function nagi(config) {
1615
1802
  validated,
1616
1803
  completedFact
1617
1804
  );
1618
- await config.hooks?.onSignalReceived?.({
1619
- runId,
1620
- flowId: flow2.id,
1621
- stepId: stepName,
1622
- attempt,
1623
- kind: "signal",
1624
- payload: validated,
1625
- at: clock.now()
1626
- });
1805
+ await fireHook(
1806
+ config.hooks?.onSignalReceived,
1807
+ {
1808
+ runId,
1809
+ flowId: flow2.id,
1810
+ stepId: stepName,
1811
+ attempt,
1812
+ kind: "signal",
1813
+ payload: validated,
1814
+ at: clock.now()
1815
+ },
1816
+ "onSignalReceived",
1817
+ dispatchDeps
1818
+ );
1627
1819
  await advance(dispatchDeps, runId);
1628
1820
  },
1629
1821
  worker(workerConfig) {
@@ -1642,7 +1834,15 @@ async function nagi(config) {
1642
1834
  `Run ${runId} references flow "${runState.flowId}" which is not registered with nagi().`
1643
1835
  );
1644
1836
  }
1837
+ if (runState.status === "canceled") {
1838
+ throw new NagiRuntimeError(
1839
+ `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.`
1840
+ );
1841
+ }
1645
1842
  if (opts.mode === "inspect") return;
1843
+ const fireHooks = opts.fireHooks !== false;
1844
+ const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
1845
+ let replayDeps = baseDeps;
1646
1846
  const pinned = runState.flowHash;
1647
1847
  if (pinned !== void 0) {
1648
1848
  const liveHash = flowHashById.get(liveFlow.id);
@@ -1664,21 +1864,25 @@ async function nagi(config) {
1664
1864
  snapshot.dag,
1665
1865
  liveFlow
1666
1866
  );
1667
- const driftDeps = {
1668
- ...dispatchDeps,
1669
- flowFor: async () => synthesized
1670
- };
1671
- await advance(driftDeps, runId);
1672
- return;
1867
+ replayDeps = { ...baseDeps, flowFor: async () => synthesized };
1673
1868
  }
1674
1869
  }
1675
- await advance(dispatchDeps, runId);
1870
+ await advance(replayDeps, runId);
1871
+ if (!fireHooks) await drainInline(replayDeps);
1676
1872
  }
1677
1873
  };
1678
1874
  }
1679
1875
  function mintRunId() {
1680
1876
  return `run-${crypto.randomUUID()}`;
1681
1877
  }
1878
+ var MAX_REPLAY_DISPATCHES = 4096;
1879
+ async function drainInline(deps) {
1880
+ for (let i = 0; i < MAX_REPLAY_DISPATCHES; i++) {
1881
+ const messages = await deps.queue.dequeue({ count: 1 });
1882
+ if (messages.length === 0) return;
1883
+ for (const msg of messages) await dispatchMessage(deps, msg);
1884
+ }
1885
+ }
1682
1886
  async function validate(schema, value) {
1683
1887
  const result = await schema["~standard"].validate(value);
1684
1888
  if ("issues" in result && result.issues !== void 0) {
@@ -1728,6 +1932,6 @@ function synthesizeReplayFlow(dag, liveFlow) {
1728
1932
  };
1729
1933
  }
1730
1934
 
1731
- export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, flow, nagi, projectRunState, sha256Canonical };
1935
+ export { InMemoryClock, InMemoryQueue, InMemoryStore, InMemoryTrigger, NagiCanceledError, NagiRuntimeError, NagiSnapshotDriftError, NagiValidationError, canonicalize, diffSnapshots, fingerprintFlows, flow, nagi, projectRunState, sha256Canonical };
1732
1936
  //# sourceMappingURL=index.js.map
1733
1937
  //# sourceMappingURL=index.js.map