@bastani/atomic 0.9.68 → 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
@@ -240,6 +240,18 @@ function reciprocalWorkflowRootRunId(runById, runId) {
240
240
  }
241
241
  return;
242
242
  }
243
+ function isRunLookup(source) {
244
+ return "run" in source;
245
+ }
246
+ function runsInSource(source) {
247
+ return isRunLookup(source) ? source.runs() : source;
248
+ }
249
+ function findRunInSource(source, runId) {
250
+ return isRunLookup(source) ? source.run(runId) : source.find((run) => run.id === runId);
251
+ }
252
+ function runsByIdOf(source) {
253
+ return isRunLookup(source) ? { get: (runId) => source.run(runId) } : new Map(source.map((run) => [run.id, run]));
254
+ }
243
255
  function index(items, cache) {
244
256
  let byId = cache.get(items);
245
257
  if (byId === undefined) {
@@ -258,6 +270,29 @@ function findSnapshotRun(runs, runId) {
258
270
  function findSnapshotStage(stages, stageId) {
259
271
  return Object.isFrozen(stages) ? index(stages, stageIndexes).get(stageId) : stages.find((stage) => stage.id === stageId);
260
272
  }
273
+ function childRunsInSource(source, parentRunId, parentStageId) {
274
+ if (isRunLookup(source) && source.childRuns !== undefined)
275
+ return source.childRuns(parentRunId, parentStageId);
276
+ return runsInSource(source).filter((run) => run.parentRunId === parentRunId && (parentStageId === undefined || run.parentStageId === parentStageId));
277
+ }
278
+ function invocationRunsInSource(source, rootRunId) {
279
+ const byId = runsByIdOf(source);
280
+ const inInvocation = (run) => reciprocalWorkflowRootRunId(byId, run.id) === rootRunId;
281
+ if (!isRunLookup(source) || source.childRuns === undefined || source.runPosition === undefined)
282
+ return runsInSource(source).filter(inInvocation);
283
+ const root = source.run(rootRunId);
284
+ if (root === undefined)
285
+ return [];
286
+ const seen = new Set([root.id]);
287
+ const found = [root];
288
+ for (let index = 0;index < found.length; index++)
289
+ for (const child of source.childRuns(found[index].id))
290
+ if (!seen.has(child.id)) {
291
+ seen.add(child.id);
292
+ found.push(child);
293
+ }
294
+ return found.filter(inInvocation).sort((left, right) => source.runPosition(left.id) - source.runPosition(right.id));
295
+ }
261
296
  var runIndexes, stageIndexes;
262
297
  var init_workflow_run_ownership = __esm(() => {
263
298
  runIndexes = new WeakMap;
@@ -486,19 +521,20 @@ function bindRunDurableBackend(run, backend) {
486
521
  Object.defineProperty(run, workflowRunBackend, { value: backend });
487
522
  }
488
523
  function availableRunDurableBackend(runs, runId) {
489
- const target = resolveRunIdTarget(runId, runs.map((run) => run.id));
524
+ const target = resolveRunIdTarget(runId, isRunIdPrefix(runId) ? runsInSource(runs).map((run) => run.id) : []);
490
525
  const id = target.kind === "exact" || target.kind === "unique_prefix" ? target.runId : runId;
491
526
  const rootRunId = durableRootRunIdForRun(runs, id);
492
- return runs.find((run) => run.id === rootRunId)?.[workflowRunBackend];
527
+ const rootRun = rootRunId === undefined ? undefined : findRunInSource(runs, rootRunId);
528
+ return rootRun?.[workflowRunBackend];
493
529
  }
494
530
  function durableRootRunIdForRun(runs, runId) {
495
- return reciprocalWorkflowRootRunId(new Map(runs.map((run) => [run.id, run])), runId);
531
+ return reciprocalWorkflowRootRunId(runsByIdOf(runs), runId);
496
532
  }
497
533
  function durableBackendForRun(backend, runs, runId) {
498
534
  const rootRunId = durableRootRunIdForRun(runs, runId);
499
535
  if (rootRunId === undefined)
500
536
  return;
501
- const runById = new Map(runs.map((run) => [run.id, run]));
537
+ const runById = runsByIdOf(runs);
502
538
  const rootBackend = availableRunDurableBackend(runs, rootRunId) ?? backend;
503
539
  if (rootRunId === runId)
504
540
  return rootBackend;
@@ -536,7 +572,7 @@ function bindStoreDurableBackend(store, backend) {
536
572
  store[workflowStoreBackend] = backend;
537
573
  }
538
574
  function availableStoreDurableBackend(store, runId) {
539
- return (store !== undefined && runId !== undefined ? availableRunDurableBackend(store.runs(), runId) : undefined) ?? store?.[workflowStoreBackend];
575
+ return (store !== undefined && runId !== undefined ? availableRunDurableBackend(store, runId) : undefined) ?? store?.[workflowStoreBackend];
540
576
  }
541
577
  function requireStoreDurableBackend(store, runId) {
542
578
  const backend = availableStoreDurableBackend(store, runId);
@@ -650,6 +686,7 @@ var init_workflow_source = __esm(() => {
650
686
 
651
687
  // dist/builtin/workflows/src/engine/run-rejection-boundary.ts
652
688
  import { AsyncLocalStorage } from "node:async_hooks";
689
+ import { randomUUID } from "node:crypto";
653
690
  import { inspect } from "node:util";
654
691
  import { isStaleExtensionContextError } from "@bastani/atomic";
655
692
  function boundaryBag() {
@@ -730,9 +767,9 @@ function recordedOwners(boundary, reason) {
730
767
  function pruneEndedSources(boundary) {
731
768
  const now = Date.now();
732
769
  for (const [source, trees] of boundary.ended) {
733
- for (const [rootRunId, endedAt] of trees)
770
+ for (const [execution, endedAt] of trees)
734
771
  if (now - endedAt > ENDED_RUN_GRACE_MS)
735
- trees.delete(rootRunId);
772
+ trees.delete(execution);
736
773
  if (trees.size === 0)
737
774
  boundary.ended.delete(source);
738
775
  }
@@ -741,12 +778,12 @@ function recordEndedRun(boundary, scope) {
741
778
  if (scope.source === undefined)
742
779
  return;
743
780
  const trees = boundary.ended.get(scope.source) ?? new Map;
744
- trees.set(scope.rootRunId, Date.now());
781
+ trees.set(scope.execution, Date.now());
745
782
  boundary.ended.set(scope.source, trees);
746
783
  }
747
784
  function endedInAnotherRunTree(boundary, source, live) {
748
- for (const endedRoot of boundary.ended.get(source)?.keys() ?? [])
749
- if (endedRoot !== live.rootRunId)
785
+ for (const endedExecution of boundary.ended.get(source)?.keys() ?? [])
786
+ if (endedExecution !== live.execution)
750
787
  return true;
751
788
  return false;
752
789
  }
@@ -960,6 +997,7 @@ function openRunRejectionScope(options) {
960
997
  const scope = {
961
998
  runId: options.runId,
962
999
  rootRunId,
1000
+ execution: parent?.execution ?? randomUUID(),
963
1001
  source: options.source === undefined ? undefined : normalizeStackPath(options.source),
964
1002
  parent,
965
1003
  fail: options.fail,
@@ -971,8 +1009,11 @@ function openRunRejectionScope(options) {
971
1009
  };
972
1010
  boundary.scopes.add(scope);
973
1011
  boundary.runs.set(scope.runId, scope);
974
- if (scope.source !== undefined)
1012
+ if (scope.source !== undefined) {
975
1013
  markSharedSource(boundary, scope.source);
1014
+ if (endedInAnotherRunTree(boundary, scope.source, scope))
1015
+ scope.sharedSource = true;
1016
+ }
976
1017
  return {
977
1018
  run: (callback) => boundary.store.run(scope, callback),
978
1019
  contain: (promise, effect = "fail-run") => {
@@ -2304,7 +2345,7 @@ var init_workflow_activity = __esm(() => {
2304
2345
  });
2305
2346
 
2306
2347
  // dist/builtin/workflows/src/shared/workflow-observation-runtime.ts
2307
- import { randomUUID } from "node:crypto";
2348
+ import { randomUUID as randomUUID2 } from "node:crypto";
2308
2349
 
2309
2350
  class WorkflowObservationRuntime {
2310
2351
  runs;
@@ -2373,7 +2414,7 @@ class WorkflowObservationRuntime {
2373
2414
  kind: "lifecycle",
2374
2415
  event: {
2375
2416
  type: "workflow_lifecycle",
2376
- eventId: randomUUID(),
2417
+ eventId: randomUUID2(),
2377
2418
  runId: run.id,
2378
2419
  rootRunId,
2379
2420
  occurredAt: now,
@@ -2625,6 +2666,8 @@ function createStoreState() {
2625
2666
  return {
2626
2667
  runs: [],
2627
2668
  runPositions: new Map,
2669
+ childRunIds: new Map,
2670
+ childRunLinks: new Map,
2628
2671
  notices: [],
2629
2672
  listeners: new Set,
2630
2673
  invalidationListeners: new Set,
@@ -2636,11 +2679,41 @@ function createStoreState() {
2636
2679
  }
2637
2680
  function reindexRuns(state) {
2638
2681
  state.runPositions.clear();
2682
+ state.childRunIds.clear();
2683
+ state.childRunLinks.clear();
2639
2684
  state.runs.forEach((run, position) => {
2640
- if (!state.runPositions.has(run.id))
2641
- state.runPositions.set(run.id, position);
2685
+ if (state.runPositions.has(run.id))
2686
+ return;
2687
+ state.runPositions.set(run.id, position);
2688
+ indexChildRun(state, run);
2642
2689
  });
2643
2690
  }
2691
+ function indexChildRun(state, run) {
2692
+ unindexChildRun(state, run.id);
2693
+ if (run.parentRunId === undefined)
2694
+ return;
2695
+ const byStage = state.childRunIds.get(run.parentRunId) ?? new Map;
2696
+ state.childRunIds.set(run.parentRunId, byStage);
2697
+ const ids = byStage.get(run.parentStageId) ?? new Set;
2698
+ byStage.set(run.parentStageId, ids);
2699
+ ids.add(run.id);
2700
+ state.childRunLinks.set(run.id, { parentRunId: run.parentRunId, parentStageId: run.parentStageId });
2701
+ }
2702
+ function unindexChildRun(state, runId) {
2703
+ const link = state.childRunLinks.get(runId);
2704
+ if (link === undefined)
2705
+ return;
2706
+ state.childRunLinks.delete(runId);
2707
+ const byStage = state.childRunIds.get(link.parentRunId);
2708
+ const ids = byStage?.get(link.parentStageId);
2709
+ if (byStage === undefined || ids === undefined)
2710
+ return;
2711
+ ids.delete(runId);
2712
+ if (ids.size === 0)
2713
+ byStage.delete(link.parentStageId);
2714
+ if (byStage.size === 0)
2715
+ state.childRunIds.delete(link.parentRunId);
2716
+ }
2644
2717
  function runPosition(state, runId) {
2645
2718
  const position = state.runPositions.get(runId);
2646
2719
  if (position !== undefined && state.runs[position]?.id === runId)
@@ -2684,13 +2757,14 @@ function createStoreContext(state = createStoreState()) {
2684
2757
  batchedChanges?.push(change);
2685
2758
  return;
2686
2759
  }
2687
- observation.capture(change === undefined ? undefined : [change]);
2688
- publish();
2760
+ const changes = change === undefined ? undefined : [change];
2761
+ observation.capture(changes);
2762
+ publish(changes);
2689
2763
  }
2690
- function publish() {
2764
+ function publish(changes) {
2691
2765
  for (const fn of state.invalidationListeners) {
2692
2766
  try {
2693
- fn();
2767
+ fn(changes);
2694
2768
  } catch {}
2695
2769
  }
2696
2770
  if (state.listeners.size > 0) {
@@ -2717,7 +2791,7 @@ function createStoreContext(state = createStoreState()) {
2717
2791
  batchedNotification = false;
2718
2792
  batchedChanges = [];
2719
2793
  observation.capture(changes);
2720
- publish();
2794
+ publish(changes);
2721
2795
  }
2722
2796
  }
2723
2797
  }
@@ -2729,22 +2803,40 @@ function createStoreContext(state = createStoreState()) {
2729
2803
  const position = runPosition(state, run.id);
2730
2804
  if (position !== undefined) {
2731
2805
  state.runs[position] = run;
2806
+ indexChildRun(state, run);
2732
2807
  return;
2733
2808
  }
2734
2809
  state.runPositions.set(run.id, state.runs.length);
2735
2810
  state.runs.push(run);
2811
+ indexChildRun(state, run);
2736
2812
  }
2737
2813
  function removeRunAt(position) {
2738
2814
  const [removed] = state.runs.splice(position, 1);
2739
2815
  if (removed === undefined)
2740
2816
  return;
2741
2817
  state.runPositions.delete(removed.id);
2818
+ unindexChildRun(state, removed.id);
2742
2819
  for (let index = position;index < state.runs.length; index++)
2743
2820
  state.runPositions.set(state.runs[index].id, index);
2744
2821
  }
2745
2822
  function clearRuns() {
2746
2823
  state.runs.length = 0;
2747
2824
  state.runPositions.clear();
2825
+ state.childRunIds.clear();
2826
+ state.childRunLinks.clear();
2827
+ }
2828
+ function childRuns(parentRunId, parentStageId) {
2829
+ if (state.runPositions.size !== state.runs.length)
2830
+ reindexRuns(state);
2831
+ const byStage = state.childRunIds.get(parentRunId);
2832
+ if (byStage === undefined)
2833
+ return [];
2834
+ const ids = parentStageId === undefined ? [...byStage.values()].flatMap((set) => [...set]) : [...byStage.get(parentStageId) ?? []];
2835
+ 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));
2836
+ }
2837
+ function reparentRun(run, parentStageId) {
2838
+ run.parentStageId = parentStageId;
2839
+ indexChildRun(state, run);
2748
2840
  }
2749
2841
  function findStage(run, stageId) {
2750
2842
  return run.stages.find((s) => s.id === stageId);
@@ -2801,6 +2893,8 @@ function createStoreContext(state = createStoreState()) {
2801
2893
  bumpAndNotify,
2802
2894
  findRun,
2803
2895
  runPosition: (runId) => runPosition(state, runId),
2896
+ childRuns,
2897
+ reparentRun,
2804
2898
  placeRun,
2805
2899
  removeRunAt,
2806
2900
  clearRuns,
@@ -2923,7 +3017,24 @@ function isAddressableStageStatus(status) {
2923
3017
  return ADDRESSABLE_STAGE_STATUSES.has(status);
2924
3018
  }
2925
3019
  function workflowBoundarySegments(runs, runId) {
2926
- return createWorkflowBoundarySegmentsResolver(runs)(runId);
3020
+ const source = runs;
3021
+ if (!isRunLookup(source) || source.childRuns === undefined)
3022
+ return createWorkflowBoundarySegmentsResolver(runsInSource(source))(runId);
3023
+ const segments = [];
3024
+ let current = source.run(runId);
3025
+ while (current !== undefined && current.parentRunId !== undefined) {
3026
+ const parent = findRunInSource(source, current.parentRunId);
3027
+ const boundary = parent?.stages.find((stage) => stage.id === current?.parentStageId);
3028
+ if (parent === undefined || boundary === undefined)
3029
+ return;
3030
+ const boundaryName = boundary.name;
3031
+ const byId = parent.stages.filter((stage) => stage.id === boundaryName);
3032
+ const matching = byId.length > 0 ? byId : parent.stages.filter((stage) => stage.name === boundaryName);
3033
+ const children = matching.length === 1 ? childRunsInSource(source, parent.id, matching[0].id) : undefined;
3034
+ segments.unshift(boundaryName.length > 0 && !boundaryName.includes("/") && !boundaryName.includes("*") && children?.length === 1 && children[0]?.id === current.id ? boundaryName : current.id);
3035
+ current = parent;
3036
+ }
3037
+ return current === undefined ? undefined : segments;
2927
3038
  }
2928
3039
  function createWorkflowBoundarySegmentsResolver(runs) {
2929
3040
  const runById = new Map(runs.map((run) => [run.id, run]));
@@ -2976,10 +3087,10 @@ function createWorkflowBoundarySegmentsResolver(runs) {
2976
3087
  };
2977
3088
  }
2978
3089
  function workflowBoundaryHops(runs, runId) {
2979
- return boundaryHopsFrom(new Map(runs.map((run) => [run.id, run])), runId);
3090
+ return boundaryHopsFrom(runsByIdOf(runs), runId);
2980
3091
  }
2981
3092
  function createWorkflowBoundaryHopsResolver(runs) {
2982
- const runById = new Map(runs.map((run) => [run.id, run]));
3093
+ const runById = runsByIdOf(runs);
2983
3094
  const cache = new Map;
2984
3095
  return (runId) => {
2985
3096
  if (cache.has(runId))
@@ -3073,6 +3184,7 @@ function pendingWorkflowStageStatuses(run, resolveOwningRunStatus, resolveBounda
3073
3184
  var ADDRESSABLE_STAGE_STATUSES;
3074
3185
  var init_pending_stage_status = __esm(() => {
3075
3186
  init_store_internal();
3187
+ init_workflow_run_ownership();
3076
3188
  init_workflow_stage_target();
3077
3189
  ADDRESSABLE_STAGE_STATUSES = new Set([
3078
3190
  "pending",
@@ -3903,13 +4015,13 @@ function recordPendingStageMessageDeliveries(messages, runId, messageId, records
3903
4015
  result[index] = next;
3904
4016
  return result;
3905
4017
  }
3906
- function compactStickyStageMessageDeliveries(messages, runs) {
3907
- 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]))));
4018
+ function compactStickyStageMessageDeliveries(messages, findRun) {
4019
+ const finished = (runId, stageId) => findRun(runId)?.stages.some((stage) => stage.id === stageId && (stage.status === "completed" || stage.status === "skipped")) === true;
3908
4020
  let changed = false;
3909
4021
  const next = messages.map((entry) => {
3910
4022
  if (entry.sticky !== true || entry.deliveries === undefined)
3911
4023
  return entry;
3912
- const deliveries = entry.deliveries.filter((delivery) => !finished.has(JSON.stringify([delivery.runId, delivery.stageId])));
4024
+ const deliveries = entry.deliveries.filter((delivery) => !finished(delivery.runId, delivery.stageId));
3913
4025
  if (deliveries.length === entry.deliveries.length)
3914
4026
  return entry;
3915
4027
  changed = true;
@@ -4078,8 +4190,8 @@ class PendingStageTransitionLedger {
4078
4190
  this.reconciledVersion = version;
4079
4191
  return result;
4080
4192
  }
4081
- async compact(backend, runId, messages, runs, archiveSettled) {
4082
- const stageStatus = createStageStatusLookup(runs);
4193
+ async compact(backend, runId, messages, findRun, archiveSettled) {
4194
+ const stageStatus = createStageStatusLookup(findRun);
4083
4195
  const endedStages = [];
4084
4196
  const dirty = new Set;
4085
4197
  for (const [deliveryRunId, byStage] of this.stages) {
@@ -4177,17 +4289,8 @@ class PendingStageTransitionLedger {
4177
4289
  function isCompactingBackend(backend) {
4178
4290
  return backend.archivePendingStageDeliveryReceipt !== undefined && backend.hasPendingStageDeliveryReceipt !== undefined;
4179
4291
  }
4180
- function createStageStatusLookup(runs) {
4181
- let runById;
4182
- return (runId, stageId) => {
4183
- if (runById === undefined) {
4184
- runById = new Map;
4185
- for (const run of runs)
4186
- if (!runById.has(run.id))
4187
- runById.set(run.id, run);
4188
- }
4189
- return runById.get(runId)?.stages.find((stage) => stage.id === stageId)?.status;
4190
- };
4292
+ function createStageStatusLookup(findRun) {
4293
+ return (runId, stageId) => findRun(runId)?.stages.find((stage) => stage.id === stageId)?.status;
4191
4294
  }
4192
4295
  function isEndedStageStatus(status) {
4193
4296
  return status === "completed" || status === "skipped" || status === "failed";
@@ -4227,6 +4330,7 @@ var init_pending_stage_transition_ledger = () => {};
4227
4330
 
4228
4331
  // dist/builtin/workflows/src/shared/store-pending-stage-delivery-methods.ts
4229
4332
  function createPendingStageDeliveryStoreMethods(context) {
4333
+ const runs = { run: context.findRun, runs: () => context.state.runs };
4230
4334
  const ledgers = new PendingStageLedgers;
4231
4335
  const batches = new PendingStageTransitionBatches(context, ledgers);
4232
4336
  return {
@@ -4249,8 +4353,8 @@ function createPendingStageDeliveryStoreMethods(context) {
4249
4353
  const run = context.findRun(input.runId);
4250
4354
  if (run === undefined)
4251
4355
  return;
4252
- const availableBackend = availableRunDurableBackend(context.state.runs, input.runId) ?? context.backend;
4253
- const backend = availableBackend === undefined ? undefined : durableBackendForRun(availableBackend, context.state.runs, input.runId);
4356
+ const availableBackend = availableRunDurableBackend(runs, input.runId) ?? context.backend;
4357
+ const backend = availableBackend === undefined ? undefined : durableBackendForRun(availableBackend, runs, input.runId);
4254
4358
  const receipt = await backend?.readSettledPendingStageMessage?.(input.runId, input.message.id);
4255
4359
  const result = queueStageMessage(receipt === undefined ? batch.messages(run) : [...batch.messages(run), receipt], input, undefined, undefined, resolvePendingStageIdentity(run, input.stageKey));
4256
4360
  if (!result.ok) {
@@ -4473,7 +4577,7 @@ class PendingStageTransitionBatch {
4473
4577
  }
4474
4578
  if (messages !== run.pendingStageMessages) {
4475
4579
  run.pendingStageMessages = [...messages];
4476
- this.context.bumpAndNotify();
4580
+ this.context.bumpAndNotify({ runId: run.id });
4477
4581
  }
4478
4582
  }
4479
4583
  async apply(backend, runId, messages) {
@@ -4509,7 +4613,7 @@ class PendingStageTransitionBatch {
4509
4613
  const live = this.context.findRun(this.runId) ?? run;
4510
4614
  if (live !== undefined)
4511
4615
  live.pendingStageMessages = [...published];
4512
- this.context.bumpAndNotify();
4616
+ this.context.bumpAndNotify({ runId: this.runId });
4513
4617
  }
4514
4618
  }
4515
4619
  async function compactTransition(backend, runId, messages, context, ledgers, run) {
@@ -4517,9 +4621,9 @@ async function compactTransition(backend, runId, messages, context, ledgers, run
4517
4621
  const reconciled = ledger.reconcile(backend, runId, messages);
4518
4622
  const archiveSettled = backend.archivePendingStageMessage !== undefined && backend.readSettledPendingStageMessage !== undefined ? (entry) => backend.archivePendingStageMessage(runId, entry) : undefined;
4519
4623
  if (isCompactingBackend(backend)) {
4520
- return await ledger.compact(backend, runId, reconciled, context.state.runs, archiveSettled);
4624
+ return await ledger.compact(backend, runId, reconciled, context.findRun, archiveSettled);
4521
4625
  }
4522
- let retained = compactStickyStageMessageDeliveries(reconciled, context.state.runs);
4626
+ let retained = compactStickyStageMessageDeliveries(reconciled, context.findRun);
4523
4627
  if (archiveSettled !== undefined)
4524
4628
  retained = await retainPendingStageMessages(retained, archiveSettled);
4525
4629
  if (run !== undefined)
@@ -4534,7 +4638,7 @@ function reconcileLive(backend, runId, context, ledgers) {
4534
4638
  const recovered = ledgers.for(current).reconcile(backend, runId, messages);
4535
4639
  if (recovered !== messages) {
4536
4640
  current.pendingStageMessages = [...recovered];
4537
- context.bumpAndNotify();
4641
+ context.bumpAndNotify({ runId });
4538
4642
  }
4539
4643
  }
4540
4644
 
@@ -4776,6 +4880,12 @@ function createRunStoreMethods(context) {
4776
4880
  run(runId) {
4777
4881
  return context.findRun(runId);
4778
4882
  },
4883
+ runPosition(runId) {
4884
+ return context.runPosition(runId);
4885
+ },
4886
+ childRuns(parentRunId, parentStageId) {
4887
+ return context.childRuns(parentRunId, parentStageId);
4888
+ },
4779
4889
  notices() {
4780
4890
  return state.notices;
4781
4891
  },
@@ -4818,7 +4928,7 @@ function createRunStoreMethods(context) {
4818
4928
  const run = context.findRun(runId);
4819
4929
  if (run?.parentStageId !== expectedParentStageId || parentStageId === expectedParentStageId)
4820
4930
  return false;
4821
- run.parentStageId = parentStageId;
4931
+ context.reparentRun(run, parentStageId);
4822
4932
  context.bumpAndNotify();
4823
4933
  return true;
4824
4934
  },
@@ -5568,12 +5678,12 @@ __export(exports_stage_ui_broker, {
5568
5678
  mountStageCustomUi: () => mountStageCustomUi,
5569
5679
  stageUiBroker: () => stageUiBroker
5570
5680
  });
5571
- import { randomUUID as randomUUID2 } from "node:crypto";
5681
+ import { randomUUID as randomUUID3 } from "node:crypto";
5572
5682
  function key(runId, stageId) {
5573
5683
  return `${runId}\x00${stageId}`;
5574
5684
  }
5575
5685
  function nextRequestId() {
5576
- return `stage-ui-${randomUUID2()}`;
5686
+ return `stage-ui-${randomUUID3()}`;
5577
5687
  }
5578
5688
 
5579
5689
  class StageUiBroker {
@@ -6930,6 +7040,7 @@ class JournalProjection {
6930
7040
  return {
6931
7041
  resumable: this.listResumableWorkflows(),
6932
7042
  completed: this.listCompletedWorkflows(),
7043
+ completedAll: this.listFinishedRootWorkflows(),
6933
7044
  inspectableIds: [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle)).map((rec) => rec.handle.workflowId)
6934
7045
  };
6935
7046
  }
@@ -6961,6 +7072,9 @@ class JournalProjection {
6961
7072
  listCompletedWorkflows() {
6962
7073
  return [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle) && isHistoricalHandle(rec.handle)).map((rec) => toResumableEntry(rec.handle));
6963
7074
  }
7075
+ listFinishedRootWorkflows() {
7076
+ return [...this.workflows.values()].filter((rec) => isRootWorkflow(rec.handle) && isTerminalStatus(rec.handle.status)).map((rec) => toResumableEntry(rec.handle));
7077
+ }
6964
7078
  toMetadata(workflowId) {
6965
7079
  const rec = this.workflows.get(workflowId);
6966
7080
  if (!rec)
@@ -7019,6 +7133,9 @@ class JournalProjection {
7019
7133
  function isRootWorkflow(handle) {
7020
7134
  return handle.rootWorkflowId === undefined || handle.rootWorkflowId === handle.workflowId;
7021
7135
  }
7136
+ function isTerminalStatus(status) {
7137
+ return status === "completed" || status === "failed" || status === "cancelled";
7138
+ }
7022
7139
  function hasResumeProgress(handle) {
7023
7140
  return handle.completedCheckpoints > 0 || handle.pendingPrompts > 0;
7024
7141
  }
@@ -7102,7 +7219,7 @@ function hasUsableContentBlock(block) {
7102
7219
  }
7103
7220
 
7104
7221
  // dist/builtin/workflows/src/shared/stage-session-store.ts
7105
- import { randomUUID as randomUUID3 } from "node:crypto";
7222
+ import { randomUUID as randomUUID4 } from "node:crypto";
7106
7223
  import { dirname, resolve } from "node:path";
7107
7224
  import {
7108
7225
  JsonlSessionStore,
@@ -7124,7 +7241,7 @@ async function stageSessionStore(options, defaultSessionDir) {
7124
7241
  }
7125
7242
  async function forkStageSession(store, sessionId, cwd, options, destination = store) {
7126
7243
  const source = await store.load(sessionId);
7127
- const id = randomUUID3();
7244
+ const id = randomUUID4();
7128
7245
  await destination.create({
7129
7246
  id,
7130
7247
  version: 4,
@@ -10209,7 +10326,7 @@ var init_stage_runner_session_options = __esm(() => {
10209
10326
  });
10210
10327
 
10211
10328
  // dist/builtin/workflows/src/shared/intercom-group.ts
10212
- import { randomUUID as randomUUID4 } from "node:crypto";
10329
+ import { randomUUID as randomUUID5 } from "node:crypto";
10213
10330
  function workflowInvocationIntercomGroup(rootRunId) {
10214
10331
  return `workflow:${rootRunId}`;
10215
10332
  }
@@ -10231,7 +10348,7 @@ function resolveStageGroup(stageOptions, workflowGroup) {
10231
10348
  const group = stageOptions.group;
10232
10349
  if (group === undefined)
10233
10350
  return workflowGroup;
10234
- const authored = group === true ? randomUUID4() : group.trim();
10351
+ const authored = group === true ? randomUUID5() : group.trim();
10235
10352
  if (authored.length === 0)
10236
10353
  return;
10237
10354
  if (workflowGroup === undefined || authored === DEFAULT_INTERCOM_GROUP)
@@ -10453,7 +10570,7 @@ function bindWorkflowHumanInput(store, ctx, stageUiBroker = currentStageUiBroker
10453
10570
  Promise.resolve().then(async () => {
10454
10571
  if (controller.signal.aborted)
10455
10572
  return;
10456
- if (store.runs().find((candidate) => candidate.id === run.id)?.status !== "running") {
10573
+ if (store.run(run.id)?.status !== "running") {
10457
10574
  if (requests.get(key)?.controller === controller)
10458
10575
  requests.delete(key);
10459
10576
  controller.abort();
@@ -14046,7 +14163,7 @@ function recordCachedStageWithTracker(store, tracker, runId, name, replayKey, ch
14046
14163
  const stageId = sourceStageId ?? cachedStageId(runId, replayKey);
14047
14164
  let parentIds = tracker.onSpawn(stageId, name);
14048
14165
  const sourceParents = sourceStageId === undefined ? undefined : checkpoint.topology?.parentIds;
14049
- const run = store.runs().find((candidate) => candidate.id === runId);
14166
+ const run = store.run(runId);
14050
14167
  const restored = sourceParents?.map((sourceId) => sourceToReplayedNodeIds?.get(sourceId) ?? run?.stages.find((stage) => stage.id === sourceId || stage.replayedFromStageId === sourceId)?.id);
14051
14168
  if (restored?.every((id) => id !== undefined)) {
14052
14169
  parentIds = restored;
@@ -14342,7 +14459,7 @@ class PromptReservationState {
14342
14459
 
14343
14460
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
14344
14461
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
14345
- import { randomUUID as randomUUID5 } from "node:crypto";
14462
+ import { randomUUID as randomUUID6 } from "node:crypto";
14346
14463
  import { setImmediate as setImmediate2 } from "node:timers";
14347
14464
  import { StorageError } from "@bastani/atomic/storage";
14348
14465
  function runProcessExitCleanups() {
@@ -14509,7 +14626,7 @@ class JournalDurableBackend {
14509
14626
  mutationContext = new AsyncLocalStorage5;
14510
14627
  processExitCleanup;
14511
14628
  unregisterExecutionStorages = registerExecutionStorages(this.executionContext, this.mutationContext);
14512
- constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID5()}`, ownsJournal = true) {
14629
+ constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID6()}`, ownsJournal = true) {
14513
14630
  this.journal = journal;
14514
14631
  this.holderId = holderId;
14515
14632
  this.ownsJournal = ownsJournal;
@@ -15628,7 +15745,7 @@ var init_journal_backend = __esm(() => {
15628
15745
  init_internal();
15629
15746
  init_memory_run_journal();
15630
15747
  init_types();
15631
- PROCESS_HOLDER_ID = randomUUID5();
15748
+ PROCESS_HOLDER_ID = randomUUID6();
15632
15749
  processExitCleanups = new Set;
15633
15750
  runInJournalTurns = createTurnSlicer(FAN_OUT_WAITING_OPERATIONS);
15634
15751
  CUSTOM_JOURNAL = { adapter: "custom", location: "custom journal" };
@@ -15956,7 +16073,7 @@ var init_workflow_artifact_env = __esm(() => {
15956
16073
  });
15957
16074
 
15958
16075
  // dist/builtin/workflows/src/shared/workflow-artifacts.ts
15959
- import { randomUUID as randomUUID6 } from "node:crypto";
16076
+ import { randomUUID as randomUUID7 } from "node:crypto";
15960
16077
  import { existsSync } from "node:fs";
15961
16078
  import { mkdir, readdir, rm, stat } from "node:fs/promises";
15962
16079
  import { dirname as dirname4, join as join5 } from "node:path";
@@ -16078,7 +16195,7 @@ function createWorkflowArtifactRunStateResolver() {
16078
16195
  let durable;
16079
16196
  if (backend !== undefined) {
16080
16197
  try {
16081
- durable = durableRunState(availableRunDurableBackend(store.runs(), runId) ?? backend, runId);
16198
+ durable = durableRunState(availableRunDurableBackend(store, runId) ?? backend, runId);
16082
16199
  } catch {
16083
16200
  backendReady = false;
16084
16201
  return localState === "protected" ? "protected" : undefined;
@@ -16165,8 +16282,8 @@ async function ensureWorkflowArtifactRunDirectory(runId) {
16165
16282
  return directory;
16166
16283
  }
16167
16284
  function workflowArtifactDirectoryPath(runId) {
16168
- const effectiveRunId = runId ?? randomUUID6();
16169
- return join5(workflowArtifactRunPath(effectiveRunId), `artifact-${randomUUID6()}`);
16285
+ const effectiveRunId = runId ?? randomUUID7();
16286
+ return join5(workflowArtifactRunPath(effectiveRunId), `artifact-${randomUUID7()}`);
16170
16287
  }
16171
16288
  async function ensureWorkflowArtifactDirectory(directory) {
16172
16289
  await pruneArtifactRootIfDue(workflowArtifactRunsRoot(), Date.now());
@@ -18316,7 +18433,8 @@ function runResultFromSnapshot(snapshot) {
18316
18433
  };
18317
18434
  }
18318
18435
  function reconcileTerminalRunResult(runId, runSnapshot, activeStore, fallback, onRunEnd) {
18319
- const canonical = activeStore.runs().find((snapshot) => snapshot.id === runId && isTerminalRunStatus(snapshot.status));
18436
+ const stored = activeStore.run(runId);
18437
+ const canonical = stored !== undefined && isTerminalRunStatus(stored.status) ? stored : undefined;
18320
18438
  const result = canonical !== undefined ? runResultFromSnapshot(canonical) : {
18321
18439
  runId,
18322
18440
  ...fallback,
@@ -18929,7 +19047,7 @@ function continuationPromptAnswer(store, sourceRun, sourceStage) {
18929
19047
  return answer;
18930
19048
  if (!stage.replayed || stage.replayedFromStageId === undefined || run.resumedFromRunId === undefined)
18931
19049
  break;
18932
- const parentRun = store.runs().find((candidate) => candidate.id === run.resumedFromRunId);
19050
+ const parentRun = store.run(run.resumedFromRunId);
18933
19051
  const parentStage = parentRun?.stages.find((candidate) => candidate.id === stage.replayedFromStageId);
18934
19052
  if (parentRun === undefined || parentStage === undefined)
18935
19053
  break;
@@ -21167,7 +21285,7 @@ var init_admission_host = __esm(() => {
21167
21285
  });
21168
21286
 
21169
21287
  // dist/builtin/workflows/src/workers/resource-admission.ts
21170
- import { randomUUID as randomUUID7 } from "node:crypto";
21288
+ import { randomUUID as randomUUID8 } from "node:crypto";
21171
21289
  import { realpath } from "node:fs/promises";
21172
21290
  import { cpus, freemem, loadavg } from "node:os";
21173
21291
  import { setTimeout as delay } from "node:timers/promises";
@@ -21182,7 +21300,7 @@ class SqlResourceAdmission {
21182
21300
  permits;
21183
21301
  configuration;
21184
21302
  owners;
21185
- owner = randomUUID7();
21303
+ owner = randomUUID8();
21186
21304
  nextReconciliation = 0;
21187
21305
  constructor(storage, options) {
21188
21306
  this.storage = storage;
@@ -21323,7 +21441,7 @@ class SqlResourceAdmission {
21323
21441
  }
21324
21442
  async acquire(kind, signal, request) {
21325
21443
  signal?.throwIfAborted();
21326
- const operation = randomUUID7();
21444
+ const operation = randomUUID8();
21327
21445
  const release = (reason = "resource cleanup confirmed") => this.storage.transaction(async (tx) => {
21328
21446
  await tx.run(`UPDATE ${this.permits} SET state = 'released', reason = ? WHERE operation = ? AND (state != 'released' OR reason = ?)`, reason, operation, FENCED_WAITER_REASON);
21329
21447
  });
@@ -21616,7 +21734,7 @@ var init_resource_admission = __esm(() => {
21616
21734
  });
21617
21735
 
21618
21736
  // dist/builtin/workflows/src/workers/admission-binding.ts
21619
- import { randomUUID as randomUUID8 } from "node:crypto";
21737
+ import { randomUUID as randomUUID9 } from "node:crypto";
21620
21738
  import { withResourceAdmission } from "@bastani/atomic";
21621
21739
 
21622
21740
  class SessionCapacitySlot {
@@ -21694,7 +21812,7 @@ async function admitWorkflowSessions(backend, opts, callback) {
21694
21812
  const admission = await SqlResourceAdmission.open(poolJournalFor(rootBackend.journal), {
21695
21813
  ...config,
21696
21814
  root: opts.parentRun?.rootRunId ?? opts.runId,
21697
- holder: randomUUID8(),
21815
+ holder: randomUUID9(),
21698
21816
  ...opts.parentRun === undefined ? { rootLimits: "replace" } : {}
21699
21817
  });
21700
21818
  return withResourceAdmission(admission, () => callback({
@@ -57913,12 +58031,12 @@ var init_verification_prompts = __esm(() => {
57913
58031
  });
57914
58032
 
57915
58033
  // dist/builtin/workflows/builtin/pattern-artifact-root.ts
57916
- import { randomUUID as randomUUID9 } from "node:crypto";
58034
+ import { randomUUID as randomUUID10 } from "node:crypto";
57917
58035
  import { mkdir as mkdir2 } from "node:fs/promises";
57918
58036
  import { join as join15 } from "node:path";
57919
58037
  async function stableArtifactRoot(ctx, workflowName) {
57920
58038
  const cwd = ctx.cwd ?? process.cwd();
57921
- const artifactDir = await ctx.tool("artifact-root", { workflow: workflowName }, async () => join15(cwd, ".atomic", "workflows", "runs", `${workflowName}-${randomUUID9()}`));
58039
+ const artifactDir = await ctx.tool("artifact-root", { workflow: workflowName }, async () => join15(cwd, ".atomic", "workflows", "runs", `${workflowName}-${randomUUID10()}`));
57922
58040
  await mkdir2(artifactDir, { recursive: true });
57923
58041
  return artifactDir;
57924
58042
  }
@@ -59565,7 +59683,7 @@ var init_goal_review = __esm(() => {
59565
59683
  });
59566
59684
 
59567
59685
  // dist/builtin/workflows/builtin/goal-ledger.ts
59568
- import { randomUUID as randomUUID10 } from "node:crypto";
59686
+ import { randomUUID as randomUUID11 } from "node:crypto";
59569
59687
  import { readFile as readFile4, rename, rm as rm2, writeFile as writeFile6 } from "node:fs/promises";
59570
59688
  import { dirname as dirname12, join as join21 } from "node:path";
59571
59689
  import { isDeepStrictEqual } from "node:util";
@@ -59675,7 +59793,7 @@ async function createGoalLedger(objective, acceptanceCriteria, artifactDir) {
59675
59793
  await writeGoalLedger(ledgerPath, existing);
59676
59794
  return { ledger: existing, ledgerPath, artifactDir };
59677
59795
  }
59678
- const goalId = randomUUID10();
59796
+ const goalId = randomUUID11();
59679
59797
  const now = new Date().toISOString();
59680
59798
  const ledger = {
59681
59799
  goal_id: goalId,
@@ -59704,7 +59822,7 @@ async function writeGoalLedger(ledgerPath, ledger) {
59704
59822
  const stateContents = `${JSON.stringify(ledger, null, 2)}
59705
59823
  `;
59706
59824
  const statePath = goalLedgerStatePath(ledgerPath);
59707
- const pendingStatePath = `${statePath}.${randomUUID10()}.tmp`;
59825
+ const pendingStatePath = `${statePath}.${randomUUID11()}.tmp`;
59708
59826
  await writeFile6(pendingStatePath, stateContents, { encoding: "utf8" });
59709
59827
  try {
59710
59828
  await rename(pendingStatePath, statePath);
@@ -64103,7 +64221,7 @@ var init_pool_stage_usage = __esm(() => {
64103
64221
  });
64104
64222
 
64105
64223
  // dist/builtin/workflows/src/durable/journal/sql-pool-queue.ts
64106
- import { createHash as createHash4, randomUUID as randomUUID11 } from "node:crypto";
64224
+ import { createHash as createHash4, randomUUID as randomUUID12 } from "node:crypto";
64107
64225
  import { assertStorageSchemaVersion as assertStorageSchemaVersion2, StorageError as StorageError2 } from "@bastani/atomic/storage";
64108
64226
  function requestIdentity(request) {
64109
64227
  return createHash4("sha256").update(request).digest("hex");
@@ -64358,7 +64476,7 @@ class SqlPoolQueue {
64358
64476
  const siblings = await tx.all(`SELECT json_extract(descriptor, '$.scope') AS scope FROM ${this.work} WHERE root = ?`, lease.runId);
64359
64477
  if (siblings.some((item) => scope.startsWith(`${item.scope}:`) || item.scope.startsWith(`${scope}:`)))
64360
64478
  throw new Error("Pool work scopes overlap");
64361
- const id = randomUUID11();
64479
+ const id = randomUUID12();
64362
64480
  await tx.run(`INSERT INTO ${this.work}(id, root, boundary, descriptor, fingerprint, epoch, ready_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, id, lease.runId, boundaryId, json, fingerprint, lease.epoch, now);
64363
64481
  if (!this.remote) {
64364
64482
  const seq = await tx.get(`SELECT COALESCE(MAX(seq), 0) AS seq FROM ${this.journal.events} WHERE run_id = ?`, lease.runId);
@@ -64869,7 +64987,7 @@ var init_external_run_routes = __esm(() => {
64869
64987
  });
64870
64988
 
64871
64989
  // dist/builtin/workflows/src/shared/pending-stage-route-capability.ts
64872
- import { randomUUID as randomUUID12 } from "node:crypto";
64990
+ import { randomUUID as randomUUID13 } from "node:crypto";
64873
64991
  function capabilitiesFor(store) {
64874
64992
  let capabilities = routeCapabilities.get(store);
64875
64993
  if (capabilities === undefined) {
@@ -64882,13 +65000,13 @@ function workflowPendingStageRouteCapability(store, runId) {
64882
65000
  const capabilities = capabilitiesFor(store);
64883
65001
  let capability = capabilities.get(runId);
64884
65002
  if (capability === undefined) {
64885
- capability = randomUUID12();
65003
+ capability = randomUUID13();
64886
65004
  capabilities.set(runId, capability);
64887
65005
  }
64888
65006
  return capability;
64889
65007
  }
64890
65008
  function rotateWorkflowPendingStageRouteCapability(store, runId) {
64891
- const capability = randomUUID12();
65009
+ const capability = randomUUID13();
64892
65010
  capabilitiesFor(store).set(runId, capability);
64893
65011
  return capability;
64894
65012
  }
@@ -64998,27 +65116,44 @@ function boundPossibleStageDeliveryStates(states) {
64998
65116
 
64999
65117
  class WorkflowTopologyIndex {
65000
65118
  lineage = [];
65119
+ lineageStarts = new Map;
65001
65120
  runById = new Map;
65002
65121
  roots = new Map;
65003
65122
  hops = new Map;
65004
65123
  refresh(runs) {
65005
65124
  const runById = new Map(runs.map((run) => [run.id, run]));
65006
65125
  const lineage = [];
65126
+ const lineageStarts = new Map;
65007
65127
  for (const run of runs) {
65008
- lineage.push(run.id, run.rootRunId, run.parentRunId, run.parentStageId);
65009
- if (run.parentRunId === undefined)
65010
- continue;
65011
- const parent = runById.get(run.parentRunId);
65012
- const boundary = parent?.stages.find((stage) => stage.id === run.parentStageId);
65013
- lineage.push(parent !== undefined, boundary?.name, authoritativeWorkflowChildRunId(boundary));
65128
+ lineageStarts.set(run.id, lineage.length);
65129
+ pushLineage(lineage, run, runById);
65014
65130
  }
65015
65131
  if (sameValues(lineage, this.lineage))
65016
65132
  return;
65017
65133
  this.lineage = lineage;
65134
+ this.lineageStarts = lineageStarts;
65018
65135
  this.runById = runById;
65019
65136
  this.roots.clear();
65020
65137
  this.hops.clear();
65021
65138
  }
65139
+ holds(source, runIds) {
65140
+ const runs = { get: (runId) => source.run(runId) };
65141
+ const values = [];
65142
+ const unchanged = (run) => {
65143
+ const start = this.lineageStarts.get(run.id);
65144
+ if (start === undefined)
65145
+ return false;
65146
+ values.length = 0;
65147
+ pushLineage(values, run, runs);
65148
+ return values.every((value2, index) => this.lineage[start + index] === value2);
65149
+ };
65150
+ for (const runId of runIds) {
65151
+ const run = source.run(runId);
65152
+ if (run === undefined || !unchanged(run) || !source.childRuns(runId).every(unchanged))
65153
+ return false;
65154
+ }
65155
+ return true;
65156
+ }
65022
65157
  rootOf(runId) {
65023
65158
  if (this.roots.has(runId))
65024
65159
  return this.roots.get(runId);
@@ -65034,6 +65169,14 @@ class WorkflowTopologyIndex {
65034
65169
  return hops;
65035
65170
  }
65036
65171
  }
65172
+ function pushLineage(values, run, runs) {
65173
+ values.push(run.id, run.rootRunId, run.parentRunId, run.parentStageId);
65174
+ if (run.parentRunId === undefined)
65175
+ return;
65176
+ const parent = runs.get(run.parentRunId);
65177
+ const boundary = parent?.stages.find((stage) => stage.id === run.parentStageId);
65178
+ values.push(parent !== undefined, boundary?.name, authoritativeWorkflowChildRunId(boundary));
65179
+ }
65037
65180
  function boundaryHops(runById, runId) {
65038
65181
  const hops = [];
65039
65182
  let current = runById.get(runId);
@@ -65078,12 +65221,12 @@ class PossibleStageRowsIndex {
65078
65221
  this.rootRunId = rootRunId;
65079
65222
  this.topology = topology;
65080
65223
  }
65081
- rows(runs, rootRun, availableBackend) {
65224
+ rows(runs, rootRun, availableBackend, lookup = runs) {
65082
65225
  if (isTerminalRunStatus(rootRun.status))
65083
65226
  return [];
65084
65227
  this.refreshEntries(rootRun.pendingStageMessages ?? []);
65085
- const resolvedBackend = availableRunDurableBackend(runs, this.rootRunId) ?? availableBackend;
65086
- const backend = resolvedBackend === undefined ? undefined : durableBackendForRun(resolvedBackend, runs, this.rootRunId);
65228
+ const resolvedBackend = availableRunDurableBackend(lookup, this.rootRunId) ?? availableBackend;
65229
+ const backend = resolvedBackend === undefined ? undefined : durableBackendForRun(resolvedBackend, lookup, this.rootRunId);
65087
65230
  this.refreshReceipts(backend);
65088
65231
  this.refreshStages(runs);
65089
65232
  for (const state of this.patterns)
@@ -65608,9 +65751,90 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65608
65751
  }
65609
65752
  return index;
65610
65753
  };
65611
- const announceRoutes = () => {
65612
- if (disposed)
65754
+ let rootRunMembers = new Map;
65755
+ const membersOf = (rootRunId) => (rootRunMembers.get(rootRunId) ?? []).flatMap((runId) => {
65756
+ const run = activeStore.run(runId);
65757
+ return run === undefined ? [] : [run];
65758
+ });
65759
+ const dropRoute = (runId) => {
65760
+ announcedRoutes.delete(runId);
65761
+ routeCompletions.delete(runId);
65762
+ possibleStageRowIndexes.delete(runId);
65763
+ };
65764
+ const unpublishedRunIds = new Set;
65765
+ const announceRun = (run, rootRunId, lookups) => {
65766
+ const parentRun = lookups.parentOf(run);
65767
+ const boundary = parentRun?.stages.find((stage) => stage.id === run.parentStageId);
65768
+ const parent = parentRun === undefined || boundary === undefined ? undefined : {
65769
+ runId: parentRun.id,
65770
+ stageKeys: [boundary.id, boundary.name].filter((key) => lookups.childAt(parentRun, key)?.id === run.id)
65771
+ };
65772
+ let possibleStages;
65773
+ if (run.id === rootRunId && isTerminalRunStatus(run.status)) {
65774
+ possibleStageRowIndexes.delete(rootRunId);
65775
+ possibleStages = [];
65776
+ } else if (run.id === rootRunId) {
65777
+ possibleStages = possibleStageRowsIndex(rootRunId).rows(lookups.rowRuns(rootRunId), run, availableStoreDurableBackend(activeStore, rootRunId), lookups.runs);
65778
+ }
65779
+ const announcement = {
65780
+ runId: run.id,
65781
+ group: workflowInvocationIntercomGroup(rootRunId),
65782
+ capability: workflowPendingStageRouteCapability(activeStore, run.id),
65783
+ ...parent === undefined ? {} : { parent },
65784
+ stages: [
65785
+ ...run.stages.filter((stage) => !isNonAgentStage(stage) && workflowInvocationOwnsGroup(workflowInvocationIntercomGroup(rootRunId), stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId))).map((stage) => ({
65786
+ stageId: stage.id,
65787
+ stageName: stage.name,
65788
+ target: stageRouteTarget(lookups.runs, rootRunId, run.id, stage.id, lookups.segments),
65789
+ lifecycle: stage.sessionId === undefined && stage.sessionFile === undefined ? "pending" : "running",
65790
+ routeEligible: stage.pendingStageDeliveryAvailable === true && isAddressableStageStatus(stage.status),
65791
+ group: stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId)
65792
+ })),
65793
+ ...nonAgentNodes(run).map((node) => ({
65794
+ stageId: node.id,
65795
+ stageName: node.name,
65796
+ target: stageRouteTarget(lookups.runs, rootRunId, run.id, node.id, lookups.segments),
65797
+ lifecycle: "pending",
65798
+ routeEligible: false,
65799
+ recipientPurpose: "control",
65800
+ group: workflowInvocationIntercomGroup(rootRunId)
65801
+ }))
65802
+ ],
65803
+ ...possibleStages === undefined ? {} : { possibleStages }
65804
+ };
65805
+ const signature = possibleStages === undefined ? JSON.stringify(announcement) : `${JSON.stringify({ ...announcement, possibleStages: undefined })}\x00${possibleStages.map(rowIdentity).join(",")}`;
65806
+ if (announcedRoutes.get(run.id)?.signature === signature)
65613
65807
  return;
65808
+ const entry = { signature };
65809
+ announcedRoutes.set(run.id, entry);
65810
+ try {
65811
+ outsideWorkflowExecutions(() => pi.events?.emit?.(PENDING_STAGE_ROUTE_EVENT, announcement));
65812
+ } catch (error) {
65813
+ if (announcedRoutes.get(run.id) === entry)
65814
+ announcedRoutes.delete(run.id);
65815
+ unpublishedRunIds.add(run.id);
65816
+ const failure = Promise.reject(error);
65817
+ failure.catch(() => {});
65818
+ routeCompletions.set(run.id, failure);
65819
+ throw error;
65820
+ }
65821
+ const completion = announcement.completion;
65822
+ if (completion === undefined) {
65823
+ announcedRoutes.delete(run.id);
65824
+ routeCompletions.delete(run.id);
65825
+ unpublishedRunIds.add(run.id);
65826
+ } else {
65827
+ routeCompletions.set(run.id, completion);
65828
+ completion.catch(() => {
65829
+ if (announcedRoutes.get(run.id) !== entry)
65830
+ return;
65831
+ announcedRoutes.delete(run.id);
65832
+ unpublishedRunIds.add(run.id);
65833
+ });
65834
+ }
65835
+ };
65836
+ const announceAllRoutes = () => {
65837
+ unpublishedRunIds.clear();
65614
65838
  const ownedRunIds = new Set;
65615
65839
  const runs = activeStore.runs();
65616
65840
  topology.refresh(runs);
@@ -65624,80 +65848,33 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65624
65848
  children.push(run);
65625
65849
  childrenByBoundary.set(key, children);
65626
65850
  }
65627
- const resolveBoundarySegments = createWorkflowBoundarySegmentsResolver(runs);
65851
+ const lookups = {
65852
+ runs,
65853
+ parentOf: (run) => run.parentRunId === undefined ? undefined : runById.get(run.parentRunId),
65854
+ childAt: (parent, segment) => resolveIndexedChildRun(childrenByBoundary, parent, segment),
65855
+ segments: createWorkflowBoundarySegmentsResolver(runs),
65856
+ rowRuns: () => runs
65857
+ };
65858
+ const members = new Map;
65628
65859
  for (const run of runs) {
65860
+ const rootRunId = topology.rootOf(run.id);
65861
+ for (const root of new Set([rootRunId, run.rootRunId])) {
65862
+ if (root === undefined)
65863
+ continue;
65864
+ const ids = members.get(root);
65865
+ if (ids === undefined)
65866
+ members.set(root, [run.id]);
65867
+ else
65868
+ ids.push(run.id);
65869
+ }
65629
65870
  if (externalRunRouteOwner(activeStore, run.id) !== undefined || !ownsRun(run.id))
65630
65871
  continue;
65631
- const rootRunId = topology.rootOf(run.id);
65632
65872
  if (rootRunId === undefined)
65633
65873
  continue;
65634
65874
  ownedRunIds.add(run.id);
65635
- const parentRun = run.parentRunId === undefined ? undefined : runById.get(run.parentRunId);
65636
- const boundary = parentRun?.stages.find((stage) => stage.id === run.parentStageId);
65637
- const parent = parentRun === undefined || boundary === undefined ? undefined : {
65638
- runId: parentRun.id,
65639
- stageKeys: [boundary.id, boundary.name].filter((key) => resolveIndexedChildRun(childrenByBoundary, parentRun, key)?.id === run.id)
65640
- };
65641
- let possibleStages;
65642
- if (run.id === rootRunId && isTerminalRunStatus(run.status)) {
65643
- possibleStageRowIndexes.delete(rootRunId);
65644
- possibleStages = [];
65645
- } else if (run.id === rootRunId) {
65646
- possibleStages = possibleStageRowsIndex(rootRunId).rows(runs, run, availableStoreDurableBackend(activeStore, rootRunId));
65647
- }
65648
- const announcement = {
65649
- runId: run.id,
65650
- group: workflowInvocationIntercomGroup(rootRunId),
65651
- capability: workflowPendingStageRouteCapability(activeStore, run.id),
65652
- ...parent === undefined ? {} : { parent },
65653
- stages: [
65654
- ...run.stages.filter((stage) => !isNonAgentStage(stage) && workflowInvocationOwnsGroup(workflowInvocationIntercomGroup(rootRunId), stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId))).map((stage) => ({
65655
- stageId: stage.id,
65656
- stageName: stage.name,
65657
- target: stageRouteTarget(runs, rootRunId, run.id, stage.id, resolveBoundarySegments),
65658
- lifecycle: stage.sessionId === undefined && stage.sessionFile === undefined ? "pending" : "running",
65659
- routeEligible: stage.pendingStageDeliveryAvailable === true && isAddressableStageStatus(stage.status),
65660
- group: stage.intercomGroup ?? workflowInvocationIntercomGroup(rootRunId)
65661
- })),
65662
- ...nonAgentNodes(run).map((node) => ({
65663
- stageId: node.id,
65664
- stageName: node.name,
65665
- target: stageRouteTarget(runs, rootRunId, run.id, node.id, resolveBoundarySegments),
65666
- lifecycle: "pending",
65667
- routeEligible: false,
65668
- recipientPurpose: "control",
65669
- group: workflowInvocationIntercomGroup(rootRunId)
65670
- }))
65671
- ],
65672
- ...possibleStages === undefined ? {} : { possibleStages }
65673
- };
65674
- const signature = possibleStages === undefined ? JSON.stringify(announcement) : `${JSON.stringify({ ...announcement, possibleStages: undefined })}\x00${possibleStages.map(rowIdentity).join(",")}`;
65675
- if (announcedRoutes.get(run.id)?.signature === signature)
65676
- continue;
65677
- const entry = { signature };
65678
- announcedRoutes.set(run.id, entry);
65679
- try {
65680
- outsideWorkflowExecutions(() => pi.events?.emit?.(PENDING_STAGE_ROUTE_EVENT, announcement));
65681
- } catch (error) {
65682
- if (announcedRoutes.get(run.id) === entry)
65683
- announcedRoutes.delete(run.id);
65684
- const failure = Promise.reject(error);
65685
- failure.catch(() => {});
65686
- routeCompletions.set(run.id, failure);
65687
- throw error;
65688
- }
65689
- const completion = announcement.completion;
65690
- if (completion === undefined) {
65691
- announcedRoutes.delete(run.id);
65692
- routeCompletions.delete(run.id);
65693
- } else {
65694
- routeCompletions.set(run.id, completion);
65695
- completion.catch(() => {
65696
- if (announcedRoutes.get(run.id) === entry)
65697
- announcedRoutes.delete(run.id);
65698
- });
65699
- }
65875
+ announceRun(run, rootRunId, lookups);
65700
65876
  }
65877
+ rootRunMembers = members;
65701
65878
  for (const runId of announcedRoutes.keys()) {
65702
65879
  if (!ownedRunIds.has(runId))
65703
65880
  announcedRoutes.delete(runId);
@@ -65710,7 +65887,65 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65710
65887
  if (!ownedRunIds.has(rootRunId))
65711
65888
  possibleStageRowIndexes.delete(rootRunId);
65712
65889
  }
65713
- sweepPromise = sweepPromise.then(() => outsideWorkflowExecutions(() => settleUndeliverablePendingStageMessages(activeStore, notifyUndeliverable, ownsRun))).then(() => {
65890
+ };
65891
+ const announceChangedRoutes = (changed) => {
65892
+ const retried = [...unpublishedRunIds];
65893
+ unpublishedRunIds.clear();
65894
+ const roots = new Set;
65895
+ for (const runId of [...changed, ...retried])
65896
+ for (const root of [topology.rootOf(runId), activeStore.run(runId)?.rootRunId])
65897
+ if (root !== undefined && rootRunMembers.has(root))
65898
+ roots.add(root);
65899
+ const segments = new Map;
65900
+ const lookups = {
65901
+ runs: activeStore,
65902
+ parentOf: (run) => run.parentRunId === undefined ? undefined : activeStore.run(run.parentRunId),
65903
+ childAt: (parent, segment) => resolveChildRun(activeStore, parent, segment),
65904
+ segments: (runId) => {
65905
+ if (!segments.has(runId))
65906
+ segments.set(runId, workflowBoundarySegments(activeStore, runId));
65907
+ return segments.get(runId);
65908
+ },
65909
+ rowRuns: membersOf
65910
+ };
65911
+ const position = (runId) => activeStore.runPosition(runId) ?? Number.MAX_SAFE_INTEGER;
65912
+ for (const rootRunId of [...roots].sort((left, right) => position(left) - position(right))) {
65913
+ for (const run of membersOf(rootRunId)) {
65914
+ if (topology.rootOf(run.id) !== rootRunId)
65915
+ continue;
65916
+ if (externalRunRouteOwner(activeStore, run.id) !== undefined || !ownsRun(run.id))
65917
+ dropRoute(run.id);
65918
+ else
65919
+ announceRun(run, rootRunId, lookups);
65920
+ }
65921
+ }
65922
+ };
65923
+ const unsettledRunIds = new Set;
65924
+ const sweep = async (changed) => {
65925
+ const runIds = changed === undefined ? undefined : new Set([...changed, ...unsettledRunIds]);
65926
+ const found = new Set;
65927
+ try {
65928
+ await settleUndeliverablePendingStageMessages(activeStore, notifyUndeliverable, ownsRun, runIds, (runId) => found.add(runId));
65929
+ } finally {
65930
+ if (runIds === undefined)
65931
+ unsettledRunIds.clear();
65932
+ else
65933
+ for (const runId of runIds)
65934
+ unsettledRunIds.delete(runId);
65935
+ for (const runId of found)
65936
+ if (hasSettlementWork(activeStore.run(runId)))
65937
+ unsettledRunIds.add(runId);
65938
+ }
65939
+ };
65940
+ const announceRoutes = (changed) => {
65941
+ if (disposed)
65942
+ return;
65943
+ const scope = changed !== undefined && topology.holds(activeStore, changed) ? changed : undefined;
65944
+ if (scope === undefined)
65945
+ announceAllRoutes();
65946
+ else
65947
+ announceChangedRoutes(scope);
65948
+ sweepPromise = sweepPromise.then(() => outsideWorkflowExecutions(() => sweep(scope))).then(() => {
65714
65949
  return;
65715
65950
  }).catch((error) => reportWarning(`atomic-workflows: pending stage delivery sweep failed: ${error.message}`));
65716
65951
  };
@@ -65718,13 +65953,21 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65718
65953
  let announcementTimer;
65719
65954
  let announcedAt = Number.NEGATIVE_INFINITY;
65720
65955
  let announcementCost = 0;
65721
- const announceNow = () => {
65956
+ let changedRunIds = new Set;
65957
+ const announceNow = (everything = false) => {
65722
65958
  if (announcementTimer !== undefined)
65723
65959
  clearTimeout(announcementTimer);
65724
65960
  announcementTimer = undefined;
65725
65961
  announcementPending = false;
65962
+ const changed = everything ? undefined : changedRunIds;
65963
+ changedRunIds = new Set;
65726
65964
  const started = performance.now();
65727
- announceRoutes();
65965
+ try {
65966
+ announceRoutes(changed);
65967
+ } catch (error) {
65968
+ changedRunIds = undefined;
65969
+ throw error;
65970
+ }
65728
65971
  announcedAt = performance.now();
65729
65972
  announcementCost = announcedAt - started;
65730
65973
  };
@@ -65747,8 +65990,15 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65747
65990
  }
65748
65991
  }
65749
65992
  };
65750
- const scheduleAnnouncement = () => {
65751
- if (disposed || announcementTimer !== undefined)
65993
+ const scheduleAnnouncement = (changes) => {
65994
+ if (disposed)
65995
+ return;
65996
+ if (changes === undefined)
65997
+ changedRunIds = undefined;
65998
+ else if (changedRunIds !== undefined)
65999
+ for (const change of changes)
66000
+ changedRunIds.add(change.runId);
66001
+ if (announcementTimer !== undefined)
65752
66002
  return;
65753
66003
  const idle = announcementCost / ROUTE_ANNOUNCEMENT_EVENT_LOOP_SHARE - announcementCost;
65754
66004
  const wait = Math.max(ROUTE_ANNOUNCEMENT_BATCH_MS, announcedAt + idle - performance.now());
@@ -65757,21 +66007,20 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65757
66007
  announcementTimer.unref?.();
65758
66008
  };
65759
66009
  const unsubscribeStore = activeStore.subscribeInvalidation(scheduleAnnouncement);
65760
- announceNow();
66010
+ announceNow(true);
65761
66011
  pi.on?.("session_start", () => {
65762
66012
  announcedRoutes.clear();
65763
- announceNow();
66013
+ announceNow(true);
65764
66014
  });
65765
66015
  const routePendingStageMessage = (payload) => {
65766
66016
  if (disposed || !isPendingStageMessageEvent(payload) || payload.handled)
65767
66017
  return;
65768
- const runs = activeStore.runs();
65769
66018
  const parsedTarget = parseWorkflowStageTarget(payload.target);
65770
66019
  if (parsedTarget === undefined)
65771
66020
  return;
65772
66021
  if (!ownsRun(parsedTarget.rootRunId))
65773
66022
  return;
65774
- if (parsedTarget.kind === "path" && isMaterializedNonAgentTarget(runs, parsedTarget)) {
66023
+ if (parsedTarget.kind === "path" && isMaterializedNonAgentTarget(activeStore, parsedTarget)) {
65775
66024
  payload.handled = true;
65776
66025
  payload.completion = Promise.resolve({
65777
66026
  outcome: "refused",
@@ -65779,22 +66028,22 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65779
66028
  });
65780
66029
  return;
65781
66030
  }
65782
- const destination = resolveMaterializedStage(runs, payload.target);
66031
+ const destination = resolveMaterializedStage(activeStore, payload.target);
65783
66032
  if (destination === undefined) {
65784
66033
  if (payload.live === true)
65785
66034
  return;
65786
- const rootRun = runs.find((candidate) => candidate.id === parsedTarget.rootRunId);
66035
+ const rootRun = activeStore.run(parsedTarget.rootRunId);
65787
66036
  if (rootRun === undefined)
65788
66037
  return;
65789
66038
  payload.handled = true;
65790
- payload.completion = deliverStickyTarget(activeStore, runs, rootRun, payload, parsedTarget).then((value2) => {
66039
+ payload.completion = deliverStickyTarget(activeStore, rootRun, payload, parsedTarget).then((value2) => {
65791
66040
  return value2;
65792
66041
  }, (error) => {
65793
66042
  throw error;
65794
66043
  });
65795
66044
  return;
65796
66045
  }
65797
- const rootRunId = durableRootRunIdForRun(runs, destination.run.id);
66046
+ const rootRunId = durableRootRunIdForRun(activeStore, destination.run.id);
65798
66047
  if (rootRunId === undefined)
65799
66048
  return;
65800
66049
  const resolvedEvent = {
@@ -65810,7 +66059,7 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65810
66059
  payload.handled = true;
65811
66060
  payload.completion = validateLiveDelivery(activeStore, resolvedEvent).then((result) => result.outcome === "forward" ? {
65812
66061
  outcome: "forward",
65813
- target: stageRouteTarget(runs, rootRunId, destination.run.id, stage.id)
66062
+ target: stageRouteTarget(activeStore, rootRunId, destination.run.id, stage.id)
65814
66063
  } : result);
65815
66064
  return;
65816
66065
  }
@@ -65818,11 +66067,11 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65818
66067
  if (uninitializedStage === undefined) {
65819
66068
  if (payload.message.expectsReply === true)
65820
66069
  return;
65821
- const stickyRoot = runs.find((candidate) => candidate.id === parsedTarget.rootRunId);
66070
+ const stickyRoot = activeStore.run(parsedTarget.rootRunId);
65822
66071
  if (stickyRoot === undefined || isTerminalRunStatus(stickyRoot.status))
65823
66072
  return;
65824
66073
  payload.handled = true;
65825
- payload.completion = deliverStickyTarget(activeStore, runs, stickyRoot, payload, parsedTarget);
66074
+ payload.completion = deliverStickyTarget(activeStore, stickyRoot, payload, parsedTarget);
65826
66075
  return;
65827
66076
  }
65828
66077
  payload.handled = true;
@@ -65863,7 +66112,7 @@ function registerPendingStageIntercomBridge(pi, activeStore, ownsRun = () => tru
65863
66112
  await Promise.allSettled(routeCompletions.values());
65864
66113
  await sweepPromise;
65865
66114
  },
65866
- refresh: announceNow
66115
+ refresh: () => announceNow(true)
65867
66116
  });
65868
66117
  }
65869
66118
  function stageRouteTarget(runs, rootRunId, runId, stageId, resolveBoundarySegments = (id) => workflowBoundarySegments(runs, id)) {
@@ -65909,20 +66158,20 @@ function resolveIndexedChildRun(childrenByBoundary, parent, segment) {
65909
66158
  function resolveChildRun(runs, parent, segment) {
65910
66159
  const boundariesById = parent.stages.filter((stage) => stage.id === segment);
65911
66160
  const boundaries = boundariesById.length > 0 ? boundariesById : parent.stages.filter((stage) => stage.name === segment);
65912
- const children = boundaries.flatMap((boundary) => runs.filter((candidate) => candidate.parentRunId === parent.id && candidate.parentStageId === boundary.id));
66161
+ const children = boundaries.flatMap((boundary) => childRunsInSource(runs, parent.id, boundary.id));
65913
66162
  return children.length === 1 ? children[0] : undefined;
65914
66163
  }
65915
66164
  function resolveMaterializedRun(runs, parsed) {
65916
66165
  if (parsed.kind !== "path")
65917
66166
  return;
65918
- const rootRun = runs.find((candidate) => candidate.id === parsed.rootRunId);
66167
+ const rootRun = findRunInSource(runs, parsed.rootRunId);
65919
66168
  if (rootRun === undefined)
65920
66169
  return;
65921
66170
  let run = rootRun;
65922
66171
  for (const segment of parsed.segments.slice(0, -1)) {
65923
- const runById = runs.filter((candidate) => candidate.id === segment && durableRootRunIdForRun(runs, candidate.id) === parsed.rootRunId);
65924
- if (runById.length === 1) {
65925
- run = runById[0];
66172
+ const runById = findRunInSource(runs, segment);
66173
+ if (runById !== undefined && durableRootRunIdForRun(runs, runById.id) === parsed.rootRunId) {
66174
+ run = runById;
65926
66175
  continue;
65927
66176
  }
65928
66177
  const child = resolveChildRun(runs, run, segment);
@@ -65985,7 +66234,7 @@ async function queueAndPersist(activeStore, event, runGroup, pendingStageDeliver
65985
66234
  queuedAt: new Date().toISOString()
65986
66235
  };
65987
66236
  const rootBackend = requireStoreDurableBackend(activeStore, event.runId);
65988
- const backend = durableBackendForRun(rootBackend, activeStore.runs(), event.runId);
66237
+ const backend = durableBackendForRun(rootBackend, activeStore, event.runId);
65989
66238
  if (backend === undefined)
65990
66239
  return { outcome: "refused", reason: "Session not found" };
65991
66240
  const senderGroup = pendingStageSenderGroup(event, runGroup);
@@ -66019,7 +66268,7 @@ async function queueAndPersist(activeStore, event, runGroup, pendingStageDeliver
66019
66268
  return { outcome: "refused", reason: "Pending-stage delivery was refused" };
66020
66269
  return { outcome: "queued", position: result.position };
66021
66270
  }
66022
- async function deliverStickyTarget(activeStore, runs, rootRun, event, parsedTarget) {
66271
+ async function deliverStickyTarget(activeStore, rootRun, event, parsedTarget) {
66023
66272
  const rootRunId = rootRun.id;
66024
66273
  const runGroup = workflowInvocationIntercomGroup(rootRunId);
66025
66274
  if (event.message.expectsReply === true) {
@@ -66031,9 +66280,9 @@ async function deliverStickyTarget(activeStore, runs, rootRun, event, parsedTarg
66031
66280
  reason: `Workflow run ${rootRunId} terminated with status ${rootRun.status} before any stage matching ${event.target} started`
66032
66281
  };
66033
66282
  }
66034
- const liveMatches = matchingLiveStages(runs, rootRunId, parsedTarget.segments);
66035
- const notInKnownSet = targetSegmentsInPossibleStages(parsedTarget.segments, rootRun.possibleStages ?? []) || liveMatches.length > 0 || matchingLiveStages(runs, rootRunId, parsedTarget.segments, { includePending: true }).length > 0 ? undefined : true;
66036
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), runs, rootRunId);
66283
+ const liveMatches = matchingLiveStages(activeStore, rootRunId, parsedTarget.segments);
66284
+ const notInKnownSet = targetSegmentsInPossibleStages(parsedTarget.segments, rootRun.possibleStages ?? []) || liveMatches.length > 0 || matchingLiveStages(activeStore, rootRunId, parsedTarget.segments, { includePending: true }).length > 0 ? undefined : true;
66285
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), activeStore, rootRunId);
66037
66286
  if (backend === undefined)
66038
66287
  return { outcome: "refused", reason: "Session not found" };
66039
66288
  const senderGroup = pendingStageSenderGroup(event, runGroup);
@@ -66101,14 +66350,13 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
66101
66350
  const parsedTarget = parseWorkflowStageTarget(event.target);
66102
66351
  if (parsedTarget === undefined)
66103
66352
  return false;
66104
- const runs = activeStore.runs();
66105
66353
  const rootRunId = parsedTarget.rootRunId;
66106
- const rootRun = runs.find((candidate) => candidate.id === rootRunId);
66354
+ const rootRun = activeStore.run(rootRunId);
66107
66355
  const entry = rootRun?.pendingStageMessages?.find((candidate) => candidate.sticky === true && candidate.message.id === event.messageId);
66108
66356
  if (rootRun === undefined || entry === undefined)
66109
66357
  return false;
66110
66358
  const delivered = new Set(event.deliveredTargets);
66111
- const records = matchingLiveStages(runs, rootRunId, parsedTarget.segments).filter((match) => delivered.has(match.target)).map((match) => ({
66359
+ const records = matchingLiveStages(activeStore, rootRunId, parsedTarget.segments).filter((match) => delivered.has(match.target)).map((match) => ({
66112
66360
  runId: match.run.id,
66113
66361
  stageId: match.stage.id,
66114
66362
  ...match.stage.name === match.stage.id ? {} : { stageName: match.stage.name },
@@ -66117,7 +66365,7 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
66117
66365
  }));
66118
66366
  if (records.length === 0)
66119
66367
  return false;
66120
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), runs, rootRunId);
66368
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, rootRunId), activeStore, rootRunId);
66121
66369
  if (backend === undefined)
66122
66370
  return false;
66123
66371
  const unconfirmedRecords = [];
@@ -66130,11 +66378,8 @@ async function recordConfirmedStickyDeliveries(activeStore, event) {
66130
66378
  }
66131
66379
  function matchingLiveStages(runs, rootRunId, patternSegments, options = {}) {
66132
66380
  const matches = [];
66133
- const runById = new Map(runs.map((run) => [run.id, run]));
66134
66381
  const hopsFor = createWorkflowBoundaryHopsResolver(runs);
66135
- for (const run of runs) {
66136
- if (reciprocalWorkflowRootRunId(runById, run.id) !== rootRunId)
66137
- continue;
66382
+ for (const run of invocationRunsInSource(runs, rootRunId)) {
66138
66383
  const hops = hopsFor(run.id);
66139
66384
  if (hops === undefined)
66140
66385
  continue;
@@ -66199,17 +66444,45 @@ function needsUndeliverableSettlement(run, entry) {
66199
66444
  return pendingStageUndeliverableReason(run, entry) !== undefined;
66200
66445
  return entry.status === "undeliverable" && entry.undeliverableNotificationId !== undefined && entry.undeliverableNotifiedAt === undefined && entry.undeliverableReason !== undefined;
66201
66446
  }
66202
- async function settleUndeliverablePendingStageMessages(activeStore, notify, ownsRun = () => true) {
66447
+ function hasSettlementWork(run) {
66448
+ return run?.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)) === true;
66449
+ }
66450
+ async function settleUndeliverablePendingStageMessages(activeStore, notify, ownsRun = () => true, runIds, onSettlementWork) {
66451
+ if (runIds !== undefined) {
66452
+ const position = (run) => activeStore.runPosition(run.id) ?? Number.MAX_SAFE_INTEGER;
66453
+ const candidates = [...new Set(runIds)].flatMap((runId) => {
66454
+ const run = activeStore.run(runId);
66455
+ return run !== undefined && hasSettlementWork(run) ? [run] : [];
66456
+ }).sort((left, right) => position(left) - position(right));
66457
+ for (const run of candidates)
66458
+ onSettlementWork?.(run.id);
66459
+ const owned = candidates.filter((run) => ownsRun(run.id));
66460
+ if (owned.length === 0)
66461
+ return 0;
66462
+ const ownedRuns = {
66463
+ run: (runId) => {
66464
+ const run = activeStore.run(runId);
66465
+ return run !== undefined && ownsRun(run.id) ? run : undefined;
66466
+ },
66467
+ runs: () => activeStore.runs().filter((run) => ownsRun(run.id))
66468
+ };
66469
+ return settleRuns(activeStore, owned, ownedRuns, notify);
66470
+ }
66203
66471
  const all = activeStore.runs();
66204
- const pending = (run) => run.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)) === true;
66205
- if (!all.some((run) => pending(run) && ownsRun(run.id)))
66472
+ const candidates = all.filter(hasSettlementWork);
66473
+ for (const run of candidates)
66474
+ onSettlementWork?.(run.id);
66475
+ if (!candidates.some((run) => ownsRun(run.id)))
66206
66476
  return 0;
66207
66477
  const runs = all.filter((run) => ownsRun(run.id));
66478
+ return settleRuns(activeStore, runs, runs, notify);
66479
+ }
66480
+ async function settleRuns(activeStore, runs, owners, notify) {
66208
66481
  let settled = 0;
66209
66482
  for (const run of runs) {
66210
- if (!run.pendingStageMessages?.some((entry) => needsUndeliverableSettlement(run, entry)))
66483
+ if (!hasSettlementWork(run))
66211
66484
  continue;
66212
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, run.id), runs, run.id);
66485
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, run.id), owners, run.id);
66213
66486
  if (backend === undefined) {
66214
66487
  throw new Error(`atomic-workflows: workflow run ${run.id} has no durable owner for pending-stage settlement`);
66215
66488
  }
@@ -66228,7 +66501,7 @@ async function settleUndeliverablePendingStageMessages(activeStore, notify, owns
66228
66501
  if (await activeStore.markPendingStageMessageUndeliverable(run.id, entry.stageKey, entry.id, reason, backend)) {
66229
66502
  settled += 1;
66230
66503
  }
66231
- const currentRun = activeStore.runs().find((candidate) => candidate.id === run.id);
66504
+ const currentRun = activeStore.run(run.id);
66232
66505
  const currentEntry = currentRun?.pendingStageMessages?.find((candidate) => candidate.stageKey === entry.stageKey && candidate.id === entry.id);
66233
66506
  if (currentEntry === undefined)
66234
66507
  continue;
@@ -66414,7 +66687,7 @@ function buildSendSignature(to, options) {
66414
66687
  }
66415
66688
 
66416
66689
  // dist/builtin/intercom/broker/pending-send-registry.ts
66417
- import { randomUUID as randomUUID13 } from "crypto";
66690
+ import { randomUUID as randomUUID14 } from "crypto";
66418
66691
 
66419
66692
  class PendingSendRegistry {
66420
66693
  generationTtlMs;
@@ -66473,7 +66746,7 @@ class PendingSendRegistry {
66473
66746
  const generation = this.nextGeneration(messageId);
66474
66747
  const attempt = {
66475
66748
  messageId,
66476
- attemptId: randomUUID13(),
66749
+ attemptId: randomUUID14(),
66477
66750
  signature,
66478
66751
  promise,
66479
66752
  resolve: resolvePromise,
@@ -66759,7 +67032,7 @@ var init_retry_policy = __esm(() => {
66759
67032
  // dist/builtin/intercom/broker/client.ts
66760
67033
  import { EventEmitter } from "events";
66761
67034
  import net2 from "net";
66762
- import { randomUUID as randomUUID14 } from "crypto";
67035
+ import { randomUUID as randomUUID15 } from "crypto";
66763
67036
  function connectAborted() {
66764
67037
  return new IntercomClientDisconnectedError({ cause: new Error("Disconnected before the broker connection registered") });
66765
67038
  }
@@ -66874,7 +67147,7 @@ var init_client = __esm(() => {
66874
67147
  if (this.socket !== socket || socket.destroyed)
66875
67148
  return this.disconnectError ?? new IntercomClientDisconnectedError;
66876
67149
  if (this.healthCheck?.socket !== socket) {
66877
- const requestId = randomUUID14();
67150
+ const requestId = randomUUID15();
66878
67151
  const result = new Promise((resolve) => {
66879
67152
  const finish = (failure) => {
66880
67153
  clearTimeout(timer);
@@ -66906,7 +67179,7 @@ var init_client = __esm(() => {
66906
67179
  }
66907
67180
  return reported;
66908
67181
  }
66909
- constructor(returnAddress = randomUUID14(), options = {}) {
67182
+ constructor(returnAddress = randomUUID15(), options = {}) {
66910
67183
  super();
66911
67184
  if (returnAddress.length === 0)
66912
67185
  throw new Error("Intercom return address must not be empty");
@@ -67567,7 +67840,7 @@ var init_client = __esm(() => {
67567
67840
  return Promise.reject(toError(error));
67568
67841
  }
67569
67842
  return new Promise((resolve, reject) => {
67570
- const requestId = randomUUID14();
67843
+ const requestId = randomUUID15();
67571
67844
  const timeout = setTimeout(() => {
67572
67845
  if (!this.pendingLists.delete(requestId))
67573
67846
  return;
@@ -67599,7 +67872,7 @@ var init_client = __esm(() => {
67599
67872
  } catch (error) {
67600
67873
  return Promise.reject(toError(error));
67601
67874
  }
67602
- const requestId = randomUUID14();
67875
+ const requestId = randomUUID15();
67603
67876
  return new Promise((resolve, reject) => {
67604
67877
  const timeout = setTimeout(() => {
67605
67878
  if (!this.pendingGroupLists.delete(requestId))
@@ -67634,7 +67907,7 @@ var init_client = __esm(() => {
67634
67907
  }
67635
67908
  if (!this.brokerAnswersStatus)
67636
67909
  return Promise.resolve(undefined);
67637
- const requestId = randomUUID14();
67910
+ const requestId = randomUUID15();
67638
67911
  return new Promise((resolve, reject) => {
67639
67912
  const timeout = setTimeout(() => {
67640
67913
  if (!this.pendingBrokerStatus.delete(requestId))
@@ -67673,7 +67946,7 @@ var init_client = __esm(() => {
67673
67946
  } catch (error) {
67674
67947
  return Promise.reject(toError(error));
67675
67948
  }
67676
- const requestId = randomUUID14();
67949
+ const requestId = randomUUID15();
67677
67950
  return new Promise((resolve, reject) => {
67678
67951
  const timeout = setTimeout(() => {
67679
67952
  if (!this.pendingMemberships.delete(requestId))
@@ -67710,7 +67983,7 @@ var init_client = __esm(() => {
67710
67983
  if (!normalizedChildName)
67711
67984
  return Promise.reject(new Error("Child session name is required"));
67712
67985
  return new Promise((resolve, reject) => {
67713
- const requestId = randomUUID14();
67986
+ const requestId = randomUUID15();
67714
67987
  const timeout = setTimeout(() => {
67715
67988
  if (!this.pendingSupervisorAuthorizations.delete(requestId))
67716
67989
  return;
@@ -67760,7 +68033,7 @@ var init_client = __esm(() => {
67760
68033
  } catch (error) {
67761
68034
  return Promise.reject(toError(error));
67762
68035
  }
67763
- const requestId = randomUUID14();
68036
+ const requestId = randomUUID15();
67764
68037
  return new Promise((resolve, reject) => {
67765
68038
  const timeout = setTimeout(() => {
67766
68039
  if (!this.pendingRestoringRecipientRequests.delete(requestId))
@@ -67817,7 +68090,7 @@ var init_client = __esm(() => {
67817
68090
  });
67818
68091
  }
67819
68092
  return new Promise((resolve, reject) => {
67820
- const requestId = randomUUID14();
68093
+ const requestId = randomUUID15();
67821
68094
  const timeout = setTimeout(() => {
67822
68095
  if (!this.pendingStageRouteRegistrations.delete(requestId))
67823
68096
  return;
@@ -67863,7 +68136,7 @@ var init_client = __esm(() => {
67863
68136
  }
67864
68137
  if (!this.brokerClaimsWorkflowInvocations)
67865
68138
  return Promise.resolve(false);
67866
- const requestId = randomUUID14();
68139
+ const requestId = randomUUID15();
67867
68140
  return new Promise((resolve, reject) => {
67868
68141
  this.pendingWorkflowInvocationClaims.set(requestId, { resolve, reject });
67869
68142
  try {
@@ -67881,7 +68154,7 @@ var init_client = __esm(() => {
67881
68154
  } catch (error) {
67882
68155
  return Promise.reject(toError(error));
67883
68156
  }
67884
- const requestId = randomUUID14();
68157
+ const requestId = randomUUID15();
67885
68158
  return new Promise((resolve, reject) => {
67886
68159
  this.pendingLiveWorkflowStageRoutes.set(requestId, { resolve, reject });
67887
68160
  try {
@@ -67949,7 +68222,7 @@ var init_client = __esm(() => {
67949
68222
  } catch (error) {
67950
68223
  return Promise.reject(toError(error));
67951
68224
  }
67952
- const messageId = options.messageId ?? randomUUID14();
68225
+ const messageId = options.messageId ?? randomUUID15();
67953
68226
  let acquired;
67954
68227
  try {
67955
68228
  const pendingSignature = JSON.stringify({
@@ -68035,7 +68308,7 @@ var init_client = __esm(() => {
68035
68308
  } catch (error) {
68036
68309
  return Promise.reject(toError(error));
68037
68310
  }
68038
- const requestId = randomUUID14();
68311
+ const requestId = randomUUID15();
68039
68312
  return new Promise((resolve, reject) => {
68040
68313
  const wrappedResolve = (group) => {
68041
68314
  clearTimeout(timeout);
@@ -68093,7 +68366,7 @@ var init_start_announcement = () => {};
68093
68366
 
68094
68367
  // dist/builtin/intercom/broker/spawn.ts
68095
68368
  import { spawn } from "child_process";
68096
- import { randomUUID as randomUUID15 } from "crypto";
68369
+ import { randomUUID as randomUUID16 } from "crypto";
68097
68370
  import { appendFileSync, chmodSync, closeSync as closeSync4, existsSync as existsSync7, mkdirSync as mkdirSync9, openSync as openSync4, readFileSync as readFileSync7, readSync as readSync2, statSync as statSync6, unlinkSync as unlinkSync4, writeFileSync as writeFileSync6 } from "fs";
68098
68371
  import { join as join30, dirname as dirname14 } from "path";
68099
68372
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -68304,7 +68577,7 @@ async function spawnBrokerIfNeeded(brokerCommand, brokerArgs, readyTimeoutMs = B
68304
68577
  }
68305
68578
  const brokerPath = resolveBrokerEntrypoint(extensionDir);
68306
68579
  const launch = getBrokerLaunchSpec(brokerPath, brokerCommand, brokerArgs, extensionDir);
68307
- const announcement = launch.kind === "windows-launcher" ? { path: BROKER_START_ANNOUNCEMENT, token: randomUUID15() } : undefined;
68580
+ const announcement = launch.kind === "windows-launcher" ? { path: BROKER_START_ANNOUNCEMENT, token: randomUUID16() } : undefined;
68308
68581
  if (announcement !== undefined) {
68309
68582
  try {
68310
68583
  unlinkSync4(announcement.path);
@@ -68633,7 +68906,7 @@ var init_reconnect_backoff = __esm(() => {
68633
68906
  });
68634
68907
 
68635
68908
  // dist/builtin/intercom/workflow-route-owner.ts
68636
- import { randomUUID as randomUUID16 } from "node:crypto";
68909
+ import { randomUUID as randomUUID17 } from "node:crypto";
68637
68910
  import { createEventBus, getBuiltinPackagePaths } from "@bastani/atomic";
68638
68911
  function closedError() {
68639
68912
  return new Error("Workflow Intercom route owner closed");
@@ -68641,7 +68914,7 @@ function closedError() {
68641
68914
  function createWorkflowRouteOwner(cwd) {
68642
68915
  const events = createEventBus();
68643
68916
  const config = loadConfig();
68644
- const id = randomUUID16();
68917
+ const id = randomUUID17();
68645
68918
  const routes = new Map;
68646
68919
  const connections = new Map;
68647
68920
  const isCurrent = (state) => routes.get(state.route.runId) === state;
@@ -68866,32 +69139,31 @@ var init_workflow_route_owner = __esm(() => {
68866
69139
  });
68867
69140
 
68868
69141
  // dist/builtin/workflows/src/runs/foreground/sdk-intercom.ts
68869
- function indexRoots(runs) {
68870
- const runById = new Map(runs.map((run) => [run.id, run]));
68871
- const rootOf = new Map;
68872
- const deliverable = new Set;
68873
- for (const run of runs) {
68874
- const root = reciprocalWorkflowRootRunId(runById, run.id);
68875
- rootOf.set(run.id, root);
68876
- if (root !== undefined && run.stages.some((stage) => stage.pendingStageDeliveryAvailable === true))
68877
- deliverable.add(root);
68878
- }
68879
- return { rootOf, deliverable };
68880
- }
68881
69142
  function createStandaloneRouteOwnership(store, roots) {
68882
69143
  const activated = new Set;
68883
- let index;
69144
+ const runs = runsByIdOf(store);
69145
+ const rootOf = new Map;
69146
+ const deliverable = new Map;
68884
69147
  const dispose = store.subscribeInvalidation(() => {
68885
- index = undefined;
69148
+ rootOf.clear();
69149
+ deliverable.clear();
68886
69150
  });
68887
69151
  return {
68888
69152
  owns: (runId) => {
68889
- index ??= indexRoots(store.runs());
68890
- const root = index.rootOf.get(runId) ?? runId;
69153
+ if (!rootOf.has(runId))
69154
+ rootOf.set(runId, reciprocalWorkflowRootRunId(runs, runId));
69155
+ const root = rootOf.get(runId) ?? runId;
68891
69156
  if (!roots.has(root))
68892
69157
  return false;
68893
- if (!activated.has(root) && index.deliverable.has(root))
68894
- activated.add(root);
69158
+ if (!activated.has(root)) {
69159
+ let canDeliver = deliverable.get(root);
69160
+ if (canDeliver === undefined) {
69161
+ canDeliver = invocationRunsInSource(store, root).some((run) => run.stages.some((stage) => stage.pendingStageDeliveryAvailable === true));
69162
+ deliverable.set(root, canDeliver);
69163
+ }
69164
+ if (canDeliver)
69165
+ activated.add(root);
69166
+ }
68895
69167
  return activated.has(root);
68896
69168
  },
68897
69169
  dispose
@@ -69332,7 +69604,7 @@ var init_startup_timeout = () => {};
69332
69604
 
69333
69605
  // dist/builtin/workflows/src/workers/pool-coordinator.ts
69334
69606
  import { fork } from "node:child_process";
69335
- import { randomUUID as randomUUID17 } from "node:crypto";
69607
+ import { randomUUID as randomUUID18 } from "node:crypto";
69336
69608
  import { createWriteStream } from "node:fs";
69337
69609
  import { appendFile, mkdir as mkdir6, rm as rm3, rmdir } from "node:fs/promises";
69338
69610
  import { dirname as dirname16, join as join32, resolve as resolve15 } from "node:path";
@@ -69503,7 +69775,7 @@ class PooledRoutes {
69503
69775
  this.mirror.batch(() => {
69504
69776
  for (const id of attempt.runs) {
69505
69777
  rotateWorkflowPendingStageRouteCapability(this.mirror, id);
69506
- const run = this.mirror.runs().find((candidate) => candidate.id === id);
69778
+ const run = this.mirror.run(id);
69507
69779
  if (run?.stages.some(isLiveStage) !== true)
69508
69780
  continue;
69509
69781
  this.mirror.recordRunStart({
@@ -69893,7 +70165,7 @@ class PoolCoordinator {
69893
70165
  throw new Error("Worker exited before delivery acknowledgement");
69894
70166
  const { slot, workerRequest } = target;
69895
70167
  await new Promise((resolve, reject) => {
69896
- const id = randomUUID17();
70168
+ const id = randomUUID18();
69897
70169
  slot.deliveries.set(id, { resolve, reject });
69898
70170
  slot.child.send({ id: workerRequest, delivery: { id, from: payload.from, message: payload.message } }, (error) => {
69899
70171
  if (error) {
@@ -70274,7 +70546,7 @@ class PoolCoordinator {
70274
70546
  this.children.add(child);
70275
70547
  if (child.pid !== undefined)
70276
70548
  this.port.send({ kind: "spawned", pid: child.pid });
70277
- const worker = randomUUID17();
70549
+ const worker = randomUUID18();
70278
70550
  this.incarnations.set(worker, child);
70279
70551
  const slot = { worker, child, deliveries: new Map, runs: new Set, stageCommands: new Map };
70280
70552
  this.slots.add(slot);
@@ -70848,6 +71120,41 @@ var init_pool_coordinator = __esm(() => {
70848
71120
  STAGE_WATCH_BACKLOG_BYTES = 8 * 1024 * 1024;
70849
71121
  });
70850
71122
 
71123
+ // dist/builtin/workflows/src/workers/pooled-run-end.ts
71124
+ function endPooledRun(store, run, error) {
71125
+ const now = Date.now();
71126
+ for (const stage of run.stages)
71127
+ if (!isTerminalStageStatus(stage.status))
71128
+ store.recordStageEnd(run.id, {
71129
+ ...stage,
71130
+ status: "failed",
71131
+ endedAt: now,
71132
+ durationMs: stage.startedAt === undefined ? undefined : Math.max(0, now - stage.startedAt),
71133
+ error
71134
+ });
71135
+ store.recordRunEnd(run.id, "failed", undefined, error);
71136
+ }
71137
+ function endPooledChild(store, childRunId, error) {
71138
+ const child = store.run(childRunId);
71139
+ if (child === undefined)
71140
+ return;
71141
+ const subtree = [child];
71142
+ const seen = new Set([child.id]);
71143
+ for (let index = 0;index < subtree.length; index++)
71144
+ for (const nested of store.childRuns(subtree[index].id))
71145
+ if (!seen.has(nested.id)) {
71146
+ seen.add(nested.id);
71147
+ subtree.push(nested);
71148
+ }
71149
+ 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);
71150
+ for (const { run } of unfinished)
71151
+ if (run.endedAt === undefined)
71152
+ endPooledRun(store, run, error);
71153
+ }
71154
+ var init_pooled_run_end = __esm(() => {
71155
+ init_store_internal();
71156
+ });
71157
+
70851
71158
  // dist/builtin/workflows/src/workers/protocol.ts
70852
71159
  var WORKER_HEARTBEAT_INTERVAL_MS = 1000;
70853
71160
 
@@ -71008,7 +71315,7 @@ function createWorkflowPendingStageDelivery(activeStore, runId, stageId, stageNa
71008
71315
  if (sessionId !== undefined && activeStore.pendingStageMessagesFor(runId, stageId).length === 0 && activeStore.pendingStageMessagesFor(runId, stageName).length === 0) {
71009
71316
  const entries = stickyPendingStageEntriesForStage(activeStore, runId, stageId, stageName, { sessionId });
71010
71317
  Promise.all(entries.map(async (entry) => {
71011
- const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, entry.runId), activeStore.runs(), entry.runId);
71318
+ const backend = durableBackendForRun(requireStoreDurableBackend(activeStore, entry.runId), activeStore, entry.runId);
71012
71319
  return await backend?.hasPendingStageDeliveryReceipt?.(entry.runId, entry.id, {
71013
71320
  runId,
71014
71321
  stageId,
@@ -71055,13 +71362,12 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
71055
71362
  ...activeStore.pendingStageMessagesFor(runId, stageName),
71056
71363
  ...stickyEntries
71057
71364
  ].map((entry) => entry.id));
71058
- const runs = activeStore.runs();
71059
71365
  const entries = [
71060
- ...(runs.find((run) => run.id === runId)?.pendingStageMessages ?? []).map((entry, index) => ({ entry, index })).filter(({ entry }) => candidateIds.has(entry.id) && entry.sticky !== true),
71366
+ ...(activeStore.run(runId)?.pendingStageMessages ?? []).map((entry, index) => ({ entry, index })).filter(({ entry }) => candidateIds.has(entry.id) && entry.sticky !== true),
71061
71367
  ...stickyEntries.map((entry) => ({ entry, index: Number.MAX_SAFE_INTEGER }))
71062
71368
  ].map(({ entry, index }) => ({ entry, index, order: pendingStageMessageAdmissionOrder(entry) })).sort((left, right) => left.order - right.order || left.index - right.index).map(({ entry }) => entry);
71063
71369
  const rootBackend = requireStoreDurableBackend(activeStore, runId);
71064
- const backend = durableBackendForRun(rootBackend, runs, runId);
71370
+ const backend = durableBackendForRun(rootBackend, activeStore, runId);
71065
71371
  if (backend === undefined) {
71066
71372
  throw new Error(`atomic-workflows: workflow run ${runId} has no durable owner for pending-stage delivery`);
71067
71373
  }
@@ -71076,9 +71382,9 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
71076
71382
  stageId,
71077
71383
  ...recipient === undefined ? {} : { sessionId: recipient.sessionId, admission: "context" }
71078
71384
  };
71079
- 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;
71385
+ 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;
71080
71386
  if (entry.sticky === true && await hasStickyReceipt()) {
71081
- const entryBackend = durableBackendForRun(rootBackend, activeStore.runs(), entry.runId);
71387
+ const entryBackend = durableBackendForRun(rootBackend, activeStore, entry.runId);
71082
71388
  if (entryBackend !== undefined) {
71083
71389
  await commit(() => activeStore.recordPendingStageMessageDeliveries(entry.runId, entry.id, [], new Date().toISOString(), entryBackend));
71084
71390
  }
@@ -71087,7 +71393,7 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
71087
71393
  if (!recipient?.receivedMessageIds.includes(entry.message.id))
71088
71394
  await deliver(toPendingStageSender(entry), entry.message);
71089
71395
  if (entry.sticky === true) {
71090
- const entryBackend = durableBackendForRun(rootBackend, activeStore.runs(), entry.runId);
71396
+ const entryBackend = durableBackendForRun(rootBackend, activeStore, entry.runId);
71091
71397
  if (entryBackend === undefined) {
71092
71398
  throw new Error(`atomic-workflows: workflow run ${entry.runId} has no durable owner for sticky pending-stage delivery`);
71093
71399
  }
@@ -71106,18 +71412,17 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
71106
71412
  }
71107
71413
  }
71108
71414
  function stickyPendingStageEntriesForStage(activeStore, runId, stageId, stageName, recipient, receivedByEndedStage = []) {
71109
- const runs = activeStore.runs();
71110
- const rootRunId = durableRootRunIdForRun(runs, runId);
71415
+ const rootRunId = durableRootRunIdForRun(activeStore, runId);
71111
71416
  if (rootRunId === undefined)
71112
71417
  return [];
71113
- const rootRun = runs.find((run) => run.id === rootRunId);
71418
+ const rootRun = activeStore.run(rootRunId);
71114
71419
  if (rootRun === undefined)
71115
71420
  return [];
71116
- const stage = runs.find((run) => run.id === runId)?.stages.find((candidate) => candidate.id === stageId);
71421
+ const stage = activeStore.run(runId)?.stages.find((candidate) => candidate.id === stageId);
71117
71422
  const ended = stage?.status === "completed" || stage?.status === "skipped";
71118
71423
  if (ended && receivedByEndedStage.length === 0)
71119
71424
  return [];
71120
- const hops = workflowBoundaryHops(runs, runId);
71425
+ const hops = workflowBoundaryHops(activeStore, runId);
71121
71426
  if (hops === undefined)
71122
71427
  return [];
71123
71428
  return (rootRun.pendingStageMessages ?? []).filter((entry) => {
@@ -71304,7 +71609,7 @@ class PoolStageHandoff {
71304
71609
  if (result === undefined)
71305
71610
  return;
71306
71611
  const terminals = new Map;
71307
- const nested = this.store.runs().some((run) => run.endedAt === undefined && run.id !== work.childRunId && this.owners.get(run.id) === work.id);
71612
+ const nested = this.ownedRunIds(work).some((id) => id !== work.childRunId && this.unended(id) !== undefined);
71308
71613
  for (const checkpoint of nested ? this.backend.listCheckpoints(root) : []) {
71309
71614
  const boundary = checkpoint.kind === "stage" ? checkpoint.topology?.boundary : undefined;
71310
71615
  if (checkpoint.kind !== "stage" || boundary?.event !== "terminal")
@@ -71316,8 +71621,9 @@ class PoolStageHandoff {
71316
71621
  this.store.batch(() => this.settle(work, result, terminals));
71317
71622
  }
71318
71623
  settle(work, result, terminals) {
71319
- for (const run of this.store.runs()) {
71320
- if (run.endedAt !== undefined || this.owners.get(run.id) !== work.id)
71624
+ for (const id of this.ownedRunIds(work)) {
71625
+ const run = this.unended(id);
71626
+ if (run === undefined)
71321
71627
  continue;
71322
71628
  if (run.id === work.childRunId) {
71323
71629
  const executions = new Map(run.stages.map((stage) => [stage.id, stage.workerExecution]));
@@ -71338,6 +71644,19 @@ class PoolStageHandoff {
71338
71644
  this.store.recordRunEnd(run.id, terminal.status, terminal.outputs);
71339
71645
  }
71340
71646
  }
71647
+ ownedRunIds(work) {
71648
+ const held = [];
71649
+ for (const id of this.attempts.get(work.id)?.runs ?? []) {
71650
+ const position = this.store.runPosition(id);
71651
+ if (position !== undefined)
71652
+ held.push({ id, position });
71653
+ }
71654
+ return held.sort((left, right) => left.position - right.position).map(({ id }) => id);
71655
+ }
71656
+ unended(runId) {
71657
+ const run = this.store.run(runId);
71658
+ return run?.endedAt === undefined ? run : undefined;
71659
+ }
71341
71660
  fence(work) {
71342
71661
  const current = this.attempts.get(work.id);
71343
71662
  if (current !== undefined && current.generation > work.generation)
@@ -71738,7 +72057,7 @@ var init_pooled_stage_task_source = __esm(() => {
71738
72057
  });
71739
72058
 
71740
72059
  // dist/builtin/workflows/src/workers/pooled-stage-handle.ts
71741
- import { randomUUID as randomUUID18 } from "node:crypto";
72060
+ import { randomUUID as randomUUID19 } from "node:crypto";
71742
72061
 
71743
72062
  class PooledStageHandle {
71744
72063
  runId;
@@ -71847,7 +72166,7 @@ class PooledStageHandle {
71847
72166
  return this.bashRuns.size > 0;
71848
72167
  }
71849
72168
  async executeBash(command, onChunk, options) {
71850
- const id = randomUUID18();
72169
+ const id = randomUUID19();
71851
72170
  this.bashRuns.set(id, onChunk);
71852
72171
  try {
71853
72172
  const result = await this.sessionCommand({
@@ -72119,7 +72438,7 @@ class PooledStageHandle {
72119
72438
  return Promise.reject(new PooledStageDeliveryError("StageNotLive", this.stageName));
72120
72439
  const outcome = Promise.withResolvers();
72121
72440
  const entry = {
72122
- op: randomUUID18(),
72441
+ op: randomUUID19(),
72123
72442
  text,
72124
72443
  intent,
72125
72444
  ...options === undefined ? {} : { options },
@@ -72612,7 +72931,7 @@ var init_pooled_stage_registry = __esm(() => {
72612
72931
 
72613
72932
  // dist/builtin/workflows/src/workers/local-pool.ts
72614
72933
  import { fork as fork2 } from "node:child_process";
72615
- import { randomUUID as randomUUID19 } from "node:crypto";
72934
+ import { randomUUID as randomUUID20 } from "node:crypto";
72616
72935
  import { resolve as resolve16 } from "node:path";
72617
72936
  import { setTimeout as delay3 } from "node:timers/promises";
72618
72937
  import { fileURLToPath as fileURLToPath6 } from "node:url";
@@ -72942,7 +73261,7 @@ class LocalWorkerPool {
72942
73261
  return { ok: false, refusal: "PoolClosed" };
72943
73262
  if (this.coordinator === undefined)
72944
73263
  return { ok: false, refusal: "StageNotOnWorker" };
72945
- const watch = randomUUID19();
73264
+ const watch = randomUUID20();
72946
73265
  this.stageWatches.set(watch, listener);
72947
73266
  try {
72948
73267
  const result = await this.command({ kind: "stage-watch", watch, ...ref });
@@ -73505,21 +73824,7 @@ class LocalWorkerPool {
73505
73824
  endFailedChild(work, error) {
73506
73825
  const store = this.store;
73507
73826
  if (store !== undefined)
73508
- store.batch(() => {
73509
- const runs = store.runs();
73510
- const byId = new Map(runs.map((run) => [run.id, run]));
73511
- const inChild = (run) => {
73512
- for (let current = run;current !== undefined; ) {
73513
- if (current.id === work.childRunId)
73514
- return true;
73515
- current = current.parentRunId === undefined ? undefined : byId.get(current.parentRunId);
73516
- }
73517
- return false;
73518
- };
73519
- for (const run of runs)
73520
- if (run.endedAt === undefined && inChild(run))
73521
- endPooledRun(store, run, error.message);
73522
- });
73827
+ store.batch(() => endPooledChild(store, work.childRunId, error.message));
73523
73828
  if (this.reconnectingViews.size > 0 || this.outboxes.size > 0)
73524
73829
  this.reconnectStageViews();
73525
73830
  }
@@ -73832,19 +74137,6 @@ class LocalWorkerPool {
73832
74137
  throw failure;
73833
74138
  }
73834
74139
  }
73835
- function endPooledRun(store, run, error) {
73836
- const now = Date.now();
73837
- for (const stage of run.stages)
73838
- if (!isTerminalStageStatus(stage.status))
73839
- store.recordStageEnd(run.id, {
73840
- ...stage,
73841
- status: "failed",
73842
- endedAt: now,
73843
- durationMs: stage.startedAt === undefined ? undefined : Math.max(0, now - stage.startedAt),
73844
- error
73845
- });
73846
- store.recordRunEnd(run.id, "failed", undefined, error);
73847
- }
73848
74140
  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;
73849
74141
  var init_local_pool = __esm(() => {
73850
74142
  init_internal();
@@ -73856,7 +74148,6 @@ var init_local_pool = __esm(() => {
73856
74148
  init_sdk_intercom();
73857
74149
  init_external_run_routes();
73858
74150
  init_stage_question_form();
73859
- init_store_internal();
73860
74151
  init_workflow_infrastructure_error();
73861
74152
  init_admission_binding();
73862
74153
  init_definitions();
@@ -73865,6 +74156,7 @@ var init_local_pool = __esm(() => {
73865
74156
  init_host_options();
73866
74157
  init_pool_coordinator();
73867
74158
  init_pool_journal();
74159
+ init_pooled_run_end();
73868
74160
  init_pooled_stage_sources();
73869
74161
  init_pooled_watch_trace();
73870
74162
  init_stage_handoff();
@@ -74522,7 +74814,7 @@ var init_run_budget = __esm(() => {
74522
74814
  });
74523
74815
 
74524
74816
  // dist/builtin/workflows/src/engine/primitives/parallel.ts
74525
- import { randomUUID as randomUUID20 } from "node:crypto";
74817
+ import { randomUUID as randomUUID21 } from "node:crypto";
74526
74818
  function createParallelPrimitive(input) {
74527
74819
  return async (steps, options = {}) => {
74528
74820
  input.runtime.exit.throwIfWorkflowExitSelected();
@@ -74530,7 +74822,7 @@ function createParallelPrimitive(input) {
74530
74822
  const normalizedOptions = normalizeGroup(options);
74531
74823
  const normalizedSteps = steps.map(normalizeGroup);
74532
74824
  const needsAutoGroup = normalizedOptions.group === true || normalizedSteps.some((step) => step.group === true);
74533
- const autoGroup = needsAutoGroup ? randomUUID20() : undefined;
74825
+ const autoGroup = needsAutoGroup ? randomUUID21() : undefined;
74534
74826
  const resolveAutoGroup = (value2) => value2.group === true && autoGroup ? { ...value2, group: autoGroup } : value2;
74535
74827
  const resolvedOptions = resolveAutoGroup(normalizedOptions);
74536
74828
  const resolvedSteps = normalizedSteps.map(resolveAutoGroup);
@@ -74542,9 +74834,9 @@ function createParallelPrimitive(input) {
74542
74834
  activeStages: new Map,
74543
74835
  parentIds: parallelParentIds
74544
74836
  };
74545
- const stageIdsBeforeParallel = new Set(input.runtime.activeStore.runs().find((run) => run.id === input.runtime.runId)?.stages.map((stage) => stage.id) ?? []);
74837
+ const stageIdsBeforeParallel = new Set(input.runtime.activeStore.run(input.runtime.runId)?.stages.map((stage) => stage.id) ?? []);
74546
74838
  const everyStepCompleted = () => {
74547
- const run = input.runtime.activeStore.runs().find((candidate) => candidate.id === input.runtime.runId);
74839
+ const run = input.runtime.activeStore.run(input.runtime.runId);
74548
74840
  if (run === undefined)
74549
74841
  return false;
74550
74842
  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]));
@@ -75411,9 +75703,9 @@ function createDurableCachedStageRecorder(input) {
75411
75703
  return {
75412
75704
  record(name, replayKey, checkpoint, scope) {
75413
75705
  const cachedChildRunId = workflowChildRunId(checkpoint);
75414
- const runById = new Map(input.store.runs().map((run) => [run.id, run]));
75415
- if (!runById.has(input.run.id))
75416
- runById.set(input.run.id, input.run);
75706
+ const runById = {
75707
+ get: (runId) => input.store.run(runId) ?? (runId === input.run.id ? input.run : undefined)
75708
+ };
75417
75709
  const durableRootId = reciprocalWorkflowRootRunId(runById, input.run.id);
75418
75710
  const cachedDescendants = cachedChildRunId === undefined || durableRootId === undefined ? undefined : durableCompletedNestedRunSubtree(input.rootBackend, durableRootId, cachedChildRunId);
75419
75711
  if (cachedChildRunId !== undefined && durableRootId !== undefined && cachedDescendants === undefined) {
@@ -75427,7 +75719,7 @@ function createDurableCachedStageRecorder(input) {
75427
75719
  replaySourceOrders.set(replayedStage.id, sourceOrder);
75428
75720
  input.run.stages.sort((left, right) => (replaySourceOrders.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (replaySourceOrders.get(right.id) ?? Number.MAX_SAFE_INTEGER));
75429
75721
  }
75430
- const stage = input.store.runs().find((run) => run.id === input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
75722
+ const stage = input.store.run(input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
75431
75723
  const persistence = stage === undefined ? undefined : input.backend.commitCheckpoint({
75432
75724
  kind: "stage",
75433
75725
  workflowId: input.run.id,
@@ -75438,7 +75730,7 @@ function createDurableCachedStageRecorder(input) {
75438
75730
  ...durableStageCheckpointMetadata(stage, durableRunTopology(input.run), sourceOrder ?? input.run.stages.findIndex((candidate) => candidate.id === stage.id))
75439
75731
  });
75440
75732
  for (const childRun of cachedDescendants ?? []) {
75441
- const existingRun = input.store.runs().find((candidate) => candidate.id === childRun.id);
75733
+ const existingRun = input.store.run(childRun.id);
75442
75734
  const isDirectChild = childRun.id === cachedChildRunId && childRun.parentRunId === input.run.id && stage?.workflowChild?.runId === cachedChildRunId;
75443
75735
  if (existingRun !== undefined) {
75444
75736
  if (stage !== undefined && isDirectChild) {
@@ -75464,15 +75756,15 @@ function createDurableCachedStageRecorder(input) {
75464
75756
  };
75465
75757
  }
75466
75758
  function reconcileCachedDirectChildParentStage(input) {
75467
- const existingRun = input.store.runs().find((run) => run.id === input.checkpointChildRunId);
75759
+ const existingRun = input.store.run(input.checkpointChildRunId);
75468
75760
  if (existingRun === undefined)
75469
75761
  return false;
75470
- const runById = new Map(input.store.runs().map((run) => [run.id, run]));
75471
- const storedParentRun = runById.get(input.parentRun.id);
75762
+ const storedParentRun = input.store.run(input.parentRun.id);
75472
75763
  if (storedParentRun !== undefined && (storedParentRun.parentRunId !== input.parentRun.parentRunId || storedParentRun.parentStageId !== input.parentRun.parentStageId))
75473
75764
  return false;
75474
- if (storedParentRun === undefined)
75475
- runById.set(input.parentRun.id, input.parentRun);
75765
+ const runById = {
75766
+ get: (runId) => input.store.run(runId) ?? (runId === input.parentRun.id ? input.parentRun : undefined)
75767
+ };
75476
75768
  const expectedRootRunId = reciprocalWorkflowRootRunId(runById, input.parentRun.id);
75477
75769
  if (expectedRootRunId === undefined)
75478
75770
  return false;
@@ -75849,7 +76141,7 @@ function createAdmittedToolExecutionTracker(options = {}) {
75849
76141
  // dist/builtin/workflows/src/engine/run-tool-node-lifecycle.ts
75850
76142
  function createToolNodeLifecycle(input) {
75851
76143
  const { store, tracker, run, sourceToContinuationNodeIds } = input;
75852
- const ownsCurrentRun = () => store.runs().some((candidate) => candidate === run);
76144
+ const ownsCurrentRun = () => store.run(run.id) === run;
75853
76145
  const replayedToolNodeIds = new Set;
75854
76146
  let pendingFrontier = input.resumeToolNode;
75855
76147
  const pendingRetries = new Map((input.retryToolNodes ?? []).map((node) => [node.id, node]));
@@ -75922,7 +76214,7 @@ function sameToolIdentity(node, expected) {
75922
76214
  function isReplayedContinuationNode(store, run, replayedToolNodeIds, nodeId) {
75923
76215
  if (replayedToolNodeIds.has(nodeId))
75924
76216
  return true;
75925
- const live = store.runs().find((candidate) => candidate === run);
76217
+ const live = store.run(run.id) === run ? run : undefined;
75926
76218
  return live?.stages.some((stage) => stage.id === nodeId && stage.replayed === true) === true;
75927
76219
  }
75928
76220
  function compatibleReplayedToolParents(tracker, translated, inferredParents, isReplayedNode) {
@@ -76292,7 +76584,7 @@ function createQueuedUserMessageConsumptionWatcher(armContinuation) {
76292
76584
  // dist/builtin/workflows/src/runs/foreground/blocked-stage-close.ts
76293
76585
  function closeBlockedStageForGoodWhenRunEnds(store, runId, close) {
76294
76586
  const unsubscribe = store.subscribe(() => {
76295
- const run = store.runs().find((candidate) => candidate.id === runId);
76587
+ const run = store.run(runId);
76296
76588
  if (run && (!isTerminalRunStatus(run.status) || run.resumable === true))
76297
76589
  return;
76298
76590
  unsubscribe();
@@ -76598,7 +76890,7 @@ function createTrackedStageCaller(input) {
76598
76890
  const budgetError = err instanceof WorkflowBudgetExceededError ? err : undefined;
76599
76891
  if (budgetError !== undefined && trackStageLifecycle && !runtime.state.skippedForParallelFailFast) {
76600
76892
  let selectedBudgetError = budgetError;
76601
- if (runtime.activeStore.runs().find((run) => run.id === runtime.runId)?.budgetState?.wrapUpCompleted !== true) {
76893
+ if (runtime.activeStore.run(runtime.runId)?.budgetState?.wrapUpCompleted !== true) {
76602
76894
  try {
76603
76895
  await runtime.budget.deliverWrapUp(runtime.name);
76604
76896
  } catch (wrapUpError) {
@@ -77045,7 +77337,7 @@ function createStageControlHandle(runtime) {
77045
77337
  runtime.scheduler.ensureReleaseBarrier(runtime.stageId);
77046
77338
  runtime.state.readinessController?.abort(new Error("atomic-workflows: readiness paused"));
77047
77339
  await runtime.scheduler.cascadePauseFrom(runtime.stageId);
77048
- const run = runtime.activeStore.runs().find((candidate) => candidate.id === runtime.runId);
77340
+ const run = runtime.activeStore.run(runtime.runId);
77049
77341
  const stillActive = run?.stages.some((stage) => stage.status === "running" && stage.id !== runtime.stageId) ?? false;
77050
77342
  if (!stillActive)
77051
77343
  runtime.activeStore.recordRunPaused(runtime.runId);
@@ -81033,7 +81325,7 @@ function createWorkflowStageFactory(input) {
81033
81325
  defaultSessionDir: input.opts.defaultSessionDir,
81034
81326
  defaultCwd: input.workflowInvocationCwd,
81035
81327
  onStartupChange(startup) {
81036
- const current = input.activeStore.runs().find((run) => run.id === input.runId);
81328
+ const current = input.activeStore.run(input.runId);
81037
81329
  if (!current?.stages.includes(stageSnapshot))
81038
81330
  return;
81039
81331
  stageSnapshot.startup = startup;
@@ -81522,7 +81814,7 @@ async function run(def, inputs, opts = {}) {
81522
81814
  const resolvedInputs = resolveAndValidateInputs(def.inputs, inputs, `workflow "${def.name}"`);
81523
81815
  const runId = opts.runId ?? crypto.randomUUID();
81524
81816
  const activeStore = opts.store ?? store;
81525
- const preset = opts.durableBackend ?? (opts.journal === undefined ? availableRunDurableBackend(activeStore.runs(), opts.continuation?.source.id ?? runId) ?? availableStoreDurableBackendOverride(activeStore) : undefined);
81817
+ const preset = opts.durableBackend ?? (opts.journal === undefined ? availableRunDurableBackend(activeStore, opts.continuation?.source.id ?? runId) ?? availableStoreDurableBackendOverride(activeStore) : undefined);
81526
81818
  const backend = preset ?? await initializeDurableBackend({ journal: opts.journal, cwd: opts.cwd });
81527
81819
  const publicResources = opts.parentRun === undefined && (opts.localWorkers || opts.admission || backend.getWorkflow(opts.continuation?.source.id ?? runId)?.resources);
81528
81820
  if (publicResources)
@@ -81558,7 +81850,7 @@ async function executeRun(def, resolvedInputs, opts) {
81558
81850
  }
81559
81851
  const declaresBudget = (budget) => (budget?.maxDurationMs ?? 0) > 0 || (budget?.maxTokens ?? 0) > 0 || (budget?.maxCost ?? 0) > 0;
81560
81852
  const hasBudgetDeclaration = declaresBudget(opts.budget) || declaresBudget(def.budget) || declaresBudget(opts.config?.budget);
81561
- const priorRun = hasBudgetDeclaration && opts.rootBudget === undefined && opts.continuation === undefined && opts.runId !== undefined ? activeStore.runs().find((candidate) => candidate.id === runId) : undefined;
81853
+ const priorRun = hasBudgetDeclaration && opts.rootBudget === undefined && opts.continuation === undefined && opts.runId !== undefined ? activeStore.run(runId) : undefined;
81562
81854
  const continuedBudget = opts.continuation?.source.budget ?? priorRun?.budget;
81563
81855
  const runBudget = opts.budget === undefined ? continuedBudget : { ...continuedBudget ?? {}, ...opts.budget };
81564
81856
  const resolvedBudget = resolve_budget({ config: opts.config?.budget, definition: def.budget, run: runBudget });
@@ -81633,17 +81925,8 @@ async function executeRun(def, resolvedInputs, opts) {
81633
81925
  if (opts.parentRun === undefined)
81634
81926
  bindRunDurableBackend(runSnapshot, rootBackend);
81635
81927
  const usageTree = () => {
81636
- const snapshots = activeStore.runs();
81637
- const childrenByParent = new Map;
81638
- for (const snapshot of snapshots) {
81639
- if (snapshot.parentRunId === undefined)
81640
- continue;
81641
- const children = childrenByParent.get(snapshot.parentRunId) ?? [];
81642
- children.push(snapshot);
81643
- childrenByParent.set(snapshot.parentRunId, children);
81644
- }
81645
81928
  const build = (run) => {
81646
- const children = (childrenByParent.get(run.id) ?? []).map(build);
81929
+ const children = activeStore.childRuns(run.id).map(build);
81647
81930
  return children.length === 0 ? { run } : { run, children };
81648
81931
  };
81649
81932
  return build(runSnapshot);
@@ -82026,7 +82309,7 @@ async function executeRun(def, resolvedInputs, opts) {
82026
82309
  return recorded;
82027
82310
  };
82028
82311
  const durableIntercomGroup = (replayKey, stageId) => {
82029
- const stages = activeStore.runs().find((candidate) => candidate.id === runId)?.stages ?? [];
82312
+ const stages = activeStore.run(runId)?.stages ?? [];
82030
82313
  return stages.find((stage) => stageId !== undefined && stage.id === stageId || stage.replayKey === replayKey)?.intercomGroup;
82031
82314
  };
82032
82315
  let observedTaskTailQuit;
@@ -82079,7 +82362,7 @@ async function executeRun(def, resolvedInputs, opts) {
82079
82362
  recordCachedStage,
82080
82363
  stage: (name, options, replayKey) => {
82081
82364
  const stage = runtime.stage(name, options);
82082
- const stageId = activeStore.runs().find((r) => r.id === runId)?.stages.at(-1)?.id;
82365
+ const stageId = activeStore.run(runId)?.stages.at(-1)?.id;
82083
82366
  if (stageId !== undefined)
82084
82367
  completedStageReplayKeys.set(stageId, replayKey);
82085
82368
  return stage;
@@ -82601,18 +82884,18 @@ var init_executor = __esm(() => {
82601
82884
  });
82602
82885
 
82603
82886
  // dist/builtin/workflows/src/runs/foreground/sdk-run.ts
82604
- import { randomUUID as randomUUID21 } from "node:crypto";
82887
+ import { randomUUID as randomUUID22 } from "node:crypto";
82605
82888
  async function run2(def, inputs, callerOpts = {}) {
82606
82889
  let opts = callerOpts;
82607
82890
  const store2 = opts.store === undefined || opts.store === store ? currentWorkflowStore() : opts.store;
82608
82891
  const sourceRunId = opts.continuation?.source.id ?? opts.runId;
82609
- const ownedBackend = sourceRunId === undefined ? undefined : availableRunDurableBackend(store2.runs(), sourceRunId);
82892
+ const ownedBackend = sourceRunId === undefined ? undefined : availableRunDurableBackend(store2, sourceRunId);
82610
82893
  const preset = opts.journal === undefined ? opts.durableBackend ?? ownedBackend ?? availableStoreDurableBackendOverride(store2) : undefined;
82611
82894
  const backend = preset ?? await initializeDurableBackend({ journal: opts.journal, cwd: opts.cwd });
82612
82895
  if (opts.journal === undefined && opts.durableBackend === undefined && ownedBackend === undefined) {
82613
82896
  bindStoreDurableBackend(store2, backend);
82614
82897
  }
82615
- const runId = opts.runId ?? randomUUID21();
82898
+ const runId = opts.runId ?? randomUUID22();
82616
82899
  if (sourceRunId !== undefined || opts.localWorkers || opts.admission) {
82617
82900
  opts = await restoreWorkerOptions(backend, { ...opts, runId });
82618
82901
  }
@@ -82783,7 +83066,7 @@ var init_workflows_host_module = __esm(() => {
82783
83066
  });
82784
83067
 
82785
83068
  // dist/builtin/workflows/src/workers/pool-journal.ts
82786
- import { createHash as createHash6, randomUUID as randomUUID22 } from "node:crypto";
83069
+ import { createHash as createHash6, randomUUID as randomUUID23 } from "node:crypto";
82787
83070
  import { existsSync as existsSync9, mkdirSync as mkdirSync10, readFileSync as readFileSync9, writeFileSync as writeFileSync7 } from "node:fs";
82788
83071
  import { basename as basename6, dirname as dirname18, join as join34, resolve as resolve19 } from "node:path";
82789
83072
  import { storageSelectionKey as storageSelectionKey2 } from "@bastani/atomic/storage";
@@ -82880,7 +83163,7 @@ function poolHostId(agentDir) {
82880
83163
  return existing;
82881
83164
  } catch {}
82882
83165
  mkdirSync10(dirname18(file), { recursive: true });
82883
- const id = randomUUID22();
83166
+ const id = randomUUID23();
82884
83167
  try {
82885
83168
  writeFileSync7(file, `${id}
82886
83169
  `, { flag: "wx" });
@@ -83408,7 +83691,7 @@ function runDetached(def, inputs, opts = {}) {
83408
83691
  let backgroundPromise;
83409
83692
  try {
83410
83693
  backgroundPromise = (async () => {
83411
- const preset = opts.durableBackend ?? (opts.journal === undefined ? availableRunDurableBackend(store2.runs(), opts.continuation?.source.id ?? runId) ?? availableStoreDurableBackendOverride(store2) : undefined);
83694
+ const preset = opts.durableBackend ?? (opts.journal === undefined ? availableRunDurableBackend(store2, opts.continuation?.source.id ?? runId) ?? availableStoreDurableBackendOverride(store2) : undefined);
83412
83695
  const backend = preset ?? await initializeDurableBackend({ journal: opts.journal, cwd: opts.cwd });
83413
83696
  if (opts.parentRun === undefined && opts.journal === undefined && opts.durableBackend === undefined) {
83414
83697
  bindStoreDurableBackend(store2, backend);
@@ -83503,19 +83786,19 @@ var init_startup_admission = __esm(() => {
83503
83786
  });
83504
83787
 
83505
83788
  // dist/builtin/workflows/src/durable/fork-workflow.ts
83506
- import { randomUUID as randomUUID23 } from "node:crypto";
83789
+ import { randomUUID as randomUUID24 } from "node:crypto";
83507
83790
  async function forkDurableWorkflow(backend, source, cwd, modelOwner, sessionStore) {
83508
83791
  source = structuredClone(source);
83509
83792
  const sourceStore = await stageSessionStore({ cwd: source.workflowCwd ?? source.invocationCwd ?? cwd });
83510
83793
  let destinationStore;
83511
83794
  try {
83512
83795
  destinationStore = sessionStore ?? await stageSessionStore({ cwd });
83513
- const workflowId = randomUUID23();
83796
+ const workflowId = randomUUID24();
83514
83797
  const ids = new Map([[source.workflowId, workflowId]]);
83515
83798
  const mapId = (id) => {
83516
83799
  let mapped = ids.get(id);
83517
83800
  if (mapped === undefined) {
83518
- mapped = randomUUID23();
83801
+ mapped = randomUUID24();
83519
83802
  ids.set(id, mapped);
83520
83803
  }
83521
83804
  return mapped;
@@ -83697,8 +83980,11 @@ function canonicalDirectory(path) {
83697
83980
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
83698
83981
  }
83699
83982
  }
83983
+ function isProjectRootRun(handle, cwd, canonicalize = canonicalDirectory) {
83984
+ return cwd !== undefined && handle.invocationCwd !== undefined && (handle.rootWorkflowId === undefined || handle.rootWorkflowId === handle.workflowId) && canonicalize(cwd) === canonicalize(handle.invocationCwd);
83985
+ }
83700
83986
  function isSdkDurableRunInScope(handle, cwd, canonicalize = canonicalDirectory) {
83701
- return cwd !== undefined && handle.invocationCwd !== undefined && handle.modelOwner !== undefined && (handle.rootWorkflowId === undefined || handle.rootWorkflowId === handle.workflowId) && canonicalize(cwd) === canonicalize(handle.invocationCwd);
83987
+ return handle.modelOwner !== undefined && isProjectRootRun(handle, cwd, canonicalize);
83702
83988
  }
83703
83989
  async function isSdkCrashedRunAdoptable(handle, cwd, backend) {
83704
83990
  return isSdkDurableRunInScope(handle, cwd) && handle.status === "running" && await backend.workflowOwnership(handle.workflowId) === "available";
@@ -83787,7 +84073,7 @@ var init_tool_resume_frontier = __esm(() => {
83787
84073
  // dist/builtin/workflows/src/durable/resume-runtime.ts
83788
84074
  function resumeBackend(deps, workflowId) {
83789
84075
  const store = deps.baseRunOpts.store ?? currentWorkflowStore();
83790
- return (workflowId === undefined ? undefined : availableRunDurableBackend(store.runs(), workflowId)) ?? deps.durableBackend ?? requireStoreDurableBackend(store, workflowId);
84076
+ return (workflowId === undefined ? undefined : availableRunDurableBackend(store, workflowId)) ?? deps.durableBackend ?? requireStoreDurableBackend(store, workflowId);
83791
84077
  }
83792
84078
  function resolveDurableEntry(workflowId, catalog) {
83793
84079
  const resolution = resolveRunIdTarget(workflowId, catalog.map((entry) => entry.workflowId));
@@ -83982,7 +84268,7 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
83982
84268
  failureDisposition: handle.failureDisposition,
83983
84269
  failedToolNodeId: handle.failedToolNodeId
83984
84270
  };
83985
- const sourceSnapshot = toolContinuation?.source ?? deps.baseRunOpts.store?.runs().find((run) => run.id === resolved.workflowId);
84271
+ const sourceSnapshot = toolContinuation?.source ?? deps.baseRunOpts.store?.run(resolved.workflowId);
83986
84272
  let adoptedClaimUpdatedAt;
83987
84273
  const rollbackStartup = async (onRestored) => {
83988
84274
  if (adopting) {
@@ -84052,10 +84338,10 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
84052
84338
  onRawSettled: async (_ok, result, error) => {
84053
84339
  const message = result?.error ?? (error instanceof Error ? error.message : String(error));
84054
84340
  if (toolContinuation !== undefined && (message.includes("insufficient_state: replay topology mismatch") || message.includes("insufficient_state: replay topology ambiguous"))) {
84055
- const current = deps.baseRunOpts.store?.runs().find((run) => run.id === resolved.workflowId);
84341
+ const current = deps.baseRunOpts.store?.run(resolved.workflowId);
84056
84342
  if (current?.status === "failed" && current.error === message) {
84057
84343
  await backend.commitWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
84058
- if (deps.baseRunOpts.store?.runs().find((run) => run.id === resolved.workflowId) === current && current.status === "failed" && current.error === message) {
84344
+ if (deps.baseRunOpts.store?.run(resolved.workflowId) === current && current.status === "failed" && current.error === message) {
84059
84345
  deps.baseRunOpts.store.recordRunStart({ ...toolContinuation.source, error: message });
84060
84346
  }
84061
84347
  }
@@ -84077,7 +84363,7 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
84077
84363
  deps.onRunAccepted?.(accepted.runId);
84078
84364
  const admission = await launch.wait;
84079
84365
  if (!admission.started) {
84080
- const snapshot = deps.baseRunOpts.store?.runs().find((run) => run.id === accepted.runId);
84366
+ const snapshot = deps.baseRunOpts.store?.run(accepted.runId);
84081
84367
  const error = workflowStartupFailureMessage(admission, snapshot?.error, `Workflow ${resolved.workflowId} ended before startup admission`);
84082
84368
  if (!adopting && sourceSnapshot === undefined)
84083
84369
  deps.baseRunOpts.store?.removeRun(accepted.runId);
@@ -84109,7 +84395,8 @@ function foreignRunningResult(name, workflowId) {
84109
84395
  };
84110
84396
  }
84111
84397
  function alreadyRunningResult(name, workflowId, store) {
84112
- const here = store?.runs().some((r) => r.id === workflowId && r.endedAt === undefined) === true;
84398
+ const current = store?.run(workflowId);
84399
+ const here = current !== undefined && current.endedAt === undefined;
84113
84400
  return {
84114
84401
  ok: false,
84115
84402
  reason: "not_resumable",
@@ -84119,7 +84406,8 @@ function alreadyRunningResult(name, workflowId, store) {
84119
84406
  function hasActiveLiveRun(store, workflowId) {
84120
84407
  if (store === undefined)
84121
84408
  return false;
84122
- return store.runs().some((r) => r.id === workflowId && r.endedAt === undefined && r.exitReason !== "quit");
84409
+ const run = store.run(workflowId);
84410
+ return run !== undefined && run.endedAt === undefined && run.exitReason !== "quit";
84123
84411
  }
84124
84412
  function purgeSuppressedWorkflowRuns(backend, store, controls = currentToolControlRegistry()) {
84125
84413
  if (store === undefined)
@@ -96735,7 +97023,7 @@ function registerDormantRunIntercomRoutes(pi, activeStore, deps) {
96735
97023
  let disposed = false;
96736
97024
  let examined = Promise.resolve();
96737
97025
  let recheck;
96738
- const isLive = (runId) => activeStore.runs().some((run) => run.id === runId);
97026
+ const isLive = (runId) => activeStore.run(runId) !== undefined;
96739
97027
  const holdSubagents = (run, ctx) => {
96740
97028
  const stageSessionIds = run.stages.flatMap((stage) => {
96741
97029
  const sessionId = stage.sessionId ?? (stage.replayKey === undefined ? undefined : run.backend.getStageSession(run.runId, stage.replayKey)?.sessionId);
@@ -96867,7 +97155,7 @@ function registerDormantRunIntercomRoutes(pi, activeStore, deps) {
96867
97155
  for (const runId of [...subagentHolds.keys()]) {
96868
97156
  if (dormant.has(runId))
96869
97157
  continue;
96870
- const resumed = activeStore.runs().find((run) => run.id === runId);
97158
+ const resumed = activeStore.run(runId);
96871
97159
  if (resumed === undefined || isTerminalRunStatus(resumed.status))
96872
97160
  releaseSubagents(runId);
96873
97161
  }
@@ -97098,11 +97386,11 @@ function aggregateWorkflowRootRunId(store, runId) {
97098
97386
  return reciprocalWorkflowRootRunId(runById, runId) ?? runId;
97099
97387
  }
97100
97388
  function workflowHasPausedStages(store, runId) {
97101
- return expandedControlRunIds(store, runId).some((controlRunId) => store.runs().find((run) => run.id === controlRunId)?.stages.some((stage) => stage.status === "paused" || stage.status === "blocked") ?? false);
97389
+ return expandedControlRunIds(store, runId).some((controlRunId) => store.run(controlRunId)?.stages.some((stage) => stage.status === "paused" || stage.status === "blocked") ?? false);
97102
97390
  }
97103
97391
  function workflowHasPausedState(store, runId) {
97104
97392
  return expandedControlRunIds(store, runId).some((controlRunId) => {
97105
- const run = store.runs().find((candidate) => candidate.id === controlRunId);
97393
+ const run = store.run(controlRunId);
97106
97394
  return run?.status === "paused" || run?.stages.some((stage) => stage.status === "paused" || stage.status === "blocked") === true;
97107
97395
  });
97108
97396
  }
@@ -97131,7 +97419,7 @@ async function executeQuitRunWithAction(runId, opts, action, retire) {
97131
97419
  const activeStore = opts?.store ?? store;
97132
97420
  const registry = opts?.stageControlRegistry ?? stageControlRegistry;
97133
97421
  const toolControls = opts?.toolControlRegistry ?? toolControlRegistry;
97134
- const run = activeStore.runs().find((candidate) => candidate.id === runId);
97422
+ const run = activeStore.run(runId);
97135
97423
  if (!run)
97136
97424
  return { ok: false, runId, reason: "not_found" };
97137
97425
  if (run.endedAt !== undefined)
@@ -97170,11 +97458,11 @@ async function executeQuitRunWithAction(runId, opts, action, retire) {
97170
97458
  pauseFailures.push(`${target.controlRunId}/${target.handle.stageId}: ${message}`);
97171
97459
  return;
97172
97460
  }
97173
- const controlRun = activeStore.runs().find((candidate) => candidate.id === target.controlRunId);
97461
+ const controlRun = activeStore.run(target.controlRunId);
97174
97462
  if (controlRun?.endedAt !== undefined)
97175
97463
  return;
97176
97464
  activeStore.recordStagePaused(target.controlRunId, target.handle.stageId);
97177
- const stage = activeStore.runs().find((candidate) => candidate.id === target.controlRunId)?.stages.find((candidate) => candidate.id === target.handle.stageId);
97465
+ const stage = activeStore.run(target.controlRunId)?.stages.find((candidate) => candidate.id === target.handle.stageId);
97178
97466
  if (stage?.status === "paused") {
97179
97467
  pausedRunIds.add(target.controlRunId);
97180
97468
  paused.push(structuredClone(stage));
@@ -97205,7 +97493,7 @@ async function executeQuitRunWithAction(runId, opts, action, retire) {
97205
97493
  for (const handle of toolHandles)
97206
97494
  if (handle.runId !== runId)
97207
97495
  pausedRunIds.add(handle.runId);
97208
- const current = activeStore.runs().find((candidate) => candidate.id === runId);
97496
+ const current = activeStore.run(runId);
97209
97497
  if (current === undefined)
97210
97498
  return { ok: false, runId, reason: "not_found" };
97211
97499
  if (current.endedAt !== undefined && runtimeQuit === undefined)
@@ -97299,7 +97587,7 @@ async function abortInFlightTools(activeStore, toolHandles) {
97299
97587
  }
97300
97588
  function collectCancelledToolNodes(activeStore, toolHandles) {
97301
97589
  return toolHandles.flatMap((handle) => {
97302
- const node = activeStore.runs().find((candidate) => candidate.id === handle.runId)?.toolNodes.find((candidate) => candidate.id === handle.nodeId);
97590
+ const node = activeStore.run(handle.runId)?.toolNodes.find((candidate) => candidate.id === handle.nodeId);
97303
97591
  if (node === undefined || node.status !== "cancelled")
97304
97592
  return [];
97305
97593
  return [{ runId: handle.runId, nodeId: handle.nodeId, node: structuredClone(node) }];
@@ -97441,10 +97729,10 @@ async function markDurableResumed(runId, backend) {
97441
97729
 
97442
97730
  // dist/builtin/workflows/src/runs/background/resume-acknowledgements.ts
97443
97731
  function targetStage(store, target) {
97444
- return store.runs().find((run) => run.id === target.controlRunId)?.stages.find((stage) => stage.id === target.handle.stageId);
97732
+ return store.run(target.controlRunId)?.stages.find((stage) => stage.id === target.handle.stageId);
97445
97733
  }
97446
97734
  function targetIsActuallyPaused(store, target) {
97447
- const run = store.runs().find((candidate) => candidate.id === target.controlRunId);
97735
+ const run = store.run(target.controlRunId);
97448
97736
  const stage = targetStage(store, target);
97449
97737
  if (run?.endedAt !== undefined || stage?.endedAt !== undefined)
97450
97738
  return false;
@@ -97460,7 +97748,7 @@ async function settleResumeAcknowledgements(store, targets, message) {
97460
97748
  const resumedRunIds = new Set;
97461
97749
  settled.forEach((result, index) => {
97462
97750
  const target = attempted[index];
97463
- const controlRun = store.runs().find((candidate) => candidate.id === target.controlRunId);
97751
+ const controlRun = store.run(target.controlRunId);
97464
97752
  const controlVisiblyRunning = target.handle.status === "running" || target.handle.status === "pending" || target.handle.status === "awaiting_input";
97465
97753
  if (result.status === "fulfilled" || controlVisiblyRunning)
97466
97754
  acknowledged += 1;
@@ -97676,7 +97964,7 @@ function workflowIdentity(id, label, inputs) {
97676
97964
  // dist/builtin/workflows/src/runs/background/run-inspect.ts
97677
97965
  function inspectRun(runId, opts) {
97678
97966
  const activeStore = opts?.store ?? store;
97679
- const candidate = activeStore.runs().find((r) => r.id === runId);
97967
+ const candidate = activeStore.run(runId);
97680
97968
  if (!candidate) {
97681
97969
  return { ok: false, runId, reason: "not_found" };
97682
97970
  }
@@ -97819,7 +98107,7 @@ async function resumeRun(runId, opts) {
97819
98107
  return {
97820
98108
  ok: true,
97821
98109
  runId,
97822
- snapshot: structuredClone(activeStore.runs().find((candidate) => candidate.id === runId) ?? run),
98110
+ snapshot: structuredClone(activeStore.run(runId) ?? run),
97823
98111
  resumed: structuredClone([...stages.resumed]),
97824
98112
  mode: "paused",
97825
98113
  message: stages.failures.length === 0 ? `Resumed workflow runtime on ${runId}.` : `Resumed workflow runtime on ${runId}; failed to resume workflow stages: ${stages.failures.join("; ")}. Failed paused stages remain resumable.`
@@ -97847,7 +98135,7 @@ async function resumeRun(runId, opts) {
97847
98135
  const acknowledgements = await settleResumeAcknowledgements(activeStore, handles, opts?.message);
97848
98136
  acknowledgedTargets = acknowledgements.acknowledged;
97849
98137
  resumed.push(...acknowledgements.resumed);
97850
- const currentRun = activeStore.runs().find((candidate) => candidate.id === runId);
98138
+ const currentRun = activeStore.run(runId);
97851
98139
  const hasPausedDescendant = workflowHasPausedStages(activeStore, runId);
97852
98140
  if (acknowledgements.acknowledged > 0 || handles.length === 0 && acknowledgements.failures.length === 0 && !hasPausedDescendant && currentRun?.status === "paused") {
97853
98141
  const attributeStage = opts?.stageId !== undefined && (hasPausedDescendant || currentRun?.resumedAt === undefined);
@@ -97876,7 +98164,7 @@ async function resumeRun(runId, opts) {
97876
98164
  lease.release();
97877
98165
  }
97878
98166
  await waitForResumeReconciliation(acknowledgedTargets);
97879
- const locallyReconciledRoot = activeStore.runs().find((candidate) => candidate.id === aggregateRootRunId);
98167
+ const locallyReconciledRoot = activeStore.run(aggregateRootRunId);
97880
98168
  if (locallyReconciledRoot?.endedAt === undefined && locallyReconciledRoot?.status === "running") {
97881
98169
  try {
97882
98170
  const transition = await markDurableResumed(aggregateRootRunId, (opts?.toolControlRegistry ?? toolControlRegistry).runControl(aggregateRootRunId)?.durableBackend ?? requireStoreDurableBackend(activeStore, aggregateRootRunId));
@@ -97891,7 +98179,7 @@ async function resumeRun(runId, opts) {
97891
98179
  const durableMessage = `Durable resume transition failed after visible local resume: ${durabilityFailure}.`;
97892
98180
  partialFailureMessage = partialFailureMessage === undefined ? durableMessage : `${partialFailureMessage} ${durableMessage}`;
97893
98181
  }
97894
- const current = activeStore.runs().find((candidate) => candidate.id === runId) ?? run;
98182
+ const current = activeStore.run(runId) ?? run;
97895
98183
  const snapshot = structuredClone(current);
97896
98184
  const resumedCopy = structuredClone(resumed);
97897
98185
  if (partialFailureMessage !== undefined) {
@@ -97956,7 +98244,7 @@ function isRunFullyPaused(activeStore, runId, controlRunIds) {
97956
98244
  async function pauseRunWithAction(runId, opts, action = "pause") {
97957
98245
  const activeStore = opts?.store ?? store;
97958
98246
  const registry = opts?.stageControlRegistry ?? stageControlRegistry;
97959
- const run = activeStore.runs().find((candidate) => candidate.id === runId);
98247
+ const run = activeStore.run(runId);
97960
98248
  if (!run)
97961
98249
  return { ok: false, runId, reason: "not_found" };
97962
98250
  if (run.endedAt !== undefined)
@@ -97976,7 +98264,7 @@ async function pauseRunWithAction(runId, opts, action = "pause") {
97976
98264
  pooled?.release();
97977
98265
  }
97978
98266
  activeStore.recordStagePaused(runId, opts.stageId);
97979
- const currentRun = activeStore.runs().find((candidate) => candidate.id === runId);
98267
+ const currentRun = activeStore.run(runId);
97980
98268
  const stage = currentRun?.stages.find((candidate) => candidate.id === opts.stageId);
97981
98269
  const paused = stage === undefined ? [] : [structuredClone(stage)];
97982
98270
  const stillActive = currentRun?.stages.some((candidate) => candidate.id !== opts.stageId && (candidate.status === "running" || candidate.status === "pending")) ?? false;
@@ -97993,7 +98281,7 @@ async function pauseRunWithAction(runId, opts, action = "pause") {
97993
98281
  await handle.pause();
97994
98282
  activeStore.recordStagePaused(controlRunId, handle.stageId);
97995
98283
  pausedRunIds.add(controlRunId);
97996
- const controlRun = activeStore.runs().find((candidate) => candidate.id === controlRunId);
98284
+ const controlRun = activeStore.run(controlRunId);
97997
98285
  const stage = controlRun?.stages.find((candidate) => candidate.id === handle.stageId);
97998
98286
  if (stage !== undefined)
97999
98287
  paused.push(structuredClone(stage));
@@ -99810,7 +100098,7 @@ async function openCompletedDurableWorkflow(workflowId, deps, catalog) {
99810
100098
  if (resolved.kind === "stale") {
99811
100099
  return failure3("stale", `Completed workflow ${resolved.entry.workflowId} is stale or missing durable checkpoint/session data and cannot be opened.`);
99812
100100
  }
99813
- const existing = deps.store.runs().find((run) => run.id === resolved.snapshot.id);
100101
+ const existing = deps.store.run(resolved.snapshot.id);
99814
100102
  if (existing !== undefined && existing.status !== "completed") {
99815
100103
  return failure3("active", `Workflow ${resolved.snapshot.id} is already active in this session; attach with /workflow connect ${resolved.snapshot.id} instead.`);
99816
100104
  }
@@ -99818,7 +100106,7 @@ async function openCompletedDurableWorkflow(workflowId, deps, catalog) {
99818
100106
  const snapshot = snapshots.find((run) => run.id === resolved.snapshot.id) ?? resolved.snapshot;
99819
100107
  deps.beforeRestore?.(snapshots);
99820
100108
  for (const restored of snapshots) {
99821
- const previous = deps.store.runs().find((run) => run.id === restored.id);
100109
+ const previous = deps.store.run(restored.id);
99822
100110
  if (previous !== undefined)
99823
100111
  deps.store.removeRun(previous.id);
99824
100112
  deps.store.recordRunStart(restored);
@@ -100182,7 +100470,7 @@ function assertWorkflowInstanceOwner(id, ctx, store) {
100182
100470
  if (seen.has(runId))
100183
100471
  return;
100184
100472
  seen.add(runId);
100185
- const local = runs.find((run) => run.id === runId);
100473
+ const local = store.run(runId);
100186
100474
  const backend = requireStoreDurableBackend(store, runId);
100187
100475
  const durable = backend.getWorkflow(runId);
100188
100476
  const modelOwner = durable?.modelOwner ?? local?.modelOwner;
@@ -100276,7 +100564,7 @@ async function prepareWorkflowResumeCatalog(runtime, suppressedLiveIds, target)
100276
100564
  }
100277
100565
  function deleteWorkflowResumeEntry(workflowId, store2 = store) {
100278
100566
  return deleteDurableWorkflowIfSafe(requireStoreDurableBackend(store2, workflowId), workflowId, (candidateId) => {
100279
- const run = store2.runs().find((candidate) => candidate.id === candidateId);
100567
+ const run = store2.run(candidateId);
100280
100568
  return run !== undefined && run.status !== "completed" && (run.endedAt === undefined || run.status === "paused");
100281
100569
  });
100282
100570
  }
@@ -101132,7 +101420,7 @@ function createWorkflowSummaryService(options) {
101132
101420
  const finalized = new Map;
101133
101421
  let disposed = false;
101134
101422
  const request = (runId) => {
101135
- const run = options.store.runs().find((entry) => entry.id === runId);
101423
+ const run = options.store.run(runId);
101136
101424
  const context = contexts.get(runId) ?? options.resolveContext();
101137
101425
  if (disposed || !run || !context?.generateWorkflowSummary || context.isSessionSummaryEnabled?.() === false || pending.has(runId))
101138
101426
  return;
@@ -101365,7 +101653,7 @@ async function dispatch(args, opts) {
101365
101653
  const admission = await raceAbort2(launch.wait, opts.signal);
101366
101654
  if (!admission.started) {
101367
101655
  const activeStore = opts.store ?? store;
101368
- const snapshot = activeStore.runs().find((run) => run.id === accepted.runId);
101656
+ const snapshot = activeStore.run(accepted.runId);
101369
101657
  if (snapshot?.status === "paused" && snapshot.exitReason === "quit") {
101370
101658
  return {
101371
101659
  action: "run",
@@ -101392,7 +101680,7 @@ async function dispatch(args, opts) {
101392
101680
  }
101393
101681
  await job.promise;
101394
101682
  const activeStore = opts.store ?? store;
101395
- const snapshot = activeStore.runs().find((run) => run.id === accepted.runId);
101683
+ const snapshot = activeStore.run(accepted.runId);
101396
101684
  if (!snapshot) {
101397
101685
  return failedRunResult(accepted.name, accepted.runId, `Workflow run ${accepted.runId} ended without a retained snapshot`);
101398
101686
  }
@@ -101521,7 +101809,7 @@ init_store_factory();
101521
101809
  function createDurableResumeRuntime(deps) {
101522
101810
  const backendRef = deps.backendRef ?? { current: undefined };
101523
101811
  const selectedBackend = (workflowId) => {
101524
- const backend = workflowId === undefined ? undefined : availableRunDurableBackend(deps.store.runs(), workflowId);
101812
+ const backend = workflowId === undefined ? undefined : availableRunDurableBackend(deps.store, workflowId);
101525
101813
  if (backend !== undefined)
101526
101814
  return backend;
101527
101815
  if (backendRef.current === undefined)
@@ -101545,14 +101833,14 @@ function createDurableResumeRuntime(deps) {
101545
101833
  const hydrateStoredWorkflowCandidates = async (backend, target) => {
101546
101834
  const ids = deps.store.runs().map((run) => run.id).filter((id) => target === undefined || id === target);
101547
101835
  for (const id of ids)
101548
- await (availableRunDurableBackend(deps.store.runs(), id) ?? backend).hydrateWorkflow(id);
101836
+ await (availableRunDurableBackend(deps.store, id) ?? backend).hydrateWorkflow(id);
101549
101837
  };
101550
101838
  let preparedCatalog = [];
101551
101839
  return {
101552
101840
  durableBackend: selectedBackend,
101553
101841
  async inspectDurableWorkflow(workflowId) {
101554
101842
  return withRecovery(async () => {
101555
- const backend = availableRunDurableBackend(deps.store.runs(), workflowId) ?? await ensureReady();
101843
+ const backend = availableRunDurableBackend(deps.store, workflowId) ?? await ensureReady();
101556
101844
  return inspectTargetedDurableWorkflow(backend, workflowId);
101557
101845
  });
101558
101846
  },
@@ -101560,7 +101848,7 @@ function createDurableResumeRuntime(deps) {
101560
101848
  options?.signal?.throwIfAborted();
101561
101849
  return raceAbort2(withWorkflowResumeAdmission(deps.store, async (dormantWrites) => {
101562
101850
  const backend = await withRecovery(async () => {
101563
- const backend = availableRunDurableBackend(deps.store.runs(), workflowId) ?? await ensureReady();
101851
+ const backend = availableRunDurableBackend(deps.store, workflowId) ?? await ensureReady();
101564
101852
  options?.signal?.throwIfAborted();
101565
101853
  if (dormantWrites.size > 0 || resolveCatalogEntry(workflowId, preparedCatalog) === undefined)
101566
101854
  preparedCatalog = isFullRunId(workflowId) ? await prepareTargetedDurableResumable(backend, [workflowId]) : await prepareRuntimeDurableResumable(() => backend, workflowId);
@@ -101599,7 +101887,7 @@ function createDurableResumeRuntime(deps) {
101599
101887
  },
101600
101888
  async prepareDurableResumable(workflowId) {
101601
101889
  return withRecovery(async () => {
101602
- const backend = (workflowId === undefined ? undefined : availableRunDurableBackend(deps.store.runs(), workflowId)) ?? await ensureReady();
101890
+ const backend = (workflowId === undefined ? undefined : availableRunDurableBackend(deps.store, workflowId)) ?? await ensureReady();
101603
101891
  try {
101604
101892
  await hydrateStoredWorkflowCandidates(backend, workflowId);
101605
101893
  preparedCatalog = await prepareRuntimeDurableResumable(() => backend, workflowId);
@@ -101617,7 +101905,7 @@ function createDurableResumeRuntime(deps) {
101617
101905
  const known = new Set(catalog.inspectableIds ?? [...catalog.resumable, ...catalog.completed].map((entry) => entry.workflowId));
101618
101906
  for (const run of deps.store.runs())
101619
101907
  if (!known.has(run.id))
101620
- await (availableRunDurableBackend(deps.store.runs(), run.id) ?? backend).hydrateWorkflow(run.id);
101908
+ await (availableRunDurableBackend(deps.store, run.id) ?? backend).hydrateWorkflow(run.id);
101621
101909
  preparedCatalog = catalog.resumable;
101622
101910
  return catalog;
101623
101911
  } finally {
@@ -101629,9 +101917,7 @@ function createDurableResumeRuntime(deps) {
101629
101917
  return withRecovery(async () => {
101630
101918
  const backend = await ensureReady();
101631
101919
  try {
101632
- preparedCatalog = (await Promise.all(workflowIds.map((id) => prepareTargetedDurableResumable(availableRunDurableBackend(deps.store.runs(), id) ?? backend, [
101633
- id
101634
- ])))).flat();
101920
+ preparedCatalog = (await Promise.all(workflowIds.map((id) => prepareTargetedDurableResumable(availableRunDurableBackend(deps.store, id) ?? backend, [id])))).flat();
101635
101921
  return preparedCatalog;
101636
101922
  } finally {
101637
101923
  purgeSuppressedWorkflowRuns(backend, deps.store, deps.toolControlRegistry);
@@ -101799,7 +102085,7 @@ function createExtensionRuntime(opts = {}) {
101799
102085
  }
101800
102086
  async function resumeFailedRun(sourceRunId, stageId, options) {
101801
102087
  options?.signal?.throwIfAborted();
101802
- const source = activeStore.runs().find((run) => run.id === sourceRunId);
102088
+ const source = activeStore.run(sourceRunId);
101803
102089
  if (source === undefined) {
101804
102090
  return { ok: false, reason: "run_not_found", message: `run not found: ${sourceRunId}` };
101805
102091
  }
@@ -101813,7 +102099,7 @@ function createExtensionRuntime(opts = {}) {
101813
102099
  if (def === undefined) {
101814
102100
  return { ok: false, reason: "workflow_not_found", message: `workflow_not_found: ${source.name}` };
101815
102101
  }
101816
- const backend = availableRunDurableBackend(activeStore.runs(), sourceRunId) ?? await ensureReady();
102102
+ const backend = availableRunDurableBackend(activeStore, sourceRunId) ?? await ensureReady();
101817
102103
  const resolvedStage = resolveResumeStage(source, backend, stageId);
101818
102104
  if (!resolvedStage.ok) {
101819
102105
  return { ok: false, reason: "insufficient_state", message: resolvedStage.message };
@@ -103036,7 +103322,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
103036
103322
  }
103037
103323
  function isWorkflowHeartbeatIdentityOwned(identity) {
103038
103324
  const pending = workflowHeartbeatSchedulerState.pending.get(identity.runId);
103039
- const run = store.runs().find((candidate) => candidate.id === identity.runId);
103325
+ const run = store.run(identity.runId);
103040
103326
  return pending?.scheduledAt === identity.scheduledAt && run !== undefined && !isWorkflowHeartbeatTerminalRun(run);
103041
103327
  }
103042
103328
  const reinstallWorkflowHeartbeatScheduler = () => {
@@ -103508,12 +103794,11 @@ init_intercom_group();
103508
103794
  init_pending_stage_route_capability();
103509
103795
  var RELEASED_STAGE_EVENT = "atomic:workflow-released-stage";
103510
103796
  function announcementFor(store, released, answer) {
103511
- const runs = store.runs();
103512
- const run = runs.find((candidate) => candidate.id === released.runId);
103797
+ const run = store.run(released.runId);
103513
103798
  const stage = run?.stages.find((candidate) => candidate.id === released.stageId);
103514
103799
  if (run === undefined || stage?.pendingStageDeliveryAvailable !== true)
103515
103800
  return;
103516
- const rootRunId = durableRootRunIdForRun(runs, run.id);
103801
+ const rootRunId = durableRootRunIdForRun(store, run.id);
103517
103802
  if (rootRunId === undefined)
103518
103803
  return;
103519
103804
  const stageKeys = [released.stageId, released.stageName].filter((key) => !key.includes("/") && !key.includes("*"));
@@ -104507,7 +104792,7 @@ init_job_tracker();
104507
104792
  init_stage_control_registry();
104508
104793
  init_expanded_workflow_graph();
104509
104794
  function classifyDurableResumeShadow(run, store, deps = {}) {
104510
- const backend = availableRunDurableBackend(store.runs(), run.id) ?? deps.backend ?? requireStoreDurableBackend(store, run.id);
104795
+ const backend = availableRunDurableBackend(store, run.id) ?? deps.backend ?? requireStoreDurableBackend(store, run.id);
104511
104796
  const toolControls = deps.toolControls ?? toolControlRegistry;
104512
104797
  if (toolControls.runControl(run.id) !== undefined && toolControls.admissionBoundary(run.id)?.closed !== true)
104513
104798
  return "not_shadow";
@@ -104696,7 +104981,7 @@ ${renderSessionList(store.runs(), { theme, includeAll: true })}`);
104696
104981
  fail(`Run not found: ${target}`);
104697
104982
  return true;
104698
104983
  }
104699
- const run = store.runs().find((candidate) => candidate.id === resolved.runId);
104984
+ const run = store.run(resolved.runId);
104700
104985
  const positional = tokens.filter((token) => !token.startsWith("--"));
104701
104986
  const stageTarget = action === "pause" && target === positional[0] ? positional[1] : undefined;
104702
104987
  if (stageTarget !== undefined) {
@@ -104817,7 +105102,7 @@ Picker requires an interactive UI surface. Pass a runId: /workflow attach <id> [
104817
105102
  fail(`Run not found: ${picked.result.runId}`);
104818
105103
  return true;
104819
105104
  }
104820
- const run = store.runs().find((r) => r.id === resolved.runId);
105105
+ const run = store.run(resolved.runId);
104821
105106
  await injectWorkflowResumeSummary(deps.pi, ctx, resolved.runId, run, undefined, requireStoreDurableBackend(store, resolved.runId));
104822
105107
  const isPaused = run !== undefined && workflowHasPausedState(store, resolved.runId);
104823
105108
  const isDurableAuthorExit = run?.exited === true && run.status === "failed" && run.resumable === true;
@@ -104872,7 +105157,7 @@ Picker requires an interactive UI surface. Pass a runId: /workflow attach <id> [
104872
105157
  return true;
104873
105158
  }
104874
105159
  const localResolution = resolveRunId(target, store);
104875
- const localBeforePreparation = isResolvedRunId(localResolution) ? store.runs().find((run) => run.id === localResolution.runId) : undefined;
105160
+ const localBeforePreparation = isResolvedRunId(localResolution) ? store.run(localResolution.runId) : undefined;
104876
105161
  const exactBeforePreparation = localBeforePreparation?.id === target ? localBeforePreparation : undefined;
104877
105162
  const shadow = localBeforePreparation === undefined ? "not_shadow" : classifyDurableResumeShadow(localBeforePreparation, store, { ...shadowDeps, backend });
104878
105163
  if (shadow === "ineligible") {
@@ -104966,7 +105251,7 @@ Picker requires an interactive UI surface. Pass a runId: /workflow attach <id> [
104966
105251
  }
104967
105252
  const stageId = resolvedStage.stageId;
104968
105253
  const stageRunId = resolvedStage.runId ?? runId;
104969
- const run = store.runs().find((r) => r.id === stageRunId);
105254
+ const run = store.run(stageRunId);
104970
105255
  const hadPausedRunState = run?.status === "paused";
104971
105256
  const hadPausedStageState = run !== undefined && workflowHasPausedStages(store, stageRunId);
104972
105257
  const isPaused = run !== undefined && workflowHasPausedState(store, stageRunId);
@@ -105481,64 +105766,66 @@ function createSessionRunControl(host) {
105481
105766
  }
105482
105767
  };
105483
105768
  const target = (runId) => typeof runId === "string" ? { runId } : { all: true };
105484
- return {
105485
- async listRuns(filter) {
105486
- const result = await request({
105487
- action: "status",
105488
- ...filter?.status === undefined ? {} : { statusFilter: filter.status }
105489
- });
105490
- if (result.action !== "status")
105491
- throw failure4("control_failed", `Unexpected workflow result: ${result.action}`, undefined);
105492
- const catalog = filter?.includeDurable ? await host.catalog?.() : undefined;
105493
- const cwd = host.context()?.cwd;
105494
- const canonicalPaths = new Map;
105495
- const canonicalize = (path) => {
105496
- const cached = canonicalPaths.get(path);
105497
- if (cached !== undefined)
105498
- return cached;
105499
- const canonical = canonicalDirectory(path);
105500
- canonicalPaths.set(path, canonical);
105501
- return canonical;
105769
+ const list = async (filter, inScope, finished) => {
105770
+ const result = await request({
105771
+ action: "status",
105772
+ ...filter?.status === undefined ? {} : { statusFilter: filter.status }
105773
+ });
105774
+ if (result.action !== "status")
105775
+ throw failure4("control_failed", `Unexpected workflow result: ${result.action}`, undefined);
105776
+ const catalog = filter?.includeDurable ? await host.catalog?.() : undefined;
105777
+ const cwd = host.context()?.cwd;
105778
+ const canonicalPaths = new Map;
105779
+ const canonicalize = (path) => {
105780
+ const cached = canonicalPaths.get(path);
105781
+ if (cached !== undefined)
105782
+ return cached;
105783
+ const canonical = canonicalDirectory(path);
105784
+ canonicalPaths.set(path, canonical);
105785
+ return canonical;
105786
+ };
105787
+ const entries = [...catalog?.resumable ?? [], ...catalog === undefined ? [] : finished(catalog)].filter((entry) => inScope(entry, cwd, canonicalize));
105788
+ const saved = new Map(entries.map((entry) => [entry.workflowId, entry]));
105789
+ const snapshots = new Map(host.store.runs().map((run) => [run.id, run]));
105790
+ const runs = result.runs.map((run) => {
105791
+ const snapshot = snapshots.get(run.runId);
105792
+ const entry = saved.get(run.runId);
105793
+ const label = snapshot?.label ?? entry?.label;
105794
+ return {
105795
+ ...run,
105796
+ label,
105797
+ identity: workflowIdentity(run.runId, label, snapshot?.inputs ?? entry?.inputs),
105798
+ summary: snapshot?.summary ?? entry?.summary,
105799
+ summarizedThrough: snapshot?.summarizedThrough ?? entry?.summarizedThrough
105502
105800
  };
105503
- const entries = [...catalog?.resumable ?? [], ...catalog?.completed ?? []].filter((entry) => isSdkDurableRunInScope(entry, cwd, canonicalize));
105504
- const saved = new Map(entries.map((entry) => [entry.workflowId, entry]));
105505
- const snapshots = new Map(host.store.runs().map((run) => [run.id, run]));
105506
- const runs = result.runs.map((run) => {
105507
- const snapshot = snapshots.get(run.runId);
105508
- const entry = saved.get(run.runId);
105509
- const label = snapshot?.label ?? entry?.label;
105510
- return {
105511
- ...run,
105512
- label,
105513
- identity: workflowIdentity(run.runId, label, snapshot?.inputs ?? entry?.inputs),
105514
- summary: snapshot?.summary ?? entry?.summary,
105515
- summarizedThrough: snapshot?.summarizedThrough ?? entry?.summarizedThrough
105516
- };
105801
+ });
105802
+ const seen = new Set(runs.map((run) => run.runId));
105803
+ for (const entry of entries) {
105804
+ if (seen.has(entry.workflowId))
105805
+ continue;
105806
+ if (filter?.status === "awaiting_input" ? entry.pendingPrompts === 0 : filter?.status !== undefined && filter.status !== entry.status)
105807
+ continue;
105808
+ seen.add(entry.workflowId);
105809
+ runs.push({
105810
+ runId: entry.workflowId,
105811
+ name: entry.name,
105812
+ status: entry.status,
105813
+ startedAt: entry.createdAt,
105814
+ elapsedMs: Math.max(0, entry.updatedAt - entry.createdAt),
105815
+ activeStages: [],
105816
+ awaitingInputCount: entry.pendingPrompts,
105817
+ awaitingInput: [],
105818
+ label: entry.label,
105819
+ identity: workflowIdentity(entry.workflowId, entry.label, entry.inputs),
105820
+ summary: entry.summary,
105821
+ summarizedThrough: entry.summarizedThrough
105517
105822
  });
105518
- const seen = new Set(runs.map((run) => run.runId));
105519
- for (const entry of entries) {
105520
- if (seen.has(entry.workflowId))
105521
- continue;
105522
- if (filter?.status === "awaiting_input" ? entry.pendingPrompts === 0 : filter?.status !== undefined && filter.status !== entry.status)
105523
- continue;
105524
- seen.add(entry.workflowId);
105525
- runs.push({
105526
- runId: entry.workflowId,
105527
- name: entry.name,
105528
- status: entry.status,
105529
- startedAt: entry.createdAt,
105530
- elapsedMs: Math.max(0, entry.updatedAt - entry.createdAt),
105531
- activeStages: [],
105532
- awaitingInputCount: entry.pendingPrompts,
105533
- awaitingInput: [],
105534
- label: entry.label,
105535
- identity: workflowIdentity(entry.workflowId, entry.label, entry.inputs),
105536
- summary: entry.summary,
105537
- summarizedThrough: entry.summarizedThrough
105538
- });
105539
- }
105540
- return runs;
105541
- },
105823
+ }
105824
+ return runs;
105825
+ };
105826
+ return {
105827
+ listRuns: (filter) => list(filter, isSdkDurableRunInScope, (catalog) => catalog.completed),
105828
+ listProjectRuns: () => list({ includeDurable: true }, isProjectRootRun, (catalog) => catalog.completedAll ?? catalog.completed),
105542
105829
  async getRun(runId) {
105543
105830
  const result = await request({ action: "status", runId });
105544
105831
  if (result.action !== "statusDetail")
@@ -105915,7 +106202,7 @@ async function workflowAnswerAction(args, owner = captureWorkflowOwnerResources(
105915
106202
  return answerResult(target.runId, "", "noop", stage.ok ? "Stage id or name is required." : stage.message);
105916
106203
  }
105917
106204
  const stageRunId = stage.runId ?? target.runId;
105918
- const snapshot = store.runs().find((run) => run.id === stageRunId)?.stages.find((item) => item.id === stage.stageId);
106205
+ const snapshot = store.run(stageRunId)?.stages.find((item) => item.id === stage.stageId);
105919
106206
  const brokerPrompt = stageUiBroker.peekStagePrompt(stageRunId, stage.stageId);
105920
106207
  if (brokerPrompt !== undefined && (args.promptId === undefined || args.promptId === brokerPrompt.id)) {
105921
106208
  if (!hasPayloadProperty(args))
@@ -106300,7 +106587,7 @@ async function abortToolNode(runId, nodeId, opts) {
106300
106587
  error: `atomic-workflows: ctx.tool ${handle.name} abandoned after abort; the callback ignored its abort signal`
106301
106588
  });
106302
106589
  }
106303
- const cancelled = activeStore.runs().find((candidate) => candidate.id === runId)?.toolNodes.find((candidate) => candidate.id === nodeId);
106590
+ const cancelled = activeStore.run(runId)?.toolNodes.find((candidate) => candidate.id === nodeId);
106304
106591
  return {
106305
106592
  ok: true,
106306
106593
  runId,
@@ -106410,7 +106697,7 @@ async function quitToolNodeAction(runId, nodeId, action, owner) {
106410
106697
  }
106411
106698
  await Promise.resolve();
106412
106699
  await Promise.resolve();
106413
- const workflowStatus = store.runs().find((candidate) => candidate.id === runId)?.status ?? "cancelled";
106700
+ const workflowStatus = store.run(runId)?.status ?? "cancelled";
106414
106701
  const abandonedNote = aborted.abandoned ? " The callback ignored its abort signal and was abandoned." : "";
106415
106702
  return {
106416
106703
  action,
@@ -106487,7 +106774,7 @@ function activePauseTargets(store, runIds, stageId) {
106487
106774
  return store.runs().filter((run) => runIds.includes(run.id)).flatMap((run) => run.stages.filter((stage) => (stageId === undefined || stage.id === stageId) && (stage.status === "running" || stage.status === "pending")).map((stage) => ({ runId: run.id, stageId: stage.id })));
106488
106775
  }
106489
106776
  function retainedPauseMessage(store, targets) {
106490
- const retained = targets.filter((target) => store.runs().find((run) => run.id === target.runId)?.stages.some((stage) => stage.id === target.stageId && stage.status === "paused"));
106777
+ const retained = targets.filter((target) => store.run(target.runId)?.stages.some((stage) => stage.id === target.stageId && stage.status === "paused"));
106491
106778
  return retained.length === 0 ? undefined : `Pauses remain in effect for stages ${retained.map((target) => `${target.runId}/${target.stageId}`).join(", ")} and can be resumed.`;
106492
106779
  }
106493
106780
  async function workflowPauseAction(args, owner = captureWorkflowOwnerResources(), guard) {
@@ -106753,7 +107040,7 @@ async function workflowResumeAction(args, deps) {
106753
107040
  };
106754
107041
  }
106755
107042
  const backend = requireStoreDurableBackend(store, target.runId);
106756
- const exact = store.runs().find((run) => run.id === target.runId);
107043
+ const exact = store.run(target.runId);
106757
107044
  const shadow = exact === undefined ? "not_shadow" : classifyDurableResumeShadow(exact, store, {
106758
107045
  backend,
106759
107046
  jobs: owner.jobs,
@@ -106803,7 +107090,7 @@ async function workflowResumeAction(args, deps) {
106803
107090
  return { action: "resume", runId: target.runId, status: "noop", message: stage.message, code: stage.code };
106804
107091
  }
106805
107092
  const stageRunId = stage.runId ?? target.runId;
106806
- const run = store.runs().find((candidate) => candidate.id === stageRunId);
107093
+ const run = store.run(stageRunId);
106807
107094
  const hadPausedRunState = run?.status === "paused";
106808
107095
  const endedBeforeResume = run?.endedAt !== undefined;
106809
107096
  const hadPausedStageState = run !== undefined && workflowHasPausedStages(store, stageRunId);
@@ -107107,7 +107394,7 @@ function workflowStageResult(args, source) {
107107
107394
  };
107108
107395
  }
107109
107396
  const stageRunId = stage.runId ?? target.runId;
107110
- const run = activeStore.runs().find((r) => r.id === stageRunId);
107397
+ const run = activeStore.run(stageRunId);
107111
107398
  const snapshot = run?.stages.find((s) => s.id === stage.stageId);
107112
107399
  return snapshot ? { action: "stage", runId: stageRunId, stage: cloneStage(snapshot) } : {
107113
107400
  action: "stage",
@@ -107150,7 +107437,7 @@ function workflowTranscriptResult(args, source) {
107150
107437
  };
107151
107438
  }
107152
107439
  const stageRunId = stage.runId ?? target.runId;
107153
- const run = activeStore.runs().find((r) => r.id === stageRunId);
107440
+ const run = activeStore.run(stageRunId);
107154
107441
  const snapshot = run?.stages.find((s) => s.id === stage.stageId);
107155
107442
  const liveHandle = source?.allowLiveHandles === false ? undefined : (source?.stageControlRegistry ?? stageControlRegistry).get(stageRunId, stage.stageId);
107156
107443
  if (liveHandle !== undefined) {
@@ -107241,7 +107528,7 @@ function makeExecuteWorkflowTool(runtime, reloadWorkflowResources, ensureWorkflo
107241
107528
  const handle = requireStoreDurableBackend(store, id).getLoadableWorkflow(id);
107242
107529
  if ((action === "resume" || action === "status" || action === "stages") && handle !== undefined && isSdkReleasedRunAdoptable(handle, recoveryCwd))
107243
107530
  return;
107244
- if (access === "sdk" && isFullRunId(args.runId?.trim() ?? "") && (action === "status" || action === "stages" || action === "resume" && handle !== undefined && await isSdkCrashedRunAdoptable(handle, recoveryCwd, requireStoreDurableBackend(store, id))) && !store.runs().some((run) => run.id === id) && handle !== undefined && isSdkDurableRunInScope(handle, recoveryCwd))
107531
+ if (access === "sdk" && isFullRunId(args.runId?.trim() ?? "") && (action === "status" || action === "stages" || action === "resume" && handle !== undefined && await isSdkCrashedRunAdoptable(handle, recoveryCwd, requireStoreDurableBackend(store, id))) && store.run(id) === undefined && handle !== undefined && isSdkDurableRunInScope(handle, recoveryCwd))
107245
107532
  return;
107246
107533
  assertWorkflowInstanceOwner(id, ctx, store);
107247
107534
  if (action === "resume" && recoveryCwd !== undefined && handle?.invocationCwd !== undefined && canonicalDirectory(recoveryCwd) !== canonicalDirectory(handle.invocationCwd)) {
@@ -107400,7 +107687,7 @@ function makeExecuteWorkflowTool(runtime, reloadWorkflowResources, ensureWorkflo
107400
107687
  onRunAccepted,
107401
107688
  owner,
107402
107689
  authorize,
107403
- beforeResume: (id) => injectWorkflowResumeSummary(pi, ctx, id, store.runs().find((run) => run.id === id), undefined, requireStoreDurableBackend(store, id))
107690
+ beforeResume: (id) => injectWorkflowResumeSummary(pi, ctx, id, store.run(id), undefined, requireStoreDurableBackend(store, id))
107404
107691
  }));
107405
107692
  default: {
107406
107693
  const _exhaustive = action;