@bastani/atomic 0.9.84 → 0.9.85-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 (183) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  3. package/dist/builtin/intercom/broker/broker.ts +25 -7
  4. package/dist/builtin/intercom/broker/spawn.ts +83 -17
  5. package/dist/builtin/intercom/index.bundle.mjs +89 -26
  6. package/dist/builtin/intercom/package.json +1 -1
  7. package/dist/builtin/mcp/package.json +1 -1
  8. package/dist/builtin/subagents/package.json +1 -1
  9. package/dist/builtin/web-access/package.json +1 -1
  10. package/dist/builtin/workflows/CHANGELOG.md +6 -0
  11. package/dist/builtin/workflows/package.json +1 -1
  12. package/dist/builtin/workflows/src/authoring.d.ts +1 -1
  13. package/dist/builtin/workflows/src/extension/index.bundle.mjs +48 -9
  14. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +48 -9
  15. package/dist/builtin/workflows/src/index.js +48 -9
  16. package/dist/builtin/workflows/src/local-worker-entry.mjs +48 -9
  17. package/dist/config.d.ts +3 -2
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +4 -3
  20. package/dist/config.js.map +1 -1
  21. package/dist/core/agent-session-export.d.ts +2 -2
  22. package/dist/core/agent-session-export.d.ts.map +1 -1
  23. package/dist/core/agent-session-export.js +4 -5
  24. package/dist/core/agent-session-export.js.map +1 -1
  25. package/dist/core/agent-session-services.js +1 -1
  26. package/dist/core/agent-session-services.js.map +1 -1
  27. package/dist/core/agent-session-summary.d.ts.map +1 -1
  28. package/dist/core/agent-session-summary.js +8 -1
  29. package/dist/core/agent-session-summary.js.map +1 -1
  30. package/dist/core/agent-session-tree.d.ts.map +1 -1
  31. package/dist/core/agent-session-tree.js +3 -6
  32. package/dist/core/agent-session-tree.js.map +1 -1
  33. package/dist/core/builtin-resource-loader.d.ts.map +1 -1
  34. package/dist/core/builtin-resource-loader.js +1 -1
  35. package/dist/core/builtin-resource-loader.js.map +1 -1
  36. package/dist/core/extensions/loader-core.d.ts +6 -2
  37. package/dist/core/extensions/loader-core.d.ts.map +1 -1
  38. package/dist/core/extensions/loader-core.js +13 -9
  39. package/dist/core/extensions/loader-core.js.map +1 -1
  40. package/dist/core/extensions/loader-discovery.js +1 -1
  41. package/dist/core/extensions/loader-discovery.js.map +1 -1
  42. package/dist/core/extensions/loader-virtual-modules.d.ts +20 -14
  43. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  44. package/dist/core/extensions/loader-virtual-modules.js +133 -78
  45. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  46. package/dist/core/extensions/ts-source-specifiers.d.ts +1 -0
  47. package/dist/core/extensions/ts-source-specifiers.d.ts.map +1 -1
  48. package/dist/core/extensions/ts-source-specifiers.js +18 -2
  49. package/dist/core/extensions/ts-source-specifiers.js.map +1 -1
  50. package/dist/core/mandatory-resource-loader.d.ts +5 -2
  51. package/dist/core/mandatory-resource-loader.d.ts.map +1 -1
  52. package/dist/core/mandatory-resource-loader.js +17 -12
  53. package/dist/core/mandatory-resource-loader.js.map +1 -1
  54. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  55. package/dist/core/model-fallback-failures.js +10 -3
  56. package/dist/core/model-fallback-failures.js.map +1 -1
  57. package/dist/core/resource-loader-extensions.d.ts.map +1 -1
  58. package/dist/core/resource-loader-extensions.js +1 -1
  59. package/dist/core/resource-loader-extensions.js.map +1 -1
  60. package/dist/core/resource-loader-reload.js +1 -1
  61. package/dist/core/resource-loader-reload.js.map +1 -1
  62. package/dist/core/resume/blueprint/resume.d.ts +4 -4
  63. package/dist/core/resume/blueprint/resume.js +4 -4
  64. package/dist/core/resume/blueprint/resume.js.map +1 -1
  65. package/dist/core/resume/session-resume.d.ts +6 -3
  66. package/dist/core/resume/session-resume.d.ts.map +1 -1
  67. package/dist/core/resume/session-resume.js +159 -37
  68. package/dist/core/resume/session-resume.js.map +1 -1
  69. package/dist/core/sdk.js +1 -1
  70. package/dist/core/sdk.js.map +1 -1
  71. package/dist/core/session-manager-core.d.ts +10 -4
  72. package/dist/core/session-manager-core.d.ts.map +1 -1
  73. package/dist/core/session-manager-core.js +23 -6
  74. package/dist/core/session-manager-core.js.map +1 -1
  75. package/dist/core/session-manager-entries.d.ts +2 -2
  76. package/dist/core/session-manager-entries.d.ts.map +1 -1
  77. package/dist/core/session-manager-entries.js +2 -1
  78. package/dist/core/session-manager-entries.js.map +1 -1
  79. package/dist/core/session-manager-history.d.ts +13 -1
  80. package/dist/core/session-manager-history.d.ts.map +1 -1
  81. package/dist/core/session-manager-history.js +21 -1
  82. package/dist/core/session-manager-history.js.map +1 -1
  83. package/dist/core/session-manager-types.d.ts +3 -1
  84. package/dist/core/session-manager-types.d.ts.map +1 -1
  85. package/dist/core/session-manager-types.js.map +1 -1
  86. package/dist/core/session-manager.d.ts +1 -1
  87. package/dist/core/session-manager.d.ts.map +1 -1
  88. package/dist/core/session-manager.js +1 -1
  89. package/dist/core/session-manager.js.map +1 -1
  90. package/dist/core/session-worktree-snapshots.d.ts +61 -4
  91. package/dist/core/session-worktree-snapshots.d.ts.map +1 -1
  92. package/dist/core/session-worktree-snapshots.js +261 -28
  93. package/dist/core/session-worktree-snapshots.js.map +1 -1
  94. package/dist/core/storage/session/entry-structure.js +31 -1
  95. package/dist/core/storage/session/entry-structure.js.map +1 -1
  96. package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts.map +1 -1
  97. package/dist/core/tools/ask-user-question/state/build-questionnaire.js +2 -1
  98. package/dist/core/tools/ask-user-question/state/build-questionnaire.js.map +1 -1
  99. package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts.map +1 -1
  100. package/dist/core/tools/ask-user-question/state/questionnaire-session.js +2 -0
  101. package/dist/core/tools/ask-user-question/state/questionnaire-session.js.map +1 -1
  102. package/dist/core/tools/ask-user-question/state/selectors/field-tone.d.ts +26 -0
  103. package/dist/core/tools/ask-user-question/state/selectors/field-tone.d.ts.map +1 -0
  104. package/dist/core/tools/ask-user-question/state/selectors/field-tone.js +27 -0
  105. package/dist/core/tools/ask-user-question/state/selectors/field-tone.js.map +1 -0
  106. package/dist/core/tools/ask-user-question/state/selectors/projections.d.ts.map +1 -1
  107. package/dist/core/tools/ask-user-question/state/selectors/projections.js +1 -0
  108. package/dist/core/tools/ask-user-question/state/selectors/projections.js.map +1 -1
  109. package/dist/core/tools/ask-user-question/state/state-reducer.js +1 -1
  110. package/dist/core/tools/ask-user-question/state/state-reducer.js.map +1 -1
  111. package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts.map +1 -1
  112. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js +6 -6
  113. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js.map +1 -1
  114. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts +5 -3
  115. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts.map +1 -1
  116. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js +14 -4
  117. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js.map +1 -1
  118. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts +2 -0
  119. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts.map +1 -1
  120. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js +3 -3
  121. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js.map +1 -1
  122. package/dist/core/tools/ask-user-question/view/components/wrapping-select.d.ts +16 -6
  123. package/dist/core/tools/ask-user-question/view/components/wrapping-select.d.ts.map +1 -1
  124. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js +42 -24
  125. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js.map +1 -1
  126. package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts.map +1 -1
  127. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js +12 -3
  128. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js.map +1 -1
  129. package/dist/core/tools/read.d.ts +1 -0
  130. package/dist/core/tools/read.d.ts.map +1 -1
  131. package/dist/core/tools/read.js +13 -14
  132. package/dist/core/tools/read.js.map +1 -1
  133. package/dist/core/worktree-snapshot/index.d.ts +2 -2
  134. package/dist/core/worktree-snapshot/index.d.ts.map +1 -1
  135. package/dist/core/worktree-snapshot/index.js +1 -1
  136. package/dist/core/worktree-snapshot/index.js.map +1 -1
  137. package/dist/core/worktree-snapshot/records.d.ts +6 -0
  138. package/dist/core/worktree-snapshot/records.d.ts.map +1 -1
  139. package/dist/core/worktree-snapshot/records.js +18 -4
  140. package/dist/core/worktree-snapshot/records.js.map +1 -1
  141. package/dist/core/worktree-snapshot/restore.d.ts +24 -1
  142. package/dist/core/worktree-snapshot/restore.d.ts.map +1 -1
  143. package/dist/core/worktree-snapshot/restore.js +443 -72
  144. package/dist/core/worktree-snapshot/restore.js.map +1 -1
  145. package/dist/core/worktree-snapshot/types.d.ts +44 -0
  146. package/dist/core/worktree-snapshot/types.d.ts.map +1 -1
  147. package/dist/core/worktree-snapshot/types.js.map +1 -1
  148. package/dist/index.d.ts +2 -2
  149. package/dist/index.d.ts.map +1 -1
  150. package/dist/index.js +2 -2
  151. package/dist/index.js.map +1 -1
  152. package/dist/modes/interactive/components/tool-execution.js +2 -1
  153. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  154. package/dist/modes/interactive/interactive-slash-commands.js +4 -1
  155. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  156. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  157. package/dist/modes/interactive-engine/isolated-runtime.js +8 -0
  158. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  159. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  160. package/dist/modes/rpc/rpc-command-handler.js +11 -2
  161. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  162. package/dist/modes/rpc/rpc-command-timeouts.d.ts.map +1 -1
  163. package/dist/modes/rpc/rpc-command-timeouts.js +1 -0
  164. package/dist/modes/rpc/rpc-command-timeouts.js.map +1 -1
  165. package/dist/modes/rpc/rpc-input-scheduler.d.ts.map +1 -1
  166. package/dist/modes/rpc/rpc-input-scheduler.js +1 -0
  167. package/dist/modes/rpc/rpc-input-scheduler.js.map +1 -1
  168. package/dist/modes/rpc/rpc-types.d.ts +11 -1
  169. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  170. package/dist/modes/rpc/rpc-types.js.map +1 -1
  171. package/docs/environment-variables.md +1 -1
  172. package/docs/guides/resume-on-any-machine.md +6 -4
  173. package/docs/intercom/operations.md +4 -0
  174. package/docs/rpc/protocol.md +2 -2
  175. package/docs/sdk/reference.md +3 -0
  176. package/docs/sdk.md +2 -2
  177. package/docs/session-format.md +11 -2
  178. package/docs/sessions.md +4 -2
  179. package/docs/settings.md +1 -1
  180. package/docs/workflows/api-reference.md +2 -2
  181. package/docs/worktree-snapshots.md +13 -5
  182. package/npm-shrinkwrap.json +32 -32
  183. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -2,6 +2,38 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.85-alpha.1] - 2026-11-13
