@bastani/atomic 0.9.78 → 0.9.79-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 (176) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +12 -0
  3. package/dist/builtin/intercom/broker/broker.ts +198 -72
  4. package/dist/builtin/intercom/broker/client-message-validation.ts +38 -0
  5. package/dist/builtin/intercom/broker/client.ts +150 -11
  6. package/dist/builtin/intercom/broker/delivery-failure-reason.ts +1 -0
  7. package/dist/builtin/intercom/broker/departed-children.ts +23 -0
  8. package/dist/builtin/intercom/broker/hosted-session-errors.ts +188 -0
  9. package/dist/builtin/intercom/broker/hosted-sessions.ts +113 -0
  10. package/dist/builtin/intercom/broker/multinode-router.ts +7 -2
  11. package/dist/builtin/intercom/broker/presence-handler.ts +2 -1
  12. package/dist/builtin/intercom/broker/protocol-version.ts +6 -1
  13. package/dist/builtin/intercom/broker/recipient-gone-errors.ts +46 -5
  14. package/dist/builtin/intercom/broker/released-reply-errors.ts +1 -1
  15. package/dist/builtin/intercom/broker/send-handler.ts +19 -3
  16. package/dist/builtin/intercom/broker/socket-writes.ts +20 -1
  17. package/dist/builtin/intercom/hosted-session-timeout-error.ts +59 -0
  18. package/dist/builtin/intercom/index.bundle.mjs +634 -125
  19. package/dist/builtin/intercom/package.json +1 -1
  20. package/dist/builtin/intercom/types.ts +41 -3
  21. package/dist/builtin/mcp/package.json +1 -1
  22. package/dist/builtin/subagents/CHANGELOG.md +8 -0
  23. package/dist/builtin/subagents/package.json +1 -1
  24. package/dist/builtin/subagents/src/extension/index.bundle.mjs +90 -34
  25. package/dist/builtin/web-access/package.json +1 -1
  26. package/dist/builtin/workflows/CHANGELOG.md +9 -0
  27. package/dist/builtin/workflows/builtin/{chunk-89we7r4p.js → chunk-5hrzxynt.js} +1 -1
  28. package/dist/builtin/workflows/builtin/{chunk-8yfssw01.js → chunk-m56qhe4b.js} +1 -1
  29. package/dist/builtin/workflows/builtin/{chunk-wh2p4qjg.js → chunk-x8m4t2jy.js} +182 -33
  30. package/dist/builtin/workflows/builtin/goal.js +2 -2
  31. package/dist/builtin/workflows/builtin/index.js +3 -3
  32. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  33. package/dist/builtin/workflows/package.json +1 -1
  34. package/dist/builtin/workflows/src/extension/index.bundle.mjs +1243 -230
  35. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +854 -170
  36. package/dist/builtin/workflows/src/index.js +854 -170
  37. package/dist/builtin/workflows/src/local-worker-entry.mjs +854 -170
  38. package/dist/cli/startup-progress.d.ts +30 -0
  39. package/dist/cli/startup-progress.d.ts.map +1 -0
  40. package/dist/cli/startup-progress.js +78 -0
  41. package/dist/cli/startup-progress.js.map +1 -0
  42. package/dist/core/agent-session-events.d.ts.map +1 -1
  43. package/dist/core/agent-session-events.js +3 -0
  44. package/dist/core/agent-session-events.js.map +1 -1
  45. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  46. package/dist/core/agent-session-extension-bindings.js +2 -0
  47. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  48. package/dist/core/agent-session-methods.d.ts +2 -0
  49. package/dist/core/agent-session-methods.d.ts.map +1 -1
  50. package/dist/core/agent-session-methods.js.map +1 -1
  51. package/dist/core/agent-session-state.d.ts +12 -4
  52. package/dist/core/agent-session-state.d.ts.map +1 -1
  53. package/dist/core/agent-session-state.js +82 -15
  54. package/dist/core/agent-session-state.js.map +1 -1
  55. package/dist/core/agent-session.d.ts +3 -0
  56. package/dist/core/agent-session.d.ts.map +1 -1
  57. package/dist/core/agent-session.js +3 -0
  58. package/dist/core/agent-session.js.map +1 -1
  59. package/dist/core/builtin-resource-loader.d.ts.map +1 -1
  60. package/dist/core/builtin-resource-loader.js +3 -0
  61. package/dist/core/builtin-resource-loader.js.map +1 -1
  62. package/dist/core/debug.d.ts +2 -0
  63. package/dist/core/debug.d.ts.map +1 -1
  64. package/dist/core/debug.js +13 -0
  65. package/dist/core/debug.js.map +1 -1
  66. package/dist/core/export-html/ansi-to-html.d.ts +5 -0
  67. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  68. package/dist/core/export-html/ansi-to-html.js +57 -20
  69. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  70. package/dist/core/export-html/template.js +1 -1
  71. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  72. package/dist/core/export-html/tool-renderer.js +2 -3
  73. package/dist/core/export-html/tool-renderer.js.map +1 -1
  74. package/dist/core/extensions/workflow-activity-hub.d.ts +7 -0
  75. package/dist/core/extensions/workflow-activity-hub.d.ts.map +1 -1
  76. package/dist/core/extensions/workflow-activity-hub.js +104 -6
  77. package/dist/core/extensions/workflow-activity-hub.js.map +1 -1
  78. package/dist/core/keybindings.d.ts +0 -8
  79. package/dist/core/keybindings.d.ts.map +1 -1
  80. package/dist/core/keybindings.js +0 -1
  81. package/dist/core/keybindings.js.map +1 -1
  82. package/dist/core/mandatory-resource-loader.d.ts.map +1 -1
  83. package/dist/core/mandatory-resource-loader.js +3 -0
  84. package/dist/core/mandatory-resource-loader.js.map +1 -1
  85. package/dist/core/resume/session-resume.d.ts +7 -1
  86. package/dist/core/resume/session-resume.d.ts.map +1 -1
  87. package/dist/core/resume/session-resume.js +136 -16
  88. package/dist/core/resume/session-resume.js.map +1 -1
  89. package/dist/core/session-history-index.d.ts +31 -0
  90. package/dist/core/session-history-index.d.ts.map +1 -0
  91. package/dist/core/session-history-index.js +82 -0
  92. package/dist/core/session-history-index.js.map +1 -0
  93. package/dist/core/session-manager-core.d.ts +3 -0
  94. package/dist/core/session-manager-core.d.ts.map +1 -1
  95. package/dist/core/session-manager-core.js +22 -17
  96. package/dist/core/session-manager-core.js.map +1 -1
  97. package/dist/core/session-manager-history.d.ts +3 -3
  98. package/dist/core/session-manager-history.d.ts.map +1 -1
  99. package/dist/core/session-manager-history.js +6 -5
  100. package/dist/core/session-manager-history.js.map +1 -1
  101. package/dist/core/storage/session/history-load-observer.d.ts +11 -0
  102. package/dist/core/storage/session/history-load-observer.d.ts.map +1 -0
  103. package/dist/core/storage/session/history-load-observer.js +25 -0
  104. package/dist/core/storage/session/history-load-observer.js.map +1 -0
  105. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  106. package/dist/core/storage/session/sql-session-store.js +6 -0
  107. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  108. package/dist/core/tool-deactivation.d.ts +11 -0
  109. package/dist/core/tool-deactivation.d.ts.map +1 -0
  110. package/dist/core/tool-deactivation.js +13 -0
  111. package/dist/core/tool-deactivation.js.map +1 -0
  112. package/dist/core/tool-status.d.ts +6 -1
  113. package/dist/core/tool-status.d.ts.map +1 -1
  114. package/dist/core/tool-status.js +11 -3
  115. package/dist/core/tool-status.js.map +1 -1
  116. package/dist/extensions/llama/errors.js +1 -1
  117. package/dist/extensions/llama/errors.js.map +1 -1
  118. package/dist/extensions/llama/provider.d.ts +1 -1
  119. package/dist/extensions/llama/provider.js +1 -1
  120. package/dist/extensions/llama/provider.js.map +1 -1
  121. package/dist/main-session.d.ts +14 -2
  122. package/dist/main-session.d.ts.map +1 -1
  123. package/dist/main-session.js +42 -9
  124. package/dist/main-session.js.map +1 -1
  125. package/dist/main.d.ts.map +1 -1
  126. package/dist/main.js +4 -2
  127. package/dist/main.js.map +1 -1
  128. package/dist/modes/interactive/components/assistant-message.d.ts +6 -0
  129. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  130. package/dist/modes/interactive/components/assistant-message.js +13 -4
  131. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  132. package/dist/modes/interactive/components/task-detail.d.ts +1 -1
  133. package/dist/modes/interactive/components/task-detail.d.ts.map +1 -1
  134. package/dist/modes/interactive/components/task-detail.js +1 -3
  135. package/dist/modes/interactive/components/task-detail.js.map +1 -1
  136. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  137. package/dist/modes/interactive/components/task-inspector.js +1 -7
  138. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  139. package/dist/modes/interactive/components/task-navigation.d.ts +0 -1
  140. package/dist/modes/interactive/components/task-navigation.d.ts.map +1 -1
  141. package/dist/modes/interactive/components/task-navigation.js +1 -3
  142. package/dist/modes/interactive/components/task-navigation.js.map +1 -1
  143. package/dist/modes/interactive/interactive-agent-events.js +5 -9
  144. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  145. package/dist/modes/interactive/interactive-deferred-startup.d.ts.map +1 -1
  146. package/dist/modes/interactive/interactive-deferred-startup.js +8 -5
  147. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  148. package/dist/modes/interactive/interactive-process-lifecycle.js +16 -10
  149. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  150. package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
  151. package/dist/modes/interactive/interactive-startup.js +2 -0
  152. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  153. package/dist/modes/interactive/interactive-unavailable-tools.d.ts +20 -0
  154. package/dist/modes/interactive/interactive-unavailable-tools.d.ts.map +1 -0
  155. package/dist/modes/interactive/interactive-unavailable-tools.js +40 -0
  156. package/dist/modes/interactive/interactive-unavailable-tools.js.map +1 -0
  157. package/dist/modes/interactive-engine/remote-component.js +1 -1
  158. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  159. package/docs/background-tasks.md +1 -1
  160. package/docs/extensions/api-reference.md +1 -1
  161. package/docs/extensions/events.md +2 -0
  162. package/docs/intercom/operations.md +2 -2
  163. package/docs/intercom/reference.md +12 -1
  164. package/docs/keybindings.md +2 -3
  165. package/docs/llama-cpp.md +9 -10
  166. package/docs/models/reference.md +1 -1
  167. package/docs/models-configuration.md +1 -1
  168. package/docs/sessions.md +6 -2
  169. package/docs/subagents.md +3 -1
  170. package/docs/usage.md +1 -1
  171. package/docs/workflows/operations.md +2 -2
  172. package/docs/worktree-snapshots.md +3 -1
  173. package/npm-shrinkwrap.json +32 -32
  174. package/package.json +4 -4
  175. package/schemas/keybindings.schema.json +0 -4
  176. package/schemas/models.schema.json +1 -1
@@ -6115,11 +6115,22 @@ function index(items, cache) {
6115
6115
  }
6116
6116
  return byId;
6117
6117
  }
6118
+ function markPublishedSnapshotArray(items) {
6119
+ publishedSnapshotArrays.add(items);
6120
+ }
6121
+ function isPublishedSnapshotArray(items) {
6122
+ return publishedSnapshotArrays.has(items);
6123
+ }
6124
+ function frozenIndex(items, cache) {
6125
+ return cache.get(items) ?? (isPublishedSnapshotArray(items) || Object.isFrozen(items) ? index(items, cache) : undefined);
6126
+ }
6118
6127
  function findSnapshotRun(runs, runId) {
6119
- return Object.isFrozen(runs) ? index(runs, runIndexes).get(runId) : runs.find((run) => run.id === runId);
6128
+ const byId = frozenIndex(runs, runIndexes);
6129
+ return byId === undefined ? runs.find((run) => run.id === runId) : byId.get(runId);
6120
6130
  }
6121
6131
  function findSnapshotStage(stages, stageId) {
6122
- return Object.isFrozen(stages) ? index(stages, stageIndexes).get(stageId) : stages.find((stage) => stage.id === stageId);
6132
+ const byId = frozenIndex(stages, stageIndexes);
6133
+ return byId === undefined ? stages.find((stage) => stage.id === stageId) : byId.get(stageId);
6123
6134
  }
