@bastani/atomic 0.9.68 → 0.9.69

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.
Files changed (144) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/CHANGELOG.md +20 -0
  7. package/dist/builtin/workflows/builtin/{chunk-95r61ve5.js → chunk-3gk3k003.js} +1 -1
  8. package/dist/builtin/workflows/builtin/{chunk-qbthhjjk.js → chunk-6bgw5p0e.js} +1 -1
  9. package/dist/builtin/workflows/builtin/{chunk-rv4xxwd6.js → chunk-k8930apc.js} +101 -37
  10. package/dist/builtin/workflows/builtin/goal.js +2 -2
  11. package/dist/builtin/workflows/builtin/index.js +3 -3
  12. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  13. package/dist/builtin/workflows/package.json +1 -1
  14. package/dist/builtin/workflows/src/extension/index.bundle.mjs +740 -453
  15. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +563 -280
  16. package/dist/builtin/workflows/src/index.js +549 -266
  17. package/dist/builtin/workflows/src/local-worker-entry.mjs +563 -280
  18. package/dist/core/agent-session-boundaries.d.ts.map +1 -1
  19. package/dist/core/agent-session-boundaries.js +14 -1
  20. package/dist/core/agent-session-boundaries.js.map +1 -1
  21. package/dist/core/agent-session-events.d.ts +6 -0
  22. package/dist/core/agent-session-events.d.ts.map +1 -1
  23. package/dist/core/agent-session-events.js +99 -20
  24. package/dist/core/agent-session-events.js.map +1 -1
  25. package/dist/core/agent-session-held-input.d.ts +44 -0
  26. package/dist/core/agent-session-held-input.d.ts.map +1 -0
  27. package/dist/core/agent-session-held-input.js +76 -0
  28. package/dist/core/agent-session-held-input.js.map +1 -0
  29. package/dist/core/agent-session-message-queue.d.ts +6 -2
  30. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  31. package/dist/core/agent-session-message-queue.js +29 -7
  32. package/dist/core/agent-session-message-queue.js.map +1 -1
  33. package/dist/core/agent-session-methods.d.ts +4 -2
  34. package/dist/core/agent-session-methods.d.ts.map +1 -1
  35. package/dist/core/agent-session-methods.js.map +1 -1
  36. package/dist/core/agent-session-persistence-failures.d.ts +19 -0
  37. package/dist/core/agent-session-persistence-failures.d.ts.map +1 -0
  38. package/dist/core/agent-session-persistence-failures.js +39 -0
  39. package/dist/core/agent-session-persistence-failures.js.map +1 -0
  40. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  41. package/dist/core/agent-session-persistent-custom-messages.js +3 -0
  42. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  43. package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
  44. package/dist/core/agent-session-post-tool-compaction.js +5 -1
  45. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  46. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  47. package/dist/core/agent-session-prompt.js +156 -16
  48. package/dist/core/agent-session-prompt.js.map +1 -1
  49. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  50. package/dist/core/agent-session-tool-hooks.js +14 -3
  51. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  52. package/dist/core/agent-session.d.ts +5 -1
  53. package/dist/core/agent-session.d.ts.map +1 -1
  54. package/dist/core/agent-session.js +5 -1
  55. package/dist/core/agent-session.js.map +1 -1
  56. package/dist/core/extensions/runner-context.d.ts +3 -0
  57. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  58. package/dist/core/extensions/runner-context.js +10 -2
  59. package/dist/core/extensions/runner-context.js.map +1 -1
  60. package/dist/core/extensions/runner.d.ts.map +1 -1
  61. package/dist/core/extensions/runner.js +1 -0
  62. package/dist/core/extensions/runner.js.map +1 -1
  63. package/dist/core/extensions/workflow-run-control.d.ts +6 -0
  64. package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
  65. package/dist/core/extensions/workflow-run-control.js.map +1 -1
  66. package/dist/core/queued-input-admission.d.ts +2 -0
  67. package/dist/core/queued-input-admission.d.ts.map +1 -1
  68. package/dist/core/queued-input-admission.js +4 -0
  69. package/dist/core/queued-input-admission.js.map +1 -1
  70. package/dist/core/storage/errors.d.ts +2 -0
  71. package/dist/core/storage/errors.d.ts.map +1 -1
  72. package/dist/core/storage/errors.js +9 -0
  73. package/dist/core/storage/errors.js.map +1 -1
  74. package/dist/core/storage/storage-status.d.ts +2 -2
  75. package/dist/core/storage/storage-status.d.ts.map +1 -1
  76. package/dist/core/storage/storage-status.js +2 -10
  77. package/dist/core/storage/storage-status.js.map +1 -1
  78. package/dist/core/system-prompt.d.ts.map +1 -1
  79. package/dist/core/system-prompt.js +16 -3
  80. package/dist/core/system-prompt.js.map +1 -1
  81. package/dist/core/tools/conflict-registry.d.ts +17 -0
  82. package/dist/core/tools/conflict-registry.d.ts.map +1 -1
  83. package/dist/core/tools/conflict-registry.js +80 -0
  84. package/dist/core/tools/conflict-registry.js.map +1 -1
  85. package/dist/core/tools/find.d.ts.map +1 -1
  86. package/dist/core/tools/find.js +23 -4
  87. package/dist/core/tools/find.js.map +1 -1
  88. package/dist/core/tools/history-protocol.d.ts +29 -0
  89. package/dist/core/tools/history-protocol.d.ts.map +1 -0
  90. package/dist/core/tools/history-protocol.js +438 -0
  91. package/dist/core/tools/history-protocol.js.map +1 -0
  92. package/dist/core/tools/read.d.ts.map +1 -1
  93. package/dist/core/tools/read.js +4 -4
  94. package/dist/core/tools/read.js.map +1 -1
  95. package/dist/core/tools/resource-selectors.d.ts +28 -0
  96. package/dist/core/tools/resource-selectors.d.ts.map +1 -1
  97. package/dist/core/tools/resource-selectors.js +73 -13
  98. package/dist/core/tools/resource-selectors.js.map +1 -1
  99. package/dist/core/tools/search-line-ranges.d.ts +5 -0
  100. package/dist/core/tools/search-line-ranges.d.ts.map +1 -1
  101. package/dist/core/tools/search-line-ranges.js +7 -3
  102. package/dist/core/tools/search-line-ranges.js.map +1 -1
  103. package/dist/core/tools/search.d.ts.map +1 -1
  104. package/dist/core/tools/search.js +5 -5
  105. package/dist/core/tools/search.js.map +1 -1
  106. package/dist/core/tools/shell-plain-words.d.ts +8 -0
  107. package/dist/core/tools/shell-plain-words.d.ts.map +1 -0
  108. package/dist/core/tools/shell-plain-words.js +139 -0
  109. package/dist/core/tools/shell-plain-words.js.map +1 -0
  110. package/dist/core/tools/write.d.ts.map +1 -1
  111. package/dist/core/tools/write.js +8 -45
  112. package/dist/core/tools/write.js.map +1 -1
  113. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  114. package/dist/modes/interactive/interactive-input-handling.js +4 -0
  115. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  116. package/dist/modes/interactive/interactive-process-lifecycle.js +4 -0
  117. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  118. package/dist/modes/interactive/interactive-queueing.d.ts +9 -1
  119. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  120. package/dist/modes/interactive/interactive-queueing.js +82 -9
  121. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  122. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  123. package/dist/modes/interactive-engine/isolated-runtime.js +15 -0
  124. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  125. package/dist/modes/print-mode.d.ts.map +1 -1
  126. package/dist/modes/print-mode.js +5 -1
  127. package/dist/modes/print-mode.js.map +1 -1
  128. package/dist/modes/rpc/rpc-command-handler.d.ts +6 -1
  129. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  130. package/dist/modes/rpc/rpc-command-handler.js +16 -1
  131. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  132. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  133. package/dist/modes/rpc/rpc-mode.js +1 -0
  134. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  135. package/docs/compaction.md +1 -1
  136. package/docs/extensions/api-reference.md +3 -1
  137. package/docs/rpc/protocol.md +1 -1
  138. package/docs/sdk.md +3 -1
  139. package/docs/sessions.md +17 -0
  140. package/docs/storage.md +2 -0
  141. package/docs/tools.md +8 -4
  142. package/docs/usage.md +1 -1
  143. package/npm-shrinkwrap.json +75 -53
  144. package/package.json +5 -5
@@ -3526,6 +3526,18 @@ function reciprocalWorkflowRootRunId(runById, runId) {
3526
3526
  }
3527
3527
  return;
3528
3528
  }