6
+
7
+ Resumed sessions always open, and `/tree` navigation now sticks.
8
+
9
+ - **Resume never strands a session.** A resume opens the full conversation even when a worktree snapshot cannot be restored exactly, restores the closest state it can reach, and says what is missing. Snapshots taken in a restored worktree keep the recorded remotes, so a later resume on another machine no longer fails with `commits-unavailable` ([#4733](https://github.com/bastani-inc/atomic/issues/4733), [#4739](https://github.com/bastani-inc/atomic/pull/4739), [#4732](https://github.com/bastani-inc/atomic/issues/4732), [#4734](https://github.com/bastani-inc/atomic/pull/4734)).
10
+ - **`/tree` moves show and stay.** The chat, tree, `/session`, and context indicator follow the selected branch at once, and the move survives quitting, resuming, and workflow forks ([#3325](https://github.com/bastani-inc/atomic/issues/3325), [#4736](https://github.com/bastani-inc/atomic/pull/4736)).
11
+ - **Fewer wasted requests, accurate usage.** Unsaved sessions skip the per-turn summary request, and the footer and `/session` count the latest summary's tokens and cost right away ([#4726](https://github.com/bastani-inc/atomic/issues/4726), [#4730](https://github.com/bastani-inc/atomic/pull/4730)).
12
+ - **Automatic retries on dropped connections.** Provider errors that report only a socket code such as `ECONNRESET` or `EPIPE` are now retried in sessions, workflows, and subagents ([#4740](https://github.com/bastani-inc/atomic/pull/4740)).
13
+ - **Smaller fixes.** `/copy` copies the right reply, `read` no longer leaves a stale image warning after switching to a vision model, huge tool results render without crashing, and `ask_user_question` fields keep readable colors after going back ([#4740](https://github.com/bastani-inc/atomic/pull/4740), [#4741](https://github.com/bastani-inc/atomic/issues/4741), [#4742](https://github.com/bastani-inc/atomic/pull/4742)).
14
+ - **Cleaner agent directories for SDK hosts.** The extension transpile cache follows each load's agent directory, and a disposed session's Intercom broker no longer writes into it ([#4728](https://github.com/bastani-inc/atomic/issues/4728), [#4731](https://github.com/bastani-inc/atomic/pull/4731), [#4727](https://github.com/bastani-inc/atomic/issues/4727), [#4737](https://github.com/bastani-inc/atomic/pull/4737)).
15
+
16
+ ### Added
17
+
18
+ - `SessionManager.recordBranch(entryId | null)` moves the leaf like `branch()` or `resetLeaf()` and saves the move, so the session reopens there, and `getSessionLeafId(entries)` returns the entry a stored session reopens at ([#3325](https://github.com/bastani-inc/atomic/issues/3325))
19
+
20
+ ### Changed
21
+
22
+ - `--no-session` and other unsaved sessions no longer generate session summaries, so they no longer send one extra model request after each turn. Summaries exist for the `/resume` picker, which never lists unsaved sessions. RPC `get_session_summary` returns `null` for an unsaved session ([#4726](https://github.com/bastani-inc/atomic/issues/4726))
23
+ - Resuming a session now always opens it with its full conversation, even when a worktree snapshot cannot be restored exactly ([#4733](https://github.com/bastani-inc/atomic/issues/4733)). Missing unpushed commits, `denied-history`, a missing or damaged snapshot blob, a change set that does not apply, an unreachable remote and an unavailable Git no longer stop the resume. Atomic restores the best state it can reach: the recorded commit with the change sets that apply (each whole or not at all), else the closest commit it can fetch (the pushed base, an earlier snapshot's commit, then the branch tip), else no checkout. In the last case the session continues in its recorded directory, or in the directory the resume started from when that is not on this machine, and nothing is ever written to either. Each such checkout gets one notice that says what was restored, what is missing and what to do next. The outcome is recorded on the session (`restore.degraded` or an `unrestored` entry) and shown by `/session snapshot`, and later snapshots record the tree the worktree actually holds. A session resume is now refused only when the session cannot be read, when a snapshot record fails the security checks, or when a restore target holds other files. Snapshot records whose remotes carry credentials, name a Git remote helper (`ext::`), or use a scheme other than `https`, `http`, `ssh`, `git` or `file` now fail with `invalid-snapshot` (`unsafe-remote`) before any Git command runs. New SDK exports: `restoreDegradedWorktree`, `isDegradableRestoreFailure`, `isRecoverableRestoreFailure`, `formatDegradedRestoreNotice` and `formatUnrestoredNotice`. `resumeSessionWorktree` gains the `cannotRestore`, `fallbackCwd` and `skipMissingRecords` options and reports `unrestored` and `missingRecords`.
24
+
25
+ ### Fixed
26
+
27
+ - Fixed the footer usage, the context indicator, and `/session` leaving out the tokens and cost of the latest session summary until a later turn or `/reload`. They now update as soon as the summary is saved, and also when a cache warm records its usage ([#4726](https://github.com/bastani-inc/atomic/issues/4726))
28
+ - Fixed `/tree` in interactive mode leaving the abandoned turns in the chat, keeping the tree cursor and `/clone` on the old leaf, and not showing a requested branch summary until the next turn. The chat, the tree, `/session` and the context indicator now follow the selected branch as soon as you navigate, and Escape while the summary is generated cancels it. Also fixed a `/tree` move without a summary being lost when you quit, resumed, continued, or the interactive engine restarted before the next turn, which put the abandoned turns back into the next request. The move is now saved in the session, so it reopens on the selected branch; `listForkPoints()` and workflow run forks use that branch too ([#3325](https://github.com/bastani-inc/atomic/issues/3325))
29
+ - Fixed the extension transpile cache staying under the first agent directory a process used: each load now caches under the agent directory in effect for it (`ATOMIC_CODING_AGENT_DIR` at that time, or the SDK session's `agentDir`), stale cache versions are pruned in every agent directory, and extension loads no longer create or recreate a missing agent directory; they skip the cache instead ([#4728](https://github.com/bastani-inc/atomic/issues/4728))
30
+ - Fixed snapshots captured in a worktree Atomic restored recording no remotes and bundling the checkout's whole history as unpushed, which made a resume on a third machine fail with `commits-unavailable` even for a fully pushed repository. A restored worktree now has the snapshot's recorded remotes (`origin`, then `origin-2`, …, credential-free as recorded, and only over the transports a restore fetches over) and remote-tracking refs under `refs/remotes/atomic/pushed/` for the commits a recorded remote is known to have, so later captures record the remotes and bundle only commits that are really unpushed. A repository without remotes restores and captures as before ([#4732](https://github.com/bastani-inc/atomic/issues/4732))
31
+ - Fixed `/copy` and RPC `get_last_assistant_text` skipping past a reply that ended normally without text and copying an earlier turn's answer instead, while still skipping empty turns that ended via abort, error, or tool calls (upstream [#12119](https://github.com/earendil-works/pi/issues/12119), [#12121](https://github.com/earendil-works/pi/pull/12121))
32
+ - Fixed provider errors that report only a Node socket error code (`ECONNRESET`, `ECONNABORTED`, `ECONNREFUSED`, `ETIMEDOUT`, `EPIPE`) not triggering automatic retries in sessions, workflows, and subagents, without matching those codes inside longer identifiers (upstream [#12128](https://github.com/earendil-works/pi/issues/12128), [#12136](https://github.com/earendil-works/pi/pull/12136))
33
+ - Fixed `read` storing a note that the current model does not support images in the tool result sent to the model, which replayed as stale text after switching to a vision model; the warning is now recorded in `details.imageUnsupportedByModel` and shown in the TUI both collapsed and expanded while `@bastani/pi-ai` still replaces unsupported images per request (upstream [#12131](https://github.com/earendil-works/pi/issues/12131), [#12139](https://github.com/earendil-works/pi/pull/12139))
34
+ - Fixed `ToolExecutionComponent` crashing with `RangeError: Maximum call stack size exceeded` when rendering a very large self-rendered tool result such as a multi-megabyte edit diff (upstream [#8036](https://github.com/earendil-works/pi/issues/8036), [#12145](https://github.com/earendil-works/pi/pull/12145))
35
+ - Fixed `ask_user_question` text fields showing the wrong color, or hiding what you typed, after you navigate back to a question with ←, Shift+Tab, or from the review tab. The "Type something." answer, "Chat about this", and notes now use the accent color while you edit them, the normal text color when they hold text without focus (so a draft stays visible on one line after you move away), and the muted color when empty. The same rule applies to answered and checked rows and to the review tab. Moving the cursor back inside a field no longer drops the color of the text after it, and reopened notes put the cursor at the end ([#4741](https://github.com/bastani-inc/atomic/issues/4741))
36
+
5
37
  ## [0.9.84] - 2026-11-13
6
38
 
7
39
  Sessions now move between machines alongside workflow runs.
@@ -4,6 +4,12 @@ All notable changes to the `pi-intercom` extension will be documented in this fi
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.9.85-alpha.1] - 2026-11-13
8
+
9
+ ### Fixed
10
+
11
+ - Fixed an Intercom broker started by a session that was then disposed writing into the agent directory after `dispose()` resolved: disposing a session now cancels a broker start it has not launched and waits for one it has (stopping it if it does not start in time), and a broker creates its `delivered-messages` files only when the first session registers, so one that exits without serving a session leaves none behind. Hosts that remove a temporary `ATOMIC_CODING_AGENT_DIR` after disposal no longer see it reappear or fail with `ENOTEMPTY` ([#4727](https://github.com/bastani-inc/atomic/issues/4727))
12
+
7
13
  ## [0.9.81] - 2026-11-13
8
14
 
9
15
  Subagents start reliably when the Intercom broker is briefly slow.
@@ -359,11 +359,24 @@ class IntercomBroker {
359
359
  private watchdog: BrokerWatchdog | undefined;
360
360
  private boundSocketInode: number | undefined;
361
361
  private lastConnectionAt = performance.now();
362
- private deliveredMessages = new DeliveredMessageCache(
363
- DELIVERED_MESSAGE_TTL_MS,
364
- DELIVERED_MESSAGE_MAX_ENTRIES,
365
- getBrokerDeliveredMessagesPath(),
366
- );
362
+ private deliveredMessageCache: DeliveredMessageCache | undefined;
363
+ /**
364
+ * #4727: the durable delivered-message authority is opened when the first session registers, before that session can
365
+ * send, so a broker that idles out having served no session leaves no durable state in the agent directory. A broker
366
+ * that does serve one reads what its predecessors recorded, so a retried send is still deduplicated across restarts.
367
+ */
368
+ private openDeliveredMessages(): DeliveredMessageCache {
369
+ this.deliveredMessageCache ??= new DeliveredMessageCache(
370
+ DELIVERED_MESSAGE_TTL_MS,
371
+ DELIVERED_MESSAGE_MAX_ENTRIES,
372
+ getBrokerDeliveredMessagesPath(),
373
+ );
374
+ return this.deliveredMessageCache;
375
+ }
376
+
377
+ private get deliveredMessages(): DeliveredMessageCache {
378
+ return this.openDeliveredMessages();
379
+ }
367
380
  private supervisorChannel = new SupervisorChannelCache();
368
381
  private sessionIdReclaim = new SessionIdReclaim();
369
382
  private pendingQuestions = new PendingQuestionIndex();
@@ -1850,6 +1863,7 @@ class IntercomBroker {
1850
1863
  supervisorId = claimedSupervisorId;
1851
1864
  }
1852
1865
 
1866
+ this.openDeliveredMessages();
1853
1867
  // #3760: a restored or reconnected session keeps the id peers know when it is free; never a live one.
1854
1868
  const id = this.sessionIdReclaim.grant(
1855
1869
  clientMessage.preferredSessionId,
@@ -2813,7 +2827,11 @@ class IntercomBroker {
2813
2827
  writeConfirmed: writeMessageWithOutcome,
2814
2828
  supervisorCache: this.supervisorChannel,
2815
2829
  pendingQuestions: this.pendingQuestions,
2816
- deliveredMessages: this.deliveredMessages,
2830
+ // A remote send reaches only a session registered here, which has opened the authority (#4727).
2831
+ deliveredMessages: {
2832
+ lookupForTarget: (...args) => this.deliveredMessages.lookupForTarget(...args),
2833
+ lookupQuestionTarget: (...args) => this.deliveredMessages.lookupQuestionTarget(...args),
2834
+ },
2817
2835
  dispatch: (socket, clientMessage, senderId) => this.dispatchSend(socket, clientMessage, senderId),
2818
2836
  revokeReleasedReservation: (key, ownerSessionId) => this.revokeReleasedReservation(key, ownerSessionId),
2819
2837
  },
@@ -3219,7 +3237,7 @@ class IntercomBroker {
3219
3237
  this.receipts.clear();
3220
3238
  for (const pending of this.pendingStageNotificationAcknowledgments.values()) clearTimeout(pending.timeout);
3221
3239
  this.pendingStageNotificationAcknowledgments.clear();
3222
- this.deliveredMessages.close();
3240
+ this.deliveredMessageCache?.close();
3223
3241
  // The watchdog thread ends while this broker's pipe still answers its probes. On Windows, process.exit waits for
3224
3242
  // that thread, and the thread for its probe's connection: one made after the pipe server closed, while a session's
3225
3243
  // connection still holds the pipe open, finds the pipe busy and waits up to 30 s for a free instance.
@@ -376,29 +376,40 @@ function toError(error: unknown): Error {
376
376
  return error instanceof Error ? error : new Error(String(error));
377
377
  }
378
378
 
379
+ /**
380
+ * Start the broker unless one answers. #4727: `signal` cancels the start until the broker process exists: nothing is
381
+ * written into the agent directory once it aborts, and waiting for another spawner's broker stops at once. A broker
382
+ * this call already launched is waited for until it listens, and stopped if it does not within the startup timeout, so
383
+ * the call never returns while that broker is still writing its start-up files. An aborted call rejects with
384
+ * `signal.reason`.
385
+ */
379
386
  export async function spawnBrokerIfNeeded(
380
387
  brokerCommand: string,
381
388
  brokerArgs: string[],
382
389
  readyTimeoutMs: number = BROKER_READY_TIMEOUT_MS,
383
390
  extensionDir: string = EXTENSION_DIR,
391
+ signal?: AbortSignal,
384
392
  ): Promise<void> {
393
+ signal?.throwIfAborted();
385
394
  ensurePrivateDirectory(getIntercomDirPath());
386
395
 
387
396
  if (await isBrokerRunning()) {
388
397
  return;
389
398
  }
390
399
 
400
+ signal?.throwIfAborted();
391
401
  const lockOwner = acquireSpawnLock();
392
402
  if (lockOwner === undefined) {
393
- await waitForBroker(readyTimeoutMs);
403
+ await waitForBroker(readyTimeoutMs, undefined, signal);
394
404
  return;
395
405
  }
396
- await spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, true);
406
+ await spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, true, signal);
397
407
  }
398
408
 
399
409
  /**
400
410
  * Start a broker while holding the spawn lock `lockOwner` wrote, and release it, unless a broker still starting takes
401
- * it over. `recheck` returns at once when a broker answers by now.
411
+ * it over. `recheck` returns at once when a broker answers by now. An aborted `signal` cancels the start before the
412
+ * broker is launched, unless `launchAnyway`, and stops a launched broker that misses its startup timeout (#4727).
402
413
  */
403
414
  async function spawnBrokerHoldingLock(
404
415
  lockOwner: string,
@@ -407,12 +418,16 @@ async function spawnBrokerHoldingLock(
407
418
  readyTimeoutMs: number,
408
419
  extensionDir: string,
409
420
  recheck: boolean,
421
+ signal?: AbortSignal,
422
+ launchAnyway = false,
410
423
  ): Promise<void> {
424
+ const cancelSignal = launchAnyway ? undefined : signal;
411
425
  let keepLock = false;
412
426
  try {
413
427
  if (recheck && (await isBrokerRunning())) {
414
428
  return;
415
429
  }
430
+ cancelSignal?.throwIfAborted();
416
431
 
417
432
  const brokerPath = resolveBrokerEntrypoint(extensionDir);
418
433
  const launch = getBrokerLaunchSpec(brokerPath, brokerCommand, brokerArgs, extensionDir);
@@ -432,9 +447,11 @@ async function spawnBrokerHoldingLock(
432
447
  }
433
448
  // Reset before spawning either way: the Windows launcher appends to this same path.
434
449
  if (!(await resetBrokerLogOnceReleased())) {
435
- await waitForBroker(readyTimeoutMs);
450
+ await waitForBroker(readyTimeoutMs, undefined, cancelSignal);
436
451
  return;
437
452
  }
453
+ // The last point before the broker exists; from here it is waited for, never abandoned while it starts.
454
+ cancelSignal?.throwIfAborted();
438
455
  // The Windows launcher redirects the broker's own stderr, so only the direct spawn
439
456
  // needs the descriptor. Node duplicates it during spawn, so the parent copy is closed
440
457
  // immediately afterwards rather than being held open for the broker's lifetime.
@@ -489,16 +506,25 @@ async function spawnBrokerHoldingLock(
489
506
  resolve();
490
507
  }, (error) => {
491
508
  cleanup();
509
+ const starting = launch.kind === "direct" && child.exitCode === null && child.signalCode === null;
510
+ // #4727: the session that launched this broker is gone and the broker did not start in time; it is stopped
511
+ // before this call returns, so it never writes into an agent directory its host may already be removing. Behind
512
+ // the Windows launcher the broker is found by the pid it announced; one that never announced cannot be found.
513
+ let abandonedPid: number | undefined;
514
+ if (signal?.aborted) {
515
+ if (launch.kind === "direct") abandonedPid = starting ? child.pid : undefined;
516
+ else if (announcement !== undefined) abandonedPid = readBrokerStartAnnouncement(announcement);
517
+ }
518
+ if (abandonedPid !== undefined) {
519
+ void stopStartingBroker(abandonedPid).finally(() => reject(toError(error)));
520
+ return;
521
+ }
492
522
  // A broker still starting keeps the lock, so later spawners wait for it instead of starting another.
493
523
  // Only now does the lock name the broker: until this hand-off it follows this live spawner, so no other
494
524
  // spawner can judge it stale and replace it while this one may still release it.
495
525
  // The Windows launcher hides the broker's pid, so its lock could only follow this live spawner and would
496
526
  // block every later spawn; there the broker's own live-socket check is what prevents a takeover.
497
- keepLock =
498
- launch.kind === "direct" &&
499
- child.exitCode === null &&
500
- child.signalCode === null &&
501
- handSpawnLockToBroker(child.pid, lockOwner);
527
+ keepLock = starting && handSpawnLockToBroker(child.pid, lockOwner);
502
528
  reject(toError(error));
503
529
  });
504
530
  });
@@ -507,6 +533,34 @@ async function spawnBrokerHoldingLock(
507
533
  }
508
534
  }
509
535
 
536
+ /** Bound on waiting for a killed, still-starting broker to be gone; a kill that has not taken by then never will. */
537
+ const STARTING_BROKER_KILL_WAIT_MS = 5_000;
538
+
539
+ /**
540
+ * Kill a broker that has not started listening, with every process it started, and wait until they are gone. A custom
541
+ * broker command can run the broker as its own child rather than replacing itself with it. Elsewhere than Windows the
542
+ * broker was spawned detached, so it leads a process group of its own; on Windows `pid` is the broker's announced pid,
543
+ * and `taskkill /T` ends its process tree.
544
+ */
545
+ async function stopStartingBroker(pid: number): Promise<void> {
546
+ const deadline = Date.now() + STARTING_BROKER_KILL_WAIT_MS;
547
+ if (process.platform === "win32") {
548
+ await new Promise<void>((resolve) => {
549
+ const taskkill = spawn("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
550
+ taskkill.once("error", () => resolve());
551
+ taskkill.once("exit", () => resolve());
552
+ });
553
+ while (isProcessAlive(pid) && Date.now() < deadline) await sleep(BROKER_POLL_MAX_INTERVAL_MS);
554
+ return;
555
+ }
556
+ try {
557
+ process.kill(-pid, "SIGKILL");
558
+ } catch {
559
+ return;
560
+ }
561
+ while (isProcessAlive(-pid) && Date.now() < deadline) await sleep(BROKER_POLL_MAX_INTERVAL_MS);
562
+ }
563
+
510
564
  /** How often a session waiting to upgrade the broker checks whether the spawn lock is free. */
511
565
  const UPGRADE_LOCK_POLL_MS = 50;
512
566
 
@@ -538,7 +592,10 @@ export type BrokerUpgradeOutcome =
538
592
  * ({@link BROKER_SPAWN_LOCK_MAX_AGE_MS} after its last renewal, about a minute). Once the process exits or the lock ages
539
593
  * out, the next spawner of either version takes it, so an older session can start an older broker, which the next
540
594
  * session of this version replaces again. A failure to stop the older broker, or to start the successor once it
541
- * stopped, is an {@link IntercomBrokerUpgradeError} whose cause is that step's failure.
595
+ * stopped, is an {@link IntercomBrokerUpgradeError} whose cause is that step's failure. `signal` cancels the upgrade
596
+ * until it asks the running broker to shut down, including its wait for the spawn lock, and a start where none is
597
+ * running as {@link spawnBrokerIfNeeded} does; once the running broker is asked to stop, the successor is launched
598
+ * regardless and stopped only if it then misses its startup timeout (#4727).
542
599
  */
543
600
  export async function upgradeBroker(
544
601
  brokerCommand: string,
@@ -547,20 +604,22 @@ export async function upgradeBroker(
547
604
  extensionDir: string = EXTENSION_DIR,
548
605
  own: BrokerProtocolRange = BROKER_PROTOCOL,
549
606
  stopTimeoutMs: number = BROKER_UPGRADE_STOP_TIMEOUT_MS,
607
+ signal?: AbortSignal,
550
608
  ): Promise<BrokerUpgradeOutcome> {
609
+ signal?.throwIfAborted();
551
610
  ensurePrivateDirectory(getIntercomDirPath());
552
- const acquired = await acquireSpawnLockWithin(readyTimeoutMs + stopTimeoutMs);
611
+ const acquired = await acquireSpawnLockWithin(readyTimeoutMs + stopTimeoutMs, signal);
553
612
  if (acquired === undefined) return "busy";
554
613
  let lockOwner = acquired;
555
614
  let lockPassedOn = false;
556
- const spawnHoldingLock = (): Promise<void> => {
615
+ const spawnHoldingLock = (launchAnyway: boolean): Promise<void> => {
557
616
  lockPassedOn = true;
558
- return spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, false);
617
+ return spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, false, signal, launchAnyway);
559
618
  };
560
619
  try {
561
620
  const answer = await controlRequest(getBrokerSocketPath(), "broker_status", "broker_status", BROKER_CONTROL_TIMEOUT_MS);
562
621
  if (!answer.connected) {
563
- await spawnHoldingLock();
622
+ await spawnHoldingLock(false);
564
623
  return "started";
565
624
  }
566
625
  const reply = answer.reply;
@@ -574,6 +633,10 @@ export async function upgradeBroker(
574
633
  if (report.storage?.digest !== successorStorageDigest()) return "storage-differs";
575
634
  const failed = (phase: "stop" | "start", cause?: Error): IntercomBrokerUpgradeError =>
576
635
  new IntercomBrokerUpgradeError({ phase, previousPid: report.pid, previousProtocolMax: running.max }, { cause });
636
+ // #4727: a cancelled upgrade leaves the running broker alone; one that has asked it to shut down launches its
637
+ // successor whatever happens, so the broker's other sessions have one to reconnect to. Only a successor that then
638
+ // misses its startup timeout is stopped once the upgrade is cancelled.
639
+ signal?.throwIfAborted();
577
640
  if ((await requestBrokerShutdown(getBrokerSocketPath())) === "unanswered") throw failed("stop");
578
641
  try {
579
642
  await waitForBrokerExit(report.pid, stopTimeoutMs, () => {
@@ -587,7 +650,7 @@ export async function upgradeBroker(
587
650
  throw error;
588
651
  }
589
652
  try {
590
- await spawnHoldingLock();
653
+ await spawnHoldingLock(true);
591
654
  } catch (error) {
592
655
  throw failed("start", toError(error));
593
656
  }
@@ -605,10 +668,11 @@ function successorStorageDigest(): string | undefined {
605
668
  return setting === undefined ? undefined : sharedStorageDigest(setting);
606
669
  }
607
670
 
608
- /** Take the spawn lock, waiting up to `boundMs` while another process holds it. */
609
- async function acquireSpawnLockWithin(boundMs: number): Promise<string | undefined> {
671
+ /** Take the spawn lock, waiting up to `boundMs` while another process holds it; an aborted `signal` ends the wait. */
672
+ async function acquireSpawnLockWithin(boundMs: number, signal?: AbortSignal): Promise<string | undefined> {
610
673
  const deadline = Date.now() + boundMs;
611
674
  for (;;) {
675
+ signal?.throwIfAborted();
612
676
  const owner = acquireSpawnLock();
613
677
  if (owner !== undefined || Date.now() >= deadline) return owner;
614
678
  await sleep(UPGRADE_LOCK_POLL_MS);
@@ -760,10 +824,12 @@ export function releaseSpawnLock(owner: string, lockPath: string = getBrokerSpaw
760
824
  export async function waitForBroker(
761
825
  timeoutMs = BROKER_READY_TIMEOUT_MS,
762
826
  announcedPid?: () => number | undefined,
827
+ signal?: AbortSignal,
763
828
  ): Promise<void> {
764
829
  const start = Date.now();
765
830
  let interval = BROKER_POLL_INITIAL_INTERVAL_MS;
766
831
  while (Date.now() - start < timeoutMs) {
832
+ signal?.throwIfAborted();
767
833
  if (await checkSocketConnectable()) {
768
834
  return;
769
835
  }
@@ -4188,24 +4188,28 @@ ${tail}`;
4188
4188
  function toError3(error) {
4189
4189
  return error instanceof Error ? error : new Error(String(error));
4190
4190
  }
4191
- async function spawnBrokerIfNeeded(brokerCommand, brokerArgs, readyTimeoutMs = BROKER_READY_TIMEOUT_MS, extensionDir = EXTENSION_DIR) {
4191
+ async function spawnBrokerIfNeeded(brokerCommand, brokerArgs, readyTimeoutMs = BROKER_READY_TIMEOUT_MS, extensionDir = EXTENSION_DIR, signal) {
4192
+ signal?.throwIfAborted();
4192
4193
  ensurePrivateDirectory(getIntercomDirPath());
4193
4194
  if (await isBrokerRunning()) {
4194
4195
  return;
4195
4196
  }
4197
+ signal?.throwIfAborted();
4196
4198
  const lockOwner = acquireSpawnLock();
4197
4199
  if (lockOwner === undefined) {
4198
- await waitForBroker(readyTimeoutMs);
4200
+ await waitForBroker(readyTimeoutMs, undefined, signal);
4199
4201
  return;
4200
4202
  }
4201
- await spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, true);
4203
+ await spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, true, signal);
4202
4204
  }
4203
- async function spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, recheck) {
4205
+ async function spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, recheck, signal, launchAnyway = false) {
4206
+ const cancelSignal = launchAnyway ? undefined : signal;
4204
4207
  let keepLock = false;
4205
4208
  try {
4206
4209
  if (recheck && await isBrokerRunning()) {
4207
4210
  return;
4208
4211
  }
4212
+ cancelSignal?.throwIfAborted();
4209
4213
  const brokerPath = resolveBrokerEntrypoint(extensionDir);
4210
4214
  const launch = getBrokerLaunchSpec(brokerPath, brokerCommand, brokerArgs, extensionDir);
4211
4215
  const announcement = launch.kind === "windows-launcher" ? { path: getBrokerStartAnnouncementPath(), token: randomUUID4() } : undefined;
@@ -4218,9 +4222,10 @@ async function spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, read
4218
4222
  writeWindowsHiddenLauncher(launch.launcherCommandLine, launch.launcherPath);
4219
4223
  }
4220
4224
  if (!await resetBrokerLogOnceReleased()) {
4221
- await waitForBroker(readyTimeoutMs);
4225
+ await waitForBroker(readyTimeoutMs, undefined, cancelSignal);
4222
4226
  return;
4223
4227
  }
4228
+ cancelSignal?.throwIfAborted();
4224
4229
  const logFd = launch.kind === "direct" ? openSync(getBrokerLogPath(), "a") : undefined;
4225
4230
  let child;
4226
4231
  try {
@@ -4265,7 +4270,19 @@ ${describeBrokerLog()}`);
4265
4270
  resolve();
4266
4271
  }, (error) => {
4267
4272
  cleanup();
4268
- keepLock = launch.kind === "direct" && child.exitCode === null && child.signalCode === null && handSpawnLockToBroker(child.pid, lockOwner);
4273
+ const starting = launch.kind === "direct" && child.exitCode === null && child.signalCode === null;
4274
+ let abandonedPid;
4275
+ if (signal?.aborted) {
4276
+ if (launch.kind === "direct")
4277
+ abandonedPid = starting ? child.pid : undefined;
4278
+ else if (announcement !== undefined)
4279
+ abandonedPid = readBrokerStartAnnouncement(announcement);
4280
+ }
4281
+ if (abandonedPid !== undefined) {
4282
+ stopStartingBroker(abandonedPid).finally(() => reject(toError3(error)));
4283
+ return;
4284
+ }
4285
+ keepLock = starting && handSpawnLockToBroker(child.pid, lockOwner);
4269
4286
  reject(toError3(error));
4270
4287
  });
4271
4288
  });
@@ -4274,21 +4291,42 @@ ${describeBrokerLog()}`);
4274
4291
  releaseSpawnLock(lockOwner);
4275
4292
  }
4276
4293
  }
4277
- async function upgradeBroker(brokerCommand, brokerArgs, readyTimeoutMs = BROKER_READY_TIMEOUT_MS, extensionDir = EXTENSION_DIR, own = BROKER_PROTOCOL, stopTimeoutMs = BROKER_UPGRADE_STOP_TIMEOUT_MS) {
4294
+ async function stopStartingBroker(pid) {
4295
+ const deadline = Date.now() + STARTING_BROKER_KILL_WAIT_MS;
4296
+ if (process.platform === "win32") {
4297
+ await new Promise((resolve) => {
4298
+ const taskkill = spawn("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
4299
+ taskkill.once("error", () => resolve());
4300
+ taskkill.once("exit", () => resolve());
4301
+ });
4302
+ while (isProcessAlive2(pid) && Date.now() < deadline)
4303
+ await sleep2(BROKER_POLL_MAX_INTERVAL_MS);
4304
+ return;
4305
+ }
4306
+ try {
4307
+ process.kill(-pid, "SIGKILL");
4308
+ } catch {
4309
+ return;
4310
+ }
4311
+ while (isProcessAlive2(-pid) && Date.now() < deadline)
4312
+ await sleep2(BROKER_POLL_MAX_INTERVAL_MS);
4313
+ }
4314
+ async function upgradeBroker(brokerCommand, brokerArgs, readyTimeoutMs = BROKER_READY_TIMEOUT_MS, extensionDir = EXTENSION_DIR, own = BROKER_PROTOCOL, stopTimeoutMs = BROKER_UPGRADE_STOP_TIMEOUT_MS, signal) {
4315
+ signal?.throwIfAborted();
4278
4316
  ensurePrivateDirectory(getIntercomDirPath());
4279
- const acquired = await acquireSpawnLockWithin(readyTimeoutMs + stopTimeoutMs);
4317
+ const acquired = await acquireSpawnLockWithin(readyTimeoutMs + stopTimeoutMs, signal);
4280
4318
  if (acquired === undefined)
4281
4319
  return "busy";
4282
4320
  let lockOwner = acquired;
4283
4321
  let lockPassedOn = false;
4284
- const spawnHoldingLock = () => {
4322
+ const spawnHoldingLock = (launchAnyway) => {
4285
4323
  lockPassedOn = true;
4286
- return spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, false);
4324
+ return spawnBrokerHoldingLock(lockOwner, brokerCommand, brokerArgs, readyTimeoutMs, extensionDir, false, signal, launchAnyway);
4287
4325
  };
4288
4326
  try {
4289
4327
  const answer = await controlRequest(getBrokerSocketPath(), "broker_status", "broker_status", BROKER_CONTROL_TIMEOUT_MS);
4290
4328
  if (!answer.connected) {
4291
- await spawnHoldingLock();
4329
+ await spawnHoldingLock(false);
4292
4330
  return "started";
4293
4331
  }
4294
4332
  const reply = answer.reply;
@@ -4301,6 +4339,7 @@ async function upgradeBroker(brokerCommand, brokerArgs, readyTimeoutMs = BROKER_
4301
4339
  if (report.storage?.digest !== successorStorageDigest())
4302
4340
  return "storage-differs";
4303
4341
  const failed = (phase, cause) => new IntercomBrokerUpgradeError({ phase, previousPid: report.pid, previousProtocolMax: running.max }, { cause });
4342
+ signal?.throwIfAborted();
4304
4343
  if (await requestBrokerShutdown(getBrokerSocketPath()) === "unanswered")
4305
4344
  throw failed("stop");
4306
4345
  try {
@@ -4315,7 +4354,7 @@ async function upgradeBroker(brokerCommand, brokerArgs, readyTimeoutMs = BROKER_
4315
4354
  throw error;
4316
4355
  }
4317
4356
  try {
4318
- await spawnHoldingLock();
4357
+ await spawnHoldingLock(true);
4319
4358
  } catch (error) {
4320
4359
  throw failed("start", toError3(error));
4321
4360
  }
@@ -4331,9 +4370,10 @@ function successorStorageDigest() {
4331
4370
  });
4332
4371
  return setting === undefined ? undefined : sharedStorageDigest(setting);
4333
4372
  }
4334
- async function acquireSpawnLockWithin(boundMs) {
4373
+ async function acquireSpawnLockWithin(boundMs, signal) {
4335
4374
  const deadline = Date.now() + boundMs;
4336
4375
  for (;; ) {
4376
+ signal?.throwIfAborted();
4337
4377
  const owner = acquireSpawnLock();
4338
4378
  if (owner !== undefined || Date.now() >= deadline)
4339
4379
  return owner;
@@ -4452,10 +4492,11 @@ function releaseSpawnLock(owner, lockPath = getBrokerSpawnLockPath()) {
4452
4492
  unlinkSync2(lockPath);
4453
4493
  } catch {}
4454
4494
  }
4455
- async function waitForBroker(timeoutMs = BROKER_READY_TIMEOUT_MS, announcedPid) {
4495
+ async function waitForBroker(timeoutMs = BROKER_READY_TIMEOUT_MS, announcedPid, signal) {
4456
4496
  const start = Date.now();
4457
4497
  let interval = BROKER_POLL_INITIAL_INTERVAL_MS;
4458
4498
  while (Date.now() - start < timeoutMs) {
4499
+ signal?.throwIfAborted();
4459
4500
  if (await checkSocketConnectable()) {
4460
4501
  return;
4461
4502
  }
@@ -4473,7 +4514,7 @@ ${describeBrokerLog()}`);
4473
4514
  ` + "The broker did not answer on its socket in time; it may still be starting, which a busy machine or an empty jiti " + "cache slows. Try again, or raise `brokerStartupTimeoutMs` in the Intercom config.json (default " + `${BROKER_READY_TIMEOUT_MS} ms).
4474
4515
  ${describeBrokerLog()}`);
4475
4516
  }
4476
- var EXTENSION_DIR, BROKER_LOG_TAIL_BYTES, BROKER_POLL_INITIAL_INTERVAL_MS = 10, BROKER_POLL_MAX_INTERVAL_MS = 100, BROKER_SPAWN_LOCK_MAX_AGE_MS = 60000, INTERNAL_INTERCOM_BROKER_ARG = "--atomic-internal-intercom-broker", BROKER_LOG_RELEASE_WAIT_MS = 1000, UPGRADE_LOCK_POLL_MS = 50, SPAWN_LOCK_RENEW_AFTER_MS = 1e4;
4517
+ var EXTENSION_DIR, BROKER_LOG_TAIL_BYTES, BROKER_POLL_INITIAL_INTERVAL_MS = 10, BROKER_POLL_MAX_INTERVAL_MS = 100, BROKER_SPAWN_LOCK_MAX_AGE_MS = 60000, INTERNAL_INTERCOM_BROKER_ARG = "--atomic-internal-intercom-broker", BROKER_LOG_RELEASE_WAIT_MS = 1000, STARTING_BROKER_KILL_WAIT_MS = 5000, UPGRADE_LOCK_POLL_MS = 50, SPAWN_LOCK_RENEW_AFTER_MS = 1e4;
4477
4518
  var init_spawn = __esm(() => {
4478
4519
  init_socket_liveness();
4479
4520
  init_start_announcement();
@@ -7398,6 +7439,7 @@ function registerIntercomLifecycle(pi, deps) {
7398
7439
  deps.setDisposed(true);
7399
7440
  deps.incrementRuntimeGeneration();
7400
7441
  deps.clearReconnectTimer();
7442
+ const brokerStarts = deps.abortBrokerStarts?.();
7401
7443
  if (deps.releaseRunningReplyWaits !== undefined)
7402
7444
  deps.releaseRunningReplyWaits(new Error(reason));
7403
7445
  else
@@ -7418,6 +7460,7 @@ function registerIntercomLifecycle(pi, deps) {
7418
7460
  console.error(`Intercom failed to disconnect during ${reason.toLowerCase()}; continuing cleanup:`, error);
7419
7461
  }
7420
7462
  }
7463
+ await brokerStarts;
7421
7464
  if (deps.disconnectAuxiliaryClients) {
7422
7465
  try {
7423
7466
  await deps.disconnectAuxiliaryClients();
@@ -9763,6 +9806,18 @@ function piIntercomExtension(pi, testOverrides = {}) {
9763
9806
  let reconnectPromise = null;
9764
9807
  let reconnectPromiseGeneration = null;
9765
9808
  let reconnectAttempt = 0;
9809
+ let connectAbort = new AbortController;
9810
+ const brokerStarts = new Set;
9811
+ function trackBrokerStart(begin) {
9812
+ const start = (async () => begin())();
9813
+ const settled = start.then(() => {}, () => {});
9814
+ brokerStarts.add(settled);
9815
+ settled.then(() => brokerStarts.delete(settled));
9816
+ return start;
9817
+ }
9818
+ function startBrokerIfNeeded(signal) {
9819
+ return trackBrokerStart(() => spawnBrokerIfNeeded(config.brokerCommand, config.brokerArgs, config.brokerStartupTimeoutMs, undefined, signal));
9820
+ }
9766
9821
  let shuttingDown = false;
9767
9822
  let disposed = true;
9768
9823
  let runtimeStarted = false;
@@ -9822,7 +9877,7 @@ function piIntercomExtension(pi, testOverrides = {}) {
9822
9877
  }
9823
9878
  const releasedStagePeers = new ReleasedStagePeers({
9824
9879
  report: ({ error, retrying, attempt, peers }) => reportReleasedStageFailure("released-stage-reconnect-failed", error, { retrying, attempt, peers }),
9825
- prepare: () => spawnBrokerIfNeeded(config.brokerCommand, config.brokerArgs, config.brokerStartupTimeoutMs),
9880
+ prepare: () => startBrokerIfNeeded(connectAbort.signal),
9826
9881
  createClient: (returnAddress) => new IntercomClient(returnAddress),
9827
9882
  cwd: () => getLiveContext()?.cwd ?? process.cwd(),
9828
9883
  relay: (from, message, channel) => {
@@ -9901,10 +9956,10 @@ function piIntercomExtension(pi, testOverrides = {}) {
9901
9956
  else
9902
9957
  warnLocalOnlyBrokerWithoutUi(reason);
9903
9958
  }
9904
- async function upgradeOlderBroker(agentDir) {
9959
+ async function upgradeOlderBroker(agentDir, signal) {
9905
9960
  let upgradeFailure;
9906
9961
  try {
9907
- await upgradeBroker(config.brokerCommand, config.brokerArgs, config.brokerStartupTimeoutMs);
9962
+ await trackBrokerStart(() => upgradeBroker(config.brokerCommand, config.brokerArgs, config.brokerStartupTimeoutMs, undefined, undefined, undefined, signal));
9908
9963
  } catch (error) {
9909
9964
  if (!isIntercomBrokerUpgradeError(error))
9910
9965
  throw error;
@@ -9912,10 +9967,10 @@ function piIntercomExtension(pi, testOverrides = {}) {
9912
9967
  throw error;
9913
9968
  upgradeFailure = error;
9914
9969
  }
9915
- await spawnBrokerIfNeeded(config.brokerCommand, config.brokerArgs, config.brokerStartupTimeoutMs);
9970
+ await startBrokerIfNeeded(signal);
9916
9971
  return { routing: await queryBrokerRouting(agentDir), upgradeFailure };
9917
9972
  }
9918
- async function settleBrokerRouting(ctx, generation) {
9973
+ async function settleBrokerRouting(ctx, generation, signal) {
9919
9974
  const agentDir = dirname4(getIntercomDirPath());
9920
9975
  const selectedShared = multiNodeSelected(agentDir, processStorageEnvironment());
9921
9976
  let routing;
@@ -9924,7 +9979,7 @@ function piIntercomExtension(pi, testOverrides = {}) {
9924
9979
  routing = await queryBrokerRouting(agentDir);
9925
9980
  let upgradeFailure;
9926
9981
  if (decideBrokerProtocol(BROKER_PROTOCOL, routing.protocol) === "upgrade") {
9927
- ({ routing, upgradeFailure } = await upgradeOlderBroker(agentDir));
9982
+ ({ routing, upgradeFailure } = await upgradeOlderBroker(agentDir, signal));
9928
9983
  }
9929
9984
  const agreed = agreedProtocol(BROKER_PROTOCOL, routing.protocol);
9930
9985
  if (agreed === undefined || agreed < VERIFIED_REGISTRATION_PROTOCOL) {
@@ -10608,10 +10663,11 @@ function piIntercomExtension(pi, testOverrides = {}) {
10608
10663
  if (connection.promise !== null)
10609
10664
  return connection.promise;
10610
10665
  const owner = connection;
10666
+ const { signal } = connectAbort;
10611
10667
  const promise = registerWithBrokerSuccessor(() => routeClientConnectGate.run(async () => {
10612
10668
  if (pendingStageRouteConnections.get(key) !== owner)
10613
10669
  throw new IntercomClientDisconnectedError;
10614
- await spawnBrokerIfNeeded(config.brokerCommand, config.brokerArgs, config.brokerStartupTimeoutMs);
10670
+ await startBrokerIfNeeded(signal);
10615
10671
  if (pendingStageRouteConnections.get(key) !== owner)
10616
10672
  throw new IntercomClientDisconnectedError;
10617
10673
  const routeReturnAddress = `${currentSessionId}:pending-stage-route:${key}`;
@@ -10816,6 +10872,7 @@ function piIntercomExtension(pi, testOverrides = {}) {
10816
10872
  const ownershipRecorded = Promise.withResolvers();
10817
10873
  const sessionIdAtStart = currentSessionId;
10818
10874
  const preferredSessionId = persistedIntercomSessionId(contextAtStart, sessionIdAtStart);
10875
+ const { signal } = connectAbort;
10819
10876
  const nextReconnectPromise = (async () => {
10820
10877
  let connectFailed = false;
10821
10878
  await ownershipRecorded.promise;
@@ -10833,8 +10890,8 @@ function piIntercomExtension(pi, testOverrides = {}) {
10833
10890
  attachClientHandlers(nextClient);
10834
10891
  try {
10835
10892
  await testOverrides.beforeConnectAttempt?.(reason);
10836
- await spawnBrokerIfNeeded(config.brokerCommand, config.brokerArgs, config.brokerStartupTimeoutMs);
10837
- const expectedRouting = await settleBrokerRouting(contextAtStart, generationAtStart);
10893
+ await startBrokerIfNeeded(signal);
10894
+ const expectedRouting = await settleBrokerRouting(contextAtStart, generationAtStart, signal);
10838
10895
  const childMetadata = currentChildOrchestratorMetadata();
10839
10896
  await nextClient.connect(buildRegistration(), childMetadata?.supervisor, supervisorAuthorizations.ownerToken, readSubagentMessageSource(runtimeContext?.subagentPolicy), resolveSessionHomeGroup(), expectedRouting);
10840
10897
  clientRegistrationGroup = resolveSessionHomeGroup();
@@ -10884,14 +10941,14 @@ function piIntercomExtension(pi, testOverrides = {}) {
10884
10941
  await nextClient.disconnect();
10885
10942
  } catch {}
10886
10943
  if (isOwnerMissingRefusal(error) && Date.now() < ownerWaitDeadline && !disposed && !shuttingDown && getLiveContext(contextAtStart, generationAtStart)) {
10887
- await delay4(liveRouteOwnerRetryDelayMs(ownerWait));
10944
+ await delay4(liveRouteOwnerRetryDelayMs(ownerWait), undefined, { signal });
10888
10945
  if (getLiveContext(contextAtStart, generationAtStart))
10889
10946
  continue;
10890
10947
  }
10891
10948
  if (isIntercomBrokerRetiring(error) || isIntercomRoutingChangedError(error)) {
10892
10949
  retiringDeadline ??= Date.now() + BROKER_RETIRING_RETRY_WINDOW_MS;
10893
10950
  if (Date.now() < retiringDeadline && !disposed && !shuttingDown && getLiveContext(contextAtStart, generationAtStart)) {
10894
- await delay4(brokerRetiringRetryDelayMs(retiringRetries++));
10951
+ await delay4(brokerRetiringRetryDelayMs(retiringRetries++), undefined, { signal });
10895
10952
  if (getLiveContext(contextAtStart, generationAtStart))
10896
10953
  continue;
10897
10954
  }
@@ -11111,7 +11168,13 @@ function piIntercomExtension(pi, testOverrides = {}) {
11111
11168
  reconnectAttempt = 0;
11112
11169
  },
11113
11170
  clearReconnectTimer,
11171
+ abortBrokerStarts: async () => {
11172
+ connectAbort.abort(new IntercomRuntimeInactiveError);
11173
+ await Promise.all(brokerStarts);
11174
+ },
11114
11175
  setRuntimeContext: (value) => {
11176
+ if (value !== null && connectAbort.signal.aborted)
11177
+ connectAbort = new AbortController;
11115
11178
  brokerRouting = null;
11116
11179
  homeRoutedAcrossMachines = null;
11117
11180
  defaultGroupWarned = false;