6124
6135
  function childRunsInSource(source, parentRunId, parentStageId) {
6125
6136
  if (isRunLookup(source) && source.childRuns !== undefined)
@@ -6144,10 +6155,11 @@ function invocationRunsInSource(source, rootRunId) {
6144
6155
  }
6145
6156
  return found.filter(inInvocation).sort((left, right) => source.runPosition(left.id) - source.runPosition(right.id));
6146
6157
  }
6147
- var runIndexes, stageIndexes;
6158
+ var runIndexes, stageIndexes, publishedSnapshotArrays;
6148
6159
  var init_workflow_run_ownership = __esm(() => {
6149
6160
  runIndexes = new WeakMap;
6150
6161
  stageIndexes = new WeakMap;
6162
+ publishedSnapshotArrays = new WeakSet;
6151
6163
  });
6152
6164
 
6153
6165
  // dist/builtin/workflows/src/durable/prompt-reservations.ts
@@ -6453,6 +6465,53 @@ function flattenTruncatedString(value2) {
6453
6465
  return value2.split("").join("");
6454
6466
  }
6455
6467
 
6468
+ // dist/builtin/workflows/src/shared/run-stage-index.ts
6469
+ function asksForInput(stage) {
6470
+ return stage.pendingPrompt !== undefined || stage.inputRequest !== undefined || stage.status === "awaiting_input" || stage.awaitingInputSince !== undefined;
6471
+ }
6472
+ function isFinished(stage) {
6473
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
6474
+ }
6475
+ function indexFrom(stages, asking, unfinished) {
6476
+ const pending = [];
6477
+ const waiting = [];
6478
+ for (const position of unfinished) {
6479
+ const stage = stages[position];
6480
+ if (stage.status === "pending")
6481
+ pending.push(stage);
6482
+ if (asksForInput(stage))
6483
+ waiting.push(stage);
6484
+ }
6485
+ return { index: { awaitingInput: asking > 0, pending, waiting }, asking, unfinished };
6486
+ }
6487
+ function indexRunFrom(run, previous, changed, appendedFrom) {
6488
+ const known = indexes.get(previous);
6489
+ if (known === undefined || !Object.isFrozen(run))
6490
+ return;
6491
+ let asking = known.asking;
6492
+ const unfinished = new Set(known.unfinished);
6493
+ const update = (position, before) => {
6494
+ const stage = run.stages[position];
6495
+ if (before !== undefined && asksForInput(before))
6496
+ asking--;
6497
+ if (asksForInput(stage))
6498
+ asking++;
6499
+ if (isFinished(stage))
6500
+ unfinished.delete(position);
6501
+ else
6502
+ unfinished.add(position);
6503
+ };
6504
+ for (const position of changed)
6505
+ update(position, previous.stages[position]);
6506
+ for (let position = appendedFrom;position < run.stages.length; position++)
6507
+ update(position, undefined);
6508
+ indexes.set(run, indexFrom(run.stages, asking, [...unfinished].sort((left, right) => left - right)));
6509
+ }
6510
+ var indexes;
6511
+ var init_run_stage_index = __esm(() => {
6512
+ indexes = new WeakMap;
6513
+ });
6514
+
6456
6515
  // dist/builtin/workflows/src/shared/tool-payload-bounds.ts
6457
6516
  function isOmittedJsonValue(value2) {
6458
6517
  return value2 === undefined || typeof value2 === "function" || typeof value2 === "symbol";
@@ -6801,25 +6860,42 @@ function sameSourceShape(value2, shape) {
6801
6860
  }
6802
6861
  return index === shape.keys.length;
6803
6862
  }
6863
+ function isSettledStage(stage) {
6864
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
6865
+ }
6804
6866
  function projectStage(stage) {
6867
+ const compact = compactStage(stage);
6868
+ deepFreezeGraphValue(compact);
6805
6869
  return {
6806
6870
  shape: sourceShape(stage),
6807
6871
  parentCount: stage.parentIds.length,
6808
6872
  toolEventCount: stage.toolEvents.length,
6809
6873
  lastToolEvent: stage.toolEvents.at(-1),
6810
6874
  noticeCount: stage.notices?.length,
6811
- compact: compactStage(stage)
6875
+ settled: isSettledStage(stage),
6876
+ compact
6812
6877
  };
6813
6878
  }
6814
6879
  function stageUnchanged(stage, projected) {
6815
6880
  return sameSourceShape(stage, projected.shape) && stage.parentIds.length === projected.parentCount && stage.toolEvents.length === projected.toolEventCount && stage.toolEvents.at(-1) === projected.lastToolEvent && stage.notices?.length === projected.noticeCount;
6816
6881
  }
6817
6882
  function projectToolNode(node) {
6818
- return { shape: sourceShape(node), parentCount: node.parentIds.length, compact: compactToolNode(node) };
6883
+ const compact = compactToolNode(node);
6884
+ deepFreezeGraphValue(compact);
6885
+ return { shape: sourceShape(node), parentCount: node.parentIds.length, compact };
6819
6886
  }
6820
6887
  function toolNodeUnchanged(node, projected) {
6821
6888
  return sameSourceShape(node, projected.shape) && node.parentIds.length === projected.parentCount;
6822
6889
  }
6890
+ function freezeCompactRun(run) {
6891
+ for (const [key, value2] of Object.entries(run)) {
6892
+ if (key === "stages" || key === "toolNodes")
6893
+ markPublishedSnapshotArray(value2);
6894
+ else
6895
+ deepFreezeGraphValue(value2);
6896
+ }
6897
+ Object.freeze(run);
6898
+ }
6823
6899
 
