@bastani/atomic 0.9.78-alpha.1 → 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 +58 -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
@@ -856,8 +856,11 @@ function stageIdentity(checkpoint) {
856
856
  function checkpointKey(c) {
857
857
  return `${c.kind}:${c.checkpointId}`;
858
858
  }
859
+ function sharingOutputAsResult(checkpoint) {
860
+ return checkpoint.kind === "stage" && typeof checkpoint.output === "string" && checkpoint.result === checkpoint.output ? { ...checkpoint, result: checkpoint.output } : checkpoint;
861
+ }
859
862
  function normalizedCheckpoint(recorded) {
860
- const checkpoint = recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded;
863
+ const checkpoint = sharingOutputAsResult(recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded);
861
864
  return checkpoint.kind === "stage" && checkpoint.topology === undefined ? {
862
865
  ...checkpoint,
863
866
  topology: {
@@ -2227,6 +2230,25 @@ function writtenHandle(event) {
2227
2230
  return;
2228
2231
  return event.payload;
2229
2232
  }
2233
+ function sharingWrittenText(entry, written) {
2234
+ const folded = entry.event;
2235
+ if (folded.type !== RUN_EVENT_TYPES.checkpointRecorded || written.type !== RUN_EVENT_TYPES.checkpointRecorded)
2236
+ return entry;
2237
+ const decoded = folded.payload;
2238
+ const source = written.payload;
2239
+ if (decoded.kind !== "stage" || source.kind !== "stage")
2240
+ return entry;
2241
+ const sharesOutput = typeof source.output === "string" && decoded.output === source.output;
2242
+ const sharesResult = typeof source.result === "string" && decoded.result === source.result;
2243
+ if (!sharesOutput && !sharesResult)
2244
+ return entry;
2245
+ const payload = {
2246
+ ...decoded,
2247
+ ...sharesOutput ? { output: source.output } : {},
2248
+ ...sharesResult ? { result: source.result } : {}
2249
+ };
2250
+ return { ...entry, event: { ...folded, payload } };
2251
+ }
2230
2252
  function snapshotNeedsHistory(tail) {
2231
2253
  const handle = writtenHandle(tail.snapshot.event);
2232
2254
  return handle !== undefined && (handle.pendingStageMessageChange !== undefined || hasPendingStageDeliveryDelta(handle.pendingStageMessages));
@@ -2651,7 +2673,7 @@ class JournalDurableBackend {
2651
2673
  for (const entry of yield* this.entries(runId, nextSeq))
2652
2674
  this.fold(entry);
2653
2675
  }
2654
- this.fold(outcome.entry);
2676
+ this.fold(sharingWrittenText(outcome.entry, event));
2655
2677
  } catch (error) {
2656
2678
  if (error instanceof Error)
2657
2679
  throw yield* this.mapOwnership(error, runId);
@@ -2894,7 +2916,7 @@ class JournalDurableBackend {
2894
2916
  if (result.value.entry.seq > nextSeq)
2895
2917
  for (const entry of yield* this.entries(runId, nextSeq))
2896
2918
  this.fold(entry);
2897
- this.fold(result.value.entry);
2919
+ this.fold(sharingWrittenText(result.value.entry, append.event));
2898
2920
  append.resolve();
2899
2921
  }
2900
2922
  settled++;
@@ -9698,11 +9720,22 @@ function index(items, cache) {
9698
9720
  }
9699
9721
  return byId;
9700
9722
  }
9723
+ function markPublishedSnapshotArray(items) {
9724
+ publishedSnapshotArrays.add(items);
9725
+ }
9726
+ function isPublishedSnapshotArray(items) {
9727
+ return publishedSnapshotArrays.has(items);
9728
+ }
9729
+ function frozenIndex(items, cache) {
9730
+ return cache.get(items) ?? (isPublishedSnapshotArray(items) || Object.isFrozen(items) ? index(items, cache) : undefined);
9731
+ }
9701
9732
  function findSnapshotRun(runs, runId) {
9702
- return Object.isFrozen(runs) ? index(runs, runIndexes).get(runId) : runs.find((run) => run.id === runId);
9733
+ const byId = frozenIndex(runs, runIndexes);
9734
+ return byId === undefined ? runs.find((run) => run.id === runId) : byId.get(runId);
9703
9735
  }
9704
9736
  function findSnapshotStage(stages, stageId) {
9705
- return Object.isFrozen(stages) ? index(stages, stageIndexes).get(stageId) : stages.find((stage) => stage.id === stageId);
9737
+ const byId = frozenIndex(stages, stageIndexes);
9738
+ return byId === undefined ? stages.find((stage) => stage.id === stageId) : byId.get(stageId);
9706
9739
  }
9707
9740
  function childRunsInSource(source, parentRunId, parentStageId) {
9708
9741
  if (isRunLookup(source) && source.childRuns !== undefined)
@@ -9727,10 +9760,11 @@ function invocationRunsInSource(source, rootRunId) {
9727
9760
  }
9728
9761
  return found.filter(inInvocation).sort((left, right) => source.runPosition(left.id) - source.runPosition(right.id));
9729
9762
  }
9730
- var runIndexes, stageIndexes;
9763
+ var runIndexes, stageIndexes, publishedSnapshotArrays;
9731
9764
  var init_workflow_run_ownership = __esm(() => {
9732
9765
  runIndexes = new WeakMap;
9733
9766
  stageIndexes = new WeakMap;
9767
+ publishedSnapshotArrays = new WeakSet;
9734
9768
  });
9735
9769
 
9736
9770
  // dist/builtin/workflows/src/durable/prompt-reservations.ts
@@ -10036,6 +10070,53 @@ function flattenTruncatedString(value2) {
10036
10070
  return value2.split("").join("");
10037
10071
  }
10038
10072
 
10073
+ // dist/builtin/workflows/src/shared/run-stage-index.ts
10074
+ function asksForInput(stage) {
10075
+ return stage.pendingPrompt !== undefined || stage.inputRequest !== undefined || stage.status === "awaiting_input" || stage.awaitingInputSince !== undefined;
10076
+ }
10077
+ function isFinished(stage) {
10078
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
10079
+ }
10080
+ function indexFrom(stages, asking, unfinished) {
10081
+ const pending = [];
10082
+ const waiting = [];
10083
+ for (const position of unfinished) {
10084
+ const stage = stages[position];
10085
+ if (stage.status === "pending")
10086
+ pending.push(stage);
10087
+ if (asksForInput(stage))
10088
+ waiting.push(stage);
10089
+ }
10090
+ return { index: { awaitingInput: asking > 0, pending, waiting }, asking, unfinished };
10091
+ }
10092
+ function indexRunFrom(run, previous, changed, appendedFrom) {
10093
+ const known = indexes.get(previous);
10094
+ if (known === undefined || !Object.isFrozen(run))
10095
+ return;
10096
+ let asking = known.asking;
10097
+ const unfinished = new Set(known.unfinished);
10098
+ const update = (position, before) => {
10099
+ const stage = run.stages[position];
10100
+ if (before !== undefined && asksForInput(before))
10101
+ asking--;
10102
+ if (asksForInput(stage))
10103
+ asking++;
10104
+ if (isFinished(stage))
10105
+ unfinished.delete(position);
10106
+ else
10107
+ unfinished.add(position);
10108
+ };
10109
+ for (const position of changed)
10110
+ update(position, previous.stages[position]);
10111
+ for (let position = appendedFrom;position < run.stages.length; position++)
10112
+ update(position, undefined);
10113
+ indexes.set(run, indexFrom(run.stages, asking, [...unfinished].sort((left, right) => left - right)));
10114
+ }
10115
+ var indexes;
10116
+ var init_run_stage_index = __esm(() => {
10117
+ indexes = new WeakMap;
10118
+ });
10119
+
10039
10120
  // dist/builtin/workflows/src/shared/tool-payload-bounds.ts
10040
10121
  function isOmittedJsonValue(value2) {
10041
10122
  return value2 === undefined || typeof value2 === "function" || typeof value2 === "symbol";
@@ -10384,25 +10465,42 @@ function sameSourceShape(value2, shape) {
10384
10465
  }
10385
10466
  return index === shape.keys.length;
10386
10467
  }
10468
+ function isSettledStage(stage) {
10469
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
10470
+ }
10387
10471
  function projectStage(stage) {
10472
+ const compact = compactStage(stage);
10473
+ deepFreezeGraphValue(compact);
10388
10474
  return {
10389
10475
  shape: sourceShape(stage),
10390
10476
  parentCount: stage.parentIds.length,
10391
10477
  toolEventCount: stage.toolEvents.length,
10392
10478
  lastToolEvent: stage.toolEvents.at(-1),
10393
10479
  noticeCount: stage.notices?.length,
10394
- compact: compactStage(stage)
10480
+ settled: isSettledStage(stage),
10481
+ compact
10395
10482
  };
10396
10483
  }
10397
10484
  function stageUnchanged(stage, projected) {
10398
10485
  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;
10399
10486
  }
10400
10487
  function projectToolNode(node) {
10401
- return { shape: sourceShape(node), parentCount: node.parentIds.length, compact: compactToolNode(node) };
10488
+ const compact = compactToolNode(node);
10489
+ deepFreezeGraphValue(compact);
10490
+ return { shape: sourceShape(node), parentCount: node.parentIds.length, compact };
10402
10491
  }
10403
10492
  function toolNodeUnchanged(node, projected) {
10404
10493
  return sameSourceShape(node, projected.shape) && node.parentIds.length === projected.parentCount;
10405
10494
  }
10495
+ function freezeCompactRun(run) {
10496
+ for (const [key, value2] of Object.entries(run)) {
10497
+ if (key === "stages" || key === "toolNodes")
10498
+ markPublishedSnapshotArray(value2);
10499
+ else
10500
+ deepFreezeGraphValue(value2);
10501
+ }
10502
+ Object.freeze(run);
10503
+ }
10406
10504
 
10407
10505
  class GraphStoreSnapshotBuilder {
10408
10506
  projected = new Map;
@@ -10431,9 +10529,7 @@ class GraphStoreSnapshotBuilder {
10431
10529
  const next = new Map;
10432
10530
  const compactRuns = [];
10433
10531
  for (const run of runs) {
10434
- const known = previous.get(run.id);
10435
- const reusable = known?.source === run ? known : undefined;
10436
- const projected = reusable !== undefined && !this.changedRuns.has(run.id) && this.runUnchanged(run, reusable) ? reusable : this.projectRun(run, reusable);
10532
+ const projected = this.refreshRun(run, previous.get(run.id));
10437
10533
  next.set(run.id, projected);
10438
10534
  compactRuns.push(projected.compact);
10439
10535
  }
@@ -10441,38 +10537,36 @@ class GraphStoreSnapshotBuilder {
10441
10537
  this.changedRuns.clear();
10442
10538
  this.changedStages.clear();
10443
10539
  this.changedToolNodes.clear();
10444
- const snapshot = {
10445
- runs: compactRuns,
10446
- notices: notices.map((notice) => ({ ...notice })),
10540
+ const compactNotices = notices.map((notice) => ({ ...notice }));
10541
+ deepFreezeGraphValue(compactNotices);
10542
+ const snapshot = Object.freeze({
10543
+ runs: Object.freeze(compactRuns),
10544
+ notices: compactNotices,
10447
10545
  version
10448
- };
10449
- deepFreezeGraphValue(snapshot);
10546
+ });
10547
+ snapshotLineages.set(snapshot, this);
10450
10548
  return snapshot;
10451
10549
  }
10452
10550
  buildRun(run) {
10453
- const known = this.projected.get(run.id);
10454
- const reusable = known?.source === run ? known : undefined;
10455
- const projected = reusable !== undefined && !this.changedRuns.has(run.id) && this.runUnchanged(run, reusable) ? reusable : this.projectRun(run, reusable);
10456
- deepFreezeGraphValue(projected.compact);
10551
+ const projected = this.refreshRun(run, this.projected.get(run.id));
10457
10552
  this.projected.set(run.id, projected);
10458
10553
  this.changedRuns.delete(run.id);
10459
10554
  this.changedStages.delete(run.id);
10460
10555
  this.changedToolNodes.delete(run.id);
10461
10556
  return projected.compact;
10462
10557
  }
10463
- runUnchanged(run, projected) {
10464
- if (!sameSourceShape(run, projected.shape))
10465
- return false;
10466
- const { stages, toolNodes } = projected.compact;
10467
- if (run.stages.length !== stages.length || run.toolNodes.length !== toolNodes.length)
10558
+ refreshRun(run, known) {
10559
+ const reusable = known?.source === run ? known : undefined;
10560
+ if (reusable === undefined || this.changedRuns.has(run.id) || !sameSourceShape(run, reusable.shape))
10561
+ return this.projectRun(run, reusable);
10562
+ if (!this.toolNodesUnchanged(run, reusable))
10563
+ return this.projectRun(run, reusable);
10564
+ return this.patchStages(run, reusable) ?? this.projectRun(run, reusable);
10565
+ }
10566
+ toolNodesUnchanged(run, projected) {
10567
+ const { toolNodes } = projected.compact;
10568
+ if (run.toolNodes.length !== toolNodes.length)
10468
10569
  return false;
10469
- const changedStages = this.changedStages.get(run.id);
10470
- for (let index = 0;index < run.stages.length; index++) {
10471
- const stage = run.stages[index];
10472
- const known = projected.stages.get(stage);
10473
- if (known === undefined || known.compact !== stages[index] || changedStages?.has(stage.id) === true || !stageUnchanged(stage, known))
10474
- return false;
10475
- }
10476
10570
  const changedToolNodes = this.changedToolNodes.get(run.id);
10477
10571
  for (let index = 0;index < run.toolNodes.length; index++) {
10478
10572
  const node = run.toolNodes[index];
@@ -10482,15 +10576,86 @@ class GraphStoreSnapshotBuilder {
10482
10576
  }
10483
10577
  return true;
10484
10578
  }
10579
+ patchStages(run, projected) {
10580
+ const sources = projected.stageSources;
10581
+ if (run.stages.length < sources.length)
10582
+ return;
10583
+ for (let index = 0;index < sources.length; index++)
10584
+ if (run.stages[index] !== sources[index])
10585
+ return;
10586
+ const changed = new Set;
10587
+ const scoped = this.changedStages.get(run.id);
10588
+ if (scoped !== undefined) {
10589
+ if (projected.duplicateStageIds)
10590
+ return;
10591
+ for (const id of scoped) {
10592
+ const position = projected.stagePositions.get(id);
10593
+ if (position !== undefined)
10594
+ changed.add(position);
10595
+ }
10596
+ }
10597
+ for (const position of projected.unsettled)
10598
+ if (!changed.has(position) && !stageUnchanged(sources[position], projected.stages[position]))
10599
+ changed.add(position);
10600
+ if (changed.size === 0 && run.stages.length === sources.length)
10601
+ return projected;
10602
+ const previous = projected.compact;
10603
+ const appendedFrom = sources.length;
10604
+ const compactStages = previous.stages.slice();
10605
+ for (const position of changed) {
10606
+ const stage = projectStage(sources[position]);
10607
+ projected.stages[position] = stage;
10608
+ compactStages[position] = stage.compact;
10609
+ if (stage.settled)
10610
+ projected.unsettled.delete(position);
10611
+ else
10612
+ projected.unsettled.add(position);
10613
+ }
10614
+ for (let position = sources.length;position < run.stages.length; position++) {
10615
+ const source = run.stages[position];
10616
+ const stage = projectStage(source);
10617
+ sources.push(source);
10618
+ projected.stages.push(stage);
10619
+ compactStages.push(stage.compact);
10620
+ if (!stage.settled)
10621
+ projected.unsettled.add(position);
10622
+ if (projected.stagePositions.has(source.id))
10623
+ projected.duplicateStageIds = true;
10624
+ else
10625
+ projected.stagePositions.set(source.id, position);
10626
+ }
10627
+ const compact = { ...previous, stages: compactStages };
10628
+ freezeCompactRun(compact);
10629
+ indexRunFrom(compact, previous, changed, appendedFrom);
10630
+ projected.compact = compact;
10631
+ return projected;
10632
+ }
10485
10633
  projectRun(run, previous) {
10486
10634
  const changedStages = this.changedStages.get(run.id);
10487
- const stages = new Map;
10635
+ const previousStages = new Map;
10636
+ if (previous !== undefined)
10637
+ for (let index = 0;index < previous.stageSources.length; index++)
10638
+ previousStages.set(previous.stageSources[index], previous.stages[index]);
10639
+ const stageSources = [];
10640
+ const stages = [];
10641
+ const stagePositions = new Map;
10642
+ const unsettled = new Set;
10643
+ let duplicateStageIds = false;
10488
10644
  const compactStages = [];
10489
10645
  for (const stage of run.stages) {
10490
- let projected = stages.get(stage) ?? previous?.stages.get(stage);
10646
+ let projected = previousStages.get(stage);
10491
10647
  if (projected === undefined || changedStages?.has(stage.id) === true || !stageUnchanged(stage, projected))
10492
10648
  projected = projectStage(stage);
10493
- stages.set(stage, projected);
10649
+ previousStages.set(stage, projected);
10650
+ const position = stages.length;
10651
+ stageSources.push(stage);
10652
+ stages.push(projected);
10653
+ if (!projected.settled)
10654
+ unsettled.add(position);
10655
+ if (stagePositions.has(stage.id))
10656
+ duplicateStageIds = true;
10657
+ else
10658
+ stagePositions.set(stage.id, position);
10494
10659
  compactStages.push(projected.compact);
10495
10660
  }
10496
10661
  const changedToolNodes = this.changedToolNodes.get(run.id);
@@ -10503,12 +10668,18 @@ class GraphStoreSnapshotBuilder {
10503
10668
  toolNodes.set(node, projected);
10504
10669
  compactToolNodes.push(projected.compact);
10505
10670
  }
10671
+ const compact = compactRun(run, compactStages, compactToolNodes);
10672
+ freezeCompactRun(compact);
10506
10673
  return {
10507
10674
  source: run,
10508
10675
  shape: sourceShape(run),
10676
+ stageSources,
10509
10677
  stages,
10678
+ stagePositions,
10679
+ duplicateStageIds,
10680
+ unsettled,
10510
10681
  toolNodes,
10511
- compact: compactRun(run, compactStages, compactToolNodes)
10682
+ compact
10512
10683
  };
10513
10684
  }
10514
10685
  }
@@ -10532,18 +10703,25 @@ function deepFreezeGraphValue(value2) {
10532
10703
  deepFreezeGraphValue(value2[key]);
10533
10704
  }
10534
10705
  }
10535
- var COMPACT_RESULT_FIELD_LIMIT = 1024, COMPACT_EXIT_OUTPUT_LIMIT;
10706
+ var COMPACT_RESULT_FIELD_LIMIT = 1024, COMPACT_EXIT_OUTPUT_LIMIT, snapshotLineages;
10536
10707
  var init_graph_store_snapshot = __esm(() => {
10708
+ init_run_stage_index();
10537
10709
  init_tool_payload_bounds();
10710
+ init_workflow_run_ownership();
10538
10711
  COMPACT_EXIT_OUTPUT_LIMIT = COMPACT_RESULT_FIELD_LIMIT * 4;
10712
+ snapshotLineages = new WeakMap;
10539
10713
  });
10540
10714
 
10541
10715
  // dist/builtin/workflows/src/shared/expanded-workflow-graph.ts
10542
- var leafExpansions, snapshotExpansions;
10716
+ var leafExpansions, snapshotExpansions, settledStageCounts, expandedStageLists, chainExpansions;
10543
10717
  var init_expanded_workflow_graph = __esm(() => {
10718
+ init_graph_store_snapshot();
10544
10719
  init_workflow_run_ownership();
10545
10720
  leafExpansions = new WeakMap;
10546
10721
  snapshotExpansions = new WeakMap;
10722
+ settledStageCounts = new WeakMap;
10723
+ expandedStageLists = new WeakSet;
10724
+ chainExpansions = new WeakMap;
10547
10725
  });
10548
10726
 
10549
10727
  // dist/builtin/workflows/src/shared/workflow-activity.ts
@@ -21556,6 +21734,55 @@ function reconcileTerminalRunResult(runId, runSnapshot, activeStore, fallback, o
21556
21734
  onRunEnd?.(runId, result.status, result.result, result.error, result.exitReason);
21557
21735
  return result;
21558
21736
  }
21737
+ function announceSettledStageEdit(store, runId, stage) {
21738
+ if (isTerminalStageStatus(stage.status))
21739
+ store.editRun(runId, () => ({ stageIds: [stage.id] }));
21740
+ }
21741
+ function endStageWithHook(store, runId, stage, hook) {
21742
+ const outcome = hook?.(runId, stage);
21743
+ announceSettledStageEdit(store, runId, stage);
21744
+ if (!isPromiseLike(outcome))
21745
+ return;
21746
+ Promise.resolve(outcome).then(() => announceSettledStageEdit(store, runId, stage), (error) => {
21747
+ announceSettledStageEdit(store, runId, stage);
21748
+ throw error;
21749
+ });
21750
+ }
21751
+ function isPromiseLike(value2) {
21752
+ return (typeof value2 === "object" || typeof value2 === "function") && value2 !== null && typeof value2.then === "function";
21753
+ }
21754
+ function applyModelFallbackMetaToStage(stage, meta) {
21755
+ const { model, thinkingLevel, rateLimits, routerSelection, warnings } = stage;
21756
+ if (meta.model !== undefined)
21757
+ stage.model = meta.model;
21758
+ if (meta.thinkingLevel !== undefined)
21759
+ stage.thinkingLevel = meta.thinkingLevel;
21760
+ else
21761
+ delete stage.thinkingLevel;
21762
+ if (meta.attemptedModels !== undefined)
21763
+ stage.attemptedModels = meta.attemptedModels;
21764
+ if (meta.modelAttempts !== undefined)
21765
+ stage.modelAttempts = meta.modelAttempts;
21766
+ if (meta.rateLimits !== undefined)
21767
+ stage.rateLimits = meta.rateLimits;
21768
+ if (meta.routerSelection !== undefined)
21769
+ stage.routerSelection = meta.routerSelection;
21770
+ if (meta.warnings !== undefined) {
21771
+ if (meta.warnings.length > 0)
21772
+ stage.warnings = meta.warnings;
21773
+ else
21774
+ delete stage.warnings;
21775
+ }
21776
+ return model !== stage.model || thinkingLevel !== stage.thinkingLevel || rateLimits !== stage.rateLimits || routerSelection !== stage.routerSelection || warnings !== stage.warnings;
21777
+ }
21778
+ function applySessionMetaToStage(stage, meta) {
21779
+ const { sessionId, sessionFile } = stage;
21780
+ if (meta.sessionId !== undefined)
21781
+ stage.sessionId = meta.sessionId;
21782
+ if (meta.sessionFile !== undefined)
21783
+ stage.sessionFile = meta.sessionFile;
21784
+ return sessionId !== stage.sessionId || sessionFile !== stage.sessionFile;
21785
+ }
21559
21786
  function applyFailureToStage(stage, failure) {
21560
21787
  stage.status = "failed";
21561
21788
  stage.error = failure.userMessage;
@@ -22255,6 +22482,7 @@ function buildPromptNodeUiAdapter(input) {
22255
22482
  input.activeStore.recordStageAttachable(input.runId, stageId, false);
22256
22483
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
22257
22484
  await input.opts.onStageEnd?.(input.runId, stageSnapshot);
22485
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
22258
22486
  if (input.opts.persistence) {
22259
22487
  await appendStageEnd(input.opts.persistence, {
22260
22488
  runId: input.runId,
@@ -22610,15 +22838,17 @@ function createStageScheduler(input) {
22610
22838
  };
22611
22839
  const descendantsOf = (stageId) => input.runSnapshot.stages.filter((stage) => stage.id !== stageId && hasAncestor(stage, stageId));
22612
22840
  const blockingAncestorFor = (stage) => {
22841
+ const holding = new Set(input.runSnapshot.stages.filter((candidate) => candidate.status === "paused" || candidate.status === "blocked").map((candidate) => candidate.id));
22842
+ if (holding.size === 0)
22843
+ return;
22613
22844
  const queue = [...stage.parentIds];
22614
22845
  const seen = new Set;
22615
- while (queue.length > 0) {
22616
- const next = queue.shift();
22617
- if (next === undefined || seen.has(next))
22846
+ for (let index = 0;index < queue.length; index++) {
22847
+ const next = queue[index];
22848
+ if (seen.has(next))
22618
22849
  continue;
22619
22850
  seen.add(next);
22620
- const ancestor = stageById(next);
22621
- if (ancestor?.status === "paused" || ancestor?.status === "blocked")
22851
+ if (holding.has(next))
22622
22852
  return next;
22623
22853
  queue.push(...input.tracker.getParents(next));
22624
22854
  }
@@ -23408,7 +23638,44 @@ function createStageControlRegistry() {
23408
23638
  return [];
23409
23639
  return [...runMap.values()].filter((entry) => entry.controlsDependencies);
23410
23640
  }
23641
+ function createEntry(runId, stageId, handle, fields) {
23642
+ const entry = { handle, ...fields, leases: new Set, epoch: 0 };
23643
+ entry.stopWatching = handle.releaseGate?.onHoldLifted(() => releaseWhenLetGo(runId, stageId, entry));
23644
+ return entry;
23645
+ }
23646
+ function stopWatching(entry) {
23647
+ entry.stopWatching?.();
23648
+ entry.stopWatching = undefined;
23649
+ clearTimeout(entry.claimTimer);
23650
+ entry.claimTimer = undefined;
23651
+ }
23652
+ function markClaimed(runId, stageId, entry) {
23653
+ entry.permanent = true;
23654
+ entry.epoch += 1;
23655
+ entry.holdsAtClaim = entry.handle.releaseGate?.holdsTaken();
23656
+ clearTimeout(entry.claimTimer);
23657
+ if (entry.handle.releaseGate === undefined)
23658
+ return;
23659
+ entry.claimTimer = setTimeout(() => {
23660
+ entry.claimTimer = undefined;
23661
+ entry.holdsAtClaim = undefined;
23662
+ releaseWhenLetGo(runId, stageId, entry);
23663
+ }, CLAIM_GRACE_MS);
23664
+ entry.claimTimer.unref();
23665
+ }
23666
+ function unusedSinceClaim(entry, gate) {
23667
+ return gate.holdsTaken() <= (entry.holdsAtClaim ?? -1);
23668
+ }
23669
+ function releaseWhenLetGo(runId, stageId, entry) {
23670
+ const gate = entry.handle.releaseGate;
23671
+ if (gate === undefined || !entry.releaseWanted || entry.leases.size > 0)
23672
+ return;
23673
+ if (unusedSinceClaim(entry, gate) || !gate.idle())
23674
+ return;
23675
+ releaseIdleEntry(runId, stageId, entry).catch((error) => console.warn("atomic-workflows: completed stage session release failed", error));
23676
+ }
23411
23677
  function disposeEntry(entry) {
23678
+ stopWatching(entry);
23412
23679
  if (entry.disposal !== undefined)
23413
23680
  return entry.disposal;
23414
23681
  try {
@@ -23433,7 +23700,26 @@ function createStageControlRegistry() {
23433
23700
  function disposeEntryInBackground(entry, message) {
23434
23701
  disposeEntry(entry).catch((err) => console.warn(message, err));
23435
23702
  }
23436
- async function releaseIdleEntry(runId, stageId, entry) {
23703
+ function releaseIdleEntry(runId, stageId, entry) {
23704
+ if (entry.releasing !== undefined) {
23705
+ entry.releaseAgain = true;
23706
+ return entry.releasing;
23707
+ }
23708
+ entry.releasing = releaseUntilSettled(runId, stageId, entry).finally(() => {
23709
+ entry.releasing = undefined;
23710
+ });
23711
+ return entry.releasing;
23712
+ }
23713
+ async function releaseUntilSettled(runId, stageId, entry) {
23714
+ do {
23715
+ entry.releaseAgain = false;
23716
+ await releaseUnlessUsed(runId, stageId, entry);
23717
+ } while (releaseRequestedAgain(entry) && _byRun.get(runId)?.get(stageId) === entry);
23718
+ }
23719
+ function releaseRequestedAgain(entry) {
23720
+ return entry.releaseAgain === true;
23721
+ }
23722
+ async function releaseUnlessUsed(runId, stageId, entry) {
23437
23723
  const gate = entry.handle.releaseGate;
23438
23724
  if (gate === undefined || entry.disposal !== undefined)
23439
23725
  return;
@@ -23444,7 +23730,7 @@ function createStageControlRegistry() {
23444
23730
  const runMap = _byRun.get(runId);
23445
23731
  if (runMap?.get(stageId) !== entry || entry.epoch !== epoch || entry.leases.size > 0)
23446
23732
  return;
23447
- if (entry.disposal !== undefined || !gate.idle())
23733
+ if (unusedSinceClaim(entry, gate) || !gate.idle())
23448
23734
  return;
23449
23735
  const { stageName, sessionId } = entry.handle;
23450
23736
  rememberSessionStore(entry.handle, savedIn);
@@ -23517,13 +23803,13 @@ function createStageControlRegistry() {
23517
23803
  rememberSessionStore(handle);
23518
23804
  const runMap = ensureRun(handle.runId);
23519
23805
  const displaced = runMap.get(handle.stageId);
23520
- runMap.set(handle.stageId, {
23521
- handle,
23806
+ runMap.set(handle.stageId, createEntry(handle.runId, handle.stageId, handle, {
23522
23807
  controlsDependencies: true,
23523
23808
  permanent: true,
23524
- leases: new Set,
23525
- epoch: 0
23526
- });
23809
+ releaseWanted: handle.releaseGate?.releaseWhenIdle === true
23810
+ }));
23811
+ if (displaced !== undefined)
23812
+ stopWatching(displaced);
23527
23813
  if (displaced !== undefined && displaced.handle !== handle && !displaced.permanent) {
23528
23814
  disposeEntryInBackground(displaced, "atomic-workflows: displaced provisional stage handle dispose failed");
23529
23815
  }
@@ -23531,8 +23817,10 @@ function createStageControlRegistry() {
23531
23817
  const existing = _byRun.get(handle.runId);
23532
23818
  if (!existing)
23533
23819
  return;
23534
- if (existing.get(handle.stageId)?.handle === handle) {
23820
+ const entry = existing.get(handle.stageId);
23821
+ if (entry?.handle === handle) {
23535
23822
  rememberSessionStore(handle);
23823
+ stopWatching(entry);
23536
23824
  existing.delete(handle.stageId);
23537
23825
  }
23538
23826
  if (existing.size === 0)
@@ -23543,8 +23831,7 @@ function createStageControlRegistry() {
23543
23831
  const runMap = ensureRun(runId);
23544
23832
  const existing = runMap.get(stageId);
23545
23833
  if (existing !== undefined && existing.handle.isDisposed !== true) {
23546
- existing.permanent = true;
23547
- existing.epoch += 1;
23834
+ markClaimed(runId, stageId, existing);
23548
23835
  return existing.handle;
23549
23836
  }
23550
23837
  if (existing !== undefined) {
@@ -23552,13 +23839,13 @@ function createStageControlRegistry() {
23552
23839
  disposeEntryInBackground(existing, "atomic-workflows: stale stage handle dispose failed");
23553
23840
  }
23554
23841
  const handle = create();
23555
- runMap.set(handle.stageId, {
23556
- handle,
23842
+ const entry = createEntry(runId, handle.stageId, handle, {
23557
23843
  controlsDependencies: false,
23558
23844
  permanent: true,
23559
- leases: new Set,
23560
- epoch: 0
23845
+ releaseWanted: true
23561
23846
  });
23847
+ markClaimed(runId, handle.stageId, entry);
23848
+ runMap.set(handle.stageId, entry);
23562
23849
  return handle;
23563
23850
  },
23564
23851
  acquireDetached(runId, stageId, create) {
@@ -23570,13 +23857,11 @@ function createStageControlRegistry() {
23570
23857
  entry = undefined;
23571
23858
  }
23572
23859
  if (entry === undefined) {
23573
- entry = {
23574
- handle: create(),
23860
+ entry = createEntry(runId, stageId, create(), {
23575
23861
  controlsDependencies: false,
23576
23862
  permanent: false,
23577
- leases: new Set,
23578
- epoch: 0
23579
- };
23863
+ releaseWanted: true
23864
+ });
23580
23865
  runMap.set(stageId, entry);
23581
23866
  }
23582
23867
  const leasedEntry = entry;
@@ -23607,8 +23892,12 @@ function createStageControlRegistry() {
23607
23892
  await leasedEntry.disposal;
23608
23893
  return;
23609
23894
  }
23610
- if (leasedEntry.permanent || leasedEntry.leases.size > 0)
23895
+ if (leasedEntry.leases.size > 0)
23896
+ return;
23897
+ if (leasedEntry.permanent) {
23898
+ releaseWhenLetGo(runId, stageId, leasedEntry);
23611
23899
  return;
23900
+ }
23612
23901
  runMap.delete(stageId);
23613
23902
  if (runMap.size === 0)
23614
23903
  _byRun.delete(runId);
@@ -23633,10 +23922,8 @@ function createStageControlRegistry() {
23633
23922
  },
23634
23923
  claim(runId, stageId) {
23635
23924
  const entry = _byRun.get(runId)?.get(stageId);
23636
- if (entry !== undefined) {
23637
- entry.permanent = true;
23638
- entry.epoch += 1;
23639
- }
23925
+ if (entry !== undefined)
23926
+ markClaimed(runId, stageId, entry);
23640
23927
  return entry?.handle;
23641
23928
  },
23642
23929
  get(runId, stageId) {
@@ -23693,12 +23980,14 @@ function createStageControlRegistry() {
23693
23980
  for (const [stageId, entry] of entries) {
23694
23981
  if (entry === undefined)
23695
23982
  continue;
23983
+ entry.releaseWanted = true;
23696
23984
  try {
23697
23985
  await releaseIdleEntry(runId, stageId, entry);
23698
23986
  } catch (error) {
23699
23987
  console.warn("atomic-workflows: completed stage session release failed", error);
23700
23988
  }
23701
23989
  }
23990
+ await Promise.allSettled([...pendingDisposals]);
23702
23991
  },
23703
23992
  onStageReleased(listener) {
23704
23993
  releaseListeners.add(listener);
@@ -23708,7 +23997,7 @@ function createStageControlRegistry() {
23708
23997
  }
23709
23998
  };
23710
23999
  }
23711
- var SESSION_KEY4 = "workflows:stage-control:v1", singleton4, stageControlRegistry;
24000
+ var CLAIM_GRACE_MS = 1e4, SESSION_KEY4 = "workflows:stage-control:v1", singleton4, stageControlRegistry;
23712
24001
  var init_stage_control_registry = __esm(() => {
23713
24002
  init_session_scoped_singleton();
23714
24003
  singleton4 = createSessionScopedSingleton(SESSION_KEY4, createStageControlRegistry);
@@ -70842,6 +71131,7 @@ function createStagePathPatternIndex(patterns) {
70842
71131
  }
70843
71132
  var ADDRESSABLE_STAGE_STATUSES;
70844
71133
  var init_pending_stage_status = __esm(() => {
71134
+ init_run_stage_index();
70845
71135
  init_store_internal();
70846
71136
  init_workflow_run_ownership();
70847
71137
  init_workflow_stage_target();
@@ -72590,9 +72880,9 @@ function isBrokerProtocolRange(value2) {
72590
72880
  function protocolRangeOf(value2) {
72591
72881
  return value2 === undefined ? LEGACY_BROKER_PROTOCOL : { min: value2.min, max: value2.max };
72592
72882
  }
72593
- var BROKER_PROTOCOL, LEGACY_BROKER_PROTOCOL, VERIFIED_REGISTRATION_PROTOCOL = 2;
72883
+ var BROKER_PROTOCOL, LEGACY_BROKER_PROTOCOL, VERIFIED_REGISTRATION_PROTOCOL = 2, HOSTED_SESSIONS_PROTOCOL = 3;
72594
72884
  var init_protocol_version = __esm(() => {
72595
- BROKER_PROTOCOL = { min: 1, max: 2 };
72885
+ BROKER_PROTOCOL = { min: 1, max: 3 };
72596
72886
  LEGACY_BROKER_PROTOCOL = { min: 1, max: 1 };
72597
72887
  });
72598
72888
 
@@ -72909,6 +73199,30 @@ function isSessionInfo(value2) {
72909
73199
  return false;
72910
73200
  return session.status === undefined || typeof session.status === "string";
72911
73201
  }
73202
+ function isSessionRegistration(value2) {
73203
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) {
73204
+ return false;
73205
+ }
73206
+ const session = value2;
73207
+ if (typeof session.cwd !== "string" || typeof session.model !== "string" || typeof session.pid !== "number" || typeof session.startedAt !== "number" || typeof session.lastActivity !== "number") {
73208
+ return false;
73209
+ }
73210
+ if (session.name !== undefined && typeof session.name !== "string") {
73211
+ return false;
73212
+ }
73213
+ if (session.group !== undefined && typeof session.group !== "string") {
73214
+ return false;
73215
+ }
73216
+ if (session.replyCapability !== undefined && session.replyCapability !== "live" && session.replyCapability !== "terminal")
73217
+ return false;
73218
+ if (session.recipientPurpose !== undefined && session.recipientPurpose !== "agent" && session.recipientPurpose !== "control") {
73219
+ return false;
73220
+ }
73221
+ if (session.groups !== undefined && (!Array.isArray(session.groups) || !session.groups.every((group) => typeof group === "string"))) {
73222
+ return false;
73223
+ }
73224
+ return session.status === undefined || typeof session.status === "string";
73225
+ }
72912
73226
 
72913
73227
  // dist/builtin/intercom/broker/delivery-failure-reason.ts
72914
73228
  function isDeliveryFailureReasonCode(value2) {
@@ -72922,7 +73236,8 @@ var init_delivery_failure_reason = __esm(() => {
72922
73236
  "recipient_not_restored",
72923
73237
  "recipient_parked",
72924
73238
  "released_reply_answered",
72925
- "released_reply_in_flight"
73239
+ "released_reply_in_flight",
73240
+ "not_hosted_by_connection"
72926
73241
  ]);
72927
73242
  });
72928
73243
 
@@ -73147,6 +73462,8 @@ function isIntercomRecipientGoneErrorCode(value2) {
73147
73462
  return CODES5.has(value2);
73148
73463
  }
73149
73464
  function hintFor3(code, childId) {
73465
+ if (code === "recipient_stage_released")
73466
+ 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.";
73150
73467
  if (code === "recipient_cancelled")
73151
73468
  return "It cannot be resumed; launch a fresh subagent if its work is still needed.";
73152
73469
  if (code === "recipient_disconnected")
@@ -73158,7 +73475,9 @@ function hintFor3(code, childId) {
73158
73475
  function rehydrateIntercomRecipientGoneError(serialized) {
73159
73476
  const options = serialized.cause === undefined ? undefined : { cause: rehydrateCause3(serialized.cause, 1) };
73160
73477
  const { code, fields } = serialized;
73161
- if (serialized.name === ENDED_NAME && code !== "recipient_disconnected" && code !== "recipient_owner_suspended")
73478
+ if (serialized.name === STAGE_RELEASED_NAME && code === "recipient_stage_released")
73479
+ return new StageRecipientReleasedError(fields, options);
73480
+ if (serialized.name === ENDED_NAME && code !== "recipient_disconnected" && code !== "recipient_owner_suspended" && code !== "recipient_stage_released")
73162
73481
  return new SubagentRecipientEndedError(code, fields, options);
73163
73482
  if (serialized.name === DISCONNECTED_NAME && code === "recipient_disconnected")
73164
73483
  return new SubagentRecipientDisconnectedError(fields, options);
@@ -73206,7 +73525,7 @@ function readSerializedIntercomRecipientGoneError(value2) {
73206
73525
  ...cause === undefined ? {} : { cause }
73207
73526
  };
73208
73527
  }
73209
- 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);
73528
+ 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);
73210
73529
  var init_recipient_gone_errors = __esm(() => {
73211
73530
  init_released_child_errors();
73212
73531
  INTERCOM_RECIPIENT_GONE_ERROR_CODES = [
@@ -73215,7 +73534,8 @@ var init_recipient_gone_errors = __esm(() => {
73215
73534
  "recipient_stopped",
73216
73535
  "recipient_cancelled",
73217
73536
  "recipient_disconnected",
73218
- "recipient_owner_suspended"
73537
+ "recipient_owner_suspended",
73538
+ "recipient_stage_released"
73219
73539
  ];
73220
73540
  CODES5 = new Set(INTERCOM_RECIPIENT_GONE_ERROR_CODES);
73221
73541
  WHAT = {
@@ -73224,7 +73544,8 @@ var init_recipient_gone_errors = __esm(() => {
73224
73544
  recipient_stopped: "was stopped (paused or quit) and has no live session",
73225
73545
  recipient_cancelled: "was cancelled for good and has no live session",
73226
73546
  recipient_disconnected: "disconnected and has not reconnected",
73227
- recipient_owner_suspended: "is released and the session that launched it is suspended or disconnected, so nothing can wake it now"
73547
+ recipient_owner_suspended: "is released and the session that launched it is suspended or disconnected, so nothing can wake it now",
73548
+ recipient_stage_released: "was released and the session that answered for it has gone away"
73228
73549
  };
73229
73550
  IntercomRecipientGoneError = class IntercomRecipientGoneError extends Error {
73230
73551
  name = BASE_NAME3;
@@ -73236,7 +73557,8 @@ var init_recipient_gone_errors = __esm(() => {
73236
73557
  childId;
73237
73558
  constructor(code, fields, options) {
73238
73559
  const hint = hintFor3(code, fields.childId);
73239
- super(`Subagent ${JSON.stringify(fields.childName)} ${WHAT[code]} (${code}). ${hint}`, options);
73560
+ const subject = code === "recipient_stage_released" ? "Workflow stage" : "Subagent";
73561
+ super(`${subject} ${JSON.stringify(fields.childName)} ${WHAT[code]} (${code}). ${hint}`, options);
73240
73562
  this.code = code;
73241
73563
  this.hint = hint;
73242
73564
  this.retryable = code === "recipient_disconnected" || code === "recipient_owner_suspended";
@@ -73270,34 +73592,25 @@ var init_recipient_gone_errors = __esm(() => {
73270
73592
  super("recipient_owner_suspended", fields, options);
73271
73593
  }
73272
73594
  };
73273
- NAMES4 = new Set([BASE_NAME3, ENDED_NAME, DISCONNECTED_NAME, OWNER_SUSPENDED_NAME]);
73595
+ StageRecipientReleasedError = class StageRecipientReleasedError extends IntercomRecipientGoneError {
73596
+ name = STAGE_RELEASED_NAME;
73597
+ constructor(fields, options) {
73598
+ super("recipient_stage_released", fields, options);
73599
+ }
73600
+ };
73601
+ NAMES4 = new Set([
73602
+ BASE_NAME3,
73603
+ ENDED_NAME,
73604
+ DISCONNECTED_NAME,
73605
+ OWNER_SUSPENDED_NAME,
73606
+ STAGE_RELEASED_NAME
73607
+ ]);
73608
+ STAGE_RELEASED_NAMES = new Set([STAGE_RELEASED_NAME]);
73274
73609
  ENDED_NAMES = new Set([ENDED_NAME]);
73275
73610
  DISCONNECTED_NAMES = new Set([DISCONNECTED_NAME]);
73276
73611
  OWNER_SUSPENDED_NAMES = new Set([OWNER_SUSPENDED_NAME]);
73277
73612
  });
73278
73613
 
73279
- // dist/builtin/intercom/group.ts
73280
- function normalizeGroup2(value2) {
73281
- if (typeof value2 !== "string")
73282
- return DEFAULT_GROUP;
73283
- const trimmed = value2.trim();
73284
- return trimmed.length > 0 ? trimmed : DEFAULT_GROUP;
73285
- }
73286
- function normalizeGroups(values, legacyGroup) {
73287
- const groups = new Set;
73288
- for (const value2 of values ?? [])
73289
- groups.add(normalizeGroup2(value2));
73290
- if (legacyGroup !== undefined)
73291
- groups.add(normalizeGroup2(legacyGroup));
73292
- if (groups.size === 0)
73293
- groups.add(DEFAULT_GROUP);
73294
- return groups;
73295
- }
73296
- var DEFAULT_GROUP = "default", RESERVED_RUNTIME_GROUPS;
73297
- var init_group = __esm(() => {
73298
- RESERVED_RUNTIME_GROUPS = new Set(["true", "auto"]);
73299
- });
73300
-
73301
73614
  // dist/builtin/intercom/live-route-refusal.ts
73302
73615
  function isLiveWorkflowStageRouteRefusalCode(value2) {
73303
73616
  return typeof value2 === "string" && LIVE_WORKFLOW_STAGE_ROUTE_REFUSAL_CODES.includes(value2);
@@ -73343,6 +73656,202 @@ var init_live_route_refusal = __esm(() => {
73343
73656
  };
73344
73657
  });
73345
73658
 
73659
+ // dist/builtin/intercom/broker/hosted-sessions.ts
73660
+ function parseLiveRoute(value2) {
73661
+ if (!isWireObject3(value2))
73662
+ return false;
73663
+ const { runId, stageKeys, capability } = value2;
73664
+ if (!isNonEmptyString(runId) || !isNonEmptyString(capability) || !Array.isArray(stageKeys))
73665
+ return false;
73666
+ if (stageKeys.length < 1 || stageKeys.length > 2 || !stageKeys.every(isNonEmptyString))
73667
+ return false;
73668
+ return { runId, stageKeys, capability };
73669
+ }
73670
+ function validateHostSessionsFrame(sessions) {
73671
+ if (!Array.isArray(sessions) || sessions.length === 0 || sessions.length > HOSTED_SESSION_FRAME_MAX) {
73672
+ return { ok: false, refusal: { code: "invalid_hosted_frame" } };
73673
+ }
73674
+ const keys = new Set;
73675
+ const parsed = [];
73676
+ for (const item of sessions) {
73677
+ if (!isWireObject3(item) || !isNonEmptyString(item.key) || keys.has(item.key)) {
73678
+ return {
73679
+ ok: false,
73680
+ refusal: isWireObject3(item) && typeof item.key === "string" ? { code: "invalid_hosted_frame", key: item.key } : { code: "invalid_hosted_frame" }
73681
+ };
73682
+ }
73683
+ const key = item.key;
73684
+ keys.add(key);
73685
+ const invalid = { ok: false, refusal: { code: "invalid_hosted_session", key } };
73686
+ const { session, returnAddress } = item;
73687
+ if (!isSessionRegistration(session) || !isNonEmptyString(session.name) || session.recipientPurpose === "control") {
73688
+ return invalid;
73689
+ }
73690
+ if (returnAddress !== undefined && !isNonEmptyString(returnAddress))
73691
+ return invalid;
73692
+ const liveRoute = item.liveRoute === undefined ? undefined : parseLiveRoute(item.liveRoute);
73693
+ if (liveRoute === false)
73694
+ return invalid;
73695
+ parsed.push({
73696
+ key,
73697
+ session,
73698
+ ...returnAddress === undefined ? {} : { returnAddress },
73699
+ ...liveRoute === undefined ? {} : { liveRoute }
73700
+ });
73701
+ }
73702
+ return { ok: true, sessions: parsed };
73703
+ }
73704
+ function readHostedSessionAssignments(value2) {
73705
+ if (!Array.isArray(value2))
73706
+ return;
73707
+ const assignments = [];
73708
+ for (const item of value2) {
73709
+ if (!isWireObject3(item) || typeof item.key !== "string" || !isNonEmptyString(item.sessionId))
73710
+ return;
73711
+ const { liveRouteRefusal } = item;
73712
+ if (liveRouteRefusal !== undefined && !isLiveWorkflowStageRouteRefusalCode(liveRouteRefusal))
73713
+ return;
73714
+ assignments.push({
73715
+ key: item.key,
73716
+ sessionId: item.sessionId,
73717
+ ...liveRouteRefusal === undefined ? {} : { liveRouteRefusal }
73718
+ });
73719
+ }
73720
+ return assignments;
73721
+ }
73722
+ 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;
73723
+ var init_hosted_sessions = __esm(() => {
73724
+ init_live_route_refusal();
73725
+ });
73726
+
73727
+ // dist/builtin/intercom/broker/hosted-session-errors.ts
73728
+ function isHostedSessionErrorCode(value2) {
73729
+ return CODES6.has(value2);
73730
+ }
73731
+ function fieldsOf(refusal) {
73732
+ return {
73733
+ ...refusal.key === undefined ? {} : { key: refusal.key },
73734
+ ...refusal.sessionId === undefined ? {} : { sessionId: refusal.sessionId }
73735
+ };
73736
+ }
73737
+ function hostedSessionErrorFor(refusal, options) {
73738
+ return refusal.code === "not_hosted_by_connection" ? new NotHostedSessionError(fieldsOf(refusal), options) : new HostedSessionRequestError(refusal.code, fieldsOf(refusal), options);
73739
+ }
73740
+ function rehydrateIntercomHostedSessionError(serialized) {
73741
+ const options = serialized.cause === undefined ? undefined : { cause: rehydrateCause3(serialized.cause, 1) };
73742
+ if (serialized.name === NOT_HOSTED_NAME)
73743
+ return new NotHostedSessionError(serialized.fields, options);
73744
+ if (serialized.name === REQUEST_NAME)
73745
+ return new HostedSessionRequestError(serialized.code, serialized.fields, options);
73746
+ const error = new IntercomHostedSessionError(serialized.code, serialized.fields, options);
73747
+ Object.defineProperty(error, "name", { value: serialized.name });
73748
+ return error;
73749
+ }
73750
+ function readHostedSessionRefusal(value2) {
73751
+ if (!isWireObject3(value2))
73752
+ return;
73753
+ const { code, key, sessionId } = value2;
73754
+ if (typeof code !== "string" || !isHostedSessionErrorCode(code))
73755
+ return;
73756
+ if (key !== undefined && typeof key !== "string" || sessionId !== undefined && typeof sessionId !== "string") {
73757
+ return;
73758
+ }
73759
+ return { code, ...key === undefined ? {} : { key }, ...sessionId === undefined ? {} : { sessionId } };
73760
+ }
73761
+ function readSerializedIntercomHostedSessionError(value2) {
73762
+ if (!isWireObject3(value2))
73763
+ return;
73764
+ const { name, code, message, hint, retryable, fields } = value2;
73765
+ if (typeof name !== "string" || typeof code !== "string" || !isHostedSessionErrorCode(code))
73766
+ return;
73767
+ if (typeof message !== "string" || typeof hint !== "string" || retryable !== false)
73768
+ return;
73769
+ const refusal = isWireObject3(fields) ? readHostedSessionRefusal({ ...fields, code }) : undefined;
73770
+ if (refusal === undefined)
73771
+ return;
73772
+ const cause = readCause(value2.cause, 1);
73773
+ if (cause === false)
73774
+ return;
73775
+ return {
73776
+ name,
73777
+ code,
73778
+ message,
73779
+ hint,
73780
+ retryable: false,
73781
+ fields: fieldsOf(refusal),
73782
+ ...cause === undefined ? {} : { cause }
73783
+ };
73784
+ }
73785
+ 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;
73786
+ var init_hosted_session_errors = __esm(() => {
73787
+ init_hosted_sessions();
73788
+ init_released_child_errors();
73789
+ init_released_reply_errors();
73790
+ HOSTED_SESSION_ERROR_CODES = [
73791
+ "invalid_hosted_frame",
73792
+ "invalid_hosted_session",
73793
+ "not_hosted_by_connection"
73794
+ ];
73795
+ CODES6 = new Set(HOSTED_SESSION_ERROR_CODES);
73796
+ HINTS6 = {
73797
+ 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.",
73798
+ invalid_hosted_session: "Give each hosted session a non-empty name and a valid agent registration (cwd, model, pid and timestamps).",
73799
+ 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."
73800
+ };
73801
+ IntercomHostedSessionError = class IntercomHostedSessionError extends Error {
73802
+ name = BASE_NAME4;
73803
+ code;
73804
+ hint;
73805
+ retryable = false;
73806
+ key;
73807
+ sessionId;
73808
+ constructor(code, fields = {}, options) {
73809
+ const subject = fields.key !== undefined ? `hosted session ${JSON.stringify(fields.key)}` : fields.sessionId !== undefined ? `session ${JSON.stringify(fields.sessionId)}` : "request";
73810
+ super(`Hosted-session request refused: ${subject} (${code}). ${HINTS6[code]}`, options);
73811
+ this.code = code;
73812
+ this.hint = HINTS6[code];
73813
+ if (fields.key !== undefined)
73814
+ this.key = fields.key;
73815
+ if (fields.sessionId !== undefined)
73816
+ this.sessionId = fields.sessionId;
73817
+ }
73818
+ };
73819
+ HostedSessionRequestError = class HostedSessionRequestError extends IntercomHostedSessionError {
73820
+ name = REQUEST_NAME;
73821
+ };
73822
+ NotHostedSessionError = class NotHostedSessionError extends IntercomHostedSessionError {
73823
+ name = NOT_HOSTED_NAME;
73824
+ constructor(fields, options) {
73825
+ super("not_hosted_by_connection", fields, options);
73826
+ }
73827
+ };
73828
+ NAMES5 = new Set([BASE_NAME4, REQUEST_NAME, NOT_HOSTED_NAME]);
73829
+ REQUEST_NAMES = new Set([REQUEST_NAME]);
73830
+ NOT_HOSTED_NAMES = new Set([NOT_HOSTED_NAME]);
73831
+ });
73832
+
73833
+ // dist/builtin/intercom/group.ts
73834
+ function normalizeGroup2(value2) {
73835
+ if (typeof value2 !== "string")
73836
+ return DEFAULT_GROUP;
73837
+ const trimmed = value2.trim();
73838
+ return trimmed.length > 0 ? trimmed : DEFAULT_GROUP;
73839
+ }
73840
+ function normalizeGroups(values, legacyGroup) {
73841
+ const groups = new Set;
73842
+ for (const value2 of values ?? [])
73843
+ groups.add(normalizeGroup2(value2));
73844
+ if (legacyGroup !== undefined)
73845
+ groups.add(normalizeGroup2(legacyGroup));
73846
+ if (groups.size === 0)
73847
+ groups.add(DEFAULT_GROUP);
73848
+ return groups;
73849
+ }
73850
+ var DEFAULT_GROUP = "default", RESERVED_RUNTIME_GROUPS;
73851
+ var init_group = __esm(() => {
73852
+ RESERVED_RUNTIME_GROUPS = new Set(["true", "auto"]);
73853
+ });
73854
+
73346
73855
  // dist/builtin/intercom/recoverable-disconnect.ts
73347
73856
  function isIntercomBrokerRetiring(error) {
73348
73857
  let current = error;
@@ -73405,6 +73914,30 @@ var init_pending_stage_route_timeout_error = __esm(() => {
73405
73914
  };
73406
73915
  });
73407
73916
 
73917
+ // dist/builtin/intercom/hosted-session-timeout-error.ts
73918
+ var HOSTED_SESSION_TIMEOUT_HINT = "Hosting is tried again on the next connection; run `atomic intercom restart` if the broker keeps timing out.", IntercomHostedSessionTimeoutError;
73919
+ var init_hosted_session_timeout_error = __esm(() => {
73920
+ init_recoverable_disconnect();
73921
+ IntercomHostedSessionTimeoutError = class IntercomHostedSessionTimeoutError extends IntercomBrokerTimeoutError {
73922
+ name = "IntercomHostedSessionTimeoutError";
73923
+ code = "hosted_session_timeout";
73924
+ phase = "hosted-session-request";
73925
+ retryable = true;
73926
+ hint = HOSTED_SESSION_TIMEOUT_HINT;
73927
+ requestType;
73928
+ sessionCount;
73929
+ timeoutMs;
73930
+ elapsedMs;
73931
+ constructor(fields, options) {
73932
+ 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);
73933
+ this.requestType = fields.requestType;
73934
+ this.sessionCount = fields.sessionCount;
73935
+ this.timeoutMs = fields.timeoutMs;
73936
+ this.elapsedMs = fields.elapsedMs;
73937
+ }
73938
+ };
73939
+ });
73940
+
73408
73941
  // dist/builtin/intercom/broker/socket-liveness.ts
73409
73942
  import net from "net";
73410
73943
  function isSocketAnswering(socketPath, timeoutMs = SOCKET_PROBE_TIMEOUT_MS) {
@@ -73543,9 +74076,12 @@ var init_client = __esm(() => {
73543
74076
  init_released_reply_errors();
73544
74077
  init_released_children();
73545
74078
  init_recipient_gone_errors();
74079
+ init_hosted_session_errors();
74080
+ init_hosted_sessions();
73546
74081
  init_group();
73547
74082
  init_recoverable_disconnect();
73548
74083
  init_pending_stage_route_timeout_error();
74084
+ init_hosted_session_timeout_error();
73549
74085
  init_socket_liveness();
73550
74086
  init_protocol_version();
73551
74087
  init_live_route_refusal();
@@ -73554,6 +74090,7 @@ var init_client = __esm(() => {
73554
74090
  init_released_child_errors();
73555
74091
  init_recipient_gone_errors();
73556
74092
  init_released_reply_errors();
74093
+ init_hosted_session_errors();
73557
74094
  ConnectionClosedBeforeRegistrationError = class ConnectionClosedBeforeRegistrationError extends Error {
73558
74095
  constructor() {
73559
74096
  super("Connection closed before registration");
@@ -73611,6 +74148,7 @@ var init_client = __esm(() => {
73611
74148
  pendingStageRouteRegistrations = new Map;
73612
74149
  pendingSupervisorAuthorizations = new Map;
73613
74150
  pendingRestoringRecipientRequests = new Map;
74151
+ pendingHostedSessionRequests = new Map;
73614
74152
  disconnecting = false;
73615
74153
  disconnectError = null;
73616
74154
  healthCheck;
@@ -73670,6 +74208,8 @@ var init_client = __esm(() => {
73670
74208
  pending.reject(error);
73671
74209
  for (const pending of this.pendingRestoringRecipientRequests.values())
73672
74210
  pending.reject(error);
74211
+ for (const pending of this.pendingHostedSessionRequests.values())
74212
+ pending.reject(error);
73673
74213
  for (const pending of this.pendingPresence.values())
73674
74214
  pending.reject(error);
73675
74215
  for (const pending of this.pendingMemberships.values())
@@ -73686,6 +74226,7 @@ var init_client = __esm(() => {
73686
74226
  this.pendingGroupLists.clear();
73687
74227
  this.pendingSupervisorAuthorizations.clear();
73688
74228
  this.pendingRestoringRecipientRequests.clear();
74229
+ this.pendingHostedSessionRequests.clear();
73689
74230
  this.pendingPresence.clear();
73690
74231
  this.pendingMemberships.clear();
73691
74232
  this.pendingLiveWorkflowStageRoutes.clear();
@@ -74018,11 +74559,14 @@ var init_client = __esm(() => {
74018
74559
  break;
74019
74560
  }
74020
74561
  case "message": {
74021
- const { from, message, channel } = brokerMessage;
74022
- if (!isSessionInfo(from) || !isMessage(message) || channel !== undefined && channel !== "supervisor") {
74562
+ const { from, message, channel, hostedRecipient } = brokerMessage;
74563
+ if (!isSessionInfo(from) || !isMessage(message) || channel !== undefined && channel !== "supervisor" || hostedRecipient !== undefined && typeof hostedRecipient !== "string") {
74023
74564
  throw new Error("Invalid message event");
74024
74565
  }
74025
- this.emit("message", from, message, channel);
74566
+ if (hostedRecipient !== undefined)
74567
+ this.emit("hosted_message", hostedRecipient, from, message, channel);
74568
+ else
74569
+ this.emit("message", from, message, channel);
74026
74570
  break;
74027
74571
  }
74028
74572
  case "pending_stage_message": {
@@ -74167,6 +74711,23 @@ var init_client = __esm(() => {
74167
74711
  this.emit("released_child_reply", notice);
74168
74712
  break;
74169
74713
  }
74714
+ case "hosted_sessions_ack": {
74715
+ const { requestId, refusal, sessions } = brokerMessage;
74716
+ const parsedRefusal = readHostedSessionRefusal(refusal);
74717
+ const assignments = sessions === undefined ? [] : readHostedSessionAssignments(sessions);
74718
+ if (typeof requestId !== "string" || refusal !== undefined && parsedRefusal === undefined || assignments === undefined) {
74719
+ throw new Error("Invalid hosted_sessions_ack message");
74720
+ }
74721
+ const pending = this.pendingHostedSessionRequests.get(requestId);
74722
+ if (!pending)
74723
+ return;
74724
+ this.pendingHostedSessionRequests.delete(requestId);
74725
+ if (parsedRefusal === undefined)
74726
+ pending.resolve(assignments);
74727
+ else
74728
+ pending.reject(hostedSessionErrorFor(parsedRefusal));
74729
+ break;
74730
+ }
74170
74731
  case "released_children_ack": {
74171
74732
  const { requestId, refusal } = brokerMessage;
74172
74733
  const parsed = refusal === undefined ? undefined : readReleasedChildRefusal(refusal);
@@ -74213,7 +74774,9 @@ var init_client = __esm(() => {
74213
74774
  case "delivery_failed": {
74214
74775
  const { messageId, attemptId, reason, reasonCode } = brokerMessage;
74215
74776
  const wireError = brokerMessage.error;
74216
- const error = readSerializedIntercomReleasedReplyError(wireError);
74777
+ const releasedReplyError = readSerializedIntercomReleasedReplyError(wireError);
74778
+ const hostedSessionError = readSerializedIntercomHostedSessionError(wireError);
74779
+ const error = releasedReplyError ?? hostedSessionError;
74217
74780
  const wireRecipientError = brokerMessage.recipientError;
74218
74781
  const recipientError = readSerializedIntercomRecipientGoneError(wireRecipientError);
74219
74782
  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)) {
@@ -74224,7 +74787,8 @@ var init_client = __esm(() => {
74224
74787
  delivered: false,
74225
74788
  reason,
74226
74789
  ...reasonCode === undefined ? {} : { reasonCode },
74227
- ...error === undefined ? {} : { error: rehydrateIntercomReleasedReplyError(error) },
74790
+ ...releasedReplyError === undefined ? {} : { error: rehydrateIntercomReleasedReplyError(releasedReplyError) },
74791
+ ...hostedSessionError === undefined ? {} : { error: rehydrateIntercomHostedSessionError(hostedSessionError) },
74228
74792
  ...recipientError === undefined ? {} : { reasonCode: recipientError.code, error: rehydrateIntercomRecipientGoneError(recipientError) }
74229
74793
  };
74230
74794
  if (attemptId === undefined)
@@ -74634,15 +75198,76 @@ var init_client = __esm(() => {
74634
75198
  });
74635
75199
  return true;
74636
75200
  }
74637
- requireBrokerProtocol(feature) {
75201
+ requireBrokerProtocol(feature, requiredProtocol = VERIFIED_REGISTRATION_PROTOCOL) {
74638
75202
  const broker = this._brokerProtocol;
74639
- if (this._sessionId === null || broker.max >= VERIFIED_REGISTRATION_PROTOCOL)
75203
+ if (this._sessionId === null || broker.max >= requiredProtocol)
74640
75204
  return;
74641
75205
  throw new IntercomBrokerProtocolError({
74642
75206
  feature,
74643
75207
  brokerProtocolMin: broker.min,
74644
75208
  brokerProtocolMax: broker.max,
74645
- requiredProtocol: VERIFIED_REGISTRATION_PROTOCOL
75209
+ requiredProtocol
75210
+ });
75211
+ }
75212
+ async hostSessions(sessions) {
75213
+ this.requireBrokerProtocol("host_sessions", HOSTED_SESSIONS_PROTOCOL);
75214
+ const frames = [];
75215
+ for (let start = 0;start < sessions.length; start += HOSTED_SESSION_FRAME_MAX) {
75216
+ const frame = sessions.slice(start, start + HOSTED_SESSION_FRAME_MAX);
75217
+ const wire = JSON.parse(JSON.stringify(frame));
75218
+ const validation = validateHostSessionsFrame(wire);
75219
+ if (!validation.ok)
75220
+ throw hostedSessionErrorFor(validation.refusal);
75221
+ frames.push(frame);
75222
+ }
75223
+ const assigned = [];
75224
+ for (const frame of frames)
75225
+ assigned.push(...await this.hostedSessionRequest({ type: "host_sessions", sessions: frame }));
75226
+ return assigned;
75227
+ }
75228
+ async unhostSessions(sessionIds) {
75229
+ this.requireBrokerProtocol("unhost_sessions", HOSTED_SESSIONS_PROTOCOL);
75230
+ if (sessionIds.length === 0)
75231
+ throw new HostedSessionRequestError("invalid_hosted_frame");
75232
+ for (let start = 0;start < sessionIds.length; start += HOSTED_SESSION_FRAME_MAX) {
75233
+ await this.hostedSessionRequest({
75234
+ type: "unhost_sessions",
75235
+ sessionIds: sessionIds.slice(start, start + HOSTED_SESSION_FRAME_MAX)
75236
+ });
75237
+ }
75238
+ }
75239
+ hostedSessionRequest(frame) {
75240
+ const socket = this.requireActiveSocket();
75241
+ const requestId = randomUUID14();
75242
+ const startedAt = performance.now();
75243
+ return new Promise((resolve, reject) => {
75244
+ const timeout = setTimeout(() => {
75245
+ this.pendingHostedSessionRequests.delete(requestId);
75246
+ const timedOut = {
75247
+ requestType: frame.type === "unhost_sessions" ? "unhost_sessions" : "host_sessions",
75248
+ sessionCount: Array.isArray(frame.sessions) ? frame.sessions.length : Array.isArray(frame.sessionIds) ? frame.sessionIds.length : 0,
75249
+ timeoutMs: RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS,
75250
+ elapsedMs: Math.round(performance.now() - startedAt)
75251
+ };
75252
+ this.requestTimeout(socket, new IntercomHostedSessionTimeoutError(timedOut)).then((error) => reject(error instanceof IntercomBrokerTimeoutError && !(error instanceof IntercomHostedSessionTimeoutError) ? new IntercomHostedSessionTimeoutError(timedOut, { cause: error }) : error));
75253
+ }, RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS);
75254
+ this.pendingHostedSessionRequests.set(requestId, {
75255
+ resolve: (sessions) => {
75256
+ clearTimeout(timeout);
75257
+ resolve([...sessions]);
75258
+ },
75259
+ reject: (error) => {
75260
+ clearTimeout(timeout);
75261
+ reject(error);
75262
+ }
75263
+ });
75264
+ try {
75265
+ writeMessage(socket, { ...frame, requestId });
75266
+ } catch (error) {
75267
+ clearTimeout(timeout);
75268
+ this.pendingHostedSessionRequests.delete(requestId);
75269
+ reject(toError(error));
75270
+ }
74646
75271
  });
74647
75272
  }
74648
75273
  restoringRecipientRequest(frame) {
@@ -74901,6 +75526,7 @@ var init_client = __esm(() => {
74901
75526
  ...options.expectedRecipientId === undefined ? {} : { expectedRecipientId: options.expectedRecipientId },
74902
75527
  ...options.onReplyTarget === undefined ? {} : { resolveReplyTarget: true },
74903
75528
  ...type === "send" ? { awaitRestoringRecipient: true } : {},
75529
+ hostedSender: options.hostedSender,
74904
75530
  message,
74905
75531
  attemptId: acquired.attempt.attemptId,
74906
75532
  ...extra
@@ -89692,6 +90318,66 @@ var init_stage_runner = __esm(() => {
89692
90318
  init_stage_runner_context();
89693
90319
  });
89694
90320
 
90321
+ // dist/builtin/workflows/src/runs/foreground/stage-session-holds.ts
90322
+ class StageSessionHolds {
90323
+ subscribers = 0;
90324
+ operations = 0;
90325
+ taken = 0;
90326
+ listeners = new Set;
90327
+ get held() {
90328
+ return this.subscribers > 0 || this.operations > 0;
90329
+ }
90330
+ get holdsTaken() {
90331
+ return this.taken;
90332
+ }
90333
+ subscription(unsubscribe) {
90334
+ this.subscribers += 1;
90335
+ this.taken += 1;
90336
+ let active = true;
90337
+ return () => {
90338
+ if (!active)
90339
+ return;
90340
+ active = false;
90341
+ this.subscribers -= 1;
90342
+ unsubscribe();
90343
+ this.lifted();
90344
+ };
90345
+ }
90346
+ async operation(operation) {
90347
+ this.operations += 1;
90348
+ this.taken += 1;
90349
+ try {
90350
+ return await operation();
90351
+ } finally {
90352
+ this.operations -= 1;
90353
+ this.lifted();
90354
+ }
90355
+ }
90356
+ observe(event) {
90357
+ switch (event.type) {
90358
+ case "agent_end":
90359
+ case "agent_settled":
90360
+ case "queue_update":
90361
+ case "compaction_end":
90362
+ case "auto_retry_end":
90363
+ this.lifted();
90364
+ }
90365
+ }
90366
+ onLifted(listener) {
90367
+ this.listeners.add(listener);
90368
+ return () => {
90369
+ this.listeners.delete(listener);
90370
+ };
90371
+ }
90372
+ clear() {
90373
+ this.listeners.clear();
90374
+ }
90375
+ lifted() {
90376
+ for (const listener of [...this.listeners])
90377
+ listener();
90378
+ }
90379
+ }
90380
+
89695
90381
  // dist/builtin/workflows/src/runs/foreground/postmortem-stage-chat.ts
89696
90382
  import { withWorktreeRootMappings as withWorktreeRootMappings2 } from "@bastani/atomic";
89697
90383
  async function reopenableSessionStore(runId, stageId, sessionId, deps) {
@@ -89769,8 +90455,12 @@ function createPostMortemStageHandle(runId, stage, sessionId, adapters, cwd, def
89769
90455
  }
89770
90456
  };
89771
90457
  const queuedUserMessages = new StageQueuedUserMessageBuffer;
89772
- const unsubscribeQueuedUserMessages = context.subscribe((event) => queuedUserMessages.record(event));
89773
- return {
90458
+ const holds = new StageSessionHolds;
90459
+ const unsubscribeQueuedUserMessages = context.subscribe((event) => {
90460
+ queuedUserMessages.record(event);
90461
+ holds.observe(event);
90462
+ });
90463
+ const handle = {
89774
90464
  runId,
89775
90465
  stageId: stage.id,
89776
90466
  stageName: stage.name,
@@ -89828,20 +90518,45 @@ function createPostMortemStageHandle(runId, stage, sessionId, adapters, cwd, def
89828
90518
  throw new Error("Post-mortem stage chat cannot pause or resume workflow execution.");
89829
90519
  },
89830
90520
  subscribe(listener) {
89831
- return context.subscribe(listener);
90521
+ return holds.subscription(context.subscribe(listener));
89832
90522
  },
89833
90523
  subscribeDeliveryActivity(listener) {
89834
- return context.__subscribeDeliveryActivity(listener);
90524
+ return holds.subscription(context.__subscribeDeliveryActivity(listener));
89835
90525
  },
89836
90526
  async dispose() {
89837
90527
  if (disposed)
89838
90528
  return;
89839
90529
  disposed = true;
90530
+ holds.clear();
89840
90531
  unsubscribeQueuedUserMessages();
89841
90532
  queuedUserMessages.clear();
89842
90533
  await context.__dispose();
90534
+ },
90535
+ releaseGate: {
90536
+ releaseWhenIdle: true,
90537
+ async savedForReopen() {
90538
+ if (disposed)
90539
+ return;
90540
+ const store = context.__persistedSessionStore() ?? sessionStore;
90541
+ const savedSessionId = context.__sessionMeta().sessionId ?? sessionId;
90542
+ if (store === undefined)
90543
+ return;
90544
+ return await isReopenableSession(store, savedSessionId) ? store : undefined;
90545
+ },
90546
+ idle() {
90547
+ return !disposed && !holds.held && stageQueuedUserMessageCount(queuedUserMessages.snapshot()) === 0 && (context.__sessionMeta().sessionId === undefined || context.__idleForRelease());
90548
+ },
90549
+ holdsTaken: () => holds.holdsTaken,
90550
+ onHoldLifted: (listener) => holds.onLifted(listener)
89843
90551
  }
89844
90552
  };
90553
+ const { sendUserMessage, prompt, steer, followUp } = handle;
90554
+ handle.ensureAttached = () => holds.operation(ensureAttached);
90555
+ handle.sendUserMessage = (text, options, beforeDelivery) => holds.operation(() => sendUserMessage(text, options, beforeDelivery));
90556
+ handle.prompt = (text) => holds.operation(() => prompt(text));
90557
+ handle.steer = (text) => holds.operation(() => steer(text));
90558
+ handle.followUp = (text) => holds.operation(() => followUp(text));
90559
+ return handle;
89845
90560
  }
89846
90561
  var TERMINAL_POSTMORTEM_STATUSES;
89847
90562
  var init_postmortem_stage_chat = __esm(() => {
@@ -94307,7 +95022,7 @@ function createWorkflowBoundaryFactory(input) {
94307
95022
  stageSnapshot.durationMs = elapsedStageMs(stageSnapshot, stageSnapshot.endedAt);
94308
95023
  }
94309
95024
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
94310
- input.opts.onStageEnd?.(input.runId, stageSnapshot);
95025
+ endStageWithHook(input.activeStore, input.runId, stageSnapshot, input.opts.onStageEnd);
94311
95026
  await appendStageEndForSnapshot();
94312
95027
  input.tracker.onSettle(stageId);
94313
95028
  })();
@@ -94333,7 +95048,7 @@ function createWorkflowBoundaryFactory(input) {
94333
95048
  finalized = true;
94334
95049
  unregisterWorkflowExitCleanup();
94335
95050
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
94336
- input.opts.onStageEnd?.(input.runId, stageSnapshot);
95051
+ endStageWithHook(input.activeStore, input.runId, stageSnapshot, input.opts.onStageEnd);
94337
95052
  await appendStageEndForSnapshot();
94338
95053
  input.tracker.onSettle(stageId);
94339
95054
  })();
@@ -95350,9 +96065,11 @@ function createStageControlHandle(runtime) {
95350
96065
  };
95351
96066
  const toolExecutions = new StageToolExecutionBuffer;
95352
96067
  const queuedUserMessages = new StageQueuedUserMessageBuffer;
96068
+ const holds = new StageSessionHolds;
95353
96069
  const unsubscribeStageEvents = runtime.innerCtx.subscribe((event) => {
95354
96070
  toolExecutions.record(event);
95355
96071
  queuedUserMessages.record(event);
96072
+ holds.observe(event);
95356
96073
  if (event.type === "task_cleanup_quarantined")
95357
96074
  runtime.activeStore.recordStageNotice(runtime.runId, runtime.stageId, {
95358
96075
  id: crypto.randomUUID(),
@@ -95364,27 +96081,6 @@ function createStageControlHandle(runtime) {
95364
96081
  if (event.type === "background_compaction")
95365
96082
  runtime.activeStore.recordStageCompaction(runtime.runId, runtime.stageId, event.compaction);
95366
96083
  });
95367
- let externalSubscribers = 0;
95368
- const countSubscription = (unsubscribe) => {
95369
- externalSubscribers += 1;
95370
- let active = true;
95371
- return () => {
95372
- if (!active)
95373
- return;
95374
- active = false;
95375
- externalSubscribers -= 1;
95376
- unsubscribe();
95377
- };
95378
- };
95379
- let activeOperations = 0;
95380
- const tracked = async (operation) => {
95381
- activeOperations += 1;
95382
- try {
95383
- return await operation();
95384
- } finally {
95385
- activeOperations -= 1;
95386
- }
95387
- };
95388
96084
  const sessionSaved = () => runtime.stageSnapshot.status === "completed" && runtime.state.stageFinalized && runtime.state.sessionCheckpointed && !runtime.state.liveHandleReleased && !runtime.state.stageClosedByWorkflowExit;
95389
96085
  const handle = {
95390
96086
  runId: runtime.runId,
@@ -95580,12 +96276,13 @@ function createStageControlHandle(runtime) {
95580
96276
  }
95581
96277
  },
95582
96278
  subscribe(listener) {
95583
- return countSubscription(runtime.innerCtx.subscribe(listener));
96279
+ return holds.subscription(runtime.innerCtx.subscribe(listener));
95584
96280
  },
95585
96281
  subscribeDeliveryActivity(listener) {
95586
- return countSubscription(runtime.innerCtx.__subscribeDeliveryActivity(listener));
96282
+ return holds.subscription(runtime.innerCtx.__subscribeDeliveryActivity(listener));
95587
96283
  },
95588
96284
  async dispose() {
96285
+ holds.clear();
95589
96286
  unsubscribeStageEvents();
95590
96287
  toolExecutions.clear();
95591
96288
  queuedUserMessages.clear();
@@ -95602,18 +96299,20 @@ function createStageControlHandle(runtime) {
95602
96299
  return await isReopenableSession(store, sessionId) ? store : undefined;
95603
96300
  },
95604
96301
  idle() {
95605
- 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();
95606
- }
96302
+ 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();
96303
+ },
96304
+ holdsTaken: () => holds.holdsTaken,
96305
+ onHoldLifted: (listener) => holds.onLifted(listener)
95607
96306
  }
95608
96307
  };
95609
96308
  const { ensureAttached, sendUserMessage, prompt, steer, followUp, pause, resume } = handle;
95610
- handle.ensureAttached = () => tracked(ensureAttached);
95611
- handle.sendUserMessage = (text, options, beforeDelivery) => tracked(() => sendUserMessage(text, options, beforeDelivery));
95612
- handle.prompt = (text) => tracked(() => prompt(text));
95613
- handle.steer = (text, options) => tracked(() => steer(text, options));
95614
- handle.followUp = (text, options) => tracked(() => followUp(text, options));
95615
- handle.pause = () => tracked(pause);
95616
- handle.resume = (message, beforeResume) => tracked(() => resume(message, beforeResume));
96309
+ handle.ensureAttached = () => holds.operation(ensureAttached);
96310
+ handle.sendUserMessage = (text, options, beforeDelivery) => holds.operation(() => sendUserMessage(text, options, beforeDelivery));
96311
+ handle.prompt = (text) => holds.operation(() => prompt(text));
96312
+ handle.steer = (text, options) => holds.operation(() => steer(text, options));
96313
+ handle.followUp = (text, options) => holds.operation(() => followUp(text, options));
96314
+ handle.pause = () => holds.operation(pause);
96315
+ handle.resume = (message, beforeResume) => holds.operation(() => resume(message, beforeResume));
95617
96316
  return handle;
95618
96317
  }
95619
96318
  var init_executor_stage_control = __esm(() => {
@@ -95668,7 +96367,7 @@ function createReplayStageContext(input) {
95668
96367
  stageSnapshot.skippedReason = input.workflowExitSkippedReason(reason);
95669
96368
  }
95670
96369
  input.activeStore.recordStageEnd(runId, stageSnapshot);
95671
- input.opts.onStageEnd?.(runId, stageSnapshot);
96370
+ endStageWithHook(input.activeStore, runId, stageSnapshot, input.opts.onStageEnd);
95672
96371
  await appendReplayStageEnd();
95673
96372
  input.tracker.onSettle(stageId);
95674
96373
  })();
@@ -95933,26 +96632,8 @@ function createWorkflowStageFactory(input) {
95933
96632
  if (keptResults !== undefined)
95934
96633
  stageSnapshot.waitResults = recordStageWaitToolResults(keptResults);
95935
96634
  const applyModelFallbackMeta = (meta) => {
95936
- if (meta.model !== undefined)
95937
- stageSnapshot.model = meta.model;
95938
- if (meta.thinkingLevel !== undefined)
95939
- stageSnapshot.thinkingLevel = meta.thinkingLevel;
95940
- else
95941
- delete stageSnapshot.thinkingLevel;
95942
- if (meta.attemptedModels !== undefined)
95943
- stageSnapshot.attemptedModels = meta.attemptedModels;
95944
- if (meta.modelAttempts !== undefined)
95945
- stageSnapshot.modelAttempts = meta.modelAttempts;
95946
- if (meta.rateLimits !== undefined)
95947
- stageSnapshot.rateLimits = meta.rateLimits;
95948
- if (meta.routerSelection !== undefined)
95949
- stageSnapshot.routerSelection = meta.routerSelection;
95950
- if (meta.warnings !== undefined) {
95951
- if (meta.warnings.length > 0)
95952
- stageSnapshot.warnings = meta.warnings;
95953
- else
95954
- delete stageSnapshot.warnings;
95955
- }
96635
+ if (applyModelFallbackMetaToStage(stageSnapshot, meta))
96636
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
95956
96637
  };
95957
96638
  let runtime;
95958
96639
  const emitLifecycleEvent = (event) => {
@@ -96054,10 +96735,12 @@ function createWorkflowStageFactory(input) {
96054
96735
  },
96055
96736
  async recordResults(_wait, results) {
96056
96737
  stageSnapshot.waitResults = recordStageWaitToolResults(results);
96738
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96057
96739
  await recordWait("wait-results");
96058
96740
  },
96059
96741
  resultsInTranscript() {
96060
96742
  delete stageSnapshot.waitResults;
96743
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96061
96744
  },
96062
96745
  async leave() {
96063
96746
  waitRecordMissing = false;
@@ -96242,13 +96925,13 @@ function createWorkflowStageFactory(input) {
96242
96925
  };
96243
96926
  const captureStageSessionMeta = async (checkpointOptions) => {
96244
96927
  const meta = innerCtx.__sessionMeta();
96245
- if (meta.sessionId !== undefined)
96246
- stageSnapshot.sessionId = meta.sessionId;
96247
- if (meta.sessionFile !== undefined)
96248
- stageSnapshot.sessionFile = meta.sessionFile;
96928
+ const changed = applySessionMetaToStage(stageSnapshot, meta);
96249
96929
  if (meta.sessionId !== undefined)
96250
96930
  input.activeStore.recordStageSession(input.runId, stageId, { sessionId: meta.sessionId });
96931
+ if (changed)
96932
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96251
96933
  const pending = input.opts.onStageSession?.(input.runId, stageSnapshot, checkpointOptions);
96934
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96252
96935
  if (checkpointOptions?.forceDurable === true || checkpointOptions?.awaitDurable === true) {
96253
96936
  await pending;
96254
96937
  return;
@@ -96323,6 +97006,7 @@ function createWorkflowStageFactory(input) {
96323
97006
  input.stageUiBroker.clearStageStatuses(input.runId, stageId);
96324
97007
  if (input.opts.onStageEnd) {
96325
97008
  await runCallback3({ kind: "workflow.stage_adapter", name: `onStageEnd:${name}`, runId: input.runId, stageId }, () => input.opts.onStageEnd(input.runId, stageSnapshot));
97009
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
96326
97010
  }
96327
97011
  if (input.opts.persistence) {
96328
97012
  await appendStageStartOnce();