@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
@@ -301,11 +301,22 @@ function index(items, cache) {
301
301
  }
302
302
  return byId;
303
303
  }
304
+ function markPublishedSnapshotArray(items) {
305
+ publishedSnapshotArrays.add(items);
306
+ }
307
+ function isPublishedSnapshotArray(items) {
308
+ return publishedSnapshotArrays.has(items);
309
+ }
310
+ function frozenIndex(items, cache) {
311
+ return cache.get(items) ?? (isPublishedSnapshotArray(items) || Object.isFrozen(items) ? index(items, cache) : undefined);
312
+ }
304
313
  function findSnapshotRun(runs, runId) {
305
- return Object.isFrozen(runs) ? index(runs, runIndexes).get(runId) : runs.find((run) => run.id === runId);
314
+ const byId = frozenIndex(runs, runIndexes);
315
+ return byId === undefined ? runs.find((run) => run.id === runId) : byId.get(runId);
306
316
  }
307
317
  function findSnapshotStage(stages, stageId) {
308
- return Object.isFrozen(stages) ? index(stages, stageIndexes).get(stageId) : stages.find((stage) => stage.id === stageId);
318
+ const byId = frozenIndex(stages, stageIndexes);
319
+ return byId === undefined ? stages.find((stage) => stage.id === stageId) : byId.get(stageId);
309
320
  }
310
321
  function childRunsInSource(source, parentRunId, parentStageId) {
311
322
  if (isRunLookup(source) && source.childRuns !== undefined)
@@ -330,10 +341,11 @@ function invocationRunsInSource(source, rootRunId) {
330
341
  }
331
342
  return found.filter(inInvocation).sort((left, right) => source.runPosition(left.id) - source.runPosition(right.id));
332
343
  }
333
- var runIndexes, stageIndexes;
344
+ var runIndexes, stageIndexes, publishedSnapshotArrays;
334
345
  var init_workflow_run_ownership = __esm(() => {
335
346
  runIndexes = new WeakMap;
336
347
  stageIndexes = new WeakMap;
348
+ publishedSnapshotArrays = new WeakSet;
337
349
  });
338
350
 
339
351
  // dist/builtin/workflows/src/durable/prompt-reservations.ts
@@ -1232,6 +1244,73 @@ var init_readiness_decision = __esm(() => {
1232
1244
  };
1233
1245
  });
1234
1246
 
1247
+ // dist/builtin/workflows/src/shared/run-stage-index.ts
1248
+ function asksForInput(stage) {
1249
+ return stage.pendingPrompt !== undefined || stage.inputRequest !== undefined || stage.status === "awaiting_input" || stage.awaitingInputSince !== undefined;
1250
+ }
1251
+ function isFinished(stage) {
1252
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
1253
+ }
1254
+ function indexFrom(stages, asking, unfinished) {
1255
+ const pending = [];
1256
+ const waiting = [];
1257
+ for (const position of unfinished) {
1258
+ const stage = stages[position];
1259
+ if (stage.status === "pending")
1260
+ pending.push(stage);
1261
+ if (asksForInput(stage))
1262
+ waiting.push(stage);
1263
+ }
1264
+ return { index: { awaitingInput: asking > 0, pending, waiting }, asking, unfinished };
1265
+ }
1266
+ function buildIndex(stages) {
1267
+ let asking = 0;
1268
+ const unfinished = [];
1269
+ stages.forEach((stage, position) => {
1270
+ if (asksForInput(stage))
1271
+ asking++;
1272
+ if (!isFinished(stage))
1273
+ unfinished.push(position);
1274
+ });
1275
+ return indexFrom(stages, asking, unfinished);
1276
+ }
1277
+ function runStageIndex(run) {
1278
+ const known = indexes.get(run);
1279
+ if (known !== undefined)
1280
+ return known.index;
1281
+ const built = buildIndex(run.stages);
1282
+ if (Object.isFrozen(run))
1283
+ indexes.set(run, built);
1284
+ return built.index;
1285
+ }
1286
+ function indexRunFrom(run, previous, changed, appendedFrom) {
1287
+ const known = indexes.get(previous);
1288
+ if (known === undefined || !Object.isFrozen(run))
1289
+ return;
1290
+ let asking = known.asking;
1291
+ const unfinished = new Set(known.unfinished);
1292
+ const update = (position, before) => {
1293
+ const stage = run.stages[position];
1294
+ if (before !== undefined && asksForInput(before))
1295
+ asking--;
1296
+ if (asksForInput(stage))
1297
+ asking++;
1298
+ if (isFinished(stage))
1299
+ unfinished.delete(position);
1300
+ else
1301
+ unfinished.add(position);
1302
+ };
1303
+ for (const position of changed)
1304
+ update(position, previous.stages[position]);
1305
+ for (let position = appendedFrom;position < run.stages.length; position++)
1306
+ update(position, undefined);
1307
+ indexes.set(run, indexFrom(run.stages, asking, [...unfinished].sort((left, right) => left - right)));
1308
+ }
1309
+ var indexes;
1310
+ var init_run_stage_index = __esm(() => {
1311
+ indexes = new WeakMap;
1312
+ });
1313
+
1235
1314
  // dist/builtin/workflows/src/shared/flat-string.ts
1236
1315
  function flattenTruncatedString(value2) {
1237
1316
  return value2.split("").join("");
@@ -1732,25 +1811,45 @@ function sameSourceShape(value2, shape) {
1732
1811
  }
1733
1812
  return index === shape.keys.length;
1734
1813
  }
1814
+ function isSettledStage(stage) {
1815
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
1816
+ }
1735
1817
  function projectStage(stage) {
1818
+ const compact = compactStage(stage);
1819
+ deepFreezeGraphValue(compact);
1736
1820
  return {
1737
1821
  shape: sourceShape(stage),
1738
1822
  parentCount: stage.parentIds.length,
1739
1823
  toolEventCount: stage.toolEvents.length,
1740
1824
  lastToolEvent: stage.toolEvents.at(-1),
1741
1825
  noticeCount: stage.notices?.length,
1742
- compact: compactStage(stage)
1826
+ settled: isSettledStage(stage),
1827
+ compact
1743
1828
  };
1744
1829
  }
1745
1830
  function stageUnchanged(stage, projected) {
1746
1831
  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;
1747
1832
  }
1748
1833
  function projectToolNode(node) {
1749
- return { shape: sourceShape(node), parentCount: node.parentIds.length, compact: compactToolNode(node) };
1834
+ const compact = compactToolNode(node);
1835
+ deepFreezeGraphValue(compact);
1836
+ return { shape: sourceShape(node), parentCount: node.parentIds.length, compact };
1750
1837
  }
1751
1838
  function toolNodeUnchanged(node, projected) {
1752
1839
  return sameSourceShape(node, projected.shape) && node.parentIds.length === projected.parentCount;
1753
1840
  }
1841
+ function freezeCompactRun(run) {
1842
+ for (const [key, value2] of Object.entries(run)) {
1843
+ if (key === "stages" || key === "toolNodes")
1844
+ markPublishedSnapshotArray(value2);
1845
+ else
1846
+ deepFreezeGraphValue(value2);
1847
+ }
1848
+ Object.freeze(run);
1849
+ }
1850
+ function graphSnapshotLineage(snapshot) {
1851
+ return snapshotLineages.get(snapshot);
1852
+ }
1754
1853
 