6824
6900
  class GraphStoreSnapshotBuilder {
6825
6901
  projected = new Map;
@@ -6848,9 +6924,7 @@ class GraphStoreSnapshotBuilder {
6848
6924
  const next = new Map;
6849
6925
  const compactRuns = [];
6850
6926
  for (const run of runs) {
6851
- const known = previous.get(run.id);
6852
- const reusable = known?.source === run ? known : undefined;
6853
- const projected = reusable !== undefined && !this.changedRuns.has(run.id) && this.runUnchanged(run, reusable) ? reusable : this.projectRun(run, reusable);
6927
+ const projected = this.refreshRun(run, previous.get(run.id));
6854
6928
  next.set(run.id, projected);
6855
6929
  compactRuns.push(projected.compact);
6856
6930
  }
@@ -6858,38 +6932,36 @@ class GraphStoreSnapshotBuilder {
6858
6932
  this.changedRuns.clear();
6859
6933
  this.changedStages.clear();
6860
6934
  this.changedToolNodes.clear();
6861
- const snapshot = {
6862
- runs: compactRuns,
6863
- notices: notices.map((notice) => ({ ...notice })),
6935
+ const compactNotices = notices.map((notice) => ({ ...notice }));
6936
+ deepFreezeGraphValue(compactNotices);
6937
+ const snapshot = Object.freeze({
6938
+ runs: Object.freeze(compactRuns),
6939
+ notices: compactNotices,
6864
6940
  version
6865
- };
6866
- deepFreezeGraphValue(snapshot);
6941
+ });
6942
+ snapshotLineages.set(snapshot, this);
6867
6943
  return snapshot;
6868
6944
  }
6869
6945
  buildRun(run) {
6870
- const known = this.projected.get(run.id);
6871
- const reusable = known?.source === run ? known : undefined;
6872
- const projected = reusable !== undefined && !this.changedRuns.has(run.id) && this.runUnchanged(run, reusable) ? reusable : this.projectRun(run, reusable);
6873
- deepFreezeGraphValue(projected.compact);
6946
+ const projected = this.refreshRun(run, this.projected.get(run.id));
6874
6947
  this.projected.set(run.id, projected);
6875
6948
  this.changedRuns.delete(run.id);
6876
6949
  this.changedStages.delete(run.id);
6877
6950
  this.changedToolNodes.delete(run.id);
6878
6951
  return projected.compact;
6879
6952
  }
6880
- runUnchanged(run, projected) {
6881
- if (!sameSourceShape(run, projected.shape))
6882
- return false;
6883
- const { stages, toolNodes } = projected.compact;
6884
- if (run.stages.length !== stages.length || run.toolNodes.length !== toolNodes.length)
6953
+ refreshRun(run, known) {
6954
+ const reusable = known?.source === run ? known : undefined;
6955
+ if (reusable === undefined || this.changedRuns.has(run.id) || !sameSourceShape(run, reusable.shape))
6956
+ return this.projectRun(run, reusable);
6957
+ if (!this.toolNodesUnchanged(run, reusable))
6958
+ return this.projectRun(run, reusable);
6959
+ return this.patchStages(run, reusable) ?? this.projectRun(run, reusable);
6960
+ }
6961
+ toolNodesUnchanged(run, projected) {
6962
+ const { toolNodes } = projected.compact;
6963
+ if (run.toolNodes.length !== toolNodes.length)
6885
6964
  return false;
6886
- const changedStages = this.changedStages.get(run.id);
6887
- for (let index = 0;index < run.stages.length; index++) {
6888
- const stage = run.stages[index];
6889
- const known = projected.stages.get(stage);
6890
- if (known === undefined || known.compact !== stages[index] || changedStages?.has(stage.id) === true || !stageUnchanged(stage, known))
6891
- return false;
6892
- }
6893
6965
  const changedToolNodes = this.changedToolNodes.get(run.id);
6894
6966
  for (let index = 0;index < run.toolNodes.length; index++) {
6895
6967
  const node = run.toolNodes[index];
@@ -6899,15 +6971,86 @@ class GraphStoreSnapshotBuilder {
6899
6971
  }
6900
6972
  return true;
6901
6973
  }
6974
+ patchStages(run, projected) {
6975
+ const sources = projected.stageSources;
6976
+ if (run.stages.length < sources.length)
6977
+ return;
6978
+ for (let index = 0;index < sources.length; index++)
6979
+ if (run.stages[index] !== sources[index])
6980
+ return;
6981
+ const changed = new Set;
6982
+ const scoped = this.changedStages.get(run.id);
6983
+ if (scoped !== undefined) {
6984
+ if (projected.duplicateStageIds)
6985
+ return;
6986
+ for (const id of scoped) {
6987
+ const position = projected.stagePositions.get(id);
6988
+ if (position !== undefined)
6989
+ changed.add(position);
6990
+ }
6991
+ }
6992
+ for (const position of projected.unsettled)
6993
+ if (!changed.has(position) && !stageUnchanged(sources[position], projected.stages[position]))
6994
+ changed.add(position);
6995
+ if (changed.size === 0 && run.stages.length === sources.length)
6996
+ return projected;
6997
+ const previous = projected.compact;
6998
+ const appendedFrom = sources.length;
6999
+ const compactStages = previous.stages.slice();
7000
+ for (const position of changed) {
7001
+ const stage = projectStage(sources[position]);
7002
+ projected.stages[position] = stage;
7003
+ compactStages[position] = stage.compact;
7004
+ if (stage.settled)
7005
+ projected.unsettled.delete(position);
7006
+ else
7007
+ projected.unsettled.add(position);
7008
+ }
7009
+ for (let position = sources.length;position < run.stages.length; position++) {
7010
+ const source = run.stages[position];
7011
+ const stage = projectStage(source);
7012
+ sources.push(source);
7013
+ projected.stages.push(stage);
7014
+ compactStages.push(stage.compact);
7015
+ if (!stage.settled)
7016
+ projected.unsettled.add(position);
7017
+ if (projected.stagePositions.has(source.id))
7018
+ projected.duplicateStageIds = true;
7019
+ else
7020
+ projected.stagePositions.set(source.id, position);
7021
+ }
7022
+ const compact = { ...previous, stages: compactStages };
7023
+ freezeCompactRun(compact);
7024
+ indexRunFrom(compact, previous, changed, appendedFrom);
7025
+ projected.compact = compact;
7026
+ return projected;
7027
+ }
6902
7028
  projectRun(run, previous) {
6903
7029
  const changedStages = this.changedStages.get(run.id);
6904
- const stages = new Map;
7030
+ const previousStages = new Map;
7031
+ if (previous !== undefined)
7032
+ for (let index = 0;index < previous.stageSources.length; index++)
7033
+ previousStages.set(previous.stageSources[index], previous.stages[index]);
7034
+ const stageSources = [];
7035
+ const stages = [];
7036
+ const stagePositions = new Map;
7037
+ const unsettled = new Set;
7038
+ let duplicateStageIds = false;
6905
7039
  const compactStages = [];
6906
7040
  for (const stage of run.stages) {
6907
- let projected = stages.get(stage) ?? previous?.stages.get(stage);
7041
+ let projected = previousStages.get(stage);
6908
7042
  if (projected === undefined || changedStages?.has(stage.id) === true || !stageUnchanged(stage, projected))
6909
7043
  projected = projectStage(stage);
6910
- stages.set(stage, projected);
7044
+ previousStages.set(stage, projected);
7045
+ const position = stages.length;
7046
+ stageSources.push(stage);
7047
+ stages.push(projected);
7048
+ if (!projected.settled)
7049
+ unsettled.add(position);
7050
+ if (stagePositions.has(stage.id))
7051
+ duplicateStageIds = true;
7052
+ else
7053
+ stagePositions.set(stage.id, position);
6911
7054
  compactStages.push(projected.compact);
6912
7055
  }
6913
7056
  const changedToolNodes = this.changedToolNodes.get(run.id);
@@ -6920,12 +7063,18 @@ class GraphStoreSnapshotBuilder {
6920
7063
  toolNodes.set(node, projected);
6921
7064
  compactToolNodes.push(projected.compact);
6922
7065
  }
7066
+ const compact = compactRun(run, compactStages, compactToolNodes);
7067
+ freezeCompactRun(compact);
6923
7068
  return {
6924
7069
  source: run,
6925
7070
  shape: sourceShape(run),
7071
+ stageSources,
6926
7072
  stages,
7073
+ stagePositions,
7074
+ duplicateStageIds,
7075
+ unsettled,
6927
7076
  toolNodes,
6928
- compact: compactRun(run, compactStages, compactToolNodes)
7077
+ compact
6929
7078
  };
6930
7079
  }
6931
7080
  }
@@ -6949,18 +7098,25 @@ function deepFreezeGraphValue(value2) {
6949
7098
  deepFreezeGraphValue(value2[key]);
6950
7099
  }
6951
7100
  }
6952
- var COMPACT_RESULT_FIELD_LIMIT = 1024, COMPACT_EXIT_OUTPUT_LIMIT;
7101
+ var COMPACT_RESULT_FIELD_LIMIT = 1024, COMPACT_EXIT_OUTPUT_LIMIT, snapshotLineages;
6953
7102
  var init_graph_store_snapshot = __esm(() => {
7103
+ init_run_stage_index();
6954
7104
  init_tool_payload_bounds();
7105
+ init_workflow_run_ownership();
6955
7106
  COMPACT_EXIT_OUTPUT_LIMIT = COMPACT_RESULT_FIELD_LIMIT * 4;
7107
+ snapshotLineages = new WeakMap;
6956
7108
  });
6957
7109
 
6958
7110
  // dist/builtin/workflows/src/shared/expanded-workflow-graph.ts
6959
- var leafExpansions, snapshotExpansions;
7111
+ var leafExpansions, snapshotExpansions, settledStageCounts, expandedStageLists, chainExpansions;
6960
7112
  var init_expanded_workflow_graph = __esm(() => {
7113
+ init_graph_store_snapshot();
6961
7114
  init_workflow_run_ownership();
6962
7115
  leafExpansions = new WeakMap;
6963
7116
  snapshotExpansions = new WeakMap;
7117
+ settledStageCounts = new WeakMap;
7118
+ expandedStageLists = new WeakSet;
7119
+ chainExpansions = new WeakMap;
6964
7120
  });
6965
7121
 
6966
7122
  // dist/builtin/workflows/src/shared/workflow-activity.ts
@@ -12108,8 +12264,11 @@ function stageIdentity(checkpoint) {
12108
12264
  function checkpointKey(c) {
12109
12265
  return `${c.kind}:${c.checkpointId}`;
12110
12266
  }
12267
+ function sharingOutputAsResult(checkpoint) {
12268
+ return checkpoint.kind === "stage" && typeof checkpoint.output === "string" && checkpoint.result === checkpoint.output ? { ...checkpoint, result: checkpoint.output } : checkpoint;
12269
+ }
12111
12270
  function normalizedCheckpoint(recorded) {
12112
- const checkpoint = recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded;
12271
+ const checkpoint = sharingOutputAsResult(recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded);
12113
12272
  return checkpoint.kind === "stage" && checkpoint.topology === undefined ? {
12114
12273
  ...checkpoint,
12115
12274
  topology: {
@@ -15345,6 +15504,25 @@ function writtenHandle(event) {
15345
15504
  return;
15346
15505
  return event.payload;
15347
15506
  }
15507
+ function sharingWrittenText(entry, written) {
15508
+ const folded = entry.event;
15509
+ if (folded.type !== RUN_EVENT_TYPES.checkpointRecorded || written.type !== RUN_EVENT_TYPES.checkpointRecorded)
15510
+ return entry;
15511
+ const decoded = folded.payload;
15512
+ const source = written.payload;
15513
+ if (decoded.kind !== "stage" || source.kind !== "stage")
15514
+ return entry;
15515
+ const sharesOutput = typeof source.output === "string" && decoded.output === source.output;
15516
+ const sharesResult = typeof source.result === "string" && decoded.result === source.result;
15517
+ if (!sharesOutput && !sharesResult)
15518
+ return entry;
15519
+ const payload = {
15520
+ ...decoded,
15521
+ ...sharesOutput ? { output: source.output } : {},
15522
+ ...sharesResult ? { result: source.result } : {}
15523
+ };
15524
+ return { ...entry, event: { ...folded, payload } };
15525
+ }
15348
15526
  function snapshotNeedsHistory(tail) {
15349
15527
  const handle = writtenHandle(tail.snapshot.event);
15350
15528
  return handle !== undefined && (handle.pendingStageMessageChange !== undefined || hasPendingStageDeliveryDelta(handle.pendingStageMessages));
@@ -15769,7 +15947,7 @@ class JournalDurableBackend {
15769
15947
  for (const entry of yield* this.entries(runId, nextSeq))
15770
15948
  this.fold(entry);
15771
15949
  }
15772
- this.fold(outcome.entry);
15950
+ this.fold(sharingWrittenText(outcome.entry, event));
15773
15951
  } catch (error) {
15774
15952
  if (error instanceof Error)
15775
15953
  throw yield* this.mapOwnership(error, runId);
@@ -16012,7 +16190,7 @@ class JournalDurableBackend {
16012
16190
  if (result.value.entry.seq > nextSeq)
16013
16191
  for (const entry of yield* this.entries(runId, nextSeq))
16014
16192
  this.fold(entry);
16015
- this.fold(result.value.entry);
16193
+ this.fold(sharingWrittenText(result.value.entry, append.event));
16016
16194
  append.resolve();
16017
16195
  }
16018
16196
  settled++;
@@ -21562,6 +21740,55 @@ function reconcileTerminalRunResult(runId, runSnapshot, activeStore, fallback, o
21562
21740
  onRunEnd?.(runId, result.status, result.result, result.error, result.exitReason);
21563
21741
  return result;
21564
21742
  }
21743
+ function announceSettledStageEdit(store, runId, stage) {
21744
+ if (isTerminalStageStatus(stage.status))
21745
+ store.editRun(runId, () => ({ stageIds: [stage.id] }));
21746
+ }
21747
+ function endStageWithHook(store, runId, stage, hook) {
21748
+ const outcome = hook?.(runId, stage);
21749
+ announceSettledStageEdit(store, runId, stage);
21750
+ if (!isPromiseLike(outcome))
21751
+ return;
21752
+ Promise.resolve(outcome).then(() => announceSettledStageEdit(store, runId, stage), (error) => {
21753
+ announceSettledStageEdit(store, runId, stage);
21754
+ throw error;
21755
+ });
21756
+ }
21757
+ function isPromiseLike(value2) {
21758
+ return (typeof value2 === "object" || typeof value2 === "function") && value2 !== null && typeof value2.then === "function";
21759
+ }
21760
+ function applyModelFallbackMetaToStage(stage, meta) {
21761
+ const { model, thinkingLevel, rateLimits, routerSelection, warnings } = stage;
21762
+ if (meta.model !== undefined)
21763
+ stage.model = meta.model;
21764
+ if (meta.thinkingLevel !== undefined)
21765
+ stage.thinkingLevel = meta.thinkingLevel;
21766
+ else
21767
+ delete stage.thinkingLevel;
21768
+ if (meta.attemptedModels !== undefined)
21769
+ stage.attemptedModels = meta.attemptedModels;
21770
+ if (meta.modelAttempts !== undefined)
21771
+ stage.modelAttempts = meta.modelAttempts;
21772
+ if (meta.rateLimits !== undefined)
21773
+ stage.rateLimits = meta.rateLimits;
21774
+ if (meta.routerSelection !== undefined)
21775
+ stage.routerSelection = meta.routerSelection;
21776
+ if (meta.warnings !== undefined) {
21777
+ if (meta.warnings.length > 0)
21778
+ stage.warnings = meta.warnings;
21779
+ else
21780
+ delete stage.warnings;
21781
+ }
21782
+ return model !== stage.model || thinkingLevel !== stage.thinkingLevel || rateLimits !== stage.rateLimits || routerSelection !== stage.routerSelection || warnings !== stage.warnings;
21783
+ }
21784
+ function applySessionMetaToStage(stage, meta) {
21785
+ const { sessionId, sessionFile } = stage;
21786
+ if (meta.sessionId !== undefined)
21787
+ stage.sessionId = meta.sessionId;
21788
+ if (meta.sessionFile !== undefined)
21789
+ stage.sessionFile = meta.sessionFile;
21790
+ return sessionId !== stage.sessionId || sessionFile !== stage.sessionFile;
21791
+ }
21565
21792
  function applyFailureToStage(stage, failure) {
21566
21793
  stage.status = "failed";
21567
21794
  stage.error = failure.userMessage;
@@ -22261,6 +22488,7 @@ function buildPromptNodeUiAdapter(input) {
22261
22488
  input.activeStore.recordStageAttachable(input.runId, stageId, false);
22262
22489
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
22263
22490
  await input.opts.onStageEnd?.(input.runId, stageSnapshot);
22491
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
22264
22492
  if (input.opts.persistence) {
22265
22493
  await appendStageEnd(input.opts.persistence, {
22266
22494
  runId: input.runId,
@@ -22616,15 +22844,17 @@ function createStageScheduler(input) {
22616
22844
  };
22617
22845
  const descendantsOf = (stageId) => input.runSnapshot.stages.filter((stage) => stage.id !== stageId && hasAncestor(stage, stageId));
22618
22846
  const blockingAncestorFor = (stage) => {
22847
+ const holding = new Set(input.runSnapshot.stages.filter((candidate) => candidate.status === "paused" || candidate.status === "blocked").map((candidate) => candidate.id));
22848
+ if (holding.size === 0)
22849
+ return;
22619
22850
  const queue = [...stage.parentIds];
22620
22851
  const seen = new Set;
22621
- while (queue.length > 0) {
22622
- const next = queue.shift();
22623
- if (next === undefined || seen.has(next))
22852
+ for (let index = 0;index < queue.length; index++) {
22853
+ const next = queue[index];
22854
+ if (seen.has(next))
22624
22855
  continue;
22625
22856
  seen.add(next);
22626
- const ancestor = stageById(next);
22627
- if (ancestor?.status === "paused" || ancestor?.status === "blocked")
22857
+ if (holding.has(next))
22628
22858
  return next;
22629
22859
  queue.push(...input.tracker.getParents(next));
22630
22860
  }
@@ -23414,7 +23644,44 @@ function createStageControlRegistry() {
23414
23644
  return [];
23415
23645
  return [...runMap.values()].filter((entry) => entry.controlsDependencies);
23416
23646
  }
23647
+ function createEntry(runId, stageId, handle, fields) {
23648
+ const entry = { handle, ...fields, leases: new Set, epoch: 0 };
23649
+ entry.stopWatching = handle.releaseGate?.onHoldLifted(() => releaseWhenLetGo(runId, stageId, entry));
23650
+ return entry;
23651
+ }
23652
+ function stopWatching(entry) {
23653
+ entry.stopWatching?.();
23654
+ entry.stopWatching = undefined;
23655
+ clearTimeout(entry.claimTimer);
23656
+ entry.claimTimer = undefined;
23657
+ }
23658
+ function markClaimed(runId, stageId, entry) {
23659
+ entry.permanent = true;
23660
+ entry.epoch += 1;
23661
+ entry.holdsAtClaim = entry.handle.releaseGate?.holdsTaken();
23662
+ clearTimeout(entry.claimTimer);
23663
+ if (entry.handle.releaseGate === undefined)
23664
+ return;
23665
+ entry.claimTimer = setTimeout(() => {
23666
+ entry.claimTimer = undefined;
23667
+ entry.holdsAtClaim = undefined;
23668
+ releaseWhenLetGo(runId, stageId, entry);
23669
+ }, CLAIM_GRACE_MS);
23670
+ entry.claimTimer.unref();
23671
+ }
23672
+ function unusedSinceClaim(entry, gate) {
23673
+ return gate.holdsTaken() <= (entry.holdsAtClaim ?? -1);
23674
+ }
23675
+ function releaseWhenLetGo(runId, stageId, entry) {
23676
+ const gate = entry.handle.releaseGate;
23677
+ if (gate === undefined || !entry.releaseWanted || entry.leases.size > 0)
23678
+ return;
23679
+ if (unusedSinceClaim(entry, gate) || !gate.idle())
23680
+ return;
23681
+ releaseIdleEntry(runId, stageId, entry).catch((error) => console.warn("atomic-workflows: completed stage session release failed", error));
23682
+ }
23417
23683
  function disposeEntry(entry) {
23684
+ stopWatching(entry);
23418
23685
  if (entry.disposal !== undefined)
23419
23686
  return entry.disposal;
23420
23687
  try {
@@ -23439,7 +23706,26 @@ function createStageControlRegistry() {
23439
23706
  function disposeEntryInBackground(entry, message) {
23440
23707
  disposeEntry(entry).catch((err) => console.warn(message, err));
23441
23708
  }
23442
- async function releaseIdleEntry(runId, stageId, entry) {
23709
+ function releaseIdleEntry(runId, stageId, entry) {
23710
+ if (entry.releasing !== undefined) {
23711
+ entry.releaseAgain = true;
23712
+ return entry.releasing;
23713
+ }
23714
+ entry.releasing = releaseUntilSettled(runId, stageId, entry).finally(() => {
23715
+ entry.releasing = undefined;
23716
+ });
23717
+ return entry.releasing;
23718
+ }
23719
+ async function releaseUntilSettled(runId, stageId, entry) {
23720
+ do {
23721
+ entry.releaseAgain = false;
23722
+ await releaseUnlessUsed(runId, stageId, entry);
23723
+ } while (releaseRequestedAgain(entry) && _byRun.get(runId)?.get(stageId) === entry);
23724
+ }
23725
+ function releaseRequestedAgain(entry) {
23726
+ return entry.releaseAgain === true;
23727
+ }
23728
+ async function releaseUnlessUsed(runId, stageId, entry) {
23443
23729
  const gate = entry.handle.releaseGate;
23444
23730
  if (gate === undefined || entry.disposal !== undefined)
23445
23731
  return;
@@ -23450,7 +23736,7 @@ function createStageControlRegistry() {
23450
23736
  const runMap = _byRun.get(runId);
23451
23737
  if (runMap?.get(stageId) !== entry || entry.epoch !== epoch || entry.leases.size > 0)
23452
23738
  return;
23453
- if (entry.disposal !== undefined || !gate.idle())
23739
+ if (unusedSinceClaim(entry, gate) || !gate.idle())
23454
23740
  return;
23455
23741
  const { stageName, sessionId } = entry.handle;
23456
23742
  rememberSessionStore(entry.handle, savedIn);
@@ -23523,13 +23809,13 @@ function createStageControlRegistry() {
23523
23809
  rememberSessionStore(handle);
23524
23810
  const runMap = ensureRun(handle.runId);
23525
23811
  const displaced = runMap.get(handle.stageId);
23526
- runMap.set(handle.stageId, {
23527
- handle,
23812
+ runMap.set(handle.stageId, createEntry(handle.runId, handle.stageId, handle, {
23528
23813
  controlsDependencies: true,
23529
23814
  permanent: true,
23530
- leases: new Set,
23531
- epoch: 0
23532
- });
23815
+ releaseWanted: handle.releaseGate?.releaseWhenIdle === true
23816
+ }));
23817
+ if (displaced !== undefined)
23818
+ stopWatching(displaced);
23533
23819
  if (displaced !== undefined && displaced.handle !== handle && !displaced.permanent) {
23534
23820
  disposeEntryInBackground(displaced, "atomic-workflows: displaced provisional stage handle dispose failed");
23535
23821
  }
@@ -23537,8 +23823,10 @@ function createStageControlRegistry() {
23537
23823
  const existing = _byRun.get(handle.runId);
23538
23824
  if (!existing)
23539
23825
  return;
23540
- if (existing.get(handle.stageId)?.handle === handle) {
23826
+ const entry = existing.get(handle.stageId);
23827
+ if (entry?.handle === handle) {
23541
23828
  rememberSessionStore(handle);
23829
+ stopWatching(entry);
23542
23830
  existing.delete(handle.stageId);
23543
23831
  }
23544
23832
  if (existing.size === 0)
@@ -23549,8 +23837,7 @@ function createStageControlRegistry() {
23549
23837
  const runMap = ensureRun(runId);
23550
23838
  const existing = runMap.get(stageId);
23551
23839
  if (existing !== undefined && existing.handle.isDisposed !== true) {
23552
- existing.permanent = true;
23553
- existing.epoch += 1;
23840
+ markClaimed(runId, stageId, existing);
23554
23841
  return existing.handle;
23555
23842
  }
23556
23843
  if (existing !== undefined) {
@@ -23558,13 +23845,13 @@ function createStageControlRegistry() {
23558
23845
  disposeEntryInBackground(existing, "atomic-workflows: stale stage handle dispose failed");
23559
23846
  }
23560
23847
  const handle = create();
23561
- runMap.set(handle.stageId, {
23562
- handle,
23848
+ const entry = createEntry(runId, handle.stageId, handle, {
23563
23849
  controlsDependencies: false,
23564
23850
  permanent: true,
23565
- leases: new Set,
23566
- epoch: 0
23851
+ releaseWanted: true
23567
23852
  });
23853
+ markClaimed(runId, handle.stageId, entry);
23854
+ runMap.set(handle.stageId, entry);
23568
23855
  return handle;
23569
23856
  },
23570
23857
  acquireDetached(runId, stageId, create) {
@@ -23576,13 +23863,11 @@ function createStageControlRegistry() {
23576
23863
  entry = undefined;
23577
23864
  }
23578
23865
  if (entry === undefined) {
23579
- entry = {
23580
- handle: create(),
23866
+ entry = createEntry(runId, stageId, create(), {
23581
23867
  controlsDependencies: false,
23582
23868
  permanent: false,
23583
- leases: new Set,
23584
- epoch: 0
23585
- };
23869
+ releaseWanted: true
23870
+ });
23586
23871
  runMap.set(stageId, entry);
23587
23872
  }
23588
23873
  const leasedEntry = entry;
@@ -23613,8 +23898,12 @@ function createStageControlRegistry() {
23613
23898
  await leasedEntry.disposal;
23614
23899
  return;
23615
23900
  }
23616
- if (leasedEntry.permanent || leasedEntry.leases.size > 0)
23901
+ if (leasedEntry.leases.size > 0)
23617
23902
  return;
23903
+ if (leasedEntry.permanent) {
23904
+ releaseWhenLetGo(runId, stageId, leasedEntry);
23905
+ return;
23906
+ }
23618
23907
  runMap.delete(stageId);
23619
23908
  if (runMap.size === 0)
23620
23909
  _byRun.delete(runId);
@@ -23639,10 +23928,8 @@ function createStageControlRegistry() {
23639
23928
  },
23640
23929
  claim(runId, stageId) {
23641
23930
  const entry = _byRun.get(runId)?.get(stageId);
23642
- if (entry !== undefined) {
23643
- entry.permanent = true;
23644
- entry.epoch += 1;
23645
- }
23931
+ if (entry !== undefined)
23932
+ markClaimed(runId, stageId, entry);
23646
23933
  return entry?.handle;
23647
23934
  },
23648
23935
  get(runId, stageId) {
@@ -23699,12 +23986,14 @@ function createStageControlRegistry() {
23699
23986
  for (const [stageId, entry] of entries) {
23700
23987
  if (entry === undefined)
23701
23988
  continue;
23989
+ entry.releaseWanted = true;
23702
23990
  try {
23703
23991
  await releaseIdleEntry(runId, stageId, entry);
23704
23992
  } catch (error) {
23705
23993
  console.warn("atomic-workflows: completed stage session release failed", error);
23706
23994
  }
23707
23995
  }
23996
+ await Promise.allSettled([...pendingDisposals]);
23708
23997
  },
23709
23998
  onStageReleased(listener) {
23710
23999
  releaseListeners.add(listener);
@@ -23714,7 +24003,7 @@ function createStageControlRegistry() {
23714
24003
  }
23715
24004
  };
23716
24005
  }
23717
- var SESSION_KEY4 = "workflows:stage-control:v1", singleton4, stageControlRegistry;
24006
+ var CLAIM_GRACE_MS = 1e4, SESSION_KEY4 = "workflows:stage-control:v1", singleton4, stageControlRegistry;
23718
24007
  var init_stage_control_registry = __esm(() => {
23719
24008
  init_session_scoped_singleton();
23720
24009
  singleton4 = createSessionScopedSingleton(SESSION_KEY4, createStageControlRegistry);
@@ -70994,6 +71283,7 @@ function createStagePathPatternIndex(patterns) {
70994
71283
  }
70995
71284
  var ADDRESSABLE_STAGE_STATUSES;
70996
71285
  var init_pending_stage_status = __esm(() => {
71286
+ init_run_stage_index();
70997
71287
  init_store_internal();
70998
71288
  init_workflow_run_ownership();
70999
71289
  init_workflow_stage_target();
@@ -72742,9 +73032,9 @@ function isBrokerProtocolRange(value2) {
72742
73032
  function protocolRangeOf(value2) {
72743
73033
  return value2 === undefined ? LEGACY_BROKER_PROTOCOL : { min: value2.min, max: value2.max };
72744
73034
  }
72745
- var BROKER_PROTOCOL, LEGACY_BROKER_PROTOCOL, VERIFIED_REGISTRATION_PROTOCOL = 2;
73035
+ var BROKER_PROTOCOL, LEGACY_BROKER_PROTOCOL, VERIFIED_REGISTRATION_PROTOCOL = 2, HOSTED_SESSIONS_PROTOCOL = 3;
72746
73036
  var init_protocol_version = __esm(() => {
72747
- BROKER_PROTOCOL = { min: 1, max: 2 };
73037
+ BROKER_PROTOCOL = { min: 1, max: 3 };
72748
73038
  LEGACY_BROKER_PROTOCOL = { min: 1, max: 1 };
72749
73039
  });
72750
73040
 
@@ -73061,6 +73351,30 @@ function isSessionInfo(value2) {
73061
73351
  return false;
73062
73352
  return session.status === undefined || typeof session.status === "string";
73063
73353
  }
73354
+ function isSessionRegistration(value2) {
73355
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) {
73356
+ return false;
73357
+ }
73358
+ const session = value2;
73359
+ if (typeof session.cwd !== "string" || typeof session.model !== "string" || typeof session.pid !== "number" || typeof session.startedAt !== "number" || typeof session.lastActivity !== "number") {
73360
+ return false;
73361
+ }
73362
+ if (session.name !== undefined && typeof session.name !== "string") {
73363
+ return false;
73364
+ }
73365
+ if (session.group !== undefined && typeof session.group !== "string") {
73366
+ return false;
73367
+ }
73368
+ if (session.replyCapability !== undefined && session.replyCapability !== "live" && session.replyCapability !== "terminal")
73369
+ return false;
73370
+ if (session.recipientPurpose !== undefined && session.recipientPurpose !== "agent" && session.recipientPurpose !== "control") {
73371
+ return false;
73372
+ }
73373
+ if (session.groups !== undefined && (!Array.isArray(session.groups) || !session.groups.every((group) => typeof group === "string"))) {
73374
+ return false;
73375
+ }
73376
+ return session.status === undefined || typeof session.status === "string";
73377
+ }
73064
73378
 
73065
73379
  // dist/builtin/intercom/broker/delivery-failure-reason.ts
73066
73380
  function isDeliveryFailureReasonCode(value2) {
@@ -73074,7 +73388,8 @@ var init_delivery_failure_reason = __esm(() => {
73074
73388
  "recipient_not_restored",
73075
73389
  "recipient_parked",
73076
73390
  "released_reply_answered",
73077
- "released_reply_in_flight"
73391
+ "released_reply_in_flight",
73392
+ "not_hosted_by_connection"
73078
73393
  ]);
73079
73394
  });
73080
73395
 
@@ -73299,6 +73614,8 @@ function isIntercomRecipientGoneErrorCode(value2) {
73299
73614
  return CODES5.has(value2);
73300
73615
  }
73301
73616
  function hintFor3(code, childId) {
73617
+ if (code === "recipient_stage_released")
73618
+ return "Send to its workflow stage target (workflow:<rootRunId>/<stage>), which reaches the stage's current session or queues until it reopens, or resume the run.";
73302
73619
  if (code === "recipient_cancelled")
73303
73620
  return "It cannot be resumed; launch a fresh subagent if its work is still needed.";
73304
73621
  if (code === "recipient_disconnected")
@@ -73310,7 +73627,9 @@ function hintFor3(code, childId) {
73310
73627
  function rehydrateIntercomRecipientGoneError(serialized) {
73311
73628
  const options = serialized.cause === undefined ? undefined : { cause: rehydrateCause3(serialized.cause, 1) };
73312
73629
  const { code, fields } = serialized;
73313
- if (serialized.name === ENDED_NAME && code !== "recipient_disconnected" && code !== "recipient_owner_suspended")
73630
+ if (serialized.name === STAGE_RELEASED_NAME && code === "recipient_stage_released")
73631
+ return new StageRecipientReleasedError(fields, options);
73632
+ if (serialized.name === ENDED_NAME && code !== "recipient_disconnected" && code !== "recipient_owner_suspended" && code !== "recipient_stage_released")
73314
73633
  return new SubagentRecipientEndedError(code, fields, options);
73315
73634
  if (serialized.name === DISCONNECTED_NAME && code === "recipient_disconnected")
73316
73635
  return new SubagentRecipientDisconnectedError(fields, options);
@@ -73358,7 +73677,7 @@ function readSerializedIntercomRecipientGoneError(value2) {
73358
73677
  ...cause === undefined ? {} : { cause }
73359
73678
  };
73360
73679
  }
73361
- var INTERCOM_RECIPIENT_GONE_ERROR_CODES, CODES5, WHAT, BASE_NAME3 = "IntercomRecipientGoneError", ENDED_NAME = "SubagentRecipientEndedError", DISCONNECTED_NAME = "SubagentRecipientDisconnectedError", OWNER_SUSPENDED_NAME = "SubagentRecipientOwnerSuspendedError", IntercomRecipientGoneError, SubagentRecipientEndedError, SubagentRecipientDisconnectedError, SubagentRecipientOwnerSuspendedError, NAMES4, ENDED_NAMES, DISCONNECTED_NAMES, OWNER_SUSPENDED_NAMES, MAX_CAUSE_DEPTH11 = 4, isWireObject2 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73680
+ var INTERCOM_RECIPIENT_GONE_ERROR_CODES, CODES5, WHAT, BASE_NAME3 = "IntercomRecipientGoneError", ENDED_NAME = "SubagentRecipientEndedError", DISCONNECTED_NAME = "SubagentRecipientDisconnectedError", OWNER_SUSPENDED_NAME = "SubagentRecipientOwnerSuspendedError", STAGE_RELEASED_NAME = "StageRecipientReleasedError", IntercomRecipientGoneError, SubagentRecipientEndedError, SubagentRecipientDisconnectedError, SubagentRecipientOwnerSuspendedError, StageRecipientReleasedError, NAMES4, STAGE_RELEASED_NAMES, ENDED_NAMES, DISCONNECTED_NAMES, OWNER_SUSPENDED_NAMES, MAX_CAUSE_DEPTH11 = 4, isWireObject2 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
73362
73681
  var init_recipient_gone_errors = __esm(() => {
73363
73682
  init_released_child_errors();
73364
73683
  INTERCOM_RECIPIENT_GONE_ERROR_CODES = [
@@ -73367,7 +73686,8 @@ var init_recipient_gone_errors = __esm(() => {
73367
73686
  "recipient_stopped",
73368
73687
  "recipient_cancelled",
73369
73688
  "recipient_disconnected",
73370
- "recipient_owner_suspended"
73689
+ "recipient_owner_suspended",
73690
+ "recipient_stage_released"
73371
73691
  ];
73372
73692
  CODES5 = new Set(INTERCOM_RECIPIENT_GONE_ERROR_CODES);
73373
73693
  WHAT = {
@@ -73376,7 +73696,8 @@ var init_recipient_gone_errors = __esm(() => {
73376
73696
  recipient_stopped: "was stopped (paused or quit) and has no live session",
73377
73697
  recipient_cancelled: "was cancelled for good and has no live session",
73378
73698
  recipient_disconnected: "disconnected and has not reconnected",
73379
- recipient_owner_suspended: "is released and the session that launched it is suspended or disconnected, so nothing can wake it now"
73699
+ recipient_owner_suspended: "is released and the session that launched it is suspended or disconnected, so nothing can wake it now",
73700
+ recipient_stage_released: "was released and the session that answered for it has gone away"
73380
73701
  };
73381
73702
  IntercomRecipientGoneError = class IntercomRecipientGoneError extends Error {
73382
73703
  name = BASE_NAME3;
@@ -73388,7 +73709,8 @@ var init_recipient_gone_errors = __esm(() => {
73388
73709
  childId;
73389
73710
  constructor(code, fields, options) {
73390
73711
  const hint = hintFor3(code, fields.childId);
73391
- super(`Subagent ${JSON.stringify(fields.childName)} ${WHAT[code]} (${code}). ${hint}`, options);
73712
+ const subject = code === "recipient_stage_released" ? "Workflow stage" : "Subagent";
73713
+ super(`${subject} ${JSON.stringify(fields.childName)} ${WHAT[code]} (${code}). ${hint}`, options);
73392
73714
  this.code = code;
73393
73715
  this.hint = hint;
73394
73716
  this.retryable = code === "recipient_disconnected" || code === "recipient_owner_suspended";
@@ -73422,34 +73744,25 @@ var init_recipient_gone_errors = __esm(() => {
73422
73744
  super("recipient_owner_suspended", fields, options);
73423
73745
  }
73424
73746
  };
73425
- NAMES4 = new Set([BASE_NAME3, ENDED_NAME, DISCONNECTED_NAME, OWNER_SUSPENDED_NAME]);
73747
+ StageRecipientReleasedError = class StageRecipientReleasedError extends IntercomRecipientGoneError {
73748
+ name = STAGE_RELEASED_NAME;
73749
+ constructor(fields, options) {
73750
+ super("recipient_stage_released", fields, options);
73751
+ }
73752
+ };
73753
+ NAMES4 = new Set([
73754
+ BASE_NAME3,
73755
+ ENDED_NAME,
73756
+ DISCONNECTED_NAME,
73757
+ OWNER_SUSPENDED_NAME,
73758
+ STAGE_RELEASED_NAME
73759
+ ]);
73760
+ STAGE_RELEASED_NAMES = new Set([STAGE_RELEASED_NAME]);
73426
73761
  ENDED_NAMES = new Set([ENDED_NAME]);
73427
73762
  DISCONNECTED_NAMES = new Set([DISCONNECTED_NAME]);
73428
73763
  OWNER_SUSPENDED_NAMES = new Set([OWNER_SUSPENDED_NAME]);
73429
73764
  });
73430
73765
 
73431
- // dist/builtin/intercom/group.ts
73432
- function normalizeGroup2(value2) {
73433
- if (typeof value2 !== "string")
73434
- return DEFAULT_GROUP;
73435
- const trimmed = value2.trim();
73436
- return trimmed.length > 0 ? trimmed : DEFAULT_GROUP;
73437
- }
73438
- function normalizeGroups(values, legacyGroup) {
73439
- const groups = new Set;
73440
- for (const value2 of values ?? [])
73441
- groups.add(normalizeGroup2(value2));
73442
- if (legacyGroup !== undefined)
73443
- groups.add(normalizeGroup2(legacyGroup));
73444
- if (groups.size === 0)
73445
- groups.add(DEFAULT_GROUP);
73446
- return groups;
73447
- }
73448
- var DEFAULT_GROUP = "default", RESERVED_RUNTIME_GROUPS;
73449
- var init_group = __esm(() => {
73450
- RESERVED_RUNTIME_GROUPS = new Set(["true", "auto"]);
73451
- });
73452
-
73453
73766
  // dist/builtin/intercom/live-route-refusal.ts
73454
73767
  function isLiveWorkflowStageRouteRefusalCode(value2) {
73455
73768
  return typeof value2 === "string" && LIVE_WORKFLOW_STAGE_ROUTE_REFUSAL_CODES.includes(value2);
@@ -73495,6 +73808,202 @@ var init_live_route_refusal = __esm(() => {
73495
73808
  };
73496
73809
  });
73497
73810
 
73811
+ // dist/builtin/intercom/broker/hosted-sessions.ts
73812
+ function parseLiveRoute(value2) {
73813
+ if (!isWireObject3(value2))
73814
+ return false;
73815
+ const { runId, stageKeys, capability } = value2;
73816
+ if (!isNonEmptyString(runId) || !isNonEmptyString(capability) || !Array.isArray(stageKeys))
73817
+ return false;
73818
+ if (stageKeys.length < 1 || stageKeys.length > 2 || !stageKeys.every(isNonEmptyString))
73819
+ return false;
73820
+ return { runId, stageKeys, capability };
73821
+ }
73822
+ function validateHostSessionsFrame(sessions) {
73823
+ if (!Array.isArray(sessions) || sessions.length === 0 || sessions.length > HOSTED_SESSION_FRAME_MAX) {
73824
+ return { ok: false, refusal: { code: "invalid_hosted_frame" } };
73825
+ }
73826
+ const keys = new Set;
73827
+ const parsed = [];
73828
+ for (const item of sessions) {
73829
+ if (!isWireObject3(item) || !isNonEmptyString(item.key) || keys.has(item.key)) {
73830
+ return {
73831
+ ok: false,
73832
+ refusal: isWireObject3(item) && typeof item.key === "string" ? { code: "invalid_hosted_frame", key: item.key } : { code: "invalid_hosted_frame" }
73833
+ };
73834
+ }
73835
+ const key = item.key;
73836
+ keys.add(key);
73837
+ const invalid = { ok: false, refusal: { code: "invalid_hosted_session", key } };
73838
+ const { session, returnAddress } = item;
73839
+ if (!isSessionRegistration(session) || !isNonEmptyString(session.name) || session.recipientPurpose === "control") {
73840
+ return invalid;
73841
+ }
73842
+ if (returnAddress !== undefined && !isNonEmptyString(returnAddress))
73843
+ return invalid;
73844
+ const liveRoute = item.liveRoute === undefined ? undefined : parseLiveRoute(item.liveRoute);
73845
+ if (liveRoute === false)
73846
+ return invalid;
73847
+ parsed.push({
73848
+ key,
73849
+ session,
73850
+ ...returnAddress === undefined ? {} : { returnAddress },
73851
+ ...liveRoute === undefined ? {} : { liveRoute }
73852
+ });
73853
+ }
73854
+ return { ok: true, sessions: parsed };
73855
+ }
73856
+ function readHostedSessionAssignments(value2) {
73857
+ if (!Array.isArray(value2))
73858
+ return;
73859
+ const assignments = [];
73860
+ for (const item of value2) {
73861
+ if (!isWireObject3(item) || typeof item.key !== "string" || !isNonEmptyString(item.sessionId))
73862
+ return;
73863
+ const { liveRouteRefusal } = item;
73864
+ if (liveRouteRefusal !== undefined && !isLiveWorkflowStageRouteRefusalCode(liveRouteRefusal))
73865
+ return;
73866
+ assignments.push({
73867
+ key: item.key,
73868
+ sessionId: item.sessionId,
73869
+ ...liveRouteRefusal === undefined ? {} : { liveRouteRefusal }
73870
+ });
73871
+ }
73872
+ return assignments;
73873
+ }
73874
+ var HOSTED_SESSION_FRAME_MAX = 500, isWireObject3 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2), isNonEmptyString = (value2) => typeof value2 === "string" && value2.trim().length > 0;
73875
+ var init_hosted_sessions = __esm(() => {
73876
+ init_live_route_refusal();
73877
+ });
73878
+
73879
+ // dist/builtin/intercom/broker/hosted-session-errors.ts
73880
+ function isHostedSessionErrorCode(value2) {
73881
+ return CODES6.has(value2);
73882
+ }
73883
+ function fieldsOf(refusal) {
73884
+ return {
73885
+ ...refusal.key === undefined ? {} : { key: refusal.key },
73886
+ ...refusal.sessionId === undefined ? {} : { sessionId: refusal.sessionId }
73887
+ };
73888
+ }
73889
+ function hostedSessionErrorFor(refusal, options) {
73890
+ return refusal.code === "not_hosted_by_connection" ? new NotHostedSessionError(fieldsOf(refusal), options) : new HostedSessionRequestError(refusal.code, fieldsOf(refusal), options);
73891
+ }
73892
+ function rehydrateIntercomHostedSessionError(serialized) {
73893
+ const options = serialized.cause === undefined ? undefined : { cause: rehydrateCause3(serialized.cause, 1) };
73894
+ if (serialized.name === NOT_HOSTED_NAME)
73895
+ return new NotHostedSessionError(serialized.fields, options);
73896
+ if (serialized.name === REQUEST_NAME)
73897
+ return new HostedSessionRequestError(serialized.code, serialized.fields, options);
73898
+ const error = new IntercomHostedSessionError(serialized.code, serialized.fields, options);
73899
+ Object.defineProperty(error, "name", { value: serialized.name });
73900
+ return error;
73901
+ }
73902
+ function readHostedSessionRefusal(value2) {
73903
+ if (!isWireObject3(value2))
73904
+ return;
73905
+ const { code, key, sessionId } = value2;
73906
+ if (typeof code !== "string" || !isHostedSessionErrorCode(code))
73907
+ return;
73908
+ if (key !== undefined && typeof key !== "string" || sessionId !== undefined && typeof sessionId !== "string") {
73909
+ return;
73910
+ }
73911
+ return { code, ...key === undefined ? {} : { key }, ...sessionId === undefined ? {} : { sessionId } };
73912
+ }
73913
+ function readSerializedIntercomHostedSessionError(value2) {
73914
+ if (!isWireObject3(value2))
73915
+ return;
73916
+ const { name, code, message, hint, retryable, fields } = value2;
73917
+ if (typeof name !== "string" || typeof code !== "string" || !isHostedSessionErrorCode(code))
73918
+ return;
73919
+ if (typeof message !== "string" || typeof hint !== "string" || retryable !== false)
73920
+ return;
73921
+ const refusal = isWireObject3(fields) ? readHostedSessionRefusal({ ...fields, code }) : undefined;
73922
+ if (refusal === undefined)
73923
+ return;
73924
+ const cause = readCause(value2.cause, 1);
73925
+ if (cause === false)
73926
+ return;
73927
+ return {
73928
+ name,
73929
+ code,
73930
+ message,
73931
+ hint,
73932
+ retryable: false,
73933
+ fields: fieldsOf(refusal),
73934
+ ...cause === undefined ? {} : { cause }
73935
+ };
73936
+ }
73937
+ var HOSTED_SESSION_ERROR_CODES, CODES6, HINTS6, BASE_NAME4 = "IntercomHostedSessionError", REQUEST_NAME = "HostedSessionRequestError", NOT_HOSTED_NAME = "NotHostedSessionError", IntercomHostedSessionError, HostedSessionRequestError, NotHostedSessionError, NAMES5, REQUEST_NAMES, NOT_HOSTED_NAMES;
73938
+ var init_hosted_session_errors = __esm(() => {
73939
+ init_hosted_sessions();
73940
+ init_released_child_errors();
73941
+ init_released_reply_errors();
73942
+ HOSTED_SESSION_ERROR_CODES = [
73943
+ "invalid_hosted_frame",
73944
+ "invalid_hosted_session",
73945
+ "not_hosted_by_connection"
73946
+ ];
73947
+ CODES6 = new Set(HOSTED_SESSION_ERROR_CODES);
73948
+ HINTS6 = {
73949
+ invalid_hosted_frame: "Send between 1 and 500 sessions per frame, each under a distinct non-empty key, or 1 to 500 session ids to remove.",
73950
+ invalid_hosted_session: "Give each hosted session a non-empty name and a valid agent registration (cwd, model, pid and timestamps).",
73951
+ not_hosted_by_connection: "Only the connection that hosts a session may send as it or remove it; host the session again after a reconnect."
73952
+ };
73953
+ IntercomHostedSessionError = class IntercomHostedSessionError extends Error {
73954
+ name = BASE_NAME4;
73955
+ code;
73956
+ hint;
73957
+ retryable = false;
73958
+ key;
73959
+ sessionId;
73960
+ constructor(code, fields = {}, options) {
73961
+ const subject = fields.key !== undefined ? `hosted session ${JSON.stringify(fields.key)}` : fields.sessionId !== undefined ? `session ${JSON.stringify(fields.sessionId)}` : "request";
73962
+ super(`Hosted-session request refused: ${subject} (${code}). ${HINTS6[code]}`, options);
73963
+ this.code = code;
73964
+ this.hint = HINTS6[code];
73965
+ if (fields.key !== undefined)
73966
+ this.key = fields.key;
73967
+ if (fields.sessionId !== undefined)
73968
+ this.sessionId = fields.sessionId;
73969
+ }
73970
+ };
73971
+ HostedSessionRequestError = class HostedSessionRequestError extends IntercomHostedSessionError {
73972
+ name = REQUEST_NAME;
73973
+ };
73974
+ NotHostedSessionError = class NotHostedSessionError extends IntercomHostedSessionError {
73975
+ name = NOT_HOSTED_NAME;
73976
+ constructor(fields, options) {
73977
+ super("not_hosted_by_connection", fields, options);
73978
+ }
73979
+ };
73980
+ NAMES5 = new Set([BASE_NAME4, REQUEST_NAME, NOT_HOSTED_NAME]);
73981
+ REQUEST_NAMES = new Set([REQUEST_NAME]);
73982
+ NOT_HOSTED_NAMES = new Set([NOT_HOSTED_NAME]);
73983
+ });
73984
+
73985
+ // dist/builtin/intercom/group.ts
73986
+ function normalizeGroup2(value2) {
73987
+ if (typeof value2 !== "string")
73988
+ return DEFAULT_GROUP;
73989
+ const trimmed = value2.trim();
73990
+ return trimmed.length > 0 ? trimmed : DEFAULT_GROUP;
73991
+ }
73992
+ function normalizeGroups(values, legacyGroup) {
73993
+ const groups = new Set;
73994
+ for (const value2 of values ?? [])
73995
+ groups.add(normalizeGroup2(value2));
73996
+ if (legacyGroup !== undefined)
73997
+ groups.add(normalizeGroup2(legacyGroup));
73998
+ if (groups.size === 0)
73999
+ groups.add(DEFAULT_GROUP);
74000
+ return groups;
74001
+ }
74002
+ var DEFAULT_GROUP = "default", RESERVED_RUNTIME_GROUPS;
74003
+ var init_group = __esm(() => {
74004
+ RESERVED_RUNTIME_GROUPS = new Set(["true", "auto"]);
74005
+ });
74006
+
73498
74007
  // dist/builtin/intercom/recoverable-disconnect.ts
73499
74008
  function isIntercomBrokerRetiring(error) {
73500
74009
  let current = error;
@@ -73557,6 +74066,30 @@ var init_pending_stage_route_timeout_error = __esm(() => {
73557
74066
  };
73558
74067
  });
73559
74068
 
74069
+ // dist/builtin/intercom/hosted-session-timeout-error.ts
74070
+ var HOSTED_SESSION_TIMEOUT_HINT = "Hosting is tried again on the next connection; run `atomic intercom restart` if the broker keeps timing out.", IntercomHostedSessionTimeoutError;
74071
+ var init_hosted_session_timeout_error = __esm(() => {
74072
+ init_recoverable_disconnect();
74073
+ IntercomHostedSessionTimeoutError = class IntercomHostedSessionTimeoutError extends IntercomBrokerTimeoutError {
74074
+ name = "IntercomHostedSessionTimeoutError";
74075
+ code = "hosted_session_timeout";
74076
+ phase = "hosted-session-request";
74077
+ retryable = true;
74078
+ hint = HOSTED_SESSION_TIMEOUT_HINT;
74079
+ requestType;
74080
+ sessionCount;
74081
+ timeoutMs;
74082
+ elapsedMs;
74083
+ constructor(fields, options) {
74084
+ super(`Hosted-session request timed out: ${fields.requestType} for ${fields.sessionCount} sessions, unanswered after ${fields.elapsedMs} ms of ${fields.timeoutMs} ms (hosted_session_timeout). ${HOSTED_SESSION_TIMEOUT_HINT}`, options);
74085
+ this.requestType = fields.requestType;
74086
+ this.sessionCount = fields.sessionCount;
74087
+ this.timeoutMs = fields.timeoutMs;
74088
+ this.elapsedMs = fields.elapsedMs;
74089
+ }
74090
+ };
74091
+ });
74092
+
73560
74093
  // dist/builtin/intercom/broker/socket-liveness.ts
73561
74094
  import net from "net";
73562
74095
  function isSocketAnswering(socketPath, timeoutMs = SOCKET_PROBE_TIMEOUT_MS) {
@@ -73695,9 +74228,12 @@ var init_client = __esm(() => {
73695
74228
  init_released_reply_errors();
73696
74229
  init_released_children();
73697
74230
  init_recipient_gone_errors();
74231
+ init_hosted_session_errors();
74232
+ init_hosted_sessions();
73698
74233
  init_group();
73699
74234
  init_recoverable_disconnect();
73700
74235
  init_pending_stage_route_timeout_error();
74236
+ init_hosted_session_timeout_error();
73701
74237
  init_socket_liveness();
73702
74238
  init_protocol_version();
73703
74239
  init_live_route_refusal();
@@ -73706,6 +74242,7 @@ var init_client = __esm(() => {
73706
74242
  init_released_child_errors();
73707
74243
  init_recipient_gone_errors();
73708
74244
  init_released_reply_errors();
74245
+ init_hosted_session_errors();
73709
74246
  ConnectionClosedBeforeRegistrationError = class ConnectionClosedBeforeRegistrationError extends Error {
73710
74247
  constructor() {
73711
74248
  super("Connection closed before registration");
@@ -73763,6 +74300,7 @@ var init_client = __esm(() => {
73763
74300
  pendingStageRouteRegistrations = new Map;
73764
74301
  pendingSupervisorAuthorizations = new Map;
73765
74302
  pendingRestoringRecipientRequests = new Map;
74303
+ pendingHostedSessionRequests = new Map;
73766
74304
  disconnecting = false;
73767
74305
  disconnectError = null;
73768
74306
  healthCheck;
@@ -73822,6 +74360,8 @@ var init_client = __esm(() => {
73822
74360
  pending.reject(error);
73823
74361
  for (const pending of this.pendingRestoringRecipientRequests.values())
73824
74362
  pending.reject(error);
74363
+ for (const pending of this.pendingHostedSessionRequests.values())
74364
+ pending.reject(error);
73825
74365
  for (const pending of this.pendingPresence.values())
73826
74366
  pending.reject(error);
73827
74367
  for (const pending of this.pendingMemberships.values())
@@ -73838,6 +74378,7 @@ var init_client = __esm(() => {
73838
74378
  this.pendingGroupLists.clear();
73839
74379
  this.pendingSupervisorAuthorizations.clear();
73840
74380
  this.pendingRestoringRecipientRequests.clear();
74381
+ this.pendingHostedSessionRequests.clear();
73841
74382
  this.pendingPresence.clear();
73842
74383
  this.pendingMemberships.clear();
73843
74384
  this.pendingLiveWorkflowStageRoutes.clear();
@@ -74170,11 +74711,14 @@ var init_client = __esm(() => {
74170
74711
  break;
74171
74712
  }
74172
74713
  case "message": {
74173
- const { from, message, channel } = brokerMessage;
74174
- if (!isSessionInfo(from) || !isMessage(message) || channel !== undefined && channel !== "supervisor") {
74714
+ const { from, message, channel, hostedRecipient } = brokerMessage;
74715
+ if (!isSessionInfo(from) || !isMessage(message) || channel !== undefined && channel !== "supervisor" || hostedRecipient !== undefined && typeof hostedRecipient !== "string") {
74175
74716
  throw new Error("Invalid message event");
74176
74717
  }
74177
- this.emit("message", from, message, channel);
74718
+ if (hostedRecipient !== undefined)
74719
+ this.emit("hosted_message", hostedRecipient, from, message, channel);
74720
+ else
74721
+ this.emit("message", from, message, channel);
74178
74722
  break;
74179
74723
  }
74180
74724
  case "pending_stage_message": {
@@ -74319,6 +74863,23 @@ var init_client = __esm(() => {
74319
74863
  this.emit("released_child_reply", notice);
74320
74864
  break;
74321
74865
  }
74866
+ case "hosted_sessions_ack": {
74867
+ const { requestId, refusal, sessions } = brokerMessage;
74868
+ const parsedRefusal = readHostedSessionRefusal(refusal);
74869
+ const assignments = sessions === undefined ? [] : readHostedSessionAssignments(sessions);
74870
+ if (typeof requestId !== "string" || refusal !== undefined && parsedRefusal === undefined || assignments === undefined) {
74871
+ throw new Error("Invalid hosted_sessions_ack message");
74872
+ }
74873
+ const pending = this.pendingHostedSessionRequests.get(requestId);
74874
+ if (!pending)
74875
+ return;
74876
+ this.pendingHostedSessionRequests.delete(requestId);
74877
+ if (parsedRefusal === undefined)
74878
+ pending.resolve(assignments);
74879
+ else
74880
+ pending.reject(hostedSessionErrorFor(parsedRefusal));
74881
+ break;
74882
+ }
74322
74883
  case "released_children_ack": {
74323
74884
  const { requestId, refusal } = brokerMessage;
74324
74885
  const parsed = refusal === undefined ? undefined : readReleasedChildRefusal(refusal);
@@ -74365,7 +74926,9 @@ var init_client = __esm(() => {
74365
74926
  case "delivery_failed": {
74366
74927
  const { messageId, attemptId, reason, reasonCode } = brokerMessage;
74367
74928
  const wireError = brokerMessage.error;
74368
- const error = readSerializedIntercomReleasedReplyError(wireError);
74929
+ const releasedReplyError = readSerializedIntercomReleasedReplyError(wireError);
74930
+ const hostedSessionError = readSerializedIntercomHostedSessionError(wireError);
74931
+ const error = releasedReplyError ?? hostedSessionError;
74369
74932
  const wireRecipientError = brokerMessage.recipientError;
74370
74933
  const recipientError = readSerializedIntercomRecipientGoneError(wireRecipientError);
74371
74934
  if (typeof messageId !== "string" || attemptId !== undefined && typeof attemptId !== "string" || typeof reason !== "string" || reasonCode !== undefined && (typeof reasonCode !== "string" || !isDeliveryFailureReasonCode(reasonCode)) || wireError !== undefined && (error === undefined || error.code !== reasonCode) || wireRecipientError !== undefined && (recipientError === undefined || reasonCode !== undefined)) {
@@ -74376,7 +74939,8 @@ var init_client = __esm(() => {
74376
74939
  delivered: false,
74377
74940
  reason,
74378
74941
  ...reasonCode === undefined ? {} : { reasonCode },
74379
- ...error === undefined ? {} : { error: rehydrateIntercomReleasedReplyError(error) },
74942
+ ...releasedReplyError === undefined ? {} : { error: rehydrateIntercomReleasedReplyError(releasedReplyError) },
74943
+ ...hostedSessionError === undefined ? {} : { error: rehydrateIntercomHostedSessionError(hostedSessionError) },
74380
74944
  ...recipientError === undefined ? {} : { reasonCode: recipientError.code, error: rehydrateIntercomRecipientGoneError(recipientError) }
74381
74945
  };
74382
74946
  if (attemptId === undefined)
@@ -74786,15 +75350,76 @@ var init_client = __esm(() => {
74786
75350
  });
74787
75351
  return true;
74788
75352
  }
74789
- requireBrokerProtocol(feature) {
75353
+ requireBrokerProtocol(feature, requiredProtocol = VERIFIED_REGISTRATION_PROTOCOL) {
74790
75354
  const broker = this._brokerProtocol;
74791
- if (this._sessionId === null || broker.max >= VERIFIED_REGISTRATION_PROTOCOL)
75355
+ if (this._sessionId === null || broker.max >= requiredProtocol)
74792
75356
  return;
74793
75357
  throw new IntercomBrokerProtocolError({
74794
75358
  feature,
74795
75359
  brokerProtocolMin: broker.min,
74796
75360
  brokerProtocolMax: broker.max,
74797
- requiredProtocol: VERIFIED_REGISTRATION_PROTOCOL
75361
+ requiredProtocol
75362
+ });
75363
+ }
75364
+ async hostSessions(sessions) {
75365
+ this.requireBrokerProtocol("host_sessions", HOSTED_SESSIONS_PROTOCOL);
75366
+ const frames = [];
75367
+ for (let start = 0;start < sessions.length; start += HOSTED_SESSION_FRAME_MAX) {
75368
+ const frame = sessions.slice(start, start + HOSTED_SESSION_FRAME_MAX);
75369
+ const wire = JSON.parse(JSON.stringify(frame));
75370
+ const validation = validateHostSessionsFrame(wire);
75371
+ if (!validation.ok)
75372
+ throw hostedSessionErrorFor(validation.refusal);
75373
+ frames.push(frame);
75374
+ }
75375
+ const assigned = [];
75376
+ for (const frame of frames)
75377
+ assigned.push(...await this.hostedSessionRequest({ type: "host_sessions", sessions: frame }));
75378
+ return assigned;
75379
+ }
75380
+ async unhostSessions(sessionIds) {
75381
+ this.requireBrokerProtocol("unhost_sessions", HOSTED_SESSIONS_PROTOCOL);
75382
+ if (sessionIds.length === 0)
75383
+ throw new HostedSessionRequestError("invalid_hosted_frame");
75384
+ for (let start = 0;start < sessionIds.length; start += HOSTED_SESSION_FRAME_MAX) {
75385
+ await this.hostedSessionRequest({
75386
+ type: "unhost_sessions",
75387
+ sessionIds: sessionIds.slice(start, start + HOSTED_SESSION_FRAME_MAX)
75388
+ });
75389
+ }
75390
+ }
75391
+ hostedSessionRequest(frame) {
75392
+ const socket = this.requireActiveSocket();
75393
+ const requestId = randomUUID15();
75394
+ const startedAt = performance.now();
75395
+ return new Promise((resolve, reject) => {
75396
+ const timeout = setTimeout(() => {
75397
+ this.pendingHostedSessionRequests.delete(requestId);
75398
+ const timedOut = {
75399
+ requestType: frame.type === "unhost_sessions" ? "unhost_sessions" : "host_sessions",
75400
+ sessionCount: Array.isArray(frame.sessions) ? frame.sessions.length : Array.isArray(frame.sessionIds) ? frame.sessionIds.length : 0,
75401
+ timeoutMs: RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS,
75402
+ elapsedMs: Math.round(performance.now() - startedAt)
75403
+ };
75404
+ this.requestTimeout(socket, new IntercomHostedSessionTimeoutError(timedOut)).then((error) => reject(error instanceof IntercomBrokerTimeoutError && !(error instanceof IntercomHostedSessionTimeoutError) ? new IntercomHostedSessionTimeoutError(timedOut, { cause: error }) : error));
75405
+ }, RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS);
75406
+ this.pendingHostedSessionRequests.set(requestId, {
75407
+ resolve: (sessions) => {
75408
+ clearTimeout(timeout);
75409
+ resolve([...sessions]);
75410
+ },
75411
+ reject: (error) => {
75412
+ clearTimeout(timeout);
75413
+ reject(error);
75414
+ }
75415
+ });
75416
+ try {
75417
+ writeMessage(socket, { ...frame, requestId });
75418
+ } catch (error) {
75419
+ clearTimeout(timeout);
75420
+ this.pendingHostedSessionRequests.delete(requestId);
75421
+ reject(toError(error));
75422
+ }
74798
75423
  });
74799
75424
  }
74800
75425
  restoringRecipientRequest(frame) {
@@ -75053,6 +75678,7 @@ var init_client = __esm(() => {
75053
75678
  ...options.expectedRecipientId === undefined ? {} : { expectedRecipientId: options.expectedRecipientId },
75054
75679
  ...options.onReplyTarget === undefined ? {} : { resolveReplyTarget: true },
75055
75680
  ...type === "send" ? { awaitRestoringRecipient: true } : {},
75681
+ hostedSender: options.hostedSender,
75056
75682
  message,
75057
75683
  attemptId: acquired.attempt.attemptId,
75058
75684
  ...extra
@@ -89757,6 +90383,66 @@ var init_stage_runner = __esm(() => {
89757
90383
  init_stage_runner_context();
89758
90384
  });
89759
90385
 
90386
+ // dist/builtin/workflows/src/runs/foreground/stage-session-holds.ts
90387
+ class StageSessionHolds {
90388
+ subscribers = 0;
90389
+ operations = 0;
90390
+ taken = 0;
90391
+ listeners = new Set;
90392
+ get held() {
90393
+ return this.subscribers > 0 || this.operations > 0;
90394
+ }
90395
+ get holdsTaken() {
90396
+ return this.taken;
90397
+ }
90398
+ subscription(unsubscribe) {
90399
+ this.subscribers += 1;
90400
+ this.taken += 1;
90401
+ let active = true;
90402
+ return () => {
90403
+ if (!active)
90404
+ return;
90405
+ active = false;
90406
+ this.subscribers -= 1;
90407
+ unsubscribe();
90408
+ this.lifted();
90409
+ };
90410
+ }
90411
+ async operation(operation) {
90412
+ this.operations += 1;
90413
+ this.taken += 1;
90414
+ try {
90415
+ return await operation();
90416
+ } finally {
90417
+ this.operations -= 1;
90418
+ this.lifted();
90419
+ }
90420
+ }
90421
+ observe(event) {
90422
+ switch (event.type) {
90423
+ case "agent_end":
90424
+ case "agent_settled":
90425
+ case "queue_update":
90426
+ case "compaction_end":
90427
+ case "auto_retry_end":
90428
+ this.lifted();
90429
+ }
90430
+ }
90431
+ onLifted(listener) {
90432
+ this.listeners.add(listener);
90433
+ return () => {
90434
+ this.listeners.delete(listener);
90435
+ };
90436
+ }
90437
+ clear() {
90438
+ this.listeners.clear();
90439
+ }
90440
+ lifted() {
90441
+ for (const listener of [...this.listeners])
90442
+ listener();
90443
+ }
90444
+ }
90445
+
89760
90446
  // dist/builtin/workflows/src/runs/foreground/postmortem-stage-chat.ts
89761
90447
  import { withWorktreeRootMappings as withWorktreeRootMappings2 } from "@bastani/atomic";
89762
90448
  async function reopenableSessionStore(runId, stageId, sessionId, deps) {
@@ -89834,8 +90520,12 @@ function createPostMortemStageHandle(runId, stage, sessionId, adapters, cwd, def
89834
90520
  }
89835
90521
  };
89836
90522
  const queuedUserMessages = new StageQueuedUserMessageBuffer;
89837
- const unsubscribeQueuedUserMessages = context.subscribe((event) => queuedUserMessages.record(event));
89838
- return {
90523
+ const holds = new StageSessionHolds;
90524
+ const unsubscribeQueuedUserMessages = context.subscribe((event) => {
90525
+ queuedUserMessages.record(event);
90526
+ holds.observe(event);
90527
+ });
90528
+ const handle = {
89839
90529
  runId,
89840
90530
  stageId: stage.id,
89841
90531
  stageName: stage.name,
@@ -89893,20 +90583,45 @@ function createPostMortemStageHandle(runId, stage, sessionId, adapters, cwd, def
89893
90583
  throw new Error("Post-mortem stage chat cannot pause or resume workflow execution.");
89894
90584
  },
89895
90585
  subscribe(listener) {
89896
- return context.subscribe(listener);
90586
+ return holds.subscription(context.subscribe(listener));
89897
90587
  },
89898
90588
  subscribeDeliveryActivity(listener) {
89899
- return context.__subscribeDeliveryActivity(listener);
90589
+ return holds.subscription(context.__subscribeDeliveryActivity(listener));
89900
90590
  },
89901
90591
  async dispose() {
89902
90592
  if (disposed)
89903
90593
  return;
89904
90594
  disposed = true;
90595
+ holds.clear();
89905
90596
  unsubscribeQueuedUserMessages();
89906
90597
  queuedUserMessages.clear();
89907
90598
  await context.__dispose();
90599
+ },
90600
+ releaseGate: {
90601
+ releaseWhenIdle: true,
90602
+ async savedForReopen() {
90603
+ if (disposed)
90604
+ return;
90605
+ const store = context.__persistedSessionStore() ?? sessionStore;
90606
+ const savedSessionId = context.__sessionMeta().sessionId ?? sessionId;
90607
+ if (store === undefined)
90608
+ return;
90609
+ return await isReopenableSession(store, savedSessionId) ? store : undefined;
90610
+ },
90611
+ idle() {
90612
+ return !disposed && !holds.held && stageQueuedUserMessageCount(queuedUserMessages.snapshot()) === 0 && (context.__sessionMeta().sessionId === undefined || context.__idleForRelease());
90613
+ },
90614
+ holdsTaken: () => holds.holdsTaken,
90615
+ onHoldLifted: (listener) => holds.onLifted(listener)
89908
90616
  }
89909
90617
  };
90618
+ const { sendUserMessage, prompt, steer, followUp } = handle;
90619
+ handle.ensureAttached = () => holds.operation(ensureAttached);
90620
+ handle.sendUserMessage = (text, options, beforeDelivery) => holds.operation(() => sendUserMessage(text, options, beforeDelivery));
90621
+ handle.prompt = (text) => holds.operation(() => prompt(text));
90622
+ handle.steer = (text) => holds.operation(() => steer(text));
90623
+ handle.followUp = (text) => holds.operation(() => followUp(text));
90624
+ return handle;
89910
90625
  }
89911
90626
  var TERMINAL_POSTMORTEM_STATUSES;
89912
90627
  var init_postmortem_stage_chat = __esm(() => {
@@ -94372,7 +95087,7 @@ function createWorkflowBoundaryFactory(input) {
94372
95087
  stageSnapshot.durationMs = elapsedStageMs(stageSnapshot, stageSnapshot.endedAt);
94373
95088
  }
94374
95089
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
94375
- input.opts.onStageEnd?.(input.runId, stageSnapshot);
95090
+ endStageWithHook(input.activeStore, input.runId, stageSnapshot, input.opts.onStageEnd);
94376
95091
  await appendStageEndForSnapshot();
94377
95092
  input.tracker.onSettle(stageId);
94378
95093
  })();
@@ -94398,7 +95113,7 @@ function createWorkflowBoundaryFactory(input) {
94398
95113
  finalized = true;
94399
95114
  unregisterWorkflowExitCleanup();
94400
95115
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
94401
- input.opts.onStageEnd?.(input.runId, stageSnapshot);
95116
+ endStageWithHook(input.activeStore, input.runId, stageSnapshot, input.opts.onStageEnd);
94402
95117
  await appendStageEndForSnapshot();
94403
95118
  input.tracker.onSettle(stageId);
94404
95119
  })();
@@ -95415,9 +96130,11 @@ function createStageControlHandle(runtime) {
95415
96130
  };
95416
96131
  const toolExecutions = new StageToolExecutionBuffer;
95417
96132
  const queuedUserMessages = new StageQueuedUserMessageBuffer;
96133
+ const holds = new StageSessionHolds;
95418
96134
  const unsubscribeStageEvents = runtime.innerCtx.subscribe((event) => {
95419
96135
  toolExecutions.record(event);
95420
96136
  queuedUserMessages.record(event);
96137
+ holds.observe(event);
95421
96138
  if (event.type === "task_cleanup_quarantined")
95422
96139
  runtime.activeStore.recordStageNotice(runtime.runId, runtime.stageId, {
95423
96140
  id: crypto.randomUUID(),
@@ -95429,27 +96146,6 @@ function createStageControlHandle(runtime) {
95429
96146
  if (event.type === "background_compaction")
95430
96147
  runtime.activeStore.recordStageCompaction(runtime.runId, runtime.stageId, event.compaction);
95431
96148
  });
95432
- let externalSubscribers = 0;
95433
- const countSubscription = (unsubscribe) => {
95434
- externalSubscribers += 1;
95435
- let active = true;
95436
- return () => {
95437
- if (!active)
95438
- return;
95439
- active = false;
95440
- externalSubscribers -= 1;
95441
- unsubscribe();
95442
- };
95443
- };
95444
- let activeOperations = 0;
95445
- const tracked = async (operation) => {
95446
- activeOperations += 1;
95447
- try {
95448
- return await operation();
95449
- } finally {
95450
- activeOperations -= 1;
95451
- }
95452
- };
95453
96149
  const sessionSaved = () => runtime.stageSnapshot.status === "completed" && runtime.state.stageFinalized && runtime.state.sessionCheckpointed && !runtime.state.liveHandleReleased && !runtime.state.stageClosedByWorkflowExit;
95454
96150
  const handle = {
95455
96151
  runId: runtime.runId,
@@ -95645,12 +96341,13 @@ function createStageControlHandle(runtime) {
95645
96341
  }
95646
96342
  },
95647
96343
  subscribe(listener) {
95648
- return countSubscription(runtime.innerCtx.subscribe(listener));
96344
+ return holds.subscription(runtime.innerCtx.subscribe(listener));
95649
96345
  },
95650
96346
  subscribeDeliveryActivity(listener) {
95651
- return countSubscription(runtime.innerCtx.__subscribeDeliveryActivity(listener));
96347
+ return holds.subscription(runtime.innerCtx.__subscribeDeliveryActivity(listener));
95652
96348
  },
95653
96349
  async dispose() {
96350
+ holds.clear();
95654
96351
  unsubscribeStageEvents();
95655
96352
  toolExecutions.clear();
95656
96353
  queuedUserMessages.clear();
@@ -95667,18 +96364,20 @@ function createStageControlHandle(runtime) {
95667
96364
  return await isReopenableSession(store, sessionId) ? store : undefined;
95668
96365
  },
95669
96366
  idle() {
95670
- return sessionSaved() && externalSubscribers === 0 && activeOperations === 0 && stageQueuedUserMessageCount(queuedUserMessages.snapshot()) === 0 && !runtime.state.waitingForStageChatTurn && runtime.state.wakeWaitingForStageChatTurn === undefined && runtime.state.readinessController === undefined && runtime.state.resumeContinuationPending === false && runtime.innerCtx.__idleForRelease();
95671
- }
96367
+ return sessionSaved() && !holds.held && stageQueuedUserMessageCount(queuedUserMessages.snapshot()) === 0 && !runtime.state.waitingForStageChatTurn && runtime.state.wakeWaitingForStageChatTurn === undefined && runtime.state.readinessController === undefined && runtime.state.resumeContinuationPending === false && runtime.innerCtx.__idleForRelease();
96368
+ },
96369
+ holdsTaken: () => holds.holdsTaken,
96370
+ onHoldLifted: (listener) => holds.onLifted(listener)
95672
96371
  }
95673
96372
  };
95674
96373
  const { ensureAttached, sendUserMessage, prompt, steer, followUp, pause, resume } = handle;
95675
- handle.ensureAttached = () => tracked(ensureAttached);
95676
- handle.sendUserMessage = (text, options, beforeDelivery) => tracked(() => sendUserMessage(text, options, beforeDelivery));
95677
- handle.prompt = (text) => tracked(() => prompt(text));
95678
- handle.steer = (text, options) => tracked(() => steer(text, options));
95679
- handle.followUp = (text, options) => tracked(() => followUp(text, options));
95680
- handle.pause = () => tracked(pause);
95681
- handle.resume = (message, beforeResume) => tracked(() => resume(message, beforeResume));
96374
+ handle.ensureAttached = () => holds.operation(ensureAttached);
96375
+ handle.sendUserMessage = (text, options, beforeDelivery) => holds.operation(() => sendUserMessage(text, options, beforeDelivery));
96376
+ handle.prompt = (text) => holds.operation(() => prompt(text));
96377
+ handle.steer = (text, options) => holds.operation(() => steer(text, options));
96378
+ handle.followUp = (text, options) => holds.operation(() => followUp(text, options));
96379
+ handle.pause = () => holds.operation(pause);
96380
+ handle.resume = (message, beforeResume) => holds.operation(() => resume(message, beforeResume));
95682
96381
  return handle;
95683
96382
  }
95684
96383
  var init_executor_stage_control = __esm(() => {
@@ -95733,7 +96432,7 @@ function createReplayStageContext(input) {
95733
96432
  stageSnapshot.skippedReason = input.workflowExitSkippedReason(reason);
95734
96433
  }
95735
96434
  input.activeStore.recordStageEnd(runId, stageSnapshot);
95736
- input.opts.onStageEnd?.(runId, stageSnapshot);
96435
+ endStageWithHook(input.activeStore, runId, stageSnapshot, input.opts.onStageEnd);
95737
96436
  await appendReplayStageEnd();
95738
96437
  input.tracker.onSettle(stageId);
95739
96438
  })();
@@ -95998,26 +96697,8 @@ function createWorkflowStageFactory(input) {
95998
96697
  if (keptResults !== undefined)
95999
96698
  stageSnapshot.waitResults = recordStageWaitToolResults(keptResults);
96000
96699
  const applyModelFallbackMeta = (meta) => {
96001
- if (meta.model !== undefined)
96002
- stageSnapshot.model = meta.model;
96003
- if (meta.thinkingLevel !== undefined)
96004
- stageSnapshot.thinkingLevel = meta.thinkingLevel;
96005
- else
96006
- delete stageSnapshot.thinkingLevel;
96007
- if (meta.attemptedModels !== undefined)
96008
- stageSnapshot.attemptedModels = meta.attemptedModels;
96009
- if (meta.modelAttempts !== undefined)
96010
- stageSnapshot.modelAttempts = meta.modelAttempts;
96011
- if (meta.rateLimits !== undefined)
96012
- stageSnapshot.rateLimits = meta.rateLimits;
96013
- if (meta.routerSelection !== undefined)
96014
- stageSnapshot.routerSelection = meta.routerSelection;
96015
- if (meta.warnings !== undefined) {
96016
- if (meta.warnings.length > 0)
96017
- stageSnapshot.warnings = meta.warnings;
96018
- else
96019
- delete stageSnapshot.warnings;
96020
- }
96700
+ if (applyModelFallbackMetaToStage(stageSnapshot, meta))
96701
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96021
96702
  };
96022
96703
  let runtime;
96023
96704
  const emitLifecycleEvent = (event) => {
@@ -96119,10 +96800,12 @@ function createWorkflowStageFactory(input) {
96119
96800
  },
96120
96801
  async recordResults(_wait, results) {
96121
96802
  stageSnapshot.waitResults = recordStageWaitToolResults(results);
96803
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96122
96804
  await recordWait("wait-results");
96123
96805
  },
96124
96806
  resultsInTranscript() {
96125
96807
  delete stageSnapshot.waitResults;
96808
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96126
96809
  },
96127
96810
  async leave() {
96128
96811
  waitRecordMissing = false;
@@ -96307,13 +96990,13 @@ function createWorkflowStageFactory(input) {
96307
96990
  };
96308
96991
  const captureStageSessionMeta = async (checkpointOptions) => {
96309
96992
  const meta = innerCtx.__sessionMeta();
96310
- if (meta.sessionId !== undefined)
96311
- stageSnapshot.sessionId = meta.sessionId;
96312
- if (meta.sessionFile !== undefined)
96313
- stageSnapshot.sessionFile = meta.sessionFile;
96993
+ const changed = applySessionMetaToStage(stageSnapshot, meta);
96314
96994
  if (meta.sessionId !== undefined)
96315
96995
  input.activeStore.recordStageSession(input.runId, stageId, { sessionId: meta.sessionId });
96996
+ if (changed)
96997
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96316
96998
  const pending = input.opts.onStageSession?.(input.runId, stageSnapshot, checkpointOptions);
96999
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96317
97000
  if (checkpointOptions?.forceDurable === true || checkpointOptions?.awaitDurable === true) {
96318
97001
  await pending;
96319
97002
  return;
@@ -96388,6 +97071,7 @@ function createWorkflowStageFactory(input) {
96388
97071
  input.stageUiBroker.clearStageStatuses(input.runId, stageId);
96389
97072
  if (input.opts.onStageEnd) {
96390
97073
  await runCallback3({ kind: "workflow.stage_adapter", name: `onStageEnd:${name}`, runId: input.runId, stageId }, () => input.opts.onStageEnd(input.runId, stageSnapshot));
97074
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96391
97075
  }
96392
97076
  if (input.opts.persistence) {
96393
97077
  await appendStageStartOnce();