3529
+ function isRunLookup(source) {
3530
+ return "run" in source;
3531
+ }
3532
+ function runsInSource(source) {
3533
+ return isRunLookup(source) ? source.runs() : source;
3534
+ }
3535
+ function findRunInSource(source, runId) {
3536
+ return isRunLookup(source) ? source.run(runId) : source.find((run) => run.id === runId);
3537
+ }
3538
+ function runsByIdOf(source) {
3539
+ return isRunLookup(source) ? { get: (runId) => source.run(runId) } : new Map(source.map((run) => [run.id, run]));
3540
+ }
3529
3541
  function index(items, cache) {
3530
3542
  let byId = cache.get(items);
3531
3543
  if (byId === undefined) {
@@ -3544,6 +3556,29 @@ function findSnapshotRun(runs, runId) {
3544
3556
  function findSnapshotStage(stages, stageId) {
3545
3557
  return Object.isFrozen(stages) ? index(stages, stageIndexes).get(stageId) : stages.find((stage) => stage.id === stageId);
3546
3558
  }
3559
+ function childRunsInSource(source, parentRunId, parentStageId) {
3560
+ if (isRunLookup(source) && source.childRuns !== undefined)
3561
+ return source.childRuns(parentRunId, parentStageId);
3562
+ return runsInSource(source).filter((run) => run.parentRunId === parentRunId && (parentStageId === undefined || run.parentStageId === parentStageId));
3563
+ }
3564
+ function invocationRunsInSource(source, rootRunId) {
3565
+ const byId = runsByIdOf(source);
3566
+ const inInvocation = (run) => reciprocalWorkflowRootRunId(byId, run.id) === rootRunId;
3567
+ if (!isRunLookup(source) || source.childRuns === undefined || source.runPosition === undefined)
3568
+ return runsInSource(source).filter(inInvocation);
3569
+ const root = source.run(rootRunId);
3570
+ if (root === undefined)
3571
+ return [];
3572
+ const seen = new Set([root.id]);
3573
+ const found = [root];
3574
+ for (let index = 0;index < found.length; index++)
3575
+ for (const child of source.childRuns(found[index].id))
3576
+ if (!seen.has(child.id)) {
3577
+ seen.add(child.id);
3578
+ found.push(child);
3579
+ }
3580
+ return found.filter(inInvocation).sort((left, right) => source.runPosition(left.id) - source.runPosition(right.id));
3581
+ }
3547
3582
  var runIndexes, stageIndexes;
3548
3583
  var init_workflow_run_ownership = __esm(() => {
3549
3584
  runIndexes = new WeakMap;
@@ -3772,19 +3807,20 @@ function bindRunDurableBackend(run, backend) {
3772
3807
  Object.defineProperty(run, workflowRunBackend, { value: backend });
3773
3808
  }
3774
3809
  function availableRunDurableBackend(runs, runId) {
3775
- const target = resolveRunIdTarget(runId, runs.map((run) => run.id));
3810
+ const target = resolveRunIdTarget(runId, isRunIdPrefix(runId) ? runsInSource(runs).map((run) => run.id) : []);
3776
3811
  const id = target.kind === "exact" || target.kind === "unique_prefix" ? target.runId : runId;
3777
3812
  const rootRunId = durableRootRunIdForRun(runs, id);
3778
- return runs.find((run) => run.id === rootRunId)?.[workflowRunBackend];
3813
+ const rootRun = rootRunId === undefined ? undefined : findRunInSource(runs, rootRunId);
3814
+ return rootRun?.[workflowRunBackend];
3779
3815
  }
3780
3816
  function durableRootRunIdForRun(runs, runId) {
3781
- return reciprocalWorkflowRootRunId(new Map(runs.map((run) => [run.id, run])), runId);
3817
+ return reciprocalWorkflowRootRunId(runsByIdOf(runs), runId);
3782
3818
  }
3783
3819
  function durableBackendForRun(backend, runs, runId) {
3784
3820
  const rootRunId = durableRootRunIdForRun(runs, runId);
3785
3821
  if (rootRunId === undefined)
3786
3822
  return;
3787
- const runById = new Map(runs.map((run) => [run.id, run]));
3823
+ const runById = runsByIdOf(runs);
3788
3824
  const rootBackend = availableRunDurableBackend(runs, rootRunId) ?? backend;
3789
3825
  if (rootRunId === runId)
3790
3826
  return rootBackend;
@@ -3822,7 +3858,7 @@ function bindStoreDurableBackend(store, backend) {
3822
3858
  store[workflowStoreBackend] = backend;
3823
3859
  }
3824
3860
  function availableStoreDurableBackend(store, runId) {
3825
- return (store !== undefined && runId !== undefined ? availableRunDurableBackend(store.runs(), runId) : undefined) ?? store?.[workflowStoreBackend];
3861
+ return (store !== undefined && runId !== undefined ? availableRunDurableBackend(store, runId) : undefined) ?? store?.[workflowStoreBackend];
3826
3862
  }
3827
3863
  function requireStoreDurableBackend(store, runId) {
3828
3864
  const backend = availableStoreDurableBackend(store, runId);
@@ -4692,6 +4728,8 @@ function createStoreState() {
4692
4728
  return {
4693
4729
  runs: [],
4694
4730
  runPositions: new Map,
4731
+ childRunIds: new Map,
4732
+ childRunLinks: new Map,
4695
4733
  notices: [],
4696
4734
  listeners: new Set,
4697
4735
  invalidationListeners: new Set,
@@ -4703,11 +4741,41 @@ function createStoreState() {
4703
4741
  }
4704
4742
  function reindexRuns(state) {
4705
4743
  state.runPositions.clear();
4744
+ state.childRunIds.clear();
4745
+ state.childRunLinks.clear();
4706
4746
  state.runs.forEach((run, position) => {
4707
- if (!state.runPositions.has(run.id))
4708
- state.runPositions.set(run.id, position);
4747
+ if (state.runPositions.has(run.id))
4748
+ return;
4749
+ state.runPositions.set(run.id, position);
4750
+ indexChildRun(state, run);
4709
4751
  });
4710
4752
  }
4753
+ function indexChildRun(state, run) {
4754
+ unindexChildRun(state, run.id);
4755
+ if (run.parentRunId === undefined)
4756
+ return;
4757
+ const byStage = state.childRunIds.get(run.parentRunId) ?? new Map;
4758
+ state.childRunIds.set(run.parentRunId, byStage);
4759
+ const ids = byStage.get(run.parentStageId) ?? new Set;
4760
+ byStage.set(run.parentStageId, ids);
4761
+ ids.add(run.id);
4762
+ state.childRunLinks.set(run.id, { parentRunId: run.parentRunId, parentStageId: run.parentStageId });
4763
+ }
4764
+ function unindexChildRun(state, runId) {
4765
+ const link = state.childRunLinks.get(runId);
4766
+ if (link === undefined)
4767
+ return;
4768
+ state.childRunLinks.delete(runId);
4769
+ const byStage = state.childRunIds.get(link.parentRunId);
4770
+ const ids = byStage?.get(link.parentStageId);
4771
+ if (byStage === undefined || ids === undefined)
4772
+ return;
4773
+ ids.delete(runId);
4774
+ if (ids.size === 0)
4775
+ byStage.delete(link.parentStageId);
4776
+ if (byStage.size === 0)
4777
+ state.childRunIds.delete(link.parentRunId);
4778
+ }
4711
4779
  function runPosition(state, runId) {
4712
4780
  const position = state.runPositions.get(runId);
4713
4781
  if (position !== undefined && state.runs[position]?.id === runId)
@@ -4751,13 +4819,14 @@ function createStoreContext(state = createStoreState()) {
4751
4819
  batchedChanges?.push(change);
4752
4820
  return;
4753
4821
  }
4754
- observation.capture(change === undefined ? undefined : [change]);
4755
- publish();
4822
+ const changes = change === undefined ? undefined : [change];
4823
+ observation.capture(changes);
4824
+ publish(changes);
4756
4825
  }
4757
- function publish() {
4826
+ function publish(changes) {
4758
4827
  for (const fn of state.invalidationListeners) {
4759
4828
  try {
4760
- fn();
4829
+ fn(changes);
4761
4830
  } catch {}
4762
4831
  }
4763
4832
  if (state.listeners.size > 0) {
@@ -4784,7 +4853,7 @@ function createStoreContext(state = createStoreState()) {
4784
4853
  batchedNotification = false;
4785
4854
  batchedChanges = [];
4786
4855
  observation.capture(changes);
4787
- publish();
4856
+ publish(changes);
4788
4857
  }
4789
4858
  }
4790
4859
  }
@@ -4796,22 +4865,40 @@ function createStoreContext(state = createStoreState()) {
4796
4865
  const position = runPosition(state, run.id);
4797
4866
  if (position !== undefined) {
4798
4867
  state.runs[position] = run;
4868
+ indexChildRun(state, run);
4799
4869
  return;
4800
4870
  }
4801
4871
  state.runPositions.set(run.id, state.runs.length);
4802
4872
  state.runs.push(run);
4873
+ indexChildRun(state, run);
4803
4874
  }
4804
4875
  function removeRunAt(position) {
4805
4876
  const [removed] = state.runs.splice(position, 1);
4806
4877
  if (removed === undefined)
4807
4878
  return;
4808
4879
  state.runPositions.delete(removed.id);
4880
+ unindexChildRun(state, removed.id);
4809
4881
  for (let index = position;index < state.runs.length; index++)
4810
4882
  state.runPositions.set(state.runs[index].id, index);
4811
4883
  }
4812
4884
  function clearRuns() {
4813
4885
  state.runs.length = 0;
4814
4886
  state.runPositions.clear();
4887
+ state.childRunIds.clear();
4888
+ state.childRunLinks.clear();
4889
+ }
4890
+ function childRuns(parentRunId, parentStageId) {
4891
+ if (state.runPositions.size !== state.runs.length)
4892
+ reindexRuns(state);
4893
+ const byStage = state.childRunIds.get(parentRunId);
4894
+ if (byStage === undefined)
4895
+ return [];
4896
+ const ids = parentStageId === undefined ? [...byStage.values()].flatMap((set) => [...set]) : [...byStage.get(parentStageId) ?? []];
4897
+ return ids.map((id) => findRun(id)).filter((run) => run !== undefined && run.parentRunId === parentRunId && (parentStageId === undefined || run.parentStageId === parentStageId)).sort((left, right) => runPosition(state, left.id) - runPosition(state, right.id));
4898
+ }
4899
+ function reparentRun(run, parentStageId) {
4900
+ run.parentStageId = parentStageId;
4901
+ indexChildRun(state, run);
4815
4902
  }
4816
4903
  function findStage(run, stageId) {
4817
4904
  return run.stages.find((s) => s.id === stageId);
@@ -4868,6 +4955,8 @@ function createStoreContext(state = createStoreState()) {
4868
4955
  bumpAndNotify,
4869
4956
  findRun,
4870
4957
  runPosition: (runId) => runPosition(state, runId),
4958
+ childRuns,
4959
+ reparentRun,
4871
4960
  placeRun,
4872
4961
  removeRunAt,
4873
4962
  clearRuns,
@@ -5040,13 +5129,13 @@ function recordPendingStageMessageDeliveries(messages, runId, messageId, records
5040
5129
  result[index] = next;
5041
5130
  return result;
5042
5131
  }
5043
- function compactStickyStageMessageDeliveries(messages, runs) {
5044
- const finished = new Set(runs.flatMap((run) => run.stages.filter((stage) => stage.status === "completed" || stage.status === "skipped").map((stage) => JSON.stringify([run.id, stage.id]))));
5132
+ function compactStickyStageMessageDeliveries(messages, findRun) {
5133
+ const finished = (runId, stageId) => findRun(runId)?.stages.some((stage) => stage.id === stageId && (stage.status === "completed" || stage.status === "skipped")) === true;
5045
5134
  let changed = false;
5046
5135
  const next = messages.map((entry) => {
5047
5136
  if (entry.sticky !== true || entry.deliveries === undefined)
5048
5137
  return entry;
5049
- const deliveries = entry.deliveries.filter((delivery) => !finished.has(JSON.stringify([delivery.runId, delivery.stageId])));
5138
+ const deliveries = entry.deliveries.filter((delivery) => !finished(delivery.runId, delivery.stageId));
5050
5139
  if (deliveries.length === entry.deliveries.length)
5051
5140
  return entry;
5052
5141
  changed = true;
@@ -5215,8 +5304,8 @@ class PendingStageTransitionLedger {
5215
5304
  this.reconciledVersion = version;
5216
5305
  return result;
5217
5306
  }
5218
- async compact(backend, runId, messages, runs, archiveSettled) {
5219
- const stageStatus = createStageStatusLookup(runs);
5307
+ async compact(backend, runId, messages, findRun, archiveSettled) {
5308
+ const stageStatus = createStageStatusLookup(findRun);
5220
5309
  const endedStages = [];
5221
5310
  const dirty = new Set;
5222
5311
  for (const [deliveryRunId, byStage] of this.stages) {
@@ -5314,17 +5403,8 @@ class PendingStageTransitionLedger {
5314
5403
  function isCompactingBackend(backend) {
5315
5404
  return backend.archivePendingStageDeliveryReceipt !== undefined && backend.hasPendingStageDeliveryReceipt !== undefined;
5316
5405
  }
5317
- function createStageStatusLookup(runs) {
5318
- let runById;
5319
- return (runId, stageId) => {
5320
- if (runById === undefined) {
5321
- runById = new Map;
5322
- for (const run of runs)
5323
- if (!runById.has(run.id))
5324
- runById.set(run.id, run);
5325
- }
5326
- return runById.get(runId)?.stages.find((stage) => stage.id === stageId)?.status;
5327
- };
5406
+ function createStageStatusLookup(findRun) {
5407
+ return (runId, stageId) => findRun(runId)?.stages.find((stage) => stage.id === stageId)?.status;
5328
5408
  }
5329
5409
  function isEndedStageStatus(status) {
5330
5410
  return status === "completed" || status === "skipped" || status === "failed";
@@ -5364,6 +5444,7 @@ var init_pending_stage_transition_ledger = () => {};
5364
5444
 
5365
5445
  // dist/builtin/workflows/src/shared/store-pending-stage-delivery-methods.ts
5366
5446
  function createPendingStageDeliveryStoreMethods(context) {
5447
+ const runs = { run: context.findRun, runs: () => context.state.runs };
5367
5448
  const ledgers = new PendingStageLedgers;
5368
5449
  const batches = new PendingStageTransitionBatches(context, ledgers);
5369
5450
  return {
@@ -5386,8 +5467,8 @@ function createPendingStageDeliveryStoreMethods(context) {
5386
5467
  const run = context.findRun(input.runId);
5387
5468
  if (run === undefined)
5388
5469
  return;
5389
- const availableBackend = availableRunDurableBackend(context.state.runs, input.runId) ?? context.backend;
5390
- const backend = availableBackend === undefined ? undefined : durableBackendForRun(availableBackend, context.state.runs, input.runId);
5470
+ const availableBackend = availableRunDurableBackend(runs, input.runId) ?? context.backend;
5471
+ const backend = availableBackend === undefined ? undefined : durableBackendForRun(availableBackend, runs, input.runId);
5391
5472
  const receipt = await backend?.readSettledPendingStageMessage?.(input.runId, input.message.id);
5392
5473
  const result = queueStageMessage(receipt === undefined ? batch.messages(run) : [...batch.messages(run), receipt], input, undefined, undefined, resolvePendingStageIdentity(run, input.stageKey));
5393
5474
  if (!result.ok) {
@@ -5610,7 +5691,7 @@ class PendingStageTransitionBatch {
5610
5691
  }
5611
5692
  if (messages !== run.pendingStageMessages) {
5612
5693
  run.pendingStageMessages = [...messages];
5613
- this.context.bumpAndNotify();
5694
+ this.context.bumpAndNotify({ runId: run.id });
5614
5695
  }
5615
5696
  }
5616
5697
  async apply(backend, runId, messages) {
@@ -5646,7 +5727,7 @@ class PendingStageTransitionBatch {
5646
5727
  const live = this.context.findRun(this.runId) ?? run;
5647
5728
  if (live !== undefined)
5648
5729
  live.pendingStageMessages = [...published];
5649
- this.context.bumpAndNotify();
5730
+ this.context.bumpAndNotify({ runId: this.runId });
5650
5731
  }
5651
5732
  }
5652
5733
  async function compactTransition(backend, runId, messages, context, ledgers, run) {
@@ -5654,9 +5735,9 @@ async function compactTransition(backend, runId, messages, context, ledgers, run
5654
5735
  const reconciled = ledger.reconcile(backend, runId, messages);
5655
5736
  const archiveSettled = backend.archivePendingStageMessage !== undefined && backend.readSettledPendingStageMessage !== undefined ? (entry) => backend.archivePendingStageMessage(runId, entry) : undefined;
5656
5737
  if (isCompactingBackend(backend)) {
5657
- return await ledger.compact(backend, runId, reconciled, context.state.runs, archiveSettled);
5738
+ return await ledger.compact(backend, runId, reconciled, context.findRun, archiveSettled);
5658
5739
  }
5659
- let retained = compactStickyStageMessageDeliveries(reconciled, context.state.runs);
5740
+ let retained = compactStickyStageMessageDeliveries(reconciled, context.findRun);
5660
5741
  if (archiveSettled !== undefined)
5661
5742
  retained = await retainPendingStageMessages(retained, archiveSettled);
5662
5743
  if (run !== undefined)
@@ -5671,7 +5752,7 @@ function reconcileLive(backend, runId, context, ledgers) {
5671
5752
  const recovered = ledgers.for(current).reconcile(backend, runId, messages);
5672
5753
  if (recovered !== messages) {
5673
5754
  current.pendingStageMessages = [...recovered];
5674
- context.bumpAndNotify();
5755
+ context.bumpAndNotify({ runId });
5675
5756
  }
5676
5757
  }
5677
5758
 
@@ -5955,6 +6036,12 @@ function createRunStoreMethods(context) {
5955
6036
  run(runId) {
5956
6037
  return context.findRun(runId);
5957
6038
  },
6039
+ runPosition(runId) {
6040
+ return context.runPosition(runId);
6041
+ },
6042
+ childRuns(parentRunId, parentStageId) {
6043
+ return context.childRuns(parentRunId, parentStageId);
6044
+ },
5958
6045
  notices() {
5959
6046
  return state.notices;
5960
6047
  },
@@ -5997,7 +6084,7 @@ function createRunStoreMethods(context) {
5997
6084
  const run = context.findRun(runId);
5998
6085
  if (run?.parentStageId !== expectedParentStageId || parentStageId === expectedParentStageId)
5999
6086
  return false;
6000
- run.parentStageId = parentStageId;
6087
+ context.reparentRun(run, parentStageId);
6001
6088
  context.bumpAndNotify();
6002
6089
  return true;
6003
6090
  },
@@ -9593,6 +9680,7 @@ class JournalProjection {
9593
9680
  return {
9594
9681
  resumable: this.listResumableWorkflows(),
9595
9682
  completed: this.listCompletedWorkflows(),
9683
+ completedAll: this.listFinishedRootWorkflows(),
9596
9684
  inspectableIds: [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle)).map((rec) => rec.handle.workflowId)
9597
9685
  };
9598
9686
  }
@@ -9624,6 +9712,9 @@ class JournalProjection {
9624
9712
  listCompletedWorkflows() {
9625
9713
  return [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle) && isHistoricalHandle(rec.handle)).map((rec) => toResumableEntry(rec.handle));
9626
9714
  }
9715
+ listFinishedRootWorkflows() {
9716
+ return [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle) && isTerminalStatus(rec.handle.status)).map((rec) => toResumableEntry(rec.handle));
9717
+ }
9627
9718
  toMetadata(workflowId) {
9628
9719
  const rec = this.workflows.get(workflowId);
9629
9720
  if (!rec)
@@ -9682,6 +9773,9 @@ class JournalProjection {
9682
9773
  function isRootWorkflow(handle) {
9683
9774
  return handle.rootWorkflowId === undefined || handle.rootWorkflowId === handle.workflowId;
9684
9775
  }
9776
+ function isTerminalStatus(status) {
9777
+ return status === "completed" || status === "failed" || status === "cancelled";
9778
+ }
9685
9779
  function hasResumeProgress(handle) {
9686
9780
  return handle.completedCheckpoints > 0 || handle.pendingPrompts > 0;
9687
9781
  }
@@ -11576,7 +11670,7 @@ function recordCachedStageWithTracker(store, tracker, runId, name, replayKey, ch
11576
11670
  const stageId = sourceStageId ?? cachedStageId(runId, replayKey);
11577
11671
  let parentIds = tracker.onSpawn(stageId, name);
11578
11672
  const sourceParents = sourceStageId === undefined ? undefined : checkpoint.topology?.parentIds;
11579
- const run = store.runs().find((candidate) => candidate.id === runId);
11673
+ const run = store.run(runId);
11580
11674
  const restored = sourceParents?.map((sourceId) => sourceToReplayedNodeIds?.get(sourceId) ?? run?.stages.find((stage) => stage.id === sourceId || stage.replayedFromStageId === sourceId)?.id);
11581
11675
  if (restored?.every((id) => id !== undefined)) {
11582
11676
  parentIds = restored;
@@ -13547,7 +13641,7 @@ function createWorkflowArtifactRunStateResolver() {
13547
13641
  let durable;
13548
13642
  if (backend !== undefined) {
13549
13643
  try {
13550
- durable = durableRunState(availableRunDurableBackend(store.runs(), runId) ?? backend, runId);
13644
+ durable = durableRunState(availableRunDurableBackend(store, runId) ?? backend, runId);
13551
13645
  } catch {
13552
13646
  backendReady = false;
13553
13647
  return localState === "protected" ? "protected" : undefined;
@@ -15785,7 +15879,8 @@ function runResultFromSnapshot(snapshot) {
15785
15879
  };
15786
15880
  }
15787
15881
  function reconcileTerminalRunResult(runId, runSnapshot, activeStore, fallback, onRunEnd) {
15788
- const canonical = activeStore.runs().find((snapshot) => snapshot.id === runId && isTerminalRunStatus(snapshot.status));
15882
+ const stored = activeStore.run(runId);
15883
+ const canonical = stored !== undefined && isTerminalRunStatus(stored.status) ? stored : undefined;
15789
15884
  const result = canonical !== undefined ? runResultFromSnapshot(canonical) : {
15790
15885
  runId,
15791
15886
  ...fallback,
@@ -16392,7 +16487,7 @@ function continuationPromptAnswer(store, sourceRun, sourceStage) {
16392
16487
  return answer;
16393
16488
  if (!stage.replayed || stage.replayedFromStageId === undefined || run.resumedFromRunId === undefined)
16394
16489
  break;
16395
- const parentRun = store.runs().find((candidate) => candidate.id === run.resumedFromRunId);
16490
+ const parentRun = store.run(run.resumedFromRunId);
16396
16491
  const parentStage = parentRun?.stages.find((candidate) => candidate.id === stage.replayedFromStageId);
16397
16492
  if (parentRun === undefined || parentStage === undefined)
16398
16493
  break;
@@ -61431,7 +61526,24 @@ function isAddressableStageStatus(status) {
61431
61526
  return ADDRESSABLE_STAGE_STATUSES.has(status);
61432
61527
  }
61433
61528
  function workflowBoundarySegments(runs, runId) {
61434
- return createWorkflowBoundarySegmentsResolver(runs)(runId);
61529
+ const source = runs;
61530
+ if (!isRunLookup(source) || source.childRuns === undefined)
61531
+ return createWorkflowBoundarySegmentsResolver(runsInSource(source))(runId);
61532
+ const segments = [];
61533
+ let current = source.run(runId);
61534
+ while (current !== undefined && current.parentRunId !== undefined) {
61535
+ const parent = findRunInSource(source, current.parentRunId);
61536
+ const boundary = parent?.stages.find((stage) => stage.id === current?.parentStageId);
61537
+ if (parent === undefined || boundary === undefined)
61538
+ return;
61539
+ const boundaryName = boundary.name;
61540
+ const byId = parent.stages.filter((stage) => stage.id === boundaryName);
61541
+ const matching = byId.length > 0 ? byId : parent.stages.filter((stage) => stage.name === boundaryName);
61542
+ const children = matching.length === 1 ? childRunsInSource(source, parent.id, matching[0].id) : undefined;
61543
+ segments.unshift(boundaryName.length > 0 && !boundaryName.includes("/") && !boundaryName.includes("*") && children?.length === 1 && children[0]?.id === current.id ? boundaryName : current.id);
61544
+ current = parent;
61545
+ }
61546
+ return current === undefined ? undefined : segments;
61435
61547
  }
61436
61548
  function createWorkflowBoundarySegmentsResolver(runs) {
61437
61549
  const runById = new Map(runs.map((run) => [run.id, run]));
@@ -61484,10 +61596,10 @@ function createWorkflowBoundarySegmentsResolver(runs) {
61484
61596
  };
61485
61597
  }
61486
61598
  function workflowBoundaryHops(runs, runId) {
61487
- return boundaryHopsFrom(new Map(runs.map((run) => [run.id, run])), runId);
61599
+ return boundaryHopsFrom(runsByIdOf(runs), runId);
61488
61600
  }
61489
61601
  function createWorkflowBoundaryHopsResolver(runs) {
61490
- const runById = new Map(runs.map((run) => [run.id, run]));
61602
+ const runById = runsByIdOf(runs);
61491
61603
  const cache = new Map;
61492
61604
  return (runId) => {
61493
61605
  if (cache.has(runId))
@@ -61555,6 +61667,7 @@ function createStagePathPatternIndex(patterns) {
61555
61667
  var ADDRESSABLE_STAGE_STATUSES;
61556
61668
  var init_pending_stage_status = __esm(() => {
61557
61669
  init_store_internal();
61670
+ init_workflow_run_ownership();
61558
61671
  init_workflow_stage_target();
61559
61672
  ADDRESSABLE_STAGE_STATUSES = new Set([
61560
61673
  "pending",
@@ -61619,27 +61732,44 @@ function boundPossibleStageDeliveryStates(states) {
61619
61732
 
61620
61733
  class WorkflowTopologyIndex {
61621
61734
  lineage = [];
61735
+ lineageStarts = new Map;
61622
61736
  runById = new Map;
61623
61737
  roots = new Map;
61624
61738
  hops = new Map;
61625
61739
  refresh(runs) {
61626
61740
  const runById = new Map(runs.map((run) => [run.id, run]));
61627
61741
  const lineage = [];
61742
+ const lineageStarts = new Map;
61628
61743
  for (const run of runs) {
61629
- lineage.push(run.id, run.rootRunId, run.parentRunId, run.parentStageId);
61630
- if (run.parentRunId === undefined)
61631
- continue;
61632
- const parent = runById.get(run.parentRunId);
61633
- const boundary = parent?.stages.find((stage) => stage.id === run.parentStageId);
61634
- lineage.push(parent !== undefined, boundary?.name, authoritativeWorkflowChildRunId(boundary));
61744
+ lineageStarts.set(run.id, lineage.length);
61745
+ pushLineage(lineage, run, runById);
61635
61746
  }
61636
61747
  if (sameValues(lineage, this.lineage))
61637
61748
  return;
61638
61749
  this.lineage = lineage;
61750
+ this.lineageStarts = lineageStarts;
61639
61751
  this.runById = runById;
61640
61752
  this.roots.clear();
61641
61753
  this.hops.clear();
61642
61754
  }
61755
+ holds(source, runIds) {
61756
+ const runs = { get: (runId) => source.run(runId) };
61757
+ const values = [];
61758
+ const unchanged = (run) => {
61759
+ const start = this.lineageStarts.get(run.id);
61760
+ if (start === undefined)
61761
+ return false;
61762
+ values.length = 0;
61763
+ pushLineage(values, run, runs);
61764
+ return values.every((value2, index) => this.lineage[start + index] === value2);
61765
+ };
61766
+ for (const runId of runIds) {
61767
+ const run = source.run(runId);
61768
+ if (run === undefined || !unchanged(run) || !source.childRuns(runId).every(unchanged))
61769
+ return false;
61770
+ }
61771
+ return true;
61772
+ }
61643
61773
  rootOf(runId) {
61644
61774
  if (this.roots.has(runId))
61645
61775
  return this.roots.get(runId);
@@ -61655,6 +61785,14 @@ class WorkflowTopologyIndex {
61655
61785
  return hops;
61656
61786
  }
61657
61787
  }
61788
+ function pushLineage(values, run, runs) {
61789
+ values.push(run.id, run.rootRunId, run.parentRunId, run.parentStageId);
61790
+ if (run.parentRunId === undefined)
61791
+ return;
61792
+ const parent = runs.get(run.parentRunId);
61793
+ const boundary = parent?.stages.find((stage) => stage.id === run.parentStageId);
61794
+ values.push(parent !== undefined, boundary?.name, authoritativeWorkflowChildRunId(boundary));
61795
+ }
61658
61796
  function boundaryHops(runById, runId) {
61659
61797
  const hops = [];
61660
61798
  let current = runById.get(runId);
@@ -61699,12 +61837,12 @@ class PossibleStageRowsIndex {
61699
61837
  this.rootRunId = rootRunId;
61700
61838
  this.topology = topology;
61701
61839
  }
61702
- rows(runs, rootRun, availableBackend) {
61840
+ rows(runs, rootRun, availableBackend, lookup = runs) {
61703
61841
  if (isTerminalRunStatus(rootRun.status))
61704
61842
  return [];
61705
61843
  this.refreshEntries(rootRun.pendingStageMessages ?? []);
61706
- const resolvedBackend = availableRunDurableBackend(runs, this.rootRunId) ?? availableBackend;
61707
- const backend = resolvedBackend === undefined ? undefined : durableBackendForRun(resolvedBackend, runs, this.rootRunId);
61844
+ const resolvedBackend = availableRunDurableBackend(lookup, this.rootRunId) ?? availableBackend;
61845
+ const backend = resolvedBackend === undefined ? undefined : durableBackendForRun(resolvedBackend, lookup, this.rootRunId);
61708
61846
  this.refreshReceipts(backend);
61709
61847
  this.refreshStages(runs);
61710
61848
  for (const state of this.patterns)
@@ -62229,9 +62367,90 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62229
62367
  }
62230
62368
  return index;
62231
62369
  };
62232
- const announceRoutes = () => {
62233
- if (disposed)
62370
+ let rootRunMembers = new Map;
62371
+ const membersOf = (rootRunId) => (rootRunMembers.get(rootRunId) ?? []).flatMap((runId) => {
62372
+ const run = activeStore.run(runId);
62373
+ return run === undefined ? [] : [run];
62374
+ });
62375
+ const dropRoute = (runId) => {
62376
+ announcedRoutes.delete(runId);
62377
+ routeCompletions.delete(runId);
62378
+ possibleStageRowIndexes.delete(runId);
62379
+ };
62380
+ const unpublishedRunIds = new Set;
62381
+ const announceRun = (run, rootRunId, lookups) => {
62382
+ const parentRun = lookups.parentOf(run);
62383
+ const boundary = parentRun?.stages.find((stage) => stage.id === run.parentStageId);
62384
+ const parent = parentRun === undefined || boundary === undefined ? undefined : {
62385
+ runId: parentRun.id,
62386
+ stageKeys: [boundary.id, boundary.name].filter((key) => lookups.childAt(parentRun, key)?.id === run.id)
62387
+ };
62388
+ let possibleStages;
62389
+ if (run.id === rootRunId && isTerminalRunStatus(run.status)) {
62390
+ possibleStageRowIndexes.delete(rootRunId);
62391
+ possibleStages = [];
62392
+ } else if (run.id === rootRunId) {
62393
+ possibleStages = possibleStageRowsIndex(rootRunId).rows(lookups.rowRuns(rootRunId), run, availableStoreDurableBackend(activeStore, rootRunId), lookups.runs);
62394
+ }
62395
+ const announcement = {
62396
+ runId: run.id,
62397
+ group: workflowInvocationIntercomGroup(rootRunId),
62398
+ capability: workflowPendingStageRouteCapability(activeStore, run.id),
62399
+ ...parent === undefined ? {} : { parent },
62400
+ stages: [
62401
+ ...run.stages.filter((stage) => !isNonAgentStage(stage) && workflowInvocationOwnsGroup(workflowInvocationIntercomGroup(rootRunId), stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId))).map((stage) => ({
62402
+ stageId: stage.id,
62403
+ stageName: stage.name,
62404
+ target: stageRouteTarget(lookups.runs, rootRunId, run.id, stage.id, lookups.segments),
62405
+ lifecycle: stage.sessionId === undefined && stage.sessionFile === undefined ? "pending" : "running",
62406
+ routeEligible: stage.pendingStageDeliveryAvailable === true && isAddressableStageStatus(stage.status),
62407
+ group: stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId)
62408
+ })),
62409
+ ...nonAgentNodes(run).map((node) => ({
62410
+ stageId: node.id,
62411
+ stageName: node.name,
62412
+ target: stageRouteTarget(lookups.runs, rootRunId, run.id, node.id, lookups.segments),
62413
+ lifecycle: "pending",
62414
+ routeEligible: false,
62415
+ recipientPurpose: "control",
62416
+ group: workflowInvocationIntercomGroup(rootRunId)
62417
+ }))
62418
+ ],
62419
+ ...possibleStages === undefined ? {} : { possibleStages }
62420
+ };
62421
+ const signature = possibleStages === undefined ? JSON.stringify(announcement) : `${JSON.stringify({ ...announcement, possibleStages: undefined })}\x00${possibleStages.map(rowIdentity).join(",")}`;
62422
+ if (announcedRoutes.get(run.id)?.signature === signature)
62234
62423
  return;
62424
+ const entry = { signature };
62425
+ announcedRoutes.set(run.id, entry);
62426
+ try {
62427
+ outsideWorkflowExecutions(() => pi.events?.emit?.(PENDING_STAGE_ROUTE_EVENT, announcement));
62428
+ } catch (error) {
62429
+ if (announcedRoutes.get(run.id) === entry)
62430
+ announcedRoutes.delete(run.id);
62431
+ unpublishedRunIds.add(run.id);
62432
+ const failure = Promise.reject(error);
62433
+ failure.catch(() => {});
62434
+ routeCompletions.set(run.id, failure);
62435
+ throw error;
62436
+ }
62437
+ const completion = announcement.completion;
62438
+ if (completion === undefined) {
62439
+ announcedRoutes.delete(run.id);
62440
+ routeCompletions.delete(run.id);
62441
+ unpublishedRunIds.add(run.id);
62442
+ } else {
62443
+ routeCompletions.set(run.id, completion);
62444
+ completion.catch(() => {
62445
+ if (announcedRoutes.get(run.id) !== entry)
62446
+ return;
62447
+ announcedRoutes.delete(run.id);
62448
+ unpublishedRunIds.add(run.id);
62449
+ });
62450
+ }
62451
+ };
62452
+ const announceAllRoutes = () => {
62453
+ unpublishedRunIds.clear();
62235
62454
  const ownedRunIds = new Set;
62236
62455
  const runs = activeStore.runs();
62237
62456
  topology.refresh(runs);
@@ -62245,80 +62464,33 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62245
62464
  children.push(run);
62246
62465
  childrenByBoundary.set(key, children);
62247
62466
  }
62248
- const resolveBoundarySegments = createWorkflowBoundarySegmentsResolver(runs);
62467
+ const lookups = {
62468
+ runs,
62469
+ parentOf: (run) => run.parentRunId === undefined ? undefined : runById.get(run.parentRunId),
62470
+ childAt: (parent, segment) => resolveIndexedChildRun(childrenByBoundary, parent, segment),
62471
+ segments: createWorkflowBoundarySegmentsResolver(runs),
62472
+ rowRuns: () => runs
62473
+ };
62474
+ const members = new Map;
62249
62475
  for (const run of runs) {
62476
+ const rootRunId = topology.rootOf(run.id);
62477
+ for (const root of new Set([rootRunId, run.rootRunId])) {
62478
+ if (root === undefined)
62479
+ continue;
62480
+ const ids = members.get(root);
62481
+ if (ids === undefined)
62482
+ members.set(root, [run.id]);
62483
+ else
62484
+ ids.push(run.id);
62485
+ }
62250
62486
  if (externalRunRouteOwner(activeStore, run.id) !== undefined || !ownsRun(run.id))
62251
62487
  continue;
62252
- const rootRunId = topology.rootOf(run.id);
62253
62488
  if (rootRunId === undefined)
62254
62489
  continue;
62255
62490
  ownedRunIds.add(run.id);
62256
- const parentRun = run.parentRunId === undefined ? undefined : runById.get(run.parentRunId);
62257
- const boundary = parentRun?.stages.find((stage) => stage.id === run.parentStageId);
62258
- const parent = parentRun === undefined || boundary === undefined ? undefined : {
62259
- runId: parentRun.id,
62260
- stageKeys: [boundary.id, boundary.name].filter((key) => resolveIndexedChildRun(childrenByBoundary, parentRun, key)?.id === run.id)
62261
- };
62262
- let possibleStages;
62263
- if (run.id === rootRunId && isTerminalRunStatus(run.status)) {
62264
- possibleStageRowIndexes.delete(rootRunId);
62265
- possibleStages = [];
62266
- } else if (run.id === rootRunId) {
62267
- possibleStages = possibleStageRowsIndex(rootRunId).rows(runs, run, availableStoreDurableBackend(activeStore, rootRunId));
62268
- }
62269
- const announcement = {
62270
- runId: run.id,
62271
- group: workflowInvocationIntercomGroup(rootRunId),
62272
- capability: workflowPendingStageRouteCapability(activeStore, run.id),
62273
- ...parent === undefined ? {} : { parent },
62274
- stages: [
62275
- ...run.stages.filter((stage) => !isNonAgentStage(stage) && workflowInvocationOwnsGroup(workflowInvocationIntercomGroup(rootRunId), stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId))).map((stage) => ({
62276
- stageId: stage.id,
62277
- stageName: stage.name,
62278
- target: stageRouteTarget(runs, rootRunId, run.id, stage.id, resolveBoundarySegments),
62279
- lifecycle: stage.sessionId === undefined && stage.sessionFile === undefined ? "pending" : "running",
62280
- routeEligible: stage.pendingStageDeliveryAvailable === true && isAddressableStageStatus(stage.status),
62281
- group: stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId)
62282
- })),
62283
- ...nonAgentNodes(run).map((node) => ({
62284
- stageId: node.id,
62285
- stageName: node.name,
62286
- target: stageRouteTarget(runs, rootRunId, run.id, node.id, resolveBoundarySegments),
62287
- lifecycle: "pending",
62288
- routeEligible: false,
62289
- recipientPurpose: "control",
62290
- group: workflowInvocationIntercomGroup(rootRunId)
62291
- }))
62292
- ],
62293
- ...possibleStages === undefined ? {} : { possibleStages }
62294
- };
62295
- const signature = possibleStages === undefined ? JSON.stringify(announcement) : `${JSON.stringify({ ...announcement, possibleStages: undefined })}\x00${possibleStages.map(rowIdentity).join(",")}`;
62296
- if (announcedRoutes.get(run.id)?.signature === signature)
62297
- continue;
62298
- const entry = { signature };
62299
- announcedRoutes.set(run.id, entry);
62300
- try {
62301
- outsideWorkflowExecutions(() => pi.events?.emit?.(PENDING_STAGE_ROUTE_EVENT, announcement));
62302
- } catch (error) {
62303
- if (announcedRoutes.get(run.id) === entry)
62304
- announcedRoutes.delete(run.id);
62305
- const failure = Promise.reject(error);
62306
- failure.catch(() => {});
62307
- routeCompletions.set(run.id, failure);
62308
- throw error;
62309
- }
62310
- const completion = announcement.completion;
62311
- if (completion === undefined) {
62312
- announcedRoutes.delete(run.id);
62313
- routeCompletions.delete(run.id);
62314
- } else {
62315
- routeCompletions.set(run.id, completion);
62316
- completion.catch(() => {
62317
- if (announcedRoutes.get(run.id) === entry)
62318
- announcedRoutes.delete(run.id);
62319
- });
62320
- }
62491
+ announceRun(run, rootRunId, lookups);
62321
62492
  }
62493
+ rootRunMembers = members;
62322
62494
  for (const runId of announcedRoutes.keys()) {
62323
62495
  if (!ownedRunIds.has(runId))
62324
62496
  announcedRoutes.delete(runId);
@@ -62331,7 +62503,65 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62331
62503
  if (!ownedRunIds.has(rootRunId))
62332
62504
  possibleStageRowIndexes.delete(rootRunId);
62333
62505
  }
62334
- sweepPromise = sweepPromise.then(() => outsideWorkflowExecutions(() => settleUndeliverablePendingStageMessages(activeStore, notifyUndeliverable, ownsRun))).then(() => {
62506
+ };
62507
+ const announceChangedRoutes = (changed) => {
62508
+ const retried = [...unpublishedRunIds];
62509
+ unpublishedRunIds.clear();
62510
+ const roots = new Set;
62511
+ for (const runId of [...changed, ...retried])
62512
+ for (const root of [topology.rootOf(runId), activeStore.run(runId)?.rootRunId])
62513
+ if (root !== undefined && rootRunMembers.has(root))
62514
+ roots.add(root);
62515
+ const segments = new Map;
62516
+ const lookups = {
62517
+ runs: activeStore,
62518
+ parentOf: (run) => run.parentRunId === undefined ? undefined : activeStore.run(run.parentRunId),
62519
+ childAt: (parent, segment) => resolveChildRun(activeStore, parent, segment),
62520
+ segments: (runId) => {
62521
+ if (!segments.has(runId))
62522
+ segments.set(runId, workflowBoundarySegments(activeStore, runId));
62523
+ return segments.get(runId);
62524
+ },
62525
+ rowRuns: membersOf
62526
+ };
62527
+ const position = (runId) => activeStore.runPosition(runId) ?? Number.MAX_SAFE_INTEGER;
62528
+ for (const rootRunId of [...roots].sort((left, right) => position(left) - position(right))) {
62529
+ for (const run of membersOf(rootRunId)) {
62530
+ if (topology.rootOf(run.id) !== rootRunId)
62531
+ continue;
62532
+ if (externalRunRouteOwner(activeStore, run.id) !== undefined || !ownsRun(run.id))
62533
+ dropRoute(run.id);
62534
+ else
62535
+ announceRun(run, rootRunId, lookups);
62536
+ }
62537
+ }
62538
+ };
62539
+ const unsettledRunIds = new Set;
62540
+ const sweep = async (changed) => {
62541
+ const runIds = changed === undefined ? undefined : new Set([...changed, ...unsettledRunIds]);
62542
+ const found = new Set;
62543
+ try {
62544
+ await settleUndeliverablePendingStageMessages(activeStore, notifyUndeliverable, ownsRun, runIds, (runId) => found.add(runId));
62545
+ } finally {
62546
+ if (runIds === undefined)
62547
+ unsettledRunIds.clear();
62548
+ else
62549
+ for (const runId of runIds)
62550
+ unsettledRunIds.delete(runId);
62551
+ for (const runId of found)
62552
+ if (hasSettlementWork(activeStore.run(runId)))
62553
+ unsettledRunIds.add(runId);
62554
+ }
62555
+ };
62556
+ const announceRoutes = (changed) => {
62557
+ if (disposed)
62558
+ return;
62559
+ const scope = changed !== undefined && topology.holds(activeStore, changed) ? changed : undefined;
62560
+ if (scope === undefined)
62561
+ announceAllRoutes();
62562
+ else
62563
+ announceChangedRoutes(scope);
62564
+ sweepPromise = sweepPromise.then(() => outsideWorkflowExecutions(() => sweep(scope))).then(() => {
62335
62565
  return;
62336
62566
  }).catch((error) => reportWarning(`atomic-workflows: pending stage delivery sweep failed: ${error.message}`));
62337
62567
  };
@@ -62339,13 +62569,21 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62339
62569
  let announcementTimer;
62340
62570
  let announcedAt = Number.NEGATIVE_INFINITY;
62341
62571
  let announcementCost = 0;
62342
- const announceNow = () => {
62572
+ let changedRunIds = new Set;
62573
+ const announceNow = (everything = false) => {
62343
62574
  if (announcementTimer !== undefined)
62344
62575
  clearTimeout(announcementTimer);
62345
62576
  announcementTimer = undefined;
62346
62577
  announcementPending = false;
62578
+ const changed = everything ? undefined : changedRunIds;
62579
+ changedRunIds = new Set;
62347
62580
  const started = performance.now();
62348
- announceRoutes();
62581
+ try {
62582
+ announceRoutes(changed);
62583
+ } catch (error) {
62584
+ changedRunIds = undefined;
62585
+ throw error;
62586
+ }
62349
62587
  announcedAt = performance.now();
62350
62588
  announcementCost = announcedAt - started;
62351
62589
  };
@@ -62368,8 +62606,15 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62368
62606
  }
62369
62607
  }
62370
62608
  };
62371
- const scheduleAnnouncement = () => {
62372
- if (disposed || announcementTimer !== undefined)
62609
+ const scheduleAnnouncement = (changes) => {
62610
+ if (disposed)
62611
+ return;
62612
+ if (changes === undefined)
62613
+ changedRunIds = undefined;
62614
+ else if (changedRunIds !== undefined)
62615
+ for (const change of changes)
62616
+ changedRunIds.add(change.runId);
62617
+ if (announcementTimer !== undefined)
62373
62618
  return;
62374
62619
  const idle = announcementCost / ROUTE_ANNOUNCEMENT_EVENT_LOOP_SHARE - announcementCost;
62375
62620
  const wait = Math.max(ROUTE_ANNOUNCEMENT_BATCH_MS, announcedAt + idle - performance.now());
@@ -62378,21 +62623,20 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62378
62623
  announcementTimer.unref?.();
62379
62624
  };
62380
62625
  const unsubscribeStore = activeStore.subscribeInvalidation(scheduleAnnouncement);
62381
- announceNow();
62626
+ announceNow(true);
62382
62627
  pi.on?.("session_start", () => {
62383
62628
  announcedRoutes.clear();
62384
- announceNow();
62629
+ announceNow(true);
62385
62630
  });
62386
62631
  const routePendingStageMessage = (payload) => {
62387
62632
  if (disposed || !isPendingStageMessageEvent(payload) || payload.handled)
62388
62633
  return;
62389
- const runs = activeStore.runs();
62390
62634
  const parsedTarget = parseWorkflowStageTarget(payload.target);
62391
62635
  if (parsedTarget === undefined)
62392
62636
  return;
62393
62637
  if (!ownsRun(parsedTarget.rootRunId))
62394
62638
  return;
62395
- if (parsedTarget.kind === "path" && isMaterializedNonAgentTarget(runs, parsedTarget)) {
62639
+ if (parsedTarget.kind === "path" && isMaterializedNonAgentTarget(activeStore, parsedTarget)) {
62396
62640
  payload.handled = true;
62397
62641
  payload.completion = Promise.resolve({
62398
62642
  outcome: "refused",
@@ -62400,22 +62644,22 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62400
62644
  });
62401
62645
  return;
62402
62646
  }
62403
- const destination = resolveMaterializedStage(runs, payload.target);
62647
+ const destination = resolveMaterializedStage(activeStore, payload.target);
62404
62648
  if (destination === undefined) {
62405
62649
  if (payload.live === true)
62406
62650
  return;
62407
- const rootRun = runs.find((candidate) => candidate.id === parsedTarget.rootRunId);
62651
+ const rootRun = activeStore.run(parsedTarget.rootRunId);
62408
62652
  if (rootRun === undefined)
62409
62653
  return;
62410
62654
  payload.handled = true;
62411
- payload.completion = deliverStickyTarget(activeStore, runs, rootRun, payload, parsedTarget).then((value2) => {
62655
+ payload.completion = deliverStickyTarget(activeStore, rootRun, payload, parsedTarget).then((value2) => {
62412
62656
  return value2;
62413
62657
  }, (error) => {
62414
62658
  throw error;
62415
62659
  });
62416
62660
  return;
62417
62661
  }
62418
- const rootRunId = durableRootRunIdForRun(runs, destination.run.id);
62662
+ const rootRunId = durableRootRunIdForRun(activeStore, destination.run.id);
62419
62663
  if (rootRunId === undefined)
62420
62664
  return;
62421
62665
  const resolvedEvent = {
@@ -62431,7 +62675,7 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62431
62675
  payload.handled = true;
62432
62676
  payload.completion = validateLiveDelivery(activeStore, resolvedEvent).then((result) => result.outcome === "forward" ? {
62433
62677
  outcome: "forward",
62434
- target: stageRouteTarget(runs, rootRunId, destination.run.id, stage.id)
62678
+ target: stageRouteTarget(activeStore, rootRunId, destination.run.id, stage.id)
62435
62679
  } : result);
62436
62680
  return;
62437
62681
  }
@@ -62439,11 +62683,11 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62439
62683
  if (uninitializedStage === undefined) {
62440
62684
  if (payload.message.expectsReply === true)
62441
62685
  return;
62442
- const stickyRoot = runs.find((candidate) => candidate.id === parsedTarget.rootRunId);
62686
+ const stickyRoot = activeStore.run(parsedTarget.rootRunId);
62443
62687
  if (stickyRoot === undefined || isTerminalRunStatus(stickyRoot.status))
62444
62688
  return;
62445
62689
  payload.handled = true;
62446
- payload.completion = deliverStickyTarget(activeStore, runs, stickyRoot, payload, parsedTarget);
62690
+ payload.completion = deliverStickyTarget(activeStore, stickyRoot, payload, parsedTarget);
62447
62691
  return;
62448
62692
  }
62449
62693
  payload.handled = true;
@@ -62484,7 +62728,7 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62484
62728
  await Promise.allSettled(routeCompletions.values());
62485
62729
  await sweepPromise;
62486
62730
  },
62487
- refresh: announceNow
62731
+ refresh: () => announceNow(true)
62488
62732
  });
62489
62733
  }
62490
62734
  function stageRouteTarget(runs, rootRunId, runId, stageId, resolveBoundarySegments = (id) => workflowBoundarySegments(runs, id)) {
@@ -62530,20 +62774,20 @@ function resolveIndexedChildRun(childrenByBoundary, parent, segment) {
62530
62774
  function resolveChildRun(runs, parent, segment) {
62531
62775
  const boundariesById = parent.stages.filter((stage) => stage.id === segment);
62532
62776
  const boundaries = boundariesById.length > 0 ? boundariesById : parent.stages.filter((stage) => stage.name === segment);
62533
- const children = boundaries.flatMap((boundary) => runs.filter((candidate) => candidate.parentRunId === parent.id && candidate.parentStageId === boundary.id));
62777
+ const children = boundaries.flatMap((boundary) => childRunsInSource(runs, parent.id, boundary.id));
62534
62778
  return children.length === 1 ? children[0] : undefined;
62535
62779
  }
62536
62780
  function resolveMaterializedRun(runs, parsed) {
62537
62781
  if (parsed.kind !== "path")
62538
62782
  return;
62539
- const rootRun = runs.find((candidate) => candidate.id === parsed.rootRunId);
62783
+ const rootRun = findRunInSource(runs, parsed.rootRunId);
62540
62784
  if (rootRun === undefined)
62541
62785
  return;
62542
62786
  let run = rootRun;
62543
62787
  for (const segment of parsed.segments.slice(0, -1)) {
62544
- const runById = runs.filter((candidate) => candidate.id === segment && durableRootRunIdForRun(runs, candidate.id) === parsed.rootRunId);
62545
- if (runById.length === 1) {
62546
- run = runById[0];
62788
+ const runById = findRunInSource(runs, segment);
62789
+ if (runById !== undefined && durableRootRunIdForRun(runs, runById.id) === parsed.rootRunId) {
62790
+ run = runById;
62547
62791
  continue;
62548
62792
  }
62549
62793
  const child = resolveChildRun(runs, run, segment);
@@ -62606,7 +62850,7 @@ async function queueAndPersist(activeStore, event, runGroup, pendingStageDeliver
62606
62850
  queuedAt: new Date().toISOString()
62607
62851
  };
62608
62852
  const rootBackend = requireStoreDurableBackend(activeStore, event.runId);
62609
- const backend = durableBackendForRun(rootBackend, activeStore.runs(), event.runId);
62853
+ const backend = durableBackendForRun(rootBackend, activeStore, event.runId);
62610
62854
  if (backend === undefined)
62611
62855
  return { outcome: "refused", reason: "Session not found" };
62612
62856
  const senderGroup = pendingStageSenderGroup(event, runGroup);
@@ -62640,7 +62884,7 @@ async function queueAndPersist(activeStore, event, runGroup, pendingStageDeliver
62640
62884
  return { outcome: "refused", reason: "Pending-stage delivery was refused" };
62641
62885
  return { outcome: "queued", position: result.position };
62642
62886
  }
62643
- async function deliverStickyTarget(activeStore, runs, rootRun, event, parsedTarget) {
62887
+ async function deliverStickyTarget(activeStore, rootRun, event, parsedTarget) {
62644
62888
  const rootRunId = rootRun.id;
62645
62889
  const runGroup = workflowInvocationIntercomGroup(rootRunId);
62646
62890
  if (event.message.expectsReply === true) {
@@ -62652,9 +62896,9 @@ async function deliverStickyTarget(activeStore, runs, rootRun, event, parsedTarg
62652
62896
  reason: `Workflow run ${rootRunId} terminated with status ${rootRun.status} before any stage matching ${event.target} started`
62653
62897
  };
62654
62898
  }
62655
- const liveMatches = matchingLiveStages(runs, rootRunId, parsedTarget.segments);
62656
- const notInKnownSet = targetSegmentsInPossibleStages(parsedTarget.segments, rootRun.possibleStages ?? []) || liveMatches.length > 0 || matchingLiveStages(runs, rootRunId, parsedTarget.segments, { includePending: true }).length > 0 ? undefined : true;
62657
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), runs, rootRunId);
62899
+ const liveMatches = matchingLiveStages(activeStore, rootRunId, parsedTarget.segments);
62900
+ const notInKnownSet = targetSegmentsInPossibleStages(parsedTarget.segments, rootRun.possibleStages ?? []) || liveMatches.length > 0 || matchingLiveStages(activeStore, rootRunId, parsedTarget.segments, { includePending: true }).length > 0 ? undefined : true;
62901
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), activeStore, rootRunId);
62658
62902
  if (backend === undefined)
62659
62903
  return { outcome: "refused", reason: "Session not found" };
62660
62904
  const senderGroup = pendingStageSenderGroup(event, runGroup);
@@ -62722,14 +62966,13 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
62722
62966
  const parsedTarget = parseWorkflowStageTarget(event.target);
62723
62967
  if (parsedTarget === undefined)
62724
62968
  return false;
62725
- const runs = activeStore.runs();
62726
62969
  const rootRunId = parsedTarget.rootRunId;
62727
- const rootRun = runs.find((candidate) => candidate.id === rootRunId);
62970
+ const rootRun = activeStore.run(rootRunId);
62728
62971
  const entry = rootRun?.pendingStageMessages?.find((candidate) => candidate.sticky === true && candidate.message.id === event.messageId);
62729
62972
  if (rootRun === undefined || entry === undefined)
62730
62973
  return false;
62731
62974
  const delivered = new Set(event.deliveredTargets);
62732
- const records = matchingLiveStages(runs, rootRunId, parsedTarget.segments).filter((match) => delivered.has(match.target)).map((match) => ({
62975
+ const records = matchingLiveStages(activeStore, rootRunId, parsedTarget.segments).filter((match) => delivered.has(match.target)).map((match) => ({
62733
62976
  runId: match.run.id,
62734
62977
  stageId: match.stage.id,
62735
62978
  ...match.stage.name === match.stage.id ? {} : { stageName: match.stage.name },
@@ -62738,7 +62981,7 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
62738
62981
  }));
62739
62982
  if (records.length === 0)
62740
62983
  return false;
62741
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), runs, rootRunId);
62984
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), activeStore, rootRunId);
62742
62985
  if (backend === undefined)
62743
62986
  return false;
62744
62987
  const unconfirmedRecords = [];
@@ -62751,11 +62994,8 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
62751
62994
  }
62752
62995
  function matchingLiveStages(runs, rootRunId, patternSegments, options = {}) {
62753
62996
  const matches = [];
62754
- const runById = new Map(runs.map((run) => [run.id, run]));
62755
62997
  const hopsFor = createWorkflowBoundaryHopsResolver(runs);
62756
- for (const run of runs) {
62757
- if (reciprocalWorkflowRootRunId(runById, run.id) !== rootRunId)
62758
- continue;
62998
+ for (const run of invocationRunsInSource(runs, rootRunId)) {
62759
62999
  const hops = hopsFor(run.id);
62760
63000
  if (hops === undefined)
62761
63001
  continue;
@@ -62820,17 +63060,45 @@ function needsUndeliverableSettlement(run, entry) {
62820
63060
  return pendingStageUndeliverableReason(run, entry) !== undefined;
62821
63061
  return entry.status === "undeliverable" && entry.undeliverableNotificationId !== undefined && entry.undeliverableNotifiedAt === undefined && entry.undeliverableReason !== undefined;
62822
63062
  }
62823
- async function settleUndeliverablePendingStageMessages(activeStore, notify, ownsRun = () => true) {
63063
+ function hasSettlementWork(run) {
63064
+ return run?.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)) === true;
63065
+ }
63066
+ async function settleUndeliverablePendingStageMessages(activeStore, notify, ownsRun = () => true, runIds, onSettlementWork) {
63067
+ if (runIds !== undefined) {
63068
+ const position = (run) => activeStore.runPosition(run.id) ?? Number.MAX_SAFE_INTEGER;
63069
+ const candidates = [...new Set(runIds)].flatMap((runId) => {
63070
+ const run = activeStore.run(runId);
63071
+ return run !== undefined && hasSettlementWork(run) ? [run] : [];
63072
+ }).sort((left, right) => position(left) - position(right));
63073
+ for (const run of candidates)
63074
+ onSettlementWork?.(run.id);
63075
+ const owned = candidates.filter((run) => ownsRun(run.id));
63076
+ if (owned.length === 0)
63077
+ return 0;
63078
+ const ownedRuns = {
63079
+ run: (runId) => {
63080
+ const run = activeStore.run(runId);
63081
+ return run !== undefined && ownsRun(run.id) ? run : undefined;
63082
+ },
63083
+ runs: () => activeStore.runs().filter((run) => ownsRun(run.id))
63084
+ };
63085
+ return settleRuns(activeStore, owned, ownedRuns, notify);
63086
+ }
62824
63087
  const all = activeStore.runs();
62825
- const pending = (run) => run.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)) === true;
62826
- if (!all.some((run) => pending(run) && ownsRun(run.id)))
63088
+ const candidates = all.filter(hasSettlementWork);
63089
+ for (const run of candidates)
63090
+ onSettlementWork?.(run.id);
63091
+ if (!candidates.some((run) => ownsRun(run.id)))
62827
63092
  return 0;
62828
63093
  const runs = all.filter((run) => ownsRun(run.id));
63094
+ return settleRuns(activeStore, runs, runs, notify);
63095
+ }
63096
+ async function settleRuns(activeStore, runs, owners, notify) {
62829
63097
  let settled = 0;
62830
63098
  for (const run of runs) {
62831
- if (!run.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)))
63099
+ if (!hasSettlementWork(run))
62832
63100
  continue;
62833
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, run.id), runs, run.id);
63101
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, run.id), owners, run.id);
62834
63102
  if (backend === undefined) {
62835
63103
  throw new Error(`atomic-workflows: workflow run ${run.id} has no durable owner for pending-stage settlement`);
62836
63104
  }
@@ -62849,7 +63117,7 @@ async function settleUndeliverablePendingStageMessages(activeStore, notify, owns
62849
63117
  if (await activeStore.markPendingStageMessageUndeliverable(run.id, entry.stageKey, entry.id, reason, backend)) {
62850
63118
  settled += 1;
62851
63119
  }
62852
- const currentRun = activeStore.runs().find((candidate) => candidate.id === run.id);
63120
+ const currentRun = activeStore.run(run.id);
62853
63121
  const currentEntry = currentRun?.pendingStageMessages?.find((candidate) => candidate.stageKey === entry.stageKey && candidate.id === entry.id);
62854
63122
  if (currentEntry === undefined)
62855
63123
  continue;
@@ -65487,32 +65755,31 @@ var init_workflow_route_owner = __esm(() => {
65487
65755
  });
65488
65756
 
65489
65757
  // dist/builtin/workflows/src/runs/foreground/sdk-intercom.ts
65490
- function indexRoots(runs) {
65491
- const runById = new Map(runs.map((run) => [run.id, run]));
65492
- const rootOf = new Map;
65493
- const deliverable = new Set;
65494
- for (const run of runs) {
65495
- const root = reciprocalWorkflowRootRunId(runById, run.id);
65496
- rootOf.set(run.id, root);
65497
- if (root !== undefined && run.stages.some((stage) => stage.pendingStageDeliveryAvailable === true))
65498
- deliverable.add(root);
65499
- }
65500
- return { rootOf, deliverable };
65501
- }
65502
65758
  function createStandaloneRouteOwnership(store, roots) {
65503
65759
  const activated = new Set;
65504
- let index;
65760
+ const runs = runsByIdOf(store);
65761
+ const rootOf = new Map;
65762
+ const deliverable = new Map;
65505
65763
  const dispose = store.subscribeInvalidation(() => {
65506
- index = undefined;
65764
+ rootOf.clear();
65765
+ deliverable.clear();
65507
65766
  });
65508
65767
  return {
65509
65768
  owns: (runId) => {
65510
- index ??= indexRoots(store.runs());
65511
- const root = index.rootOf.get(runId) ?? runId;
65769
+ if (!rootOf.has(runId))
65770
+ rootOf.set(runId, reciprocalWorkflowRootRunId(runs, runId));
65771
+ const root = rootOf.get(runId) ?? runId;
65512
65772
  if (!roots.has(root))
65513
65773
  return false;
65514
- if (!activated.has(root) && index.deliverable.has(root))
65515
- activated.add(root);
65774
+ if (!activated.has(root)) {
65775
+ let canDeliver = deliverable.get(root);
65776
+ if (canDeliver === undefined) {
65777
+ canDeliver = invocationRunsInSource(store, root).some((run) => run.stages.some((stage) => stage.pendingStageDeliveryAvailable === true));
65778
+ deliverable.set(root, canDeliver);
65779
+ }
65780
+ if (canDeliver)
65781
+ activated.add(root);
65782
+ }
65516
65783
  return activated.has(root);
65517
65784
  },
65518
65785
  dispose
@@ -66124,7 +66391,7 @@ class PooledRoutes {
66124
66391
  this.mirror.batch(() => {
66125
66392
  for (const id of attempt.runs) {
66126
66393
  rotateWorkflowPendingStageRouteCapability(this.mirror, id);
66127
- const run = this.mirror.runs().find((candidate) => candidate.id === id);
66394
+ const run = this.mirror.run(id);
66128
66395
  if (run?.stages.some(isLiveStage) !== true)
66129
66396
  continue;
66130
66397
  this.mirror.recordRunStart({
@@ -67469,6 +67736,41 @@ var init_pool_coordinator = __esm(() => {
67469
67736
  STAGE_WATCH_BACKLOG_BYTES = 8 * 1024 * 1024;
67470
67737
  });
67471
67738
 
67739
+ // dist/builtin/workflows/src/workers/pooled-run-end.ts
67740
+ function endPooledRun(store, run, error) {
67741
+ const now = Date.now();
67742
+ for (const stage of run.stages)
67743
+ if (!isTerminalStageStatus(stage.status))
67744
+ store.recordStageEnd(run.id, {
67745
+ ...stage,
67746
+ status: "failed",
67747
+ endedAt: now,
67748
+ durationMs: stage.startedAt === undefined ? undefined : Math.max(0, now - stage.startedAt),
67749
+ error
67750
+ });
67751
+ store.recordRunEnd(run.id, "failed", undefined, error);
67752
+ }
67753
+ function endPooledChild(store, childRunId, error) {
67754
+ const child = store.run(childRunId);
67755
+ if (child === undefined)
67756
+ return;
67757
+ const subtree = [child];
67758
+ const seen = new Set([child.id]);
67759
+ for (let index = 0;index < subtree.length; index++)
67760
+ for (const nested of store.childRuns(subtree[index].id))
67761
+ if (!seen.has(nested.id)) {
67762
+ seen.add(nested.id);
67763
+ subtree.push(nested);
67764
+ }
67765
+ const unfinished = subtree.filter((run) => run.endedAt === undefined).map((run) => ({ run, position: store.runPosition(run.id) ?? Number.MAX_SAFE_INTEGER })).sort((left, right) => left.position - right.position);
67766
+ for (const { run } of unfinished)
67767
+ if (run.endedAt === undefined)
67768
+ endPooledRun(store, run, error);
67769
+ }
67770
+ var init_pooled_run_end = __esm(() => {
67771
+ init_store_internal();
67772
+ });
67773
+
67472
67774
  // dist/builtin/workflows/src/workers/pooled-stage-sources.ts
67473
67775
  function registerPooledStageSource(store, source) {
67474
67776
  let registered = sources.get(store);
@@ -67646,7 +67948,7 @@ function createWorkflowPendingStageDelivery(activeStore, runId, stageId, stageNa
67646
67948
  if (sessionId !== undefined && activeStore.pendingStageMessagesFor(runId, stageId).length === 0 && activeStore.pendingStageMessagesFor(runId, stageName).length === 0) {
67647
67949
  const entries = stickyPendingStageEntriesForStage(activeStore, runId, stageId, stageName, { sessionId });
67648
67950
  Promise.all(entries.map(async (entry) => {
67649
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, entry.runId), activeStore.runs(), entry.runId);
67951
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, entry.runId), activeStore, entry.runId);
67650
67952
  return await backend?.hasPendingStageDeliveryReceipt?.(entry.runId, entry.id, {
67651
67953
  runId,
67652
67954
  stageId,
@@ -67693,13 +67995,12 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
67693
67995
  ...activeStore.pendingStageMessagesFor(runId, stageName),
67694
67996
  ...stickyEntries
67695
67997
  ].map((entry) => entry.id));
67696
- const runs = activeStore.runs();
67697
67998
  const entries = [
67698
- ...(runs.find((run) => run.id === runId)?.pendingStageMessages ?? []).map((entry, index) => ({ entry, index })).filter(({ entry }) => candidateIds.has(entry.id) && entry.sticky !== true),
67999
+ ...(activeStore.run(runId)?.pendingStageMessages ?? []).map((entry, index) => ({ entry, index })).filter(({ entry }) => candidateIds.has(entry.id) && entry.sticky !== true),
67699
68000
  ...stickyEntries.map((entry) => ({ entry, index: Number.MAX_SAFE_INTEGER }))
67700
68001
  ].map(({ entry, index }) => ({ entry, index, order: pendingStageMessageAdmissionOrder(entry) })).sort((left, right) => left.order - right.order || left.index - right.index).map(({ entry }) => entry);
67701
68002
  const rootBackend = requireStoreDurableBackend(activeStore, runId);
67702
- const backend = durableBackendForRun(rootBackend, runs, runId);
68003
+ const backend = durableBackendForRun(rootBackend, activeStore, runId);
67703
68004
  if (backend === undefined) {
67704
68005
  throw new Error(`atomic-workflows: workflow run ${runId} has no durable owner for pending-stage delivery`);
67705
68006
  }
@@ -67714,9 +68015,9 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
67714
68015
  stageId,
67715
68016
  ...recipient === undefined ? {} : { sessionId: recipient.sessionId, admission: "context" }
67716
68017
  };
67717
- const hasStickyReceipt = async () => (activeStore.runs().find((run) => run.id === entry.runId)?.pendingStageMessages?.find((candidate) => candidate.id === entry.id)?.deliveries?.some((delivery) => delivery.runId === runId && delivery.stageId === stageId && (recipient === undefined || delivery.sessionId === recipient.sessionId && delivery.admission === "context")) ?? false) || await durableBackendForRun(rootBackend, activeStore.runs(), entry.runId)?.hasPendingStageDeliveryReceipt?.(entry.runId, entry.id, stickyReceipt) === true;
68018
+ const hasStickyReceipt = async () => (activeStore.run(entry.runId)?.pendingStageMessages?.find((candidate) => candidate.id === entry.id)?.deliveries?.some((delivery) => delivery.runId === runId && delivery.stageId === stageId && (recipient === undefined || delivery.sessionId === recipient.sessionId && delivery.admission === "context")) ?? false) || await durableBackendForRun(rootBackend, activeStore, entry.runId)?.hasPendingStageDeliveryReceipt?.(entry.runId, entry.id, stickyReceipt) === true;
67718
68019
  if (entry.sticky === true && await hasStickyReceipt()) {
67719
- const entryBackend = durableBackendForRun(rootBackend, activeStore.runs(), entry.runId);
68020
+ const entryBackend = durableBackendForRun(rootBackend, activeStore, entry.runId);
67720
68021
  if (entryBackend !== undefined) {
67721
68022
  await commit(() => activeStore.recordPendingStageMessageDeliveries(entry.runId, entry.id, [], new Date().toISOString(), entryBackend));
67722
68023
  }
@@ -67725,7 +68026,7 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
67725
68026
  if (!recipient?.receivedMessageIds.includes(entry.message.id))
67726
68027
  await deliver(toPendingStageSender(entry), entry.message);
67727
68028
  if (entry.sticky === true) {
67728
- const entryBackend = durableBackendForRun(rootBackend, activeStore.runs(), entry.runId);
68029
+ const entryBackend = durableBackendForRun(rootBackend, activeStore, entry.runId);
67729
68030
  if (entryBackend === undefined) {
67730
68031
  throw new Error(`atomic-workflows: workflow run ${entry.runId} has no durable owner for sticky pending-stage delivery`);
67731
68032
  }
@@ -67744,18 +68045,17 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
67744
68045
  }
67745
68046
  }
67746
68047
  function stickyPendingStageEntriesForStage(activeStore, runId, stageId, stageName, recipient, receivedByEndedStage = []) {
67747
- const runs = activeStore.runs();
67748
- const rootRunId = durableRootRunIdForRun(runs, runId);
68048
+ const rootRunId = durableRootRunIdForRun(activeStore, runId);
67749
68049
  if (rootRunId === undefined)
67750
68050
  return [];
67751
- const rootRun = runs.find((run) => run.id === rootRunId);
68051
+ const rootRun = activeStore.run(rootRunId);
67752
68052
  if (rootRun === undefined)
67753
68053
  return [];
67754
- const stage = runs.find((run) => run.id === runId)?.stages.find((candidate) => candidate.id === stageId);
68054
+ const stage = activeStore.run(runId)?.stages.find((candidate) => candidate.id === stageId);
67755
68055
  const ended = stage?.status === "completed" || stage?.status === "skipped";
67756
68056
  if (ended && receivedByEndedStage.length === 0)
67757
68057
  return [];
67758
- const hops = workflowBoundaryHops(runs, runId);
68058
+ const hops = workflowBoundaryHops(activeStore, runId);
67759
68059
  if (hops === undefined)
67760
68060
  return [];
67761
68061
  return (rootRun.pendingStageMessages ?? []).filter((entry) => {
@@ -67942,7 +68242,7 @@ class PoolStageHandoff {
67942
68242
  if (result === undefined)
67943
68243
  return;
67944
68244
  const terminals = new Map;
67945
- const nested = this.store.runs().some((run) => run.endedAt === undefined && run.id !== work.childRunId && this.owners.get(run.id) === work.id);
68245
+ const nested = this.ownedRunIds(work).some((id) => id !== work.childRunId && this.unended(id) !== undefined);
67946
68246
  for (const checkpoint of nested ? this.backend.listCheckpoints(root) : []) {
67947
68247
  const boundary = checkpoint.kind === "stage" ? checkpoint.topology?.boundary : undefined;
67948
68248
  if (checkpoint.kind !== "stage" || boundary?.event !== "terminal")
@@ -67954,8 +68254,9 @@ class PoolStageHandoff {
67954
68254
  this.store.batch(() => this.settle(work, result, terminals));
67955
68255
  }
67956
68256
  settle(work, result, terminals) {
67957
- for (const run of this.store.runs()) {
67958
- if (run.endedAt !== undefined || this.owners.get(run.id) !== work.id)
68257
+ for (const id of this.ownedRunIds(work)) {
68258
+ const run = this.unended(id);
68259
+ if (run === undefined)
67959
68260
  continue;
67960
68261
  if (run.id === work.childRunId) {
67961
68262
  const executions = new Map(run.stages.map((stage) => [stage.id, stage.workerExecution]));
@@ -67976,6 +68277,19 @@ class PoolStageHandoff {
67976
68277
  this.store.recordRunEnd(run.id, terminal.status, terminal.outputs);
67977
68278
  }
67978
68279
  }
68280
+ ownedRunIds(work) {
68281
+ const held = [];
68282
+ for (const id of this.attempts.get(work.id)?.runs ?? []) {
68283
+ const position = this.store.runPosition(id);
68284
+ if (position !== undefined)
68285
+ held.push({ id, position });
68286
+ }
68287
+ return held.sort((left, right) => left.position - right.position).map(({ id }) => id);
68288
+ }
68289
+ unended(runId) {
68290
+ const run = this.store.run(runId);
68291
+ return run?.endedAt === undefined ? run : undefined;
68292
+ }
67979
68293
  fence(work) {
67980
68294
  const current = this.attempts.get(work.id);
67981
68295
  if (current !== undefined && current.generation > work.generation)
@@ -70191,21 +70505,7 @@ class LocalWorkerPool {
70191
70505
  endFailedChild(work, error) {
70192
70506
  const store = this.store;
70193
70507
  if (store !== undefined)
70194
- store.batch(() => {
70195
- const runs = store.runs();
70196
- const byId = new Map(runs.map((run) => [run.id, run]));
70197
- const inChild = (run) => {
70198
- for (let current = run;current !== undefined; ) {
70199
- if (current.id === work.childRunId)
70200
- return true;
70201
- current = current.parentRunId === undefined ? undefined : byId.get(current.parentRunId);
70202
- }
70203
- return false;
70204
- };
70205
- for (const run of runs)
70206
- if (run.endedAt === undefined && inChild(run))
70207
- endPooledRun(store, run, error.message);
70208
- });
70508
+ store.batch(() => endPooledChild(store, work.childRunId, error.message));
70209
70509
  if (this.reconnectingViews.size > 0 || this.outboxes.size > 0)
70210
70510
  this.reconnectStageViews();
70211
70511
  }
@@ -70518,19 +70818,6 @@ class LocalWorkerPool {
70518
70818
  throw failure;
70519
70819
  }
70520
70820
  }
70521
- function endPooledRun(store, run, error) {
70522
- const now = Date.now();
70523
- for (const stage of run.stages)
70524
- if (!isTerminalStageStatus(stage.status))
70525
- store.recordStageEnd(run.id, {
70526
- ...stage,
70527
- status: "failed",
70528
- endedAt: now,
70529
- durationMs: stage.startedAt === undefined ? undefined : Math.max(0, now - stage.startedAt),
70530
- error
70531
- });
70532
- store.recordRunEnd(run.id, "failed", undefined, error);
70533
- }
70534
70821
  var RECONNECT_ATTEMPT_PUBLICATIONS = 40, INTERNAL_WORKFLOW_WORKER_ARG = "--internal-workflow-worker", DEFAULT_WORK_LEASE_MS = 30000, MINIMUM_WORK_LEASE_MS, MAX_TIMER_DELAY_MS = 2147483647, COORDINATOR_STDERR_TAIL_CHARACTERS = 8192, COORDINATOR_EXIT_GRACE_MS = 5000, COMPLETION_TURN_BUDGET_MS = 4, completeInTurns;
70535
70822
  var init_local_pool = __esm(() => {
70536
70823
  init_internal();
@@ -70542,7 +70829,6 @@ var init_local_pool = __esm(() => {
70542
70829
  init_sdk_intercom();
70543
70830
  init_external_run_routes();
70544
70831
  init_stage_question_form();
70545
- init_store_internal();
70546
70832
  init_workflow_infrastructure_error();
70547
70833
  init_admission_binding();
70548
70834
  init_definitions();
@@ -70551,6 +70837,7 @@ var init_local_pool = __esm(() => {
70551
70837
  init_host_options();
70552
70838
  init_pool_coordinator();
70553
70839
  init_pool_journal();
70840
+ init_pooled_run_end();
70554
70841
  init_pooled_stage_sources();
70555
70842
  init_pooled_watch_trace();
70556
70843
  init_stage_handoff();
@@ -71218,9 +71505,9 @@ function createParallelPrimitive(input) {
71218
71505
  activeStages: new Map,
71219
71506
  parentIds: parallelParentIds
71220
71507
  };
71221
- const stageIdsBeforeParallel = new Set(input.runtime.activeStore.runs().find((run) => run.id === input.runtime.runId)?.stages.map((stage) => stage.id) ?? []);
71508
+ const stageIdsBeforeParallel = new Set(input.runtime.activeStore.run(input.runtime.runId)?.stages.map((stage) => stage.id) ?? []);
71222
71509
  const everyStepCompleted = () => {
71223
- const run = input.runtime.activeStore.runs().find((candidate) => candidate.id === input.runtime.runId);
71510
+ const run = input.runtime.activeStore.run(input.runtime.runId);
71224
71511
  if (run === undefined)
71225
71512
  return false;
71226
71513
  const completed = run.stages.filter((stage) => stage.status === "completed" && !stageIdsBeforeParallel.has(stage.id) && stage.parentIds.length === parallelParentIds.length && stage.parentIds.every((parentId, index) => parentId === parallelParentIds[index]));
@@ -73288,9 +73575,9 @@ function createDurableCachedStageRecorder(input) {
73288
73575
  return {
73289
73576
  record(name, replayKey, checkpoint, scope) {
73290
73577
  const cachedChildRunId = workflowChildRunId(checkpoint);
73291
- const runById = new Map(input.store.runs().map((run) => [run.id, run]));
73292
- if (!runById.has(input.run.id))
73293
- runById.set(input.run.id, input.run);
73578
+ const runById = {
73579
+ get: (runId) => input.store.run(runId) ?? (runId === input.run.id ? input.run : undefined)
73580
+ };
73294
73581
  const durableRootId = reciprocalWorkflowRootRunId(runById, input.run.id);
73295
73582
  const cachedDescendants = cachedChildRunId === undefined || durableRootId === undefined ? undefined : durableCompletedNestedRunSubtree(input.rootBackend, durableRootId, cachedChildRunId);
73296
73583
  if (cachedChildRunId !== undefined && durableRootId !== undefined && cachedDescendants === undefined) {
@@ -73304,7 +73591,7 @@ function createDurableCachedStageRecorder(input) {
73304
73591
  replaySourceOrders.set(replayedStage.id, sourceOrder);
73305
73592
  input.run.stages.sort((left, right) => (replaySourceOrders.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (replaySourceOrders.get(right.id) ?? Number.MAX_SAFE_INTEGER));
73306
73593
  }
73307
- const stage = input.store.runs().find((run) => run.id === input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
73594
+ const stage = input.store.run(input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
73308
73595
  const persistence = stage === undefined ? undefined : input.backend.commitCheckpoint({
73309
73596
  kind: "stage",
73310
73597
  workflowId: input.run.id,
@@ -73315,7 +73602,7 @@ function createDurableCachedStageRecorder(input) {
73315
73602
  ...durableStageCheckpointMetadata(stage, durableRunTopology(input.run), sourceOrder ?? input.run.stages.findIndex((candidate) => candidate.id === stage.id))
73316
73603
  });
73317
73604
  for (const childRun of cachedDescendants ?? []) {
73318
- const existingRun = input.store.runs().find((candidate) => candidate.id === childRun.id);
73605
+ const existingRun = input.store.run(childRun.id);
73319
73606
  const isDirectChild = childRun.id === cachedChildRunId && childRun.parentRunId === input.run.id && stage?.workflowChild?.runId === cachedChildRunId;
73320
73607
  if (existingRun !== undefined) {
73321
73608
  if (stage !== undefined && isDirectChild) {
@@ -73341,15 +73628,15 @@ function createDurableCachedStageRecorder(input) {
73341
73628
  };
73342
73629
  }
73343
73630
  function reconcileCachedDirectChildParentStage(input) {
73344
- const existingRun = input.store.runs().find((run) => run.id === input.checkpointChildRunId);
73631
+ const existingRun = input.store.run(input.checkpointChildRunId);
73345
73632
  if (existingRun === undefined)
73346
73633
  return false;
73347
- const runById = new Map(input.store.runs().map((run) => [run.id, run]));
73348
- const storedParentRun = runById.get(input.parentRun.id);
73634
+ const storedParentRun = input.store.run(input.parentRun.id);
73349
73635
  if (storedParentRun !== undefined && (storedParentRun.parentRunId !== input.parentRun.parentRunId || storedParentRun.parentStageId !== input.parentRun.parentStageId))
73350
73636
  return false;
73351
- if (storedParentRun === undefined)
73352
- runById.set(input.parentRun.id, input.parentRun);
73637
+ const runById = {
73638
+ get: (runId) => input.store.run(runId) ?? (runId === input.parentRun.id ? input.parentRun : undefined)
73639
+ };
73353
73640
  const expectedRootRunId = reciprocalWorkflowRootRunId(runById, input.parentRun.id);
73354
73641
  if (expectedRootRunId === undefined)
73355
73642
  return false;
@@ -73432,6 +73719,7 @@ function deferStageUntilRunRelease(input) {
73432
73719
 
73433
73720
  // dist/builtin/workflows/src/engine/run-rejection-boundary.ts
73434
73721
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
73722
+ import { randomUUID as randomUUID22 } from "node:crypto";
73435
73723
  import { inspect } from "node:util";
73436
73724
  import { isStaleExtensionContextError as isStaleExtensionContextError3 } from "@bastani/atomic";
73437
73725
  function boundaryBag() {
@@ -73512,9 +73800,9 @@ function recordedOwners(boundary, reason) {
73512
73800
  function pruneEndedSources(boundary) {
73513
73801
  const now = Date.now();
73514
73802
  for (const [source, trees] of boundary.ended) {
73515
- for (const [rootRunId, endedAt] of trees)
73803
+ for (const [execution, endedAt] of trees)
73516
73804
  if (now - endedAt > ENDED_RUN_GRACE_MS)
73517
- trees.delete(rootRunId);
73805
+ trees.delete(execution);
73518
73806
  if (trees.size === 0)
73519
73807
  boundary.ended.delete(source);
73520
73808
  }
@@ -73523,12 +73811,12 @@ function recordEndedRun(boundary, scope) {
73523
73811
  if (scope.source === undefined)
73524
73812
  return;
73525
73813
  const trees = boundary.ended.get(scope.source) ?? new Map;
73526
- trees.set(scope.rootRunId, Date.now());
73814
+ trees.set(scope.execution, Date.now());
73527
73815
  boundary.ended.set(scope.source, trees);
73528
73816
  }
73529
73817
  function endedInAnotherRunTree(boundary, source, live) {
73530
- for (const endedRoot of boundary.ended.get(source)?.keys() ?? [])
73531
- if (endedRoot !== live.rootRunId)
73818
+ for (const endedExecution of boundary.ended.get(source)?.keys() ?? [])
73819
+ if (endedExecution !== live.execution)
73532
73820
  return true;
73533
73821
  return false;
73534
73822
  }
@@ -73739,6 +74027,7 @@ function openRunRejectionScope(options) {
73739
74027
  const scope = {
73740
74028
  runId: options.runId,
73741
74029
  rootRunId,
74030
+ execution: parent?.execution ?? randomUUID22(),
73742
74031
  source: options.source === undefined ? undefined : normalizeStackPath(options.source),
73743
74032
  parent,
73744
74033
  fail: options.fail,
@@ -73750,8 +74039,11 @@ function openRunRejectionScope(options) {
73750
74039
  };
73751
74040
  boundary.scopes.add(scope);
73752
74041
  boundary.runs.set(scope.runId, scope);
73753
- if (scope.source !== undefined)
74042
+ if (scope.source !== undefined) {
73754
74043
  markSharedSource(boundary, scope.source);
74044
+ if (endedInAnotherRunTree(boundary, scope.source, scope))
74045
+ scope.sharedSource = true;
74046
+ }
73755
74047
  return {
73756
74048
  run: (callback) => boundary.store.run(scope, callback),
73757
74049
  contain: (promise, effect = "fail-run") => {
@@ -74126,7 +74418,7 @@ function createAdmittedToolExecutionTracker(options = {}) {
74126
74418
  // dist/builtin/workflows/src/engine/run-tool-node-lifecycle.ts
74127
74419
  function createToolNodeLifecycle(input) {
74128
74420
  const { store, tracker, run, sourceToContinuationNodeIds } = input;
74129
- const ownsCurrentRun = () => store.runs().some((candidate) => candidate === run);
74421
+ const ownsCurrentRun = () => store.run(run.id) === run;
74130
74422
  const replayedToolNodeIds = new Set;
74131
74423
  let pendingFrontier = input.resumeToolNode;
74132
74424
  const pendingRetries = new Map((input.retryToolNodes ?? []).map((node) => [node.id, node]));
@@ -74199,7 +74491,7 @@ function sameToolIdentity(node, expected) {
74199
74491
  function isReplayedContinuationNode(store, run, replayedToolNodeIds, nodeId) {
74200
74492
  if (replayedToolNodeIds.has(nodeId))
74201
74493
  return true;
74202
- const live = store.runs().find((candidate) => candidate === run);
74494
+ const live = store.run(run.id) === run ? run : undefined;
74203
74495
  return live?.stages.some((stage) => stage.id === nodeId && stage.replayed === true) === true;
74204
74496
  }
74205
74497
  function compatibleReplayedToolParents(tracker, translated, inferredParents, isReplayedNode) {
@@ -74569,7 +74861,7 @@ function createQueuedUserMessageConsumptionWatcher(armContinuation) {
74569
74861
  // dist/builtin/workflows/src/runs/foreground/blocked-stage-close.ts
74570
74862
  function closeBlockedStageForGoodWhenRunEnds(store, runId, close) {
74571
74863
  const unsubscribe = store.subscribe(() => {
74572
- const run = store.runs().find((candidate) => candidate.id === runId);
74864
+ const run = store.run(runId);
74573
74865
  if (run && (!isTerminalRunStatus(run.status) || run.resumable === true))
74574
74866
  return;
74575
74867
  unsubscribe();
@@ -74875,7 +75167,7 @@ function createTrackedStageCaller(input) {
74875
75167
  const budgetError = err instanceof WorkflowBudgetExceededError ? err : undefined;
74876
75168
  if (budgetError !== undefined && trackStageLifecycle && !runtime.state.skippedForParallelFailFast) {
74877
75169
  let selectedBudgetError = budgetError;
74878
- if (runtime.activeStore.runs().find((run) => run.id === runtime.runId)?.budgetState?.wrapUpCompleted !== true) {
75170
+ if (runtime.activeStore.run(runtime.runId)?.budgetState?.wrapUpCompleted !== true) {
74879
75171
  try {
74880
75172
  await runtime.budget.deliverWrapUp(runtime.name);
74881
75173
  } catch (wrapUpError) {
@@ -75322,7 +75614,7 @@ function createStageControlHandle(runtime) {
75322
75614
  runtime.scheduler.ensureReleaseBarrier(runtime.stageId);
75323
75615
  runtime.state.readinessController?.abort(new Error("atomic-workflows: readiness paused"));
75324
75616
  await runtime.scheduler.cascadePauseFrom(runtime.stageId);
75325
- const run = runtime.activeStore.runs().find((candidate) => candidate.id === runtime.runId);
75617
+ const run = runtime.activeStore.run(runtime.runId);
75326
75618
  const stillActive = run?.stages.some((stage) => stage.status === "running" && stage.id !== runtime.stageId) ?? false;
75327
75619
  if (!stillActive)
75328
75620
  runtime.activeStore.recordRunPaused(runtime.runId);
@@ -79310,7 +79602,7 @@ function createWorkflowStageFactory(input) {
79310
79602
  defaultSessionDir: input.opts.defaultSessionDir,
79311
79603
  defaultCwd: input.workflowInvocationCwd,
79312
79604
  onStartupChange(startup) {
79313
- const current = input.activeStore.runs().find((run) => run.id === input.runId);
79605
+ const current = input.activeStore.run(input.runId);
79314
79606
  if (!current?.stages.includes(stageSnapshot))
79315
79607
  return;
79316
79608
  stageSnapshot.startup = startup;
@@ -79799,7 +80091,7 @@ async function run(def, inputs, opts = {}) {
79799
80091
  const resolvedInputs = resolveAndValidateInputs(def.inputs, inputs, `workflow "${def.name}"`);
79800
80092
  const runId = opts.runId ?? crypto.randomUUID();
79801
80093
  const activeStore = opts.store ?? store;
79802
- const preset = opts.durableBackend ?? (opts.journal === undefined ? availableRunDurableBackend(activeStore.runs(), opts.continuation?.source.id ?? runId) ?? availableStoreDurableBackendOverride(activeStore) : undefined);
80094
+ const preset = opts.durableBackend ?? (opts.journal === undefined ? availableRunDurableBackend(activeStore, opts.continuation?.source.id ?? runId) ?? availableStoreDurableBackendOverride(activeStore) : undefined);
79803
80095
  const backend = preset ?? await initializeDurableBackend({ journal: opts.journal, cwd: opts.cwd });
79804
80096
  const publicResources = opts.parentRun === undefined && (opts.localWorkers || opts.admission || backend.getWorkflow(opts.continuation?.source.id ?? runId)?.resources);
79805
80097
  if (publicResources)
@@ -79835,7 +80127,7 @@ async function executeRun(def, resolvedInputs, opts) {
79835
80127
  }
79836
80128
  const declaresBudget = (budget) => (budget?.maxDurationMs ?? 0) > 0 || (budget?.maxTokens ?? 0) > 0 || (budget?.maxCost ?? 0) > 0;
79837
80129
  const hasBudgetDeclaration = declaresBudget(opts.budget) || declaresBudget(def.budget) || declaresBudget(opts.config?.budget);
79838
- const priorRun = hasBudgetDeclaration && opts.rootBudget === undefined && opts.continuation === undefined && opts.runId !== undefined ? activeStore.runs().find((candidate) => candidate.id === runId) : undefined;
80130
+ const priorRun = hasBudgetDeclaration && opts.rootBudget === undefined && opts.continuation === undefined && opts.runId !== undefined ? activeStore.run(runId) : undefined;
79839
80131
  const continuedBudget = opts.continuation?.source.budget ?? priorRun?.budget;
79840
80132
  const runBudget = opts.budget === undefined ? continuedBudget : { ...continuedBudget ?? {}, ...opts.budget };
79841
80133
  const resolvedBudget = resolve_budget({ config: opts.config?.budget, definition: def.budget, run: runBudget });
@@ -79910,17 +80202,8 @@ async function executeRun(def, resolvedInputs, opts) {
79910
80202
  if (opts.parentRun === undefined)
79911
80203
  bindRunDurableBackend(runSnapshot, rootBackend);
79912
80204
  const usageTree = () => {
79913
- const snapshots = activeStore.runs();
79914
- const childrenByParent = new Map;
79915
- for (const snapshot of snapshots) {
79916
- if (snapshot.parentRunId === undefined)
79917
- continue;
79918
- const children = childrenByParent.get(snapshot.parentRunId) ?? [];
79919
- children.push(snapshot);
79920
- childrenByParent.set(snapshot.parentRunId, children);
79921
- }
79922
80205
  const build = (run) => {
79923
- const children = (childrenByParent.get(run.id) ?? []).map(build);
80206
+ const children = activeStore.childRuns(run.id).map(build);
79924
80207
  return children.length === 0 ? { run } : { run, children };
79925
80208
  };
79926
80209
  return build(runSnapshot);
@@ -80303,7 +80586,7 @@ async function executeRun(def, resolvedInputs, opts) {
80303
80586
  return recorded;
80304
80587
  };
80305
80588
  const durableIntercomGroup = (replayKey, stageId) => {
80306
- const stages = activeStore.runs().find((candidate) => candidate.id === runId)?.stages ?? [];
80589
+ const stages = activeStore.run(runId)?.stages ?? [];
80307
80590
  return stages.find((stage) => stageId !== undefined && stage.id === stageId || stage.replayKey === replayKey)?.intercomGroup;
80308
80591
  };
80309
80592
  let observedTaskTailQuit;
@@ -80356,7 +80639,7 @@ async function executeRun(def, resolvedInputs, opts) {
80356
80639
  recordCachedStage,
80357
80640
  stage: (name, options, replayKey) => {
80358
80641
  const stage = runtime.stage(name, options);
80359
- const stageId = activeStore.runs().find((r) => r.id === runId)?.stages.at(-1)?.id;
80642
+ const stageId = activeStore.run(runId)?.stages.at(-1)?.id;
80360
80643
  if (stageId !== undefined)
80361
80644
  completedStageReplayKeys.set(stageId, replayKey);
80362
80645
  return stage;
@@ -80878,18 +81161,18 @@ var init_executor = __esm(() => {
80878
81161
  });
80879
81162
 
80880
81163
  // dist/builtin/workflows/src/runs/foreground/sdk-run.ts
80881
- import { randomUUID as randomUUID22 } from "node:crypto";
81164
+ import { randomUUID as randomUUID23 } from "node:crypto";
80882
81165
  async function run2(def, inputs, callerOpts = {}) {
80883
81166
  let opts = callerOpts;
80884
81167
  const store2 = opts.store === undefined || opts.store === store ? currentWorkflowStore() : opts.store;
80885
81168
  const sourceRunId = opts.continuation?.source.id ?? opts.runId;
80886
- const ownedBackend = sourceRunId === undefined ? undefined : availableRunDurableBackend(store2.runs(), sourceRunId);
81169
+ const ownedBackend = sourceRunId === undefined ? undefined : availableRunDurableBackend(store2, sourceRunId);
80887
81170
  const preset = opts.journal === undefined ? opts.durableBackend ?? ownedBackend ?? availableStoreDurableBackendOverride(store2) : undefined;
80888
81171
  const backend = preset ?? await initializeDurableBackend({ journal: opts.journal, cwd: opts.cwd });
80889
81172
  if (opts.journal === undefined && opts.durableBackend === undefined && ownedBackend === undefined) {
80890
81173
  bindStoreDurableBackend(store2, backend);
80891
81174
  }
80892
- const runId = opts.runId ?? randomUUID22();
81175
+ const runId = opts.runId ?? randomUUID23();
80893
81176
  if (sourceRunId !== undefined || opts.localWorkers || opts.admission) {
80894
81177
  opts = await restoreWorkerOptions(backend, { ...opts, runId });
80895
81178
  }