@bastani/atomic 0.9.68-alpha.1 → 0.9.69-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -1041,6 +1041,7 @@ class JournalProjection {
1041
1041
  return {
1042
1042
  resumable: this.listResumableWorkflows(),
1043
1043
  completed: this.listCompletedWorkflows(),
1044
+ completedAll: this.listFinishedRootWorkflows(),
1044
1045
  inspectableIds: [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle)).map((rec) => rec.handle.workflowId)
1045
1046
  };
1046
1047
  }
@@ -1072,6 +1073,9 @@ class JournalProjection {
1072
1073
  listCompletedWorkflows() {
1073
1074
  return [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle) && isHistoricalHandle(rec.handle)).map((rec) => toResumableEntry(rec.handle));
1074
1075
  }
1076
+ listFinishedRootWorkflows() {
1077
+ return [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle) && isTerminalStatus(rec.handle.status)).map((rec) => toResumableEntry(rec.handle));
1078
+ }
1075
1079
  toMetadata(workflowId) {
1076
1080
  const rec = this.workflows.get(workflowId);
1077
1081
  if (!rec)
@@ -1130,6 +1134,9 @@ class JournalProjection {
1130
1134
  function isRootWorkflow(handle) {
1131
1135
  return handle.rootWorkflowId === undefined || handle.rootWorkflowId === handle.workflowId;
1132
1136
  }
1137
+ function isTerminalStatus(status) {
1138
+ return status === "completed" || status === "failed" || status === "cancelled";
1139
+ }
1133
1140
  function hasResumeProgress(handle) {
1134
1141
  return handle.completedCheckpoints > 0 || handle.pendingPrompts > 0;
1135
1142
  }
@@ -6344,6 +6351,18 @@ function reciprocalWorkflowRootRunId(runById, runId) {
6344
6351
  }
6345
6352
  return;
6346
6353
  }
6354
+ function isRunLookup(source) {
6355
+ return "run" in source;
6356
+ }
6357
+ function runsInSource(source) {
6358
+ return isRunLookup(source) ? source.runs() : source;
6359
+ }
6360
+ function findRunInSource(source, runId) {
6361
+ return isRunLookup(source) ? source.run(runId) : source.find((run) => run.id === runId);
6362
+ }
6363
+ function runsByIdOf(source) {
6364
+ return isRunLookup(source) ? { get: (runId) => source.run(runId) } : new Map(source.map((run) => [run.id, run]));
6365
+ }
6347
6366
  function index(items, cache) {
6348
6367
  let byId = cache.get(items);
6349
6368
  if (byId === undefined) {
@@ -6362,6 +6381,29 @@ function findSnapshotRun(runs, runId) {
6362
6381
  function findSnapshotStage(stages, stageId) {
6363
6382
  return Object.isFrozen(stages) ? index(stages, stageIndexes).get(stageId) : stages.find((stage) => stage.id === stageId);
6364
6383
  }
6384
+ function childRunsInSource(source, parentRunId, parentStageId) {
6385
+ if (isRunLookup(source) && source.childRuns !== undefined)
6386
+ return source.childRuns(parentRunId, parentStageId);
6387
+ return runsInSource(source).filter((run) => run.parentRunId === parentRunId && (parentStageId === undefined || run.parentStageId === parentStageId));
6388
+ }
6389
+ function invocationRunsInSource(source, rootRunId) {
6390
+ const byId = runsByIdOf(source);
6391
+ const inInvocation = (run) => reciprocalWorkflowRootRunId(byId, run.id) === rootRunId;
6392
+ if (!isRunLookup(source) || source.childRuns === undefined || source.runPosition === undefined)
6393
+ return runsInSource(source).filter(inInvocation);
6394
+ const root = source.run(rootRunId);
6395
+ if (root === undefined)
6396
+ return [];
6397
+ const seen = new Set([root.id]);
6398
+ const found = [root];
6399
+ for (let index = 0;index < found.length; index++)
6400
+ for (const child of source.childRuns(found[index].id))
6401
+ if (!seen.has(child.id)) {
6402
+ seen.add(child.id);
6403
+ found.push(child);
6404
+ }
6405
+ return found.filter(inInvocation).sort((left, right) => source.runPosition(left.id) - source.runPosition(right.id));
6406
+ }
6365
6407
  var runIndexes, stageIndexes;
6366
6408
  var init_workflow_run_ownership = __esm(() => {
6367
6409
  runIndexes = new WeakMap;
@@ -6590,19 +6632,20 @@ function bindRunDurableBackend(run, backend) {
6590
6632
  Object.defineProperty(run, workflowRunBackend, { value: backend });
6591
6633
  }
6592
6634
  function availableRunDurableBackend(runs, runId) {
6593
- const target = resolveRunIdTarget(runId, runs.map((run) => run.id));
6635
+ const target = resolveRunIdTarget(runId, isRunIdPrefix(runId) ? runsInSource(runs).map((run) => run.id) : []);
6594
6636
  const id = target.kind === "exact" || target.kind === "unique_prefix" ? target.runId : runId;
6595
6637
  const rootRunId = durableRootRunIdForRun(runs, id);
6596
- return runs.find((run) => run.id === rootRunId)?.[workflowRunBackend];
6638
+ const rootRun = rootRunId === undefined ? undefined : findRunInSource(runs, rootRunId);
6639
+ return rootRun?.[workflowRunBackend];
6597
6640
  }
6598
6641
  function durableRootRunIdForRun(runs, runId) {
6599
- return reciprocalWorkflowRootRunId(new Map(runs.map((run) => [run.id, run])), runId);
6642
+ return reciprocalWorkflowRootRunId(runsByIdOf(runs), runId);
6600
6643
  }
6601
6644
  function durableBackendForRun(backend, runs, runId) {
6602
6645
  const rootRunId = durableRootRunIdForRun(runs, runId);
6603
6646
  if (rootRunId === undefined)
6604
6647
  return;
6605
- const runById = new Map(runs.map((run) => [run.id, run]));
6648
+ const runById = runsByIdOf(runs);
6606
6649
  const rootBackend = availableRunDurableBackend(runs, rootRunId) ?? backend;
6607
6650
  if (rootRunId === runId)
6608
6651
  return rootBackend;
@@ -6640,7 +6683,7 @@ function bindStoreDurableBackend(store, backend) {
6640
6683
  store[workflowStoreBackend] = backend;
6641
6684
  }
6642
6685
  function availableStoreDurableBackend(store, runId) {
6643
- return (store !== undefined && runId !== undefined ? availableRunDurableBackend(store.runs(), runId) : undefined) ?? store?.[workflowStoreBackend];
6686
+ return (store !== undefined && runId !== undefined ? availableRunDurableBackend(store, runId) : undefined) ?? store?.[workflowStoreBackend];
6644
6687
  }
6645
6688
  function requireStoreDurableBackend(store, runId) {
6646
6689
  const backend = availableStoreDurableBackend(store, runId);
@@ -7510,6 +7553,8 @@ function createStoreState() {
7510
7553
  return {
7511
7554
  runs: [],
7512
7555
  runPositions: new Map,
7556
+ childRunIds: new Map,
7557
+ childRunLinks: new Map,
7513
7558
  notices: [],
7514
7559
  listeners: new Set,
7515
7560
  invalidationListeners: new Set,
@@ -7521,11 +7566,41 @@ function createStoreState() {
7521
7566
  }
7522
7567
  function reindexRuns(state) {
7523
7568
  state.runPositions.clear();
7569
+ state.childRunIds.clear();
7570
+ state.childRunLinks.clear();
7524
7571
  state.runs.forEach((run, position) => {
7525
- if (!state.runPositions.has(run.id))
7526
- state.runPositions.set(run.id, position);
7572
+ if (state.runPositions.has(run.id))
7573
+ return;
7574
+ state.runPositions.set(run.id, position);
7575
+ indexChildRun(state, run);
7527
7576
  });
7528
7577
  }
7578
+ function indexChildRun(state, run) {
7579
+ unindexChildRun(state, run.id);
7580
+ if (run.parentRunId === undefined)
7581
+ return;
7582
+ const byStage = state.childRunIds.get(run.parentRunId) ?? new Map;
7583
+ state.childRunIds.set(run.parentRunId, byStage);
7584
+ const ids = byStage.get(run.parentStageId) ?? new Set;
7585
+ byStage.set(run.parentStageId, ids);
7586
+ ids.add(run.id);
7587
+ state.childRunLinks.set(run.id, { parentRunId: run.parentRunId, parentStageId: run.parentStageId });
7588
+ }
7589
+ function unindexChildRun(state, runId) {
7590
+ const link = state.childRunLinks.get(runId);
7591
+ if (link === undefined)
7592
+ return;
7593
+ state.childRunLinks.delete(runId);
7594
+ const byStage = state.childRunIds.get(link.parentRunId);
7595
+ const ids = byStage?.get(link.parentStageId);
7596
+ if (byStage === undefined || ids === undefined)
7597
+ return;
7598
+ ids.delete(runId);
7599
+ if (ids.size === 0)
7600
+ byStage.delete(link.parentStageId);
7601
+ if (byStage.size === 0)
7602
+ state.childRunIds.delete(link.parentRunId);
7603
+ }
7529
7604
  function runPosition(state, runId) {
7530
7605
  const position = state.runPositions.get(runId);
7531
7606
  if (position !== undefined && state.runs[position]?.id === runId)
@@ -7569,13 +7644,14 @@ function createStoreContext(state = createStoreState()) {
7569
7644
  batchedChanges?.push(change);
7570
7645
  return;
7571
7646
  }
7572
- observation.capture(change === undefined ? undefined : [change]);
7573
- publish();
7647
+ const changes = change === undefined ? undefined : [change];
7648
+ observation.capture(changes);
7649
+ publish(changes);
7574
7650
  }
7575
- function publish() {
7651
+ function publish(changes) {
7576
7652
  for (const fn of state.invalidationListeners) {
7577
7653
  try {
7578
- fn();
7654
+ fn(changes);
7579
7655
  } catch {}
7580
7656
  }
7581
7657
  if (state.listeners.size > 0) {
@@ -7602,7 +7678,7 @@ function createStoreContext(state = createStoreState()) {
7602
7678
  batchedNotification = false;
7603
7679
  batchedChanges = [];
7604
7680
  observation.capture(changes);
7605
- publish();
7681
+ publish(changes);
7606
7682
  }
7607
7683
  }
7608
7684
  }
@@ -7614,22 +7690,40 @@ function createStoreContext(state = createStoreState()) {
7614
7690
  const position = runPosition(state, run.id);
7615
7691
  if (position !== undefined) {
7616
7692
  state.runs[position] = run;
7693
+ indexChildRun(state, run);
7617
7694
  return;
7618
7695
  }
7619
7696
  state.runPositions.set(run.id, state.runs.length);
7620
7697
  state.runs.push(run);
7698
+ indexChildRun(state, run);
7621
7699
  }
7622
7700
  function removeRunAt(position) {
7623
7701
  const [removed] = state.runs.splice(position, 1);
7624
7702
  if (removed === undefined)
7625
7703
  return;
7626
7704
  state.runPositions.delete(removed.id);
7705
+ unindexChildRun(state, removed.id);
7627
7706
  for (let index = position;index < state.runs.length; index++)
7628
7707
  state.runPositions.set(state.runs[index].id, index);
7629
7708
  }
7630
7709
  function clearRuns() {
7631
7710
  state.runs.length = 0;
7632
7711
  state.runPositions.clear();
7712
+ state.childRunIds.clear();
7713
+ state.childRunLinks.clear();
7714
+ }
7715
+ function childRuns(parentRunId, parentStageId) {
7716
+ if (state.runPositions.size !== state.runs.length)
7717
+ reindexRuns(state);
7718
+ const byStage = state.childRunIds.get(parentRunId);
7719
+ if (byStage === undefined)
7720
+ return [];
7721
+ const ids = parentStageId === undefined ? [...byStage.values()].flatMap((set) => [...set]) : [...byStage.get(parentStageId) ?? []];
7722
+ 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));
7723
+ }
7724
+ function reparentRun(run, parentStageId) {
7725
+ run.parentStageId = parentStageId;
7726
+ indexChildRun(state, run);
7633
7727
  }
7634
7728
  function findStage(run, stageId) {
7635
7729
  return run.stages.find((s) => s.id === stageId);
@@ -7686,6 +7780,8 @@ function createStoreContext(state = createStoreState()) {
7686
7780
  bumpAndNotify,
7687
7781
  findRun,
7688
7782
  runPosition: (runId) => runPosition(state, runId),
7783
+ childRuns,
7784
+ reparentRun,
7689
7785
  placeRun,
7690
7786
  removeRunAt,
7691
7787
  clearRuns,
@@ -7858,13 +7954,13 @@ function recordPendingStageMessageDeliveries(messages, runId, messageId, records
7858
7954
  result[index] = next;
7859
7955
  return result;
7860
7956
  }
7861
- function compactStickyStageMessageDeliveries(messages, runs) {
7862
- 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]))));
7957
+ function compactStickyStageMessageDeliveries(messages, findRun) {
7958
+ const finished = (runId, stageId) => findRun(runId)?.stages.some((stage) => stage.id === stageId && (stage.status === "completed" || stage.status === "skipped")) === true;
7863
7959
  let changed = false;
7864
7960
  const next = messages.map((entry) => {
7865
7961
  if (entry.sticky !== true || entry.deliveries === undefined)
7866
7962
  return entry;
7867
- const deliveries = entry.deliveries.filter((delivery) => !finished.has(JSON.stringify([delivery.runId, delivery.stageId])));
7963
+ const deliveries = entry.deliveries.filter((delivery) => !finished(delivery.runId, delivery.stageId));
7868
7964
  if (deliveries.length === entry.deliveries.length)
7869
7965
  return entry;
7870
7966
  changed = true;
@@ -8033,8 +8129,8 @@ class PendingStageTransitionLedger {
8033
8129
  this.reconciledVersion = version;
8034
8130
  return result;
8035
8131
  }
8036
- async compact(backend, runId, messages, runs, archiveSettled) {
8037
- const stageStatus = createStageStatusLookup(runs);
8132
+ async compact(backend, runId, messages, findRun, archiveSettled) {
8133
+ const stageStatus = createStageStatusLookup(findRun);
8038
8134
  const endedStages = [];
8039
8135
  const dirty = new Set;
8040
8136
  for (const [deliveryRunId, byStage] of this.stages) {
@@ -8132,17 +8228,8 @@ class PendingStageTransitionLedger {
8132
8228
  function isCompactingBackend(backend) {
8133
8229
  return backend.archivePendingStageDeliveryReceipt !== undefined && backend.hasPendingStageDeliveryReceipt !== undefined;
8134
8230
  }
8135
- function createStageStatusLookup(runs) {
8136
- let runById;
8137
- return (runId, stageId) => {
8138
- if (runById === undefined) {
8139
- runById = new Map;
8140
- for (const run of runs)
8141
- if (!runById.has(run.id))
8142
- runById.set(run.id, run);
8143
- }
8144
- return runById.get(runId)?.stages.find((stage) => stage.id === stageId)?.status;
8145
- };
8231
+ function createStageStatusLookup(findRun) {
8232
+ return (runId, stageId) => findRun(runId)?.stages.find((stage) => stage.id === stageId)?.status;
8146
8233
  }
8147
8234
  function isEndedStageStatus(status) {
8148
8235
  return status === "completed" || status === "skipped" || status === "failed";
@@ -8182,6 +8269,7 @@ var init_pending_stage_transition_ledger = () => {};
8182
8269
 
8183
8270
  // dist/builtin/workflows/src/shared/store-pending-stage-delivery-methods.ts
8184
8271
  function createPendingStageDeliveryStoreMethods(context) {
8272
+ const runs = { run: context.findRun, runs: () => context.state.runs };
8185
8273
  const ledgers = new PendingStageLedgers;
8186
8274
  const batches = new PendingStageTransitionBatches(context, ledgers);
8187
8275
  return {
@@ -8204,8 +8292,8 @@ function createPendingStageDeliveryStoreMethods(context) {
8204
8292
  const run = context.findRun(input.runId);
8205
8293
  if (run === undefined)
8206
8294
  return;
8207
- const availableBackend = availableRunDurableBackend(context.state.runs, input.runId) ?? context.backend;
8208
- const backend = availableBackend === undefined ? undefined : durableBackendForRun(availableBackend, context.state.runs, input.runId);
8295
+ const availableBackend = availableRunDurableBackend(runs, input.runId) ?? context.backend;
8296
+ const backend = availableBackend === undefined ? undefined : durableBackendForRun(availableBackend, runs, input.runId);
8209
8297
  const receipt = await backend?.readSettledPendingStageMessage?.(input.runId, input.message.id);
8210
8298
  const result = queueStageMessage(receipt === undefined ? batch.messages(run) : [...batch.messages(run), receipt], input, undefined, undefined, resolvePendingStageIdentity(run, input.stageKey));
8211
8299
  if (!result.ok) {
@@ -8428,7 +8516,7 @@ class PendingStageTransitionBatch {
8428
8516
  }
8429
8517
  if (messages !== run.pendingStageMessages) {
8430
8518
  run.pendingStageMessages = [...messages];
8431
- this.context.bumpAndNotify();
8519
+ this.context.bumpAndNotify({ runId: run.id });
8432
8520
  }
8433
8521
  }
8434
8522
  async apply(backend, runId, messages) {
@@ -8464,7 +8552,7 @@ class PendingStageTransitionBatch {
8464
8552
  const live = this.context.findRun(this.runId) ?? run;
8465
8553
  if (live !== undefined)
8466
8554
  live.pendingStageMessages = [...published];
8467
- this.context.bumpAndNotify();
8555
+ this.context.bumpAndNotify({ runId: this.runId });
8468
8556
  }
8469
8557
  }
8470
8558
  async function compactTransition(backend, runId, messages, context, ledgers, run) {
@@ -8472,9 +8560,9 @@ async function compactTransition(backend, runId, messages, context, ledgers, run
8472
8560
  const reconciled = ledger.reconcile(backend, runId, messages);
8473
8561
  const archiveSettled = backend.archivePendingStageMessage !== undefined && backend.readSettledPendingStageMessage !== undefined ? (entry) => backend.archivePendingStageMessage(runId, entry) : undefined;
8474
8562
  if (isCompactingBackend(backend)) {
8475
- return await ledger.compact(backend, runId, reconciled, context.state.runs, archiveSettled);
8563
+ return await ledger.compact(backend, runId, reconciled, context.findRun, archiveSettled);
8476
8564
  }
8477
- let retained = compactStickyStageMessageDeliveries(reconciled, context.state.runs);
8565
+ let retained = compactStickyStageMessageDeliveries(reconciled, context.findRun);
8478
8566
  if (archiveSettled !== undefined)
8479
8567
  retained = await retainPendingStageMessages(retained, archiveSettled);
8480
8568
  if (run !== undefined)
@@ -8489,7 +8577,7 @@ function reconcileLive(backend, runId, context, ledgers) {
8489
8577
  const recovered = ledgers.for(current).reconcile(backend, runId, messages);
8490
8578
  if (recovered !== messages) {
8491
8579
  current.pendingStageMessages = [...recovered];
8492
- context.bumpAndNotify();
8580
+ context.bumpAndNotify({ runId });
8493
8581
  }
8494
8582
  }
8495
8583
 
@@ -8773,6 +8861,12 @@ function createRunStoreMethods(context) {
8773
8861
  run(runId) {
8774
8862
  return context.findRun(runId);
8775
8863
  },
8864
+ runPosition(runId) {
8865
+ return context.runPosition(runId);
8866
+ },
8867
+ childRuns(parentRunId, parentStageId) {
8868
+ return context.childRuns(parentRunId, parentStageId);
8869
+ },
8776
8870
  notices() {
8777
8871
  return state.notices;
8778
8872
  },
@@ -8815,7 +8909,7 @@ function createRunStoreMethods(context) {
8815
8909
  const run = context.findRun(runId);
8816
8910
  if (run?.parentStageId !== expectedParentStageId || parentStageId === expectedParentStageId)
8817
8911
  return false;
8818
- run.parentStageId = parentStageId;
8912
+ context.reparentRun(run, parentStageId);
8819
8913
  context.bumpAndNotify();
8820
8914
  return true;
8821
8915
  },
@@ -13142,7 +13236,7 @@ function recordCachedStageWithTracker(store, tracker, runId, name, replayKey, ch
13142
13236
  const stageId = sourceStageId ?? cachedStageId(runId, replayKey);
13143
13237
  let parentIds = tracker.onSpawn(stageId, name);
13144
13238
  const sourceParents = sourceStageId === undefined ? undefined : checkpoint.topology?.parentIds;
13145
- const run = store.runs().find((candidate) => candidate.id === runId);
13239
+ const run = store.run(runId);
13146
13240
  const restored = sourceParents?.map((sourceId) => sourceToReplayedNodeIds?.get(sourceId) ?? run?.stages.find((stage) => stage.id === sourceId || stage.replayedFromStageId === sourceId)?.id);
13147
13241
  if (restored?.every((id) => id !== undefined)) {
13148
13242
  parentIds = restored;
@@ -13553,7 +13647,7 @@ function createWorkflowArtifactRunStateResolver() {
13553
13647
  let durable;
13554
13648
  if (backend !== undefined) {
13555
13649
  try {
13556
- durable = durableRunState(availableRunDurableBackend(store.runs(), runId) ?? backend, runId);
13650
+ durable = durableRunState(availableRunDurableBackend(store, runId) ?? backend, runId);
13557
13651
  } catch {
13558
13652
  backendReady = false;
13559
13653
  return localState === "protected" ? "protected" : undefined;
@@ -15791,7 +15885,8 @@ function runResultFromSnapshot(snapshot) {
15791
15885
  };
15792
15886
  }
15793
15887
  function reconcileTerminalRunResult(runId, runSnapshot, activeStore, fallback, onRunEnd) {
15794
- const canonical = activeStore.runs().find((snapshot) => snapshot.id === runId && isTerminalRunStatus(snapshot.status));
15888
+ const stored = activeStore.run(runId);
15889
+ const canonical = stored !== undefined && isTerminalRunStatus(stored.status) ? stored : undefined;
15795
15890
  const result = canonical !== undefined ? runResultFromSnapshot(canonical) : {
15796
15891
  runId,
15797
15892
  ...fallback,
@@ -16398,7 +16493,7 @@ function continuationPromptAnswer(store, sourceRun, sourceStage) {
16398
16493
  return answer;
16399
16494
  if (!stage.replayed || stage.replayedFromStageId === undefined || run.resumedFromRunId === undefined)
16400
16495
  break;
16401
- const parentRun = store.runs().find((candidate) => candidate.id === run.resumedFromRunId);
16496
+ const parentRun = store.run(run.resumedFromRunId);
16402
16497
  const parentStage = parentRun?.stages.find((candidate) => candidate.id === stage.replayedFromStageId);
16403
16498
  if (parentRun === undefined || parentStage === undefined)
16404
16499
  break;
@@ -61320,7 +61415,24 @@ function isAddressableStageStatus(status) {
61320
61415
  return ADDRESSABLE_STAGE_STATUSES.has(status);
61321
61416
  }
61322
61417
  function workflowBoundarySegments(runs, runId) {
61323
- return createWorkflowBoundarySegmentsResolver(runs)(runId);
61418
+ const source = runs;
61419
+ if (!isRunLookup(source) || source.childRuns === undefined)
61420
+ return createWorkflowBoundarySegmentsResolver(runsInSource(source))(runId);
61421
+ const segments = [];
61422
+ let current = source.run(runId);
61423
+ while (current !== undefined && current.parentRunId !== undefined) {
61424
+ const parent = findRunInSource(source, current.parentRunId);
61425
+ const boundary = parent?.stages.find((stage) => stage.id === current?.parentStageId);
61426
+ if (parent === undefined || boundary === undefined)
61427
+ return;
61428
+ const boundaryName = boundary.name;
61429
+ const byId = parent.stages.filter((stage) => stage.id === boundaryName);
61430
+ const matching = byId.length > 0 ? byId : parent.stages.filter((stage) => stage.name === boundaryName);
61431
+ const children = matching.length === 1 ? childRunsInSource(source, parent.id, matching[0].id) : undefined;
61432
+ segments.unshift(boundaryName.length > 0 && !boundaryName.includes("/") && !boundaryName.includes("*") && children?.length === 1 && children[0]?.id === current.id ? boundaryName : current.id);
61433
+ current = parent;
61434
+ }
61435
+ return current === undefined ? undefined : segments;
61324
61436
  }
61325
61437
  function createWorkflowBoundarySegmentsResolver(runs) {
61326
61438
  const runById = new Map(runs.map((run) => [run.id, run]));
@@ -61373,10 +61485,10 @@ function createWorkflowBoundarySegmentsResolver(runs) {
61373
61485
  };
61374
61486
  }
61375
61487
  function workflowBoundaryHops(runs, runId) {
61376
- return boundaryHopsFrom(new Map(runs.map((run) => [run.id, run])), runId);
61488
+ return boundaryHopsFrom(runsByIdOf(runs), runId);
61377
61489
  }
61378
61490
  function createWorkflowBoundaryHopsResolver(runs) {
61379
- const runById = new Map(runs.map((run) => [run.id, run]));
61491
+ const runById = runsByIdOf(runs);
61380
61492
  const cache = new Map;
61381
61493
  return (runId) => {
61382
61494
  if (cache.has(runId))
@@ -61444,6 +61556,7 @@ function createStagePathPatternIndex(patterns) {
61444
61556
  var ADDRESSABLE_STAGE_STATUSES;
61445
61557
  var init_pending_stage_status = __esm(() => {
61446
61558
  init_store_internal();
61559
+ init_workflow_run_ownership();
61447
61560
  init_workflow_stage_target();
61448
61561
  ADDRESSABLE_STAGE_STATUSES = new Set([
61449
61562
  "pending",
@@ -61508,27 +61621,44 @@ function boundPossibleStageDeliveryStates(states) {
61508
61621
 
61509
61622
  class WorkflowTopologyIndex {
61510
61623
  lineage = [];
61624
+ lineageStarts = new Map;
61511
61625
  runById = new Map;
61512
61626
  roots = new Map;
61513
61627
  hops = new Map;
61514
61628
  refresh(runs) {
61515
61629
  const runById = new Map(runs.map((run) => [run.id, run]));
61516
61630
  const lineage = [];
61631
+ const lineageStarts = new Map;
61517
61632
  for (const run of runs) {
61518
- lineage.push(run.id, run.rootRunId, run.parentRunId, run.parentStageId);
61519
- if (run.parentRunId === undefined)
61520
- continue;
61521
- const parent = runById.get(run.parentRunId);
61522
- const boundary = parent?.stages.find((stage) => stage.id === run.parentStageId);
61523
- lineage.push(parent !== undefined, boundary?.name, authoritativeWorkflowChildRunId(boundary));
61633
+ lineageStarts.set(run.id, lineage.length);
61634
+ pushLineage(lineage, run, runById);
61524
61635
  }
61525
61636
  if (sameValues(lineage, this.lineage))
61526
61637
  return;
61527
61638
  this.lineage = lineage;
61639
+ this.lineageStarts = lineageStarts;
61528
61640
  this.runById = runById;
61529
61641
  this.roots.clear();
61530
61642
  this.hops.clear();
61531
61643
  }
61644
+ holds(source, runIds) {
61645
+ const runs = { get: (runId) => source.run(runId) };
61646
+ const values = [];
61647
+ const unchanged = (run) => {
61648
+ const start = this.lineageStarts.get(run.id);
61649
+ if (start === undefined)
61650
+ return false;
61651
+ values.length = 0;
61652
+ pushLineage(values, run, runs);
61653
+ return values.every((value2, index) => this.lineage[start + index] === value2);
61654
+ };
61655
+ for (const runId of runIds) {
61656
+ const run = source.run(runId);
61657
+ if (run === undefined || !unchanged(run) || !source.childRuns(runId).every(unchanged))
61658
+ return false;
61659
+ }
61660
+ return true;
61661
+ }
61532
61662
  rootOf(runId) {
61533
61663
  if (this.roots.has(runId))
61534
61664
  return this.roots.get(runId);
@@ -61544,6 +61674,14 @@ class WorkflowTopologyIndex {
61544
61674
  return hops;
61545
61675
  }
61546
61676
  }
61677
+ function pushLineage(values, run, runs) {
61678
+ values.push(run.id, run.rootRunId, run.parentRunId, run.parentStageId);
61679
+ if (run.parentRunId === undefined)
61680
+ return;
61681
+ const parent = runs.get(run.parentRunId);
61682
+ const boundary = parent?.stages.find((stage) => stage.id === run.parentStageId);
61683
+ values.push(parent !== undefined, boundary?.name, authoritativeWorkflowChildRunId(boundary));
61684
+ }
61547
61685
  function boundaryHops(runById, runId) {
61548
61686
  const hops = [];
61549
61687
  let current = runById.get(runId);
@@ -61588,12 +61726,12 @@ class PossibleStageRowsIndex {
61588
61726
  this.rootRunId = rootRunId;
61589
61727
  this.topology = topology;
61590
61728
  }
61591
- rows(runs, rootRun, availableBackend) {
61729
+ rows(runs, rootRun, availableBackend, lookup = runs) {
61592
61730
  if (isTerminalRunStatus(rootRun.status))
61593
61731
  return [];
61594
61732
  this.refreshEntries(rootRun.pendingStageMessages ?? []);
61595
- const resolvedBackend = availableRunDurableBackend(runs, this.rootRunId) ?? availableBackend;
61596
- const backend = resolvedBackend === undefined ? undefined : durableBackendForRun(resolvedBackend, runs, this.rootRunId);
61733
+ const resolvedBackend = availableRunDurableBackend(lookup, this.rootRunId) ?? availableBackend;
61734
+ const backend = resolvedBackend === undefined ? undefined : durableBackendForRun(resolvedBackend, lookup, this.rootRunId);
61597
61735
  this.refreshReceipts(backend);
61598
61736
  this.refreshStages(runs);
61599
61737
  for (const state of this.patterns)
@@ -62118,9 +62256,90 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62118
62256
  }
62119
62257
  return index;
62120
62258
  };
62121
- const announceRoutes = () => {
62122
- if (disposed)
62259
+ let rootRunMembers = new Map;
62260
+ const membersOf = (rootRunId) => (rootRunMembers.get(rootRunId) ?? []).flatMap((runId) => {
62261
+ const run = activeStore.run(runId);
62262
+ return run === undefined ? [] : [run];
62263
+ });
62264
+ const dropRoute = (runId) => {
62265
+ announcedRoutes.delete(runId);
62266
+ routeCompletions.delete(runId);
62267
+ possibleStageRowIndexes.delete(runId);
62268
+ };
62269
+ const unpublishedRunIds = new Set;
62270
+ const announceRun = (run, rootRunId, lookups) => {
62271
+ const parentRun = lookups.parentOf(run);
62272
+ const boundary = parentRun?.stages.find((stage) => stage.id === run.parentStageId);
62273
+ const parent = parentRun === undefined || boundary === undefined ? undefined : {
62274
+ runId: parentRun.id,
62275
+ stageKeys: [boundary.id, boundary.name].filter((key) => lookups.childAt(parentRun, key)?.id === run.id)
62276
+ };
62277
+ let possibleStages;
62278
+ if (run.id === rootRunId && isTerminalRunStatus(run.status)) {
62279
+ possibleStageRowIndexes.delete(rootRunId);
62280
+ possibleStages = [];
62281
+ } else if (run.id === rootRunId) {
62282
+ possibleStages = possibleStageRowsIndex(rootRunId).rows(lookups.rowRuns(rootRunId), run, availableStoreDurableBackend(activeStore, rootRunId), lookups.runs);
62283
+ }
62284
+ const announcement = {
62285
+ runId: run.id,
62286
+ group: workflowInvocationIntercomGroup(rootRunId),
62287
+ capability: workflowPendingStageRouteCapability(activeStore, run.id),
62288
+ ...parent === undefined ? {} : { parent },
62289
+ stages: [
62290
+ ...run.stages.filter((stage) => !isNonAgentStage(stage) && workflowInvocationOwnsGroup(workflowInvocationIntercomGroup(rootRunId), stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId))).map((stage) => ({
62291
+ stageId: stage.id,
62292
+ stageName: stage.name,
62293
+ target: stageRouteTarget(lookups.runs, rootRunId, run.id, stage.id, lookups.segments),
62294
+ lifecycle: stage.sessionId === undefined && stage.sessionFile === undefined ? "pending" : "running",
62295
+ routeEligible: stage.pendingStageDeliveryAvailable === true && isAddressableStageStatus(stage.status),
62296
+ group: stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId)
62297
+ })),
62298
+ ...nonAgentNodes(run).map((node) => ({
62299
+ stageId: node.id,
62300
+ stageName: node.name,
62301
+ target: stageRouteTarget(lookups.runs, rootRunId, run.id, node.id, lookups.segments),
62302
+ lifecycle: "pending",
62303
+ routeEligible: false,
62304
+ recipientPurpose: "control",
62305
+ group: workflowInvocationIntercomGroup(rootRunId)
62306
+ }))
62307
+ ],
62308
+ ...possibleStages === undefined ? {} : { possibleStages }
62309
+ };
62310
+ const signature = possibleStages === undefined ? JSON.stringify(announcement) : `${JSON.stringify({ ...announcement, possibleStages: undefined })}\x00${possibleStages.map(rowIdentity).join(",")}`;
62311
+ if (announcedRoutes.get(run.id)?.signature === signature)
62123
62312
  return;
62313
+ const entry = { signature };
62314
+ announcedRoutes.set(run.id, entry);
62315
+ try {
62316
+ outsideWorkflowExecutions(() => pi.events?.emit?.(PENDING_STAGE_ROUTE_EVENT, announcement));
62317
+ } catch (error) {
62318
+ if (announcedRoutes.get(run.id) === entry)
62319
+ announcedRoutes.delete(run.id);
62320
+ unpublishedRunIds.add(run.id);
62321
+ const failure = Promise.reject(error);
62322
+ failure.catch(() => {});
62323
+ routeCompletions.set(run.id, failure);
62324
+ throw error;
62325
+ }
62326
+ const completion = announcement.completion;
62327
+ if (completion === undefined) {
62328
+ announcedRoutes.delete(run.id);
62329
+ routeCompletions.delete(run.id);
62330
+ unpublishedRunIds.add(run.id);
62331
+ } else {
62332
+ routeCompletions.set(run.id, completion);
62333
+ completion.catch(() => {
62334
+ if (announcedRoutes.get(run.id) !== entry)
62335
+ return;
62336
+ announcedRoutes.delete(run.id);
62337
+ unpublishedRunIds.add(run.id);
62338
+ });
62339
+ }
62340
+ };
62341
+ const announceAllRoutes = () => {
62342
+ unpublishedRunIds.clear();
62124
62343
  const ownedRunIds = new Set;
62125
62344
  const runs = activeStore.runs();
62126
62345
  topology.refresh(runs);
@@ -62134,80 +62353,33 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62134
62353
  children.push(run);
62135
62354
  childrenByBoundary.set(key, children);
62136
62355
  }
62137
- const resolveBoundarySegments = createWorkflowBoundarySegmentsResolver(runs);
62356
+ const lookups = {
62357
+ runs,
62358
+ parentOf: (run) => run.parentRunId === undefined ? undefined : runById.get(run.parentRunId),
62359
+ childAt: (parent, segment) => resolveIndexedChildRun(childrenByBoundary, parent, segment),
62360
+ segments: createWorkflowBoundarySegmentsResolver(runs),
62361
+ rowRuns: () => runs
62362
+ };
62363
+ const members = new Map;
62138
62364
  for (const run of runs) {
62365
+ const rootRunId = topology.rootOf(run.id);
62366
+ for (const root of new Set([rootRunId, run.rootRunId])) {
62367
+ if (root === undefined)
62368
+ continue;
62369
+ const ids = members.get(root);
62370
+ if (ids === undefined)
62371
+ members.set(root, [run.id]);
62372
+ else
62373
+ ids.push(run.id);
62374
+ }
62139
62375
  if (externalRunRouteOwner(activeStore, run.id) !== undefined || !ownsRun(run.id))
62140
62376
  continue;
62141
- const rootRunId = topology.rootOf(run.id);
62142
62377
  if (rootRunId === undefined)
62143
62378
  continue;
62144
62379
  ownedRunIds.add(run.id);
62145
- const parentRun = run.parentRunId === undefined ? undefined : runById.get(run.parentRunId);
62146
- const boundary = parentRun?.stages.find((stage) => stage.id === run.parentStageId);
62147
- const parent = parentRun === undefined || boundary === undefined ? undefined : {
62148
- runId: parentRun.id,
62149
- stageKeys: [boundary.id, boundary.name].filter((key) => resolveIndexedChildRun(childrenByBoundary, parentRun, key)?.id === run.id)
62150
- };
62151
- let possibleStages;
62152
- if (run.id === rootRunId && isTerminalRunStatus(run.status)) {
62153
- possibleStageRowIndexes.delete(rootRunId);
62154
- possibleStages = [];
62155
- } else if (run.id === rootRunId) {
62156
- possibleStages = possibleStageRowsIndex(rootRunId).rows(runs, run, availableStoreDurableBackend(activeStore, rootRunId));
62157
- }
62158
- const announcement = {
62159
- runId: run.id,
62160
- group: workflowInvocationIntercomGroup(rootRunId),
62161
- capability: workflowPendingStageRouteCapability(activeStore, run.id),
62162
- ...parent === undefined ? {} : { parent },
62163
- stages: [
62164
- ...run.stages.filter((stage) => !isNonAgentStage(stage) && workflowInvocationOwnsGroup(workflowInvocationIntercomGroup(rootRunId), stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId))).map((stage) => ({
62165
- stageId: stage.id,
62166
- stageName: stage.name,
62167
- target: stageRouteTarget(runs, rootRunId, run.id, stage.id, resolveBoundarySegments),
62168
- lifecycle: stage.sessionId === undefined && stage.sessionFile === undefined ? "pending" : "running",
62169
- routeEligible: stage.pendingStageDeliveryAvailable === true && isAddressableStageStatus(stage.status),
62170
- group: stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId)
62171
- })),
62172
- ...nonAgentNodes(run).map((node) => ({
62173
- stageId: node.id,
62174
- stageName: node.name,
62175
- target: stageRouteTarget(runs, rootRunId, run.id, node.id, resolveBoundarySegments),
62176
- lifecycle: "pending",
62177
- routeEligible: false,
62178
- recipientPurpose: "control",
62179
- group: workflowInvocationIntercomGroup(rootRunId)
62180
- }))
62181
- ],
62182
- ...possibleStages === undefined ? {} : { possibleStages }
62183
- };
62184
- const signature = possibleStages === undefined ? JSON.stringify(announcement) : `${JSON.stringify({ ...announcement, possibleStages: undefined })}\x00${possibleStages.map(rowIdentity).join(",")}`;
62185
- if (announcedRoutes.get(run.id)?.signature === signature)
62186
- continue;
62187
- const entry = { signature };
62188
- announcedRoutes.set(run.id, entry);
62189
- try {
62190
- outsideWorkflowExecutions(() => pi.events?.emit?.(PENDING_STAGE_ROUTE_EVENT, announcement));
62191
- } catch (error) {
62192
- if (announcedRoutes.get(run.id) === entry)
62193
- announcedRoutes.delete(run.id);
62194
- const failure = Promise.reject(error);
62195
- failure.catch(() => {});
62196
- routeCompletions.set(run.id, failure);
62197
- throw error;
62198
- }
62199
- const completion = announcement.completion;
62200
- if (completion === undefined) {
62201
- announcedRoutes.delete(run.id);
62202
- routeCompletions.delete(run.id);
62203
- } else {
62204
- routeCompletions.set(run.id, completion);
62205
- completion.catch(() => {
62206
- if (announcedRoutes.get(run.id) === entry)
62207
- announcedRoutes.delete(run.id);
62208
- });
62209
- }
62380
+ announceRun(run, rootRunId, lookups);
62210
62381
  }
62382
+ rootRunMembers = members;
62211
62383
  for (const runId of announcedRoutes.keys()) {
62212
62384
  if (!ownedRunIds.has(runId))
62213
62385
  announcedRoutes.delete(runId);
@@ -62220,7 +62392,65 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62220
62392
  if (!ownedRunIds.has(rootRunId))
62221
62393
  possibleStageRowIndexes.delete(rootRunId);
62222
62394
  }
62223
- sweepPromise = sweepPromise.then(() => outsideWorkflowExecutions(() => settleUndeliverablePendingStageMessages(activeStore, notifyUndeliverable, ownsRun))).then(() => {
62395
+ };
62396
+ const announceChangedRoutes = (changed) => {
62397
+ const retried = [...unpublishedRunIds];
62398
+ unpublishedRunIds.clear();
62399
+ const roots = new Set;
62400
+ for (const runId of [...changed, ...retried])
62401
+ for (const root of [topology.rootOf(runId), activeStore.run(runId)?.rootRunId])
62402
+ if (root !== undefined && rootRunMembers.has(root))
62403
+ roots.add(root);
62404
+ const segments = new Map;
62405
+ const lookups = {
62406
+ runs: activeStore,
62407
+ parentOf: (run) => run.parentRunId === undefined ? undefined : activeStore.run(run.parentRunId),
62408
+ childAt: (parent, segment) => resolveChildRun(activeStore, parent, segment),
62409
+ segments: (runId) => {
62410
+ if (!segments.has(runId))
62411
+ segments.set(runId, workflowBoundarySegments(activeStore, runId));
62412
+ return segments.get(runId);
62413
+ },
62414
+ rowRuns: membersOf
62415
+ };
62416
+ const position = (runId) => activeStore.runPosition(runId) ?? Number.MAX_SAFE_INTEGER;
62417
+ for (const rootRunId of [...roots].sort((left, right) => position(left) - position(right))) {
62418
+ for (const run of membersOf(rootRunId)) {
62419
+ if (topology.rootOf(run.id) !== rootRunId)
62420
+ continue;
62421
+ if (externalRunRouteOwner(activeStore, run.id) !== undefined || !ownsRun(run.id))
62422
+ dropRoute(run.id);
62423
+ else
62424
+ announceRun(run, rootRunId, lookups);
62425
+ }
62426
+ }
62427
+ };
62428
+ const unsettledRunIds = new Set;
62429
+ const sweep = async (changed) => {
62430
+ const runIds = changed === undefined ? undefined : new Set([...changed, ...unsettledRunIds]);
62431
+ const found = new Set;
62432
+ try {
62433
+ await settleUndeliverablePendingStageMessages(activeStore, notifyUndeliverable, ownsRun, runIds, (runId) => found.add(runId));
62434
+ } finally {
62435
+ if (runIds === undefined)
62436
+ unsettledRunIds.clear();
62437
+ else
62438
+ for (const runId of runIds)
62439
+ unsettledRunIds.delete(runId);
62440
+ for (const runId of found)
62441
+ if (hasSettlementWork(activeStore.run(runId)))
62442
+ unsettledRunIds.add(runId);
62443
+ }
62444
+ };
62445
+ const announceRoutes = (changed) => {
62446
+ if (disposed)
62447
+ return;
62448
+ const scope = changed !== undefined && topology.holds(activeStore, changed) ? changed : undefined;
62449
+ if (scope === undefined)
62450
+ announceAllRoutes();
62451
+ else
62452
+ announceChangedRoutes(scope);
62453
+ sweepPromise = sweepPromise.then(() => outsideWorkflowExecutions(() => sweep(scope))).then(() => {
62224
62454
  return;
62225
62455
  }).catch((error) => reportWarning(`atomic-workflows: pending stage delivery sweep failed: ${error.message}`));
62226
62456
  };
@@ -62228,13 +62458,21 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62228
62458
  let announcementTimer;
62229
62459
  let announcedAt = Number.NEGATIVE_INFINITY;
62230
62460
  let announcementCost = 0;
62231
- const announceNow = () => {
62461
+ let changedRunIds = new Set;
62462
+ const announceNow = (everything = false) => {
62232
62463
  if (announcementTimer !== undefined)
62233
62464
  clearTimeout(announcementTimer);
62234
62465
  announcementTimer = undefined;
62235
62466
  announcementPending = false;
62467
+ const changed = everything ? undefined : changedRunIds;
62468
+ changedRunIds = new Set;
62236
62469
  const started = performance.now();
62237
- announceRoutes();
62470
+ try {
62471
+ announceRoutes(changed);
62472
+ } catch (error) {
62473
+ changedRunIds = undefined;
62474
+ throw error;
62475
+ }
62238
62476
  announcedAt = performance.now();
62239
62477
  announcementCost = announcedAt - started;
62240
62478
  };
@@ -62257,8 +62495,15 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62257
62495
  }
62258
62496
  }
62259
62497
  };
62260
- const scheduleAnnouncement = () => {
62261
- if (disposed || announcementTimer !== undefined)
62498
+ const scheduleAnnouncement = (changes) => {
62499
+ if (disposed)
62500
+ return;
62501
+ if (changes === undefined)
62502
+ changedRunIds = undefined;
62503
+ else if (changedRunIds !== undefined)
62504
+ for (const change of changes)
62505
+ changedRunIds.add(change.runId);
62506
+ if (announcementTimer !== undefined)
62262
62507
  return;
62263
62508
  const idle = announcementCost / ROUTE_ANNOUNCEMENT_EVENT_LOOP_SHARE - announcementCost;
62264
62509
  const wait = Math.max(ROUTE_ANNOUNCEMENT_BATCH_MS, announcedAt + idle - performance.now());
@@ -62267,21 +62512,20 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62267
62512
  announcementTimer.unref?.();
62268
62513
  };
62269
62514
  const unsubscribeStore = activeStore.subscribeInvalidation(scheduleAnnouncement);
62270
- announceNow();
62515
+ announceNow(true);
62271
62516
  pi.on?.("session_start", () => {
62272
62517
  announcedRoutes.clear();
62273
- announceNow();
62518
+ announceNow(true);
62274
62519
  });
62275
62520
  const routePendingStageMessage = (payload) => {
62276
62521
  if (disposed || !isPendingStageMessageEvent(payload) || payload.handled)
62277
62522
  return;
62278
- const runs = activeStore.runs();
62279
62523
  const parsedTarget = parseWorkflowStageTarget(payload.target);
62280
62524
  if (parsedTarget === undefined)
62281
62525
  return;
62282
62526
  if (!ownsRun(parsedTarget.rootRunId))
62283
62527
  return;
62284
- if (parsedTarget.kind === "path" && isMaterializedNonAgentTarget(runs, parsedTarget)) {
62528
+ if (parsedTarget.kind === "path" && isMaterializedNonAgentTarget(activeStore, parsedTarget)) {
62285
62529
  payload.handled = true;
62286
62530
  payload.completion = Promise.resolve({
62287
62531
  outcome: "refused",
@@ -62289,22 +62533,22 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62289
62533
  });
62290
62534
  return;
62291
62535
  }
62292
- const destination = resolveMaterializedStage(runs, payload.target);
62536
+ const destination = resolveMaterializedStage(activeStore, payload.target);
62293
62537
  if (destination === undefined) {
62294
62538
  if (payload.live === true)
62295
62539
  return;
62296
- const rootRun = runs.find((candidate) => candidate.id === parsedTarget.rootRunId);
62540
+ const rootRun = activeStore.run(parsedTarget.rootRunId);
62297
62541
  if (rootRun === undefined)
62298
62542
  return;
62299
62543
  payload.handled = true;
62300
- payload.completion = deliverStickyTarget(activeStore, runs, rootRun, payload, parsedTarget).then((value2) => {
62544
+ payload.completion = deliverStickyTarget(activeStore, rootRun, payload, parsedTarget).then((value2) => {
62301
62545
  return value2;
62302
62546
  }, (error) => {
62303
62547
  throw error;
62304
62548
  });
62305
62549
  return;
62306
62550
  }
62307
- const rootRunId = durableRootRunIdForRun(runs, destination.run.id);
62551
+ const rootRunId = durableRootRunIdForRun(activeStore, destination.run.id);
62308
62552
  if (rootRunId === undefined)
62309
62553
  return;
62310
62554
  const resolvedEvent = {
@@ -62320,7 +62564,7 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62320
62564
  payload.handled = true;
62321
62565
  payload.completion = validateLiveDelivery(activeStore, resolvedEvent).then((result) => result.outcome === "forward" ? {
62322
62566
  outcome: "forward",
62323
- target: stageRouteTarget(runs, rootRunId, destination.run.id, stage.id)
62567
+ target: stageRouteTarget(activeStore, rootRunId, destination.run.id, stage.id)
62324
62568
  } : result);
62325
62569
  return;
62326
62570
  }
@@ -62328,11 +62572,11 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62328
62572
  if (uninitializedStage === undefined) {
62329
62573
  if (payload.message.expectsReply === true)
62330
62574
  return;
62331
- const stickyRoot = runs.find((candidate) => candidate.id === parsedTarget.rootRunId);
62575
+ const stickyRoot = activeStore.run(parsedTarget.rootRunId);
62332
62576
  if (stickyRoot === undefined || isTerminalRunStatus(stickyRoot.status))
62333
62577
  return;
62334
62578
  payload.handled = true;
62335
- payload.completion = deliverStickyTarget(activeStore, runs, stickyRoot, payload, parsedTarget);
62579
+ payload.completion = deliverStickyTarget(activeStore, stickyRoot, payload, parsedTarget);
62336
62580
  return;
62337
62581
  }
62338
62582
  payload.handled = true;
@@ -62373,7 +62617,7 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
62373
62617
  await Promise.allSettled(routeCompletions.values());
62374
62618
  await sweepPromise;
62375
62619
  },
62376
- refresh: announceNow
62620
+ refresh: () => announceNow(true)
62377
62621
  });
62378
62622
  }
62379
62623
  function stageRouteTarget(runs, rootRunId, runId, stageId, resolveBoundarySegments = (id) => workflowBoundarySegments(runs, id)) {
@@ -62419,20 +62663,20 @@ function resolveIndexedChildRun(childrenByBoundary, parent, segment) {
62419
62663
  function resolveChildRun(runs, parent, segment) {
62420
62664
  const boundariesById = parent.stages.filter((stage) => stage.id === segment);
62421
62665
  const boundaries = boundariesById.length > 0 ? boundariesById : parent.stages.filter((stage) => stage.name === segment);
62422
- const children = boundaries.flatMap((boundary) => runs.filter((candidate) => candidate.parentRunId === parent.id && candidate.parentStageId === boundary.id));
62666
+ const children = boundaries.flatMap((boundary) => childRunsInSource(runs, parent.id, boundary.id));
62423
62667
  return children.length === 1 ? children[0] : undefined;
62424
62668
  }
62425
62669
  function resolveMaterializedRun(runs, parsed) {
62426
62670
  if (parsed.kind !== "path")
62427
62671
  return;
62428
- const rootRun = runs.find((candidate) => candidate.id === parsed.rootRunId);
62672
+ const rootRun = findRunInSource(runs, parsed.rootRunId);
62429
62673
  if (rootRun === undefined)
62430
62674
  return;
62431
62675
  let run = rootRun;
62432
62676
  for (const segment of parsed.segments.slice(0, -1)) {
62433
- const runById = runs.filter((candidate) => candidate.id === segment && durableRootRunIdForRun(runs, candidate.id) === parsed.rootRunId);
62434
- if (runById.length === 1) {
62435
- run = runById[0];
62677
+ const runById = findRunInSource(runs, segment);
62678
+ if (runById !== undefined && durableRootRunIdForRun(runs, runById.id) === parsed.rootRunId) {
62679
+ run = runById;
62436
62680
  continue;
62437
62681
  }
62438
62682
  const child = resolveChildRun(runs, run, segment);
@@ -62495,7 +62739,7 @@ async function queueAndPersist(activeStore, event, runGroup, pendingStageDeliver
62495
62739
  queuedAt: new Date().toISOString()
62496
62740
  };
62497
62741
  const rootBackend = requireStoreDurableBackend(activeStore, event.runId);
62498
- const backend = durableBackendForRun(rootBackend, activeStore.runs(), event.runId);
62742
+ const backend = durableBackendForRun(rootBackend, activeStore, event.runId);
62499
62743
  if (backend === undefined)
62500
62744
  return { outcome: "refused", reason: "Session not found" };
62501
62745
  const senderGroup = pendingStageSenderGroup(event, runGroup);
@@ -62529,7 +62773,7 @@ async function queueAndPersist(activeStore, event, runGroup, pendingStageDeliver
62529
62773
  return { outcome: "refused", reason: "Pending-stage delivery was refused" };
62530
62774
  return { outcome: "queued", position: result.position };
62531
62775
  }
62532
- async function deliverStickyTarget(activeStore, runs, rootRun, event, parsedTarget) {
62776
+ async function deliverStickyTarget(activeStore, rootRun, event, parsedTarget) {
62533
62777
  const rootRunId = rootRun.id;
62534
62778
  const runGroup = workflowInvocationIntercomGroup(rootRunId);
62535
62779
  if (event.message.expectsReply === true) {
@@ -62541,9 +62785,9 @@ async function deliverStickyTarget(activeStore, runs, rootRun, event, parsedTarg
62541
62785
  reason: `Workflow run ${rootRunId} terminated with status ${rootRun.status} before any stage matching ${event.target} started`
62542
62786
  };
62543
62787
  }
62544
- const liveMatches = matchingLiveStages(runs, rootRunId, parsedTarget.segments);
62545
- const notInKnownSet = targetSegmentsInPossibleStages(parsedTarget.segments, rootRun.possibleStages ?? []) || liveMatches.length > 0 || matchingLiveStages(runs, rootRunId, parsedTarget.segments, { includePending: true }).length > 0 ? undefined : true;
62546
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), runs, rootRunId);
62788
+ const liveMatches = matchingLiveStages(activeStore, rootRunId, parsedTarget.segments);
62789
+ const notInKnownSet = targetSegmentsInPossibleStages(parsedTarget.segments, rootRun.possibleStages ?? []) || liveMatches.length > 0 || matchingLiveStages(activeStore, rootRunId, parsedTarget.segments, { includePending: true }).length > 0 ? undefined : true;
62790
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), activeStore, rootRunId);
62547
62791
  if (backend === undefined)
62548
62792
  return { outcome: "refused", reason: "Session not found" };
62549
62793
  const senderGroup = pendingStageSenderGroup(event, runGroup);
@@ -62611,14 +62855,13 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
62611
62855
  const parsedTarget = parseWorkflowStageTarget(event.target);
62612
62856
  if (parsedTarget === undefined)
62613
62857
  return false;
62614
- const runs = activeStore.runs();
62615
62858
  const rootRunId = parsedTarget.rootRunId;
62616
- const rootRun = runs.find((candidate) => candidate.id === rootRunId);
62859
+ const rootRun = activeStore.run(rootRunId);
62617
62860
  const entry = rootRun?.pendingStageMessages?.find((candidate) => candidate.sticky === true && candidate.message.id === event.messageId);
62618
62861
  if (rootRun === undefined || entry === undefined)
62619
62862
  return false;
62620
62863
  const delivered = new Set(event.deliveredTargets);
62621
- const records = matchingLiveStages(runs, rootRunId, parsedTarget.segments).filter((match) => delivered.has(match.target)).map((match) => ({
62864
+ const records = matchingLiveStages(activeStore, rootRunId, parsedTarget.segments).filter((match) => delivered.has(match.target)).map((match) => ({
62622
62865
  runId: match.run.id,
62623
62866
  stageId: match.stage.id,
62624
62867
  ...match.stage.name === match.stage.id ? {} : { stageName: match.stage.name },
@@ -62627,7 +62870,7 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
62627
62870
  }));
62628
62871
  if (records.length === 0)
62629
62872
  return false;
62630
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), runs, rootRunId);
62873
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), activeStore, rootRunId);
62631
62874
  if (backend === undefined)
62632
62875
  return false;
62633
62876
  const unconfirmedRecords = [];
@@ -62640,11 +62883,8 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
62640
62883
  }
62641
62884
  function matchingLiveStages(runs, rootRunId, patternSegments, options = {}) {
62642
62885
  const matches = [];
62643
- const runById = new Map(runs.map((run) => [run.id, run]));
62644
62886
  const hopsFor = createWorkflowBoundaryHopsResolver(runs);
62645
- for (const run of runs) {
62646
- if (reciprocalWorkflowRootRunId(runById, run.id) !== rootRunId)
62647
- continue;
62887
+ for (const run of invocationRunsInSource(runs, rootRunId)) {
62648
62888
  const hops = hopsFor(run.id);
62649
62889
  if (hops === undefined)
62650
62890
  continue;
@@ -62709,17 +62949,45 @@ function needsUndeliverableSettlement(run, entry) {
62709
62949
  return pendingStageUndeliverableReason(run, entry) !== undefined;
62710
62950
  return entry.status === "undeliverable" && entry.undeliverableNotificationId !== undefined && entry.undeliverableNotifiedAt === undefined && entry.undeliverableReason !== undefined;
62711
62951
  }
62712
- async function settleUndeliverablePendingStageMessages(activeStore, notify, ownsRun = () => true) {
62952
+ function hasSettlementWork(run) {
62953
+ return run?.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)) === true;
62954
+ }
62955
+ async function settleUndeliverablePendingStageMessages(activeStore, notify, ownsRun = () => true, runIds, onSettlementWork) {
62956
+ if (runIds !== undefined) {
62957
+ const position = (run) => activeStore.runPosition(run.id) ?? Number.MAX_SAFE_INTEGER;
62958
+ const candidates = [...new Set(runIds)].flatMap((runId) => {
62959
+ const run = activeStore.run(runId);
62960
+ return run !== undefined && hasSettlementWork(run) ? [run] : [];
62961
+ }).sort((left, right) => position(left) - position(right));
62962
+ for (const run of candidates)
62963
+ onSettlementWork?.(run.id);
62964
+ const owned = candidates.filter((run) => ownsRun(run.id));
62965
+ if (owned.length === 0)
62966
+ return 0;
62967
+ const ownedRuns = {
62968
+ run: (runId) => {
62969
+ const run = activeStore.run(runId);
62970
+ return run !== undefined && ownsRun(run.id) ? run : undefined;
62971
+ },
62972
+ runs: () => activeStore.runs().filter((run) => ownsRun(run.id))
62973
+ };
62974
+ return settleRuns(activeStore, owned, ownedRuns, notify);
62975
+ }
62713
62976
  const all = activeStore.runs();
62714
- const pending = (run) => run.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)) === true;
62715
- if (!all.some((run) => pending(run) && ownsRun(run.id)))
62977
+ const candidates = all.filter(hasSettlementWork);
62978
+ for (const run of candidates)
62979
+ onSettlementWork?.(run.id);
62980
+ if (!candidates.some((run) => ownsRun(run.id)))
62716
62981
  return 0;
62717
62982
  const runs = all.filter((run) => ownsRun(run.id));
62983
+ return settleRuns(activeStore, runs, runs, notify);
62984
+ }
62985
+ async function settleRuns(activeStore, runs, owners, notify) {
62718
62986
  let settled = 0;
62719
62987
  for (const run of runs) {
62720
- if (!run.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)))
62988
+ if (!hasSettlementWork(run))
62721
62989
  continue;
62722
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, run.id), runs, run.id);
62990
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, run.id), owners, run.id);
62723
62991
  if (backend === undefined) {
62724
62992
  throw new Error(`atomic-workflows: workflow run ${run.id} has no durable owner for pending-stage settlement`);
62725
62993
  }
@@ -62738,7 +63006,7 @@ async function settleUndeliverablePendingStageMessages(activeStore, notify, owns
62738
63006
  if (await activeStore.markPendingStageMessageUndeliverable(run.id, entry.stageKey, entry.id, reason, backend)) {
62739
63007
  settled += 1;
62740
63008
  }
62741
- const currentRun = activeStore.runs().find((candidate) => candidate.id === run.id);
63009
+ const currentRun = activeStore.run(run.id);
62742
63010
  const currentEntry = currentRun?.pendingStageMessages?.find((candidate) => candidate.stageKey === entry.stageKey && candidate.id === entry.id);
62743
63011
  if (currentEntry === undefined)
62744
63012
  continue;
@@ -65376,32 +65644,31 @@ var init_workflow_route_owner = __esm(() => {
65376
65644
  });
65377
65645
 
65378
65646
  // dist/builtin/workflows/src/runs/foreground/sdk-intercom.ts
65379
- function indexRoots(runs) {
65380
- const runById = new Map(runs.map((run) => [run.id, run]));
65381
- const rootOf = new Map;
65382
- const deliverable = new Set;
65383
- for (const run of runs) {
65384
- const root = reciprocalWorkflowRootRunId(runById, run.id);
65385
- rootOf.set(run.id, root);
65386
- if (root !== undefined && run.stages.some((stage) => stage.pendingStageDeliveryAvailable === true))
65387
- deliverable.add(root);
65388
- }
65389
- return { rootOf, deliverable };
65390
- }
65391
65647
  function createStandaloneRouteOwnership(store, roots) {
65392
65648
  const activated = new Set;
65393
- let index;
65649
+ const runs = runsByIdOf(store);
65650
+ const rootOf = new Map;
65651
+ const deliverable = new Map;
65394
65652
  const dispose = store.subscribeInvalidation(() => {
65395
- index = undefined;
65653
+ rootOf.clear();
65654
+ deliverable.clear();
65396
65655
  });
65397
65656
  return {
65398
65657
  owns: (runId) => {
65399
- index ??= indexRoots(store.runs());
65400
- const root = index.rootOf.get(runId) ?? runId;
65658
+ if (!rootOf.has(runId))
65659
+ rootOf.set(runId, reciprocalWorkflowRootRunId(runs, runId));
65660
+ const root = rootOf.get(runId) ?? runId;
65401
65661
  if (!roots.has(root))
65402
65662
  return false;
65403
- if (!activated.has(root) && index.deliverable.has(root))
65404
- activated.add(root);
65663
+ if (!activated.has(root)) {
65664
+ let canDeliver = deliverable.get(root);
65665
+ if (canDeliver === undefined) {
65666
+ canDeliver = invocationRunsInSource(store, root).some((run) => run.stages.some((stage) => stage.pendingStageDeliveryAvailable === true));
65667
+ deliverable.set(root, canDeliver);
65668
+ }
65669
+ if (canDeliver)
65670
+ activated.add(root);
65671
+ }
65405
65672
  return activated.has(root);
65406
65673
  },
65407
65674
  dispose
@@ -66013,7 +66280,7 @@ class PooledRoutes {
66013
66280
  this.mirror.batch(() => {
66014
66281
  for (const id of attempt.runs) {
66015
66282
  rotateWorkflowPendingStageRouteCapability(this.mirror, id);
66016
- const run = this.mirror.runs().find((candidate) => candidate.id === id);
66283
+ const run = this.mirror.run(id);
66017
66284
  if (run?.stages.some(isLiveStage) !== true)
66018
66285
  continue;
66019
66286
  this.mirror.recordRunStart({
@@ -67384,6 +67651,41 @@ var init_pool_coordinator = __esm(() => {
67384
67651
  STAGE_WATCH_BACKLOG_BYTES = 8 * 1024 * 1024;
67385
67652
  });
67386
67653
 
67654
+ // dist/builtin/workflows/src/workers/pooled-run-end.ts
67655
+ function endPooledRun(store, run, error) {
67656
+ const now = Date.now();
67657
+ for (const stage of run.stages)
67658
+ if (!isTerminalStageStatus(stage.status))
67659
+ store.recordStageEnd(run.id, {
67660
+ ...stage,
67661
+ status: "failed",
67662
+ endedAt: now,
67663
+ durationMs: stage.startedAt === undefined ? undefined : Math.max(0, now - stage.startedAt),
67664
+ error
67665
+ });
67666
+ store.recordRunEnd(run.id, "failed", undefined, error);
67667
+ }
67668
+ function endPooledChild(store, childRunId, error) {
67669
+ const child = store.run(childRunId);
67670
+ if (child === undefined)
67671
+ return;
67672
+ const subtree = [child];
67673
+ const seen = new Set([child.id]);
67674
+ for (let index = 0;index < subtree.length; index++)
67675
+ for (const nested of store.childRuns(subtree[index].id))
67676
+ if (!seen.has(nested.id)) {
67677
+ seen.add(nested.id);
67678
+ subtree.push(nested);
67679
+ }
67680
+ 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);
67681
+ for (const { run } of unfinished)
67682
+ if (run.endedAt === undefined)
67683
+ endPooledRun(store, run, error);
67684
+ }
67685
+ var init_pooled_run_end = __esm(() => {
67686
+ init_store_internal();
67687
+ });
67688
+
67387
67689
  // dist/builtin/workflows/src/workers/pooled-stage-sources.ts
67388
67690
  function registerPooledStageSource(store, source) {
67389
67691
  let registered = sources.get(store);
@@ -67561,7 +67863,7 @@ function createWorkflowPendingStageDelivery(activeStore, runId, stageId, stageNa
67561
67863
  if (sessionId !== undefined && activeStore.pendingStageMessagesFor(runId, stageId).length === 0 && activeStore.pendingStageMessagesFor(runId, stageName).length === 0) {
67562
67864
  const entries = stickyPendingStageEntriesForStage(activeStore, runId, stageId, stageName, { sessionId });
67563
67865
  Promise.all(entries.map(async (entry) => {
67564
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, entry.runId), activeStore.runs(), entry.runId);
67866
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, entry.runId), activeStore, entry.runId);
67565
67867
  return await backend?.hasPendingStageDeliveryReceipt?.(entry.runId, entry.id, {
67566
67868
  runId,
67567
67869
  stageId,
@@ -67608,13 +67910,12 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
67608
67910
  ...activeStore.pendingStageMessagesFor(runId, stageName),
67609
67911
  ...stickyEntries
67610
67912
  ].map((entry) => entry.id));
67611
- const runs = activeStore.runs();
67612
67913
  const entries = [
67613
- ...(runs.find((run) => run.id === runId)?.pendingStageMessages ?? []).map((entry, index) => ({ entry, index })).filter(({ entry }) => candidateIds.has(entry.id) && entry.sticky !== true),
67914
+ ...(activeStore.run(runId)?.pendingStageMessages ?? []).map((entry, index) => ({ entry, index })).filter(({ entry }) => candidateIds.has(entry.id) && entry.sticky !== true),
67614
67915
  ...stickyEntries.map((entry) => ({ entry, index: Number.MAX_SAFE_INTEGER }))
67615
67916
  ].map(({ entry, index }) => ({ entry, index, order: pendingStageMessageAdmissionOrder(entry) })).sort((left, right) => left.order - right.order || left.index - right.index).map(({ entry }) => entry);
67616
67917
  const rootBackend = requireStoreDurableBackend(activeStore, runId);
67617
- const backend = durableBackendForRun(rootBackend, runs, runId);
67918
+ const backend = durableBackendForRun(rootBackend, activeStore, runId);
67618
67919
  if (backend === undefined) {
67619
67920
  throw new Error(`atomic-workflows: workflow run ${runId} has no durable owner for pending-stage delivery`);
67620
67921
  }
@@ -67629,9 +67930,9 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
67629
67930
  stageId,
67630
67931
  ...recipient === undefined ? {} : { sessionId: recipient.sessionId, admission: "context" }
67631
67932
  };
67632
- 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;
67933
+ 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;
67633
67934
  if (entry.sticky === true && await hasStickyReceipt()) {
67634
- const entryBackend = durableBackendForRun(rootBackend, activeStore.runs(), entry.runId);
67935
+ const entryBackend = durableBackendForRun(rootBackend, activeStore, entry.runId);
67635
67936
  if (entryBackend !== undefined) {
67636
67937
  await commit(() => activeStore.recordPendingStageMessageDeliveries(entry.runId, entry.id, [], new Date().toISOString(), entryBackend));
67637
67938
  }
@@ -67640,7 +67941,7 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
67640
67941
  if (!recipient?.receivedMessageIds.includes(entry.message.id))
67641
67942
  await deliver(toPendingStageSender(entry), entry.message);
67642
67943
  if (entry.sticky === true) {
67643
- const entryBackend = durableBackendForRun(rootBackend, activeStore.runs(), entry.runId);
67944
+ const entryBackend = durableBackendForRun(rootBackend, activeStore, entry.runId);
67644
67945
  if (entryBackend === undefined) {
67645
67946
  throw new Error(`atomic-workflows: workflow run ${entry.runId} has no durable owner for sticky pending-stage delivery`);
67646
67947
  }
@@ -67659,18 +67960,17 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
67659
67960
  }
67660
67961
  }
67661
67962
  function stickyPendingStageEntriesForStage(activeStore, runId, stageId, stageName, recipient, receivedByEndedStage = []) {
67662
- const runs = activeStore.runs();
67663
- const rootRunId = durableRootRunIdForRun(runs, runId);
67963
+ const rootRunId = durableRootRunIdForRun(activeStore, runId);
67664
67964
  if (rootRunId === undefined)
67665
67965
  return [];
67666
- const rootRun = runs.find((run) => run.id === rootRunId);
67966
+ const rootRun = activeStore.run(rootRunId);
67667
67967
  if (rootRun === undefined)
67668
67968
  return [];
67669
- const stage = runs.find((run) => run.id === runId)?.stages.find((candidate) => candidate.id === stageId);
67969
+ const stage = activeStore.run(runId)?.stages.find((candidate) => candidate.id === stageId);
67670
67970
  const ended = stage?.status === "completed" || stage?.status === "skipped";
67671
67971
  if (ended && receivedByEndedStage.length === 0)
67672
67972
  return [];
67673
- const hops = workflowBoundaryHops(runs, runId);
67973
+ const hops = workflowBoundaryHops(activeStore, runId);
67674
67974
  if (hops === undefined)
67675
67975
  return [];
67676
67976
  return (rootRun.pendingStageMessages ?? []).filter((entry) => {
@@ -67857,7 +68157,7 @@ class PoolStageHandoff {
67857
68157
  if (result === undefined)
67858
68158
  return;
67859
68159
  const terminals = new Map;
67860
- const nested = this.store.runs().some((run) => run.endedAt === undefined && run.id !== work.childRunId && this.owners.get(run.id) === work.id);
68160
+ const nested = this.ownedRunIds(work).some((id) => id !== work.childRunId && this.unended(id) !== undefined);
67861
68161
  for (const checkpoint of nested ? this.backend.listCheckpoints(root) : []) {
67862
68162
  const boundary = checkpoint.kind === "stage" ? checkpoint.topology?.boundary : undefined;
67863
68163
  if (checkpoint.kind !== "stage" || boundary?.event !== "terminal")
@@ -67869,8 +68169,9 @@ class PoolStageHandoff {
67869
68169
  this.store.batch(() => this.settle(work, result, terminals));
67870
68170
  }
67871
68171
  settle(work, result, terminals) {
67872
- for (const run of this.store.runs()) {
67873
- if (run.endedAt !== undefined || this.owners.get(run.id) !== work.id)
68172
+ for (const id of this.ownedRunIds(work)) {
68173
+ const run = this.unended(id);
68174
+ if (run === undefined)
67874
68175
  continue;
67875
68176
  if (run.id === work.childRunId) {
67876
68177
  const executions = new Map(run.stages.map((stage) => [stage.id, stage.workerExecution]));
@@ -67891,6 +68192,19 @@ class PoolStageHandoff {
67891
68192
  this.store.recordRunEnd(run.id, terminal.status, terminal.outputs);
67892
68193
  }
67893
68194
  }
68195
+ ownedRunIds(work) {
68196
+ const held = [];
68197
+ for (const id of this.attempts.get(work.id)?.runs ?? []) {
68198
+ const position = this.store.runPosition(id);
68199
+ if (position !== undefined)
68200
+ held.push({ id, position });
68201
+ }
68202
+ return held.sort((left, right) => left.position - right.position).map(({ id }) => id);
68203
+ }
68204
+ unended(runId) {
68205
+ const run = this.store.run(runId);
68206
+ return run?.endedAt === undefined ? run : undefined;
68207
+ }
67894
68208
  fence(work) {
67895
68209
  const current = this.attempts.get(work.id);
67896
68210
  if (current !== undefined && current.generation > work.generation)
@@ -70106,21 +70420,7 @@ class LocalWorkerPool {
70106
70420
  endFailedChild(work, error) {
70107
70421
  const store = this.store;
70108
70422
  if (store !== undefined)
70109
- store.batch(() => {
70110
- const runs = store.runs();
70111
- const byId = new Map(runs.map((run) => [run.id, run]));
70112
- const inChild = (run) => {
70113
- for (let current = run;current !== undefined; ) {
70114
- if (current.id === work.childRunId)
70115
- return true;
70116
- current = current.parentRunId === undefined ? undefined : byId.get(current.parentRunId);
70117
- }
70118
- return false;
70119
- };
70120
- for (const run of runs)
70121
- if (run.endedAt === undefined && inChild(run))
70122
- endPooledRun(store, run, error.message);
70123
- });
70423
+ store.batch(() => endPooledChild(store, work.childRunId, error.message));
70124
70424
  if (this.reconnectingViews.size > 0 || this.outboxes.size > 0)
70125
70425
  this.reconnectStageViews();
70126
70426
  }
@@ -70433,19 +70733,6 @@ class LocalWorkerPool {
70433
70733
  throw failure;
70434
70734
  }
70435
70735
  }
70436
- function endPooledRun(store, run, error) {
70437
- const now = Date.now();
70438
- for (const stage of run.stages)
70439
- if (!isTerminalStageStatus(stage.status))
70440
- store.recordStageEnd(run.id, {
70441
- ...stage,
70442
- status: "failed",
70443
- endedAt: now,
70444
- durationMs: stage.startedAt === undefined ? undefined : Math.max(0, now - stage.startedAt),
70445
- error
70446
- });
70447
- store.recordRunEnd(run.id, "failed", undefined, error);
70448
- }
70449
70736
  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;
70450
70737
  var init_local_pool = __esm(() => {
70451
70738
  init_internal();
@@ -70457,7 +70744,6 @@ var init_local_pool = __esm(() => {
70457
70744
  init_sdk_intercom();
70458
70745
  init_external_run_routes();
70459
70746
  init_stage_question_form();
70460
- init_store_internal();
70461
70747
  init_workflow_infrastructure_error();
70462
70748
  init_admission_binding();
70463
70749
  init_definitions();
@@ -70466,6 +70752,7 @@ var init_local_pool = __esm(() => {
70466
70752
  init_host_options();
70467
70753
  init_pool_coordinator();
70468
70754
  init_pool_journal();
70755
+ init_pooled_run_end();
70469
70756
  init_pooled_stage_sources();
70470
70757
  init_pooled_watch_trace();
70471
70758
  init_stage_handoff();
@@ -71133,9 +71420,9 @@ function createParallelPrimitive(input) {
71133
71420
  activeStages: new Map,
71134
71421
  parentIds: parallelParentIds
71135
71422
  };
71136
- const stageIdsBeforeParallel = new Set(input.runtime.activeStore.runs().find((run) => run.id === input.runtime.runId)?.stages.map((stage) => stage.id) ?? []);
71423
+ const stageIdsBeforeParallel = new Set(input.runtime.activeStore.run(input.runtime.runId)?.stages.map((stage) => stage.id) ?? []);
71137
71424
  const everyStepCompleted = () => {
71138
- const run = input.runtime.activeStore.runs().find((candidate) => candidate.id === input.runtime.runId);
71425
+ const run = input.runtime.activeStore.run(input.runtime.runId);
71139
71426
  if (run === undefined)
71140
71427
  return false;
71141
71428
  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]));
@@ -73203,9 +73490,9 @@ function createDurableCachedStageRecorder(input) {
73203
73490
  return {
73204
73491
  record(name, replayKey, checkpoint, scope) {
73205
73492
  const cachedChildRunId = workflowChildRunId(checkpoint);
73206
- const runById = new Map(input.store.runs().map((run) => [run.id, run]));
73207
- if (!runById.has(input.run.id))
73208
- runById.set(input.run.id, input.run);
73493
+ const runById = {
73494
+ get: (runId) => input.store.run(runId) ?? (runId === input.run.id ? input.run : undefined)
73495
+ };
73209
73496
  const durableRootId = reciprocalWorkflowRootRunId(runById, input.run.id);
73210
73497
  const cachedDescendants = cachedChildRunId === undefined || durableRootId === undefined ? undefined : durableCompletedNestedRunSubtree(input.rootBackend, durableRootId, cachedChildRunId);
73211
73498
  if (cachedChildRunId !== undefined && durableRootId !== undefined && cachedDescendants === undefined) {
@@ -73219,7 +73506,7 @@ function createDurableCachedStageRecorder(input) {
73219
73506
  replaySourceOrders.set(replayedStage.id, sourceOrder);
73220
73507
  input.run.stages.sort((left, right) => (replaySourceOrders.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (replaySourceOrders.get(right.id) ?? Number.MAX_SAFE_INTEGER));
73221
73508
  }
73222
- const stage = input.store.runs().find((run) => run.id === input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
73509
+ const stage = input.store.run(input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
73223
73510
  const persistence = stage === undefined ? undefined : input.backend.commitCheckpoint({
73224
73511
  kind: "stage",
73225
73512
  workflowId: input.run.id,
@@ -73230,7 +73517,7 @@ function createDurableCachedStageRecorder(input) {
73230
73517
  ...durableStageCheckpointMetadata(stage, durableRunTopology(input.run), sourceOrder ?? input.run.stages.findIndex((candidate) => candidate.id === stage.id))
73231
73518
  });
73232
73519
  for (const childRun of cachedDescendants ?? []) {
73233
- const existingRun = input.store.runs().find((candidate) => candidate.id === childRun.id);
73520
+ const existingRun = input.store.run(childRun.id);
73234
73521
  const isDirectChild = childRun.id === cachedChildRunId && childRun.parentRunId === input.run.id && stage?.workflowChild?.runId === cachedChildRunId;
73235
73522
  if (existingRun !== undefined) {
73236
73523
  if (stage !== undefined && isDirectChild) {
@@ -73256,15 +73543,15 @@ function createDurableCachedStageRecorder(input) {
73256
73543
  };
73257
73544
  }
73258
73545
  function reconcileCachedDirectChildParentStage(input) {
73259
- const existingRun = input.store.runs().find((run) => run.id === input.checkpointChildRunId);
73546
+ const existingRun = input.store.run(input.checkpointChildRunId);
73260
73547
  if (existingRun === undefined)
73261
73548
  return false;
73262
- const runById = new Map(input.store.runs().map((run) => [run.id, run]));
73263
- const storedParentRun = runById.get(input.parentRun.id);
73549
+ const storedParentRun = input.store.run(input.parentRun.id);
73264
73550
  if (storedParentRun !== undefined && (storedParentRun.parentRunId !== input.parentRun.parentRunId || storedParentRun.parentStageId !== input.parentRun.parentStageId))
73265
73551
  return false;
73266
- if (storedParentRun === undefined)
73267
- runById.set(input.parentRun.id, input.parentRun);
73552
+ const runById = {
73553
+ get: (runId) => input.store.run(runId) ?? (runId === input.parentRun.id ? input.parentRun : undefined)
73554
+ };
73268
73555
  const expectedRootRunId = reciprocalWorkflowRootRunId(runById, input.parentRun.id);
73269
73556
  if (expectedRootRunId === undefined)
73270
73557
  return false;
@@ -73347,6 +73634,7 @@ function deferStageUntilRunRelease(input) {
73347
73634
 
73348
73635
  // dist/builtin/workflows/src/engine/run-rejection-boundary.ts
73349
73636
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
73637
+ import { randomUUID as randomUUID21 } from "node:crypto";
73350
73638
  import { inspect } from "node:util";
73351
73639
  import { isStaleExtensionContextError as isStaleExtensionContextError3 } from "@bastani/atomic";
73352
73640
  function boundaryBag() {
@@ -73427,9 +73715,9 @@ function recordedOwners(boundary, reason) {
73427
73715
  function pruneEndedSources(boundary) {
73428
73716
  const now = Date.now();
73429
73717
  for (const [source, trees] of boundary.ended) {
73430
- for (const [rootRunId, endedAt] of trees)
73718
+ for (const [execution, endedAt] of trees)
73431
73719
  if (now - endedAt > ENDED_RUN_GRACE_MS)
73432
- trees.delete(rootRunId);
73720
+ trees.delete(execution);
73433
73721
  if (trees.size === 0)
73434
73722
  boundary.ended.delete(source);
73435
73723
  }
@@ -73438,12 +73726,12 @@ function recordEndedRun(boundary, scope) {
73438
73726
  if (scope.source === undefined)
73439
73727
  return;
73440
73728
  const trees = boundary.ended.get(scope.source) ?? new Map;
73441
- trees.set(scope.rootRunId, Date.now());
73729
+ trees.set(scope.execution, Date.now());
73442
73730
  boundary.ended.set(scope.source, trees);
73443
73731
  }
73444
73732
  function endedInAnotherRunTree(boundary, source, live) {
73445
- for (const endedRoot of boundary.ended.get(source)?.keys() ?? [])
73446
- if (endedRoot !== live.rootRunId)
73733
+ for (const endedExecution of boundary.ended.get(source)?.keys() ?? [])
73734
+ if (endedExecution !== live.execution)
73447
73735
  return true;
73448
73736
  return false;
73449
73737
  }
@@ -73654,6 +73942,7 @@ function openRunRejectionScope(options) {
73654
73942
  const scope = {
73655
73943
  runId: options.runId,
73656
73944
  rootRunId,
73945
+ execution: parent?.execution ?? randomUUID21(),
73657
73946
  source: options.source === undefined ? undefined : normalizeStackPath(options.source),
73658
73947
  parent,
73659
73948
  fail: options.fail,
@@ -73665,8 +73954,11 @@ function openRunRejectionScope(options) {
73665
73954
  };
73666
73955
  boundary.scopes.add(scope);
73667
73956
  boundary.runs.set(scope.runId, scope);
73668
- if (scope.source !== undefined)
73957
+ if (scope.source !== undefined) {
73669
73958
  markSharedSource(boundary, scope.source);
73959
+ if (endedInAnotherRunTree(boundary, scope.source, scope))
73960
+ scope.sharedSource = true;
73961
+ }
73670
73962
  return {
73671
73963
  run: (callback) => boundary.store.run(scope, callback),
73672
73964
  contain: (promise, effect = "fail-run") => {
@@ -74041,7 +74333,7 @@ function createAdmittedToolExecutionTracker(options = {}) {
74041
74333
  // dist/builtin/workflows/src/engine/run-tool-node-lifecycle.ts
74042
74334
  function createToolNodeLifecycle(input) {
74043
74335
  const { store, tracker, run, sourceToContinuationNodeIds } = input;
74044
- const ownsCurrentRun = () => store.runs().some((candidate) => candidate === run);
74336
+ const ownsCurrentRun = () => store.run(run.id) === run;
74045
74337
  const replayedToolNodeIds = new Set;
74046
74338
  let pendingFrontier = input.resumeToolNode;
74047
74339
  const pendingRetries = new Map((input.retryToolNodes ?? []).map((node) => [node.id, node]));
@@ -74114,7 +74406,7 @@ function sameToolIdentity(node, expected) {
74114
74406
  function isReplayedContinuationNode(store, run, replayedToolNodeIds, nodeId) {
74115
74407
  if (replayedToolNodeIds.has(nodeId))
74116
74408
  return true;
74117
- const live = store.runs().find((candidate) => candidate === run);
74409
+ const live = store.run(run.id) === run ? run : undefined;
74118
74410
  return live?.stages.some((stage) => stage.id === nodeId && stage.replayed === true) === true;
74119
74411
  }
74120
74412
  function compatibleReplayedToolParents(tracker, translated, inferredParents, isReplayedNode) {
@@ -74484,7 +74776,7 @@ function createQueuedUserMessageConsumptionWatcher(armContinuation) {
74484
74776
  // dist/builtin/workflows/src/runs/foreground/blocked-stage-close.ts
74485
74777
  function closeBlockedStageForGoodWhenRunEnds(store, runId, close) {
74486
74778
  const unsubscribe = store.subscribe(() => {
74487
- const run = store.runs().find((candidate) => candidate.id === runId);
74779
+ const run = store.run(runId);
74488
74780
  if (run && (!isTerminalRunStatus(run.status) || run.resumable === true))
74489
74781
  return;
74490
74782
  unsubscribe();
@@ -74790,7 +75082,7 @@ function createTrackedStageCaller(input) {
74790
75082
  const budgetError = err instanceof WorkflowBudgetExceededError ? err : undefined;
74791
75083
  if (budgetError !== undefined && trackStageLifecycle && !runtime.state.skippedForParallelFailFast) {
74792
75084
  let selectedBudgetError = budgetError;
74793
- if (runtime.activeStore.runs().find((run) => run.id === runtime.runId)?.budgetState?.wrapUpCompleted !== true) {
75085
+ if (runtime.activeStore.run(runtime.runId)?.budgetState?.wrapUpCompleted !== true) {
74794
75086
  try {
74795
75087
  await runtime.budget.deliverWrapUp(runtime.name);
74796
75088
  } catch (wrapUpError) {
@@ -75237,7 +75529,7 @@ function createStageControlHandle(runtime) {
75237
75529
  runtime.scheduler.ensureReleaseBarrier(runtime.stageId);
75238
75530
  runtime.state.readinessController?.abort(new Error("atomic-workflows: readiness paused"));
75239
75531
  await runtime.scheduler.cascadePauseFrom(runtime.stageId);
75240
- const run = runtime.activeStore.runs().find((candidate) => candidate.id === runtime.runId);
75532
+ const run = runtime.activeStore.run(runtime.runId);
75241
75533
  const stillActive = run?.stages.some((stage) => stage.status === "running" && stage.id !== runtime.stageId) ?? false;
75242
75534
  if (!stillActive)
75243
75535
  runtime.activeStore.recordRunPaused(runtime.runId);
@@ -79225,7 +79517,7 @@ function createWorkflowStageFactory(input) {
79225
79517
  defaultSessionDir: input.opts.defaultSessionDir,
79226
79518
  defaultCwd: input.workflowInvocationCwd,
79227
79519
  onStartupChange(startup) {
79228
- const current = input.activeStore.runs().find((run) => run.id === input.runId);
79520
+ const current = input.activeStore.run(input.runId);
79229
79521
  if (!current?.stages.includes(stageSnapshot))
79230
79522
  return;
79231
79523
  stageSnapshot.startup = startup;
@@ -79714,7 +80006,7 @@ async function run(def, inputs, opts = {}) {
79714
80006
  const resolvedInputs = resolveAndValidateInputs(def.inputs, inputs, `workflow "${def.name}"`);
79715
80007
  const runId = opts.runId ?? crypto.randomUUID();
79716
80008
  const activeStore = opts.store ?? store;
79717
- const preset = opts.durableBackend ?? (opts.journal === undefined ? availableRunDurableBackend(activeStore.runs(), opts.continuation?.source.id ?? runId) ?? availableStoreDurableBackendOverride(activeStore) : undefined);
80009
+ const preset = opts.durableBackend ?? (opts.journal === undefined ? availableRunDurableBackend(activeStore, opts.continuation?.source.id ?? runId) ?? availableStoreDurableBackendOverride(activeStore) : undefined);
79718
80010
  const backend = preset ?? await initializeDurableBackend({ journal: opts.journal, cwd: opts.cwd });
79719
80011
  const publicResources = opts.parentRun === undefined && (opts.localWorkers || opts.admission || backend.getWorkflow(opts.continuation?.source.id ?? runId)?.resources);
79720
80012
  if (publicResources)
@@ -79750,7 +80042,7 @@ async function executeRun(def, resolvedInputs, opts) {
79750
80042
  }
79751
80043
  const declaresBudget = (budget) => (budget?.maxDurationMs ?? 0) > 0 || (budget?.maxTokens ?? 0) > 0 || (budget?.maxCost ?? 0) > 0;
79752
80044
  const hasBudgetDeclaration = declaresBudget(opts.budget) || declaresBudget(def.budget) || declaresBudget(opts.config?.budget);
79753
- const priorRun = hasBudgetDeclaration && opts.rootBudget === undefined && opts.continuation === undefined && opts.runId !== undefined ? activeStore.runs().find((candidate) => candidate.id === runId) : undefined;
80045
+ const priorRun = hasBudgetDeclaration && opts.rootBudget === undefined && opts.continuation === undefined && opts.runId !== undefined ? activeStore.run(runId) : undefined;
79754
80046
  const continuedBudget = opts.continuation?.source.budget ?? priorRun?.budget;
79755
80047
  const runBudget = opts.budget === undefined ? continuedBudget : { ...continuedBudget ?? {}, ...opts.budget };
79756
80048
  const resolvedBudget = resolve_budget({ config: opts.config?.budget, definition: def.budget, run: runBudget });
@@ -79825,17 +80117,8 @@ async function executeRun(def, resolvedInputs, opts) {
79825
80117
  if (opts.parentRun === undefined)
79826
80118
  bindRunDurableBackend(runSnapshot, rootBackend);
79827
80119
  const usageTree = () => {
79828
- const snapshots = activeStore.runs();
79829
- const childrenByParent = new Map;
79830
- for (const snapshot of snapshots) {
79831
- if (snapshot.parentRunId === undefined)
79832
- continue;
79833
- const children = childrenByParent.get(snapshot.parentRunId) ?? [];
79834
- children.push(snapshot);
79835
- childrenByParent.set(snapshot.parentRunId, children);
79836
- }
79837
80120
  const build = (run) => {
79838
- const children = (childrenByParent.get(run.id) ?? []).map(build);
80121
+ const children = activeStore.childRuns(run.id).map(build);
79839
80122
  return children.length === 0 ? { run } : { run, children };
79840
80123
  };
79841
80124
  return build(runSnapshot);
@@ -80218,7 +80501,7 @@ async function executeRun(def, resolvedInputs, opts) {
80218
80501
  return recorded;
80219
80502
  };
80220
80503
  const durableIntercomGroup = (replayKey, stageId) => {
80221
- const stages = activeStore.runs().find((candidate) => candidate.id === runId)?.stages ?? [];
80504
+ const stages = activeStore.run(runId)?.stages ?? [];
80222
80505
  return stages.find((stage) => stageId !== undefined && stage.id === stageId || stage.replayKey === replayKey)?.intercomGroup;
80223
80506
  };
80224
80507
  let observedTaskTailQuit;
@@ -80271,7 +80554,7 @@ async function executeRun(def, resolvedInputs, opts) {
80271
80554
  recordCachedStage,
80272
80555
  stage: (name, options, replayKey) => {
80273
80556
  const stage = runtime.stage(name, options);
80274
- const stageId = activeStore.runs().find((r) => r.id === runId)?.stages.at(-1)?.id;
80557
+ const stageId = activeStore.run(runId)?.stages.at(-1)?.id;
80275
80558
  if (stageId !== undefined)
80276
80559
  completedStageReplayKeys.set(stageId, replayKey);
80277
80560
  return stage;
@@ -80793,18 +81076,18 @@ var init_executor = __esm(() => {
80793
81076
  });
80794
81077
 
80795
81078
  // dist/builtin/workflows/src/runs/foreground/sdk-run.ts
80796
- import { randomUUID as randomUUID21 } from "node:crypto";
81079
+ import { randomUUID as randomUUID22 } from "node:crypto";
80797
81080
  async function run2(def, inputs, callerOpts = {}) {
80798
81081
  let opts = callerOpts;
80799
81082
  const store2 = opts.store === undefined || opts.store === store ? currentWorkflowStore() : opts.store;
80800
81083
  const sourceRunId = opts.continuation?.source.id ?? opts.runId;
80801
- const ownedBackend = sourceRunId === undefined ? undefined : availableRunDurableBackend(store2.runs(), sourceRunId);
81084
+ const ownedBackend = sourceRunId === undefined ? undefined : availableRunDurableBackend(store2, sourceRunId);
80802
81085
  const preset = opts.journal === undefined ? opts.durableBackend ?? ownedBackend ?? availableStoreDurableBackendOverride(store2) : undefined;
80803
81086
  const backend = preset ?? await initializeDurableBackend({ journal: opts.journal, cwd: opts.cwd });
80804
81087
  if (opts.journal === undefined && opts.durableBackend === undefined && ownedBackend === undefined) {
80805
81088
  bindStoreDurableBackend(store2, backend);
80806
81089
  }
80807
- const runId = opts.runId ?? randomUUID21();
81090
+ const runId = opts.runId ?? randomUUID22();
80808
81091
  if (sourceRunId !== undefined || opts.localWorkers || opts.admission) {
80809
81092
  opts = await restoreWorkerOptions(backend, { ...opts, runId });
80810
81093
  }
@@ -80975,7 +81258,7 @@ var init_workflows_host_module = __esm(() => {
80975
81258
  });
80976
81259
 
80977
81260
  // dist/builtin/workflows/src/workers/pool-journal.ts
80978
- import { createHash as createHash6, randomUUID as randomUUID22 } from "node:crypto";
81261
+ import { createHash as createHash6, randomUUID as randomUUID23 } from "node:crypto";
80979
81262
  import { existsSync as existsSync7, mkdirSync as mkdirSync9, readFileSync as readFileSync8, writeFileSync as writeFileSync7 } from "node:fs";
80980
81263
  import { basename as basename6, dirname as dirname17, join as join32, resolve as resolve18 } from "node:path";
80981
81264
  import { storageSelectionKey as storageSelectionKey2 } from "@bastani/atomic/storage";
@@ -81072,7 +81355,7 @@ function poolHostId(agentDir) {
81072
81355
  return existing;
81073
81356
  } catch {}
81074
81357
  mkdirSync9(dirname17(file), { recursive: true });
81075
- const id = randomUUID22();
81358
+ const id = randomUUID23();
81076
81359
  try {
81077
81360
  writeFileSync7(file, `${id}
81078
81361
  `, { flag: "wx" });
@@ -81109,7 +81392,7 @@ init_store();
81109
81392
  init_workflow_infrastructure_error();
81110
81393
  init_admission_binding();
81111
81394
  init_definitions();
81112
- import { randomUUID as randomUUID24 } from "node:crypto";
81395
+ import { randomUUID as randomUUID25 } from "node:crypto";
81113
81396
  import { setTimeout as delay4 } from "node:timers/promises";
81114
81397
  import {
81115
81398
  applyProviderRateLimitObservation as applyProviderRateLimitObservation2,
@@ -81131,10 +81414,11 @@ function poolWorkerCommit(input) {
81131
81414
  init_pending_stage_delivery2();
81132
81415
  init_pending_stage_delivery();
81133
81416
  init_store_pending_stage_delivery_methods();
81417
+ init_workflow_run_ownership();
81134
81418
  function pooledStageQueuedEntries(journal, store, root, stage) {
81135
81419
  const messages = journal.getWorkflow(root)?.pendingStageMessages ?? [];
81136
- const runs = store.runs();
81137
- const run = runs.find((candidate) => candidate.id === stage.runId);
81420
+ const runs = runsByIdOf(store);
81421
+ const run = runs.get(stage.runId);
81138
81422
  if (run === undefined)
81139
81423
  return [];
81140
81424
  const exact = new Set;
@@ -81149,12 +81433,11 @@ function pooledStageQueuedEntries(journal, store, root, stage) {
81149
81433
  ].map(({ entry, index }) => ({ entry, index, order: pendingStageMessageAdmissionOrder(entry) })).sort((left, right) => left.order - right.order || left.index - right.index).map(({ entry }) => entry);
81150
81434
  }
81151
81435
  function pooledStageHops(journal, runs, root, runId) {
81152
- const byId = new Map(runs.map((run) => [run.id, run]));
81153
81436
  const hops = [];
81154
- let current = byId.get(runId);
81437
+ let current = runs.get(runId);
81155
81438
  while (current !== undefined && current.parentRunId !== root) {
81156
81439
  const child = current;
81157
- const parent = child.parentRunId === undefined ? undefined : byId.get(child.parentRunId);
81440
+ const parent = child.parentRunId === undefined ? undefined : runs.get(child.parentRunId);
81158
81441
  const boundary = parent?.stages.find((stage) => stage.id === child.parentStageId);
81159
81442
  if (parent === undefined || boundary === undefined)
81160
81443
  return;
@@ -81223,11 +81506,11 @@ init_resource_admission();
81223
81506
  // dist/builtin/workflows/src/workers/session-store.ts
81224
81507
  init_stage_topology();
81225
81508
  init_run_durable_topology();
81226
- import { randomUUID as randomUUID23 } from "node:crypto";
81509
+ import { randomUUID as randomUUID24 } from "node:crypto";
81227
81510
  function workerSessionStore(input) {
81228
81511
  const checkpoint = (id, header) => {
81229
81512
  const owner = header.workflow;
81230
- const run = input.store.runs().find((run) => run.id === owner?.runId);
81513
+ const run = owner === undefined ? undefined : input.store.run(owner.runId);
81231
81514
  const stage = run?.stages.find((stage) => stage.id === owner?.stageId);
81232
81515
  if (!run || !stage?.replayKey)
81233
81516
  throw new Error("Pool session has no active stage");
@@ -81239,7 +81522,7 @@ function workerSessionStore(input) {
81239
81522
  ...durableStageCheckpointMetadata(stage, durableRunTopology(run), run.stages.indexOf(stage)),
81240
81523
  kind: "stage",
81241
81524
  workflowId: input.root,
81242
- checkpointId: `${prefix}:session:${id}:${randomUUID23()}`,
81525
+ checkpointId: `${prefix}:session:${id}:${randomUUID24()}`,
81243
81526
  replayKey: `${prefix}:${stage.replayKey}`,
81244
81527
  name: stage.name,
81245
81528
  sessionId: id,
@@ -81768,7 +82051,7 @@ class WorkerStageWatches {
81768
82051
  const prompts = this.options.prompts?.();
81769
82052
  if (held?.workId !== command.attempt.workId || held.generation !== command.attempt.generation || !prompts)
81770
82053
  return { refusal: "StaleAttempt" };
81771
- const stage = prompts.store.runs().find((run) => run.id === command.runId)?.stages.find((candidate) => candidate.id === command.stageId);
82054
+ const stage = prompts.store.run(command.runId)?.stages.find((candidate) => candidate.id === command.stageId);
81772
82055
  if (stage === undefined)
81773
82056
  return { refusal: "PromptNotPending" };
81774
82057
  if (TERMINAL.has(stage.status))
@@ -82101,7 +82384,7 @@ class WorkerStageUiBroker extends StageUiBroker {
82101
82384
  this.workerStore = workerStore;
82102
82385
  }
82103
82386
  requestCustomUi(runId, stageId, factory, options, signal, sessionId, humanInput) {
82104
- const stage = this.workerStore.runs().find((run) => run.id === runId)?.stages.find((candidate) => candidate.id === stageId);
82387
+ const stage = this.workerStore.run(runId)?.stages.find((candidate) => candidate.id === stageId);
82105
82388
  if (stage?.promptFootprint?.kind === "custom")
82106
82389
  return Promise.reject(new Error(POOLED_CUSTOM_PROMPT_UNAVAILABLE));
82107
82390
  return super.requestCustomUi(runId, stageId, factory, options, signal, sessionId, humanInput);
@@ -82223,7 +82506,7 @@ async function runWorker(start) {
82223
82506
  configurePooledWatchTrace(start.journalPath, `worker:${process.pid}`);
82224
82507
  const sessions = await new StorageProvider3().openSessionStore({ kind: "sqlite", path: start.journalPath, prefix: `${sqlPoolStorage(poolJournal).tables.runs}_pool_` }, { agentDir: "", domain: "sessions" });
82225
82508
  const commit = poolWorkerCommit({
82226
- send: async (mutation) => await request({ kind: "commit", operation: randomUUID24(), mutation }),
82509
+ send: async (mutation) => await request({ kind: "commit", operation: randomUUID25(), mutation }),
82227
82510
  catchUp: () => reader.catchUpWorkflow(start.root)
82228
82511
  });
82229
82512
  const reads = new Set([