@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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,45 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.79-alpha.1] - 2026-11-11
6
+
7
+ Resuming long sessions is faster and keeps your tools and subagents, long workflow runs stay responsive, and interrupting a response is calmer.
8
+
9
+ - **Faster, more faithful resume.** Resume shows its slow steps before the TUI appears, keeps the tools a session last ran with, brings back `subagent`, `workflow`, `todo` and MCP tools that were missing for a turn, stays in your own checkout instead of a snapshot worktree, and reaches a usable prompt sooner on long histories. Background subagents survive a reboot, and one that cannot be restored is reported with a ready call to relaunch it ([#4660](https://github.com/bastani-inc/atomic/issues/4660), [#4664](https://github.com/bastani-inc/atomic/pull/4664)).
10
+ - **Long workflow runs stay light.** The graph overlay and progress widget no longer slow down as stages finish, finished stages you reopened leave memory again once their chat closes, and released stages share one Intercom connection per session ([#4642](https://github.com/bastani-inc/atomic/issues/4642), [#4659](https://github.com/bastani-inc/atomic/pull/4659)).
11
+ - **Calmer interrupts and Ctrl+C.** Ctrl+C clears typed text before stopping work and exits only on a second press from an empty, idle editor, and an interrupted response ends with a muted `Interrupted by user` line instead of a red error ([#4670](https://github.com/bastani-inc/atomic/pull/4670)).
12
+ - **Simpler `/tasks` details.** The "Foreground wait" action, which never changed how a task ran, is gone ([#4662](https://github.com/bastani-inc/atomic/issues/4662), [#4665](https://github.com/bastani-inc/atomic/pull/4665)).
13
+ - **Upstream fixes.** MCP tools loaded by `tool_search` survive resume and `/reload`, `/export` links are clickable, the standalone binary resolves extension dependencies declared in `main` or `exports`, llama.cpp defaults to port 9931, and Anthropic message threads follow the `api.anthropic.com` endpoint ([#4663](https://github.com/bastani-inc/atomic/pull/4663)).
14
+
15
+ ### Added
16
+
17
+ - Resuming lists its slow steps on the terminal before the TUI appears (`Loading the session history (0.6 s)…`, `Checking 6 checkouts against the session's snapshots…`, `Restoring … from snapshot …`), a history of 100,000 entries or more before it is read, and any other step that blocks the terminal as soon as it ends; quick resumes stay silent ([#4660](https://github.com/bastani-inc/atomic/issues/4660))
18
+ - Interactive startup notes `Tools this session was using aren't available right now: <names>` when a tool the session was using, or one its tool selection names, is not registered once startup finishes, and `/tools` lists such tools under **Missing**; tools left out with `--tools`, `--no-tools` or `--no-extensions` are never listed ([#4660](https://github.com/bastani-inc/atomic/issues/4660))
19
+
20
+ ### Changed
21
+
22
+ - Workflow activity frames from `ctx.observeWorkflowActivity` and `session.workflows.observe`, and `workflow_activity_changed` events, share their root graph's nodes as deep-frozen objects instead of cloning every node for every observer, so a change to a long run no longer costs a copy of its whole graph. Each frame still has its own root, graph and `nodes` array; copy a node before changing it ([#4642](https://github.com/bastani-inc/atomic/issues/4642))
23
+ - Ctrl+C clears the editor first when it has text, even while a response is streaming; with an empty editor it stops running work at once, as Escape does. On an empty, idle editor the first press shows "Press Ctrl+C again to exit" and a second press within 0.8 s exits. Clearing text or stopping work never counts toward exiting, so a quick second press after clearing no longer quits Atomic ([#4670](https://github.com/bastani-inc/atomic/pull/4670))
24
+ - A response you interrupt with Escape or Ctrl+C ends with a muted `Interrupted by user` line instead of a red provider message such as "This operation was aborted" or "Aborted after 2 retry attempts" ([#4670](https://github.com/bastani-inc/atomic/pull/4670))
25
+
26
+ ### Fixed
27
+
28
+ - Fixed MCP tools loaded by `tool_search` being dropped on resume and `/reload` when an extension deactivates only its own tool at `session_start` (upstream [#12054](https://github.com/earendil-works/pi/pull/12054))
29
+ - Fixed `/export` HTML showing raw terminal hyperlink escape codes around links in custom tool output; links are now clickable, other terminal escape sequences are dropped, and clicking a link no longer expands or collapses the output (upstream [#12052](https://github.com/earendil-works/pi/pull/12052))
30
+ - Fixed the standalone binary failing to resolve extension npm dependencies whose entry point is declared in `package.json` `main` or `exports`, including imports made from inside other dependencies (upstream [#12046](https://github.com/earendil-works/pi/pull/12046))
31
+ - Fixed the llama.cpp provider defaulting to port 8080 while `llama serve` listens on 9931; the default server URL is now `http://127.0.0.1:9931`, and the llama.cpp guide starts the router, including the NVIDIA RTX recipe router, with `llama serve` on that port (upstream [#12001](https://github.com/earendil-works/pi/pull/12001), [#12004](https://github.com/earendil-works/pi/pull/12004))
32
+ - Fixed Anthropic message threads staying off for custom providers whose `baseUrl` is on `api.anthropic.com`; the default now follows the endpoint, not the provider ID (upstream [#11987](https://github.com/earendil-works/pi/issues/11987))
33
+ - Fixed a later plain resume bringing back tools an earlier run left out with `--tools`, `--no-tools`, `--exclude-tools` or a `-name` modifier, so resumed sessions keep the tools they last ran with, as in upstream pi ([#4660](https://github.com/bastani-inc/atomic/issues/4660))
34
+ - Fixed a resumed session losing `subagent`, `workflow`, `todo` and MCP tools for good after one turn ran while they were not registered, for example while their extensions were still loading or had failed to load: such tools now come back on resume like in a new session, while a tool an extension or SDK caller turned off with `setActiveTools` stays off ([#4660](https://github.com/bastani-inc/atomic/issues/4660))
35
+ - Fixed resume moving a session into a snapshot worktree under `~/.atomic/agent/worktree-snapshots/worktrees/` when its own project checkout had only changed since the snapshot, for example after work was merged: the session continues in its checkout without a notice, and a session an earlier resume moved into such a worktree returns to its checkout when it did no work there since ([#4660](https://github.com/bastani-inc/atomic/issues/4660))
36
+ - Fixed resuming a long session walking its whole history again and again: the session's branch, worktree restores, latest snapshots and name are kept current as entries are added, and recorded checkouts are compared with their snapshots once each, several at a time. On a 200,000-entry session with six checkouts, time to a usable prompt dropped from about 10.4 s to about 6.3 s; about 2 s of that is the session no longer being moved into a restored worktree, and about 4 s remains in full-history parses that this change does not remove ([#4660](https://github.com/bastani-inc/atomic/issues/4660))
37
+ - Fixed a startup step that fails, such as a tool status that cannot be read or extension loading that did not finish, holding back session recovery: the session keeps its tools and working directory and interrupted work is still recovered ([#4660](https://github.com/bastani-inc/atomic/issues/4660))
38
+
39
+ ### Removed
40
+
41
+ - Removed the "Foreground wait" action and the `app.tasks.foreground` keybinding from the `/tasks` detail page. It only showed a passing `yielded` or `settled` line and briefly dropped the task from the running-tasks count; it never changed how the task ran or what the agent was told ([#4662](https://github.com/bastani-inc/atomic/issues/4662))
42
+ - Removed the "Loading remote component…" line that briefly appeared while an interactive component drew its first frame ([#4670](https://github.com/bastani-inc/atomic/pull/4670))
43
+
5
44
  ## [0.9.78] - 2026-11-11
6
45
 
7
46
  GitHub Copilot users get Gemini 4 Carbon and Claude Fable 5.2, and automatic model routing can rank Gemini 4 Carbon.
@@ -4,6 +4,18 @@ All notable changes to the `pi-intercom` extension will be documented in this fi
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.9.79-alpha.1] - 2026-11-11
8
+
9
+ ### Added
10
+
11
+ - Added hosted sessions: `IntercomClient.hostSessions` lists and routes many lightweight sessions over one broker connection, with typed `HostedSessionRequestError` and `NotHostedSessionError` refusals. The broker now speaks Intercom protocol 1 to 3, so the next session of this version replaces an older running broker ([#4642](https://github.com/bastani-inc/atomic/issues/4642))
12
+ - Added the typed `StageRecipientReleasedError` (`recipient_stage_released`) for a send to a released workflow stage whose hosted peer is gone: it names why and points to the stage's `workflow:` target instead of answering `Session not found` ([#4642](https://github.com/bastani-inc/atomic/issues/4642))
13
+ - Added the typed, retryable `IntercomHostedSessionTimeoutError` (`hosted_session_timeout`) for a hosting request the broker never answers ([#4642](https://github.com/bastani-inc/atomic/issues/4642))
14
+
15
+ ### Fixed
16
+
17
+ - Fixed each finished workflow stage that was released from memory keeping its own broker connection open for the rest of the session: released stages now share one connection per session, keeping their names, `closed · reply: post-mortem only` listing, post-mortem asks and plain-send relay ([#4642](https://github.com/bastani-inc/atomic/issues/4642))
18
+
7
19
  ## [0.9.77] - 2026-11-11
8
20
 
9
21
  Messages to ended, released or replaced sessions arrive or fail with a reason.
@@ -9,6 +9,7 @@ import { dirname } from "path";
9
9
  import { randomUUID } from "crypto";
10
10
  import { createMessageReader, type JsonWireValue } from "./framing.js";
11
11
  import {
12
+ clientHostsSessions,
12
13
  discardHeldWrites,
13
14
  flushHeldWrites,
14
15
  type HeldWrite,
@@ -55,6 +56,8 @@ import type {
55
56
  WorkflowRunParentAnnouncement,
56
57
  PendingStageRouteRefusalCode,
57
58
  ReleasedChildRefusal,
59
+ HostedSessionAssignment,
60
+ HostedSessionRefusal,
58
61
  } from "../types.js";
59
62
  import {
60
63
  formatWorkflowStageTarget,
@@ -62,11 +65,12 @@ import {
62
65
  withWorkflowStageTargetFinalSegment,
63
66
  } from "../workflow-stage-target.js";
64
67
  import { DELIVERED_MESSAGE_MAX_ENTRIES, DeliveredMessageCache } from "./delivered-message-cache.js";
65
- import { isMessage } from "./client-message-validation.js";
68
+ import { isMessage, isSessionRegistration } from "./client-message-validation.js";
66
69
  import { buildMessageSendSignature } from "./send-signature.js";
67
70
  import {
68
71
  deliveryTargetIdentity,
69
72
  handleBrokerSend,
73
+ messageFrameFor,
70
74
  type BrokerConnectedSession,
71
75
  type PendingStageRoute,
72
76
  type ReleasedAskerReplyRouter,
@@ -100,6 +104,8 @@ import { type HeldSend, RestoringRecipients, type RestoringRecipientWake } from
100
104
  import { DepartedChildren, type HeldSendRefusal, validateEndedChildrenFrame } from "./departed-children.js";
101
105
  import { WorkflowStageAliases } from "./workflow-stage-aliases.js";
102
106
  import { type IntercomRecipientGoneError, serializeIntercomRecipientGoneError } from "./recipient-gone-errors.js";
107
+ import { NotHostedSessionError, serializeIntercomHostedSessionError } from "./hosted-session-errors.js";
108
+ import { type ParsedHostedSession, validateHostSessionsFrame, validateUnhostSessionsFrame } from "./hosted-sessions.js";
103
109
  import { ReleasedAskerReplies, type ReleasedAskerReplyRoute } from "./released-asker-replies.js";
104
110
  import { releasedAskerReplyRefusal } from "./released-asker-remote-replies.js";
105
111
  import { hasGroup, normalizeGroup, normalizeGroups, workflowInvocationRefusalFor } from "../group.js";
@@ -235,42 +241,6 @@ interface PendingReleasedReplyAck {
235
241
  readonly route: ReleasedAskerReplyRoute;
236
242
  }
237
243
 
238
- function isSessionRegistration(value: unknown): value is Omit<SessionInfo, "id"> {
239
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
240
- return false;
241
- }
242
-
243
- const session = value as Record<string, unknown>;
244
-
245
- if (
246
- typeof session.cwd !== "string"
247
- || typeof session.model !== "string"
248
- || typeof session.pid !== "number"
249
- || typeof session.startedAt !== "number"
250
- || typeof session.lastActivity !== "number"
251
- ) {
252
- return false;
253
- }
254
-
255
- if (session.name !== undefined && typeof session.name !== "string") {
256
- return false;
257
- }
258
-
259
- if (session.group !== undefined && typeof session.group !== "string") {
260
- return false;
261
- }
262
-
263
- if (session.replyCapability !== undefined && session.replyCapability !== "live" && session.replyCapability !== "terminal") return false;
264
- if (session.recipientPurpose !== undefined &&
265
- session.recipientPurpose !== "agent" && session.recipientPurpose !== "control") {
266
- return false;
267
- }
268
- if (session.groups !== undefined &&
269
- (!Array.isArray(session.groups) || !session.groups.every((group) => typeof group === "string"))) {
270
- return false;
271
- }
272
- return session.status === undefined || typeof session.status === "string";
273
- }
274
244
  function isSupervisorRegistration(value: unknown): value is SupervisorRegistration {
275
245
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
276
246
  const registration = value as Record<string, unknown>;
@@ -380,6 +350,8 @@ function isWorkflowPossibleStageAnnouncements(
380
350
 
381
351
  class IntercomBroker {
382
352
  private sessions = new Map<string, ConnectedSession>();
353
+ /** #4642: the sessions each connection hosts, by the hosting session's id. */
354
+ private hostedSessions = new Map<string, Set<string>>();
383
355
  private unclassifiedConnections = new Map<net.Socket, number>();
384
356
  private server: net.Server;
385
357
  private readonly instanceId = randomUUID();
@@ -877,6 +849,75 @@ class IntercomBroker {
877
849
  return entries;
878
850
  }
879
851
 
852
+ /** The preconditions of a live workflow-stage route a registrant may hold, checked before any alias is taken. */
853
+ private liveWorkflowStageRouteRefusal(
854
+ registrant: ConnectedSession | undefined,
855
+ runId: string,
856
+ stageKeys: readonly string[],
857
+ capability: string,
858
+ ): LiveWorkflowStageRouteRefusalCode | undefined {
859
+ if (!stageKeys.every((stageKey) => !stageKey.includes("/") && !stageKey.includes("*"))) return "invalid_stage_key";
860
+ const ownerRegistration = this.pendingStageRoutes.get(runId);
861
+ if (ownerRegistration === undefined) return "owner_missing";
862
+ if (registrant === undefined || !isAgentRecipient(registrant.info)) return "registrant_not_agent";
863
+ if (ownerRegistration.capability !== capability) return "capability_mismatch";
864
+ const registrantGroup = registrant.registrationGroup ?? registrant.info.group ?? "default";
865
+ if (!invocationOwnsGroup(ownerRegistration.group, registrantGroup)) return "group_mismatch";
866
+ return undefined;
867
+ }
868
+
869
+ /** #4642: a hosted session takes its live workflow-stage aliases as a connected stage would; a refusal keeps it hosted. */
870
+ private registerHostedLiveRoute(
871
+ hosted: ConnectedSession,
872
+ route: NonNullable<ParsedHostedSession["liveRoute"]>,
873
+ ): LiveWorkflowStageRouteRefusalCode | undefined {
874
+ return (
875
+ this.liveWorkflowStageRouteRefusal(hosted, route.runId, route.stageKeys, route.capability) ??
876
+ this.registerLiveWorkflowStageRoute(hosted.info.id, randomUUID(), route.runId, route.stageKeys, route.capability)
877
+ );
878
+ }
879
+
880
+ /** #4642: register one session hosted by `hostId`, listed and addressed like a connected one, on the host's socket. */
881
+ private hostSession(hostId: string, socket: net.Socket, item: ParsedHostedSession): ConnectedSession {
882
+ const id = randomUUID();
883
+ const initialGroups = normalizeGroups(item.session.groups, item.session.group);
884
+ const legacyGroup = normalizeGroup(item.session.group ?? initialGroups.values().next().value);
885
+ const info: SessionInfo = { ...item.session, id };
886
+ setSessionGroups(info, initialGroups, legacyGroup);
887
+ const name = info.name?.trim();
888
+ const hosted: ConnectedSession = {
889
+ socket,
890
+ info,
891
+ registrationGroup: legacyGroup,
892
+ ...(name ? { registrationName: name } : {}),
893
+ ...(item.returnAddress === undefined ? {} : { registrationReturnAddress: item.returnAddress }),
894
+ hostedBy: hostId,
895
+ };
896
+ this.sessions.set(id, hosted);
897
+ let hosts = this.hostedSessions.get(hostId);
898
+ if (hosts === undefined) {
899
+ hosts = new Set();
900
+ this.hostedSessions.set(hostId, hosts);
901
+ }
902
+ hosts.add(id);
903
+ this.broadcastToMemberships({ type: "session_joined", session: info }, sessionGroups(info), id);
904
+ return hosted;
905
+ }
906
+
907
+ /** #4642: a send as a session this connection does not host is refused with `NotHostedSessionError`. */
908
+ private refuseHostedSender(socket: net.Socket, clientMessage: SendClientMessage, hostedSender: string): void {
909
+ const message = clientMessage.message;
910
+ const error = new NotHostedSessionError({ sessionId: hostedSender });
911
+ writeMessageIfOpen(socket, {
912
+ type: "delivery_failed",
913
+ messageId: isMessage(message) ? message.id : "unknown",
914
+ ...(typeof clientMessage.attemptId === "string" ? { attemptId: clientMessage.attemptId } : {}),
915
+ reason: error.message,
916
+ reasonCode: error.code,
917
+ error: serializeIntercomHostedSessionError(error),
918
+ });
919
+ }
920
+
880
921
  private acknowledgeLiveWorkflowStageRoute(requestId: string): void {
881
922
  const activation = this.liveWorkflowStageRouteActivations.get(requestId);
882
923
  if (activation === undefined || activation.pendingRequestIds.size > 0) return;
@@ -1042,7 +1083,15 @@ class IntercomBroker {
1042
1083
  return undefined;
1043
1084
  }
1044
1085
  const reachable = hasGroup(sessionGroups(sender.info), stage.group) || this.canControlWorkflowInvocation(sender, route.group);
1045
- return reachable ? stage.target : undefined;
1086
+ if (!reachable) return undefined;
1087
+ // #4642: a released stage whose hosted peer is gone and that no live session answers for is refused with why
1088
+ // by the send itself, not forwarded to a run that has nothing to queue for it.
1089
+ const live = this.liveWorkflowStageRoutes.get(stage.target);
1090
+ const liveSession = live === undefined ? undefined : this.sessions.get(live.sessionId);
1091
+ if (liveSession === undefined && this.departedChildren.isReleasedStage(alias, { id: sender.info.id, info: sender.info })) {
1092
+ return undefined;
1093
+ }
1094
+ return stage.target;
1046
1095
  };
1047
1096
 
1048
1097
  private routePendingStage = (route: PendingStageRoute): boolean => {
@@ -1328,7 +1377,7 @@ class IntercomBroker {
1328
1377
  }
1329
1378
  if (pending.message.expectsReply === true && pending.resolveReplyTarget === true && pending.attemptId !== undefined)
1330
1379
  writeMessageIfOpen(pending.senderSocket, { type: "question_target", messageId: pending.messageId, attemptId: pending.attemptId, sessionId: target.info.id });
1331
- const frame: BrokerMessage = { type: "message", from: pending.sender, message: pending.message };
1380
+ const frame: BrokerMessage = messageFrameFor(target, pending.sender, pending.message);
1332
1381
  const signature = pending.signature;
1333
1382
  const finish = (recipient: ConnectedSession, sender: ReceiptSender | undefined): void => {
1334
1383
  const notify = (message: BrokerMessage): void => {
@@ -1435,7 +1484,7 @@ class IntercomBroker {
1435
1484
  // The write itself is the writability check, so a stage that dropped between
1436
1485
  // the owner's answer and this loop is not reported as delivered and a retried
1437
1486
  // send re-forwards to it.
1438
- if (!writeMessageIfOpen(targetSession.socket, { type: "message", from: pending.sender, message: pending.message }))
1487
+ if (!writeMessageIfOpen(targetSession.socket, messageFrameFor(targetSession, pending.sender, pending.message)))
1439
1488
  continue;
1440
1489
  delivered.push(target);
1441
1490
  }
@@ -2032,6 +2081,68 @@ class IntercomBroker {
2032
2081
  break;
2033
2082
  }
2034
2083
 
2084
+ case "host_sessions": {
2085
+ const host = this.sessions.get(currentId);
2086
+ if (
2087
+ host === undefined ||
2088
+ host.hostedBy !== undefined ||
2089
+ typeof clientMessage.requestId !== "string" ||
2090
+ !clientHostsSessions(socket)
2091
+ ) {
2092
+ throw new Error("Invalid host_sessions message");
2093
+ }
2094
+ const requestId = clientMessage.requestId;
2095
+ const validation = validateHostSessionsFrame(clientMessage.sessions);
2096
+ if (!validation.ok) {
2097
+ writeMessageIfOpen(socket, { type: "hosted_sessions_ack", requestId, refusal: validation.refusal });
2098
+ break;
2099
+ }
2100
+ const assignments: HostedSessionAssignment[] = [];
2101
+ const presences: Promise<void>[] = [];
2102
+ // #4639: a host back after its connection closed takes over the departures it kept; hosting a name again ends its.
2103
+ this.adoptOrphans(currentId, host);
2104
+ for (const item of validation.sessions) {
2105
+ const hosted = this.hostSession(currentId, socket, item);
2106
+ if (hosted.registrationName !== undefined)
2107
+ this.dispatchHeldSends(this.departedChildren.supersede(currentId, hosted.registrationName));
2108
+ const presence = this.multiNode?.sessionRegistered(hosted);
2109
+ if (presence !== undefined) presences.push(presence);
2110
+ const liveRouteRefusal = item.liveRoute === undefined ? undefined : this.registerHostedLiveRoute(hosted, item.liveRoute);
2111
+ assignments.push({
2112
+ key: item.key,
2113
+ sessionId: hosted.info.id,
2114
+ ...(liveRouteRefusal === undefined ? {} : { liveRouteRefusal }),
2115
+ });
2116
+ }
2117
+ // Multi-node: the answer waits until other brokers can resolve the hosted sessions, as `registered` does.
2118
+ const answer = (): void => {
2119
+ writeMessageIfOpen(socket, { type: "hosted_sessions_ack", requestId, sessions: assignments });
2120
+ };
2121
+ if (presences.length === 0) answer();
2122
+ else void Promise.all(presences).then(answer);
2123
+ break;
2124
+ }
2125
+
2126
+ case "unhost_sessions": {
2127
+ if (typeof clientMessage.requestId !== "string" || !this.sessions.has(currentId)) {
2128
+ throw new Error("Invalid unhost_sessions message");
2129
+ }
2130
+ const validation = validateUnhostSessionsFrame(clientMessage.sessionIds);
2131
+ const hosted = this.hostedSessions.get(currentId);
2132
+ const refusal: HostedSessionRefusal | undefined = validation.ok
2133
+ ? validation.sessionIds
2134
+ .filter((sessionId) => hosted?.has(sessionId) !== true)
2135
+ .map((sessionId) => ({ code: "not_hosted_by_connection" as const, sessionId }))[0]
2136
+ : validation.refusal;
2137
+ if (!validation.ok || refusal !== undefined) {
2138
+ writeMessageIfOpen(socket, { type: "hosted_sessions_ack", requestId: clientMessage.requestId, refusal });
2139
+ break;
2140
+ }
2141
+ for (const sessionId of validation.sessionIds) this.disconnectSession(sessionId);
2142
+ writeMessageIfOpen(socket, { type: "hosted_sessions_ack", requestId: clientMessage.requestId });
2143
+ break;
2144
+ }
2145
+
2035
2146
  case "reserve_released_children": {
2036
2147
  const owner = this.sessions.get(currentId);
2037
2148
  if (owner === undefined || typeof clientMessage.requestId !== "string") {
@@ -2341,35 +2452,18 @@ class IntercomBroker {
2341
2452
  });
2342
2453
  this.endRefusedConnection(socket, currentId, setId);
2343
2454
  };
2344
- if (!clientMessage.stageKeys.every((stageKey) => !stageKey.includes("/") && !stageKey.includes("*"))) {
2345
- // A stage name containing "/" or "*" cannot be a canonical path segment, but throwing
2346
- // here reaches the framing reader's onError and destroys the stage session's whole
2347
- // broker connection. Refuse orderly like every neighbouring rejection; host clients
2348
- // filter such name keys and register the stage-id key instead.
2349
- refuse("invalid_stage_key");
2350
- return;
2351
- }
2352
- const ownerRegistration = this.pendingStageRoutes.get(clientMessage.runId);
2353
- const registeringSession = this.sessions.get(currentId);
2354
- if (ownerRegistration === undefined) {
2355
- refuse("owner_missing");
2356
- return;
2357
- }
2358
- if (registeringSession === undefined || !isAgentRecipient(registeringSession.info)) {
2359
- refuse("registrant_not_agent");
2360
- return;
2361
- }
2362
- if (ownerRegistration.capability !== clientMessage.capability) {
2363
- refuse("capability_mismatch");
2364
- return;
2365
- }
2366
- if (
2367
- !invocationOwnsGroup(
2368
- ownerRegistration.group,
2369
- registeringSession.registrationGroup ?? registeringSession.info.group ?? "default",
2370
- )
2371
- ) {
2372
- refuse("group_mismatch");
2455
+ // A stage name containing "/" or "*" cannot be a canonical path segment, but throwing
2456
+ // here reaches the framing reader's onError and destroys the stage session's whole
2457
+ // broker connection. Refuse orderly like every neighbouring rejection; host clients
2458
+ // filter such name keys and register the stage-id key instead.
2459
+ const precondition = this.liveWorkflowStageRouteRefusal(
2460
+ this.sessions.get(currentId),
2461
+ clientMessage.runId,
2462
+ clientMessage.stageKeys,
2463
+ clientMessage.capability,
2464
+ );
2465
+ if (precondition !== undefined) {
2466
+ refuse(precondition);
2373
2467
  return;
2374
2468
  }
2375
2469
  const refusal = this.registerLiveWorkflowStageRoute(
@@ -2421,7 +2515,17 @@ class IntercomBroker {
2421
2515
 
2422
2516
  case "send":
2423
2517
  case "supervisor_send": {
2424
- this.dispatchSend(socket, clientMessage, currentId);
2518
+ const hostedSender = clientMessage.hostedSender;
2519
+ if (hostedSender === undefined) {
2520
+ this.dispatchSend(socket, clientMessage, currentId);
2521
+ break;
2522
+ }
2523
+ if (typeof hostedSender !== "string") throw new Error("Invalid hostedSender");
2524
+ if (this.hostedSessions.get(currentId)?.has(hostedSender) !== true) {
2525
+ this.refuseHostedSender(socket, clientMessage, hostedSender);
2526
+ break;
2527
+ }
2528
+ this.dispatchSend(socket, clientMessage, hostedSender);
2425
2529
  break;
2426
2530
  }
2427
2531
 
@@ -2799,12 +2903,15 @@ class IntercomBroker {
2799
2903
  }
2800
2904
 
2801
2905
  private failHeldSendWith(held: HeldSend, error: IntercomRecipientGoneError): void {
2906
+ // #4642: a client that registered below protocol 3 validates `recipientError` against the codes it knows and ends
2907
+ // the connection over one it does not; it gets the plain reason, which already says what the typed error does.
2908
+ const typed = error.code !== "recipient_stage_released" || clientHostsSessions(held.socket);
2802
2909
  writeMessageIfOpen(held.socket, {
2803
2910
  type: "delivery_failed",
2804
2911
  messageId: held.messageId,
2805
2912
  ...(held.attemptId === undefined ? {} : { attemptId: held.attemptId }),
2806
2913
  reason: error.message,
2807
- recipientError: serializeIntercomRecipientGoneError(error),
2914
+ ...(typed ? { recipientError: serializeIntercomRecipientGoneError(error) } : {}),
2808
2915
  });
2809
2916
  }
2810
2917
 
@@ -2930,6 +3037,22 @@ class IntercomBroker {
2930
3037
  private disconnectSession(sessionId: string): void {
2931
3038
  const departed = this.sessions.get(sessionId);
2932
3039
  if (!departed) return;
3040
+ // #4642: the sessions a connection hosts leave with it, and a hosted session leaves its host's index.
3041
+ for (const hostedId of [...(this.hostedSessions.get(sessionId) ?? [])]) this.disconnectSession(hostedId);
3042
+ this.hostedSessions.delete(sessionId);
3043
+ if (departed.hostedBy !== undefined) {
3044
+ this.hostedSessions.get(departed.hostedBy)?.delete(sessionId);
3045
+ // A released stage whose peer left answers with why, and where to send instead, rather than `Session not found`.
3046
+ if (departed.registrationName !== undefined) {
3047
+ const marked = this.departedChildren.markStageReleased(departed.hostedBy, {
3048
+ childName: departed.registrationName,
3049
+ group: normalizeGroup(departed.registrationGroup),
3050
+ aliases: [sessionId],
3051
+ });
3052
+ this.refuseHeldSends(marked.refused);
3053
+ this.dispatchHeldSends(marked.evicted);
3054
+ }
3055
+ }
2933
3056
 
2934
3057
  this.restoringRecipients.dropSender(sessionId);
2935
3058
  this.departedChildren.dropSender(sessionId);
@@ -2952,7 +3075,7 @@ class IntercomBroker {
2952
3075
  }
2953
3076
  this.releasedAskerReplies.dropOwner(sessionId);
2954
3077
  for (const [messageId, pending] of [...this.releasedReplyAcks]) {
2955
- if (pending.ownerSessionId === sessionId || pending.socket === departed.socket) {
3078
+ if (pending.ownerSessionId === sessionId || (departed.hostedBy === undefined && pending.socket === departed.socket)) {
2956
3079
  this.settleReleasedReply(messageId, "uncertain");
2957
3080
  }
2958
3081
  }
@@ -3040,6 +3163,8 @@ class IntercomBroker {
3040
3163
  /** Deliver a broadcast once to each session represented in any given group. */
3041
3164
  private broadcastToMemberships(msg: BrokerMessage, groups: ReadonlySet<string>, exclude?: string): void {
3042
3165
  for (const [id, session] of this.sessions) {
3166
+ // #4642: a hosted session shares its host's socket and needs no copy of its own.
3167
+ if (session.hostedBy !== undefined) continue;
3043
3168
  if (id !== exclude && [...groups].some((group) => hasGroup(sessionGroups(session.info), group))) {
3044
3169
  writeMessageIfOpen(session.socket, msg);
3045
3170
  }
@@ -3082,6 +3207,7 @@ class IntercomBroker {
3082
3207
  session.socket.end();
3083
3208
  }
3084
3209
  this.sessions.clear();
3210
+ this.hostedSessions.clear();
3085
3211
  this.pendingStageRoutes.clear();
3086
3212
  this.pendingStageAcknowledgments.clear();
3087
3213
  this.liveWorkflowStageRoutes.clear();
@@ -52,3 +52,41 @@ export function isSessionInfo(value: unknown): value is SessionInfo {
52
52
  if (session.group !== undefined && typeof session.group !== "string") return false;
53
53
  return session.status === undefined || typeof session.status === "string";
54
54
  }
55
+
56
+ /** A `register` frame's session: everything but the id the broker assigns. */
57
+ export function isSessionRegistration(value: unknown): value is Omit<SessionInfo, "id"> {
58
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
59
+ return false;
60
+ }
61
+
62
+ const session = value as Record<string, unknown>;
63
+
64
+ if (
65
+ typeof session.cwd !== "string"
66
+ || typeof session.model !== "string"
67
+ || typeof session.pid !== "number"
68
+ || typeof session.startedAt !== "number"
69
+ || typeof session.lastActivity !== "number"
70
+ ) {
71
+ return false;
72
+ }
73
+
74
+ if (session.name !== undefined && typeof session.name !== "string") {
75
+ return false;
76
+ }
77
+
78
+ if (session.group !== undefined && typeof session.group !== "string") {
79
+ return false;
80
+ }
81
+
82
+ if (session.replyCapability !== undefined && session.replyCapability !== "live" && session.replyCapability !== "terminal") return false;
83
+ if (session.recipientPurpose !== undefined &&
84
+ session.recipientPurpose !== "agent" && session.recipientPurpose !== "control") {
85
+ return false;
86
+ }
87
+ if (session.groups !== undefined &&
88
+ (!Array.isArray(session.groups) || !session.groups.every((group) => typeof group === "string"))) {
89
+ return false;
90
+ }
91
+ return session.status === undefined || typeof session.status === "string";
92
+ }