@chroxy/server 0.11.0 → 0.11.10

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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -1,7 +1,12 @@
1
+ import { ServerSessionStatusSchema, ServerActivityDeltaSchema } from '@chroxy/protocol'
1
2
  import { createLogger } from './logger.js'
2
- import { getDefaultModelId, getRegistryForProvider } from './models.js'
3
+ import { getRegistryForProvider, resolveRosterProvider } from './models.js'
3
4
  import { settlePush } from './push.js'
4
5
  import { terminalMirrorRecipient } from './handler-utils.js'
6
+ import { isBoundClient } from './environments/authority.js'
7
+ import { broadcastRosterPerRecipient } from './roster-broadcast.js'
8
+ import { getProviderRuntimeInfo } from './providers.js'
9
+ import { MODEL_UNSUPPORTED_CODE } from './codex-model-rejections.js'
5
10
 
6
11
  const log = createLogger('ws-forwarding')
7
12
 
@@ -142,7 +147,81 @@ function terminalSubscriberFilter(sessionId) {
142
147
 
143
148
  /** Multi-session forwarding via normalizer */
144
149
  function setupSessionForwarding(normalizer, ctx) {
145
- const { sessionManager, devPreview, checkpointManager, broadcast, broadcastToSession } = ctx
150
+ const { sessionManager, devPreview, checkpointManager, broadcast, broadcastToSession, defaultProvider = null } = ctx
151
+
152
+ // #8497: sessions whose turn a `result` ended in the CURRENT synchronous turn
153
+ // end. A provider that finishes a requested Stop with a `result` and then a
154
+ // `stopped` (claude-cli) emits both back to back in one call stack, so the
155
+ // `stopped` that follows must not announce idle a second time. Cleared on a
156
+ // microtask rather than on the next stream_start: a Stop pressed before the
157
+ // next turn produced any output forwards nothing in between, and a flag that
158
+ // outlived the tick would swallow that turn's idle (the stuck-busy bug this
159
+ // exists to fix). The failure mode of the tick scope is a repeated idle, which
160
+ // is idempotent on every client; the failure mode of a longer scope is a
161
+ // session that stays busy forever.
162
+ const idledByResultThisTick = new Set()
163
+
164
+ // #8502: sessions whose turn-end `session_list` is already queued for this
165
+ // synchronous turn end. A `result` and a `stopped` that coincide (claude-sdk's
166
+ // quiet acknowledgement of a Stop, claude-cli's close handler) share ONE list.
167
+ const turnEndListQueued = new Set()
168
+
169
+ // The `session_list` a turn end refreshes, built AFTER the provider's
170
+ // synchronous teardown rather than inside the emit. claude-sdk, ACP and Codex
171
+ // app-server emit `result` / `stopped` and only then clear `_isBusy`
172
+ // (_clearMessageState), so a list built inside the emit publishes the finished
173
+ // session as busy. `agent_idle` reaches viewers only, and the clients re-derive
174
+ // `isIdle` from this list's rows, so a client that is not viewing the session
175
+ // would end the turn busy. A microtask runs once the emitting call stack
176
+ // unwinds and before any later await; the providers clear busy synchronously in
177
+ // that same stack (checked per provider in #8502).
178
+ //
179
+ // `afterBusyCleared` marks the list the provider itself asked for once its busy
180
+ // window really ended (`busy_cleared`). Every other trigger is skipped while the
181
+ // session reports `busyClearedOwed`: its busy flag outlives the `result` (the
182
+ // jsonl-subprocess family clears it in the child's close handler, a later
183
+ // event-loop turn), so a list built now would publish the finished session as
184
+ // busy AFTER the viewer's agent_idle, and the clients, which re-derive isIdle
185
+ // from the list row even for the active session, would flip back to Working
186
+ // until the child exits. The session states this itself; it is not guessed
187
+ // from `isRunning`, which is also true for a restarted queued turn and for
188
+ // background shells, where the list is correct and wanted.
189
+ const queueTurnEndSessionList = (sessionId, { afterBusyCleared = false } = {}) => {
190
+ if (turnEndListQueued.has(sessionId)) return
191
+ turnEndListQueued.add(sessionId)
192
+ queueMicrotask(() => {
193
+ turnEndListQueued.delete(sessionId)
194
+ if (!afterBusyCleared && sessionManager.getSession?.(sessionId)?.session?.busyClearedOwed === true) return
195
+ try {
196
+ executeSideEffects([{ type: 'session_list' }], sessionId, ctx)
197
+ } catch (err) {
198
+ log.error(`deferred session_list after turn end threw for session ${sessionId}: ${err?.message || err}`)
199
+ }
200
+ })
201
+ }
202
+
203
+ // #8873: the `session_list` a provider start's outcome refreshes
204
+ // (`session_restore_failed`, `session_start_settled`), coalesced so a burst of
205
+ // outcomes costs one `listSessions()` and one send per client rather than one
206
+ // each. Restored sessions start together at boot, so their failures (and the
207
+ // #8876 deadline timers) arrive together. They arrive as separate timer or I/O
208
+ // callbacks, and Node drains microtasks between callbacks, so a microtask
209
+ // would coalesce only outcomes emitted in one call stack. `setImmediate` runs
210
+ // once per event-loop turn, after every callback of that turn. The list is
211
+ // built when it fires, so it reflects every outcome in the burst.
212
+ let startOutcomeListQueued = false
213
+ const queueStartOutcomeSessionList = () => {
214
+ if (!ctx.broadcastSessionList || startOutcomeListQueued) return
215
+ startOutcomeListQueued = true
216
+ setImmediate(() => {
217
+ startOutcomeListQueued = false
218
+ try {
219
+ ctx.broadcastSessionList()
220
+ } catch (err) {
221
+ log.error(`deferred session_list after a provider start outcome threw: ${err?.message || err}`)
222
+ }
223
+ })
224
+ }
146
225
 
147
226
  sessionManager.on('session_event', ({ sessionId, event, data }) => {
148
227
  // #5313 (WP-1.3): this listener runs synchronously inside the
@@ -152,30 +231,54 @@ function setupSessionForwarding(normalizer, ctx) {
152
231
  // Contain it: wrap the body, log with the session id, and swallow so a
153
232
  // single malformed event can't bring down the process.
154
233
  try {
155
- // models_updated is global — broadcast to ALL clients, not per-session.
234
+ // models_updated is global — not scoped to viewers of one session (unlike
235
+ // broadcastToSession). #7895: it is no longer sent to every client
236
+ // unconditionally either — broadcastRosterPerRecipient fans it out so
237
+ // each connected client receives it only when the tag names a registry
238
+ // their own active session actually uses (see that function's docstring,
239
+ // ./roster-broadcast.js, for the exact per-tag recipient rule).
156
240
  // Look up the session's provider so clients receive the provider-scoped
157
241
  // defaultModel rather than the Claude-only global. Falls back to the
158
- // Claude default registry when the session is not found (e.g. already
159
- // destroyed). Includes the provider name in the payload so clients can
160
- // route the model list to the correct session type. (#2993)
242
+ // daemon's resolved default when the session is not found (e.g. already
243
+ // destroyed) — same resolution `ws-history.js`'s connect path uses
244
+ // (`resolveRosterProvider`), so a roster this event produces is tagged the
245
+ // same way whether a client learns of it via reconnect or via this live
246
+ // push. (#2993)
247
+ //
248
+ // #7895 — this used to hardcode the fallback tag to `'claude-sdk'` and
249
+ // broadcast ONE message. A claude-cli/claude-tui/claude-byok client keys
250
+ // its roster by the EXACT tag it arrives under
251
+ // (`packages/store-core/src/models-by-provider.ts`), so that single
252
+ // `claude-sdk`-tagged message was delivered and discarded by every other
253
+ // Claude-family client — the same #7756 bug the overlay-reload path was
254
+ // fixed for. `broadcastRosterPerRecipient` (`./roster-broadcast.js`) is
255
+ // that same per-recipient re-tagging, shared rather than re-implemented a
256
+ // third time: a default-registry roster is re-sent once per known
257
+ // Claude-family tag, each copy filtered to the clients that resolve to it;
258
+ // a non-Claude roster (codex, gemini, …) is sent once, unchanged, to its
259
+ // exact-match clients only — untouched from pre-#7895 behaviour.
161
260
  if (event === 'models_updated' && data?.models) {
162
261
  const sessionEntry = sessionManager.getSession(sessionId)
163
262
  const providerName = sessionEntry?.provider ?? null
164
- const registry = providerName ? getRegistryForProvider(providerName) : null
165
- const defaultModel = registry ? registry.getDefaultModelId() : getDefaultModelId()
166
- // When the session is not found (race with teardown) providerName is null
167
- // but we still fall back to the Claude default registry, so advertise
168
- // 'claude-sdk' rather than null so clients can route the model list
169
- // consistently. (#2993)
170
- const resolvedProvider = providerName ?? 'claude-sdk'
171
- broadcast({ type: 'available_models', models: data.models, defaultModel, provider: resolvedProvider })
263
+ const rosterProvider = resolveRosterProvider(providerName, defaultProvider)
264
+ // getRegistryForProvider never returns a falsy value (unknown/null names
265
+ // fall back to defaultRegistry), and resolveRosterProvider never returns
266
+ // a falsy tag either — so this always resolves to a real registry.
267
+ const defaultModel = getRegistryForProvider(rosterProvider).getDefaultModelId()
268
+ broadcastRosterPerRecipient({
269
+ broadcast,
270
+ sessionManager,
271
+ defaultProvider,
272
+ message: { type: 'available_models', models: data.models, defaultModel, provider: rosterProvider },
273
+ })
172
274
  return
173
275
  }
174
276
 
175
277
  // #5665: monthly programmatic-credit meter is machine-wide — broadcast to
176
278
  // ALL authenticated clients, not per-session.
177
279
  if (event === 'monthly_budget') {
178
- broadcast({ type: 'monthly_budget', ...data })
280
+ // The host's spend meter: not for a session-scoped connection.
281
+ broadcast({ type: 'monthly_budget', ...data }, (client) => !isBoundClient(client))
179
282
  return
180
283
  }
181
284
 
@@ -206,26 +309,102 @@ function setupSessionForwarding(normalizer, ctx) {
206
309
  return
207
310
  }
208
311
 
209
- // Sidebar activity feed: lightweight status broadcast to ALL authenticated clients
210
- if (event === 'stream_start') {
312
+ // #8301: a DAEMON-authored user turn (the CI-completion wake, recorded by
313
+ // SessionManager.recordDaemonUserInput). Same wire shape input-handlers.js
314
+ // broadcasts for a typed input, minus `clientId` — there is no sending
315
+ // client, so every viewer of the session renders it. Transient here: the
316
+ // history entry was recorded at the source, which is what a reconnecting
317
+ // client replays. Not routed through the normalizer — like terminal_output
318
+ // above, it is a straight relay with no per-provider shape to normalise.
319
+ if (event === 'user_input') {
320
+ broadcastToSession(sessionId, {
321
+ type: 'user_input',
322
+ sessionId,
323
+ text: typeof data?.text === 'string' ? data.text : '',
324
+ messageId: data?.messageId,
325
+ timestamp: typeof data?.timestamp === 'number' ? data.timestamp : Date.now(),
326
+ // The daemon wrote this turn, not a person. Optional and additive: an
327
+ // older client ignores it and renders the bubble as it always did.
328
+ ...(data?.source === 'daemon' ? { source: 'daemon' } : {}),
329
+ })
330
+ return
331
+ }
332
+
333
+ // #8502: a provider whose `result` precedes the end of its busy window (the
334
+ // jsonl-subprocess family: the child is still exiting when the result line is
335
+ // parsed) says so when busy actually clears. Nothing to normalise or relay to
336
+ // a viewer: it exists to refresh the list the clients re-derive busy from.
337
+ if (event === 'busy_cleared') {
338
+ queueTurnEndSessionList(sessionId, { afterBusyCleared: true })
339
+ return
340
+ }
341
+
342
+ // Sidebar activity feed: lightweight status broadcast to ALL authenticated clients.
343
+ // #7393: not for a `late` thinking stream_start (claude-tui shows a reasoning
344
+ // block that reached the transcript after its turn's `result`). That is a
345
+ // finished turn being decorated, not the session starting work, and nothing
346
+ // would send idle again until the next `result`.
347
+ if (event === 'stream_start' && data?.late !== true) {
211
348
  broadcast({ type: 'session_activity', sessionId, isBusy: true, lastCost: null })
212
349
  } else if (event === 'result') {
213
350
  broadcast({ type: 'session_activity', sessionId, isBusy: false, lastCost: data?.cost ?? null })
351
+ idledByResultThisTick.add(sessionId)
352
+ queueMicrotask(() => idledByResultThisTick.delete(sessionId))
353
+ queueTurnEndSessionList(sessionId)
214
354
  }
215
355
 
216
- // Dev server preview: scan tool_result events for localhost server patterns
217
- if (event === 'tool_result' && data?.result) {
218
- devPreview.handleToolResult(sessionId, data.result)
356
+ // #8497: a requested Stop ends the turn with `stopped` and, on most
357
+ // providers (ACP, Codex app-server, the jsonl-subprocess family), NO
358
+ // `result`. Both clients leave busy on `agent_idle` / `session_activity`,
359
+ // which only a `result` produced, so those sessions stayed busy for good.
360
+ // Announcing idle here covers every provider at the one place they all meet
361
+ // the wire, and `stopped` stays the quiet confirmation: no `result` is
362
+ // minted, so no marker or chip can follow. Skipped when the same turn end
363
+ // already went idle through a `result`.
364
+ let announceIdle = false
365
+ if (event === 'stopped' && !idledByResultThisTick.has(sessionId)) {
366
+ announceIdle = true
367
+ broadcast({ type: 'session_activity', sessionId, isBusy: false, lastCost: null })
219
368
  }
369
+ // Every turn end refreshes the list, including a `stopped` the idle frames
370
+ // were deduped against: the `result` that deduped it queued the list, and the
371
+ // queue is idempotent per synchronous turn end.
372
+ if (event === 'stopped') queueTurnEndSessionList(sessionId)
373
+ // A turn can also end with only an `error` (an SDK query that threw, a BYOK
374
+ // `_emitTurnError`, ACP / Codex `_failTurn`): no `result`, no `stopped`, so no
375
+ // agent_idle or idle ping, and the clients leave busy on nothing else. The
376
+ // list is the one signal left. An `error` that does not end a turn costs one
377
+ // list that reports the session's true state, which is still busy.
378
+ if (event === 'error') queueTurnEndSessionList(sessionId)
220
379
 
221
380
  const normCtx = {
222
381
  sessionId,
223
382
  mode: 'multi',
224
383
  getSessionEntry: () => sessionManager.getSession(sessionId),
384
+ announceIdle,
225
385
  }
226
386
  const result = normalizer.normalize(event, data, normCtx)
227
387
  if (!result) return
228
388
 
389
+ // #7745/#7835: creation/subscription can replay before an async provider
390
+ // handshake and project-policy compilation finish. Ready is the first
391
+ // generic event after those facts settle, so refresh the same bounded
392
+ // session-scoped snapshot used by sendSessionInfo. This is deliberately a
393
+ // separate frame: existing ready and boolean capability semantics stay
394
+ // unchanged, while the creating tab converges without a reselect.
395
+ if (event === 'ready') {
396
+ const entry = sessionManager.getSession(sessionId)
397
+ if (entry?.session) {
398
+ result.messages.push({
399
+ msg: {
400
+ type: 'provider_runtime_info',
401
+ sessionId,
402
+ ...getProviderRuntimeInfo(entry.provider, entry.session),
403
+ },
404
+ })
405
+ }
406
+ }
407
+
229
408
  // Handle delta buffering
230
409
  if (result.buffer) {
231
410
  // #6818: forward the thinking flag so the coalesced frame reconstructs as
@@ -235,18 +414,74 @@ function setupSessionForwarding(normalizer, ctx) {
235
414
  }
236
415
 
237
416
  // Execute side effects before messages (flush_deltas must happen before stream_end broadcast)
238
- executeSideEffects(result.sideEffects, sessionId, ctx)
417
+ // #8502: a `result`'s own `session_list` is the queued turn-end one (above),
418
+ // built after the provider's teardown. Running it here too would publish the
419
+ // stale busy row first and a second list straight after it.
420
+ executeSideEffects(
421
+ event === 'result' ? result.sideEffects?.filter((effect) => effect.type !== 'session_list') : result.sideEffects,
422
+ sessionId,
423
+ ctx,
424
+ )
239
425
  executeRegistrations(result.registrations, sessionId, ctx)
240
426
 
241
427
  // Broadcast messages
242
428
  for (const { msg, filter } of result.messages) {
243
429
  const stamped = withServerTs(msg)
244
- if (filter) {
430
+ // Bounded session attention is visible with the session roster, even
431
+ // when the operator is viewing another session. The broadcaster retains
432
+ // its central bound-session recipient check. All other work stays scoped.
433
+ if (msg.type === 'session_status') {
434
+ const parsed = ServerSessionStatusSchema.safeParse({ ...stamped, sessionId })
435
+ if (parsed.success) broadcast(parsed.data)
436
+ } else if (msg.type === 'activity_delta' && msg.entry?.id === 'decision:session' && msg.entry?.kind === 'decision') {
437
+ const parsed = ServerActivityDeltaSchema.safeParse({ ...stamped, sessionId })
438
+ if (parsed.success && parsed.data.entry.label.length <= 280) {
439
+ const { id, kind, label, status, startedAt, endedAt } = parsed.data.entry
440
+ broadcast({ ...parsed.data, entry: { id, kind, label, status, startedAt, ...(endedAt !== undefined ? { endedAt } : {}) } })
441
+ }
442
+ } else if (filter) {
245
443
  broadcastToSession(sessionId, stamped, filter)
246
444
  } else {
247
445
  broadcastToSession(sessionId, stamped)
248
446
  }
249
447
  }
448
+
449
+ // #8909: a backend model refusal changes the ledger every session on the same
450
+ // codex client reads live, so resend each same-provider session's runtime frame
451
+ // (this one included) and let its picker disable the model. After the event's
452
+ // own messages, so the error reaches clients first. One failing session must
453
+ // not stop the rest, and a failure to enumerate sessions must not abort the
454
+ // rest of this listener, including the afterEffects step below.
455
+ if (event === 'error' && data?.code === MODEL_UNSUPPORTED_CODE) {
456
+ try {
457
+ const provider = sessionManager.getSession(sessionId)?.provider
458
+ const rows = provider ? sessionManager.listSessions() || [] : []
459
+ for (const row of rows) {
460
+ const sid = row?.sessionId
461
+ if (!sid) continue
462
+ try {
463
+ const peer = sessionManager.getSession(sid)
464
+ if (!peer?.session || peer.provider !== provider) continue
465
+ broadcastToSession(sid, withServerTs({
466
+ type: 'provider_runtime_info',
467
+ sessionId: sid,
468
+ ...getProviderRuntimeInfo(peer.provider, peer.session),
469
+ }))
470
+ } catch (err) {
471
+ log.error(`provider_runtime_info refresh after model rejection failed for session ${sid}: ${err?.message || err}`)
472
+ }
473
+ }
474
+ } catch (err) {
475
+ log.error(`provider_runtime_info refresh after model rejection failed: ${err?.message || err}`)
476
+ }
477
+ }
478
+
479
+ // #7379: AFTER the broadcast, deliberately. Releasing a permission runs
480
+ // ws-permissions' cleanup() -> tearDownRoute, which unsubscribes the
481
+ // permission-induced viewers of this session — so anything released here
482
+ // must already have been told. Same executor as sideEffects so the two
483
+ // buckets can never grow divergent handling.
484
+ executeSideEffects(result.afterEffects, sessionId, ctx)
250
485
  } catch (err) {
251
486
  // #5313 (WP-1.3): see the try at the top of this listener.
252
487
  const message = err?.message || String(err)
@@ -265,6 +500,20 @@ function setupSessionForwarding(normalizer, ctx) {
265
500
  // (#2954). History stays on disk; client shows a retry affordance.
266
501
  sessionManager.on('session_restore_failed', safeForward('session_restore_failed', (payload) => {
267
502
  broadcast({ type: 'session_restore_failed', ...payload })
503
+ // #8861 / #8092: a session re-parked after an ASYNC start failure was already
504
+ // in the last `session_list` (it was live when that went out), and the
505
+ // restore-branch teardown in `_handleAsyncStartFailure` never emits
506
+ // `session_destroyed`, so without a refresh every client's sidebar keeps a
507
+ // clickable entry for a session that no longer exists ("Session not found").
508
+ // Re-sending the list is what removes it.
509
+ queueStartOutcomeSessionList()
510
+ }))
511
+
512
+ // #8872: a session whose async start() was still settling went out in
513
+ // `session_list` as `starting`; once the start resolves, re-send the list so
514
+ // every client can open it.
515
+ sessionManager.on('session_start_settled', safeForward('session_start_settled', () => {
516
+ queueStartOutcomeSessionList()
268
517
  }))
269
518
 
270
519
  // Persist failures — surface to clients so the user knows a session-list
@@ -291,12 +540,23 @@ function setupSessionForwarding(normalizer, ctx) {
291
540
  broadcastToSession(sessionId, {
292
541
  type: 'session_error',
293
542
  code: errorCode || 'SESSION_START_FAILED',
543
+ // #8981: lets clients tell a refused fresh session apart from every other
544
+ // session_error and record it as a coded chat error. Mirrored by
545
+ // SESSION_CREATE_FAILED_CATEGORY in store-core.
546
+ category: 'create_failed',
294
547
  sessionId,
295
548
  recoverable: false,
296
549
  message: errorMessage
297
550
  ? `The session failed to start: ${errorMessage}`
298
551
  : `The session failed to start${provider ? ` (${provider})` : ''}.`,
299
552
  })
553
+ // #8981: nothing else announces the removal. `session_destroyed` listeners
554
+ // never send a `session_list`, and clients drop a session (and its messages)
555
+ // only when a list omits it, so the failed session would linger in sidebars
556
+ // and a coded entry parked for it would never land. The setImmediate inside
557
+ // fires after the synchronous destroySession that follows this emit, so the
558
+ // list omits the session.
559
+ queueStartOutcomeSessionList()
300
560
  }))
301
561
 
302
562
  // #5731 (T3): a checkpoint create/delete that couldn't be flushed to disk will
@@ -319,8 +579,11 @@ function setupSessionForwarding(normalizer, ctx) {
319
579
  }
320
580
 
321
581
  // Dev server preview: broadcast tunnel start/stop to clients
322
- devPreview.on('dev_preview_started', safeForward('dev_preview_started', ({ sessionId, port, url }) => {
323
- broadcastToSession(sessionId, { type: 'dev_preview', port, url })
582
+ devPreview.on('dev_preview_status', safeForward('dev_preview_status', ({ sessionId, ...message }) => {
583
+ broadcastToSession(sessionId, message)
584
+ }))
585
+ devPreview.on('dev_preview_started', safeForward('dev_preview_started', ({ sessionId, port, url, target, exposure }) => {
586
+ broadcastToSession(sessionId, { type: 'dev_preview', port, url, ...(target ? { target, exposure } : {}) })
324
587
  }))
325
588
  devPreview.on('dev_preview_stopped', safeForward('dev_preview_stopped', ({ sessionId, port }) => {
326
589
  broadcastToSession(sessionId, { type: 'dev_preview_stopped', port })
@@ -329,7 +592,7 @@ function setupSessionForwarding(normalizer, ctx) {
329
592
  // (and the exposed local port) may still be live. Surface it as a per-session
330
593
  // error banner (reusing `session_error`, like the checkpoint/persist failure
331
594
  // paths) so the user can verify / kill cloudflared instead of assuming the
332
- // port is closed. recoverable:true — informational; the slot is already freed.
595
+ // port is closed. The slot stays tracked until child exit is confirmed.
333
596
  devPreview.on('dev_preview_stop_failed', safeForward('dev_preview_stop_failed', ({ sessionId, port, error }) => {
334
597
  if (!sessionId) return
335
598
  broadcastToSession(sessionId, {
@@ -350,7 +613,7 @@ function setupSessionForwarding(normalizer, ctx) {
350
613
 
351
614
  /** Legacy single CLI session forwarding via normalizer */
352
615
  function setupCliForwarding(normalizer, ctx) {
353
- const { cliSession, devPreview, broadcast } = ctx
616
+ const { cliSession, devPreview, broadcast, defaultProvider = null } = ctx
354
617
 
355
618
  // #3240: `skill_changed` is forwarded so legacy single-CLI users get the
356
619
  // same trust-mismatch broadcast as multi-session mode. The normaliser
@@ -405,6 +668,12 @@ function setupCliForwarding(normalizer, ctx) {
405
668
  broadcast(stamped)
406
669
  }
407
670
  }
671
+
672
+ // #7379: after the broadcast — see the multi-session path. This path
673
+ // broadcasts globally rather than per-session, so the unsubscribe hazard
674
+ // does not bite here; the ordering is mirrored anyway so the two paths
675
+ // cannot drift into different semantics for the same effect.
676
+ executeSideEffects(result.afterEffects, null, ctx)
408
677
  } catch (err) {
409
678
  const message = err?.message || String(err)
410
679
  log.error(`legacy-cli forwarding threw (event=${event}): ${message}${err?.stack ? '\n' + err.stack : ''}`)
@@ -412,16 +681,12 @@ function setupCliForwarding(normalizer, ctx) {
412
681
  })
413
682
  }
414
683
 
415
- // Dev server preview: scan tool_result events for localhost server patterns (legacy CLI)
416
- // #5313 (WP-1.3): safeForward — a throw here must not unwind CliSession's emit().
417
- cliSession.on('tool_result', safeForward('cli:tool_result', (data) => {
418
- if (data?.result) {
419
- devPreview.handleToolResult('__legacy__', data.result)
420
- }
684
+ devPreview.on('dev_preview_status', safeForward('cli:dev_preview_status', ({ sessionId, ...message }) => {
685
+ if (sessionId === '__legacy__') broadcast({ ...message, sessionId })
421
686
  }))
422
- devPreview.on('dev_preview_started', safeForward('cli:dev_preview_started', ({ sessionId, port, url }) => {
687
+ devPreview.on('dev_preview_started', safeForward('cli:dev_preview_started', ({ sessionId, port, url, target, exposure }) => {
423
688
  if (sessionId === '__legacy__') {
424
- broadcast({ type: 'dev_preview', port, url })
689
+ broadcast({ type: 'dev_preview', port, url, ...(target ? { target, exposure } : {}) })
425
690
  }
426
691
  }))
427
692
  devPreview.on('dev_preview_stopped', safeForward('cli:dev_preview_stopped', ({ sessionId, port }) => {
@@ -444,12 +709,23 @@ function setupCliForwarding(normalizer, ctx) {
444
709
  }
445
710
  }))
446
711
 
447
- // models_updated bypasses normalizer — global broadcast.
448
- // CLI mode is always a Claude session; include provider so clients can
449
- // route the model list consistently with the multi-session path. (#2993)
712
+ // models_updated bypasses normalizer — global broadcast. Legacy single-CLI
713
+ // mode has no sessionManager and exactly one running session, so — unlike
714
+ // the multi-session path above — there is no per-client provider variance
715
+ // to fan out over; every connected client sees the SAME roster tag. Tag it
716
+ // with whatever `ws-history.js`'s legacy connect path
717
+ // (`resolveRosterProvider(null, billingCanary?.defaultProvider)`) would send
718
+ // for this daemon, rather than the literal `'claude-cli'` (#7895): a
719
+ // claude-tui or claude-byok client — or a daemon started with a non-default
720
+ // `config.provider` — keys its roster by that EXACT tag
721
+ // (`packages/store-core/src/models-by-provider.ts`), so a hardcoded
722
+ // `'claude-cli'` was delivered and discarded whenever the connect-time tag
723
+ // disagreed.
450
724
  cliSession.on('models_updated', safeForward('cli:models_updated', (data) => {
451
725
  if (data?.models) {
452
- broadcast({ type: 'available_models', models: data.models, defaultModel: getDefaultModelId(), provider: 'claude-cli' })
726
+ const legacyProvider = resolveRosterProvider(null, defaultProvider)
727
+ const legacyRegistry = getRegistryForProvider(legacyProvider)
728
+ broadcast({ type: 'available_models', models: data.models, defaultModel: legacyRegistry.getDefaultModelId(), provider: legacyProvider })
453
729
  }
454
730
  }))
455
731
  }
@@ -457,7 +733,7 @@ function setupCliForwarding(normalizer, ctx) {
457
733
  /** Execute side effect descriptors returned by the normalizer */
458
734
  function executeSideEffects(sideEffects, sessionId, ctx) {
459
735
  if (!sideEffects) return
460
- const { normalizer, sessionManager, pushManager, broadcast, broadcastToSession, broadcastSessionList } = ctx
736
+ const { normalizer, sessionManager, pushManager, broadcast, broadcastToSession, broadcastSessionList, releasePermission } = ctx
461
737
  for (const effect of sideEffects) {
462
738
  switch (effect.type) {
463
739
  case 'session_list':
@@ -469,6 +745,20 @@ function executeSideEffects(sideEffects, sessionId, ctx) {
469
745
  }
470
746
  }
471
747
  break
748
+ case 'release_permission':
749
+ // #7379: the session says the turn behind this prompt is dead, so the
750
+ // daemon must stop holding (and re-sending) its pending entry. Optional
751
+ // in ctx so a harness that does not wire permissions still forwards
752
+ // events; a no-op when the requestId was never in the HTTP map, which is
753
+ // the normal case for the SDK path and for a hook that closed cleanly.
754
+ if (releasePermission) {
755
+ try {
756
+ releasePermission(effect.requestId, sessionId)
757
+ } catch (err) {
758
+ log.warn(`Failed to release abandoned permission ${effect.requestId}: ${err?.message || err}`)
759
+ }
760
+ }
761
+ break
472
762
  case 'refresh_context':
473
763
  if (sessionManager) {
474
764
  sessionManager.getSessionContext(effect.sessionId || sessionId).then((ctxData) => {
@@ -11,7 +11,20 @@
11
11
  *
12
12
  * This module is the SINGLE SOURCE OF TRUTH for the shape: the JSDoc typedef
13
13
  * below, the `CTX_NAMESPACES` list, and `assertCtxShape()` are all derived from
14
- * the same five buckets. ws-server.js builds the production ctx; tests build a
14
+ * the same five buckets. Only two of those were ever COUPLED, though —
15
+ * `nsCtx`'s `FIELD_TO_NS` and `assertCtxShape` both read `CTX_NAMESPACES`,
16
+ * while the typedef was decorative and drifted silently (seven fields missing,
17
+ * one present here but absent from the roster — #7403). They are now pinned
18
+ * against each other by `tests/ws-handler-context-typedef-parity.test.js`.
19
+ *
20
+ * That pins TWO of the three sides. `assertCtxShape({deep: true})`, which
21
+ * ws-server.js runs on its own `_handlerCtx` at construction, pins
22
+ * roster ⊆ production. What is still unpinned is production ⊆ roster — a
23
+ * getter added to ws-server.js's namespace literals but never added to
24
+ * CTX_NAMESPACES is invisible to every check here. That is exactly how
25
+ * `tokenManager` drifted for the whole life of #6006.
26
+ *
27
+ * ws-server.js builds the production ctx; tests build a
15
28
  * namespaced mock via `tests/test-helpers.js` and may run it through
16
29
  * `assertCtxShape()` so a partial mock fails loudly at construction instead of
17
30
  * at the first missing-field read deep inside a handler.
@@ -35,6 +48,10 @@
35
48
  * @property {(sessionId: string) => void} syncTerminalMirror - Re-evaluate the terminal-mirror coalescer gate for a session after its subscriber set changes (#5837).
36
49
  * @property {(ws: any, sessionId: string) => void} sendSessionInfo - Send a session_info envelope.
37
50
  * @property {(ws: any, sessionId: string) => void} replayHistory - Replay a session's history to a client.
51
+ * @property {(ws: any, sessionId: string) => void} reseedActiveAgents - Re-assert a session's live subagents after a replay wiped the client's list (#7340).
52
+ * @property {(ws: any, sessionId: string) => void} resendPendingQuestions - Re-assert the AskUserQuestions a session is still blocked on, after a replay's `history_replay_end` let the client's sweep stamp them '(resolved)' (#7457).
53
+ * @property {(ws: any, sessionId: string) => void} resendPendingPermissions - Re-assert the permission prompts a session is still blocked on, after a full-rebuild replay's `history_replay_end` swapped away the live card (#8328, #8340). Honours the session-bound-client guard (#8342).
54
+ * @property {(client: object) => boolean} isConnectionAuthorized - True only while the connection is still authenticated AND the credential it authenticated with is still valid. Handlers call it after every await and before any side effect, because a suspended handler keeps its `client` after the connection has ended.
38
55
  * @property {Map} clients - WebSocket → client-state Map (the WsClientManager's Map).
39
56
  *
40
57
  * @typedef {Object} WsHandlerSessions
@@ -63,12 +80,24 @@
63
80
  * @property {object|null} skillsUsageRecorder - Per-skill usage aggregates (lives on SessionManager).
64
81
  * @property {(requestId: string, result: object) => void} resolvePairRequester - Resolve a pending pair request.
65
82
  * @property {(requestId: string, reason: string) => void} broadcastPairResolved - Fan-out a pair-resolved notice.
83
+ * @property {object} shellApprovalStore - #6277 host-local user-shell approval store (always constructed on the production ctx; test mocks may pass null).
84
+ * @property {object|null} repoEventStore - #5966 bounded RepoEventStore; null until the first GitHub-webhook delivery lazily creates it.
85
+ * @property {{url: string|null, lanOnly: boolean, note: string|null}} webhookPayloadUrl - #6540 GitHub payload URL derived from the live origin (`deriveWebhookPayloadUrl`).
86
+ * @property {object|null} repoWebhookDeliveries - #6540 in-memory recent-delivery ring; null until the first delivery.
87
+ * @property {(value: string|null) => void} setWebhookSecretCache - #6540 refresh the in-process webhook-secret cache.
88
+ * @property {object|null} orchestrationManager - #6691 OrchestrationManager; null while the feature is off.
89
+ * @property {object|null} schedulerEngine - #6871 scheduled-task engine; null when scheduling is off.
90
+ * @property {object|null} sessionCiWatcher - #7427 SessionCiWatcher, so an on-demand PR survey can arm the watch; null when `sessionCi.watch` is off.
91
+ * @property {object|null} daemonUpdate - #8331 DaemonUpdateStatus (pending-update banner + restart-now / postpone request files); null when not wired.
66
92
  *
67
93
  * @typedef {Object} WsHandlerRuntime
68
94
  * @property {boolean} draining - True while the server is draining for shutdown.
69
95
  * @property {string[]} projectsDirs - Per-provider projects dirs (computed fresh each access).
96
+ * @property {Array<{provider: string, projectsDir: string}>} transcriptSources - The same dirs tagged with the owning provider (#7828).
70
97
  * @property {string[]} userAgentsDirs - Per-provider agents dirs (computed fresh each access).
71
98
  * @property {Map} evaluatorIterations - sessionId → stable auto-evaluator iteration counter (#3186/#3637).
99
+ * @property {Map} pendingEvaluatorAwaits - sessionId → in-flight evaluator-await lock, shared by every message (#3636/#3666).
100
+ * @property {Map} inputDedupRecords - sessionId → bounded clientMessageId acceptance records (#7822).
72
101
  *
73
102
  * @typedef {Object} WsHandlerContext
74
103
  * @property {WsHandlerTransport} transport
@@ -86,7 +115,7 @@
86
115
  *
87
116
  * Optional, cross-cutting test-injection seams (e.g. `ctx.evaluateDraft`,
88
117
  * `ctx.summarizeSession`, `ctx.scanConversations`, `ctx.resolveRepoSet`,
89
- * `ctx.surveyRunners`, `ctx.realpath`, `ctx._pendingEvaluatorAwaits`) are
118
+ * `ctx.surveyRunners`, `ctx.realpath`) are
90
119
  * deliberately NOT listed here — they are optional DI hooks read with
91
120
  * `ctx?.X ?? defaultX` and never present on the production ctx.
92
121
  *
@@ -109,6 +138,10 @@ export const CTX_NAMESPACES = {
109
138
  'syncTerminalMirror',
110
139
  'sendSessionInfo',
111
140
  'replayHistory',
141
+ 'reseedActiveAgents',
142
+ 'resendPendingQuestions',
143
+ 'resendPendingPermissions',
144
+ 'isConnectionAuthorized',
112
145
  'clients',
113
146
  ],
114
147
  sessions: [
@@ -127,6 +160,12 @@ export const CTX_NAMESPACES = {
127
160
  'pushManager',
128
161
  'pairingManager',
129
162
  'checkpointManager',
163
+ // #6006: the token lifecycle manager, exposed so the primary-gated
164
+ // `revoke_token` handler can fire the operator panic button. Null under
165
+ // --no-auth. It was on the production ctx and in the typedef but NOT in
166
+ // this roster (#7403) — so `assertCtxShape({deep:true})` never required it
167
+ // and `nsCtx()` never routed it. The typedef was the correct side.
168
+ 'tokenManager',
130
169
  'devPreview',
131
170
  'webTaskManager',
132
171
  'environmentManager',
@@ -161,15 +200,44 @@ export const CTX_NAMESPACES = {
161
200
  // SessionManager and exists either way, so tasks are still readable and
162
201
  // editable with no engine present.
163
202
  'schedulerEngine',
203
+ // #7427: the SessionCiWatcher (#7426). The `session_pr_status_request`
204
+ // handler hands its survey snapshot to `observe()`, so a dashboard pull ARMS
205
+ // the watch instead of waiting on the sweep's five-minute discovery pass.
206
+ // NULL whenever `sessionCi.watch` is off — the handler treats absence as
207
+ // "nothing to arm" and its reply is unaffected either way.
208
+ 'sessionCiWatcher',
209
+ // #8331: the DaemonUpdateStatus module (daemon-update-status.js) behind the
210
+ // dashboard's "update ready" banner. NULL in tests and wherever server-cli did
211
+ // not build one; the `daemon_update_action` handler reports that as
212
+ // UNAVAILABLE rather than pretending an update can be applied.
213
+ 'daemonUpdate',
164
214
  ],
165
215
  runtime: [
166
216
  'draining',
167
217
  'projectsDirs',
218
+ 'transcriptSources',
168
219
  'userAgentsDirs',
169
220
  'evaluatorIterations',
221
+ 'pendingEvaluatorAwaits',
222
+ 'inputDedupRecords',
170
223
  ],
171
224
  }
172
225
 
226
+ /**
227
+ * The per-message handler ctx: the long-lived ctx spread with this message's
228
+ * correlation id. The spread is shallow, so anything that must outlive one
229
+ * message (a lock, a counter) has to live on a NESTED object (`ctx.runtime.*`),
230
+ * never as a direct property of the ctx. ws-server.js dispatch and the tests
231
+ * that exercise cross-message behaviour both build their ctx through this.
232
+ *
233
+ * @param {object} baseCtx
234
+ * @param {string} correlationId
235
+ * @returns {object}
236
+ */
237
+ export function buildMessageCtx(baseCtx, correlationId) {
238
+ return { ...baseCtx, correlationId }
239
+ }
240
+
173
241
  /** All namespace names, in declaration order. */
174
242
  export const CTX_NAMESPACE_NAMES = Object.keys(CTX_NAMESPACES)
175
243