@nagi-js/core 0.1.1-rc.5 → 0.1.1-rc.7

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
@@ -37,12 +37,15 @@ function matchArms(def) {
37
37
  return def.mode === "discriminator" ? Object.values(def.arms) : def.arms;
38
38
  }
39
39
  function readSelectedArm(matchId, runState) {
40
+ let selected = null;
40
41
  for (const fact of runState.facts) {
41
42
  if (fact.kind === "match.arm-selected" && fact.stepId === matchId) {
42
- return fact.arm;
43
+ selected = fact.arm;
44
+ } else if (fact.kind === "step.reset" && fact.stepId === matchId) {
45
+ selected = null;
43
46
  }
44
47
  }
45
- return null;
48
+ return selected;
46
49
  }
47
50
  function selectArm(def, args) {
48
51
  if (def.mode === "discriminator") {
@@ -112,6 +115,22 @@ function makeBuilder() {
112
115
  };
113
116
  return attachDef({ kind: "signal", id: "" }, def);
114
117
  }
118
+ function subflow(child, config) {
119
+ const def = {
120
+ kind: "subflow",
121
+ needs: config.needs ?? {},
122
+ childFlowId: child.id,
123
+ buildInput: config.input,
124
+ ...config.timeoutMs !== void 0 ? { timeoutMs: config.timeoutMs } : {},
125
+ ...config.when !== void 0 ? {
126
+ when: config.when
127
+ } : {}
128
+ };
129
+ return attachDef(
130
+ { kind: "subflow", id: "" },
131
+ def
132
+ );
133
+ }
115
134
  function match(config) {
116
135
  const needs = "needs" in config && config.needs ? config.needs : {};
117
136
  if (isDiscriminator(config)) {
@@ -206,6 +225,7 @@ function makeBuilder() {
206
225
  const builder = {
207
226
  task,
208
227
  signal,
228
+ subflow,
209
229
  match,
210
230
  step,
211
231
  include,
@@ -385,6 +405,7 @@ async function canonicalizeStep(id, def) {
385
405
  const base = { id, kind: def.kind, needs };
386
406
  if (def.kind === "task") return canonicalizeTask(base, def);
387
407
  if (def.kind === "signal") return canonicalizeSignal(base, def);
408
+ if (def.kind === "subflow") return canonicalizeSubflow(base, def);
388
409
  return canonicalizeMatch(base, def);
389
410
  }
390
411
  async function canonicalizeTask(base, def) {
@@ -404,6 +425,14 @@ async function canonicalizeSignal(base, def) {
404
425
  }
405
426
  return out;
406
427
  }
428
+ async function canonicalizeSubflow(base, def) {
429
+ const out = { ...base };
430
+ if (def.when !== void 0) out.whenHash = await hashFnSource(def.when);
431
+ if (def.timeoutMs !== void 0) out.timeoutMs = def.timeoutMs;
432
+ out.childFlowId = def.childFlowId;
433
+ out.subflowInputHash = await hashFnSource(def.buildInput);
434
+ return out;
435
+ }
407
436
  async function canonicalizeMatch(base, def) {
408
437
  const out = { ...base };
409
438
  out.matchMode = def.mode;
@@ -612,6 +641,20 @@ var InMemoryStore = class {
612
641
  activeByKey = /* @__PURE__ */ new Map();
613
642
  /** Reverse lookup so terminal facts can free the slot in O(1). */
614
643
  keyByActiveRun = /* @__PURE__ */ new Map();
644
+ /**
645
+ * Index: parentRunId → set of child run ids spawned by `b.subflow()`.
646
+ * Populated in `tryStartRun` when `fact.parentRunId` is set. Used by
647
+ * `listChildren()` to power transitive cancel cascade in O(children).
648
+ */
649
+ childrenByParent = /* @__PURE__ */ new Map();
650
+ /**
651
+ * Pruned-but-kept summaries. Populated by `pruneFacts` when `keepSummary`
652
+ * is true so that `queryRuns` still surfaces runs whose facts were dropped.
653
+ * Mirrors the postgres adapter's retained `workflow_run` row after a prune.
654
+ * Also blocks `tryStartRun` from reusing a pruned runId — matching the
655
+ * postgres `INSERT ... ON CONFLICT DO NOTHING` semantic on `run_id`.
656
+ */
657
+ summaries = /* @__PURE__ */ new Map();
615
658
  leaseMs;
616
659
  constructor(opts = {}) {
617
660
  this.leaseMs = opts.leaseMs ?? DEFAULT_STORE_LEASE_MS;
@@ -629,9 +672,16 @@ var InMemoryStore = class {
629
672
  }
630
673
  }
631
674
  }
675
+ if (fact.kind === "step.reset") {
676
+ const leasePrefix = `${runId}::${fact.stepId}::`;
677
+ for (const key of this.leases.keys()) {
678
+ if (key.startsWith(leasePrefix)) this.leases.delete(key);
679
+ }
680
+ this.outputs.delete(`${runId}::${fact.stepId}`);
681
+ }
632
682
  }
633
683
  async tryStartRun(runId, fact, concurrency) {
634
- if (this.facts.has(runId)) {
684
+ if (this.facts.has(runId) || this.summaries.has(runId)) {
635
685
  return { started: false, canceled: [] };
636
686
  }
637
687
  const canceled = [];
@@ -653,8 +703,18 @@ var InMemoryStore = class {
653
703
  this.keyByActiveRun.set(runId, slot);
654
704
  }
655
705
  this.facts.set(runId, [fact]);
706
+ if (fact.parentRunId !== void 0) {
707
+ const set = this.childrenByParent.get(fact.parentRunId) ?? /* @__PURE__ */ new Set();
708
+ set.add(runId);
709
+ this.childrenByParent.set(fact.parentRunId, set);
710
+ }
656
711
  return { started: true, canceled };
657
712
  }
713
+ async listChildren(parentRunId) {
714
+ const set = this.childrenByParent.get(parentRunId);
715
+ if (set === void 0) return [];
716
+ return Array.from(set);
717
+ }
658
718
  async loadRunState(runId) {
659
719
  return projectRunState(runId, this.facts.get(runId) ?? []);
660
720
  }
@@ -689,8 +749,10 @@ var InMemoryStore = class {
689
749
  const result = await body(void 0);
690
750
  if (result.fact.kind === "step.completed") {
691
751
  await this.completeStep(runId, stepId, result.output, result.fact);
692
- } else {
752
+ } else if (result.fact.kind === "step.failed") {
693
753
  await this.failStep(runId, stepId, result.fact.error, result.fact);
754
+ } else {
755
+ await this.appendFact(runId, result.fact);
694
756
  }
695
757
  return result.output;
696
758
  }
@@ -714,7 +776,169 @@ var InMemoryStore = class {
714
776
  readGlobalFacts() {
715
777
  return this.globalFacts;
716
778
  }
779
+ async queryRuns(opts) {
780
+ const where = opts.where ?? {};
781
+ const statuses = where.status === void 0 ? void 0 : Array.isArray(where.status) ? where.status : [where.status];
782
+ const matches = (summary) => {
783
+ if (where.flowId !== void 0 && summary.flowId !== where.flowId)
784
+ return false;
785
+ if (statuses !== void 0 && !statuses.includes(summary.status))
786
+ return false;
787
+ if (where.input !== void 0 && !containsJson(summary.input, where.input))
788
+ return false;
789
+ return true;
790
+ };
791
+ const summaries = [];
792
+ for (const [runId, factList] of this.facts) {
793
+ const summary = summarize(runId, factList);
794
+ if (summary === null) continue;
795
+ if (matches(summary)) summaries.push(summary);
796
+ }
797
+ for (const summary of this.summaries.values()) {
798
+ if (matches(summary)) summaries.push(summary);
799
+ }
800
+ summaries.sort((a, b) => {
801
+ const t = b.startedAt.getTime() - a.startedAt.getTime();
802
+ if (t !== 0) return t;
803
+ return a.runId < b.runId ? 1 : a.runId > b.runId ? -1 : 0;
804
+ });
805
+ if (opts.latest === true) {
806
+ return { runs: summaries.slice(0, 1), cursor: null };
807
+ }
808
+ const limit = clampLimit(opts.limit);
809
+ let start = 0;
810
+ if (opts.cursor !== void 0) {
811
+ const c = decodeCursor(opts.cursor);
812
+ start = summaries.findIndex(
813
+ (s) => s.startedAt.getTime() < c.t || s.startedAt.getTime() === c.t && s.runId < c.r
814
+ );
815
+ if (start === -1) start = summaries.length;
816
+ }
817
+ const page = summaries.slice(start, start + limit);
818
+ const hasMore = start + limit < summaries.length;
819
+ const last = page[page.length - 1];
820
+ const cursor = hasMore && last !== void 0 ? encodeCursor({ t: last.startedAt.getTime(), r: last.runId }) : null;
821
+ return { runs: page, cursor };
822
+ }
823
+ async pruneFacts(opts) {
824
+ const olderThanMs = opts.olderThan.getTime();
825
+ const statusSet = new Set(opts.statuses);
826
+ const victims = [];
827
+ for (const [runId, factList] of this.facts) {
828
+ const summary = summarize(runId, factList);
829
+ if (summary === null) continue;
830
+ if (summary.completedAt === null) continue;
831
+ if (!statusSet.has(summary.status)) continue;
832
+ if (summary.completedAt.getTime() >= olderThanMs) continue;
833
+ const first = factList[0];
834
+ const parentRunId = first !== void 0 && first.kind === "flow.started" ? first.parentRunId : void 0;
835
+ victims.push({
836
+ runId,
837
+ summary,
838
+ factCount: factList.length,
839
+ parentRunId
840
+ });
841
+ }
842
+ let runsPruned = 0;
843
+ let factsPruned = 0;
844
+ for (const v of victims) {
845
+ this.facts.delete(v.runId);
846
+ deleteByRunPrefix(this.outputs, v.runId);
847
+ deleteByRunPrefix(this.onces, v.runId);
848
+ deleteByRunPrefix(this.leases, v.runId);
849
+ this.childrenByParent.delete(v.runId);
850
+ if (v.parentRunId !== void 0) {
851
+ const siblings = this.childrenByParent.get(v.parentRunId);
852
+ if (siblings !== void 0) {
853
+ siblings.delete(v.runId);
854
+ if (siblings.size === 0) this.childrenByParent.delete(v.parentRunId);
855
+ }
856
+ }
857
+ if (opts.keepSummary) {
858
+ this.summaries.set(v.runId, v.summary);
859
+ } else {
860
+ this.summaries.delete(v.runId);
861
+ }
862
+ runsPruned += 1;
863
+ factsPruned += v.factCount;
864
+ }
865
+ return { runsPruned, factsPruned };
866
+ }
717
867
  };
868
+ function deleteByRunPrefix(map, runId) {
869
+ const prefix = `${runId}::`;
870
+ for (const key of map.keys()) {
871
+ if (key.startsWith(prefix)) map.delete(key);
872
+ }
873
+ }
874
+ function summarize(runId, facts) {
875
+ const first = facts[0];
876
+ if (first === void 0 || first.kind !== "flow.started") return null;
877
+ const projected = projectRunState(runId, facts);
878
+ let completedAt = null;
879
+ for (let i = facts.length - 1; i >= 0; i--) {
880
+ const f = facts[i];
881
+ if (f === void 0) continue;
882
+ if (f.kind === "flow.completed" || f.kind === "flow.failed" || f.kind === "flow.canceled") {
883
+ completedAt = f.at;
884
+ break;
885
+ }
886
+ }
887
+ return {
888
+ runId,
889
+ flowId: first.flowId,
890
+ status: projected.status,
891
+ startedAt: first.at,
892
+ completedAt,
893
+ input: first.input
894
+ };
895
+ }
896
+ var DEFAULT_LIMIT = 50;
897
+ var MAX_LIMIT = 500;
898
+ function clampLimit(limit) {
899
+ if (limit === void 0) return DEFAULT_LIMIT;
900
+ if (!Number.isInteger(limit) || limit < 1) return DEFAULT_LIMIT;
901
+ return Math.min(limit, MAX_LIMIT);
902
+ }
903
+ function encodeCursor(c) {
904
+ const bytes = new TextEncoder().encode(JSON.stringify(c));
905
+ let binary = "";
906
+ for (let i = 0; i < bytes.length; i++) {
907
+ binary += String.fromCharCode(bytes[i]);
908
+ }
909
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
910
+ }
911
+ function decodeCursor(s) {
912
+ try {
913
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/");
914
+ const binary = atob(b64);
915
+ const bytes = new Uint8Array(binary.length);
916
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
917
+ const parsed = JSON.parse(new TextDecoder().decode(bytes));
918
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.t === "number" && typeof parsed.r === "string") {
919
+ return parsed;
920
+ }
921
+ throw new Error("malformed cursor body");
922
+ } catch (err) {
923
+ throw new Error(
924
+ `queryRuns: invalid cursor \u2014 ${err instanceof Error ? err.message : String(err)}`
925
+ );
926
+ }
927
+ }
928
+ function containsJson(haystack, needle) {
929
+ if (Array.isArray(needle)) {
930
+ if (!Array.isArray(haystack)) return false;
931
+ return needle.every((n) => haystack.some((h) => containsJson(h, n)));
932
+ }
933
+ if (needle !== null && typeof needle === "object") {
934
+ if (haystack === null || Array.isArray(haystack) || typeof haystack !== "object")
935
+ return false;
936
+ return Object.entries(needle).every(
937
+ ([k, v]) => k in haystack && containsJson(haystack[k], v)
938
+ );
939
+ }
940
+ return haystack === needle;
941
+ }
718
942
  function projectRunState(runId, facts) {
719
943
  let flowId = "";
720
944
  let status = "pending";
@@ -761,6 +985,14 @@ function projectRunState(runId, facts) {
761
985
  error: fact.error
762
986
  };
763
987
  break;
988
+ case "step.canceled":
989
+ steps[fact.stepId] = {
990
+ stepId: fact.stepId,
991
+ status: "canceled",
992
+ attempts: fact.attempt,
993
+ ...fact.error !== void 0 ? { error: fact.error } : {}
994
+ };
995
+ break;
764
996
  case "step.skipped":
765
997
  steps[fact.stepId] = {
766
998
  stepId: fact.stepId,
@@ -768,6 +1000,9 @@ function projectRunState(runId, facts) {
768
1000
  attempts: 0
769
1001
  };
770
1002
  break;
1003
+ case "step.reset":
1004
+ delete steps[fact.stepId];
1005
+ break;
771
1006
  }
772
1007
  }
773
1008
  return {
@@ -954,13 +1189,28 @@ function checkUpstream(def, runState) {
954
1189
  const upstreamState = runState.steps[upstream.id];
955
1190
  if (upstreamState === void 0) return "blocked";
956
1191
  if (upstreamState.status === "completed") continue;
957
- if (upstreamState.status === "skipped" || upstreamState.status === "failed") {
1192
+ if (upstreamState.status === "skipped") {
1193
+ if (manualSkipCascade(upstream.id, runState) === "continue") continue;
1194
+ return "transitive-skip";
1195
+ }
1196
+ if (upstreamState.status === "failed") {
958
1197
  return "transitive-skip";
959
1198
  }
960
1199
  return "blocked";
961
1200
  }
962
1201
  return "ready";
963
1202
  }
1203
+ function manualSkipCascade(stepId, runState) {
1204
+ for (let i = runState.facts.length - 1; i >= 0; i--) {
1205
+ const f = runState.facts[i];
1206
+ if (f === void 0) continue;
1207
+ if (f.kind !== "step.skipped") continue;
1208
+ if (f.stepId !== stepId) continue;
1209
+ if (f.reason !== "manual") return "skip";
1210
+ return f.cascade ?? "skip";
1211
+ }
1212
+ return "skip";
1213
+ }
964
1214
  function checkParentMatch(def, runState) {
965
1215
  if (!def.parentMatch) return "ready";
966
1216
  const { matchId, armId } = def.parentMatch;
@@ -1012,6 +1262,36 @@ function flowTermination(flow2, runState) {
1012
1262
  }
1013
1263
  return { done, failed };
1014
1264
  }
1265
+ function descendantsOf(flow2, stepId) {
1266
+ const children = /* @__PURE__ */ new Map();
1267
+ const addEdge = (from, to) => {
1268
+ const bucket = children.get(from);
1269
+ if (bucket) bucket.push(to);
1270
+ else children.set(from, [to]);
1271
+ };
1272
+ for (const [id, step] of Object.entries(flow2.steps)) {
1273
+ const def = getDef(step);
1274
+ for (const upstreamId of needsStepIds(def)) addEdge(upstreamId, id);
1275
+ if (def.kind === "match") {
1276
+ for (const arm of matchArms(def)) {
1277
+ for (const armStepId of arm.stepIds) addEdge(id, armStepId);
1278
+ }
1279
+ }
1280
+ }
1281
+ const out = [stepId];
1282
+ const seen = /* @__PURE__ */ new Set([stepId]);
1283
+ for (let i = 0; i < out.length; i++) {
1284
+ const current = out[i];
1285
+ if (current === void 0) continue;
1286
+ for (const child of children.get(current) ?? []) {
1287
+ if (seen.has(child)) continue;
1288
+ if (!(child in flow2.steps)) continue;
1289
+ seen.add(child);
1290
+ out.push(child);
1291
+ }
1292
+ }
1293
+ return out;
1294
+ }
1015
1295
  function extractInput(runState) {
1016
1296
  for (const fact of runState.facts) {
1017
1297
  if (fact.kind === "flow.started") return fact.input;
@@ -1076,7 +1356,7 @@ async function dispatchMessage(deps, message) {
1076
1356
  attempt,
1077
1357
  at: clock.now()
1078
1358
  });
1079
- const startEventInput = def.kind === "task" ? extractInput(await store.loadRunState(runId)) : null;
1359
+ const startEventInput = def.kind === "task" || def.kind === "subflow" ? extractInput(await store.loadRunState(runId)) : null;
1080
1360
  const startEvent = {
1081
1361
  runId,
1082
1362
  flowId: flow2.id,
@@ -1092,7 +1372,7 @@ async function dispatchMessage(deps, message) {
1092
1372
  const startedAt = Date.now();
1093
1373
  try {
1094
1374
  if (def.kind === "task") {
1095
- const output = await executeTask({
1375
+ const { output, skipAdvance } = await executeTask({
1096
1376
  deps,
1097
1377
  message,
1098
1378
  def,
@@ -1100,6 +1380,7 @@ async function dispatchMessage(deps, message) {
1100
1380
  stepId,
1101
1381
  attempt
1102
1382
  });
1383
+ if (skipAdvance) return;
1103
1384
  const completeEvent = {
1104
1385
  runId,
1105
1386
  flowId: flow2.id,
@@ -1124,6 +1405,10 @@ async function dispatchMessage(deps, message) {
1124
1405
  } else if (def.kind === "match") {
1125
1406
  await executeMatch({ deps, message, def, runId, stepId, attempt });
1126
1407
  await advance(deps, runId);
1408
+ } else if (def.kind === "subflow") {
1409
+ await executeSubflow({ deps, message, def, runId, stepId });
1410
+ await queue.ack(message.receipt);
1411
+ return;
1127
1412
  }
1128
1413
  } catch (err) {
1129
1414
  await handleStepError({
@@ -1147,35 +1432,148 @@ async function executeTask(args) {
1147
1432
  const runState = await store.loadRunState(runId);
1148
1433
  const input = extractInput(runState);
1149
1434
  const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
1150
- const output = await store.runStep(
1435
+ const ac = new AbortController();
1436
+ const watcher = startCancelWatcher({
1437
+ store,
1151
1438
  runId,
1152
1439
  stepId,
1153
1440
  attempt,
1154
- async (tx) => {
1155
- const ctx = makeStepCtx({
1156
- runId,
1157
- stepId,
1158
- attempt,
1159
- input,
1160
- store,
1161
- clock,
1162
- tx,
1163
- ...deps.logger !== void 0 ? { logger: deps.logger } : {}
1164
- });
1165
- const out = await def.run({ input, needs, ctx });
1166
- const fact = {
1167
- kind: "step.completed",
1168
- runId,
1169
- stepId,
1170
- attempt,
1171
- output: out,
1172
- at: clock.now()
1173
- };
1174
- return { output: out, fact };
1441
+ ac,
1442
+ intervalMs: deps.cancelPollIntervalMs ?? CANCEL_POLL_INTERVAL_MS
1443
+ });
1444
+ try {
1445
+ let stepAbortedHere = false;
1446
+ const output = await store.runStep(
1447
+ runId,
1448
+ stepId,
1449
+ attempt,
1450
+ async (tx) => {
1451
+ const ctx = makeStepCtx({
1452
+ runId,
1453
+ stepId,
1454
+ attempt,
1455
+ input,
1456
+ store,
1457
+ clock,
1458
+ tx,
1459
+ signal: ac.signal,
1460
+ ...deps.logger !== void 0 ? { logger: deps.logger } : {}
1461
+ });
1462
+ const out = await def.run({ input, needs, ctx });
1463
+ const postState = await store.loadRunState(runId);
1464
+ if (postState.status === "canceled") {
1465
+ const canceledFact = {
1466
+ kind: "step.canceled",
1467
+ runId,
1468
+ stepId,
1469
+ attempt,
1470
+ at: clock.now()
1471
+ };
1472
+ return { output: out, fact: canceledFact };
1473
+ }
1474
+ if (hasAbortRequest(postState.facts, stepId, attempt)) {
1475
+ stepAbortedHere = true;
1476
+ const canceledFact = {
1477
+ kind: "step.canceled",
1478
+ runId,
1479
+ stepId,
1480
+ attempt,
1481
+ at: clock.now()
1482
+ };
1483
+ return { output: out, fact: canceledFact };
1484
+ }
1485
+ const fact = {
1486
+ kind: "step.completed",
1487
+ runId,
1488
+ stepId,
1489
+ attempt,
1490
+ output: out,
1491
+ at: clock.now()
1492
+ };
1493
+ return { output: out, fact };
1494
+ }
1495
+ );
1496
+ await queue.ack(message.receipt);
1497
+ return { output, skipAdvance: stepAbortedHere };
1498
+ } finally {
1499
+ watcher.stop();
1500
+ }
1501
+ }
1502
+ var CANCEL_POLL_INTERVAL_MS = 250;
1503
+ function startCancelWatcher(args) {
1504
+ const { store, runId, stepId, attempt, ac, intervalMs } = args;
1505
+ let stopped = false;
1506
+ void (async () => {
1507
+ while (!stopped) {
1508
+ await new Promise((r) => setTimeout(r, intervalMs));
1509
+ if (stopped) return;
1510
+ try {
1511
+ const s = await store.loadRunState(runId);
1512
+ if (s.status === "canceled" || s.status === "failed" || s.status === "completed") {
1513
+ if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "run"));
1514
+ return;
1515
+ }
1516
+ if (hasAbortRequest(s.facts, stepId, attempt)) {
1517
+ if (!ac.signal.aborted) ac.abort(new NagiAbortError(runId, "step"));
1518
+ return;
1519
+ }
1520
+ } catch {
1521
+ }
1175
1522
  }
1176
- );
1177
- await queue.ack(message.receipt);
1178
- return output;
1523
+ })();
1524
+ return {
1525
+ stop: () => {
1526
+ stopped = true;
1527
+ }
1528
+ };
1529
+ }
1530
+ function hasAbortRequest(facts, stepId, attempt) {
1531
+ for (let i = facts.length - 1; i >= 0; i--) {
1532
+ const f = facts[i];
1533
+ if (f === void 0) continue;
1534
+ if (f.kind === "step.reset" && f.stepId === stepId) return false;
1535
+ if (f.kind === "step.abort-requested" && f.stepId === stepId && f.attempt === attempt) {
1536
+ return true;
1537
+ }
1538
+ }
1539
+ return false;
1540
+ }
1541
+ var NagiAbortError = class extends Error {
1542
+ runId;
1543
+ scope;
1544
+ constructor(runId, scope) {
1545
+ super(
1546
+ scope === "run" ? `Run ${runId} was canceled \u2014 ctx.signal aborted.` : `Step in run ${runId} was aborted by operator.retry() \u2014 ctx.signal aborted.`
1547
+ );
1548
+ this.name = "NagiAbortError";
1549
+ this.runId = runId;
1550
+ this.scope = scope;
1551
+ }
1552
+ };
1553
+ async function executeSubflow(args) {
1554
+ const { deps, def, runId, stepId } = args;
1555
+ const { store } = deps;
1556
+ if (deps.lookupFlow === void 0 || deps.startChildRun === void 0) {
1557
+ throw new Error(
1558
+ `subflow dispatch requires DispatchDeps.lookupFlow + .startChildRun (step "${stepId}" referenced child "${def.childFlowId}")`
1559
+ );
1560
+ }
1561
+ const child = deps.lookupFlow(def.childFlowId);
1562
+ if (child === void 0) {
1563
+ throw new Error(
1564
+ `Subflow step "${stepId}" references child flow "${def.childFlowId}" which is not registered with nagi(). Pass it to flows[].`
1565
+ );
1566
+ }
1567
+ const runState = await store.loadRunState(runId);
1568
+ const parentInput = extractInput(runState);
1569
+ const needs = resolveNeeds(def, (id) => runState.steps[id]?.output ?? null);
1570
+ const childInput = def.buildInput({ input: parentInput, needs });
1571
+ await deps.startChildRun({
1572
+ child,
1573
+ childInput,
1574
+ parentRunId: runId,
1575
+ parentStepId: stepId
1576
+ });
1179
1577
  }
1180
1578
  async function executeMatch(args) {
1181
1579
  const { deps, message, def, runId, stepId } = args;
@@ -1197,6 +1595,24 @@ async function handleStepError(args) {
1197
1595
  const { deps, flow: flow2, message, def, runId, stepId, attempt, err } = args;
1198
1596
  const { store, queue, clock } = deps;
1199
1597
  const error = serializeError(err);
1598
+ const postState = await store.loadRunState(runId);
1599
+ const runIsCanceled = postState.status === "canceled";
1600
+ const stepAborted = hasAbortRequest(postState.facts, stepId, attempt);
1601
+ if (runIsCanceled || stepAborted) {
1602
+ const isAbort = err instanceof Error && (err.name === "AbortError" || err.name === "NagiAbortError");
1603
+ const canceledFact = {
1604
+ kind: "step.canceled",
1605
+ runId,
1606
+ stepId,
1607
+ attempt,
1608
+ ...isAbort ? { error } : {},
1609
+ at: clock.now()
1610
+ };
1611
+ await store.appendFact(runId, canceledFact);
1612
+ await queue.ack(message.receipt);
1613
+ if (!stepAborted) await advance(deps, runId);
1614
+ return;
1615
+ }
1200
1616
  const policy = def.kind === "task" && def.retry ? def.retry : deps.defaultRetry ?? DEFAULT_RETRY2;
1201
1617
  const shouldRetry = attempt < policy.maxAttempts && retryAllows(policy, err);
1202
1618
  if (shouldRetry) {
@@ -1376,14 +1792,13 @@ async function promoteMatches(args) {
1376
1792
  return promoted;
1377
1793
  }
1378
1794
  function makeStepCtx(args) {
1379
- const { runId, stepId, attempt, input, store, clock, tx } = args;
1380
- const ac = new AbortController();
1795
+ const { runId, stepId, attempt, input, store, clock, tx, signal } = args;
1381
1796
  return {
1382
1797
  input,
1383
1798
  runId,
1384
1799
  stepId,
1385
1800
  attempt,
1386
- signal: ac.signal,
1801
+ signal,
1387
1802
  now: () => clock.now(),
1388
1803
  // `tx` is supplied by `Store.runStep` — for adapters with no real
1389
1804
  // transaction (in-memory) it is `undefined as Tx`, and handlers that
@@ -1441,6 +1856,7 @@ async function finalizeFlowFailure(args) {
1441
1856
  const event = { runId, flowId: flow2.id, error, at: clock.now() };
1442
1857
  await fireHook(flow2.onError, event, "flow.onError", deps);
1443
1858
  await fireHook(deps.hooks?.onFlowError, event, "onFlowError", deps);
1859
+ await propagateToParent(deps, runId, { kind: "failed", error });
1444
1860
  }
1445
1861
  async function finalizeFlowCompletion(args) {
1446
1862
  const { deps, flow: flow2, runId, runState } = args;
@@ -1455,6 +1871,102 @@ async function finalizeFlowCompletion(args) {
1455
1871
  const event = { runId, flowId: flow2.id, output, at: clock.now() };
1456
1872
  await fireHook(flow2.onComplete, event, "flow.onComplete", deps);
1457
1873
  await fireHook(deps.hooks?.onFlowComplete, event, "onFlowComplete", deps);
1874
+ await propagateToParent(deps, runId, { kind: "completed", output });
1875
+ }
1876
+ async function propagateToParent(deps, childRunId, outcome) {
1877
+ const { store, clock } = deps;
1878
+ const childState = await store.loadRunState(childRunId);
1879
+ const startedFact = childState.facts.find((f) => f.kind === "flow.started");
1880
+ if (startedFact?.parentRunId === void 0 || startedFact?.parentStepId === void 0) {
1881
+ return;
1882
+ }
1883
+ const parentRunId = startedFact.parentRunId;
1884
+ const parentStepId = startedFact.parentStepId;
1885
+ const parentState = await store.loadRunState(parentRunId);
1886
+ if (parentState.status === "completed" || parentState.status === "failed" || parentState.status === "canceled") {
1887
+ deps.logger?.info(
1888
+ "nagi: subflow wake skipped \u2014 parent run already terminal",
1889
+ {
1890
+ parentRunId,
1891
+ parentStepId,
1892
+ childRunId,
1893
+ parentStatus: parentState.status
1894
+ }
1895
+ );
1896
+ return;
1897
+ }
1898
+ const parentStep = parentState.steps[parentStepId];
1899
+ if (parentStep?.status !== "running") {
1900
+ deps.logger?.info("nagi: subflow wake skipped \u2014 parent step not running", {
1901
+ parentRunId,
1902
+ parentStepId,
1903
+ childRunId,
1904
+ parentStepStatus: parentStep?.status ?? "missing"
1905
+ });
1906
+ return;
1907
+ }
1908
+ const attempt = parentStep.attempts > 0 ? parentStep.attempts : 1;
1909
+ const parentFlow = await deps.flowFor(parentRunId);
1910
+ if (outcome.kind === "completed") {
1911
+ const subflowOutput = {
1912
+ childRunId,
1913
+ output: outcome.output
1914
+ };
1915
+ const completedFact = {
1916
+ kind: "step.completed",
1917
+ runId: parentRunId,
1918
+ stepId: parentStepId,
1919
+ attempt,
1920
+ output: subflowOutput,
1921
+ at: clock.now()
1922
+ };
1923
+ await store.completeStep(
1924
+ parentRunId,
1925
+ parentStepId,
1926
+ subflowOutput,
1927
+ completedFact
1928
+ );
1929
+ await fireHook(
1930
+ deps.hooks?.onStepComplete,
1931
+ {
1932
+ runId: parentRunId,
1933
+ flowId: parentFlow.id,
1934
+ stepId: parentStepId,
1935
+ attempt,
1936
+ kind: "subflow",
1937
+ output: subflowOutput,
1938
+ durationMs: 0,
1939
+ at: clock.now()
1940
+ },
1941
+ "onStepComplete",
1942
+ deps
1943
+ );
1944
+ } else {
1945
+ const failedFact = {
1946
+ kind: "step.failed",
1947
+ runId: parentRunId,
1948
+ stepId: parentStepId,
1949
+ attempt,
1950
+ error: outcome.error,
1951
+ at: clock.now()
1952
+ };
1953
+ await store.failStep(parentRunId, parentStepId, outcome.error, failedFact);
1954
+ await fireHook(
1955
+ deps.hooks?.onStepError,
1956
+ {
1957
+ runId: parentRunId,
1958
+ flowId: parentFlow.id,
1959
+ stepId: parentStepId,
1960
+ attempt,
1961
+ kind: "subflow",
1962
+ error: outcome.error,
1963
+ at: clock.now()
1964
+ },
1965
+ "onStepError",
1966
+ deps
1967
+ );
1968
+ }
1969
+ await advance(deps, parentRunId);
1458
1970
  }
1459
1971
  function computeFlowOutput(flow2, runState) {
1460
1972
  if (flow2.output === void 0) return null;
@@ -1662,8 +2174,190 @@ async function nagi(config) {
1662
2174
  }
1663
2175
  return flow2;
1664
2176
  }
2177
+ function lookupFlow(flowId) {
2178
+ return flowsById.get(flowId);
2179
+ }
2180
+ async function startRunInternal(args) {
2181
+ const { flow: flow2, validatedInput, runId, parentRunId, parentStepId } = args;
2182
+ const startedAt = clock.now();
2183
+ const flowHash = flowHashById.get(flow2.id);
2184
+ const fact = {
2185
+ kind: "flow.started",
2186
+ runId,
2187
+ flowId: flow2.id,
2188
+ input: validatedInput,
2189
+ at: startedAt,
2190
+ ...flowHash !== void 0 ? { flowHash } : {},
2191
+ codeVersion,
2192
+ ...parentRunId !== void 0 ? { parentRunId } : {},
2193
+ ...parentStepId !== void 0 ? { parentStepId } : {}
2194
+ };
2195
+ let concurrencyArg;
2196
+ if (flow2.concurrency !== void 0) {
2197
+ const derived = flow2.concurrency.keyFn(validatedInput);
2198
+ if (typeof derived !== "string" || derived.length === 0) {
2199
+ throw new NagiValidationError([
2200
+ {
2201
+ message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
2202
+ path: ["concurrency", "keyFn"]
2203
+ }
2204
+ ]);
2205
+ }
2206
+ concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
2207
+ }
2208
+ const { started, canceled } = await config.store.tryStartRun(
2209
+ runId,
2210
+ fact,
2211
+ concurrencyArg
2212
+ );
2213
+ if (!started) return { started: false };
2214
+ for (const c of canceled) {
2215
+ const cancelError = new NagiCanceledError({
2216
+ runId: c.runId,
2217
+ canceledByRunId: runId,
2218
+ concurrencyKey: c.fact.concurrencyKey
2219
+ });
2220
+ const serialized = {
2221
+ name: cancelError.name,
2222
+ message: cancelError.message,
2223
+ ...cancelError.stack !== void 0 ? { stack: cancelError.stack } : {},
2224
+ cause: {
2225
+ canceledByRunId: runId,
2226
+ concurrencyKey: c.fact.concurrencyKey
2227
+ }
2228
+ };
2229
+ const errorEvent = {
2230
+ runId: c.runId,
2231
+ flowId: flow2.id,
2232
+ error: serialized,
2233
+ at: c.fact.at
2234
+ };
2235
+ await fireHook(
2236
+ flow2.onError,
2237
+ errorEvent,
2238
+ "flow.onError",
2239
+ dispatchDeps
2240
+ );
2241
+ await fireHook(
2242
+ config.hooks?.onFlowError,
2243
+ errorEvent,
2244
+ "onFlowError",
2245
+ dispatchDeps
2246
+ );
2247
+ await propagateToParent(dispatchDeps, c.runId, {
2248
+ kind: "canceled",
2249
+ error: serialized
2250
+ });
2251
+ }
2252
+ const startEvent = {
2253
+ runId,
2254
+ flowId: flow2.id,
2255
+ input: validatedInput,
2256
+ at: startedAt
2257
+ };
2258
+ await fireHook(
2259
+ flow2.onStart,
2260
+ startEvent,
2261
+ "flow.onStart",
2262
+ dispatchDeps
2263
+ );
2264
+ await fireHook(
2265
+ config.hooks?.onFlowStart,
2266
+ startEvent,
2267
+ "onFlowStart",
2268
+ dispatchDeps
2269
+ );
2270
+ await advance(dispatchDeps, runId);
2271
+ return { started: true };
2272
+ }
2273
+ async function startChildRun(args) {
2274
+ const { child, childInput, parentRunId, parentStepId } = args;
2275
+ if (!flowsById.has(child.id)) {
2276
+ throw new NagiRuntimeError(
2277
+ `Subflow child "${child.id}" not registered with nagi(). Pass it to flows[].`
2278
+ );
2279
+ }
2280
+ const validated = await validate(child.input, childInput);
2281
+ const childRunId = mintRunId();
2282
+ const { started } = await startRunInternal({
2283
+ flow: child,
2284
+ validatedInput: validated,
2285
+ runId: childRunId,
2286
+ parentRunId,
2287
+ parentStepId
2288
+ });
2289
+ if (!started) {
2290
+ throw new NagiRuntimeError(
2291
+ `startChildRun: minted child runId collided with an existing run (${childRunId})`
2292
+ );
2293
+ }
2294
+ return childRunId;
2295
+ }
2296
+ async function cancelRunRecursive(runId, args) {
2297
+ const state = await config.store.loadRunState(runId);
2298
+ if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
2299
+ config.logger?.info("nagi: cancel skipped \u2014 run already terminal", {
2300
+ runId,
2301
+ status: state.status
2302
+ });
2303
+ return;
2304
+ }
2305
+ const flow2 = flowsById.get(state.flowId);
2306
+ const canceledFact = {
2307
+ kind: "flow.canceled",
2308
+ cause: args.cause,
2309
+ runId,
2310
+ at: clock.now(),
2311
+ // Explicit/operator cancels record self as canceler. Observers
2312
+ // discriminate via `cause` (or, for legacy facts, `canceledByRunId === runId`).
2313
+ canceledByRunId: runId,
2314
+ // Legacy carrier: explicit cancels stuff `reason` here for back-compat;
2315
+ // operator cancels use `note` instead and leave this empty.
2316
+ concurrencyKey: args.cause === "explicit" ? args.reason : "",
2317
+ ...args.actor !== void 0 ? { actor: args.actor } : {},
2318
+ ...args.note !== void 0 ? { note: args.note } : {}
2319
+ };
2320
+ await config.store.appendFact(runId, canceledFact);
2321
+ if (flow2 !== void 0) {
2322
+ const cancelError2 = {
2323
+ name: "NagiCanceledError",
2324
+ message: `Run ${runId} was canceled: ${args.reason}`
2325
+ };
2326
+ const event = {
2327
+ runId,
2328
+ flowId: flow2.id,
2329
+ error: cancelError2,
2330
+ at: clock.now()
2331
+ };
2332
+ await fireHook(flow2.onError, event, "flow.onError", dispatchDeps);
2333
+ await fireHook(
2334
+ config.hooks?.onFlowError,
2335
+ event,
2336
+ "onFlowError",
2337
+ dispatchDeps
2338
+ );
2339
+ }
2340
+ const children = await config.store.listChildren(runId);
2341
+ for (const childId of children) {
2342
+ await cancelRunRecursive(childId, {
2343
+ cause: "explicit",
2344
+ reason: `parent ${runId} canceled: ${args.reason}`,
2345
+ note: args.cause === "operator" && args.actor !== void 0 ? `cascade from operator ${args.actor} aborting parent ${runId}` : `cascade from parent ${runId}`
2346
+ });
2347
+ }
2348
+ const cancelError = {
2349
+ name: "NagiCanceledError",
2350
+ message: `Run ${runId} was canceled: ${args.reason}`
2351
+ };
2352
+ await propagateToParent(dispatchDeps, runId, {
2353
+ kind: "canceled",
2354
+ error: cancelError
2355
+ });
2356
+ }
1665
2357
  const dispatchDeps = {
1666
2358
  flowFor,
2359
+ lookupFlow,
2360
+ startChildRun,
1667
2361
  store: config.store,
1668
2362
  queue: config.queue,
1669
2363
  clock,
@@ -1671,7 +2365,7 @@ async function nagi(config) {
1671
2365
  ...config.logger !== void 0 ? { logger: config.logger } : {},
1672
2366
  ...config.defaultRetry !== void 0 ? { defaultRetry: config.defaultRetry } : {}
1673
2367
  };
1674
- return {
2368
+ const wf = {
1675
2369
  async start(flow2, input, opts) {
1676
2370
  if (!flowsById.has(flow2.id)) {
1677
2371
  throw new NagiRuntimeError(
@@ -1693,91 +2387,7 @@ async function nagi(config) {
1693
2387
  runId = mintRunId();
1694
2388
  }
1695
2389
  const validated = await validate(flow2.input, input);
1696
- const startedAt = clock.now();
1697
- const flowHash = flowHashById.get(flow2.id);
1698
- const fact = {
1699
- kind: "flow.started",
1700
- runId,
1701
- flowId: flow2.id,
1702
- input: validated,
1703
- at: startedAt,
1704
- ...flowHash !== void 0 ? { flowHash } : {},
1705
- codeVersion
1706
- };
1707
- let concurrencyArg;
1708
- if (flow2.concurrency !== void 0) {
1709
- const derived = flow2.concurrency.keyFn(validated);
1710
- if (typeof derived !== "string" || derived.length === 0) {
1711
- throw new NagiValidationError([
1712
- {
1713
- message: `flow.concurrency.keyFn must return a non-empty string (got ${typeof derived === "string" ? '""' : typeof derived})`,
1714
- path: ["concurrency", "keyFn"]
1715
- }
1716
- ]);
1717
- }
1718
- concurrencyArg = { key: derived, mode: flow2.concurrency.mode };
1719
- }
1720
- const { started, canceled } = await config.store.tryStartRun(
1721
- runId,
1722
- fact,
1723
- concurrencyArg
1724
- );
1725
- if (!started) {
1726
- return runId;
1727
- }
1728
- for (const c of canceled) {
1729
- const cancelError = new NagiCanceledError({
1730
- runId: c.runId,
1731
- canceledByRunId: runId,
1732
- concurrencyKey: c.fact.concurrencyKey
1733
- });
1734
- const serialized = {
1735
- name: cancelError.name,
1736
- message: cancelError.message,
1737
- ...cancelError.stack !== void 0 ? { stack: cancelError.stack } : {},
1738
- cause: {
1739
- canceledByRunId: runId,
1740
- concurrencyKey: c.fact.concurrencyKey
1741
- }
1742
- };
1743
- const errorEvent = {
1744
- runId: c.runId,
1745
- flowId: flow2.id,
1746
- error: serialized,
1747
- at: c.fact.at
1748
- };
1749
- await fireHook(
1750
- flow2.onError,
1751
- errorEvent,
1752
- "flow.onError",
1753
- dispatchDeps
1754
- );
1755
- await fireHook(
1756
- config.hooks?.onFlowError,
1757
- errorEvent,
1758
- "onFlowError",
1759
- dispatchDeps
1760
- );
1761
- }
1762
- const startEvent = {
1763
- runId,
1764
- flowId: flow2.id,
1765
- input: validated,
1766
- at: startedAt
1767
- };
1768
- await fireHook(
1769
- flow2.onStart,
1770
- startEvent,
1771
- "flow.onStart",
1772
- dispatchDeps
1773
- );
1774
- await fireHook(
1775
- config.hooks?.onFlowStart,
1776
- startEvent,
1777
- "onFlowStart",
1778
- dispatchDeps
1779
- );
1780
- await advance(dispatchDeps, runId);
2390
+ await startRunInternal({ flow: flow2, validatedInput: validated, runId });
1781
2391
  return runId;
1782
2392
  },
1783
2393
  async signal(runId, signalName, payload) {
@@ -1863,6 +2473,21 @@ async function nagi(config) {
1863
2473
  );
1864
2474
  await advance(dispatchDeps, runId);
1865
2475
  },
2476
+ async cancel(runId, opts) {
2477
+ await cancelRunRecursive(runId, {
2478
+ cause: "explicit",
2479
+ reason: opts?.reason ?? "explicit wf.cancel()"
2480
+ });
2481
+ },
2482
+ operator() {
2483
+ return makeOperator({
2484
+ deps: dispatchDeps,
2485
+ clock,
2486
+ flowsById,
2487
+ cancelRunRecursive,
2488
+ ...config.logger !== void 0 ? { logger: config.logger } : {}
2489
+ });
2490
+ },
1866
2491
  worker(workerConfig) {
1867
2492
  if (config.flows.length === 0) {
1868
2493
  throw new NagiRuntimeError(
@@ -1888,6 +2513,7 @@ async function nagi(config) {
1888
2513
  const fireHooks = opts.fireHooks !== false;
1889
2514
  const baseDeps = fireHooks ? dispatchDeps : { ...dispatchDeps, fireHooks: false };
1890
2515
  let replayDeps = baseDeps;
2516
+ let effectiveFlow = liveFlow;
1891
2517
  const pinned = runState.flowHash;
1892
2518
  if (pinned !== void 0) {
1893
2519
  const liveHash = flowHashById.get(liveFlow.id);
@@ -1910,12 +2536,99 @@ async function nagi(config) {
1910
2536
  liveFlow
1911
2537
  );
1912
2538
  replayDeps = { ...baseDeps, flowFor: async () => synthesized };
2539
+ effectiveFlow = synthesized;
2540
+ }
2541
+ }
2542
+ if (opts.from !== void 0) {
2543
+ if (runState.status === "running") {
2544
+ throw new NagiRuntimeError(
2545
+ `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.`
2546
+ );
2547
+ }
2548
+ if (!(opts.from in effectiveFlow.steps)) {
2549
+ throw new NagiValidationError([
2550
+ {
2551
+ message: `replay({ from }): step "${opts.from}" is not a step in flow "${effectiveFlow.id}".`,
2552
+ path: ["from"]
2553
+ }
2554
+ ]);
2555
+ }
2556
+ const cascade = descendantsOf(effectiveFlow, opts.from);
2557
+ const at = clock.now();
2558
+ for (const stepId of cascade) {
2559
+ const fact = stepId === opts.from ? { kind: "step.reset", runId, at, stepId } : {
2560
+ kind: "step.reset",
2561
+ runId,
2562
+ at,
2563
+ stepId,
2564
+ cascadedFrom: opts.from
2565
+ };
2566
+ await config.store.appendFact(runId, fact);
1913
2567
  }
1914
2568
  }
1915
2569
  await advance(replayDeps, runId);
1916
2570
  if (!fireHooks) await drainInline(replayDeps);
2571
+ },
2572
+ async queryRuns(opts = {}) {
2573
+ if (opts.latest === true) {
2574
+ if (opts.limit !== void 0 || opts.cursor !== void 0) {
2575
+ throw new NagiValidationError([
2576
+ {
2577
+ message: "queryRuns: `latest: true` is incompatible with `limit` / `cursor` \u2014 `latest` returns at most one row.",
2578
+ path: ["latest"]
2579
+ }
2580
+ ]);
2581
+ }
2582
+ }
2583
+ return config.store.queryRuns(opts);
2584
+ },
2585
+ async pruneFacts(opts) {
2586
+ if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
2587
+ throw new NagiValidationError([
2588
+ {
2589
+ message: "pruneFacts: `olderThan` must be a valid Date.",
2590
+ path: ["olderThan"]
2591
+ }
2592
+ ]);
2593
+ }
2594
+ const statuses = opts.statuses ?? [
2595
+ "completed"
2596
+ ];
2597
+ for (const s of statuses) {
2598
+ if (s !== "completed" && s !== "failed" && s !== "canceled") {
2599
+ throw new NagiValidationError([
2600
+ {
2601
+ message: `pruneFacts: status "${s}" is not prunable. Allowed: "completed" | "failed" | "canceled".`,
2602
+ path: ["statuses"]
2603
+ }
2604
+ ]);
2605
+ }
2606
+ }
2607
+ const batchSize = opts.batchSize ?? 1e3;
2608
+ if (!Number.isInteger(batchSize) || batchSize < 1) {
2609
+ throw new NagiValidationError([
2610
+ {
2611
+ message: "pruneFacts: `batchSize` must be a positive integer.",
2612
+ path: ["batchSize"]
2613
+ }
2614
+ ]);
2615
+ }
2616
+ const keepSummary = opts.keepSummary ?? true;
2617
+ return config.store.pruneFacts({
2618
+ olderThan: opts.olderThan,
2619
+ statuses,
2620
+ batchSize,
2621
+ keepSummary
2622
+ });
1917
2623
  }
1918
2624
  };
2625
+ Object.defineProperty(wf, "__dispatchDeps", {
2626
+ value: dispatchDeps,
2627
+ enumerable: false,
2628
+ writable: false,
2629
+ configurable: false
2630
+ });
2631
+ return wf;
1919
2632
  }
1920
2633
  function mintRunId() {
1921
2634
  return `run-${crypto.randomUUID()}`;
@@ -1928,6 +2641,161 @@ async function drainInline(deps) {
1928
2641
  for (const msg of messages) await dispatchMessage(deps, msg);
1929
2642
  }
1930
2643
  }
2644
+ function makeOperator(o) {
2645
+ const { deps, clock, flowsById, cancelRunRecursive } = o;
2646
+ const store = deps.store;
2647
+ function resolveFlow(flowId, runId) {
2648
+ const flow2 = flowsById.get(flowId);
2649
+ if (!flow2) {
2650
+ throw new NagiRuntimeError(
2651
+ `Run ${runId} references flow "${flowId}" which is not registered with nagi().`
2652
+ );
2653
+ }
2654
+ return flow2;
2655
+ }
2656
+ async function skip(runId, stepId, opts) {
2657
+ if (typeof opts.actor !== "string" || opts.actor.length === 0) {
2658
+ throw new NagiValidationError([
2659
+ {
2660
+ message: "operator.skip: opts.actor must be a non-empty string",
2661
+ path: ["actor"]
2662
+ }
2663
+ ]);
2664
+ }
2665
+ const cascade = opts.cascade ?? "skip";
2666
+ const state = await store.loadRunState(runId);
2667
+ const flow2 = resolveFlow(state.flowId, runId);
2668
+ if (!(stepId in flow2.steps)) {
2669
+ throw new NagiValidationError([
2670
+ {
2671
+ message: `operator.skip: step "${stepId}" is not a step in flow "${flow2.id}".`,
2672
+ path: ["stepId"]
2673
+ }
2674
+ ]);
2675
+ }
2676
+ const stepState = state.steps[stepId];
2677
+ if (stepState !== void 0 && (stepState.status === "completed" || stepState.status === "failed" || stepState.status === "skipped" || stepState.status === "canceled")) {
2678
+ o.logger?.info("nagi: operator.skip noop \u2014 step already terminal", {
2679
+ runId,
2680
+ stepId,
2681
+ status: stepState.status
2682
+ });
2683
+ return;
2684
+ }
2685
+ if (state.status === "completed" || state.status === "failed" || state.status === "canceled") {
2686
+ throw new NagiRuntimeError(
2687
+ `operator.skip: run ${runId} is already terminal (${state.status}); cannot skip step "${stepId}".`
2688
+ );
2689
+ }
2690
+ const fact = {
2691
+ kind: "step.skipped",
2692
+ runId,
2693
+ at: clock.now(),
2694
+ stepId,
2695
+ reason: "manual",
2696
+ actor: opts.actor,
2697
+ cascade,
2698
+ ...opts.note !== void 0 ? { note: opts.note } : {}
2699
+ };
2700
+ await store.appendFact(runId, fact);
2701
+ await advance(deps, runId);
2702
+ }
2703
+ async function waitForStepToSettle(runId, stepId, attempt, deadlineMs) {
2704
+ const start = Date.now();
2705
+ while (Date.now() - start < deadlineMs) {
2706
+ const s = await store.loadRunState(runId);
2707
+ const ss = s.steps[stepId];
2708
+ if (ss === void 0) return;
2709
+ if (ss.status === "completed" || ss.status === "failed" || ss.status === "skipped" || ss.status === "canceled") {
2710
+ return;
2711
+ }
2712
+ if (s.status === "completed" || s.status === "failed" || s.status === "canceled") {
2713
+ return;
2714
+ }
2715
+ if (ss.attempts > attempt) return;
2716
+ await new Promise((r) => setTimeout(r, 50));
2717
+ }
2718
+ throw new NagiRuntimeError(
2719
+ `operator.retry: timed out after ${deadlineMs}ms waiting for step "${stepId}" (attempt ${attempt}) to honor abort signal. Handler may be ignoring ctx.signal.`
2720
+ );
2721
+ }
2722
+ async function retry(runId, stepId, opts) {
2723
+ if (typeof opts.actor !== "string" || opts.actor.length === 0) {
2724
+ throw new NagiValidationError([
2725
+ {
2726
+ message: "operator.retry: opts.actor must be a non-empty string",
2727
+ path: ["actor"]
2728
+ }
2729
+ ]);
2730
+ }
2731
+ const state = await store.loadRunState(runId);
2732
+ if (state.status === "canceled") {
2733
+ throw new NagiRuntimeError(
2734
+ `operator.retry: run ${runId} is canceled; cannot retry. Start a new run instead.`
2735
+ );
2736
+ }
2737
+ const flow2 = resolveFlow(state.flowId, runId);
2738
+ if (!(stepId in flow2.steps)) {
2739
+ throw new NagiValidationError([
2740
+ {
2741
+ message: `operator.retry: step "${stepId}" is not a step in flow "${flow2.id}".`,
2742
+ path: ["stepId"]
2743
+ }
2744
+ ]);
2745
+ }
2746
+ const stepState = state.steps[stepId];
2747
+ if (stepState !== void 0 && stepState.status === "running") {
2748
+ const abortFact = {
2749
+ kind: "step.abort-requested",
2750
+ runId,
2751
+ at: clock.now(),
2752
+ stepId,
2753
+ attempt: stepState.attempts,
2754
+ actor: opts.actor,
2755
+ ...opts.note !== void 0 ? { note: opts.note } : {}
2756
+ };
2757
+ await store.appendFact(runId, abortFact);
2758
+ await waitForStepToSettle(runId, stepId, stepState.attempts, 3e4);
2759
+ }
2760
+ const cascade = descendantsOf(flow2, stepId);
2761
+ const at = clock.now();
2762
+ for (const id of cascade) {
2763
+ const fact = id === stepId ? {
2764
+ kind: "step.reset",
2765
+ runId,
2766
+ at,
2767
+ stepId: id,
2768
+ actor: opts.actor,
2769
+ ...opts.note !== void 0 ? { note: opts.note } : {}
2770
+ } : {
2771
+ kind: "step.reset",
2772
+ runId,
2773
+ at,
2774
+ stepId: id,
2775
+ cascadedFrom: stepId
2776
+ };
2777
+ await store.appendFact(runId, fact);
2778
+ }
2779
+ await advance(deps, runId);
2780
+ }
2781
+ async function abort(runId, opts) {
2782
+ if (typeof opts.actor !== "string" || opts.actor.length === 0) {
2783
+ throw new NagiValidationError([
2784
+ {
2785
+ message: "operator.abort: opts.actor must be a non-empty string",
2786
+ path: ["actor"]
2787
+ }
2788
+ ]);
2789
+ }
2790
+ await cancelRunRecursive(runId, {
2791
+ cause: "operator",
2792
+ reason: opts.note ?? `aborted by operator ${opts.actor}`,
2793
+ actor: opts.actor,
2794
+ ...opts.note !== void 0 ? { note: opts.note } : {}
2795
+ });
2796
+ }
2797
+ return { skip, retry, abort };
2798
+ }
1931
2799
  async function validate(schema, value) {
1932
2800
  const result = await schema["~standard"].validate(value);
1933
2801
  if ("issues" in result && result.issues !== void 0) {