1755
1854
  class GraphStoreSnapshotBuilder {
1756
1855
  projected = new Map;
@@ -1779,9 +1878,7 @@ class GraphStoreSnapshotBuilder {
1779
1878
  const next = new Map;
1780
1879
  const compactRuns = [];
1781
1880
  for (const run of runs) {
1782
- const known = previous.get(run.id);
1783
- const reusable = known?.source === run ? known : undefined;
1784
- const projected = reusable !== undefined && !this.changedRuns.has(run.id) && this.runUnchanged(run, reusable) ? reusable : this.projectRun(run, reusable);
1881
+ const projected = this.refreshRun(run, previous.get(run.id));
1785
1882
  next.set(run.id, projected);
1786
1883
  compactRuns.push(projected.compact);
1787
1884
  }
@@ -1789,38 +1886,36 @@ class GraphStoreSnapshotBuilder {
1789
1886
  this.changedRuns.clear();
1790
1887
  this.changedStages.clear();
1791
1888
  this.changedToolNodes.clear();
1792
- const snapshot = {
1793
- runs: compactRuns,
1794
- notices: notices.map((notice) => ({ ...notice })),
1889
+ const compactNotices = notices.map((notice) => ({ ...notice }));
1890
+ deepFreezeGraphValue(compactNotices);
1891
+ const snapshot = Object.freeze({
1892
+ runs: Object.freeze(compactRuns),
1893
+ notices: compactNotices,
1795
1894
  version
1796
- };
1797
- deepFreezeGraphValue(snapshot);
1895
+ });
1896
+ snapshotLineages.set(snapshot, this);
1798
1897
  return snapshot;
1799
1898
  }
1800
1899
  buildRun(run) {
1801
- const known = this.projected.get(run.id);
1802
- const reusable = known?.source === run ? known : undefined;
1803
- const projected = reusable !== undefined && !this.changedRuns.has(run.id) && this.runUnchanged(run, reusable) ? reusable : this.projectRun(run, reusable);
1804
- deepFreezeGraphValue(projected.compact);
1900
+ const projected = this.refreshRun(run, this.projected.get(run.id));
1805
1901
  this.projected.set(run.id, projected);
1806
1902
  this.changedRuns.delete(run.id);
1807
1903
  this.changedStages.delete(run.id);
1808
1904
  this.changedToolNodes.delete(run.id);
1809
1905
  return projected.compact;
1810
1906
  }
1811
- runUnchanged(run, projected) {
1812
- if (!sameSourceShape(run, projected.shape))
1813
- return false;
1814
- const { stages, toolNodes } = projected.compact;
1815
- if (run.stages.length !== stages.length || run.toolNodes.length !== toolNodes.length)
1907
+ refreshRun(run, known) {
1908
+ const reusable = known?.source === run ? known : undefined;
1909
+ if (reusable === undefined || this.changedRuns.has(run.id) || !sameSourceShape(run, reusable.shape))
1910
+ return this.projectRun(run, reusable);
1911
+ if (!this.toolNodesUnchanged(run, reusable))
1912
+ return this.projectRun(run, reusable);
1913
+ return this.patchStages(run, reusable) ?? this.projectRun(run, reusable);
1914
+ }
1915
+ toolNodesUnchanged(run, projected) {
1916
+ const { toolNodes } = projected.compact;
1917
+ if (run.toolNodes.length !== toolNodes.length)
1816
1918
  return false;
1817
- const changedStages = this.changedStages.get(run.id);
1818
- for (let index = 0;index < run.stages.length; index++) {
1819
- const stage = run.stages[index];
1820
- const known = projected.stages.get(stage);
1821
- if (known === undefined || known.compact !== stages[index] || changedStages?.has(stage.id) === true || !stageUnchanged(stage, known))
1822
- return false;
1823
- }
1824
1919
  const changedToolNodes = this.changedToolNodes.get(run.id);
1825
1920
  for (let index = 0;index < run.toolNodes.length; index++) {
1826
1921
  const node = run.toolNodes[index];
@@ -1830,15 +1925,86 @@ class GraphStoreSnapshotBuilder {
1830
1925
  }
1831
1926
  return true;
1832
1927
  }
1928
+ patchStages(run, projected) {
1929
+ const sources = projected.stageSources;
1930
+ if (run.stages.length < sources.length)
1931
+ return;
1932
+ for (let index = 0;index < sources.length; index++)
1933
+ if (run.stages[index] !== sources[index])
1934
+ return;
1935
+ const changed = new Set;
1936
+ const scoped = this.changedStages.get(run.id);
1937
+ if (scoped !== undefined) {
1938
+ if (projected.duplicateStageIds)
1939
+ return;
1940
+ for (const id of scoped) {
1941
+ const position = projected.stagePositions.get(id);
1942
+ if (position !== undefined)
1943
+ changed.add(position);
1944
+ }
1945
+ }
1946
+ for (const position of projected.unsettled)
1947
+ if (!changed.has(position) && !stageUnchanged(sources[position], projected.stages[position]))
1948
+ changed.add(position);
1949
+ if (changed.size === 0 && run.stages.length === sources.length)
1950
+ return projected;
1951
+ const previous = projected.compact;
1952
+ const appendedFrom = sources.length;
1953
+ const compactStages = previous.stages.slice();
1954
+ for (const position of changed) {
1955
+ const stage = projectStage(sources[position]);
1956
+ projected.stages[position] = stage;
1957
+ compactStages[position] = stage.compact;
1958
+ if (stage.settled)
1959
+ projected.unsettled.delete(position);
1960
+ else
1961
+ projected.unsettled.add(position);
1962
+ }
1963
+ for (let position = sources.length;position < run.stages.length; position++) {
1964
+ const source = run.stages[position];
1965
+ const stage = projectStage(source);
1966
+ sources.push(source);
1967
+ projected.stages.push(stage);
1968
+ compactStages.push(stage.compact);
1969
+ if (!stage.settled)
1970
+ projected.unsettled.add(position);
1971
+ if (projected.stagePositions.has(source.id))
1972
+ projected.duplicateStageIds = true;
1973
+ else
1974
+ projected.stagePositions.set(source.id, position);
1975
+ }
1976
+ const compact = { ...previous, stages: compactStages };
1977
+ freezeCompactRun(compact);
1978
+ indexRunFrom(compact, previous, changed, appendedFrom);
1979
+ projected.compact = compact;
1980
+ return projected;
1981
+ }
1833
1982
  projectRun(run, previous) {
1834
1983
  const changedStages = this.changedStages.get(run.id);
1835
- const stages = new Map;
1984
+ const previousStages = new Map;
1985
+ if (previous !== undefined)
1986
+ for (let index = 0;index < previous.stageSources.length; index++)
1987
+ previousStages.set(previous.stageSources[index], previous.stages[index]);
1988
+ const stageSources = [];
1989
+ const stages = [];
1990
+ const stagePositions = new Map;
1991
+ const unsettled = new Set;
1992
+ let duplicateStageIds = false;
1836
1993
  const compactStages = [];
1837
1994
  for (const stage of run.stages) {
1838
- let projected = stages.get(stage) ?? previous?.stages.get(stage);
1995
+ let projected = previousStages.get(stage);
1839
1996
  if (projected === undefined || changedStages?.has(stage.id) === true || !stageUnchanged(stage, projected))
1840
1997
  projected = projectStage(stage);
1841
- stages.set(stage, projected);
1998
+ previousStages.set(stage, projected);
1999
+ const position = stages.length;
2000
+ stageSources.push(stage);
2001
+ stages.push(projected);
2002
+ if (!projected.settled)
2003
+ unsettled.add(position);
2004
+ if (stagePositions.has(stage.id))
2005
+ duplicateStageIds = true;
2006
+ else
2007
+ stagePositions.set(stage.id, position);
1842
2008
  compactStages.push(projected.compact);
1843
2009
  }
1844
2010
  const changedToolNodes = this.changedToolNodes.get(run.id);
@@ -1851,12 +2017,18 @@ class GraphStoreSnapshotBuilder {
1851
2017
  toolNodes.set(node, projected);
1852
2018
  compactToolNodes.push(projected.compact);
1853
2019
  }
2020
+ const compact = compactRun(run, compactStages, compactToolNodes);
2021
+ freezeCompactRun(compact);
1854
2022
  return {
1855
2023
  source: run,
1856
2024
  shape: sourceShape(run),
2025
+ stageSources,
1857
2026
  stages,
2027
+ stagePositions,
2028
+ duplicateStageIds,
2029
+ unsettled,
1858
2030
  toolNodes,
1859
- compact: compactRun(run, compactStages, compactToolNodes)
2031
+ compact
1860
2032
  };
1861
2033
  }
1862
2034
  }
@@ -1880,10 +2052,13 @@ function deepFreezeGraphValue(value2) {
1880
2052
  deepFreezeGraphValue(value2[key]);
1881
2053
  }
1882
2054
  }
1883
- var COMPACT_RESULT_FIELD_LIMIT = 1024, COMPACT_EXIT_OUTPUT_LIMIT;
2055
+ var COMPACT_RESULT_FIELD_LIMIT = 1024, COMPACT_EXIT_OUTPUT_LIMIT, snapshotLineages;
1884
2056
  var init_graph_store_snapshot = __esm(() => {
2057
+ init_run_stage_index();
1885
2058
  init_tool_payload_bounds();
2059
+ init_workflow_run_ownership();
1886
2060
  COMPACT_EXIT_OUTPUT_LIMIT = COMPACT_RESULT_FIELD_LIMIT * 4;
2061
+ snapshotLineages = new WeakMap;
1887
2062
  });
1888
2063
 
1889
2064
  // dist/builtin/workflows/src/shared/expanded-workflow-graph.ts
@@ -1942,23 +2117,148 @@ function isLeafRun(run) {
1942
2117
  function expandWorkflowGraph(snapshot, rootRunId) {
1943
2118
  return createWorkflowGraphExpander(snapshot)(rootRunId);
1944
2119
  }
2120
+ function isSettledStage2(stage) {
2121
+ return stage.status === "completed" || stage.status === "failed" || stage.status === "skipped";
2122
+ }
2123
+ function settledStageCount(stages) {
2124
+ const known = settledStageCounts.get(stages);
2125
+ if (known !== undefined)
2126
+ return known;
2127
+ let count = 0;
2128
+ for (const stage of stages)
2129
+ if (isSettledStage2(stage))
2130
+ count++;
2131
+ if (expandedStageLists.has(stages))
2132
+ settledStageCounts.set(stages, count);
2133
+ return count;
2134
+ }
2135
+ function executionOrderKey(stage) {
2136
+ return stage.executionOrder ?? Number.MAX_SAFE_INTEGER;
2137
+ }
2138
+ function chainStage(stage) {
2139
+ return stage.nodeKind !== "tool" && authoritativeWorkflowChildRunId(stage) === undefined;
2140
+ }
2141
+ function isChainRun(run) {
2142
+ if (toolNodesFor(run).length > 0)
2143
+ return false;
2144
+ let order = Number.NEGATIVE_INFINITY;
2145
+ for (const stage of run.stages) {
2146
+ const next = executionOrderKey(stage);
2147
+ if (next < order || !chainStage(stage))
2148
+ return false;
2149
+ order = next;
2150
+ }
2151
+ return true;
2152
+ }
2153
+ function expandChainFrom(run, previous) {
2154
+ const before = previous.run.stages;
2155
+ if (run.id !== previous.run.id || run.name !== previous.run.name || toolNodesFor(run).length > 0)
2156
+ return;
2157
+ if (run.stages.length < before.length)
2158
+ return;
2159
+ const replaced = [];
2160
+ for (let index = 0;index < before.length; index++) {
2161
+ const stage = run.stages[index];
2162
+ const earlier = before[index];
2163
+ if (stage === earlier)
2164
+ continue;
2165
+ if (stage.id !== earlier.id || stage.executionOrder !== earlier.executionOrder || !sameIds(stage.parentIds, earlier.parentIds) || !chainStage(stage))
2166
+ return;
2167
+ replaced.push(index);
2168
+ }
2169
+ let order = before.length === 0 ? Number.NEGATIVE_INFINITY : executionOrderKey(before[before.length - 1]);
2170
+ for (let index = before.length;index < run.stages.length; index++) {
2171
+ const stage = run.stages[index];
2172
+ const next = executionOrderKey(stage);
2173
+ if (next < order || !chainStage(stage))
2174
+ return;
2175
+ order = next;
2176
+ }
2177
+ const graph = previous.graph;
2178
+ if (replaced.length === 0 && run.stages.length === before.length)
2179
+ return graph;
2180
+ const stages = graph.stages.slice();
2181
+ const nodes = graph.nodes.slice();
2182
+ for (const index of replaced) {
2183
+ const earlier = graph.stages[index];
2184
+ const stage = {
2185
+ ...run.stages[index],
2186
+ id: earlier.id,
2187
+ parentIds: earlier.parentIds,
2188
+ workflowGraphTarget: earlier.workflowGraphTarget
2189
+ };
2190
+ stages[index] = stage;
2191
+ nodes[index] = { kind: "stage", stage };
2192
+ }
2193
+ let settled = settledStageCounts.get(graph.stages);
2194
+ if (settled !== undefined)
2195
+ for (const index of replaced)
2196
+ settled += Number(isSettledStage2(stages[index])) - Number(isSettledStage2(graph.stages[index]));
2197
+ let targets = graph.targets;
2198
+ if (run.stages.length > before.length) {
2199
+ const extended = new Map(graph.targets);
2200
+ for (let index = before.length;index < run.stages.length; index++) {
2201
+ const source = run.stages[index];
2202
+ const target = { runId: run.id, stageId: source.id, runName: run.name, depth: 0 };
2203
+ extended.set(source.id, target);
2204
+ const stage = {
2205
+ ...source,
2206
+ id: source.id,
2207
+ parentIds: Object.freeze([...source.parentIds]),
2208
+ workflowGraphTarget: target
2209
+ };
2210
+ stages.push(stage);
2211
+ nodes.push({ kind: "stage", stage });
2212
+ if (settled !== undefined)
2213
+ settled += Number(isSettledStage2(stage));
2214
+ }
2215
+ targets = extended;
2216
+ }
2217
+ expandedStageLists.add(stages);
2218
+ if (settled !== undefined)
2219
+ settledStageCounts.set(stages, settled);
2220
+ return { stages, renderStages: stages, tools: graph.tools, nodes, targets };
2221
+ }
2222
+ function rememberChainExpansion(memo, runById, run, graph, patched) {
2223
+ if (patched || isChainRun(run))
2224
+ memo.set(run.id, { run, graph });
2225
+ else
2226
+ memo.delete(run.id);
2227
+ for (const runId of memo.keys())
2228
+ if (!runById.has(runId))
2229
+ memo.delete(runId);
2230
+ }
1945
2231
  function createWorkflowGraphExpander(snapshot) {
1946
2232
  let runById;
1947
2233
  let expansions;
2234
+ let chains;
1948
2235
  if (Object.isFrozen(snapshot)) {
1949
2236
  expansions = snapshotExpansions.get(snapshot);
1950
2237
  if (expansions === undefined) {
1951
2238
  expansions = new Map;
1952
2239
  snapshotExpansions.set(snapshot, expansions);
1953
2240
  }
2241
+ const lineage = graphSnapshotLineage(snapshot);
2242
+ if (lineage !== undefined) {
2243
+ chains = chainExpansions.get(lineage);
2244
+ if (chains === undefined) {
2245
+ chains = new Map;
2246
+ chainExpansions.set(lineage, chains);
2247
+ }
2248
+ }
1954
2249
  }
1955
2250
  return (rootRunId) => {
1956
2251
  const known = expansions?.get(rootRunId);
1957
2252
  if (known !== undefined)
1958
2253
  return known;
1959
2254
  runById ??= new Map(snapshot.runs.map((run) => [run.id, run]));
1960
- const graph = expandIndexedWorkflowGraph(runById, rootRunId);
2255
+ const root = runById.get(rootRunId);
2256
+ const previous = root === undefined ? undefined : chains?.get(rootRunId);
2257
+ const patched = root === undefined || previous === undefined ? undefined : expandChainFrom(root, previous);
2258
+ const graph = patched ?? expandIndexedWorkflowGraph(runById, rootRunId);
1961
2259
  expansions?.set(rootRunId, graph);
2260
+ if (chains !== undefined && root !== undefined)
2261
+ rememberChainExpansion(chains, runById, root, graph, patched !== undefined);
1962
2262
  return graph;
1963
2263
  };
1964
2264
  }
@@ -2113,8 +2413,10 @@ function expandIndexedWorkflowGraph(runById, rootRunId) {
2113
2413
  return result;
2114
2414
  };
2115
2415
  const expanded = expandRun(root, 0, []);
2416
+ const stages = expanded.stages.filter((stage) => stage.nodeKind !== "tool");
2417
+ expandedStageLists.add(stages);
2116
2418
  return {
2117
- stages: expanded.stages.filter((stage) => stage.nodeKind !== "tool"),
2419
+ stages,
2118
2420
  renderStages: expanded.stages,
2119
2421
  tools: expanded.tools,
2120
2422
  nodes: expanded.nodes,
@@ -2262,8 +2564,9 @@ function expandedStageLabel(stage) {
2262
2564
  const depthPrefix = target.depth > 0 ? `${childAliasFor(stage) ?? target.runName}:` : "";
2263
2565
  return `${depthPrefix}${stage.name} (${target.runId}/${target.stageId})`;
2264
2566
  }
2265
- var MissingWorkflowToolNodesError, leafExpansions, snapshotExpansions;
2567
+ var MissingWorkflowToolNodesError, leafExpansions, snapshotExpansions, settledStageCounts, expandedStageLists, chainExpansions;
2266
2568
  var init_expanded_workflow_graph = __esm(() => {
2569
+ init_graph_store_snapshot();
2267
2570
  init_workflow_run_ownership();
2268
2571
  MissingWorkflowToolNodesError = class MissingWorkflowToolNodesError extends Error {
2269
2572
  runId;
@@ -2275,6 +2578,9 @@ var init_expanded_workflow_graph = __esm(() => {
2275
2578
  };
2276
2579
  leafExpansions = new WeakMap;
2277
2580
  snapshotExpansions = new WeakMap;
2581
+ settledStageCounts = new WeakMap;
2582
+ expandedStageLists = new WeakSet;
2583
+ chainExpansions = new WeakMap;
2278
2584
  });
2279
2585
 
2280
2586
  // dist/builtin/workflows/src/shared/workflow-activity.ts
@@ -2298,7 +2604,68 @@ function isStoppingRun(run, rootRunId, runs, stoppingRunIds) {
2298
2604
  }
2299
2605
  return stoppingRunIds.has(rootRunId);
2300
2606
  }
2301
- function projectRoot(rootRunId, runs, runById, ownership) {
2607
+ function isQuietStage(stage) {
2608
+ return (stage.status === "completed" || stage.status === "failed" || stage.status === "skipped") && stage.pendingPrompt === undefined;
2609
+ }
2610
+ function indexStages(stages) {
2611
+ const positions = new Map;
2612
+ const active = new Set;
2613
+ for (let position = 0;position < stages.length; position++) {
2614
+ const stage = stages[position];
2615
+ if (positions.has(stage.id))
2616
+ return;
2617
+ positions.set(stage.id, position);
2618
+ if (!isQuietStage(stage))
2619
+ active.add(position);
2620
+ }
2621
+ return { stages, positions, active };
2622
+ }
2623
+ function reindexStages(stages, previous) {
2624
+ if (previous === undefined || stages.length < previous.stages.length)
2625
+ return indexStages(stages);
2626
+ if (stages === previous.stages)
2627
+ return previous;
2628
+ const { positions, active } = previous;
2629
+ for (let position = 0;position < previous.stages.length; position++) {
2630
+ const stage = stages[position];
2631
+ if (stage === previous.stages[position])
2632
+ continue;
2633
+ if (stage.id !== previous.stages[position].id)
2634
+ return indexStages(stages);
2635
+ if (isQuietStage(stage))
2636
+ active.delete(position);
2637
+ else
2638
+ active.add(position);
2639
+ }
2640
+ for (let position = previous.stages.length;position < stages.length; position++) {
2641
+ const stage = stages[position];
2642
+ if (positions.has(stage.id))
2643
+ return indexStages(stages);
2644
+ positions.set(stage.id, position);
2645
+ if (!isQuietStage(stage))
2646
+ active.add(position);
2647
+ }
2648
+ return { stages, positions, active };
2649
+ }
2650
+ function ownedNodeIdsByRun(keys, runIds) {
2651
+ const owned = new Map;
2652
+ for (const key of keys) {
2653
+ for (let colon = key.indexOf(":");colon !== -1; colon = key.indexOf(":", colon + 1)) {
2654
+ const runId = key.slice(0, colon);
2655
+ if (!runIds.has(runId))
2656
+ continue;
2657
+ const ids = owned.get(runId);
2658
+ if (ids === undefined)
2659
+ owned.set(runId, [key.slice(colon + 1)]);
2660
+ else
2661
+ ids.push(key.slice(colon + 1));
2662
+ }
2663
+ }
2664
+ return owned;
2665
+ }
2666
+ function projectRoot(rootRunId, runs, runById, ownership, stageIndexOf = () => {
2667
+ return;
2668
+ }) {
2302
2669
  let activeExecutionCount = 0;
2303
2670
  let waitingStages = 0;
2304
2671
  let humanWaits = 0;
@@ -2312,6 +2679,9 @@ function projectRoot(rootRunId, runs, runById, ownership) {
2312
2679
  let stoppingExecutionCount = 0;
2313
2680
  let independentContinuation = false;
2314
2681
  let childContinuation = false;
2682
+ const runIds = new Set(runs.map((run) => run.id));
2683
+ const executingByRun = ownedNodeIdsByRun(ownership.executingStageIds, runIds);
2684
+ const retryingByRun = ownedNodeIdsByRun(ownership.retryingStageIds, runIds);
2315
2685
  for (const run of runs) {
2316
2686
  const runStopping = isStoppingRun(run, rootRunId, runById, ownership.stoppingRunIds);
2317
2687
  let runExecutionCount = run.toolNodes.filter((tool) => ownership.executingToolNodeIds.has(workflowActivityNodeKey(run.id, tool.id))).length;
@@ -2329,18 +2699,40 @@ function projectRoot(rootRunId, runs, runById, ownership) {
2329
2699
  else
2330
2700
  manualWaits++;
2331
2701
  }
2332
- const statuses = new Map([...run.stages, ...run.toolNodes].map((node) => [
2333
- node.id,
2334
- endedStatuses.has(node.status) ? "ended" : node.status
2335
- ]));
2702
+ const index = stageIndexOf(run);
2703
+ const nodeStatus = (node) => endedStatuses.has(node.status) ? "ended" : node.status;
2704
+ const statuses = index === undefined ? new Map([...run.stages, ...run.toolNodes].map((node) => [node.id, nodeStatus(node)])) : new Map(run.toolNodes.map((node) => [node.id, nodeStatus(node)]));
2705
+ const statusOf = (id) => {
2706
+ if (index === undefined || statuses.has(id))
2707
+ return statuses.get(id);
2708
+ const position = index.positions.get(id);
2709
+ return position === undefined ? undefined : nodeStatus(index.stages[position]);
2710
+ };
2336
2711
  const live = ownership.liveRunIds?.has(run.id) === true;
2337
2712
  for (const tool of run.toolNodes) {
2338
- if (live && run.status === "running" && !runStopping && tool.status === "pending" && tool.parentIds.every((id) => statuses.get(id) === "ended")) {
2713
+ if (live && run.status === "running" && !runStopping && tool.status === "pending" && tool.parentIds.every((id) => statusOf(id) === "ended")) {
2339
2714
  runnable = true;
2340
2715
  independentContinuation = true;
2341
2716
  }
2342
2717
  }
2343
- for (const stage of run.stages) {
2718
+ const activeStages = index === undefined ? run.stages : [...index.active].sort((left, right) => left - right).map((position) => index.stages[position]);
2719
+ if (index !== undefined) {
2720
+ const quietOwned = (stageId) => {
2721
+ const position = index.positions.get(stageId);
2722
+ return position !== undefined && !index.active.has(position);
2723
+ };
2724
+ for (const stageId of executingByRun.get(run.id) ?? [])
2725
+ if (quietOwned(stageId))
2726
+ runExecutionCount++;
2727
+ for (const stageId of retryingByRun.get(run.id) ?? []) {
2728
+ if (!quietOwned(stageId))
2729
+ continue;
2730
+ retrying = true;
2731
+ if (!runStopping)
2732
+ independentContinuation = true;
2733
+ }
2734
+ }
2735
+ for (const stage of activeStages) {
2344
2736
  if (run.status === "running" && stage.status === "paused")
2345
2737
  paused = true;
2346
2738
  if (live && run.status === "running" && !runStopping && stage.status === "suspended")
@@ -2361,14 +2753,14 @@ function projectRoot(rootRunId, runs, runById, ownership) {
2361
2753
  if (!runStopping)
2362
2754
  independentContinuation = true;
2363
2755
  }
2364
- if (run.status === "running" && !runStopping && stage.status === "pending" && stage.parentIds.every((id) => statuses.get(id) === "ended")) {
2756
+ if (run.status === "running" && !runStopping && stage.status === "pending" && stage.parentIds.every((id) => statusOf(id) === "ended")) {
2365
2757
  runnable = true;
2366
2758
  independentContinuation = true;
2367
2759
  }
2368
2760
  }
2369
2761
  const childBoundary = (stage) => stage.status === "running" && stage.workflowChildRun !== undefined;
2370
- if (live && run.status === "running" && !runStopping && !run.pendingPrompt && run.blockedAt === undefined && run.failureDisposition !== "active_blocked" && run.stages.every((stage) => !stage.pendingPrompt && (stage.status === "completed" || stage.status === "failed" || stage.status === "skipped" || childBoundary(stage))) && run.toolNodes.every((tool) => endedStatuses.has(tool.status))) {
2371
- if (run.stages.some(childBoundary))
2762
+ if (live && run.status === "running" && !runStopping && !run.pendingPrompt && run.blockedAt === undefined && run.failureDisposition !== "active_blocked" && activeStages.every((stage) => !stage.pendingPrompt && (stage.status === "completed" || stage.status === "failed" || stage.status === "skipped" || childBoundary(stage))) && run.toolNodes.every((tool) => endedStatuses.has(tool.status))) {
2763
+ if (activeStages.some(childBoundary))
2372
2764
  childContinuation = true;
2373
2765
  else {
2374
2766
  runnable = true;
@@ -2420,14 +2812,36 @@ function projectPrompt(prompt) {
2420
2812
  createdAt: prompt.createdAt
2421
2813
  };
2422
2814
  }
2815
+ function frozenGraphNode(node) {
2816
+ Object.freeze(node.parentIds);
2817
+ if (node.kind === "stage" && node.pendingPrompt !== undefined) {
2818
+ if (node.pendingPrompt.choices !== undefined)
2819
+ Object.freeze(node.pendingPrompt.choices);
2820
+ Object.freeze(node.pendingPrompt);
2821
+ }
2822
+ return Object.freeze(node);
2823
+ }
2423
2824
  function projectGraphNode(node) {
2424
2825
  let projected = projectedGraphNodes.get(node);
2425
2826
  if (projected === undefined) {
2426
- projected = projectExpandedNode(node);
2827
+ projected = frozenGraphNode(projectExpandedNode(node));
2427
2828
  projectedGraphNodes.set(node, projected);
2428
2829
  }
2429
2830
  return projected;
2430
2831
  }
2832
+ function projectNodes(expanded, previous) {
2833
+ if (previous === undefined)
2834
+ return expanded.map(projectGraphNode);
2835
+ const projected = previous.projected.slice(0, expanded.length);
2836
+ for (let index = 0;index < expanded.length; index++) {
2837
+ const node = expanded[index];
2838
+ if (index >= projected.length)
2839
+ projected.push(projectGraphNode(node));
2840
+ else if (node !== previous.expanded[index])
2841
+ projected[index] = projectGraphNode(node);
2842
+ }
2843
+ return projected;
2844
+ }
2431
2845
  function projectExpandedNode(node) {
2432
2846
  if (node.kind === "stage") {
2433
2847
  const { stage } = node;
@@ -2459,11 +2873,11 @@ function projectExpandedNode(node) {
2459
2873
  ordinal: tool.ordinal
2460
2874
  };
2461
2875
  }
2462
- function projectGraph(graph, runs) {
2876
+ function projectGraph(nodes, runs) {
2463
2877
  const runPrompts = runs.flatMap((run) => run.pendingPrompt === undefined ? [] : [{ ...projectPrompt(run.pendingPrompt), runId: run.id }]);
2464
- return { nodes: graph.nodes.map(projectGraphNode), ...runPrompts.length === 0 ? {} : { runPrompts } };
2878
+ return { nodes, ...runPrompts.length === 0 ? {} : { runPrompts } };
2465
2879
  }
2466
- function projectWorkflowActivity({ snapshot, ownership }) {
2880
+ function projectActivities({ snapshot, ownership }, stageIndexOf, projectRootNodes) {
2467
2881
  const byId = new Map(snapshot.runs.map((run) => [run.id, run]));
2468
2882
  const roots = new Map;
2469
2883
  for (const run of snapshot.runs) {
@@ -2476,10 +2890,34 @@ function projectWorkflowActivity({ snapshot, ownership }) {
2476
2890
  }
2477
2891
  const expand = createWorkflowGraphExpander(snapshot);
2478
2892
  return [...roots].map(([id, runs]) => ({
2479
- ...projectRoot(id, runs, byId, ownership),
2480
- graph: projectGraph(expand(id), runs)
2893
+ ...projectRoot(id, runs, byId, ownership, stageIndexOf),
2894
+ graph: projectGraph(projectRootNodes(id, expand(id).nodes), runs)
2481
2895
  }));
2482
2896
  }
2897
+
2898
+ class WorkflowActivityProjector {
2899
+ stageIndexes = new Map;
2900
+ projectedNodes = new Map;
2901
+ project(input) {
2902
+ const previousIndexes = this.stageIndexes;
2903
+ const previousNodes = this.projectedNodes;
2904
+ const stageIndexes = new Map;
2905
+ const projectedNodes = new Map;
2906
+ const activities = projectActivities(input, (run) => {
2907
+ const index = reindexStages(run.stages, previousIndexes.get(run.id));
2908
+ if (index !== undefined)
2909
+ stageIndexes.set(run.id, index);
2910
+ return index;
2911
+ }, (rootRunId, expanded) => {
2912
+ const projected = projectNodes(expanded, previousNodes.get(rootRunId));
2913
+ projectedNodes.set(rootRunId, { expanded, projected });
2914
+ return projected;
2915
+ });
2916
+ this.stageIndexes = stageIndexes;
2917
+ this.projectedNodes = projectedNodes;
2918
+ return activities;
2919
+ }
2920
+ }
2483
2921
  var endedStatuses, projectedGraphNodes;
2484
2922
  var init_workflow_activity = __esm(() => {
2485
2923
  init_expanded_workflow_graph();
@@ -3341,13 +3779,14 @@ function pendingWorkflowStageStatus(run, stage, resolveOwningRunStatus, resolveB
3341
3779
  };
3342
3780
  }
3343
3781
  function pendingWorkflowStageStatuses(run, resolveOwningRunStatus, resolveBoundarySegments) {
3344
- return run.stages.flatMap((stage) => {
3782
+ return runStageIndex(run).pending.flatMap((stage) => {
3345
3783
  const pending = pendingWorkflowStageStatus(run, stage, resolveOwningRunStatus, resolveBoundarySegments);
3346
3784
  return pending === undefined ? [] : [pending];
3347
3785
  });
3348
3786
  }
3349
3787
  var ADDRESSABLE_STAGE_STATUSES;
3350
3788
  var init_pending_stage_status = __esm(() => {
3789
+ init_run_stage_index();
3351
3790
  init_store_internal();
3352
3791
  init_workflow_run_ownership();
3353
3792
  init_workflow_stage_target();
@@ -4234,7 +4673,44 @@ function createStageControlRegistry() {
4234
4673
  return [];
4235
4674
  return [...runMap.values()].filter((entry) => entry.controlsDependencies);
4236
4675
  }
4676
+ function createEntry(runId, stageId, handle, fields) {
4677
+ const entry = { handle, ...fields, leases: new Set, epoch: 0 };
4678
+ entry.stopWatching = handle.releaseGate?.onHoldLifted(() => releaseWhenLetGo(runId, stageId, entry));
4679
+ return entry;
4680
+ }
4681
+ function stopWatching(entry) {
4682
+ entry.stopWatching?.();
4683
+ entry.stopWatching = undefined;
4684
+ clearTimeout(entry.claimTimer);
4685
+ entry.claimTimer = undefined;
4686
+ }
4687
+ function markClaimed(runId, stageId, entry) {
4688
+ entry.permanent = true;
4689
+ entry.epoch += 1;
4690
+ entry.holdsAtClaim = entry.handle.releaseGate?.holdsTaken();
4691
+ clearTimeout(entry.claimTimer);
4692
+ if (entry.handle.releaseGate === undefined)
4693
+ return;
4694
+ entry.claimTimer = setTimeout(() => {
4695
+ entry.claimTimer = undefined;
4696
+ entry.holdsAtClaim = undefined;
4697
+ releaseWhenLetGo(runId, stageId, entry);
4698
+ }, CLAIM_GRACE_MS);
4699
+ entry.claimTimer.unref();
4700
+ }
4701
+ function unusedSinceClaim(entry, gate) {
4702
+ return gate.holdsTaken() <= (entry.holdsAtClaim ?? -1);
4703
+ }
4704
+ function releaseWhenLetGo(runId, stageId, entry) {
4705
+ const gate = entry.handle.releaseGate;
4706
+ if (gate === undefined || !entry.releaseWanted || entry.leases.size > 0)
4707
+ return;
4708
+ if (unusedSinceClaim(entry, gate) || !gate.idle())
4709
+ return;
4710
+ releaseIdleEntry(runId, stageId, entry).catch((error) => console.warn("atomic-workflows: completed stage session release failed", error));
4711
+ }
4237
4712
  function disposeEntry(entry) {
4713
+ stopWatching(entry);
4238
4714
  if (entry.disposal !== undefined)
4239
4715
  return entry.disposal;
4240
4716
  try {
@@ -4259,7 +4735,26 @@ function createStageControlRegistry() {
4259
4735
  function disposeEntryInBackground(entry, message) {
4260
4736
  disposeEntry(entry).catch((err) => console.warn(message, err));
4261
4737
  }
4262
- async function releaseIdleEntry(runId, stageId, entry) {
4738
+ function releaseIdleEntry(runId, stageId, entry) {
4739
+ if (entry.releasing !== undefined) {
4740
+ entry.releaseAgain = true;
4741
+ return entry.releasing;
4742
+ }
4743
+ entry.releasing = releaseUntilSettled(runId, stageId, entry).finally(() => {
4744
+ entry.releasing = undefined;
4745
+ });
4746
+ return entry.releasing;
4747
+ }
4748
+ async function releaseUntilSettled(runId, stageId, entry) {
4749
+ do {
4750
+ entry.releaseAgain = false;
4751
+ await releaseUnlessUsed(runId, stageId, entry);
4752
+ } while (releaseRequestedAgain(entry) && _byRun.get(runId)?.get(stageId) === entry);
4753
+ }
4754
+ function releaseRequestedAgain(entry) {
4755
+ return entry.releaseAgain === true;
4756
+ }
4757
+ async function releaseUnlessUsed(runId, stageId, entry) {
4263
4758
  const gate = entry.handle.releaseGate;
4264
4759
  if (gate === undefined || entry.disposal !== undefined)
4265
4760
  return;
@@ -4270,7 +4765,7 @@ function createStageControlRegistry() {
4270
4765
  const runMap = _byRun.get(runId);
4271
4766
  if (runMap?.get(stageId) !== entry || entry.epoch !== epoch || entry.leases.size > 0)
4272
4767
  return;
4273
- if (entry.disposal !== undefined || !gate.idle())
4768
+ if (unusedSinceClaim(entry, gate) || !gate.idle())
4274
4769
  return;
4275
4770
  const { stageName, sessionId } = entry.handle;
4276
4771
  rememberSessionStore(entry.handle, savedIn);
@@ -4343,13 +4838,13 @@ function createStageControlRegistry() {
4343
4838
  rememberSessionStore(handle);
4344
4839
  const runMap = ensureRun(handle.runId);
4345
4840
  const displaced = runMap.get(handle.stageId);
4346
- runMap.set(handle.stageId, {
4347
- handle,
4841
+ runMap.set(handle.stageId, createEntry(handle.runId, handle.stageId, handle, {
4348
4842
  controlsDependencies: true,
4349
4843
  permanent: true,
4350
- leases: new Set,
4351
- epoch: 0
4352
- });
4844
+ releaseWanted: handle.releaseGate?.releaseWhenIdle === true
4845
+ }));
4846
+ if (displaced !== undefined)
4847
+ stopWatching(displaced);
4353
4848
  if (displaced !== undefined && displaced.handle !== handle && !displaced.permanent) {
4354
4849
  disposeEntryInBackground(displaced, "atomic-workflows: displaced provisional stage handle dispose failed");
4355
4850
  }
@@ -4357,8 +4852,10 @@ function createStageControlRegistry() {
4357
4852
  const existing = _byRun.get(handle.runId);
4358
4853
  if (!existing)
4359
4854
  return;
4360
- if (existing.get(handle.stageId)?.handle === handle) {
4855
+ const entry = existing.get(handle.stageId);
4856
+ if (entry?.handle === handle) {
4361
4857
  rememberSessionStore(handle);
4858
+ stopWatching(entry);
4362
4859
  existing.delete(handle.stageId);
4363
4860
  }
4364
4861
  if (existing.size === 0)
@@ -4369,8 +4866,7 @@ function createStageControlRegistry() {
4369
4866
  const runMap = ensureRun(runId);
4370
4867
  const existing = runMap.get(stageId);
4371
4868
  if (existing !== undefined && existing.handle.isDisposed !== true) {
4372
- existing.permanent = true;
4373
- existing.epoch += 1;
4869
+ markClaimed(runId, stageId, existing);
4374
4870
  return existing.handle;
4375
4871
  }
4376
4872
  if (existing !== undefined) {
@@ -4378,13 +4874,13 @@ function createStageControlRegistry() {
4378
4874
  disposeEntryInBackground(existing, "atomic-workflows: stale stage handle dispose failed");
4379
4875
  }
4380
4876
  const handle = create();
4381
- runMap.set(handle.stageId, {
4382
- handle,
4877
+ const entry = createEntry(runId, handle.stageId, handle, {
4383
4878
  controlsDependencies: false,
4384
4879
  permanent: true,
4385
- leases: new Set,
4386
- epoch: 0
4880
+ releaseWanted: true
4387
4881
  });
4882
+ markClaimed(runId, handle.stageId, entry);
4883
+ runMap.set(handle.stageId, entry);
4388
4884
  return handle;
4389
4885
  },
4390
4886
  acquireDetached(runId, stageId, create) {
@@ -4396,13 +4892,11 @@ function createStageControlRegistry() {
4396
4892
  entry = undefined;
4397
4893
  }
4398
4894
  if (entry === undefined) {
4399
- entry = {
4400
- handle: create(),
4895
+ entry = createEntry(runId, stageId, create(), {
4401
4896
  controlsDependencies: false,
4402
4897
  permanent: false,
4403
- leases: new Set,
4404
- epoch: 0
4405
- };
4898
+ releaseWanted: true
4899
+ });
4406
4900
  runMap.set(stageId, entry);
4407
4901
  }
4408
4902
  const leasedEntry = entry;
@@ -4433,8 +4927,12 @@ function createStageControlRegistry() {
4433
4927
  await leasedEntry.disposal;
4434
4928
  return;
4435
4929
  }
4436
- if (leasedEntry.permanent || leasedEntry.leases.size > 0)
4930
+ if (leasedEntry.leases.size > 0)
4437
4931
  return;
4932
+ if (leasedEntry.permanent) {
4933
+ releaseWhenLetGo(runId, stageId, leasedEntry);
4934
+ return;
4935
+ }
4438
4936
  runMap.delete(stageId);
4439
4937
  if (runMap.size === 0)
4440
4938
  _byRun.delete(runId);
@@ -4459,10 +4957,8 @@ function createStageControlRegistry() {
4459
4957
  },
4460
4958
  claim(runId, stageId) {
4461
4959
  const entry = _byRun.get(runId)?.get(stageId);
4462
- if (entry !== undefined) {
4463
- entry.permanent = true;
4464
- entry.epoch += 1;
4465
- }
4960
+ if (entry !== undefined)
4961
+ markClaimed(runId, stageId, entry);
4466
4962
  return entry?.handle;
4467
4963
  },
4468
4964
  get(runId, stageId) {
@@ -4519,12 +5015,14 @@ function createStageControlRegistry() {
4519
5015
  for (const [stageId, entry] of entries) {
4520
5016
  if (entry === undefined)
4521
5017
  continue;
5018
+ entry.releaseWanted = true;
4522
5019
  try {
4523
5020
  await releaseIdleEntry(runId, stageId, entry);
4524
5021
  } catch (error) {
4525
5022
  console.warn("atomic-workflows: completed stage session release failed", error);
4526
5023
  }
4527
5024
  }
5025
+ await Promise.allSettled([...pendingDisposals]);
4528
5026
  },
4529
5027
  onStageReleased(listener) {
4530
5028
  releaseListeners.add(listener);
@@ -4542,7 +5040,7 @@ function adoptStageControlRegistry(scope, preserveCurrentWhenTargetExists = fals
4542
5040
  function currentStageControlRegistry() {
4543
5041
  return singleton.current();
4544
5042
  }
4545
- var SESSION_KEY = "workflows:stage-control:v1", singleton, stageControlRegistry;
5043
+ var CLAIM_GRACE_MS = 1e4, SESSION_KEY = "workflows:stage-control:v1", singleton, stageControlRegistry;
4546
5044
  var init_stage_control_registry = __esm(() => {
4547
5045
  init_session_scoped_singleton();
4548
5046
  singleton = createSessionScopedSingleton(SESSION_KEY, createStageControlRegistry);
@@ -7627,8 +8125,11 @@ function stageIdentity(checkpoint) {
7627
8125
  function checkpointKey(c) {
7628
8126
  return `${c.kind}:${c.checkpointId}`;
7629
8127
  }
8128
+ function sharingOutputAsResult(checkpoint) {
8129
+ return checkpoint.kind === "stage" && typeof checkpoint.output === "string" && checkpoint.result === checkpoint.output ? { ...checkpoint, result: checkpoint.output } : checkpoint;
8130
+ }
7630
8131
  function normalizedCheckpoint(recorded) {
7631
- const checkpoint = recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded;
8132
+ const checkpoint = sharingOutputAsResult(recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded);
7632
8133
  return checkpoint.kind === "stage" && checkpoint.topology === undefined ? {
7633
8134
  ...checkpoint,
7634
8135
  topology: {
@@ -18269,6 +18770,25 @@ function writtenHandle(event) {
18269
18770
  return;
18270
18771
  return event.payload;
18271
18772
  }
18773
+ function sharingWrittenText(entry, written) {
18774
+ const folded = entry.event;
18775
+ if (folded.type !== RUN_EVENT_TYPES.checkpointRecorded || written.type !== RUN_EVENT_TYPES.checkpointRecorded)
18776
+ return entry;
18777
+ const decoded = folded.payload;
18778
+ const source = written.payload;
18779
+ if (decoded.kind !== "stage" || source.kind !== "stage")
18780
+ return entry;
18781
+ const sharesOutput = typeof source.output === "string" && decoded.output === source.output;
18782
+ const sharesResult = typeof source.result === "string" && decoded.result === source.result;
18783
+ if (!sharesOutput && !sharesResult)
18784
+ return entry;
18785
+ const payload = {
18786
+ ...decoded,
18787
+ ...sharesOutput ? { output: source.output } : {},
18788
+ ...sharesResult ? { result: source.result } : {}
18789
+ };
18790
+ return { ...entry, event: { ...folded, payload } };
18791
+ }
18272
18792
  function snapshotNeedsHistory(tail) {
18273
18793
  const handle = writtenHandle(tail.snapshot.event);
18274
18794
  return handle !== undefined && (handle.pendingStageMessageChange !== undefined || hasPendingStageDeliveryDelta(handle.pendingStageMessages));
@@ -18693,7 +19213,7 @@ class JournalDurableBackend {
18693
19213
  for (const entry of yield* this.entries(runId, nextSeq))
18694
19214
  this.fold(entry);
18695
19215
  }
18696
- this.fold(outcome.entry);
19216
+ this.fold(sharingWrittenText(outcome.entry, event));
18697
19217
  } catch (error) {
18698
19218
  if (error instanceof Error)
18699
19219
  throw yield* this.mapOwnership(error, runId);
@@ -18936,7 +19456,7 @@ class JournalDurableBackend {
18936
19456
  if (result.value.entry.seq > nextSeq)
18937
19457
  for (const entry of yield* this.entries(runId, nextSeq))
18938
19458
  this.fold(entry);
18939
- this.fold(result.value.entry);
19459
+ this.fold(sharingWrittenText(result.value.entry, append.event));
18940
19460
  append.resolve();
18941
19461
  }
18942
19462
  settled++;
@@ -24547,6 +25067,55 @@ function reconcileTerminalRunResult(runId, runSnapshot, activeStore, fallback, o
24547
25067
  onRunEnd?.(runId, result.status, result.result, result.error, result.exitReason);
24548
25068
  return result;
24549
25069
  }
25070
+ function announceSettledStageEdit(store, runId, stage) {
25071
+ if (isTerminalStageStatus(stage.status))
25072
+ store.editRun(runId, () => ({ stageIds: [stage.id] }));
25073
+ }
25074
+ function endStageWithHook(store, runId, stage, hook) {
25075
+ const outcome = hook?.(runId, stage);
25076
+ announceSettledStageEdit(store, runId, stage);
25077
+ if (!isPromiseLike(outcome))
25078
+ return;
25079
+ Promise.resolve(outcome).then(() => announceSettledStageEdit(store, runId, stage), (error) => {
25080
+ announceSettledStageEdit(store, runId, stage);
25081
+ throw error;
25082
+ });
25083
+ }
25084
+ function isPromiseLike(value2) {
25085
+ return (typeof value2 === "object" || typeof value2 === "function") && value2 !== null && typeof value2.then === "function";
25086
+ }
25087
+ function applyModelFallbackMetaToStage(stage, meta) {
25088
+ const { model, thinkingLevel, rateLimits, routerSelection, warnings } = stage;
25089
+ if (meta.model !== undefined)
25090
+ stage.model = meta.model;
25091
+ if (meta.thinkingLevel !== undefined)
25092
+ stage.thinkingLevel = meta.thinkingLevel;
25093
+ else
25094
+ delete stage.thinkingLevel;
25095
+ if (meta.attemptedModels !== undefined)
25096
+ stage.attemptedModels = meta.attemptedModels;
25097
+ if (meta.modelAttempts !== undefined)
25098
+ stage.modelAttempts = meta.modelAttempts;
25099
+ if (meta.rateLimits !== undefined)
25100
+ stage.rateLimits = meta.rateLimits;
25101
+ if (meta.routerSelection !== undefined)
25102
+ stage.routerSelection = meta.routerSelection;
25103
+ if (meta.warnings !== undefined) {
25104
+ if (meta.warnings.length > 0)
25105
+ stage.warnings = meta.warnings;
25106
+ else
25107
+ delete stage.warnings;
25108
+ }
25109
+ return model !== stage.model || thinkingLevel !== stage.thinkingLevel || rateLimits !== stage.rateLimits || routerSelection !== stage.routerSelection || warnings !== stage.warnings;
25110
+ }
25111
+ function applySessionMetaToStage(stage, meta) {
25112
+ const { sessionId, sessionFile } = stage;
25113
+ if (meta.sessionId !== undefined)
25114
+ stage.sessionId = meta.sessionId;
25115
+ if (meta.sessionFile !== undefined)
25116
+ stage.sessionFile = meta.sessionFile;
25117
+ return sessionId !== stage.sessionId || sessionFile !== stage.sessionFile;
25118
+ }
24550
25119
  function applyFailureToStage(stage, failure) {
24551
25120
  stage.status = "failed";
24552
25121
  stage.error = failure.userMessage;
@@ -25252,6 +25821,7 @@ function buildPromptNodeUiAdapter(input) {
25252
25821
  input.activeStore.recordStageAttachable(input.runId, stageId, false);
25253
25822
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
25254
25823
  await input.opts.onStageEnd?.(input.runId, stageSnapshot);
25824
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
25255
25825
  if (input.opts.persistence) {
25256
25826
  await appendStageEnd(input.opts.persistence, {
25257
25827
  runId: input.runId,
@@ -25607,15 +26177,17 @@ function createStageScheduler(input) {
25607
26177
  };
25608
26178
  const descendantsOf = (stageId) => input.runSnapshot.stages.filter((stage) => stage.id !== stageId && hasAncestor(stage, stageId));
25609
26179
  const blockingAncestorFor = (stage) => {
26180
+ const holding = new Set(input.runSnapshot.stages.filter((candidate) => candidate.status === "paused" || candidate.status === "blocked").map((candidate) => candidate.id));
26181
+ if (holding.size === 0)
26182
+ return;
25610
26183
  const queue = [...stage.parentIds];
25611
26184
  const seen = new Set;
25612
- while (queue.length > 0) {
25613
- const next = queue.shift();
25614
- if (next === undefined || seen.has(next))
26185
+ for (let index = 0;index < queue.length; index++) {
26186
+ const next = queue[index];
26187
+ if (seen.has(next))
25615
26188
  continue;
25616
26189
  seen.add(next);
25617
- const ancestor = stageById(next);
25618
- if (ancestor?.status === "paused" || ancestor?.status === "blocked")
26190
+ if (holding.has(next))
25619
26191
  return next;
25620
26192
  queue.push(...input.tracker.getParents(next));
25621
26193
  }
@@ -74885,9 +75457,9 @@ function isBrokerProtocolRange(value2) {
74885
75457
  function protocolRangeOf(value2) {
74886
75458
  return value2 === undefined ? LEGACY_BROKER_PROTOCOL : { min: value2.min, max: value2.max };
74887
75459
  }
74888
- var BROKER_PROTOCOL, LEGACY_BROKER_PROTOCOL, VERIFIED_REGISTRATION_PROTOCOL = 2;
75460
+ var BROKER_PROTOCOL, LEGACY_BROKER_PROTOCOL, VERIFIED_REGISTRATION_PROTOCOL = 2, HOSTED_SESSIONS_PROTOCOL = 3;
74889
75461
  var init_protocol_version = __esm(() => {
74890
- BROKER_PROTOCOL = { min: 1, max: 2 };
75462
+ BROKER_PROTOCOL = { min: 1, max: 3 };
74891
75463
  LEGACY_BROKER_PROTOCOL = { min: 1, max: 1 };
74892
75464
  });
74893
75465
 
@@ -75204,6 +75776,30 @@ function isSessionInfo(value2) {
75204
75776
  return false;
75205
75777
  return session.status === undefined || typeof session.status === "string";
75206
75778
  }
75779
+ function isSessionRegistration(value2) {
75780
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) {
75781
+ return false;
75782
+ }
75783
+ const session = value2;
75784
+ if (typeof session.cwd !== "string" || typeof session.model !== "string" || typeof session.pid !== "number" || typeof session.startedAt !== "number" || typeof session.lastActivity !== "number") {
75785
+ return false;
75786
+ }
75787
+ if (session.name !== undefined && typeof session.name !== "string") {
75788
+ return false;
75789
+ }
75790
+ if (session.group !== undefined && typeof session.group !== "string") {
75791
+ return false;
75792
+ }
75793
+ if (session.replyCapability !== undefined && session.replyCapability !== "live" && session.replyCapability !== "terminal")
75794
+ return false;
75795
+ if (session.recipientPurpose !== undefined && session.recipientPurpose !== "agent" && session.recipientPurpose !== "control") {
75796
+ return false;
75797
+ }
75798
+ if (session.groups !== undefined && (!Array.isArray(session.groups) || !session.groups.every((group) => typeof group === "string"))) {
75799
+ return false;
75800
+ }
75801
+ return session.status === undefined || typeof session.status === "string";
75802
+ }
75207
75803
 
75208
75804
  // dist/builtin/intercom/broker/delivery-failure-reason.ts
75209
75805
  function isDeliveryFailureReasonCode(value2) {
@@ -75217,7 +75813,8 @@ var init_delivery_failure_reason = __esm(() => {
75217
75813
  "recipient_not_restored",
75218
75814
  "recipient_parked",
75219
75815
  "released_reply_answered",
75220
- "released_reply_in_flight"
75816
+ "released_reply_in_flight",
75817
+ "not_hosted_by_connection"
75221
75818
  ]);
75222
75819
  });
75223
75820
 
@@ -75442,6 +76039,8 @@ function isIntercomRecipientGoneErrorCode(value2) {
75442
76039
  return CODES5.has(value2);
75443
76040
  }
75444
76041
  function hintFor3(code, childId) {
76042
+ if (code === "recipient_stage_released")
76043
+ 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.";
75445
76044
  if (code === "recipient_cancelled")
75446
76045
  return "It cannot be resumed; launch a fresh subagent if its work is still needed.";
75447
76046
  if (code === "recipient_disconnected")
@@ -75453,7 +76052,9 @@ function hintFor3(code, childId) {
75453
76052
  function rehydrateIntercomRecipientGoneError(serialized) {
75454
76053
  const options = serialized.cause === undefined ? undefined : { cause: rehydrateCause3(serialized.cause, 1) };
75455
76054
  const { code, fields } = serialized;
75456
- if (serialized.name === ENDED_NAME && code !== "recipient_disconnected" && code !== "recipient_owner_suspended")
76055
+ if (serialized.name === STAGE_RELEASED_NAME && code === "recipient_stage_released")
76056
+ return new StageRecipientReleasedError(fields, options);
76057
+ if (serialized.name === ENDED_NAME && code !== "recipient_disconnected" && code !== "recipient_owner_suspended" && code !== "recipient_stage_released")
75457
76058
  return new SubagentRecipientEndedError(code, fields, options);
75458
76059
  if (serialized.name === DISCONNECTED_NAME && code === "recipient_disconnected")
75459
76060
  return new SubagentRecipientDisconnectedError(fields, options);
@@ -75501,7 +76102,7 @@ function readSerializedIntercomRecipientGoneError(value2) {
75501
76102
  ...cause === undefined ? {} : { cause }
75502
76103
  };
75503
76104
  }
75504
- 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_DEPTH13 = 4, isWireObject2 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
76105
+ 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_DEPTH13 = 4, isWireObject2 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
75505
76106
  var init_recipient_gone_errors = __esm(() => {
75506
76107
  init_released_child_errors();
75507
76108
  INTERCOM_RECIPIENT_GONE_ERROR_CODES = [
@@ -75510,7 +76111,8 @@ var init_recipient_gone_errors = __esm(() => {
75510
76111
  "recipient_stopped",
75511
76112
  "recipient_cancelled",
75512
76113
  "recipient_disconnected",
75513
- "recipient_owner_suspended"
76114
+ "recipient_owner_suspended",
76115
+ "recipient_stage_released"
75514
76116
  ];
75515
76117
  CODES5 = new Set(INTERCOM_RECIPIENT_GONE_ERROR_CODES);
75516
76118
  WHAT = {
@@ -75519,7 +76121,8 @@ var init_recipient_gone_errors = __esm(() => {
75519
76121
  recipient_stopped: "was stopped (paused or quit) and has no live session",
75520
76122
  recipient_cancelled: "was cancelled for good and has no live session",
75521
76123
  recipient_disconnected: "disconnected and has not reconnected",
75522
- recipient_owner_suspended: "is released and the session that launched it is suspended or disconnected, so nothing can wake it now"
76124
+ recipient_owner_suspended: "is released and the session that launched it is suspended or disconnected, so nothing can wake it now",
76125
+ recipient_stage_released: "was released and the session that answered for it has gone away"
75523
76126
  };
75524
76127
  IntercomRecipientGoneError = class IntercomRecipientGoneError extends Error {
75525
76128
  name = BASE_NAME3;
@@ -75531,7 +76134,8 @@ var init_recipient_gone_errors = __esm(() => {
75531
76134
  childId;
75532
76135
  constructor(code, fields, options) {
75533
76136
  const hint = hintFor3(code, fields.childId);
75534
- super(`Subagent ${JSON.stringify(fields.childName)} ${WHAT[code]} (${code}). ${hint}`, options);
76137
+ const subject = code === "recipient_stage_released" ? "Workflow stage" : "Subagent";
76138
+ super(`${subject} ${JSON.stringify(fields.childName)} ${WHAT[code]} (${code}). ${hint}`, options);
75535
76139
  this.code = code;
75536
76140
  this.hint = hint;
75537
76141
  this.retryable = code === "recipient_disconnected" || code === "recipient_owner_suspended";
@@ -75565,34 +76169,25 @@ var init_recipient_gone_errors = __esm(() => {
75565
76169
  super("recipient_owner_suspended", fields, options);
75566
76170
  }
75567
76171
  };
75568
- NAMES4 = new Set([BASE_NAME3, ENDED_NAME, DISCONNECTED_NAME, OWNER_SUSPENDED_NAME]);
76172
+ StageRecipientReleasedError = class StageRecipientReleasedError extends IntercomRecipientGoneError {
76173
+ name = STAGE_RELEASED_NAME;
76174
+ constructor(fields, options) {
76175
+ super("recipient_stage_released", fields, options);
76176
+ }
76177
+ };
76178
+ NAMES4 = new Set([
76179
+ BASE_NAME3,
76180
+ ENDED_NAME,
76181
+ DISCONNECTED_NAME,
76182
+ OWNER_SUSPENDED_NAME,
76183
+ STAGE_RELEASED_NAME
76184
+ ]);
76185
+ STAGE_RELEASED_NAMES = new Set([STAGE_RELEASED_NAME]);
75569
76186
  ENDED_NAMES = new Set([ENDED_NAME]);
75570
76187
  DISCONNECTED_NAMES = new Set([DISCONNECTED_NAME]);
75571
76188
  OWNER_SUSPENDED_NAMES = new Set([OWNER_SUSPENDED_NAME]);
75572
76189
  });
75573
76190
 
75574
- // dist/builtin/intercom/group.ts
75575
- function normalizeGroup2(value2) {
75576
- if (typeof value2 !== "string")
75577
- return DEFAULT_GROUP;
75578
- const trimmed = value2.trim();
75579
- return trimmed.length > 0 ? trimmed : DEFAULT_GROUP;
75580
- }
75581
- function normalizeGroups(values, legacyGroup) {
75582
- const groups = new Set;
75583
- for (const value2 of values ?? [])
75584
- groups.add(normalizeGroup2(value2));
75585
- if (legacyGroup !== undefined)
75586
- groups.add(normalizeGroup2(legacyGroup));
75587
- if (groups.size === 0)
75588
- groups.add(DEFAULT_GROUP);
75589
- return groups;
75590
- }
75591
- var DEFAULT_GROUP = "default", RESERVED_RUNTIME_GROUPS;
75592
- var init_group = __esm(() => {
75593
- RESERVED_RUNTIME_GROUPS = new Set(["true", "auto"]);
75594
- });
75595
-
75596
76191
  // dist/builtin/intercom/live-route-refusal.ts
75597
76192
  function isLiveWorkflowStageRouteRefusalCode(value2) {
75598
76193
  return typeof value2 === "string" && LIVE_WORKFLOW_STAGE_ROUTE_REFUSAL_CODES.includes(value2);
@@ -75638,6 +76233,202 @@ var init_live_route_refusal = __esm(() => {
75638
76233
  };
75639
76234
  });
75640
76235
 
76236
+ // dist/builtin/intercom/broker/hosted-sessions.ts
76237
+ function parseLiveRoute(value2) {
76238
+ if (!isWireObject3(value2))
76239
+ return false;
76240
+ const { runId, stageKeys, capability } = value2;
76241
+ if (!isNonEmptyString(runId) || !isNonEmptyString(capability) || !Array.isArray(stageKeys))
76242
+ return false;
76243
+ if (stageKeys.length < 1 || stageKeys.length > 2 || !stageKeys.every(isNonEmptyString))
76244
+ return false;
76245
+ return { runId, stageKeys, capability };
76246
+ }
76247
+ function validateHostSessionsFrame(sessions) {
76248
+ if (!Array.isArray(sessions) || sessions.length === 0 || sessions.length > HOSTED_SESSION_FRAME_MAX) {
76249
+ return { ok: false, refusal: { code: "invalid_hosted_frame" } };
76250
+ }
76251
+ const keys = new Set;
76252
+ const parsed = [];
76253
+ for (const item of sessions) {
76254
+ if (!isWireObject3(item) || !isNonEmptyString(item.key) || keys.has(item.key)) {
76255
+ return {
76256
+ ok: false,
76257
+ refusal: isWireObject3(item) && typeof item.key === "string" ? { code: "invalid_hosted_frame", key: item.key } : { code: "invalid_hosted_frame" }
76258
+ };
76259
+ }
76260
+ const key = item.key;
76261
+ keys.add(key);
76262
+ const invalid = { ok: false, refusal: { code: "invalid_hosted_session", key } };
76263
+ const { session, returnAddress } = item;
76264
+ if (!isSessionRegistration(session) || !isNonEmptyString(session.name) || session.recipientPurpose === "control") {
76265
+ return invalid;
76266
+ }
76267
+ if (returnAddress !== undefined && !isNonEmptyString(returnAddress))
76268
+ return invalid;
76269
+ const liveRoute = item.liveRoute === undefined ? undefined : parseLiveRoute(item.liveRoute);
76270
+ if (liveRoute === false)
76271
+ return invalid;
76272
+ parsed.push({
76273
+ key,
76274
+ session,
76275
+ ...returnAddress === undefined ? {} : { returnAddress },
76276
+ ...liveRoute === undefined ? {} : { liveRoute }
76277
+ });
76278
+ }
76279
+ return { ok: true, sessions: parsed };
76280
+ }
76281
+ function readHostedSessionAssignments(value2) {
76282
+ if (!Array.isArray(value2))
76283
+ return;
76284
+ const assignments = [];
76285
+ for (const item of value2) {
76286
+ if (!isWireObject3(item) || typeof item.key !== "string" || !isNonEmptyString(item.sessionId))
76287
+ return;
76288
+ const { liveRouteRefusal } = item;
76289
+ if (liveRouteRefusal !== undefined && !isLiveWorkflowStageRouteRefusalCode(liveRouteRefusal))
76290
+ return;
76291
+ assignments.push({
76292
+ key: item.key,
76293
+ sessionId: item.sessionId,
76294
+ ...liveRouteRefusal === undefined ? {} : { liveRouteRefusal }
76295
+ });
76296
+ }
76297
+ return assignments;
76298
+ }
76299
+ 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;
76300
+ var init_hosted_sessions = __esm(() => {
76301
+ init_live_route_refusal();
76302
+ });
76303
+
76304
+ // dist/builtin/intercom/broker/hosted-session-errors.ts
76305
+ function isHostedSessionErrorCode(value2) {
76306
+ return CODES6.has(value2);
76307
+ }
76308
+ function fieldsOf(refusal) {
76309
+ return {
76310
+ ...refusal.key === undefined ? {} : { key: refusal.key },
76311
+ ...refusal.sessionId === undefined ? {} : { sessionId: refusal.sessionId }
76312
+ };
76313
+ }
76314
+ function hostedSessionErrorFor(refusal, options) {
76315
+ return refusal.code === "not_hosted_by_connection" ? new NotHostedSessionError(fieldsOf(refusal), options) : new HostedSessionRequestError(refusal.code, fieldsOf(refusal), options);
76316
+ }
76317
+ function rehydrateIntercomHostedSessionError(serialized) {
76318
+ const options = serialized.cause === undefined ? undefined : { cause: rehydrateCause3(serialized.cause, 1) };
76319
+ if (serialized.name === NOT_HOSTED_NAME)
76320
+ return new NotHostedSessionError(serialized.fields, options);
76321
+ if (serialized.name === REQUEST_NAME)
76322
+ return new HostedSessionRequestError(serialized.code, serialized.fields, options);
76323
+ const error = new IntercomHostedSessionError(serialized.code, serialized.fields, options);
76324
+ Object.defineProperty(error, "name", { value: serialized.name });
76325
+ return error;
76326
+ }
76327
+ function readHostedSessionRefusal(value2) {
76328
+ if (!isWireObject3(value2))
76329
+ return;
76330
+ const { code, key, sessionId } = value2;
76331
+ if (typeof code !== "string" || !isHostedSessionErrorCode(code))
76332
+ return;
76333
+ if (key !== undefined && typeof key !== "string" || sessionId !== undefined && typeof sessionId !== "string") {
76334
+ return;
76335
+ }
76336
+ return { code, ...key === undefined ? {} : { key }, ...sessionId === undefined ? {} : { sessionId } };
76337
+ }
76338
+ function readSerializedIntercomHostedSessionError(value2) {
76339
+ if (!isWireObject3(value2))
76340
+ return;
76341
+ const { name, code, message, hint, retryable, fields } = value2;
76342
+ if (typeof name !== "string" || typeof code !== "string" || !isHostedSessionErrorCode(code))
76343
+ return;
76344
+ if (typeof message !== "string" || typeof hint !== "string" || retryable !== false)
76345
+ return;
76346
+ const refusal = isWireObject3(fields) ? readHostedSessionRefusal({ ...fields, code }) : undefined;
76347
+ if (refusal === undefined)
76348
+ return;
76349
+ const cause = readCause(value2.cause, 1);
76350
+ if (cause === false)
76351
+ return;
76352
+ return {
76353
+ name,
76354
+ code,
76355
+ message,
76356
+ hint,
76357
+ retryable: false,
76358
+ fields: fieldsOf(refusal),
76359
+ ...cause === undefined ? {} : { cause }
76360
+ };
76361
+ }
76362
+ 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;
76363
+ var init_hosted_session_errors = __esm(() => {
76364
+ init_hosted_sessions();
76365
+ init_released_child_errors();
76366
+ init_released_reply_errors();
76367
+ HOSTED_SESSION_ERROR_CODES = [
76368
+ "invalid_hosted_frame",
76369
+ "invalid_hosted_session",
76370
+ "not_hosted_by_connection"
76371
+ ];
76372
+ CODES6 = new Set(HOSTED_SESSION_ERROR_CODES);
76373
+ HINTS6 = {
76374
+ 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.",
76375
+ invalid_hosted_session: "Give each hosted session a non-empty name and a valid agent registration (cwd, model, pid and timestamps).",
76376
+ 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."
76377
+ };
76378
+ IntercomHostedSessionError = class IntercomHostedSessionError extends Error {
76379
+ name = BASE_NAME4;
76380
+ code;
76381
+ hint;
76382
+ retryable = false;
76383
+ key;
76384
+ sessionId;
76385
+ constructor(code, fields = {}, options) {
76386
+ const subject = fields.key !== undefined ? `hosted session ${JSON.stringify(fields.key)}` : fields.sessionId !== undefined ? `session ${JSON.stringify(fields.sessionId)}` : "request";
76387
+ super(`Hosted-session request refused: ${subject} (${code}). ${HINTS6[code]}`, options);
76388
+ this.code = code;
76389
+ this.hint = HINTS6[code];
76390
+ if (fields.key !== undefined)
76391
+ this.key = fields.key;
76392
+ if (fields.sessionId !== undefined)
76393
+ this.sessionId = fields.sessionId;
76394
+ }
76395
+ };
76396
+ HostedSessionRequestError = class HostedSessionRequestError extends IntercomHostedSessionError {
76397
+ name = REQUEST_NAME;
76398
+ };
76399
+ NotHostedSessionError = class NotHostedSessionError extends IntercomHostedSessionError {
76400
+ name = NOT_HOSTED_NAME;
76401
+ constructor(fields, options) {
76402
+ super("not_hosted_by_connection", fields, options);
76403
+ }
76404
+ };
76405
+ NAMES5 = new Set([BASE_NAME4, REQUEST_NAME, NOT_HOSTED_NAME]);
76406
+ REQUEST_NAMES = new Set([REQUEST_NAME]);
76407
+ NOT_HOSTED_NAMES = new Set([NOT_HOSTED_NAME]);
76408
+ });
76409
+
76410
+ // dist/builtin/intercom/group.ts
76411
+ function normalizeGroup2(value2) {
76412
+ if (typeof value2 !== "string")
76413
+ return DEFAULT_GROUP;
76414
+ const trimmed = value2.trim();
76415
+ return trimmed.length > 0 ? trimmed : DEFAULT_GROUP;
76416
+ }
76417
+ function normalizeGroups(values, legacyGroup) {
76418
+ const groups = new Set;
76419
+ for (const value2 of values ?? [])
76420
+ groups.add(normalizeGroup2(value2));
76421
+ if (legacyGroup !== undefined)
76422
+ groups.add(normalizeGroup2(legacyGroup));
76423
+ if (groups.size === 0)
76424
+ groups.add(DEFAULT_GROUP);
76425
+ return groups;
76426
+ }
76427
+ var DEFAULT_GROUP = "default", RESERVED_RUNTIME_GROUPS;
76428
+ var init_group = __esm(() => {
76429
+ RESERVED_RUNTIME_GROUPS = new Set(["true", "auto"]);
76430
+ });
76431
+
75641
76432
  // dist/builtin/intercom/recoverable-disconnect.ts
75642
76433
  function isIntercomBrokerRetiring(error) {
75643
76434
  let current = error;
@@ -75700,6 +76491,30 @@ var init_pending_stage_route_timeout_error = __esm(() => {
75700
76491
  };
75701
76492
  });
75702
76493
 
76494
+ // dist/builtin/intercom/hosted-session-timeout-error.ts
76495
+ var HOSTED_SESSION_TIMEOUT_HINT = "Hosting is tried again on the next connection; run `atomic intercom restart` if the broker keeps timing out.", IntercomHostedSessionTimeoutError;
76496
+ var init_hosted_session_timeout_error = __esm(() => {
76497
+ init_recoverable_disconnect();
76498
+ IntercomHostedSessionTimeoutError = class IntercomHostedSessionTimeoutError extends IntercomBrokerTimeoutError {
76499
+ name = "IntercomHostedSessionTimeoutError";
76500
+ code = "hosted_session_timeout";
76501
+ phase = "hosted-session-request";
76502
+ retryable = true;
76503
+ hint = HOSTED_SESSION_TIMEOUT_HINT;
76504
+ requestType;
76505
+ sessionCount;
76506
+ timeoutMs;
76507
+ elapsedMs;
76508
+ constructor(fields, options) {
76509
+ 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);
76510
+ this.requestType = fields.requestType;
76511
+ this.sessionCount = fields.sessionCount;
76512
+ this.timeoutMs = fields.timeoutMs;
76513
+ this.elapsedMs = fields.elapsedMs;
76514
+ }
76515
+ };
76516
+ });
76517
+
75703
76518
  // dist/builtin/intercom/broker/socket-liveness.ts
75704
76519
  import net from "net";
75705
76520
  function isSocketAnswering(socketPath, timeoutMs = SOCKET_PROBE_TIMEOUT_MS) {
@@ -75838,9 +76653,12 @@ var init_client = __esm(() => {
75838
76653
  init_released_reply_errors();
75839
76654
  init_released_children();
75840
76655
  init_recipient_gone_errors();
76656
+ init_hosted_session_errors();
76657
+ init_hosted_sessions();
75841
76658
  init_group();
75842
76659
  init_recoverable_disconnect();
75843
76660
  init_pending_stage_route_timeout_error();
76661
+ init_hosted_session_timeout_error();
75844
76662
  init_socket_liveness();
75845
76663
  init_protocol_version();
75846
76664
  init_live_route_refusal();
@@ -75849,6 +76667,7 @@ var init_client = __esm(() => {
75849
76667
  init_released_child_errors();
75850
76668
  init_recipient_gone_errors();
75851
76669
  init_released_reply_errors();
76670
+ init_hosted_session_errors();
75852
76671
  ConnectionClosedBeforeRegistrationError = class ConnectionClosedBeforeRegistrationError extends Error {
75853
76672
  constructor() {
75854
76673
  super("Connection closed before registration");
@@ -75906,6 +76725,7 @@ var init_client = __esm(() => {
75906
76725
  pendingStageRouteRegistrations = new Map;
75907
76726
  pendingSupervisorAuthorizations = new Map;
75908
76727
  pendingRestoringRecipientRequests = new Map;
76728
+ pendingHostedSessionRequests = new Map;
75909
76729
  disconnecting = false;
75910
76730
  disconnectError = null;
75911
76731
  healthCheck;
@@ -75965,6 +76785,8 @@ var init_client = __esm(() => {
75965
76785
  pending.reject(error);
75966
76786
  for (const pending of this.pendingRestoringRecipientRequests.values())
75967
76787
  pending.reject(error);
76788
+ for (const pending of this.pendingHostedSessionRequests.values())
76789
+ pending.reject(error);
75968
76790
  for (const pending of this.pendingPresence.values())
75969
76791
  pending.reject(error);
75970
76792
  for (const pending of this.pendingMemberships.values())
@@ -75981,6 +76803,7 @@ var init_client = __esm(() => {
75981
76803
  this.pendingGroupLists.clear();
75982
76804
  this.pendingSupervisorAuthorizations.clear();
75983
76805
  this.pendingRestoringRecipientRequests.clear();
76806
+ this.pendingHostedSessionRequests.clear();
75984
76807
  this.pendingPresence.clear();
75985
76808
  this.pendingMemberships.clear();
75986
76809
  this.pendingLiveWorkflowStageRoutes.clear();
@@ -76313,11 +77136,14 @@ var init_client = __esm(() => {
76313
77136
  break;
76314
77137
  }
76315
77138
  case "message": {
76316
- const { from, message, channel } = brokerMessage;
76317
- if (!isSessionInfo(from) || !isMessage(message) || channel !== undefined && channel !== "supervisor") {
77139
+ const { from, message, channel, hostedRecipient } = brokerMessage;
77140
+ if (!isSessionInfo(from) || !isMessage(message) || channel !== undefined && channel !== "supervisor" || hostedRecipient !== undefined && typeof hostedRecipient !== "string") {
76318
77141
  throw new Error("Invalid message event");
76319
77142
  }
76320
- this.emit("message", from, message, channel);
77143
+ if (hostedRecipient !== undefined)
77144
+ this.emit("hosted_message", hostedRecipient, from, message, channel);
77145
+ else
77146
+ this.emit("message", from, message, channel);
76321
77147
  break;
76322
77148
  }
76323
77149
  case "pending_stage_message": {
@@ -76462,6 +77288,23 @@ var init_client = __esm(() => {
76462
77288
  this.emit("released_child_reply", notice);
76463
77289
  break;
76464
77290
  }
77291
+ case "hosted_sessions_ack": {
77292
+ const { requestId, refusal, sessions } = brokerMessage;
77293
+ const parsedRefusal = readHostedSessionRefusal(refusal);
77294
+ const assignments = sessions === undefined ? [] : readHostedSessionAssignments(sessions);
77295
+ if (typeof requestId !== "string" || refusal !== undefined && parsedRefusal === undefined || assignments === undefined) {
77296
+ throw new Error("Invalid hosted_sessions_ack message");
77297
+ }
77298
+ const pending = this.pendingHostedSessionRequests.get(requestId);
77299
+ if (!pending)
77300
+ return;
77301
+ this.pendingHostedSessionRequests.delete(requestId);
77302
+ if (parsedRefusal === undefined)
77303
+ pending.resolve(assignments);
77304
+ else
77305
+ pending.reject(hostedSessionErrorFor(parsedRefusal));
77306
+ break;
77307
+ }
76465
77308
  case "released_children_ack": {
76466
77309
  const { requestId, refusal } = brokerMessage;
76467
77310
  const parsed = refusal === undefined ? undefined : readReleasedChildRefusal(refusal);
@@ -76508,7 +77351,9 @@ var init_client = __esm(() => {
76508
77351
  case "delivery_failed": {
76509
77352
  const { messageId, attemptId, reason, reasonCode } = brokerMessage;
76510
77353
  const wireError = brokerMessage.error;
76511
- const error = readSerializedIntercomReleasedReplyError(wireError);
77354
+ const releasedReplyError = readSerializedIntercomReleasedReplyError(wireError);
77355
+ const hostedSessionError = readSerializedIntercomHostedSessionError(wireError);
77356
+ const error = releasedReplyError ?? hostedSessionError;
76512
77357
  const wireRecipientError = brokerMessage.recipientError;
76513
77358
  const recipientError = readSerializedIntercomRecipientGoneError(wireRecipientError);
76514
77359
  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)) {
@@ -76519,7 +77364,8 @@ var init_client = __esm(() => {
76519
77364
  delivered: false,
76520
77365
  reason,
76521
77366
  ...reasonCode === undefined ? {} : { reasonCode },
76522
- ...error === undefined ? {} : { error: rehydrateIntercomReleasedReplyError(error) },
77367
+ ...releasedReplyError === undefined ? {} : { error: rehydrateIntercomReleasedReplyError(releasedReplyError) },
77368
+ ...hostedSessionError === undefined ? {} : { error: rehydrateIntercomHostedSessionError(hostedSessionError) },
76523
77369
  ...recipientError === undefined ? {} : { reasonCode: recipientError.code, error: rehydrateIntercomRecipientGoneError(recipientError) }
76524
77370
  };
76525
77371
  if (attemptId === undefined)
@@ -76929,15 +77775,76 @@ var init_client = __esm(() => {
76929
77775
  });
76930
77776
  return true;
76931
77777
  }
76932
- requireBrokerProtocol(feature) {
77778
+ requireBrokerProtocol(feature, requiredProtocol = VERIFIED_REGISTRATION_PROTOCOL) {
76933
77779
  const broker = this._brokerProtocol;
76934
- if (this._sessionId === null || broker.max >= VERIFIED_REGISTRATION_PROTOCOL)
77780
+ if (this._sessionId === null || broker.max >= requiredProtocol)
76935
77781
  return;
76936
77782
  throw new IntercomBrokerProtocolError({
76937
77783
  feature,
76938
77784
  brokerProtocolMin: broker.min,
76939
77785
  brokerProtocolMax: broker.max,
76940
- requiredProtocol: VERIFIED_REGISTRATION_PROTOCOL
77786
+ requiredProtocol
77787
+ });
77788
+ }
77789
+ async hostSessions(sessions) {
77790
+ this.requireBrokerProtocol("host_sessions", HOSTED_SESSIONS_PROTOCOL);
77791
+ const frames = [];
77792
+ for (let start = 0;start < sessions.length; start += HOSTED_SESSION_FRAME_MAX) {
77793
+ const frame = sessions.slice(start, start + HOSTED_SESSION_FRAME_MAX);
77794
+ const wire = JSON.parse(JSON.stringify(frame));
77795
+ const validation = validateHostSessionsFrame(wire);
77796
+ if (!validation.ok)
77797
+ throw hostedSessionErrorFor(validation.refusal);
77798
+ frames.push(frame);
77799
+ }
77800
+ const assigned = [];
77801
+ for (const frame of frames)
77802
+ assigned.push(...await this.hostedSessionRequest({ type: "host_sessions", sessions: frame }));
77803
+ return assigned;
77804
+ }
77805
+ async unhostSessions(sessionIds) {
77806
+ this.requireBrokerProtocol("unhost_sessions", HOSTED_SESSIONS_PROTOCOL);
77807
+ if (sessionIds.length === 0)
77808
+ throw new HostedSessionRequestError("invalid_hosted_frame");
77809
+ for (let start = 0;start < sessionIds.length; start += HOSTED_SESSION_FRAME_MAX) {
77810
+ await this.hostedSessionRequest({
77811
+ type: "unhost_sessions",
77812
+ sessionIds: sessionIds.slice(start, start + HOSTED_SESSION_FRAME_MAX)
77813
+ });
77814
+ }
77815
+ }
77816
+ hostedSessionRequest(frame) {
77817
+ const socket = this.requireActiveSocket();
77818
+ const requestId = randomUUID15();
77819
+ const startedAt = performance.now();
77820
+ return new Promise((resolve, reject) => {
77821
+ const timeout = setTimeout(() => {
77822
+ this.pendingHostedSessionRequests.delete(requestId);
77823
+ const timedOut = {
77824
+ requestType: frame.type === "unhost_sessions" ? "unhost_sessions" : "host_sessions",
77825
+ sessionCount: Array.isArray(frame.sessions) ? frame.sessions.length : Array.isArray(frame.sessionIds) ? frame.sessionIds.length : 0,
77826
+ timeoutMs: RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS,
77827
+ elapsedMs: Math.round(performance.now() - startedAt)
77828
+ };
77829
+ this.requestTimeout(socket, new IntercomHostedSessionTimeoutError(timedOut)).then((error) => reject(error instanceof IntercomBrokerTimeoutError && !(error instanceof IntercomHostedSessionTimeoutError) ? new IntercomHostedSessionTimeoutError(timedOut, { cause: error }) : error));
77830
+ }, RESTORING_RECIPIENT_REQUEST_TIMEOUT_MS);
77831
+ this.pendingHostedSessionRequests.set(requestId, {
77832
+ resolve: (sessions) => {
77833
+ clearTimeout(timeout);
77834
+ resolve([...sessions]);
77835
+ },
77836
+ reject: (error) => {
77837
+ clearTimeout(timeout);
77838
+ reject(error);
77839
+ }
77840
+ });
77841
+ try {
77842
+ writeMessage(socket, { ...frame, requestId });
77843
+ } catch (error) {
77844
+ clearTimeout(timeout);
77845
+ this.pendingHostedSessionRequests.delete(requestId);
77846
+ reject(toError(error));
77847
+ }
76941
77848
  });
76942
77849
  }
76943
77850
  restoringRecipientRequest(frame) {
@@ -77196,6 +78103,7 @@ var init_client = __esm(() => {
77196
78103
  ...options.expectedRecipientId === undefined ? {} : { expectedRecipientId: options.expectedRecipientId },
77197
78104
  ...options.onReplyTarget === undefined ? {} : { resolveReplyTarget: true },
77198
78105
  ...type === "send" ? { awaitRestoringRecipient: true } : {},
78106
+ hostedSender: options.hostedSender,
77199
78107
  message,
77200
78108
  attemptId: acquired.attempt.attemptId,
77201
78109
  ...extra
@@ -91798,6 +92706,66 @@ var init_stage_runner = __esm(() => {
91798
92706
  init_stage_runner_context();
91799
92707
  });
91800
92708
 
92709
+ // dist/builtin/workflows/src/runs/foreground/stage-session-holds.ts
92710
+ class StageSessionHolds {
92711
+ subscribers = 0;
92712
+ operations = 0;
92713
+ taken = 0;
92714
+ listeners = new Set;
92715
+ get held() {
92716
+ return this.subscribers > 0 || this.operations > 0;
92717
+ }
92718
+ get holdsTaken() {
92719
+ return this.taken;
92720
+ }
92721
+ subscription(unsubscribe) {
92722
+ this.subscribers += 1;
92723
+ this.taken += 1;
92724
+ let active = true;
92725
+ return () => {
92726
+ if (!active)
92727
+ return;
92728
+ active = false;
92729
+ this.subscribers -= 1;
92730
+ unsubscribe();
92731
+ this.lifted();
92732
+ };
92733
+ }
92734
+ async operation(operation) {
92735
+ this.operations += 1;
92736
+ this.taken += 1;
92737
+ try {
92738
+ return await operation();
92739
+ } finally {
92740
+ this.operations -= 1;
92741
+ this.lifted();
92742
+ }
92743
+ }
92744
+ observe(event) {
92745
+ switch (event.type) {
92746
+ case "agent_end":
92747
+ case "agent_settled":
92748
+ case "queue_update":
92749
+ case "compaction_end":
92750
+ case "auto_retry_end":
92751
+ this.lifted();
92752
+ }
92753
+ }
92754
+ onLifted(listener) {
92755
+ this.listeners.add(listener);
92756
+ return () => {
92757
+ this.listeners.delete(listener);
92758
+ };
92759
+ }
92760
+ clear() {
92761
+ this.listeners.clear();
92762
+ }
92763
+ lifted() {
92764
+ for (const listener of [...this.listeners])
92765
+ listener();
92766
+ }
92767
+ }
92768
+
91801
92769
  // dist/builtin/workflows/src/runs/foreground/postmortem-stage-chat.ts
91802
92770
  import { withWorktreeRootMappings as withWorktreeRootMappings2 } from "@bastani/atomic";
91803
92771
  async function reopenableSessionStore(runId, stageId, sessionId, deps) {
@@ -91897,8 +92865,12 @@ function createPostMortemStageHandle(runId, stage, sessionId, adapters, cwd, def
91897
92865
  }
91898
92866
  };
91899
92867
  const queuedUserMessages = new StageQueuedUserMessageBuffer;
91900
- const unsubscribeQueuedUserMessages = context.subscribe((event) => queuedUserMessages.record(event));
91901
- return {
92868
+ const holds = new StageSessionHolds;
92869
+ const unsubscribeQueuedUserMessages = context.subscribe((event) => {
92870
+ queuedUserMessages.record(event);
92871
+ holds.observe(event);
92872
+ });
92873
+ const handle = {
91902
92874
  runId,
91903
92875
  stageId: stage.id,
91904
92876
  stageName: stage.name,
@@ -91956,20 +92928,45 @@ function createPostMortemStageHandle(runId, stage, sessionId, adapters, cwd, def
91956
92928
  throw new Error("Post-mortem stage chat cannot pause or resume workflow execution.");
91957
92929
  },
91958
92930
  subscribe(listener) {
91959
- return context.subscribe(listener);
92931
+ return holds.subscription(context.subscribe(listener));
91960
92932
  },
91961
92933
  subscribeDeliveryActivity(listener) {
91962
- return context.__subscribeDeliveryActivity(listener);
92934
+ return holds.subscription(context.__subscribeDeliveryActivity(listener));
91963
92935
  },
91964
92936
  async dispose() {
91965
92937
  if (disposed)
91966
92938
  return;
91967
92939
  disposed = true;
92940
+ holds.clear();
91968
92941
  unsubscribeQueuedUserMessages();
91969
92942
  queuedUserMessages.clear();
91970
92943
  await context.__dispose();
92944
+ },
92945
+ releaseGate: {
92946
+ releaseWhenIdle: true,
92947
+ async savedForReopen() {
92948
+ if (disposed)
92949
+ return;
92950
+ const store = context.__persistedSessionStore() ?? sessionStore;
92951
+ const savedSessionId = context.__sessionMeta().sessionId ?? sessionId;
92952
+ if (store === undefined)
92953
+ return;
92954
+ return await isReopenableSession(store, savedSessionId) ? store : undefined;
92955
+ },
92956
+ idle() {
92957
+ return !disposed && !holds.held && stageQueuedUserMessageCount(queuedUserMessages.snapshot()) === 0 && (context.__sessionMeta().sessionId === undefined || context.__idleForRelease());
92958
+ },
92959
+ holdsTaken: () => holds.holdsTaken,
92960
+ onHoldLifted: (listener) => holds.onLifted(listener)
91971
92961
  }
91972
92962
  };
92963
+ const { sendUserMessage, prompt, steer, followUp } = handle;
92964
+ handle.ensureAttached = () => holds.operation(ensureAttached);
92965
+ handle.sendUserMessage = (text, options, beforeDelivery) => holds.operation(() => sendUserMessage(text, options, beforeDelivery));
92966
+ handle.prompt = (text) => holds.operation(() => prompt(text));
92967
+ handle.steer = (text) => holds.operation(() => steer(text));
92968
+ handle.followUp = (text) => holds.operation(() => followUp(text));
92969
+ return handle;
91973
92970
  }
91974
92971
  var TERMINAL_POSTMORTEM_STATUSES;
91975
92972
  var init_postmortem_stage_chat = __esm(() => {
@@ -93857,7 +94854,7 @@ function createWorkflowBoundaryFactory(input) {
93857
94854
  stageSnapshot.durationMs = elapsedStageMs(stageSnapshot, stageSnapshot.endedAt);
93858
94855
  }
93859
94856
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
93860
- input.opts.onStageEnd?.(input.runId, stageSnapshot);
94857
+ endStageWithHook(input.activeStore, input.runId, stageSnapshot, input.opts.onStageEnd);
93861
94858
  await appendStageEndForSnapshot();
93862
94859
  input.tracker.onSettle(stageId);
93863
94860
  })();
@@ -93883,7 +94880,7 @@ function createWorkflowBoundaryFactory(input) {
93883
94880
  finalized = true;
93884
94881
  unregisterWorkflowExitCleanup();
93885
94882
  input.activeStore.recordStageEnd(input.runId, stageSnapshot);
93886
- input.opts.onStageEnd?.(input.runId, stageSnapshot);
94883
+ endStageWithHook(input.activeStore, input.runId, stageSnapshot, input.opts.onStageEnd);
93887
94884
  await appendStageEndForSnapshot();
93888
94885
  input.tracker.onSettle(stageId);
93889
94886
  })();
@@ -94803,9 +95800,11 @@ function createStageControlHandle(runtime) {
94803
95800
  };
94804
95801
  const toolExecutions = new StageToolExecutionBuffer;
94805
95802
  const queuedUserMessages = new StageQueuedUserMessageBuffer;
95803
+ const holds = new StageSessionHolds;
94806
95804
  const unsubscribeStageEvents = runtime.innerCtx.subscribe((event) => {
94807
95805
  toolExecutions.record(event);
94808
95806
  queuedUserMessages.record(event);
95807
+ holds.observe(event);
94809
95808
  if (event.type === "task_cleanup_quarantined")
94810
95809
  runtime.activeStore.recordStageNotice(runtime.runId, runtime.stageId, {
94811
95810
  id: crypto.randomUUID(),
@@ -94817,27 +95816,6 @@ function createStageControlHandle(runtime) {
94817
95816
  if (event.type === "background_compaction")
94818
95817
  runtime.activeStore.recordStageCompaction(runtime.runId, runtime.stageId, event.compaction);
94819
95818
  });
94820
- let externalSubscribers = 0;
94821
- const countSubscription = (unsubscribe) => {
94822
- externalSubscribers += 1;
94823
- let active = true;
94824
- return () => {
94825
- if (!active)
94826
- return;
94827
- active = false;
94828
- externalSubscribers -= 1;
94829
- unsubscribe();
94830
- };
94831
- };
94832
- let activeOperations = 0;
94833
- const tracked = async (operation) => {
94834
- activeOperations += 1;
94835
- try {
94836
- return await operation();
94837
- } finally {
94838
- activeOperations -= 1;
94839
- }
94840
- };
94841
95819
  const sessionSaved = () => runtime.stageSnapshot.status === "completed" && runtime.state.stageFinalized && runtime.state.sessionCheckpointed && !runtime.state.liveHandleReleased && !runtime.state.stageClosedByWorkflowExit;
94842
95820
  const handle = {
94843
95821
  runId: runtime.runId,
@@ -95033,12 +96011,13 @@ function createStageControlHandle(runtime) {
95033
96011
  }
95034
96012
  },
95035
96013
  subscribe(listener) {
95036
- return countSubscription(runtime.innerCtx.subscribe(listener));
96014
+ return holds.subscription(runtime.innerCtx.subscribe(listener));
95037
96015
  },
95038
96016
  subscribeDeliveryActivity(listener) {
95039
- return countSubscription(runtime.innerCtx.__subscribeDeliveryActivity(listener));
96017
+ return holds.subscription(runtime.innerCtx.__subscribeDeliveryActivity(listener));
95040
96018
  },
95041
96019
  async dispose() {
96020
+ holds.clear();
95042
96021
  unsubscribeStageEvents();
95043
96022
  toolExecutions.clear();
95044
96023
  queuedUserMessages.clear();
@@ -95055,18 +96034,20 @@ function createStageControlHandle(runtime) {
95055
96034
  return await isReopenableSession(store, sessionId) ? store : undefined;
95056
96035
  },
95057
96036
  idle() {
95058
- 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();
95059
- }
96037
+ 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();
96038
+ },
96039
+ holdsTaken: () => holds.holdsTaken,
96040
+ onHoldLifted: (listener) => holds.onLifted(listener)
95060
96041
  }
95061
96042
  };
95062
96043
  const { ensureAttached, sendUserMessage, prompt, steer, followUp, pause, resume } = handle;
95063
- handle.ensureAttached = () => tracked(ensureAttached);
95064
- handle.sendUserMessage = (text, options, beforeDelivery) => tracked(() => sendUserMessage(text, options, beforeDelivery));
95065
- handle.prompt = (text) => tracked(() => prompt(text));
95066
- handle.steer = (text, options) => tracked(() => steer(text, options));
95067
- handle.followUp = (text, options) => tracked(() => followUp(text, options));
95068
- handle.pause = () => tracked(pause);
95069
- handle.resume = (message, beforeResume) => tracked(() => resume(message, beforeResume));
96044
+ handle.ensureAttached = () => holds.operation(ensureAttached);
96045
+ handle.sendUserMessage = (text, options, beforeDelivery) => holds.operation(() => sendUserMessage(text, options, beforeDelivery));
96046
+ handle.prompt = (text) => holds.operation(() => prompt(text));
96047
+ handle.steer = (text, options) => holds.operation(() => steer(text, options));
96048
+ handle.followUp = (text, options) => holds.operation(() => followUp(text, options));
96049
+ handle.pause = () => holds.operation(pause);
96050
+ handle.resume = (message, beforeResume) => holds.operation(() => resume(message, beforeResume));
95070
96051
  return handle;
95071
96052
  }
95072
96053
  var init_executor_stage_control = __esm(() => {
@@ -95121,7 +96102,7 @@ function createReplayStageContext(input) {
95121
96102
  stageSnapshot.skippedReason = input.workflowExitSkippedReason(reason);
95122
96103
  }
95123
96104
  input.activeStore.recordStageEnd(runId, stageSnapshot);
95124
- input.opts.onStageEnd?.(runId, stageSnapshot);
96105
+ endStageWithHook(input.activeStore, runId, stageSnapshot, input.opts.onStageEnd);
95125
96106
  await appendReplayStageEnd();
95126
96107
  input.tracker.onSettle(stageId);
95127
96108
  })();
@@ -95386,26 +96367,8 @@ function createWorkflowStageFactory(input) {
95386
96367
  if (keptResults !== undefined)
95387
96368
  stageSnapshot.waitResults = recordStageWaitToolResults(keptResults);
95388
96369
  const applyModelFallbackMeta = (meta) => {
95389
- if (meta.model !== undefined)
95390
- stageSnapshot.model = meta.model;
95391
- if (meta.thinkingLevel !== undefined)
95392
- stageSnapshot.thinkingLevel = meta.thinkingLevel;
95393
- else
95394
- delete stageSnapshot.thinkingLevel;
95395
- if (meta.attemptedModels !== undefined)
95396
- stageSnapshot.attemptedModels = meta.attemptedModels;
95397
- if (meta.modelAttempts !== undefined)
95398
- stageSnapshot.modelAttempts = meta.modelAttempts;
95399
- if (meta.rateLimits !== undefined)
95400
- stageSnapshot.rateLimits = meta.rateLimits;
95401
- if (meta.routerSelection !== undefined)
95402
- stageSnapshot.routerSelection = meta.routerSelection;
95403
- if (meta.warnings !== undefined) {
95404
- if (meta.warnings.length > 0)
95405
- stageSnapshot.warnings = meta.warnings;
95406
- else
95407
- delete stageSnapshot.warnings;
95408
- }
96370
+ if (applyModelFallbackMetaToStage(stageSnapshot, meta))
96371
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
95409
96372
  };
95410
96373
  let runtime;
95411
96374
  const emitLifecycleEvent = (event) => {
@@ -95507,10 +96470,12 @@ function createWorkflowStageFactory(input) {
95507
96470
  },
95508
96471
  async recordResults(_wait, results) {
95509
96472
  stageSnapshot.waitResults = recordStageWaitToolResults(results);
96473
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
95510
96474
  await recordWait("wait-results");
95511
96475
  },
95512
96476
  resultsInTranscript() {
95513
96477
  delete stageSnapshot.waitResults;
96478
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
95514
96479
  },
95515
96480
  async leave() {
95516
96481
  waitRecordMissing = false;
@@ -95695,13 +96660,13 @@ function createWorkflowStageFactory(input) {
95695
96660
  };
95696
96661
  const captureStageSessionMeta = async (checkpointOptions) => {
95697
96662
  const meta = innerCtx.__sessionMeta();
95698
- if (meta.sessionId !== undefined)
95699
- stageSnapshot.sessionId = meta.sessionId;
95700
- if (meta.sessionFile !== undefined)
95701
- stageSnapshot.sessionFile = meta.sessionFile;
96663
+ const changed = applySessionMetaToStage(stageSnapshot, meta);
95702
96664
  if (meta.sessionId !== undefined)
95703
96665
  input.activeStore.recordStageSession(input.runId, stageId, { sessionId: meta.sessionId });
96666
+ if (changed)
96667
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
95704
96668
  const pending = input.opts.onStageSession?.(input.runId, stageSnapshot, checkpointOptions);
96669
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
95705
96670
  if (checkpointOptions?.forceDurable === true || checkpointOptions?.awaitDurable === true) {
95706
96671
  await pending;
95707
96672
  return;
@@ -95776,6 +96741,7 @@ function createWorkflowStageFactory(input) {
95776
96741
  input.stageUiBroker.clearStageStatuses(input.runId, stageId);
95777
96742
  if (input.opts.onStageEnd) {
95778
96743
  await runCallback3({ kind: "workflow.stage_adapter", name: `onStageEnd:${name}`, runId: input.runId, stageId }, () => input.opts.onStageEnd(input.runId, stageSnapshot));
96744
+ announceSettledStageEdit(input.activeStore, input.runId, stageSnapshot);
95779
96745
  }
95780
96746
  if (input.opts.persistence) {
95781
96747
  await appendStageStartOnce();
@@ -103567,6 +104533,7 @@ init_returned_run_status();
103567
104533
 
103568
104534
  // dist/builtin/workflows/src/shared/run-indicator-status.ts
103569
104535
  init_returned_run_status();
104536
+ init_run_stage_index();
103570
104537
  var TERMINAL_OR_BLOCKED = new Set(["completed", "failed", "killed", "cancelled", "skipped", "blocked"]);
103571
104538
  function runIndicatorStatus(run, allRuns = [run]) {
103572
104539
  const status = effectiveRunStatus(run);
@@ -103604,9 +104571,7 @@ function resolveRunIndicatorStatuses(runs, allRuns) {
103604
104571
  return statuses;
103605
104572
  }
103606
104573
  function runHasPendingInput(run) {
103607
- if (run.pendingPrompt !== undefined)
103608
- return true;
103609
- return run.stages.some((stage) => stage.status === "awaiting_input" || stage.awaitingInputSince !== undefined || stage.pendingPrompt !== undefined || stage.inputRequest !== undefined);
104574
+ return run.pendingPrompt !== undefined || runStageIndex(run).awaitingInput;
103610
104575
  }
103611
104576
  function ancestorsOfPendingInputRuns(allRuns) {
103612
104577
  const runsById = new Map(allRuns.map((candidate) => [candidate.id, candidate]));
@@ -106938,6 +107903,8 @@ class GraphViewState {
106938
107903
  piKeybindings;
106939
107904
  footerData;
106940
107905
  getStageQueuedMessageCount;
107906
+ getQueuedStageSignature;
107907
+ queuedSignature;
106941
107908
  focusedIndex = 0;
106942
107909
  switcherOpen = false;
106943
107910
  switcherState = { query: "", selectedIndex: 0 };
@@ -106986,6 +107953,7 @@ class GraphViewState {
106986
107953
  this.piKeybindings = opts.piKeybindings;
106987
107954
  this.footerData = opts.footerData;
106988
107955
  this.getStageQueuedMessageCount = opts.getStageQueuedMessageCount;
107956
+ this.getQueuedStageSignature = opts.getQueuedStageSignature;
106989
107957
  this._unsubscribe = subscribeStoreInvalidation(this.store, () => {
106990
107958
  this.storeChanged = true;
106991
107959
  });
@@ -107021,9 +107989,8 @@ class GraphViewState {
107021
107989
  return nodeCardHeight(stage, { queuedMessageCount: this._stageQueuedMessageCount(stage) });
107022
107990
  }
107023
107991
  _refreshQueuedNodeHeights() {
107024
- if (!this.getStageQueuedMessageCount)
107025
- return;
107026
- if (!this.cachedLayout.some((node) => (node.height ?? NODE_H) !== this._nodeHeight(node.stage)))
107992
+ const signature = this.getQueuedStageSignature?.();
107993
+ if (signature === undefined || signature === this.queuedSignature)
107027
107994
  return;
107028
107995
  this.lastBuiltSnapshotVersion = null;
107029
107996
  this._rebuildLayout();
@@ -107034,6 +108001,7 @@ class GraphViewState {
107034
108001
  this._refreshQueuedNodeHeights();
107035
108002
  return;
107036
108003
  }
108004
+ this.queuedSignature = this.getQueuedStageSignature?.();
107037
108005
  const run = this._getCurrentRun();
107038
108006
  if (!run) {
107039
108007
  this.cachedLayout = [];
@@ -107644,7 +108612,6 @@ class GraphViewGraphRenderer extends GraphViewRenderHelpers {
107644
108612
  // dist/builtin/workflows/src/tui/graph-view-layout.ts
107645
108613
  import { ScrollView, VStack } from "@earendil-works/pi-tui";
107646
108614
  import {
107647
- getScrollbarGeometry,
107648
108615
  getScrollViewBox,
107649
108616
  renderLayoutFrame
107650
108617
  } from "@earendil-works/pi-tui/dist/layout.js";
@@ -107738,8 +108705,9 @@ class GraphViewLayout {
107738
108705
  const margin = new CallbackComponent(() => [""]);
107739
108706
  const header = new CallbackComponent((width) => this.callbacks.renderHeader(width));
107740
108707
  const body = new CallbackComponent((width) => {
107741
- this.lastBodyWidth = width;
107742
- return this.renderBody(width);
108708
+ const contentWidth = this.scrollbarShown ? Math.max(1, width - 1) : width;
108709
+ this.lastBodyWidth = contentWidth;
108710
+ return this.renderBody(contentWidth);
107743
108711
  });
107744
108712
  const footer = new CallbackComponent((width) => this.callbacks.renderFooter(width));
107745
108713
  this.scrollView = new ScrollView(body, {
@@ -107770,7 +108738,7 @@ class GraphViewLayout {
107770
108738
  frame = this.renderPass(safeWidth, safeHeight, measuredWidth, requestedTop);
107771
108739
  }
107772
108740
  const bodyBox = getScrollViewBox(frame, this.scrollView);
107773
- this.scrollbar = bodyBox ? getScrollbarGeometry(bodyBox) : undefined;
108741
+ this.scrollbar = bodyBox === undefined ? undefined : this.bodyScrollbarGeometry(bodyBox);
107774
108742
  if (!this.scrollbar)
107775
108743
  this.draggingScrollbar = undefined;
107776
108744
  const wrappedRows = Array.from({ length: safeHeight }, () => false);
@@ -107793,7 +108761,6 @@ class GraphViewLayout {
107793
108761
  this.scrollView.updateLayout(this.bodyContentRows, this.bodyViewportRows, requestRender);
107794
108762
  if (restoreTop !== undefined && this.scrollView.scrollTop < restoreTop)
107795
108763
  this.scrollView.scrollTo(restoreTop);
107796
- this.scrollView.setScrollbar(this.bodyContentRows > this.bodyViewportRows ? "always" : "hidden");
107797
108764
  this.callbacks.beforeFrame?.(this.scrollView, this.bodyViewportRows, this.bodyContentRows, safeWidth);
107798
108765
  return renderLayoutFrame(this.root, safeWidth, safeHeight, requestRender);
107799
108766
  }
@@ -107872,14 +108839,45 @@ class GraphViewLayout {
107872
108839
  invalidate() {
107873
108840
  this.root.invalidate();
107874
108841
  }
108842
+ get scrollbarShown() {
108843
+ return this.bodyContentRows > this.bodyViewportRows;
108844
+ }
108845
+ thumb(trackHeight) {
108846
+ const height = Math.max(Math.min(2, trackHeight), Math.min(trackHeight, Math.round(trackHeight * trackHeight / this.bodyContentRows)));
108847
+ const maxScrollTop = Math.max(0, this.bodyContentRows - trackHeight);
108848
+ const offset = Math.round(this.scrollView.scrollTop / Math.max(1, maxScrollTop) * (trackHeight - height));
108849
+ return { offset, height, maxScrollTop };
108850
+ }
108851
+ bodyScrollbarGeometry(bodyBox) {
108852
+ if (!this.scrollbarShown || bodyBox.rect.height <= 0)
108853
+ return;
108854
+ const thumb = this.thumb(bodyBox.rect.height);
108855
+ return {
108856
+ column: bodyBox.rect.x + bodyBox.rect.width - 1,
108857
+ trackTop: bodyBox.rect.y,
108858
+ trackHeight: bodyBox.rect.height,
108859
+ thumbTop: bodyBox.rect.y + thumb.offset,
108860
+ thumbHeight: thumb.height,
108861
+ maxScrollTop: thumb.maxScrollTop
108862
+ };
108863
+ }
107875
108864
  renderBody(width) {
107876
108865
  const contentRows = this.bodyContentRows;
107877
108866
  const lines = new Array(contentRows);
107878
108867
  const top = Math.max(0, Math.min(contentRows, this.scrollView.scrollTop));
107879
108868
  const rows = Math.max(0, Math.min(this.bodyViewportRows, contentRows - top));
107880
108869
  const visible = this.callbacks.renderBody(width, top, rows, contentRows);
108870
+ const thumb = this.scrollbarShown ? this.thumb(this.bodyViewportRows) : undefined;
108871
+ const thumbCell = this.scrollView.scrollbarThumbStyle(this.scrollView.isScrollbarActive ? "█" : "┃");
108872
+ const trackCell = this.scrollView.scrollbarTrackStyle("│");
107881
108873
  for (let index = 0;index < visible.length && index < rows; index++) {
107882
- lines[top + index] = visible[index];
108874
+ const line = visible[index];
108875
+ if (thumb === undefined) {
108876
+ lines[top + index] = line;
108877
+ continue;
108878
+ }
108879
+ const cell = index >= thumb.offset && index < thumb.offset + thumb.height ? thumbCell : trackCell;
108880
+ lines[top + index] = `${line}${" ".repeat(Math.max(0, width - visibleWidth(line)))}${cell}`;
107883
108881
  }
107884
108882
  if (top > 0)
107885
108883
  lines[top - 1] = " ";
@@ -112253,6 +113251,7 @@ class WorkflowAttachPane {
112253
113251
  piKeybindings: this.piKeybindings,
112254
113252
  footerData: this.footerData,
112255
113253
  getStageQueuedMessageCount: (runId, stageId) => this._stageQueuedMessageCount(runId, stageId),
113254
+ getQueuedStageSignature: () => this._queuedStageSignature(),
112256
113255
  requestRender: () => {
112257
113256
  if (this.mode !== "graph")
112258
113257
  return;
@@ -112267,6 +113266,20 @@ class WorkflowAttachPane {
112267
113266
  return this._stageSnapshot(runId, stageId)?.queuedUserMessageCount ?? 0;
112268
113267
  return count;
112269
113268
  }
113269
+ _queuedStageSignature() {
113270
+ const registry = this.registry;
113271
+ if (registry === undefined)
113272
+ return "";
113273
+ const queued = [];
113274
+ for (const run of readGraphStoreSnapshot(this.store).runs) {
113275
+ for (const handle of registry.forRun(run.id)) {
113276
+ const count = stageQueuedUserMessageCount(handle.queuedUserMessages?.());
113277
+ if (count > 0)
113278
+ queued.push([run.id, handle.stageId, count]);
113279
+ }
113280
+ }
113281
+ return JSON.stringify(queued);
113282
+ }
112270
113283
  _resolveRunId() {
112271
113284
  if (this.runId)
112272
113285
  return this.runId;
@@ -112987,7 +114000,7 @@ init_pending_stage_status();
112987
114000
  init_returned_run_status();
112988
114001
  // dist/builtin/workflows/src/tui/pending-input-affordance.ts
112989
114002
  init_returned_run_status();
112990
- init_store_internal();
114003
+ init_run_stage_index();
112991
114004
  init_workflow_run_ownership();
112992
114005
  var TERMINAL_OR_BLOCKED2 = new Set(["completed", "failed", "killed", "cancelled", "skipped", "blocked"]);
112993
114006
  var MAX_PROMPT_DISPLAY_CHARS = 256;
@@ -113186,9 +114199,7 @@ function descriptorsAreCompatible(prompt, request) {
113186
114199
  }
113187
114200
  function stagePromptOccurrences(run) {
113188
114201
  const occurrences = [];
113189
- for (const stage of run.stages) {
113190
- if (isTerminalStageStatus(stage.status))
113191
- continue;
114202
+ for (const stage of runStageIndex(run).waiting) {
113192
114203
  const prompt = stage.pendingPrompt;
113193
114204
  const request = stage.inputRequest;
113194
114205
  if (prompt !== undefined && request !== undefined) {
@@ -113361,8 +114372,7 @@ function progressLabel(stages) {
113361
114372
  const total = stages.length;
113362
114373
  if (total === 0)
113363
114374
  return;
113364
- const done = stages.filter((s) => s.status === "completed" || s.status === "failed" || s.status === "skipped").length;
113365
- return `${done}/${total}`;
114375
+ return `${settledStageCount(stages)}/${total}`;
113366
114376
  }
113367
114377
  function elapsedLabel(run, now) {
113368
114378
  if (run.endedAt !== undefined) {
@@ -113784,13 +114794,6 @@ function reportWidgetFailure(ui, message) {
113784
114794
  console.error(message);
113785
114795
  return;
113786
114796
  }
113787
- function liveWidgetSnapshot(storeInstance) {
113788
- return {
113789
- runs: storeInstance.runs(),
113790
- notices: storeInstance.notices(),
113791
- version: 0
113792
- };
113793
- }
113794
114797
  function installStoreWidget(pi, storeInstance, timers = defaultTimerApi, clock = () => performance.now()) {
113795
114798
  const ui = pi.ui;
113796
114799
  if (!ui?.setWidget) {
@@ -113821,7 +114824,7 @@ function installStoreWidget(pi, storeInstance, timers = defaultTimerApi, clock =
113821
114824
  placement: "belowEditor",
113822
114825
  scroll: { maxHeight: 10, maxHeightFraction: 1 / 3 },
113823
114826
  timers,
113824
- getSnapshot: () => liveWidgetSnapshot(storeInstance),
114827
+ getSnapshot: () => readGraphStoreSnapshot(storeInstance),
113825
114828
  subscribe: (listener) => {
113826
114829
  const throttled = budgetedStoreListener(listener, timers, clock);
113827
114830
  const unsubscribe = subscribeStoreInvalidation(storeInstance, throttled.listener);
@@ -113831,7 +114834,7 @@ function installStoreWidget(pi, storeInstance, timers = defaultTimerApi, clock =
113831
114834
  };
113832
114835
  },
113833
114836
  getPreviewLines: (snap, now) => buildThemedWidgetLines(snap, undefined, 120, now),
113834
- render: (snap, { theme, width, now }) => buildThemedWidgetLines(snap, theme, width, now, layout),
114837
+ render: (_snap, { theme, width, now }) => buildThemedWidgetLines(readGraphStoreSnapshot(storeInstance), theme, width, now, layout),
113835
114838
  getNextRefreshDelayMs: (snap, now) => nextWidgetRefreshDelayMs(snap, now),
113836
114839
  requestRenderOnStateNoop: false,
113837
114840
  isStaleError: isStaleExtensionContextError5,
@@ -114067,16 +115070,27 @@ function enqueueTargetTurn(queues, key, deliver) {
114067
115070
  return current;
114068
115071
  }
114069
115072
  async function deliverAsPostMortemTurn(event, resolveHandle, assertActive) {
114070
- const handle = await reopenCompletedStage(event.workflowRunId, event.workflowStageId, resolveHandle, assertActive);
114071
- for (const message of event.messages) {
114072
- assertActive();
114073
- if (handle.isStreaming)
114074
- await handle.followUp(message.content);
114075
- else
114076
- await handle.prompt(message.content);
115073
+ await withReopenedStage(event.workflowRunId, event.workflowStageId, resolveHandle, assertActive, async (handle) => {
115074
+ for (const message of event.messages) {
115075
+ assertActive();
115076
+ if (handle.isStreaming)
115077
+ await handle.followUp(message.content);
115078
+ else
115079
+ await handle.prompt(message.content);
115080
+ }
115081
+ });
115082
+ }
115083
+ async function withReopenedStage(runId, stageId, resolveHandle, assertActive, use) {
115084
+ const handle = await resolveCompletedStage(runId, stageId, resolveHandle, assertActive);
115085
+ const letGo = handle.subscribe(() => {});
115086
+ try {
115087
+ await attachWithTimeout(handle);
115088
+ return await use(handle);
115089
+ } finally {
115090
+ letGo();
114077
115091
  }
114078
115092
  }
114079
- async function reopenCompletedStage(runId, stageId, resolveHandle, assertActive) {
115093
+ async function resolveCompletedStage(runId, stageId, resolveHandle, assertActive) {
114080
115094
  assertActive();
114081
115095
  const resolution = await resolveHandle(runId, stageId);
114082
115096
  assertActive();
@@ -114090,7 +115104,6 @@ async function reopenCompletedStage(runId, stageId, resolveHandle, assertActive)
114090
115104
  if (handle.status !== "completed" || handle.isDisposed === true) {
114091
115105
  throw new Error(`Intercom ask target is not resumable: workflow stage ${runId}/${stageId} has no retained completed conversation.`);
114092
115106
  }
114093
- await attachWithTimeout(handle);
114094
115107
  return handle;
114095
115108
  }
114096
115109
  function assistantMessageText(message) {
@@ -114118,15 +115131,14 @@ async function collectTurnReply(handle, content) {
114118
115131
  }
114119
115132
  function createCompletedStageAnswerer(resolveHandle, assertActive = () => {}) {
114120
115133
  const queues = new Map;
114121
- return (runId, stageId, content) => enqueueTargetTurn(queues, `${runId}:${stageId}`, async () => {
114122
- const handle = await reopenCompletedStage(runId, stageId, resolveHandle, assertActive);
115134
+ return (runId, stageId, content) => enqueueTargetTurn(queues, `${runId}:${stageId}`, () => withReopenedStage(runId, stageId, resolveHandle, assertActive, async (handle) => {
114123
115135
  if (handle.isStreaming) {
114124
115136
  throw new Error(`Completed workflow stage ${runId}/${stageId} is busy with another turn; ask again when it is idle.`);
114125
115137
  }
114126
115138
  const reply = await collectTurnReply(handle, content);
114127
115139
  assertActive();
114128
115140
  return reply ?? `Completed workflow stage ${runId}/${stageId} reopened but produced no text answer.`;
114129
- });
115141
+ }));
114130
115142
  }
114131
115143
  async function attachWithTimeout(handle) {
114132
115144
  let timeout;
@@ -117267,7 +118279,7 @@ function registerCompletedChatHandles(snapshot, deps, sessionStore) {
117267
118279
  continue;
117268
118280
  const key = completedChatKey(snapshot.id, stage.id);
117269
118281
  const registration = registrations.get(key)?.deref();
117270
- const existing = registry.claim(snapshot.id, stage.id);
118282
+ const existing = registry.peek(snapshot.id, stage.id);
117271
118283
  if (existing?.sessionId === stage.sessionId && existing.sessionStore === sessionStore && !existing.isDisposed)
117272
118284
  continue;
117273
118285
  if (registration !== undefined) {
@@ -122931,7 +123943,8 @@ function flushWorkflowActivityPublications() {
122931
123943
  function createWorkflowObservation(store, publisher, ownerSessionId) {
122932
123944
  const runtime = workflowObservationRuntime(store);
122933
123945
  let roots = new Map;
122934
- const project = () => projectWorkflowActivity({ snapshot: store.graphSnapshot(), ownership: { ...runtime, ownerSessionId } });
123946
+ const projector = new WorkflowActivityProjector;
123947
+ const project = () => projector.project({ snapshot: store.graphSnapshot(), ownership: { ...runtime, ownerSessionId } });
122935
123948
  const snapshot = () => {
122936
123949
  if (runtime.recovering)
122937
123950
  publisher.publishSnapshot({ availability: "recovering" });