@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -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 +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/ws-server.js CHANGED
@@ -5,43 +5,52 @@ import { WebSocketServer } from 'ws'
5
5
  import { readFileSync } from 'fs'
6
6
  import { fileURLToPath } from 'url'
7
7
  import { dirname, join } from 'path'
8
- import { homedir } from 'os'
9
8
  import { PagesStore } from './pages-store.js'
10
9
  import { ShellApprovalStore } from './shell-approval-store.js'
11
10
  import { finalizeShellCreate } from './handlers/session-handlers.js'
12
11
  import { decrypt, DIRECTION_CLIENT } from '@chroxy/store-core/crypto'
13
12
  import { safeTokenCompare } from './token-compare.js'
14
13
  import { createClientSender } from './ws-client-sender.js'
14
+ import { isAuthorityRevoked } from './connection-authority.js'
15
15
  import { ClientMessageSchema, EncryptedEnvelopeSchema } from './ws-schemas.js'
16
16
  import { EventNormalizer } from './event-normalizer.js'
17
17
  import { createFileOps } from './ws-file-ops/index.js'
18
18
  import { createPermissionHandler } from './ws-permissions.js'
19
19
  import { setupForwarding } from './ws-forwarding.js'
20
20
  import { handleSessionMessage, handleCliMessage } from './ws-message-handlers.js'
21
- import { handleAuthMessage, handlePairMessage, handlePairRequestMessage, handleKeyExchange, BENIGN_PAIR_WINDOW_MS } from './ws-auth.js'
21
+ import { dispatchPolicyFor, isPrincipalClient, frameForPrincipal, principalMaySee, principalPolicyOptsFromCtx, sendPrincipalRefusal, PRINCIPAL_ALLOWED_MESSAGE_TYPES } from './principal-policy.js'
22
+ import { PrincipalSubscriptions } from './principal-subscriptions.js'
23
+ import { principalAuditor } from './principal-audit.js'
24
+ import { handleAuthMessage, isLoopbackConnection, handlePairMessage, handlePairRequestMessage, handleKeyExchange, BENIGN_PAIR_WINDOW_MS } from './ws-auth.js'
22
25
  import { postPairLinkToDiscord } from './discord-pair-delivery.js'
23
- import { sendPostAuthInfo, replayHistory, flushPostAuthQueue, sendSessionInfo } from './ws-history.js'
26
+ import { sendPostAuthInfo, replayHistory, flushPostAuthQueue, sendSessionInfo, reseedActiveAgents, resendPendingQuestions, resendPendingPermissionsForSession } from './ws-history.js'
24
27
  import { createDevicePreferences } from './device-preferences.js'
25
28
  import { isUserShellEnabled, isIdeFeatureEnabled, isOrchestrationEnabled, DEFAULT_MAX_PAYLOAD_BYTES } from './config.js'
26
29
  import { createHttpHandler } from './http-routes.js'
30
+ import { getDashboardBuildId } from './dashboard-build.js'
27
31
  import { setMcpOAuthCallbackBase } from './byok-mcp-oauth.js'
28
32
  import { CheckpointManager } from './checkpoint-manager.js'
29
33
  import { DevPreviewManager } from './dev-preview.js'
34
+ import { broadcastEnvironmentList, isBoundClient, isBoundToOtherSession, CONVERSATION_FRAME } from './environments/authority.js'
30
35
  import { WebTaskManager } from './web-task-manager.js'
31
36
  import { RateLimiter, getClientIp, getRateLimitKey, LOOPBACK_ADDRESSES } from './rate-limiter.js'
32
37
  import { isUserShellApprovalRequired } from './config.js'
33
38
  import { writeShellApprovalInfo, removeShellApprovalInfo } from './shell-approval-info.js'
34
- import { createLogger, addLogListener, removeLogListener } from './logger.js'
39
+ import { createLogger, addLogListener, removeLogListener, loggableValue } from './logger.js'
35
40
  import { PermissionAuditLog } from './permission-audit.js'
36
41
  import { WsBroadcaster } from './ws-broadcaster.js'
37
42
  import { WsClientManager } from './ws-client-manager.js'
38
- import { terminalMirrorRecipient } from './handler-utils.js'
39
- import { getProviderDataDirs } from './providers.js'
40
- import { assertCtxShape } from './ws-handler-context.js'
43
+ import { terminalMirrorRecipient, canClientSeeWebTask } from './handler-utils.js'
44
+ import { frameForBoundClient } from './outgoing-policy.js'
45
+ import { captureBearer, bearerStillValid } from './bearer-recheck.js'
46
+ import { getProviderDataDirs, getProviderTranscriptSources, resolveDaemonDefaultProvider } from './providers.js'
47
+ import { assertCtxShape, buildMessageCtx } from './ws-handler-context.js'
41
48
  import { isLoopbackHost } from './bind-host.js'
42
49
  import { getLanIp } from './lan-ip.js'
43
50
  import { deriveWebhookPayloadUrl } from './github-webhook.js'
44
- import { isLocalOrLanPeer } from './connection-locality.js'
51
+ import { isLocalOrLanPeer, isLoopbackPeer } from './connection-locality.js'
52
+ import { configPath } from './config-dir.js'
53
+ import { QuestionRouteMap } from './question-route-map.js'
45
54
 
46
55
  const __filename = fileURLToPath(import.meta.url)
47
56
  const __dirname = dirname(__filename)
@@ -201,6 +210,20 @@ const REVOKE_ACK_TIMEOUT_MS = 10_000
201
210
  // Cloudflare / mobile-OS idle timeouts open for clients that don't initiate.
202
211
  export const KEEPALIVE_SWEEP_MS = 15_000
203
212
 
213
+ // Application close code sent when a connection's credential stops being valid
214
+ // (the pairing token was revoked, expired or evicted). Distinct from the
215
+ // protocol-level 1008 so a client re-pairs instead of retrying the dead token.
216
+ export const WS_CLOSE_CREDENTIAL_INVALID = 4401
217
+
218
+ // The revoke acknowledgement's error codes (the only errors a stripped connection still gets).
219
+ const REVOKE_NOTICE_ERROR_CODES = new Set(['REVOKE_NOT_DURABLE', 'REVOKE_DURABILITY_UNKNOWN'])
220
+
221
+ // Frames that belong to the authentication handshake and are never withheld.
222
+ const AUTH_FLOW_FRAME_TYPES = new Set([
223
+ 'auth_ok', 'auth_fail', 'key_exchange_ok', 'pair_fail', 'pair_result',
224
+ 'pair_request_pending', 'pair_request_ack',
225
+ ])
226
+
204
227
  async function checkLatestVersion(packageName) {
205
228
  const now = Date.now()
206
229
  if (_latestVersionCache.checkedAt > 0 && (now - _latestVersionCache.checkedAt) < VERSION_CHECK_TTL) {
@@ -266,7 +289,7 @@ function _isSecureRequest(req) {
266
289
  * { type: 'cancel_queued', clientMessageId, sessionId? } — cancel ONE queued send-while-busy follow-up (#5943); server emits message_dequeued(reason: 'cancelled')
267
290
  * { type: 'set_model', model: '...' } — change model on active session
268
291
  * { type: 'set_permission_mode', mode: '...', confirmed? } — change permission mode (confirmed: true required for 'auto')
269
- * { type: 'permission_response', requestId, decision } — respond to permission prompt
292
+ * { type: 'permission_response', requestId, decision, scope? } — respond to permission prompt; `scope: 'session'` beside `allow` labels an "Allow for Session" answer (#8517: a label only, shown on permission_resolved and in the journal; the session rule is a separate set_permission_rules)
270
293
  * { type: 'list_sessions' } — request session list
271
294
  * { type: 'switch_session', sessionId } — switch to a different session
272
295
  * { type: 'create_session', name?, cwd?, provider?, agentCommId? } — create a new session
@@ -275,6 +298,7 @@ function _isSecureRequest(req) {
275
298
  * { type: 'register_push_token', token } — register push token for notifications
276
299
  * { type: 'user_question_response', answer } — respond to AskUserQuestion prompt
277
300
  * { type: 'list_directory', path? } — request directory listing for file browser
301
+ * { type: 'check_git_repo', path, requestId? } — is path a git repo? (New Session worktree switch, #8972)
278
302
  * { type: 'browse_files', path? } — request file/directory listing for file browser
279
303
  * { type: 'read_file', path } — request file content for file viewer
280
304
  * { type: 'write_file', path, content } — write file content (path validated, 5MB limit)
@@ -325,15 +349,22 @@ function _isSecureRequest(req) {
325
349
  * { type: 'terminal_unsubscribe', sessionId } — #5835 opt OUT of a session's live PTY mirror
326
350
  * { type: 'terminal_resize', sessionId, cols, rows } — #5835 Phase 2 request to resize the live claude-tui PTY; applied only for the session's primary owner (or an unclaimed session), then broadcast back as terminal_size
327
351
  * { type: 'terminal_input', sessionId, data } — #5835 Phase 3 raw keystrokes → live claude-tui PTY (true remote control); authority mirrors `input` (bound-session check + single-driver primary gate; an observer's keystroke is rejected with input_conflict)
328
- * { type: 'set_thinking_level', level } — set thinking budget level ('default'|'high'|'max')
352
+ * { type: 'set_thinking_level', level } — set the reasoning level; `level: null` CLEARS the session's override back to the provider/model default with no roster check (#7786). Otherwise the accepted values are whatever the session's ACTIVE MODEL advertises (`reasoningLevels`), falling back to the Claude triple for a model row that carries none (#7730)
329
353
  * { type: 'set_permission_rules', rules, sessionId } — set per-session auto-approval rules
330
354
  * { type: 'set_mcp_server_enabled', server, enabled, sessionId?, requestId? } — #6824 runtime park/unpark of an ALREADY-CONFIGURED MCP server (BYOK lane; own-session gate)
331
355
  * { type: 'submit_mcp_auth_code', server, code, sessionId?, requestId? } — #6822 submit a pasted OAuth authorization code for a remote MCP server (BYOK lane)
332
356
  * { type: 'add_mcp_server', name, config, scope?, sessionId?, requestId? } — #6974 ADD an MCP server, persisting it to the user's MCP config (BYOK lane; STRICT-PRIMARY gate — any non-primary token is rejected, since a configured server is a command this machine will spawn; #7001)
333
357
  * { type: 'remove_mcp_server', name, scope?, sessionId?, requestId? } — #6974 permanently REMOVE a configured MCP server from the user's MCP config (BYOK lane; same strict-primary gate)
358
+ * { type: 'trust_folder', sessionId, digest, requestId? } — trust the folder of a session so its project settings (.mcp.json, .claude/settings.json, CLAUDE.md, agents, skills, commands) load; the folder comes from the server's session record, never from the message. `digest` is the one from the folder_trust_state the owner reviewed: the daemon rescans and refuses (FOLDER_TRUST_CHANGED, or FOLDER_TRUST_UNTRUSTABLE for a folder that cannot be fully reviewed) when it differs. Tied to the exact content of the listed files: any change makes the folder untrusted again. PRIMARY-ONLY (primary token, not session-bound, no agent principal; others get FOLDER_TRUST_FORBIDDEN). Reply: folder_trust_result, then folder_trust_state to every session in that folder
359
+ * { type: 'untrust_folder', sessionId, requestId? } — stop trusting the folder of a session (same gate and reply as trust_folder)
334
360
  * { type: 'scheduled_tasks_request', requestId? } — #6871 read the standing scheduled-task registry + the scheduler gate state (host-level: a pairing-BOUND client is rejected)
335
- * { type: 'scheduled_task_action', action, taskId?, task?, requestId? } — #6871 create/update/pause/resume/delete a scheduled task (UNBOUND-STRICT-PRIMARY gate — a scheduled task makes this machine run an agent session unattended; a pairing-BOUND client is rejected even if it is primary, #7025)
361
+ * { type: 'scheduled_task_action', action, taskId?, handle?, task?, requestId? } — #6871 create/update/pause/resume/delete a scheduled task, or (#7079) `discard_unreadable` a load-refused stored entry by its opaque server-derived `handle` (UNBOUND-STRICT-PRIMARY gate — a scheduled task makes this machine run an agent session unattended; a pairing-BOUND client is rejected even if it is primary, #7025)
336
362
  * { type: 'set_scheduler_enabled', enabled, requestId? } — #6871 flip the PERSISTED global scheduled-execution gate (features.scheduler); same unbound-strict-primary gate, and a daemon restart is required for it to take effect (reported as scheduler.restartRequired)
363
+ * { type: 'daemon_update_action', action: 'restart-now'|'postpone', target, confirmBusy?, requestId? } — #8331 apply or hold off the update the idle-only auto-deploy has queued for the daily daemon (STRICT-PRIMARY + UNBOUND gate — restarting kills every live session; a pairing or bound client gets daemon_update_action_result{code:NOT_AUTHORIZED} and nothing is written). restart-now with busy sessions and no confirmBusy replies daemon_update_confirm_required instead of writing
364
+ * { type: 'principal_admin_grant', label, scope, sessionIds?, cwdRoots?, ttlMs?, requestId? } | { type: 'principal_admin_list', requestId? } | { type: 'principal_admin_revoke', principalId?, label?, requestId? } | { type: 'principal_admin_disable', all?: true, label?, requestId? } | { type: 'principal_admin_enable', all?: true, label?, requestId? } — #9116 agent-principal management (S11 adds the kill switch pair: disable persists a flag in the config dir and closes the affected principals' connections 4401; enable is explicit and refused while the audit log is unwritable) (STRICT-PRIMARY + UNBOUND + loopback-only; refused to bound clients and principals at dispatch). grant refuses until S11; reply is principal_admin_result
365
+ * { type: 'principal_subscribe', requestId, sessionIds[], cursors?[{ sessionId, journalId, seq }] } | { type: 'principal_unsubscribe', requestId?, sessionIds? } | { type: 'principal_events_read', requestId, sessionId, cursor?, limit? } — #9118 (S3 of #9112) the agent principal's journal read path (observe tier; every session id must be granted or the whole request is refused scope_denied); refused to every client that is not a principal; replies are principal_subscribed / principal_event / principal_live_fence / principal_gap / principal_events_page
366
+ * { type: 'principal_pending_permissions', requestId, sessionIds? } — #9119 (S4 of #9112) a read-only snapshot of the permission requests still pending on the principal's granted sessions, from the canonical state of both pipelines (observe tier; every explicit session id must be granted or the whole request is refused scope_denied, indistinguishable from a nonexistent session; omitted = every granted session); refused to every client that is not a principal; grants no decision authority; reply is principal_pending_permissions_result
367
+ * { type: 'principal_sessions_snapshot', requestId, sessionIds? } — #9120 (S5 of #9112) a read-only roster of the principal's granted sessions: observed status, declared status, handoff blockers, model requested/observed (observe tier; every explicit session id must be granted or the whole request is refused scope_denied, indistinguishable from a nonexistent session; omitted = every granted session); refused to every client that is not a principal; reply is principal_sessions_snapshot_result
337
368
  * { type: 'set_prompt_evaluator', value: boolean, sessionId? } — toggle the per-session promptEvaluator (#3185)
338
369
  * { type: 'set_prompt_evaluator_skip_pattern', value: string|null, sessionId? } — set the per-session evaluator skip-pattern source (#3639)
339
370
  * { type: 'set_chroxy_context_hint', value: boolean, sessionId? } — toggle the per-session Chroxy context hint (#3805)
@@ -345,53 +376,80 @@ function _isSecureRequest(req) {
345
376
  * { type: 'extension_message', ... } — opaque extension payload (passthrough, no server handling)
346
377
  * { type: 'create_environment', name, cwd, image?, ... } — create persistent container environment
347
378
  * { type: 'list_environments' } — list all persistent environments
348
- * { type: 'destroy_environment', environmentId } — destroy an environment and its container
379
+ * { type: 'destroy_environment', environmentId, force? } — destroy an environment and its container. #7562: REFUSES while sessions are running inside it (environment_error, code ENVIRONMENT_HAS_LIVE_SESSIONS) unless `force: true`, which destroys those sessions cleanly FIRST and then the environment
349
380
  * { type: 'get_environment', environmentId } — get single environment details
381
+ * { type: 'list_failed_restores' } — #7625 roster of sessions the boot restore could not bring back (BOUND-REFUSED: rows carry cwd, an absolute host path, plus a sibling-session roster — same reasoning as list_environments #7596. Replies with a degraded, schema-valid failed_restores_list carrying refused+code, not an error, so the caller never waits on a reply that never comes)
382
+ * { type: 'retry_failed_restore', sessionId } — #7625 re-attempt one parked failed restore (BOUND-REFUSED, at the UNBOUND bar rather than strict primary: the caller supplies a sessionId and nothing else — provider, cwd and every spawn input come from the entry the daemon itself persisted, so there is no caller-chosen binary/argv/env)
383
+ * { type: 'get_failed_restore_history', sessionId, offset?, limit? } — #8860 read one page (oldest first; limit clamped 1..100, default 50) of a parked failed restore's PRESERVED history, so a session that can never be resumed (e.g. a Codex auto-mode session with no native locator) is still readable. READ-ONLY: resumes, rebuilds and creates nothing, so the native-resume contract is unchanged. BOUND-REFUSED, at least as strict as list_failed_restores — the history is transcript content, more sensitive than the roster's cwd. Replies with a degraded, schema-valid failed_restore_history carrying ok:false+refused+code, not an error
384
+ * { type: 'list_archived_sessions' } — provider-neutral session archive: the roster of ended sessions whose chroxy-held history was kept (closed, idle-timed-out, stale at boot, dismissed/expired failed restores). READ-ONLY. BOUND-REFUSED like get_failed_restore_history (rows carry cwd and the names of sibling sessions); replies with a degraded, schema-valid archived_sessions_list carrying refused+code, not an error
385
+ * { type: 'get_archived_session_history', archiveId, offset?, limit? } — read one page (oldest first; limit clamped 1..100, default 50, ~256 KiB per page) of an archived session's history. READ-ONLY: resumes and creates nothing. BOUND-REFUSED before the archiveId is validated or looked up. archiveId is a server-generated token; only a known one is accepted and no path is ever built from client input
386
+ * { type: 'delete_archived_session', archiveId? | all: true } — remove one archive record, or all of them. Touches only archive records (no live session, no failed restore). BOUND-REFUSED. Exactly one of archiveId / all:true
387
+ * { type: 'restore_archived_session', archiveId, mode: 'native' | 'new_thread' } — #8866 continue an archived session, on an explicit request only. native resumes the SAME conversation (the boot / retry recipe) and the record leaves the archive (released, no tombstone); new_thread starts a NEW session in the archived cwd/provider/model (no permissionMode, sandbox, locator or worktree carried; container binding kept or refused) that carries a bounded (32 KiB) transcript of the archived history with its FIRST user message, and the record stays. BOUND-REFUSED before the archiveId is validated or looked up
388
+ * { type: 'set_session_archive_policy', enabled, maxEntries, maxAgeDays, maxMegabytes, purge?, requestId? } — #8869 replace the archive retention policy of the running daemon (retention re-runs now) and persist it to config. All four fields required and validated like the sessionArchive config block (maxEntries above 1000 is rejected, not clamped); purge:true (delete every existing archive) is only valid with enabled:false. UNBOUND-ONLY (BOUND-REFUSED, the delete_archived_session bar)
350
389
  *
351
390
  * Server -> Client:
352
391
  * All session-scoped messages include a `sessionId` field for background sync.
353
- * { type: 'auth_ok', clientId, serverMode, serverVersion, latestVersion, serverCommit, cwd, defaultCwd, connectedClients, encryption, resultTimeoutMs, hardTimeoutMs, streamStallTimeoutMs } — auth succeeded (encryption: 'required'|'disabled'; resultTimeoutMs = soft-warning window in ms, hardTimeoutMs = hard-kill window in ms, streamStallTimeoutMs = stream-stall recovery window in ms (0 = disabled) — #3760, #3905, #4477)
354
- * { type: 'key_exchange_ok', publicKey } — server's ephemeral X25519 public key (E2E encryption)
355
- * { type: 'auth_bootstrap', providers, slashCommands, agents, sessionId?, tunnelUrl? } — #5555: connect-time burst folding the provider/slash-command/agent lists so a new client skips its 3-request list_* round trip; tunnelUrl re-advertises the live public URL (sub-item 7)
392
+ * Field lists below are PINNED to the protocol schemas by tests/ws-outbound-coverage.test.js (#7107):
393
+ * every schema-backed line must name every field of its Server*Schema (bar `type` and the
394
+ * broadcaster-injected `sessionId`) and nothing the schema lacks, and a `?` must be optional in
395
+ * the schema. Fields a producer sends that the schema does not declare are the checked
396
+ * ROSTER_FIELDS_SCHEMA_LACKS list in that test. Lines whose type has no schema are unpinned.
397
+ * { type: 'auth_ok', clientId, serverMode, serverVersion, latestVersion, dashboardBuildId?, serverCommit, cwd, defaultCwd, connectedClients, encryption, protocolVersion, minProtocolVersion, maxProtocolVersion, webFeatures, features, capabilities?, availablePermissionModes?, availablePermissionModesProvider?, resultTimeoutMs, hardTimeoutMs, streamStallTimeoutMs, exposure?, billingCanary?, serverPublicKey?, serverKeySig?, newIdentityKey?, rotationCert? } — auth succeeded (encryption: 'required'|'disabled'; resultTimeoutMs = soft-warning window in ms, hardTimeoutMs = hard-kill window in ms, streamStallTimeoutMs = stream-stall recovery window in ms (0 = disabled) — #3760, #3905, #4477)
398
+ * { type: 'key_exchange_ok', publicKey, serverKeySig?, newIdentityKey?, rotationCert? } — server's ephemeral X25519 public key (E2E encryption)
399
+ * { type: 'auth_bootstrap', providers, slashCommands, agents, defaultProvider?, sessionId?, tunnelUrl?, sessionToken?, credentialConfirmation? } — #5555: connect-time burst folding the provider/slash-command/agent lists so a new client skips its 3-request list_* round trip; tunnelUrl re-advertises the live public URL (sub-item 7)
400
+ * { type: 'provider_runtime_info', sessionId, provider, binaryVersion, binaryPath?, newerBinary?, rejectedModels?, inputRequiresReady, capabilities, customization, projectInstructions } — #7745/#7835 live provider identity plus bounded customization and instruction-delivery evidence; resent on connect, switch, reconnect and late join, then refreshed on ready
356
401
  * { type: 'tunnel_url_changed', url, previousUrl? } — #5555 (sub-item 7): quick-tunnel recovery rotated the public URL; clients repoint their stored endpoint. Best-effort for tunnel-connected clients (their socket rode the now-dead old tunnel); durable recovery is auth_bootstrap.tunnelUrl on reconnect
357
402
  * { type: 'auth_fail', reason: '...' } — auth failed
358
403
  * { type: 'server_mode', mode: 'cli' } — which backend mode is active
359
- * { type: 'message', ... } — parsed chat message
360
- * { type: 'stream_start', messageId: '...' } — beginning of streaming response
361
- * { type: 'stream_delta', messageId, delta } — token-by-token text
362
- * { type: 'stream_end', messageId: '...' } — streaming response complete
404
+ * { type: 'message', messageType, content, tool?, options?, timestamp, code?, subtype?, compactMetadata?, mcpPromptExpansion?, messageId?, attemptedResumeId?, authCause?, stdout?, stderr?, timeoutMs?, retrySafe?, delivery?, kind?, thinkingDurationMs?, thinkingTokens?, thinkingPrecedes?, splits?, historySeq? } — parsed chat message
405
+ * { type: 'input_ack', sessionId, clientMessageId, status, delivery, retrySafe, retentionExpiresAt?, dedupScope, acceptedAt?, reason?, message?, context? } — #7822 correlated input validation/queue acceptance; never provider completion
406
+ * { type: 'stream_start', messageId: '...', serverTs?, thinking?, thinkingPrecedes? } — beginning of streaming response
407
+ * { type: 'stream_delta', messageId, delta, serverTs?, thinking? } — token-by-token text
408
+ * { type: 'stream_end', messageId: '...', serverTs?, thinking?, thinkingDurationMs?, thinkingTokens? } — streaming response complete
363
409
  * { type: 'terminal_output', sessionId, data } — #5835 live claude-tui PTY mirror (raw, ANSI-intact, coalesced ~50ms); emitted from ws-forwarding.js to clients that opted in via terminal_subscribe; the remote-viewer / authenticity surface
364
410
  * { type: 'terminal_size', sessionId, cols, rows } — #5835 Phase 2 authoritative live-PTY grid size; sent to a client on terminal_subscribe and broadcast to all terminal subscribers on a primary-driven terminal_resize so observers re-letterbox to the same grid
365
- * { type: 'tool_start', messageId, toolUseId, tool, input, serverName? } — tool invocation (serverName present for MCP tools)
411
+ * { type: 'tool_start', messageId, toolUseId, tool, input, serverName?, timestamp?, historySeq? } — tool invocation (serverName present for MCP tools)
366
412
  * { type: 'tool_input_delta', messageId, toolUseId, partialJson } — #4080/#4081: incremental partial JSON for the streaming tool_use `input`; concatenate per-toolUseId for the live bubble preview
367
- * { type: 'tool_result', toolUseId, result, truncated, images?, isError? } — tool result (images: [{mediaType, data}]; #6712 isError flags a failed tool for the error affordance)
413
+ * { type: 'tool_result', toolUseId, result, truncated, images?, isError?, terminatedReason?, input?, timestamp?, historySeq? } — tool result (images: [{mediaType, data}]; #6712 isError flags a failed tool for the error affordance)
368
414
  * { type: 'mcp_servers', servers: [{ name, status, enabled?, canToggle?, authUrl? }] } — configured MCP servers (#6824: enabled + canToggle per-server; BYOK lane sets canToggle:true so clients render the enable/disable toggle; status 'disabled' = parked; #6822: status 'oauth-required' + authUrl surfaces the browser authorization URL a remote server needs)
369
- * { type: 'result', ... } — query stats
415
+ * { type: 'result', cost?, duration?, usage?, queueLength?, contextOccupancy?, turnOutcome?, timestamp?, historySeq?, replayed? } — query stats; #8965 replayed:true marks a result the server is replaying from history; #7326 turnOutcome? ('completed'|'truncated'|'refused'|'stopped'|'interrupted'|'stopped_before_output') says how the turn ended, timestamp? is the marker's identity for the marked ones
370
416
  * { type: 'status', connected: true } — connection status
371
- * { type: 'claude_ready' } — Claude Code ready for input
417
+ * { type: 'claude_ready', backgroundTasks?, scheduledWakeup? } — Claude Code ready for input
372
418
  * { type: 'model_changed', model: '...' } — active model updated
419
+ * { type: 'thinking_level_changed', level: '...', effective?: '...'|null, sessionId? } — #7803 active thinking/reasoning level updated (four senders, one builder in thinking-level-wire.js: ws-history.js's reconnect/tab-switch replay, settings-handlers.js after an accepted set_thinking_level, event-normalizer.js's `ready` burst for the level a fresh codex session booted at, and event-normalizer.js's own entry for a level the session changed or learned). #8700: `effective` is the level the provider reports it applied, sent only by a provider declaring `capabilities.thinkingLevelEffective` (claude-sdk: Claude Code's applied effort); null = not reported yet
373
420
  * { type: 'available_models', models: [...], provider?, defaultModel? } — models the active provider accepts
374
421
  * { type: 'permission_input', requestId, found, tool?, input?, error? } — #6543 (IDE P3 feature B) reply to a `get_permission_input` pull: the FULL secret-redacted tool input for a pending permission (the `permission_request` broadcast truncates `input` at ~10K), so a client can build a per-hunk pre-write diff. `found:false` (+ `error`) when the request is unknown / already resolved / owned by another session — the handler is session-bound (a client only gets input for a permission its session owns).
375
422
  * { type: 'permission_audit_result', entries } — #6772 reply to a `query_permission_audit` pull: recent permission audit entries (mode changes / session-rule changes / allow-deny decisions) matching the query's optional sessionId/auditType/since/limit. Consumed by the dashboard's per-session "Permission history" view.
376
- * { type: 'permission_request', requestId, tool, description, input, remainingMs } — permission prompt
423
+ * { type: 'permission_request', requestId, tool, description, input, remainingMs, floored, explicitConsent?, nonDelegable?, toolUseId? } — permission prompt and consent policy; `toolUseId` (#8357) is the provider's id for the tool call, sent on a hook-routed prompt whose payload names it, and is the same id the AskUserQuestion `user_question` carries
424
+ * { type: 'permission_resolved', decision, requestId?, toolUseId?, reason?, scope?, resolvedBy?, sessionId? } — a pending permission prompt was resolved (broadcast so every client drops its card). `requestId` names a tool-permission prompt; `toolUseId` instead names a superseded AskUserQuestion (#8470), never both. `reason` says why (#8374: 'stopped' vs a user deny); `scope: 'session'` marks an "Allow for Session" answer (#8517); `resolvedBy` ({ kind: 'user'|'agent'|'rule'|'timeout'|'auto_mode'|'abort'|'cleared', label? }, #9119) says WHAT resolved it as a class, never a token, client id or device name (`agent`, with the operator's principal label, is reserved for S15 and not produced yet; `rule` resolves before a prompt exists and is not produced either)
377
425
  * { type: 'confirm_permission_mode', mode, warning } — server challenges auto mode (client must re-send with confirmed: true)
378
426
  * { type: 'permission_mode_changed', mode: '...' } — permission mode updated
379
- * { type: 'available_permission_modes', modes: [...] } — permission modes
427
+ * { type: 'available_permission_modes', modes: [...], provider? } — permission modes for ONE provider (#8224: `provider` names it; clients file the roster under it and derive the active session's picker, so a session of a provider that has no roster yet never inherits another provider's "Plan (unavailable)"). Sent with the connect burst and by `sendSessionInfo` for every session surfaced to a client
380
428
  * { type: 'session_list', sessions: [...] } — all sessions
381
- * { type: 'session_switched', sessionId, name, cwd, conversationId?, sessionPreset? } — switched active session. On a fresh create-confirm `sessionPreset` (#5553) discloses the resolved per-repo preset (length-only preamble — the text is already folded into the prompt server-side — plus the seed staged editable into the composer + trust metadata); omitted when the session has no preset.
382
- * { type: 'session_created', sessionId, name } — new session created
429
+ * { type: 'session_switched', sessionId, name, cwd, conversationId?, agentConnection?, sessionPreset?, requestId? } — switched active session. #7977: the create-confirm echoes the `create_session` `requestId` when one was sent; a re-home/switch never carries one. On a fresh create-confirm `sessionPreset` (#5553) discloses the resolved per-repo preset (length-only preamble — the text is already folded into the prompt server-side — plus the seed staged editable into the composer + trust metadata); omitted when the session has no preset.
383
430
  * { type: 'session_destroyed', sessionId } — session removed
384
- * { type: 'session_stopped', sessionId?, code? } — user-initiated Stop confirmation (#4756); CliSession emitted `stopped` after a clean SIGINT exit; pairs with the louder `session_error` crash toast
385
- * { type: 'session_restore_failed', sessionId, name, provider, cwd?, model?, permissionMode?, errorCode, errorMessage, originalHistoryPreserved, historyLength? }
431
+ * { type: 'session_stopped', sessionId?, code? } — user-initiated Stop confirmation (#4756); CliSession emitted `stopped` after a clean SIGINT exit; pairs with the louder `session_error` crash toast; #8497: on a turn that ended without a `result` the server follows it with `agent_idle` and a `session_activity` isBusy=false so the client leaves busy
432
+ * { type: 'session_restore_failed', sessionId, name, provider, cwd?, model?, permissionMode?, errorCode, errorMessage, originalHistoryPreserved, historyLength?, agentConnection? }
386
433
  * — session in persisted state could not be restored (e.g. missing env var); history kept on disk for retry
387
434
  * { type: 'session_persist_failed', sessionId, name|null }
388
435
  * — a session-list mutation (create/rename/destroy) could not be flushed to disk and will be lost on restart (#5714).
389
436
  * `name` is null on the destroy path where the entry was already removed before the flush.
390
- * { type: 'session_error', message, category?, sessionId?, recoverable? } — session operation error
391
- * { type: 'history_replay_start', sessionId, fullHistory?, truncated? } — beginning of history replay
392
- * { type: 'history_replay_end', sessionId } — end of history replay
437
+ * { type: 'failed_restores_list', generatedAt, restores[], refused?, code? } — #7625 reply to list_failed_restores. Per-row shape matches session_restore_failed (both built from getFailedRestores()); historyLength only, never the history itself. `refused: true` is the bound-client degraded snapshot, and is what distinguishes a refusal from a genuinely empty roster. DASHBOARD-ONLY (PLATFORM_SPECIFIC), like the environment_* family
438
+ * { type: 'retry_failed_restore_result', sessionId, ok, code?, message? } — #7625 reply to retry_failed_restore. code FAILED_RESTORE_NOT_FOUND means the entry was already gone (a concurrent retry won, or the 30-day TTL pruned it) — i.e. a stale button, deliberately distinguishable from a retry that ran and re-failed. `ok` reflects the SETTLED provider start (#8861): `ok:true` means start() resolved or is still pending after the settle timeout, and `ok:false` covers a start() that rejected within it (code = the provider's error code, default START_FAILED). A re-failure ALSO arrives as a fresh session_restore_failed broadcast (followed by a session_list refresh). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
439
+ * { type: 'failed_restore_history', sessionId, ok, total?, offset?, entries?[], refused?, code?, message? } — #8860 reply to get_failed_restore_history. entries are saved history entries oldest-first, each through the persistence truncation with server bookkeeping (_seq) dropped; offset echoes the page start served. code FAILED_RESTORE_NOT_FOUND = entry already gone (stale view); refused:true = bound-client degraded reply. DASHBOARD-ONLY (PLATFORM_SPECIFIC)
440
+ * { type: 'archived_sessions_list', generatedAt, policy{enabled,maxEntries,maxAgeDays,maxMegabytes}, sessions[], truncated?, refused?, code? } — reply to list_archived_sessions. sessions are newest-first rows of typed metadata only (archiveId, sessionId, name, provider, cwd, model, reason, archivedAt, lastActivityAt, createdAt, historyLength, bytes), never transcript content. truncated:true means the roster was cut to fit one frame (512 KiB of rows, newest first; older sessions exist but are not listed). refused:true is the bound-client degraded snapshot. DASHBOARD-ONLY (PLATFORM_SPECIFIC)
441
+ * { type: 'archived_session_history', archiveId, ok, total?, offset?, entries?[], refused?, code?, message? } — reply to get_archived_session_history; entries use the failed_restore_history entry shape and bounds. code ARCHIVED_SESSION_NOT_FOUND = unknown id or the record aged out / was deleted. DASHBOARD-ONLY (PLATFORM_SPECIFIC)
442
+ * { type: 'delete_archived_session_result', ok, deleted, archiveId?, refused?, code?, message? } — reply to delete_archived_session; deleted is the number of records removed. ok:false codes: ARCHIVED_SESSION_NOT_FOUND (no such record), ARCHIVED_SESSION_DELETE_FAILED (the record could not be unlinked and is still on disk), ARCHIVED_SESSIONS_DELETE_PARTIAL (all:true; deleted went, the rest remain). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
443
+ * { type: 'restore_archived_session_result', archiveId, mode?, ok, sessionId?, seed?{messagesIncluded,messagesTotal,bytes}, refused?, code?, message? } — reply to restore_archived_session; sessionId is the live session (switch to it). seed (new_thread) says how much of the transcript rides with the first message. The roster rows of archived_sessions_list also carry restore{native,nativeReason?,newThread,newThreadReason?} (advisory, cheap checks). ok:false codes: ARCHIVED_SESSION_NOT_FOUND, ARCHIVED_SESSION_INVALID, ARCHIVE_RESTORE_PROVIDER_UNAVAILABLE, ARCHIVE_RESTORE_FORBIDDEN_USER_SHELL, ARCHIVE_RESTORE_CWD_MISSING, ARCHIVE_RESTORE_NATIVE_UNSUPPORTED, ARCHIVE_RESTORE_LOCATOR_MISSING, ARCHIVE_RESTORE_ALREADY_LIVE (sessionId names the live/parked owner of that conversation), ENVIRONMENT_UNAVAILABLE, provider start codes, ARCHIVED_SESSION_FORBIDDEN_BOUND_CLIENT (refused:true). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
444
+ * { type: 'session_archive_policy_result', ok, policy?{enabled,maxEntries,maxAgeDays,maxMegabytes}, deleted?, requestId?, refused?, code?, message? } — reply to set_session_archive_policy; policy is what is now in force. ok:false codes: SESSION_ARCHIVE_POLICY_INVALID, SESSION_ARCHIVE_POLICY_PERSIST_FAILED (nothing applied), SESSION_ARCHIVE_PURGE_PARTIAL (policy applied, some records could not be removed), SESSION_ARCHIVE_POLICY_FORBIDDEN_BOUND_CLIENT (refused:true). DASHBOARD-ONLY (PLATFORM_SPECIFIC)
445
+ * { type: 'folder_trust_state', sessionId, status, summary?{files,mcpServers,hooks,statusLine,enabledPlugins,counts,warnings,hasCommandBearingFiles,untrustable}, digest?, appliesFrom, launchedWithProject? } — whether the session folder's project settings load: status trusted|untrusted (every folder starts untrusted, one with nothing command-bearing included); summary (commands and args, environment KEYS only) and digest are removed for a session-bound client; appliesFrom next_turn (claude-sdk) | restart (claude-cli, claude-tui, docker variants); a provider that does not run claude gets no frame. launchedWithProject (restart providers only): whether the RUNNING process was launched with project settings, which it keeps until it restarts. Sent when a session is ready, on subscribe/switch, and after a trust change. Handled by both clients.
446
+ * { type: 'folder_trust_result', sessionId, ok, status, error?, requestId? } — reply to trust_folder / untrust_folder to the requester; status is the folder's state after the change. Handled by both clients.
447
+ * { type: 'session_error', message, category?, sessionId?, recoverable?, code?, reason?, requestId?, boundSessionId?, boundSessionName?, primaryClientId?, attemptedSessionId?, activityId? } — session operation error
448
+ * { type: 'history_replay_start', sessionId, fullHistory?, truncated?, conversationId?, latestSeq? } — beginning of history replay
449
+ * { type: 'history_replay_end', sessionId, latestSeq? } — end of history replay
450
+ * { type: 'tool_input_backfill', sessionId, messageId, toolUseId?, input } — delta replay only, capability history_tool_input_backfill_v1: the input of a held tool card that has none (no historySeq; reconcile-only)
393
451
  * { type: 'conversation_id', sessionId, conversationId } — SDK conversation ID for session portability
394
- * { type: 'user_question', toolUseId, questions } — AskUserQuestion prompt from Claude
452
+ * { type: 'user_question', toolUseId, questions, timestamp?, historySeq?, interrupted?, superseded? } — AskUserQuestion prompt from Claude
395
453
  * { type: 'agent_busy' } — agent started processing (per-session)
396
454
  * { type: 'agent_idle' } — agent finished processing (per-session)
397
455
  * { type: 'plan_started' } — Claude entered plan mode (transient)
@@ -399,11 +457,12 @@ function _isSecureRequest(req) {
399
457
  * { type: 'inactivity_warning', messageId, idleMs, prefab } — soft check-in prompt, session stays alive (#3899)
400
458
  * { type: 'multi_question_intervention', toolUseId, questionCount, reason, timestamp } — chroxy permission-hook denied a multi-question AskUserQuestion (#4653)
401
459
  * { type: 'server_shutdown', reason, restartEtaMs } — server shutting down (reason: 'restart'|'shutdown')
402
- * { type: 'server_status', message } — non-error status update (e.g., recovery)
403
- * { type: 'server_error', category, message, recoverable, sessionId? } — server-side error forwarded to app
404
- * { type: 'directory_listing', path, parentPath, entries, error } — directory listing response for file browser
460
+ * { type: 'server_status', message, phase?, tunnelMode?, tunnelUrl?, attempt?, maxAttempts? } — non-error status update (e.g., recovery)
461
+ * { type: 'server_error', category?, message, recoverable, correlationId?, sessionId? } — server-side error forwarded to app
462
+ * { type: 'directory_listing', path, parentPath, entries, error, requestId? } — directory listing response for file browser (requestId echoes the request's, when it carried one)
463
+ * { type: 'git_repo_check_result', path, isGitRepo, requestId? } — is the New Session dir a git repo (true/false, null = cannot tell) (#8972)
405
464
  * { type: 'file_listing', path, parentPath, entries, error } — file browser listing response
406
- * { type: 'file_content', path, content, language, size, truncated, error } — file content response
465
+ * { type: 'file_content', path, content, language, size, truncated, error, requestId? } — file content response
407
466
  * { type: 'symbols_snapshot', path, symbols: [{ name, kind, file, line, exported }], truncated, error } — #6471 workspace symbol table (opt-in IDE, features.ide; dashboard-only v1)
408
467
  * { type: 'symbol_location', symbol, file, line, error } — #6475 go-to-definition result (opt-in IDE, features.ide; dashboard-only v1)
409
468
  * { type: 'code_search_results', query, results: [{ file, line, column, text }], truncated, error } — #6474 find-in-project results (opt-in IDE, features.ide; dashboard-only v1)
@@ -418,14 +477,17 @@ function _isSecureRequest(req) {
418
477
  * { type: 'checkpoint_restored', checkpointId, mode, newSessionId?, name?, filesOnly? } — checkpoint restored (#6766/#6767: mode 'files' keeps the current session — no newSessionId, name = the checkpoint's name; 'conversation'/'both' create + re-home to a rewound session, name = its name; filesOnly true = working tree only, conversation NOT branched)
419
478
  * { type: 'primary_changed', sessionId, clientId } — last-writer-wins primary changed (null on disconnect)
420
479
  * { type: 'session_role', sessionId, primaryClientId } — #5589/#5281: explicit primary-ownership; client derives its role (primary iff primaryClientId === own clientId, observer if another holds it, null = unclaimed)
421
- * { type: 'pong' } — heartbeat response
480
+ * { type: 'pong', serverTs? } — heartbeat response
422
481
  * { type: 'permission_expired', requestId, sessionId, message } — permission response could not be routed (expired/handled)
423
- * { type: 'token_rotated', token?, expiresAt, reason? } — API token changed. Scheduled rotation carries the new `token` to encrypted clients (transparent re-key, sessions survive). A `reason: 'revoke'` (#6006) carries NO token: the operator revoked, so the server severed user-shell sessions and cleared this connection's auth — the client must re-authenticate with the current token (obtained out-of-band). #6965: for a revoke this message is WITHHELD until the daemon's token persist reports success, so the ack can never precede the revocation being stored — that persist is an fsync of the temp file + containing directory on the `config.json` fallback, while on the OS-keychain path (the macOS/libsecret default) durability is delegated to the keychain and no fsync is performed here. If the persist FAILS the connection receives an `error` with `code: 'REVOKE_NOT_DURABLE'` FIRST and then this message anyway: enforcement already ran unconditionally, so the client must still re-authenticate — the message carries no token and makes no durability claim, and the caveat rides the error. #7053: the wait is BOUNDED (`REVOKE_ACK_TIMEOUT_MS`), because an `onPersist` that never settles would otherwise emit nothing at all and make the panic button look like a no-op; on timeout the connection gets `code: 'REVOKE_DURABILITY_UNKNOWN'` — deliberately NOT `REVOKE_NOT_DURABLE`, since a timeout means the outcome is unknown and may still land, not that the write is known to have failed — followed by this message on the same reasoning.
482
+ * { type: 'permission_outcome', requestId, tool, description, outcome, input?, decision?, toolUseId?, sessionId, timestamp, historySeq } — #8348: how a permission prompt ended (outcome 'allowed' | 'denied' | 'expired' | 'stopped'), delivered ONLY inside a history replay so a session switch or reload still shows the prompt, with the same sanitized, capped `input` the live permission_request carried and, on an allowed outcome, which allow was chosen (`decision`: allow | allowSession | allowAlways) (#8503, both absent on older entries); the live permission_request / permission_resolved / permission_expired frames stay transient and are not replayed
483
+ * { type: 'credential_invalidated', reason } — sent just before the server ends a connection whose stored pairing credential is no longer valid (reason: 'revoked' | 'expired' | 'evicted' | 'invalid'); close code 4401 follows. It travels the normal (possibly encrypted) channel, so it is the authenticated evidence a client may forget that credential on; the close code alone is not
484
+ * { type: 'token_rotated', token?, expiresAt, reason? } — API token changed. Scheduled rotation carries the new `token` to encrypted clients that authenticated with the primary token (transparent re-key, sessions survive); session-bound and pairing-issued connections receive no frame, since rotation does not touch their credential. A `reason: 'revoke'` (#6006) carries NO token: the operator revoked, so the server severed user-shell sessions and cleared this connection's auth — the client must re-authenticate with the current token (obtained out-of-band). #6965: for a revoke this message is WITHHELD until the daemon's token persist reports success, so the ack can never precede the revocation being stored — that persist is an fsync of the temp file + containing directory on the `config.json` fallback, while on the OS-keychain path (the macOS/libsecret default) durability is delegated to the keychain and no fsync is performed here. If the persist FAILS the connection receives an `error` with `code: 'REVOKE_NOT_DURABLE'` FIRST and then this message anyway: enforcement already ran unconditionally, so the client must still re-authenticate — the message carries no token and makes no durability claim, and the caveat rides the error. #7053: the wait is BOUNDED (`REVOKE_ACK_TIMEOUT_MS`), because an `onPersist` that never settles would otherwise emit nothing at all and make the panic button look like a no-op; on timeout the connection gets `code: 'REVOKE_DURABILITY_UNKNOWN'` — deliberately NOT `REVOKE_NOT_DURABLE`, since a timeout means the outcome is unknown and may still land, not that the write is known to have failed — followed by this message on the same reasoning.
424
485
  * { type: 'session_warning', sessionId, name, reason, message, remainingMs } — session about to timeout
425
486
  * { type: 'session_timeout', sessionId, name, idleMs } — session destroyed due to idle timeout
426
487
  * { type: 'statusline_output', sessionId, text, active?, truncated? } — #6791: rendered stdout of the user's own Claude Code statusLine script (active:false + empty text clears it)
427
- * { type: 'dev_preview', port, url, sessionId } — dev server preview tunnel opened
488
+ * { type: 'dev_preview', port, url, target?, exposure?, sessionId } — approved HTTP preview opened
428
489
  * { type: 'dev_preview_stopped', port, sessionId } — dev server preview tunnel closed
490
+ * { type: 'dev_preview_status', sessionId, requestId, port, state, reason? } — explicit HTTP preview request lifecycle
429
491
  * { type: 'web_task_created', task } — cloud task launched
430
492
  * { type: 'web_task_updated', task } — cloud task status changed
431
493
  * { type: 'web_task_error', taskId?, message, code?, boundSessionId?, boundSessionName? } — cloud task error
@@ -434,37 +496,39 @@ function _isSecureRequest(req) {
434
496
  * are populated on SESSION_TOKEN_MISMATCH only;
435
497
  * see docs/error-taxonomy.md)
436
498
  * { type: 'web_task_list', tasks } — response to list_web_tasks
437
- * { type: 'diff_result', diff, error? } — git diff result
438
- * { type: 'error', message } — general error message
439
- * { type: 'file_list', path, files, error? } — file listing response
440
- * { type: 'git_branches_result', branches, current, error? } — git branches result
499
+ * { type: 'diff_result', files, error } — git diff result
500
+ * { type: 'error', message, requestId?, code?, fatal?, correlationId?, details?, actualAuthor? } — general error message (actualAuthor: only on the skill_trust_grant INVALID_AUTHOR arm)
501
+ * { type: 'file_list', files, resources, error, sessionId? } — file listing response;
502
+ * files[].path is cwd-relative
503
+ * and '/'-separated on every OS (#7282)
504
+ * { type: 'git_branches_result', branches, currentBranch, error } — git branches result
441
505
  * { type: 'git_commit_result', hash, message, error } — git commit result
442
- * { type: 'git_create_pr_result', url, number, branch, base, error } — in-app PR creation result (#6876; dashboard-only v1)
506
+ * { type: 'git_create_pr_result', url, number, branch, base, error, existingUrl? } — in-app PR creation result (#6876; dashboard-only v1)
443
507
  * { type: 'git_stage_result', error } — git stage result
444
- * { type: 'git_status_result', status, error? } — git status result
508
+ * { type: 'git_status_result', branch, staged, unstaged, untracked, error } — git status result
445
509
  * { type: 'git_unstage_result', error } — git unstage result
446
510
  * { type: 'write_file_result', path, error } — write file result
447
- * { type: 'append_memory_result', path, created, error? } — `#`-quick-append ack (#6861)
448
- * { type: 'memory_stack_result', entries, memoryFile, error?, requestId? } — reply to `memory_read` (#6864, epic #6760): ordered global/project/local CLAUDE.md stack with per-file provenance (+ recursively-resolved @imports, path-confined to the session cwd + ~/.claude) plus the auto-generated MEMORY.md descriptor. Server-only for v1 — no client handler yet; the dashboard/mobile memory-panel consumers are the sibling slices #6867/#6870
449
- * { type: 'log_entry', level, message, timestamp } — server log entry for dashboard
511
+ * { type: 'append_memory_result', path, created, error } — `#`-quick-append ack (#6861)
512
+ * { type: 'memory_stack_result', entries, memoryFile, error, requestId? } — reply to `memory_read` (#6864, epic #6760): ordered global/project/local CLAUDE.md stack with per-file provenance (+ recursively-resolved @imports, path-confined to the session cwd + ~/.claude) plus the auto-generated MEMORY.md descriptor. Server-only for v1 — no client handler yet; the dashboard/mobile memory-panel consumers are the sibling slices #6867/#6870
513
+ * { type: 'log_entry', component, level, message, timestamp, sessionId? } — server log entry for dashboard
450
514
  * { type: 'session_activity', sessionId, isBusy, lastCost } — session busy/idle state change
451
- * { type: 'session_context', sessionId, cwd, conversationId?, ... } — session context data
515
+ * { type: 'session_context', sessionId, gitBranch, gitDirty, gitAhead, projectName } — session context data
452
516
  * { type: 'session_updated', sessionId, name } — session metadata updated
453
- * { type: 'discovered_sessions', sessions } — discovered local Claude sessions
454
517
  * { type: 'pair_fail', reason } — pairing failed
455
518
  * { type: 'pairing_refreshed' } — pairing ID consumed; clients should re-fetch /qr (#2916)
456
519
  * { type: 'pair_request_pending', requestId, verifyCode } — pairing-approval primitive (#5510, epic #5509): ack to the camera-less requester carrying the 6-digit code to DISPLAY. Sent only over the requester's own pre-auth connection; the code travels server→requester only and is never echoed back.
457
520
  * { type: 'pair_pending', requestId, deviceName, verifyCode, expiresAt } — pairing-approval fan-out (#5510) to HOST-LEVEL (unbound) surfaces only; carries the verify code to COMPARE and the attacker-controlled (schema-capped, plain-text) deviceName. Bound/session-scoped clients never receive it.
458
521
  * { type: 'pair_result', requestId, ok, token?, reason? } — pairing-approval terminal result (#5510) to the requester over its still-open connection. On approve `ok: true` + the unbound (host-authority) session token, delivered exactly once and never logged; on deny/expire/disconnect `ok: false` + reason.
459
522
  * { type: 'pair_resolved', requestId, reason } — pairing-approval retraction (#5510) to host-level surfaces so every banner drops a request that was approved/denied/expired/disconnected elsewhere.
460
- * { type: 'rate_limited', message } — client rate-limited
461
- * { type: 'agent_spawned', sessionId, agentId, parentToolId, model } — background agent spawned
462
- * { type: 'agent_completed', sessionId, agentId, parentToolId } — background agent completed
523
+ * { type: 'rate_limited', message, retryAfterMs } — client rate-limited
524
+ * { type: 'agent_spawned', sessionId, toolUseId, description, startedAt } — a Task/Agent subagent spawned. #7340: the field list here read `agentId, parentToolId, model` — three names the emitter has never sent (see event-normalizer's `agent_spawned`); corrected alongside the lifecycle fix. `toolUseId` is the spawning tool_use block's id, and is the key `agent_completed` / `agent_event` correlate on.
525
+ * { type: 'agent_completed', sessionId, toolUseId } — that subagent reached a terminal state: the provider's own terminal signal (the CLI/SDK `task_notification`, byok's child returning, or a cancel), or turn end, whichever comes first. Turn end completes every tracked subagent EXCEPT one whose backgrounding the provider itself confirmed (#7340) — those outlive their turn deliberately, and `task_notification` is then their only finalizer. The exemption applies on the claude-cli path only, where a persistent child can still deliver it; see `_clearMessageState` in base-session.js.
463
526
  * { type: 'agent_event', sessionId, parentToolUseId, eventType, payload } — Task subagent intermediate wire event re-emit (#5016, transient; eventType is one of `tool_start` / `tool_input_delta` / `tool_result` / `stream_delta`)
464
- * { type: 'background_work_changed', sessionId, pending } — pending background shells snapshot changed (#4307, transient; `pending: [{ shellId, command, startedAt }, …]`)
465
- * { type: 'shell_pending_approval', approvalId, hint? } — #6277 host-local user-shell approval: a requested user-shell spawn is HELD pending the host operator's out-of-band approval (`chroxy shell approve <id>`). Informational; dashboard-only banner for v1. The normal `session_switched` confirms on approval, a `session_error` (SHELL_APPROVAL_DENIED) on deny.
527
+ * { type: 'background_work_changed', sessionId, pending, busyReason?, backgroundShellCount? } — pending background shells snapshot changed (#4307, transient; `pending: [{ shellId, command, startedAt }, …]`; #8302: `busyReason` is `'turn'` | `'background-shells'` | `null` and `backgroundShellCount` is the tracker size, quiesced shells included — both omitted when the session cannot be resolved)
528
+ * { type: 'shell_pending_approval', approvalId, hint?, requestId? } — #6277 host-local user-shell approval: a requested user-shell spawn is HELD pending the host operator's out-of-band approval (`chroxy shell approve <id>`). Informational; dashboard-only banner for v1. The normal `session_switched` confirms on approval, a `session_error` (SHELL_APPROVAL_DENIED) on deny.
466
529
  * { type: 'activity_snapshot', sessionId, schemaVersion, entries } — Control Room full activity tree for a session, on subscribe/resync (#5161 schema; emitter #5160; `entries: [{ id, kind, label, status, startedAt, endedAt?, parentId?, outputRef? }, …]`)
467
530
  * { type: 'activity_delta', sessionId, schemaVersion, op, entry } — Control Room incremental activity-entry change (#5161 schema; emitter #5160; `op` is one of `started` / `updated` / `ended`; `entry` is the full node)
531
+ * { type: 'cancel_activity_ack', activityId, sessionId?, requestId? } — positive ack for a `cancel_activity`, echoing the activity (scoped by sessionId, #5277) and the request id so the dashboard can correlate the click; failures arrive as a `CANCEL_ACTIVITY_FAILED` session_error
468
532
  * { type: 'message_queued', sessionId, clientMessageId?, text, queueLength } — a send-while-busy follow-up entered the server's outgoing-message queue (#5936/#5937, transient; mirrors `_outgoingQueue`)
469
533
  * { type: 'message_dequeued', sessionId, clientMessageId?, queueLength, reason } — a queued follow-up left the queue (#5936/#5937/#5943, transient; `reason` is `flush` (auto-sent on turn-complete), `interrupted` (whole queue cancelled by a Stop), or `cancelled` (one item cancelled via `cancel_queued`))
470
534
  * { type: 'host_status_snapshot', requestId?, generatedAt, root, summary, repos, error? } — Control Room Host/Repo Status survey reply (#5171 schema; emitter #5174); reply to a `host_status_request`. Always carries the full snapshot shape (so it is protocol-schema-valid); on failure `repos` is empty, `summary` is zeroed, and an additive `error: { code, message }` annotation is present for the consumer to branch on. `requestId` echoes the request when provided.
@@ -479,21 +543,24 @@ function _isSecureRequest(req) {
479
543
  * { type: 'emulator_action_ack', action, avd?, serial?, requestId?, status } — Control Room Android emulator action ack (#6137, epic #5530); reply to a successful `emulator_action` (boot/kill). The server re-surveys, validates the target (boot → a stopped `avd`, kill → a running `serial`) + state-gates it, runs `emulator -avd` (detached) / `adb emu kill`, and echoes `action` + the relevant `avd`/`serial` (+ `requestId`) plus the resulting `status` ("starting"/"killed"). Failures surface as an EMULATOR_ACTION_FAILED `session_error` echoing the same correlation fields.
480
544
  * { type: 'wsl_status_snapshot', requestId?, generatedAt, available, note, defaultDistro, distros, error? } — Control Room WSL2 distro survey reply (#6138, epic #5530); reply to a `wsl_status_request`. Read-only (Windows hosts). `distros` is the `wsl.exe -l -v` inventory (name/state/version/isDefault); `defaultDistro` names the `*`-marked default. `available:false` (with `note`, empty distros) off Windows / no wsl.exe is a first-class state. Same degraded-snapshot-with-`error` posture as the sibling surveys.
481
545
  * { type: 'wsl_action_ack', action, distro, requestId?, status } — Control Room WSL2 action ack (#6138, epic #5530); reply to a successful `wsl_action` (start/terminate). The server re-surveys `wsl.exe -l -v`, validates the `distro` is enumerated + state-gated (start a non-running distro, terminate a running one), runs `wsl.exe -d <distro> -e true` / `wsl.exe --terminate <distro>`, and echoes `action`/`distro` (+ `requestId`) plus the resulting `status` ("running"/"stopped"). Failures surface as a WSL_ACTION_FAILED `session_error` echoing the same correlation fields.
482
- * { type: 'integration_status_snapshot', requestId?, generatedAt, root, summary, repos, repoMemoryCli?, error? } — Control Room Integrations survey reply (#5499 schema + emitter, epic #5498); reply to an `integration_status_request`. Per-repo repo-memory status (config, cache stats, telemetry report); `repoMemoryCli` notes the once-per-snapshot binary probe. Same degraded-snapshot-with-`error` posture as the host/runner surveys. `requestId` echoes the request when provided.
483
- * { type: 'containers_action_ack', action, environmentId, requestId?, status? } — Control Room container lifecycle action ack (#6134, epic #5530); reply to a successful `containers_action` (stop/restart/destroy). Echoes `action`/`environmentId` (+ `requestId` when provided) and carries the resulting `status` (stopped/running/destroyed). Failures surface as a CONTAINER_ACTION_FAILED `session_error` echoing the same correlation fields.
546
+ * { type: 'integration_status_snapshot', requestId?, generatedAt, root, summary, repos, repoMemoryCli?, ghCli?, error? } — Control Room Integrations survey reply (#5499 schema + emitter, epic #5498); reply to an `integration_status_request`. Per-repo repo-memory status (config, cache stats, telemetry report); `repoMemoryCli` notes the once-per-snapshot binary probe. Same degraded-snapshot-with-`error` posture as the host/runner surveys. `requestId` echoes the request when provided.
547
+ * { type: 'containers_action_ack', action, environmentId, requestId?, status? } — Control Room container lifecycle action ack (#6134, epic #5530); reply to a successful `containers_action` (stop/restart/destroy). Echoes `action`/`environmentId` (+ `requestId` when provided) and carries the resulting `status` (stopped/running/destroyed). Failures surface as a CONTAINER_ACTION_FAILED `session_error` echoing the same correlation fields — including the #7562 live-session destroy refusal, which uses `reason: 'live-sessions'` and is escaped with `force: true` on the request.
484
548
  * { type: 'byok_pool_action_ack', action, requestId?, key?, drained?, evicted?, limits?, configured? } — Control Room BYOK pool mutating action ack (#6135 slice 2, epic #5530); reply to a successful `byok_pool_action` (drain/recycle/resize). Echoes `action` (+ `requestId`/`key` when provided) and carries the result: `drained` (containers evicted by drain/recycle), `evicted` (containers evicted to honor a tightened resize), `limits` (new effective caps after resize), `configured` (the operator-configured cap ceiling resize clamps to). Failures surface as a BYOK_POOL_ACTION_FAILED `session_error` echoing the same correlation fields.
485
549
  * { type: 'simulator_action_ack', action, udid, requestId?, status } — Control Room iOS simulator action ack (#6136 slice 2, epic #5530); reply to a successful `simulator_action` (boot/shutdown). The server re-surveys `xcrun simctl list devices`, validates the `udid` is enumerated + state-gated (boot a non-booted device, shutdown a booted one), runs `simctl <action> <udid>`, and echoes `action`/`udid` (+ `requestId` when provided) plus the resulting `status` ("Booted"/"Shutdown"). Failures surface as a SIMULATOR_ACTION_FAILED `session_error` echoing the same correlation fields.
486
- * { type: 'integration_action_ack', action, repoPath, requestId?, counts } — Control Room Integrations action ack (#5500, epic #5498); reply to a successful `integration_action` (currently `repo_memory_reindex`). Echoes `action`/`repoPath` (+ `requestId` when provided) cloning the cancel_activity_ack correlation contract; `counts` carries the parsed scanned/summarized/fresh/skipped index result, or null when the CLI output was unparseable. Failures surface as an INTEGRATION_ACTION_FAILED `session_error` echoing the same correlation fields.
550
+ * { type: 'integration_action_ack', action, repoPath, requestId?, counts, runId? } — Control Room Integrations action ack (#5500, epic #5498); reply to a successful `integration_action` (currently `repo_memory_reindex`). Echoes `action`/`repoPath` (+ `requestId` when provided) cloning the cancel_activity_ack correlation contract; `counts` carries the parsed scanned/summarized/fresh/skipped index result, or null when the CLI output was unparseable. Failures surface as an INTEGRATION_ACTION_FAILED `session_error` echoing the same correlation fields.
487
551
  * { type: 'skills_inventory_snapshot', requestId?, generatedAt, root, global, globalError?, repos, error? } — Control Room Skills inventory survey reply (#5554 schema + emitter, epic #5159); reply to a `skills_inventory_request`. `global` is the `~/.chroxy/skills/` tier and `repos` the per-repo `.chroxy/skills/` overlays, each entry carrying name/description/activation/trust/hash/installed + usage (lastUsed/count/repos). Skill BODIES never leave the server. Same degraded-snapshot-with-`error` posture as the host/runner/integration surveys; `globalError` / per-repo `error` degrade a single tier without blanking the snapshot. `requestId` echoes the request when provided.
488
552
  * { type: 'mailbox_status_snapshot', requestId?, generatedAt, registrations, recentEvents, error? } — Control Room "Mailbox" tab survey reply (#5914 follow-up); reply to a `mailbox_status_request`. `registrations` is the live agentCommId→session map (each with sessionName/isBusy/isTui) and `recentEvents` a bounded newest-first ring buffer of recent live-interrupt deliveries (to/from/unreadCount/outcome). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
553
+ * { type: 'session_status', sessionId, declaredStatus } — bounded agent-declared status, independent of provider busy state; replayed on session-info delivery.
489
554
  * { type: 'external_sessions_snapshot', requestId?, generatedAt, sessions, error? } — Control Room mission-control external-session survey reply (#5969, epic #5422 phase 4); reply to an `external_sessions_request`. `sessions` lists the LIVE external Claude Code sessions the daemon learned about over `POST /api/events` (#5413) — sessions it did NOT launch — each carrying source/sessionId/name/project/cwd, a read-only `status` ('running'|'idle'), active `subagents`, and `lastActivityTs`. Read-only (no PTY/control handle exists for these). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
490
555
  * { type: 'repo_events_delta', generatedAt, event } — Control Room repo-events LIVE delta (#6536, PR-2 of #5966); server-INITIATED (no request) push of a single newly-buffered repo-event when a GitHub webhook delivery lands, so the pane updates without a Refresh. Host-level: broadcast ONLY to unbound (host-authority) clients — a session-bound (share-a-session) token never receives host repo activity. A client that hasn't run the survey ignores it; a client with a snapshot appends the event (bounded). No `error`/`requestId` — degraded surveys still flow through the pull `repo_events_snapshot`.
491
- * { type: 'repo_events_snapshot', requestId?, generatedAt, events, error? } — Control Room repo-events survey reply (#5966, epic #5422 phase 5); reply to a `repo_events_request`. `events` is the tail (most-recent-last) of the daemon's bounded RepoEventStore — GitHub-webhook activity (push/pull_request/issues/ping) ingested HMAC-verified over `POST /api/github/webhook` (#6468) — each carrying kind/repo/actor/at plus kind-specific branch/action/number/title/url and a pre-rendered `summary`. Read-only; no delta stream (a full snapshot per pull, like the host/mailbox/external surveys). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
556
+ * { type: 'repo_events_snapshot', requestId?, generatedAt, events, activeRepos?, error? } — Control Room repo-events survey reply (#5966, epic #5422 phase 5); reply to a `repo_events_request`. `events` is the tail (most-recent-last) of the daemon's bounded RepoEventStore — GitHub-webhook activity (push/pull_request/issues/ping) ingested HMAC-verified over `POST /api/github/webhook` (#6468) — each carrying kind/repo/actor/at plus kind-specific branch/action/number/title/url and a pre-rendered `summary`. Read-only; no delta stream (a full snapshot per pull, like the host/mailbox/external surveys). Host-level: a session-bound token is refused with an additive `error: { code, message }` on an otherwise-empty (schema-valid) snapshot. `requestId` echoes the request when provided.
492
557
  * { type: 'github_webhook_config', requestId?, generatedAt, configured, source, payloadUrl, lanOnly, note?, recommendedEvents, deliveries, error? } — Control Room repo-events webhook-secret config reply (#6540, item 3 of #6536); reply to a `github_webhook_config_request` and to a `github_webhook_set_secret` / `github_webhook_clear_secret` write. Reports whether an HMAC secret is configured and its `source` ('store'|'env'|'none') — never the value — plus the `payloadUrl` to paste into GitHub (derived from the live tunnel URL, else the LAN address, `lanOnly` + `note` when GitHub can't reach it), the `recommendedEvents`, and the recent-`deliveries` readout (count / last / verify result). Writes are host-authority gated (a session-bound token is rejected with a generic `error`); the read is open to any authenticated client. `requestId` echoes the request when provided.
558
+ * { type: 'session_pr_status', requestId?, sessionId, generatedAt, branch, repo, pr, checks, merge, reason } — the session's pull-request / CI status (#7344, display slice); reply to a `session_pr_status_request`. SESSION-scoped, not host-scoped: a pairing-bound token may ask about the session it is bound to and no other. Assembled from ONE `gh pr list` response (plus git for branch/remote) using the user's existing local `gh auth`, so `checks` and `merge` always describe the same head SHA (`pr.headRefOid`). `checks.state:'none'` means this head produced NO run and is NOT a green; `checks` and `merge` are separate facts and must never be collapsed into one "ready to merge?" badge (21/21 green alongside `mergeStateStatus:'BLOCKED'` is the case that motivated the issue). `pr:null` with `reason:null` is the quiet negative (no open PR for this branch) — on a fork checkout it is BEST-EFFORT, since a transiently-failed upstream widening reports the same shape (#7435; the distinction is held server-side for the CI watcher and not transmitted); `pr:null` with a `reason` means the survey could not determine it, and must never render as an implied green.
559
+ * { type: 'session_pr_threads', requestId?, sessionId, countedAt, prNumber, unresolvedCount, totalCount, truncated, reason } — the unresolved REVIEW-THREAD COUNT for the session's pull request (#7430, on-demand follow-on to #7344); reply to a `session_pr_threads_request`. Same SESSION-scoped authority as `session_pr_status`: a pairing-bound token may ask about the session it is bound to and no other. A SEPARATE message from `session_pr_status` on purpose — the count needs a GraphQL `reviewThreads` read that `gh pr list --json` cannot serve, and since #7426 that survey runs on a daemon-side sweep over every session, so folding the count in would put a second `gh` subprocess on every tick of a background poll for a field only a click wants. This pair is sent by the click and never by the sweep. `countedAt` is its OWN timestamp, not the status snapshot's `generatedAt` — the two go stale on different schedules. `unresolvedCount: 0` means the server COUNTED and found none; `unresolvedCount: null` (always with a `reason`) means it could not find out, and a client MUST render those differently — a missing count printed as "0 unresolved threads" reads as "nothing is blocking this PR", the exact false green this surface exists to prevent. `truncated: true` means more threads exist than one page read, so the count is a LOWER BOUND and a truncated 0 is not a definite zero. `prNumber` names the PR the count describes so a consumer can check it agrees with the PR its `session_pr_status` snapshot names.
493
560
  * { type: 'summarize_session_result', sessionId, summary, truncated?, requestId? } — reply to a `summarize_session` (#5547); the model-written continuation brief built from the session's persisted history, seeded editable into the dashboard's create-session composer. `truncated` flags a windowed history. Failures surface as a SUMMARIZE_FAILED `session_error` echoing `sessionId`/`requestId` (curated message — no token/key material).
494
561
  * { type: 'session_preset_snapshot', cwd, preset: { source, active, trustState, enabled, preamble, seed, preambleLength, seedLength, capped, repoPath } | null, requestId? } — Control Room per-repo session-preset reply (#5553, epic #5159); reply to a host-authority `session_preset_get` / `session_preset_set` / `session_preset_approve` / `session_preset_revoke`. `preset` is null when the repo has no preset. Full preamble + seed text reaches HOST-level clients only (the four requests are rejected for session-bound pairing clients). `requestId` echoes the request when provided.
495
- * { type: 'provider_list', providers } — available providers
496
- * { type: 'byok_credentials_status', requestId?, status, source, masked?, reason? } — BYOK credentials state for the dashboard (#4052)
562
+ * { type: 'provider_list', providers, defaultProvider? } — available providers
563
+ * { type: 'byok_credentials_status', requestId?, status, source, masked?, reason?, fileExists? } — BYOK credentials state for the dashboard (#4052)
497
564
  * { type: 'credentials_status', requestId?, credentials: [{ key, provider, label, kind, status, source, masked?, oauth }], fileExists?, fileError? } — generalized provider-credential status for the dashboard (#3855); masked, value-free; sent to requester + broadcast after set/delete
498
565
  * { type: 'credential_test_result', requestId?, key, ok, error?, model?, latencyMs? } — result of a test_credential ping (#3855)
499
566
  * { type: 'notification_prefs', requestId?, prefs: { categories, devices, quietHours } } — current notification preferences snapshot (#4541/#4542); echoed back on `notification_prefs_get` and broadcast after every `notification_prefs_set`
@@ -507,19 +574,21 @@ function _isSecureRequest(req) {
507
574
  * { type: 'skill_trust_grant_ok', requestId, sessionId, skillName, author } — ack for skill_trust_grant handler (#3297)
508
575
  * { type: 'push_token_error', message } — push token registration error
509
576
  * { type: 'cost_update', sessionId, sessionCost, totalCost, budget } — session cost update (budget-oriented; sessionId injected by _broadcastToSession)
510
- * { type: 'session_usage', sessionId, cumulativeUsage } — per-session cumulative tokens + cost; cumulativeUsage = { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUsd, turnsBilled } (#4072)
577
+ * { type: 'session_usage', sessionId, cumulativeUsage, agentConnection? } — per-session cumulative tokens + cost; cumulativeUsage = { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, costUsd, turnsBilled } (#4072)
511
578
  * { type: 'session_cost_threshold_crossed', sessionId, costUsd, thresholdUsd } — soft "you've spent $X" warning; fires ONCE per session when cumulativeUsage.costUsd >= threshold (#4075)
512
- * { type: 'budget_warning', sessionId, message, ... } — budget approaching limit
513
- * { type: 'budget_exceeded', sessionId, message, ... } — budget exceeded
514
- * { type: 'monthly_budget', month, spentUsd, budgetUsd, percent, warning, exceeded, ... } — machine-wide monthly programmatic-credit meter (#5665); broadcast to ALL clients after each programmatic-credit turn + sent once on connect
515
- * { type: 'web_feature_status', features } — web feature availability
516
- * { type: 'permission_rules_updated', rules } — per-session auto-approval rules changed
517
- * { type: 'extension_message', ... } — opaque extension payload (passthrough, no server handling)
579
+ * { type: 'budget_warning', sessionId, message, sessionCost, budget, percent } — budget approaching limit
580
+ * { type: 'budget_exceeded', sessionId, message, sessionCost, budget, percent } — budget exceeded
581
+ * { type: 'budget_resume_ack', sessionId, wasPaused, requestId? } — ack for a `resume_budget` (#5752), sent to the requester unconditionally; `wasPaused: false` means the session was not paused (no-op, no `budget_resumed` broadcast)
582
+ * { type: 'billing_canary', eraStarted, defaultProvider, defaultBillingClass, warnings } — billing-canary snapshot, broadcast when it changes (including back to all-clear); the same snapshot seeds `auth_ok.billingCanary` for late joiners (#5821)
583
+ * { type: 'monthly_budget', month, spentUsd, budgetUsd, percent, warning, exceeded, turnsBilled, warningPercent, justWarned?, justExceeded?, billingClass? } — machine-wide monthly programmatic-credit meter (#5665); broadcast to ALL clients after each programmatic-credit turn + sent once on connect
584
+ * { type: 'web_feature_status', available, remote, teleport } — web feature availability. CONSUMED, NEVER SENT (#7109): no server code builds this frame (the data ships as `auth_ok.webFeatures`), but both clients dispatch on it through store-core. Not a phantom — keep it.
585
+ * { type: 'permission_rules_updated', sessionId, rules, persistentRules } — per-session auto-approval rules changed
586
+ * { type: 'extension_message', provider, subtype, data? } — opaque extension payload (passthrough, no server handling)
518
587
  * { type: 'environment_created', environmentId, name, status } — environment created
519
588
  * { type: 'environment_list', environments: [...] } — list of all environments
520
589
  * { type: 'environment_destroyed', environmentId } — environment destroyed
521
590
  * { type: 'environment_info', environment: {...} } — single environment details
522
- * { type: 'environment_error', error, environmentId? } — environment operation error
591
+ * { type: 'environment_error', error, environmentId?, code?, sessions? } — environment operation error. `code` is 'DOCKER_IMAGE_NOT_ALLOWED' (image allowlist) or 'ENVIRONMENT_HAS_LIVE_SESSIONS' (#7562 destroy refusal); `sessions` accompanies the latter with the ids still running inside the environment
523
592
  * { type: 'evaluate_draft_result', requestId, verdict?, rewritten?, clarification?, reasoning?, error? } — prompt evaluator response (#3068)
524
593
  * { type: 'prompt_evaluator_changed', sessionId, value: boolean } — per-session promptEvaluator toggle changed (#3185)
525
594
  * { type: 'prompt_evaluator_skip_pattern_changed', sessionId, value: string|null } — per-session evaluator skip pattern changed (#3639)
@@ -531,7 +600,18 @@ function _isSecureRequest(req) {
531
600
  * { type: 'orchestration_runs_snapshot', requestId?, generatedAt, runs: [RunSummary], error? } — orchestration runs-list survey (#6691, dashboard-only v1)
532
601
  * { type: 'orchestration_run_snapshot', requestId?, generatedAt, seq, run: RunDetail|null, error? } — one run's full detail (pull-only; run:null = degraded reply) (#6691)
533
602
  * { type: 'orchestration_run_delta', runId, seq, generatedAt, run?, node?, gate?, timeline? } — live run update pushed to host-level clients; client applies iff seq===held+1 (#6691)
534
- * { type: 'scheduled_tasks', generatedAt, scheduler: { enabled, engineArmed, restartRequired, source }, schedulableProviders, defaultProvider, defaultProviderRefusal, tasks[], requestId?, error? } — #6871 scheduled-task registry snapshot for the dashboard panel; sent to the REQUESTING client only, and re-emitted as the ack for every accepted mutation. Each task carries the engine's own verdicts (providerRefusal / effectivePermissionMode / permissionModeClamped / quarantined) so a client never re-derives a safety decision
603
+ * { type: 'scheduled_tasks', generatedAt, scheduler: { enabled, engineArmed, restartRequired, source }, schedulableProviders, defaultProvider, defaultProviderRefusal, tasks[], unreadableCount?, unreadable?: [{ handle, reason }] (#7079 — load-refused stored entries, never their contents), requestId?, error? } — #6871 scheduled-task registry snapshot for the dashboard panel; sent to the REQUESTING client only, and re-emitted as the ack for every accepted mutation. Each task carries the engine's own verdicts (providerRefusal / effectivePermissionMode / permissionModeClamped / quarantined) so a client never re-derives a safety decision
604
+ * { type: 'daemon_update_status', running, pending, lastDeploy, postponedUntil, requestPending, applying } — #8331 the queued daily-daemon update + last deploy result; sent on auth and on change to STRICT-PRIMARY, UNBOUND clients ONLY
605
+ * { type: 'daemon_update_confirm_required', requestId, target, reasons[], sessions[] } — #8331 reply to restart-now while sessions are busy; nothing was written
606
+ * { type: 'daemon_update_action_result', requestId, action, ok, force?, postponedUntil?, code?, message? } — #8331 outcome of daemon_update_action (codes: NOT_AUTHORIZED, STALE_TARGET, NO_PENDING_UPDATE, APPLYING, WRITE_FAILED, UNAVAILABLE, UNSUPPORTED_ACTION)
607
+ * { type: 'principal_admin_result', requestId, op: 'grant'|'list'|'revoke'|'disable'|'enable', ok, code?, message?, health?, principals?, principalId?, alreadyRevoked?, durable?, disabled? } — #9116 reply to principal_admin_grant|list|revoke|disable|enable, sent ONLY to the strict-primary, loopback requester (codes: NOT_AUTHORIZED, PRINCIPALS_NOT_ENABLED, UNAVAILABLE, BAD_REQUEST, NOT_FOUND, AUDIT_UNAVAILABLE, ALL_DISABLED, PERSIST_FAILED); `grant` always refuses until the audit writer and kill switch land; `revoke` is acknowledged only after the durable write (durable:false = revoked in memory, not confirmed on disk); carries no token and no hash
608
+ * { type: 'principal_subscribed', requestId, sessions: [{ sessionId, journalId, headSeq, gap? }] } — #9118 (S3 of #9112) reply to principal_subscribe, sent ONLY to the agent principal that asked; `gap` ({ reason, fromSeq?, toSeq? }) says the cursor could not be honored exactly (evicted, journal_reset, restart_loss, unknown_cursor)
609
+ * { type: 'principal_event', requestId?, sessionId, journalId, journalSeq, ts, eventType, data, truncated?, replay? } — #9118 one normalized, redacted journal event for a subscribed principal (never raw PTY, never thinking text); `journalSeq` not `seq`: the transport stamps its own `seq` on every frame; replay:true for a replayed event
610
+ * { type: 'principal_live_fence', requestId, sessionId, journalId, journalSeq } — #9118 end of the replay: every event after this journalSeq is live
611
+ * { type: 'principal_gap', requestId?, sessionId, journalId, reason, fromSeq?, toSeq?, ended } — #9118 events the principal cannot get (reason evicted|journal_reset|restart_loss|unknown_cursor) or, with ended:true, a subscription the daemon ended (held_overflow, backpressure): subscribe again
612
+ * { type: 'principal_events_page', requestId, sessionId, journalId, events[], headSeq, cursor, more, gap? } — #9118 reply to principal_events_read (limit <= 200); `cursor` is what the next read passes
613
+ * { type: 'principal_pending_permissions_result', requestId, generatedAt, permissions[{ requestId, sessionId, tool, floored, explicitConsent, nonDelegable, origin: 'in_process'|'hook', createdAt|null, expiresAt|null, description? }], truncated } — #9119 reply to principal_pending_permissions, sent ONLY to the agent principal that asked; at most 100 requests oldest first (`truncated` says more existed); resolved and expired requests are excluded (`generatedAt` is the freshness); `description` is the bounded, sanitised one and is present ONLY when `floored` is false; NEVER the tool input
614
+ * { type: 'principal_sessions_snapshot_result', requestId, generatedAt, sessions[{ sessionId, name, provider, status: { isBusy, busyReason: 'turn'|'background-shells'|null, starting }|null, declaredStatus: { state, summary, next?, blockedOn?, etaMinutes?, decision?, updatedAt, source }|null, model: { requested, observed }|null, blockers[{ code, detail? }], leaseHolder: null (S8), lastActivityAt|null }], truncated } — #9120 reply to principal_sessions_snapshot, sent ONLY to the agent principal that asked; at most 100 rows in request order (`truncated` says more existed); `blockers` is the #8281 handoff-blocker list (EMPTY means nothing can still act; a row whose read failed carries [{ code: 'unavailable' }], never an empty list); no cwd, history, cost or capability field
535
615
  * { type: 'orchestration_action_ack', requestId?, action, runId, gateId? } — terminal success echo for a mutating orchestration action (#6691)
536
616
  *
537
617
  * Encrypted envelope (bidirectional, wraps any message above after key exchange):
@@ -574,11 +654,26 @@ function _isSecureRequest(req) {
574
654
  * - A session operation failed in an expected, user-facing way → `session_error`
575
655
  */
576
656
  export class WsServer {
577
- constructor({ port, apiToken, cliSession, sessionManager, defaultSessionId, authRequired = true, pushManager = null, maxPayload, noEncrypt, keyExchangeTimeoutMs, localhostBypass, tokenManager, pairingManager, serverIdentity = null, maxPendingConnections, backpressureThreshold, environmentManager, orchestrationManager = null, schedulerEngine = null, config = null, diagnosticsRateLimit = null, devicePreferences = null, pagesStore = null, pagesRateLimiter } = {}) {
657
+ constructor({ port, apiToken, cliSession, sessionManager, defaultSessionId, authRequired = true, pushManager = null, maxPayload, noEncrypt, keyExchangeTimeoutMs, localhostBypass, tokenManager, pairingManager, serverIdentity = null, maxPendingConnections, backpressureThreshold, environmentManager, orchestrationManager = null, schedulerEngine = null, sessionCiWatcher = null, daemonUpdate = null, config = null, diagnosticsRateLimit = null, devicePreferences = null, pagesStore = null, pagesRateLimiter, principalStore = null, principalTimers = null, principalJournal = null } = {}) {
578
658
  this.port = port
579
659
  this.apiToken = apiToken
580
660
  this._tokenManager = tokenManager || null
581
661
  this._pairingManager = pairingManager || null
662
+ // #9116: the agent-principal credential store (principal-store.js). Null where the
663
+ // caller built none: then no principal can authenticate and every principal
664
+ // connection (there can be none) is treated as invalid. Timers are injectable so a
665
+ // test can drive the per-connection expiry without waiting.
666
+ this._principalStore = principalStore || null
667
+ this._principalTimers = principalTimers || { setTimeout, clearTimeout }
668
+ // #9118: the daemon-side normalized event journal (principal-journal.js) behind the
669
+ // agent principal's read path. Null where the caller built none: then nothing is
670
+ // journaled and `principal_subscribe` / `principal_events_read` refuse.
671
+ this._principalJournal = principalJournal || null
672
+ this._principalSubscriptions = null
673
+ // Journal only sessions the SessionManager currently holds (never a late frame about a gone one)
674
+ if (this._principalJournal && typeof sessionManager?.getSession === 'function') {
675
+ this._principalJournal.setLiveness((id) => sessionManager.getSession(id) != null)
676
+ }
582
677
  // #5536 — long-lived Ed25519 identity keypair. Its secret half signs each
583
678
  // connection's ephemeral exchange public key (eager + discrete paths) so a
584
679
  // pinned client can verify the exchange key came from this daemon. Null when
@@ -643,13 +738,13 @@ export class WsServer {
643
738
  ? pagesRateLimiter
644
739
  : new RateLimiter({ name: 'pages', windowMs: 60_000, maxMessages: 120, burst: 30 })
645
740
  this.pagesStore = pagesStore || new PagesStore({
646
- pagesDir: join(process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'), 'pages'),
741
+ pagesDir: configPath('pages'),
647
742
  })
648
743
  // #6277: host-local user-shell approval store. The create gate holds a spawn
649
744
  // here when userShell.requireApproval is on; the host operator approves it
650
745
  // out-of-band via the loopback /api/shell routes (or `chroxy shell approve`).
651
746
  this._shellApprovalStore = new ShellApprovalStore()
652
- this._clientSend = createClientSender(log)
747
+ this._clientSend = createClientSender(log, { mayDeliver: (client, message) => this._mayDeliverTo(client, message) })
653
748
  // audit P1-2: when a client's active session changes, re-sync the live
654
749
  // terminal mirror gate for BOTH the session it left and the one it joined.
655
750
  // Without this a client opted into session A's terminal that switches to B
@@ -730,6 +825,15 @@ export class WsServer {
730
825
  // would never fire in production. Cleaned up by `_sessionDestroyedHandler`
731
826
  // so a long-running server doesn't leak entries for destroyed sessions.
732
827
  this._evaluatorIterations = new Map() // sessionId -> iteration count
828
+ // Per-session evaluator-await lock (#3636/#3666). Lives here for the same
829
+ // reason as the counter above: the handler ctx is spread per message, so a
830
+ // lock stored on the ctx itself would be a fresh, empty one every time.
831
+ this._pendingEvaluatorAwaits = new Map() // sessionId -> in-flight promise
832
+ // #7822: bounded process-local input acceptance records. The handler scopes
833
+ // these by session and clientMessageId; session destruction drops the whole
834
+ // bucket. They are intentionally not persisted, so acks describe process
835
+ // retention rather than promising exactly-once across daemon restarts.
836
+ this._inputDedupRecords = new Map() // sessionId -> Map<clientMessageId, record>
733
837
  this._permissionSessionMap = new Map() // requestId -> sessionId (for routing responses to correct session)
734
838
  // #5704: refcount of permission-INDUCED session subscriptions, per client.
735
839
  // clientId -> Map<sessionId, refcount>. _registerPermissionRoute increments
@@ -746,7 +850,7 @@ export class WsServer {
746
850
  this._permissionSubs = new Map() // clientId -> Map<sessionId, refcount>
747
851
  this._hookSecrets = new Set() // per-session hook secrets registered by active CliSessions
748
852
  this._sessionHookSecrets = new Map() // sessionId -> hookSecret (for cleanup on session_destroyed)
749
- this._questionSessionMap = new Map() // toolUseId -> sessionId (for routing question responses)
853
+ this._questionSessionMap = new QuestionRouteMap() // toolUseId -> sessionId (for routing question responses; remembers just-removed routes, #8470)
750
854
  // #5563: primary-ownership now lives on the WsClientManager (sessionId →
751
855
  // primary clientId) with explicit claim/observe/hand-off semantics, not a
752
856
  // last-writer-wins map. `primaryClients` is no longer a server-owned Map;
@@ -766,9 +870,26 @@ export class WsServer {
766
870
  // counts iterate the sessionId→clients index instead of scanning all clients.
767
871
  clientManager: this._clientManager,
768
872
  sendFn,
873
+ // A principal's frames are decided at the delivery point too (the
874
+ // broadcaster's bound-other-session drop would otherwise discard them).
875
+ principalOpts: () => self._principalPolicyOpts(),
876
+ // #9118: every outgoing session-tagged broadcast is offered once to the journal,
877
+ // whoever receives it. The journal decides what is kept.
878
+ journalTap: this._principalJournal ? (msg) => self._principalJournal.record(msg) : undefined,
769
879
  backpressureThreshold: this._backpressureThreshold,
770
880
  backpressureMaxDrops: this._backpressureMaxDrops,
771
881
  })
882
+ if (this._principalJournal) {
883
+ // Delivered by a dedicated per-subscription direct send (principal-subscriptions.js),
884
+ // each frame through `_send` -> `frameForPrincipal`; never by a broadcast.
885
+ this._principalSubscriptions = new PrincipalSubscriptions({
886
+ journal: this._principalJournal,
887
+ send: sendFn,
888
+ maySee: (client, sessionId) => client.authenticated === true &&
889
+ principalMaySee(client, sessionId, 'observe', self._principalPolicyOpts()).ok,
890
+ backpressureBytes: this._backpressureThreshold,
891
+ })
892
+ }
772
893
  const broadcastFn = (msg, filter) => self._broadcast(msg, filter)
773
894
  // Pass explicit workspace root so file ops resolve paths against the
774
895
  // session manager's default cwd instead of falling back to homedir.
@@ -777,8 +898,12 @@ export class WsServer {
777
898
  this._permissions = createPermissionHandler({
778
899
  sendFn,
779
900
  broadcastFn,
780
- validateBearerAuth: (req, res) => self._validateBearerAuth(req, res),
901
+ // Used by POST /permission-response, which limits a scoped token to its
902
+ // own session itself — opt in explicitly.
903
+ validateBearerAuth: (req, res) => self._validateBearerAuth(req, res, { allowScoped: true }),
781
904
  validateHookAuth: (req, res) => self._validateHookAuth(req, res),
905
+ captureBearer: (req) => captureBearer(self, req),
906
+ bearerStillValid: (captured) => bearerStillValid(self, captured),
782
907
  pushManager,
783
908
  pendingPermissions: this._pendingPermissions,
784
909
  permissionSessionMap: this._permissionSessionMap,
@@ -845,6 +970,7 @@ export class WsServer {
845
970
  self._adoptPermissionSubscription(client.id, sid)
846
971
  self._clientManager.unsubscribe(client, sid)
847
972
  },
973
+ isConnectionAuthorized: (client) => self._isConnectionAuthorized(client),
848
974
  setActiveSession: (client, sid) => self._clientManager.setActiveSession(client, sid),
849
975
  // #5563: explicit primary-ownership surface. `updatePrimary` is the
850
976
  // first-input adoption path (claims if unclaimed, no-op if already
@@ -863,6 +989,18 @@ export class WsServer {
863
989
  syncTerminalMirror: (sid) => self._syncTerminalMirror(sid),
864
990
  sendSessionInfo: (ws, sid) => self._sendSessionInfo(ws, sid),
865
991
  replayHistory: (ws, sid, opts) => self._replayHistory(ws, sid, opts),
992
+ // #7340: re-assert a session's live subagents after a replay wiped them.
993
+ reseedActiveAgents: (ws, sid) => self._reseedActiveAgents(ws, sid),
994
+ // #7457: re-assert the questions a session is still blocked on, after a
995
+ // replay's end frame let the client's sweep stamp them '(resolved)'.
996
+ resendPendingQuestions: (ws, sid) => self._resendPendingQuestions(ws, sid),
997
+ // #8340: the permission-card counterpart, for the replay path that ends
998
+ // its own `history_replay_end` outside `replayHistory` (request_full_history).
999
+ // Wired straight to the per-session implementation, NOT through a
1000
+ // `_resendPendingPermissions` method: that name is the legacy `(ws)`
1001
+ // connect-time delegate (test compat), and a same-named wrapper here was
1002
+ // silently shadowed by it, dropping `sid` (unfiltered resend).
1003
+ resendPendingPermissions: (ws, sid) => resendPendingPermissionsForSession(self._historyCtx, ws, sid),
866
1004
  get clients() { return self.clients },
867
1005
  },
868
1006
  sessions: {
@@ -890,6 +1028,13 @@ export class WsServer {
890
1028
  // `revoke_token` handler can fire the operator panic button
891
1029
  // (TokenManager.revoke()). Null when auth is disabled (--no-auth).
892
1030
  get tokenManager() { return self._tokenManager },
1031
+ // #9116: the agent-principal store and the call that ends one principal's
1032
+ // connections (revoke): the strict-primary `principal_admin_*` handlers.
1033
+ get principalStore() { return self._principalStore },
1034
+ get principalJournal() { return self._principalJournal },
1035
+ get principalSubscriptions() { return self._principalSubscriptions },
1036
+ endPrincipalConnections: (selector, reason) => self._endPrincipalConnections(selector, reason),
1037
+ drainPrincipalQueues: (selector) => self._drainPrincipalQueues(selector),
893
1038
  get devPreview() { return self._devPreview },
894
1039
  get webTaskManager() { return self._webTaskManager },
895
1040
  get environmentManager() { return self.environmentManager },
@@ -938,16 +1083,28 @@ export class WsServer {
938
1083
  // default) — the handlers report that as "not armed" rather than hiding
939
1084
  // it. Late-bound so it tracks the server instance.
940
1085
  get schedulerEngine() { return self._schedulerEngine ?? null },
1086
+ // #7427: the SessionCiWatcher. The `session_pr_status_request` handler
1087
+ // feeds its survey snapshot to `observe()`, so opening the dashboard
1088
+ // ARMS the watch rather than waiting on the sweep's five-minute
1089
+ // discovery pass. Null when the watcher is off; the handler no-ops.
1090
+ get sessionCiWatcher() { return self._sessionCiWatcher ?? null },
1091
+ // #8331: the daily-daemon update banner's status + request files.
1092
+ get daemonUpdate() { return self._daemonUpdate ?? null },
941
1093
  },
942
1094
  runtime: {
943
1095
  get draining() { return self._draining },
944
1096
  // Multi-provider data dirs (#2965): computed fresh each access so new
945
1097
  // provider registrations are reflected without restarting the server.
946
1098
  get projectsDirs() { return getProviderDataDirs().map(d => join(d, 'projects')) },
1099
+ // #7828: the same dirs, TAGGED with the provider that owns each, so a
1100
+ // discovered conversation carries its provider instead of being assumed Claude.
1101
+ get transcriptSources() { return getProviderTranscriptSources() },
947
1102
  get userAgentsDirs() { return getProviderDataDirs().map(d => join(d, 'agents')) },
948
1103
  // #3637: stable per-session auto-evaluator iteration counter (#3186).
949
1104
  // See WsServer constructor for the lifecycle rationale.
950
1105
  evaluatorIterations: this._evaluatorIterations,
1106
+ pendingEvaluatorAwaits: this._pendingEvaluatorAwaits,
1107
+ inputDedupRecords: this._inputDedupRecords,
951
1108
  },
952
1109
  }
953
1110
  // Fail loudly if the production ctx ever drifts from the declared shape.
@@ -976,6 +1133,9 @@ export class WsServer {
976
1133
  get serverMode() { return self.serverMode },
977
1134
  serverVersion: SERVER_VERSION,
978
1135
  get latestVersion() { return self._latestVersion },
1136
+ // #8268 — id of the dashboard bundle on disk NOW (re-evaluated per auth_ok, so a
1137
+ // rebuilt dist is seen without a restart). null when no dist is built.
1138
+ get dashboardBuildId() { return getDashboardBuildId() },
979
1139
  get gitInfo() { return self._gitInfo },
980
1140
  get encryptionEnabled() { return self._encryptionEnabled },
981
1141
  // #5536 — identity keypair for signing the eager exchange public key.
@@ -991,9 +1151,10 @@ export class WsServer {
991
1151
  protocolVersion: SERVER_PROTOCOL_VERSION,
992
1152
  minProtocolVersion: MIN_PROTOCOL_VERSION,
993
1153
  get webTaskManager() { return self._webTaskManager },
1154
+ get agentConnections() { return self.config?.agentConnections ?? [] },
994
1155
  send: sendFn,
995
1156
  broadcast: broadcastFn,
996
- getConnectedClientList: () => self._getConnectedClientList(),
1157
+ getConnectedClientList: (forClient) => self._getConnectedClientList(forClient),
997
1158
  get permissions() { return self._permissions },
998
1159
  // #3760: effective inactivity timeout, surfaced in auth_ok so clients
999
1160
  // render their ActivityIndicator timeout warning against the real
@@ -1018,6 +1179,16 @@ export class WsServer {
1018
1179
  // `ide` capability so clients gate IDE UI. Late-bound getter so a test
1019
1180
  // mutating self.config is seen.
1020
1181
  get ideEnabled() { return isIdeFeatureEnabled(self.config) },
1182
+ // #8619: whether the operator has opted in to Auto permission mode
1183
+ // (`allowAutoPermissionMode: true` in the local config) — the same gate
1184
+ // `set_permission_mode` enforces (settings-handlers.js). Surfaced as the
1185
+ // `autoPermissionMode` capability so a client can disable Auto in its
1186
+ // mode pickers and say WHY. Late-bound getter so a test mutating
1187
+ // self.config is seen.
1188
+ get autoPermissionModeAllowed() { return self.config?.allowAutoPermissionMode === true },
1189
+ // Truthful by construction: read off the manager that will actually name the session,
1190
+ // not off the config that was meant to configure it. Late-bound like its neighbours.
1191
+ get projectSessionNames() { return self.sessionManager?.sessionNaming === 'project' },
1021
1192
  // #6691: whether the orchestration harness is enabled on THIS server,
1022
1193
  // surfaced as the `orchestration` capability so the dashboard reveals the
1023
1194
  // Runs surface. Server-wide gate, not token-scoped; fail-closed.
@@ -1038,6 +1209,8 @@ export class WsServer {
1038
1209
  // surfaced in auth_ok so the dashboard can render a warning banner.
1039
1210
  // null until start() has bound a socket.
1040
1211
  get exposure() { return self.exposure },
1212
+ // #8331: the update-banner status, sent post-auth to strict-primary clients only.
1213
+ get daemonUpdate() { return self._daemonUpdate ?? null },
1041
1214
  // #5821: current billing-canary snapshot, seeded into auth_ok so a
1042
1215
  // freshly-connected client renders the billing banner immediately. null
1043
1216
  // until a provider is wired (server-cli sets it post-construct) — live
@@ -1052,6 +1225,23 @@ export class WsServer {
1052
1225
  // letting the client skip its 3-request connect-time round trip.
1053
1226
  get fileOps() { return self._fileOps },
1054
1227
  get userAgentsDirs() { return getProviderDataDirs().map(d => join(d, 'agents')) },
1228
+ // #8151 round-2 review (Critical 1) — `sendAuthBootstrap`
1229
+ // (ws-history.js) reads this to resolve the daemon's actual default
1230
+ // provider (`resolveDaemonDefaultProvider`), the same value
1231
+ // `_handlerCtx.services.config` feeds to the `list_providers`
1232
+ // handler (settings-handlers.js). Before this getter existed,
1233
+ // `_historyCtx` had no `config`/`services` key at all, so
1234
+ // `auth_bootstrap.defaultProvider` was unconditionally
1235
+ // `DEFAULT_PROVIDER` (then claude-tui) in every real connection — the C3
1236
+ // fix's own test only ever built its ctx by hand and never caught
1237
+ // this, because a hand-built ctx is exactly the shape the fix
1238
+ // assumed, not the shape the real server actually produces. Both
1239
+ // ctx objects read the SAME `self.config` — the one property on the
1240
+ // WsServer instance itself — so `provider_list` and `auth_bootstrap`
1241
+ // cannot report two different "daemon default" values again, even
1242
+ // though `_handlerCtx` nests its copy under `services` and this one
1243
+ // is flat (matching this ctx's existing `fileOps`/`tunnelUrl` shape).
1244
+ get config() { return self.config },
1055
1245
  // #5555 (sub-item 7): the current public tunnel URL (wss://), folded into
1056
1246
  // the auth_bootstrap burst so a reconnecting client always re-learns the
1057
1247
  // live URL — the durable recovery path when a quick-tunnel rotation
@@ -1065,6 +1255,7 @@ export class WsServer {
1065
1255
  get authFailures() { return self._authFailures },
1066
1256
  get benignPairAttempts() { return self._benignPairAttempts },
1067
1257
  get pairingManager() { return self._pairingManager },
1258
+ get principalStore() { return self._principalStore },
1068
1259
  // #5536 — identity keypair for signing the discrete exchange public key.
1069
1260
  get serverIdentity() { return self._serverIdentity },
1070
1261
  get activeSessionId() {
@@ -1083,6 +1274,8 @@ export class WsServer {
1083
1274
  },
1084
1275
  send: sendFn,
1085
1276
  onAuthSuccess: (ws, client) => {
1277
+ // #9116: a principal connection ends at its own expiry even if it never sends.
1278
+ if (client.principal != null) self._armPrincipalExpiry(ws, client)
1086
1279
  // If paired, include sessionToken in auth_ok response
1087
1280
  if (client._sessionToken) {
1088
1281
  self._sendPostAuthInfo(ws, { sessionToken: client._sessionToken })
@@ -1118,12 +1311,83 @@ export class WsServer {
1118
1311
  // Multi-session support: prefer sessionManager, fall back to single cliSession
1119
1312
  this.sessionManager = sessionManager || null
1120
1313
  this.environmentManager = environmentManager || null
1314
+ // #7552: a session opening or closing inside a container environment changes
1315
+ // `EnvironmentInfo.sessions`, which the dashboard's Environments panel both
1316
+ // RENDERS ("N connected") and gates its Destroy button on. Nothing else
1317
+ // re-sends the list on session lifecycle — the four `environment_list` emit
1318
+ // sites in feature-handlers.js fire on env list/create/destroy requests
1319
+ // only — so without this the panel would show a stale count for as long as
1320
+ // it stays mounted, and the destroy guard would be deciding from it. Cheap
1321
+ // and quiet: EnvironmentManager emits only on a REAL tag change.
1322
+ if (this.environmentManager && typeof this.environmentManager.on === 'function') {
1323
+ this._environmentSessionsChangedHandler = () => {
1324
+ try {
1325
+ // #7596: fan the environment list to UNBOUND (host) clients only.
1326
+ // This is the most frequent leak path — it fires on every session
1327
+ // open/close — so a plain broadcast would stream the host-level
1328
+ // surface to every bound (share-a-session) listener continuously.
1329
+ broadcastEnvironmentList(
1330
+ (msg, filter) => this._broadcast(msg, filter),
1331
+ this.environmentManager.list(),
1332
+ )
1333
+ } catch (err) {
1334
+ log.warn(`environment_list re-broadcast failed: ${err?.message || err}`)
1335
+ }
1336
+ }
1337
+ this.environmentManager.on('environment_sessions_changed', this._environmentSessionsChangedHandler)
1338
+
1339
+ // #7601: fast-path for a CHROXY-initiated environment stop/restart. The
1340
+ // #7601 liveness poll is the mandatory detector (an EXTERNAL `docker stop`
1341
+ // fires no event), but a `containers_action stop`/`restart` DOES emit here
1342
+ // — so surface CONTAINER_VANISHED on the environment's bound sessions
1343
+ // immediately rather than waiting up to a poll interval. A restart bounces
1344
+ // the container (stop then start), severing every session's `docker exec`
1345
+ // binding, so it surfaces a vanish too (the #7599 message covers "stopped,
1346
+ // restarted, or removed"; #7602 owns the re-attach). Bridged via
1347
+ // `env.sessions` reusing the destroy-with-sessions fan-out shape — NO
1348
+ // SessionManager handle is injected into EnvironmentManager.
1349
+ this._environmentStoppedHandler = ({ id } = {}) => this._surfaceContainerVanishedForEnvironment(id, 'environment_stopped')
1350
+ // #7602: a RESTART ends with the container running again, and `restart()`
1351
+ // has already awaited `docker restart` and set `status: 'running'` before
1352
+ // emitting — so re-attach right here instead of leaving it to the poll.
1353
+ // Order is load-bearing: the vanish must surface FIRST (that is what arms
1354
+ // the latch whose clearing IS the recovery edge). A `stop` gets no
1355
+ // re-attach — its container is, correctly, still down.
1356
+ this._environmentRestartedHandler = ({ id } = {}) => {
1357
+ this._surfaceContainerVanishedForEnvironment(id, 'environment_restarted')
1358
+ try {
1359
+ this.sessionManager?.reattachEnvironmentSessions?.(id, 'environment_restarted')
1360
+ } catch (err) {
1361
+ log.warn(`[environment_restarted] re-attach fan-out failed for env ${id}: ${err?.message || err}`)
1362
+ }
1363
+ }
1364
+ this.environmentManager.on('environment_stopped', this._environmentStoppedHandler)
1365
+ this.environmentManager.on('environment_restarted', this._environmentRestartedHandler)
1366
+ } else {
1367
+ this._environmentSessionsChangedHandler = null
1368
+ this._environmentStoppedHandler = null
1369
+ this._environmentRestartedHandler = null
1370
+ }
1121
1371
  // #6691 (E-4): the OrchestrationManager (null when the feature is off). Its
1122
1372
  // run_delta events are forwarded to host-level clients by server-cli via
1123
1373
  // _broadcastOrchestrationDelta; the handlers read it off ctx.services.
1124
1374
  this._orchestrationManager = orchestrationManager || null
1125
1375
  // #6871: nullable by design — null whenever scheduled execution is disabled.
1126
1376
  this._schedulerEngine = schedulerEngine || null
1377
+ // #7427: the CI watcher, so the on-demand PR-survey handler can arm it.
1378
+ // Null when `sessionCi.watch` is off. The WsServer only hands it to
1379
+ // handlers — it never starts, stops or ticks it (server-cli owns that).
1380
+ this._sessionCiWatcher = sessionCiWatcher || null
1381
+ // #8331: the daily-daemon update status (null unless server-cli built and
1382
+ // started one). Its `change` events fan out to STRICT-PRIMARY, UNBOUND clients
1383
+ // only. close() unsubscribes AND closes it, so every teardown path that closes
1384
+ // this server (shutdown, emergencyCleanup) also stops its watcher and timers.
1385
+ this._daemonUpdate = daemonUpdate || null
1386
+ this._daemonUpdateChangeHandler = null
1387
+ if (this._daemonUpdate && typeof this._daemonUpdate.on === 'function') {
1388
+ this._daemonUpdateChangeHandler = (status) => this._broadcastDaemonUpdateStatus(status)
1389
+ this._daemonUpdate.on('change', this._daemonUpdateChangeHandler)
1390
+ }
1127
1391
  this.defaultSessionId = defaultSessionId || null
1128
1392
  this._checkpointManager = new CheckpointManager()
1129
1393
 
@@ -1136,6 +1400,14 @@ export class WsServer {
1136
1400
  const entry = sessionManager.getSession(sessionId)
1137
1401
  this._registerSessionHookSecretIfMissing(sessionId, entry)
1138
1402
  this._attachPermissionAuditSink(sessionId, entry)
1403
+ // #9118: every create or restore of an id is a NEW incarnation: a fresh journal
1404
+ try { this._principalJournal?.beginIncarnation(sessionId) } catch (err) { log.warn(`principal journal incarnation failed: ${err?.message || err}`) }
1405
+ }
1406
+ // #9118: canonical removal (every destroy path and the restore-rebind branch; never a
1407
+ // daemon shutdown, which does not pass through `_cleanupSessionMaps`): the principal
1408
+ // journal, its sidecar and its subscriptions go with the session.
1409
+ this._sessionRemovedHandler = ({ sessionId }) => {
1410
+ try { this._principalJournal?.removeSession(sessionId) } catch (err) { log.warn(`principal journal removal failed: ${err?.message || err}`) }
1139
1411
  }
1140
1412
  this._sessionDestroyedHandler = ({ sessionId }) => {
1141
1413
  // Look up the stored secret — the session is already removed from the map
@@ -1179,6 +1451,16 @@ export class WsServer {
1179
1451
  // but a long-running server with many session destroys would
1180
1452
  // accumulate dead entries.
1181
1453
  this._evaluatorIterations.delete(sessionId)
1454
+ this._pendingEvaluatorAwaits.delete(sessionId)
1455
+ this._inputDedupRecords.delete(sessionId)
1456
+ // #7450's survey-throttle prune used to live here, keyed on this
1457
+ // EVENT — but #8092 found a teardown path (the restore-rebind branch
1458
+ // of `_handleAsyncStartFailure()`) that removes a session without
1459
+ // ever emitting `session_destroyed`, so an event-based prune missed
1460
+ // it. The prune now lives in `SessionManager._cleanupSessionMaps()`
1461
+ // (and `destroyAll()`, which bypasses that method) instead — the
1462
+ // removal itself, reached by every teardown path rather than only
1463
+ // the ones that happen to fire this particular event.
1182
1464
  }
1183
1465
  // #3057: audit auto-deny resolution paths (timeout / aborted / cleared).
1184
1466
  // The WS inline response path in settings-handlers.js audits user
@@ -1205,6 +1487,7 @@ export class WsServer {
1205
1487
  }
1206
1488
  sessionManager.on('session_created', this._sessionCreatedHandler)
1207
1489
  sessionManager.on('session_destroyed', this._sessionDestroyedHandler)
1490
+ sessionManager.on('session_removed', this._sessionRemovedHandler)
1208
1491
  sessionManager.on('session_event', this._sessionEventAuditHandler)
1209
1492
 
1210
1493
  // Retroactively register hook secrets for sessions that already exist
@@ -1234,10 +1517,14 @@ export class WsServer {
1234
1517
  }
1235
1518
 
1236
1519
  // Dev server preview tunneling
1237
- this._devPreview = new DevPreviewManager()
1520
+ this._devPreview = new DevPreviewManager({ daemonPort: port, authRequired, getSession: id => this.sessionManager?.getSession(id),
1521
+ tunnelConfig: { binaryProvenance: this.sessionManager?._binaryProvenanceOptions?.() } })
1238
1522
 
1239
- // Web task manager (Claude Code Web cloud delegation)
1240
- this._webTaskManager = new WebTaskManager({ cwd: sessionManager?.defaultCwd || process.cwd() })
1523
+ // Web task manager (Claude Code Web cloud delegation). #8039: pass
1524
+ // sessionManager so every spawn (feature detection, launch, teleport)
1525
+ // routes through the verified SessionManager.verifyOneShotExecutable()
1526
+ // gate instead of a bare, unverified `claude` PATH lookup.
1527
+ this._webTaskManager = new WebTaskManager({ cwd: sessionManager?.defaultCwd || process.cwd(), sessionManager })
1241
1528
 
1242
1529
  // Legacy single-session mode: wrap cliSession in a minimal shim
1243
1530
  if (!sessionManager && cliSession) {
@@ -1278,8 +1565,15 @@ export class WsServer {
1278
1565
  this._draining = false
1279
1566
  this._latestVersion = null
1280
1567
 
1281
- // Background version check (non-blocking, skipped in test/CI)
1282
- if (process.env.NODE_ENV !== 'test') {
1568
+ // Background version check (non-blocking, skipped in test/CI). #7265: this
1569
+ // used to be gated on `process.env.NODE_ENV !== 'test'`, but nothing in this
1570
+ // repo's harness or CI ever sets NODE_ENV=test, so the skip never fired and
1571
+ // every WsServer construction in the test suite made a real outbound request
1572
+ // to registry.npmjs.org. Gate on an explicit, harness-set switch instead —
1573
+ // matches the CHROXY_DISABLE_KEYCHAIN / CHROXY_CRED_DISABLE_KEYCHAIN pattern
1574
+ // in tests/_setup.mjs — so this changes exactly one behaviour and can't
1575
+ // re-arm (or fail to arm) any other NODE_ENV gate.
1576
+ if (process.env.CHROXY_DISABLE_UPDATE_CHECK !== '1') {
1283
1577
  checkLatestVersion(packageJson.name).then((v) => { this._latestVersion = v }).catch((err) => {
1284
1578
  log.warn(`Failed to check latest npm version: ${err.message} (non-critical, update check skipped)`)
1285
1579
  })
@@ -1289,6 +1583,7 @@ export class WsServer {
1289
1583
  // authenticated dashboard clients so they can auto-refresh the QR code (#2916).
1290
1584
  this._pairingRefreshedHandler = null
1291
1585
  this._pendingRequestExpiredHandler = null
1586
+ this._sessionTokenRemovedHandler = null
1292
1587
  if (this._pairingManager) {
1293
1588
  this._pairingRefreshedHandler = () => {
1294
1589
  this._broadcast({ type: 'pairing_refreshed' })
@@ -1304,6 +1599,20 @@ export class WsServer {
1304
1599
  this._broadcastPairResolved(requestId, 'expired')
1305
1600
  }
1306
1601
  this._pairingManager.on('pending_request_expired', this._pendingRequestExpiredHandler)
1602
+
1603
+ // A stored pairing token stopped being valid (revoked, expired, evicted):
1604
+ // end every connection that authenticated with it.
1605
+ this._sessionTokenRemovedHandler = ({ token, reason }) => {
1606
+ // Daemon teardown (reason 'destroyed') clears the store from memory only: the
1607
+ // tokens stay valid on disk. _endCredentialConnection sees the destroyed
1608
+ // pairing manager and ends the connection quietly, without a notice.
1609
+ for (const [ws, client] of [...this.clients]) {
1610
+ if (client.pairingCredential != null && client.pairingCredential === token) {
1611
+ this._endCredentialConnection(ws, client, reason)
1612
+ }
1613
+ }
1614
+ }
1615
+ this._pairingManager.on('session_token_removed', this._sessionTokenRemovedHandler)
1307
1616
  }
1308
1617
 
1309
1618
  // Wire TokenManager rotation events — broadcast new token to all clients
@@ -1499,9 +1808,15 @@ export class WsServer {
1499
1808
  // Send the new token to encrypted clients (they need it for reconnection).
1500
1809
  // Unencrypted clients (e.g. localhost dashboard) get the event without the
1501
1810
  // raw token to avoid leaking credentials over plaintext connections.
1811
+ //
1812
+ // The rotated token is the PRIMARY credential, so only a connection that
1813
+ // authenticated with the primary token is told about it. A session-scoped
1814
+ // or pairing-issued connection holds its own stored credential, which
1815
+ // rotation does not touch: it receives nothing and keeps that credential.
1502
1816
  let encrypted = 0, unencrypted = 0
1503
1817
  for (const [ws, client] of this.clients) {
1504
1818
  if (!client.authenticated || ws.readyState !== 1) continue
1819
+ if (!this._holdsPrimaryCredential(client)) continue
1505
1820
  // Carry `reason: 'scheduled'` so the wire is self-describing and
1506
1821
  // matches the documented contract + TokenManager's event payload.
1507
1822
  if (client.encryptionState) {
@@ -1513,7 +1828,9 @@ export class WsServer {
1513
1828
  // and de-auths instead, so a compromised connection can't gain
1514
1829
  // currency this way. Unencrypted clients get no token, so theirs
1515
1830
  // stays stale (they must reconnect) — handled by the else branch.
1516
- client.authToken = newToken
1831
+ // A session-scoped connection was not sent the token (see
1832
+ // outgoing-policy.js), so its recorded credential stays its own.
1833
+ if (!isBoundClient(client)) client.authToken = newToken
1517
1834
  encrypted++
1518
1835
  } else {
1519
1836
  this._send(ws, { type: 'token_rotated', expiresAt, reason: 'scheduled' })
@@ -1555,7 +1872,7 @@ export class WsServer {
1555
1872
  }
1556
1873
  const queryToken = dashUrl.searchParams.get('token')
1557
1874
  const token = queryToken || bearerToken || cookieVal
1558
- if (!token || !this._isTokenValid(token)) {
1875
+ if (!token || !this._isTokenValid(token) || this._isSessionScopedToken(token)) {
1559
1876
  res.writeHead(403, { 'Content-Type': 'text/html', ...securityHeaders })
1560
1877
  res.end('<h1>403 Forbidden</h1><p>Invalid or missing token.</p>')
1561
1878
  return false
@@ -1571,11 +1888,30 @@ export class WsServer {
1571
1888
  return true
1572
1889
  }
1573
1890
 
1891
+ /**
1892
+ * True when `token` is a pairing-issued token bound to one session.
1893
+ * Linking-mode (unbound) session tokens and the primary token are not.
1894
+ */
1895
+ _isSessionScopedToken(token) {
1896
+ const pm = this._pairingManager
1897
+ if (!pm || !token) return false
1898
+ // Fail closed: a manager that cannot report a token's binding is treated
1899
+ // as having bound it. Any stored session id (including an empty string)
1900
+ // counts as bound; only null/undefined is unscoped.
1901
+ if (typeof pm.getSessionIdForToken !== 'function') return true
1902
+ return pm.getSessionIdForToken(token) != null
1903
+ }
1904
+
1574
1905
  /**
1575
1906
  * Validate Bearer token on an HTTP request. Returns true if auth passes
1576
1907
  * (or auth is disabled). On failure, writes a 403 response and returns false.
1908
+ *
1909
+ * A session-scoped token is refused by default: routes guarded by this check
1910
+ * serve host-wide data. A route that a scoped client legitimately calls opts
1911
+ * in with `{ allowScoped: true }` and MUST itself limit the request to the
1912
+ * token's bound session.
1577
1913
  */
1578
- _validateBearerAuth(req, res) {
1914
+ _validateBearerAuth(req, res, { allowScoped = false } = {}) {
1579
1915
  if (!this.authRequired) return true
1580
1916
  const authHeader = req.headers['authorization'] || ''
1581
1917
  const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
@@ -1584,6 +1920,11 @@ export class WsServer {
1584
1920
  res.end(JSON.stringify({ error: 'unauthorized' }))
1585
1921
  return false
1586
1922
  }
1923
+ if (!allowScoped && this._isSessionScopedToken(token)) {
1924
+ res.writeHead(403, { 'Content-Type': 'application/json' })
1925
+ res.end(JSON.stringify({ error: 'session_scoped_token' }))
1926
+ return false
1927
+ }
1587
1928
  return true
1588
1929
  }
1589
1930
 
@@ -1642,6 +1983,7 @@ export class WsServer {
1642
1983
  tokenClass: entry.tokenClass || 'primary',
1643
1984
  deviceName: entry.deviceName,
1644
1985
  clientId: entry.clientId,
1986
+ requestId: entry.requestId || undefined,
1645
1987
  })
1646
1988
  }
1647
1989
 
@@ -1657,6 +1999,7 @@ export class WsServer {
1657
1999
  type: 'session_error',
1658
2000
  code: 'SHELL_APPROVAL_DENIED',
1659
2001
  message: 'The host operator declined this shell.',
2002
+ ...(entry.requestId ? { requestId: entry.requestId } : {}),
1660
2003
  })
1661
2004
  break
1662
2005
  }
@@ -1778,7 +2121,7 @@ export class WsServer {
1778
2121
  }
1779
2122
  // No hook secrets registered — fall back to main token validation
1780
2123
  // (handles legacy single-session setups and tests that don't register secrets)
1781
- if (!this._isTokenValid(token)) {
2124
+ if (!this._isTokenValid(token) || this._isSessionScopedToken(token)) {
1782
2125
  res.writeHead(403, { 'Content-Type': 'application/json' })
1783
2126
  res.end(JSON.stringify({ error: 'unauthorized' }))
1784
2127
  return false
@@ -2037,6 +2380,10 @@ export class WsServer {
2037
2380
  // is safe: an attacker can't strip cloudflared's edge-stamped header to gain
2038
2381
  // the bypass.
2039
2382
  req._chroxyLocalPeer = localPeer
2383
+ // #9116: the strict loopback verdict (socket peer AND no proxy-family hint) taken at
2384
+ // the upgrade. A principal token is accepted only on such a connection; the retained
2385
+ // request is classified again at `auth` (ws-auth.js `isLoopbackConnection`).
2386
+ req._chroxyLoopbackPeer = isLoopbackPeer(req)
2040
2387
  if (localPeer) {
2041
2388
  delete req.headers['sec-websocket-extensions']
2042
2389
  }
@@ -2099,11 +2446,16 @@ export class WsServer {
2099
2446
  // encryption bypass so a tunneled (proxied) connection to socketIp
2100
2447
  // 127.0.0.1 is not treated as trusted-local and still requires E2E.
2101
2448
  localPeer: req._chroxyLocalPeer === true,
2449
+ // #9116: the upgrade request, retained so loopback origin is decided again at
2450
+ // `auth` and on every principal re-check, and the verdict taken at the upgrade.
2451
+ _upgradeReq: req,
2452
+ loopbackAtUpgrade: req._chroxyLoopbackPeer === true,
2102
2453
  // #3404: visible defaults to true; mobile flips to false on backgrounding
2103
2454
  // so completion push notifications fire instead of being suppressed by
2104
2455
  // a still-alive but invisible WS connection.
2105
2456
  visible: true,
2106
2457
  _seq: 0, // monotonic sequence number for outbound messages
2458
+ pairingCredential: null, // stored pairing token this connection authenticated with (null = primary / none)
2107
2459
  encryptionState: null, // { sharedKey, sendNonce, recvNonce } when active
2108
2460
  encryptionPending: false, // true while waiting for key_exchange
2109
2461
  postAuthQueue: null, // queued messages during key exchange
@@ -2153,6 +2505,9 @@ export class WsServer {
2153
2505
  : null
2154
2506
 
2155
2507
  ws.on('message', (raw) => {
2508
+ // Once a close has begun (e.g. after an auth failure) frames already in
2509
+ // flight must not be dispatched.
2510
+ if (ws.readyState !== 1) return
2156
2511
  let msg
2157
2512
  try {
2158
2513
  msg = JSON.parse(raw.toString())
@@ -2195,7 +2550,7 @@ export class WsServer {
2195
2550
  if (client) client.isAlive = true
2196
2551
  if (client?.encryptionState) {
2197
2552
  if (msg.type !== 'encrypted') {
2198
- log.error(`Plaintext frame from ${client.id} after encryption established (type=${msg?.type}); closing connection`)
2553
+ log.error(`Plaintext frame from ${client.id} after encryption established (type=${loggableValue(msg?.type)}); closing connection`)
2199
2554
  ws.close(1008, 'encryption required')
2200
2555
  return
2201
2556
  }
@@ -2270,19 +2625,33 @@ export class WsServer {
2270
2625
  this._startApprovalListener()
2271
2626
  }
2272
2627
 
2273
- // Detect Claude Code Web features (non-blocking)
2628
+ // Detect Claude Code Web features (non-blocking). #7299: detectFeatures()
2629
+ // itself never rejects — every failure mode (a gate refusal, a missing
2630
+ // binary, a timed-out --help) degrades to remote=false/teleport=false and
2631
+ // is logged inside it. The `.catch` stays anyway: it hangs off the promise
2632
+ // `.then()` returns, so it also covers a throw inside the handler and any
2633
+ // rejection path a future change adds. This chain is fire-and-forget, and
2634
+ // an unhandled rejection takes the whole daemon down (#5369), so the catch
2635
+ // is worth keeping even though nothing reaches it today.
2274
2636
  this._webTaskManager.detectFeatures().then(({ remote, teleport }) => {
2275
2637
  if (remote || teleport) {
2276
2638
  log.info(`Claude Code Web features detected: remote=${remote}, teleport=${teleport}`)
2277
2639
  }
2278
2640
  }).catch((err) => {
2279
- log.warn(`Failed to detect Claude Code Web features: ${err.message} (non-critical, web features disabled)`)
2641
+ log.warn(`Claude Code Web feature detection failed: ${err?.message || err} (non-critical, web features disabled)`)
2280
2642
  })
2281
2643
 
2282
2644
  // Forward web task events to all authenticated clients
2283
- this._webTaskManager.on('task_created', (task) => this._broadcast({ type: 'web_task_created', task }))
2284
- this._webTaskManager.on('task_updated', (task) => this._broadcast({ type: 'web_task_updated', task }))
2285
- this._webTaskManager.on('task_error', ({ taskId, message }) => this._broadcast({ type: 'web_task_error', taskId, message }))
2645
+ // A session-bound client receives a task frame only for a task in its bound
2646
+ // session's cwd (canClientSeeWebTask — the same rule list_web_tasks applies).
2647
+ // An error whose task cannot be resolved by id reaches unbound clients only.
2648
+ const webTaskRecipient = (task) => (client) => canClientSeeWebTask(client, task, this.sessionManager)
2649
+ this._webTaskManager.on('task_created', (task) => this._broadcast({ type: 'web_task_created', task }, webTaskRecipient(task)))
2650
+ this._webTaskManager.on('task_updated', (task) => this._broadcast({ type: 'web_task_updated', task }, webTaskRecipient(task)))
2651
+ this._webTaskManager.on('task_error', ({ taskId, message }) => {
2652
+ const task = this._webTaskManager.getTask?.(taskId) ?? null
2653
+ this._broadcast({ type: 'web_task_error', taskId, message }, webTaskRecipient(task))
2654
+ })
2286
2655
 
2287
2656
  // Broadcast structured log entries to dashboard clients.
2288
2657
  // Re-entrancy guard prevents infinite recursion when _broadcast() itself
@@ -2331,6 +2700,14 @@ export class WsServer {
2331
2700
  pushManager: this.pushManager,
2332
2701
  permissionSessionMap: this._permissionSessionMap,
2333
2702
  questionSessionMap: this._questionSessionMap,
2703
+ // #7895 — the daemon's resolved default provider, fed to
2704
+ // `broadcastRosterPerRecipient`/`resolveRosterProvider` so the two
2705
+ // `available_models` send sites in ws-forwarding.js tag a no-session (or
2706
+ // legacy single-session) roster identically to `ws-history.js`'s connect
2707
+ // path and `createOverlayReloadBroadcaster`'s overlay-reload path — the
2708
+ // SAME resolution (#7932: `resolveDaemonDefaultProvider`, ./providers.js)
2709
+ // `billingCanaryMonitor`'s `getDefaultProvider` uses.
2710
+ defaultProvider: resolveDaemonDefaultProvider(this.config),
2334
2711
  // #4788 Wave 2: hand the question-route registration through a helper so
2335
2712
  // dispatch and routing-guard stay symmetric. When a question is
2336
2713
  // registered for session S, every currently-connected client that's
@@ -2345,6 +2722,13 @@ export class WsServer {
2345
2722
  // settings-handlers subscription guard naturally passes for legitimate
2346
2723
  // viewers (including the "view A → switch to B → respond" flow).
2347
2724
  registerPermissionRoute: (requestId, sessionId) => this._registerPermissionRoute(requestId, sessionId),
2725
+ // #7379: a session reporting `permission_expired` means the turn that
2726
+ // raised the prompt is gone, so the daemon's own pending entry must be
2727
+ // released — otherwise resendPendingPermissions hands a dead prompt, with
2728
+ // a live Allow button, to the next client that connects. One ctx serves
2729
+ // both the multi-session and legacy-CLI forwarding paths, so wiring it
2730
+ // here covers both by construction.
2731
+ releasePermission: (requestId, sessionId) => this._permissions?.releaseAbandonedPermission?.(requestId, sessionId),
2348
2732
  broadcast: (msg, filter) => this._broadcast(msg, filter),
2349
2733
  broadcastToSession: (sid, msg, filter) => this._broadcastToSession(sid, msg, filter),
2350
2734
  broadcastSessionList: () => this._handlerCtx.transport.broadcastSessionList(),
@@ -2397,6 +2781,8 @@ export class WsServer {
2397
2781
  _replayHistory(ws, sessionId, opts) { replayHistory(this._historyCtx, ws, sessionId, opts) }
2398
2782
  _flushPostAuthQueue(ws, queue) { flushPostAuthQueue(this._historyCtx, ws, queue) }
2399
2783
  _sendSessionInfo(ws, sessionId) { sendSessionInfo(this._historyCtx, ws, sessionId) }
2784
+ _reseedActiveAgents(ws, sessionId) { reseedActiveAgents(this._historyCtx, ws, sessionId) }
2785
+ _resendPendingQuestions(ws, sessionId) { resendPendingQuestions(this._historyCtx, ws, sessionId) }
2400
2786
 
2401
2787
  /** Route incoming client messages */
2402
2788
  async _handleMessage(ws, msg) {
@@ -2420,6 +2806,31 @@ export class WsServer {
2420
2806
  }
2421
2807
  return
2422
2808
  }
2809
+
2810
+ // A connection that authenticated with a stored pairing token is only as
2811
+ // good as that token: re-check it on every frame (an `auth` frame included)
2812
+ // rather than trusting the `authenticated` flag cached at connect time.
2813
+ // Removal events end the connection eagerly; this is the backstop for any
2814
+ // removal that did not announce itself, and it fails closed (no pairing
2815
+ // store => no credential). The cause is not known here, so the reason is
2816
+ // neutral.
2817
+ if (client.pairingCredential != null &&
2818
+ !this._pairingManager?.isSessionTokenLive(client.pairingCredential)) {
2819
+ this._endCredentialConnection(ws, client, 'invalid')
2820
+ return
2821
+ }
2822
+
2823
+ // #9116: an agent principal is re-checked on EVERY frame before dispatch (credential
2824
+ // live, not expired, not revoked, store trusted, loopback origin retained). Fails
2825
+ // closed: a principal with no store is not live.
2826
+ if (client.principal != null) {
2827
+ const state = this._principalState(client)
2828
+ if (state !== 'live') {
2829
+ this._endCredentialConnection(ws, client, state)
2830
+ return
2831
+ }
2832
+ }
2833
+
2423
2834
  if (msg.type === 'auth') return
2424
2835
 
2425
2836
  // Key exchange for E2E encryption (delegates to ws-auth.js)
@@ -2459,12 +2870,36 @@ export class WsServer {
2459
2870
  const { allowed, retryAfterMs } = this._rateLimiter.check(client.rateLimitKey)
2460
2871
  if (!allowed) {
2461
2872
  this._send(ws, { type: 'rate_limited', retryAfterMs, message: 'Too many messages. Please slow down.' })
2873
+ this._sendPreviewRefusal(ws, msg, 'Preview request was not admitted. Wait for the message limit to reset, then request a new preview')
2462
2874
  return
2463
2875
  }
2464
2876
  }
2465
2877
 
2878
+ // A session-scoped connection's refused request gets its refusal whatever the
2879
+ // request's shape or the server's state (draining, no session manager): the
2880
+ // decision is not left to schema validation or to a handler. Applied before
2881
+ // both, so a malformed or unknown type is refused, not answered with a
2882
+ // schema error. (The dispatcher applies the same gate again.)
2883
+ //
2884
+ // The policy is chosen by ONE selector shared with handleSessionMessage: a
2885
+ // principal is refused by the principal allowlist instead of the bound one,
2886
+ // every other client by `refuseBoundMessage` as before.
2887
+ if ((isBoundClient(client) || isPrincipalClient(client)) &&
2888
+ dispatchPolicyFor(client)(ws, client, msg, buildMessageCtx(this._handlerCtx, correlationId))) {
2889
+ return
2890
+ }
2891
+
2892
+ // An agent principal is refused (not silently dropped) while the daemon drains: every
2893
+ // allowed application operation, permission_response included (the drain exemption
2894
+ // below is for human clients). Transport handling above is unchanged.
2895
+ if (this._draining && isPrincipalClient(client) && Object.hasOwn(PRINCIPAL_ALLOWED_MESSAGE_TYPES, msg?.type)) {
2896
+ sendPrincipalRefusal(ws, client, msg, buildMessageCtx(this._handlerCtx, correlationId), 'draining')
2897
+ return
2898
+ }
2899
+
2466
2900
  // During drain, only allow permission_response and user_question_response
2467
2901
  if (this._draining && msg.type !== 'permission_response' && msg.type !== 'user_question_response') {
2902
+ this._sendPreviewRefusal(ws, msg, 'Server is restarting; reconnect before requesting a preview')
2468
2903
  if (msg.type === 'input') {
2469
2904
  this._send(ws, { type: 'server_status', message: 'Server is restarting, please wait...' })
2470
2905
  }
@@ -2477,6 +2912,7 @@ export class WsServer {
2477
2912
  const details = parsed.error.issues.map(i => i.message).join(', ')
2478
2913
  log.warn(`[${correlationId}] Invalid message from ${client.id}: ${details}`)
2479
2914
  this._send(ws, { type: 'error', code: 'INVALID_MESSAGE', correlationId, details })
2915
+ this._sendPreviewRefusal(ws, msg, 'Invalid preview request; check the service port and reconnect to this session')
2480
2916
  return
2481
2917
  }
2482
2918
  const validatedMsg = parsed.data
@@ -2484,7 +2920,7 @@ export class WsServer {
2484
2920
  log.debug(`[${correlationId}] Handling ${validatedMsg.type} from ${client.id}`)
2485
2921
 
2486
2922
  // Route based on server mode — pass correlationId in context
2487
- const ctx = { ...this._handlerCtx, correlationId }
2923
+ const ctx = buildMessageCtx(this._handlerCtx, correlationId)
2488
2924
  try {
2489
2925
  if (this.sessionManager) {
2490
2926
  await handleSessionMessage(ws, client, validatedMsg, ctx)
@@ -2492,6 +2928,10 @@ export class WsServer {
2492
2928
  await handleCliMessage(ws, client, validatedMsg, ctx)
2493
2929
  }
2494
2930
  } catch (err) {
2931
+ if (isAuthorityRevoked(err)) {
2932
+ log.info(`[${correlationId}] ${validatedMsg.type} from ${client.id} not started: connection no longer authorized`)
2933
+ return
2934
+ }
2495
2935
  log.error(`[${correlationId}] Handler error for ${validatedMsg.type}: ${err.message}`)
2496
2936
  this._send(ws, { type: 'server_error', correlationId, message: err.message, recoverable: true })
2497
2937
  }
@@ -2521,6 +2961,41 @@ export class WsServer {
2521
2961
  this._broadcaster._broadcast(message, filter)
2522
2962
  }
2523
2963
 
2964
+ /**
2965
+ * #7601 — fast-path bridge: a chroxy-initiated environment stop/restart severs
2966
+ * every bound session's container binding, so surface CONTAINER_VANISHED on each
2967
+ * one right away. Reads `env.sessions` (the roster EnvironmentManager maintains)
2968
+ * and calls the session provider's idempotent `notifyContainerVanished()` — the
2969
+ * SAME surface the #7599 reactive paths and the #7601 poll use, so a stop the
2970
+ * poll also catches is deduped by the provider's latch. Does NOT inject a
2971
+ * SessionManager handle into EnvironmentManager, does NOT untag `env.sessions`,
2972
+ * and does NOT touch a session lacking the surface (feature-detected, never a
2973
+ * provider list — docker-byok gained the surface in #7600).
2974
+ *
2975
+ * @param {string} envId
2976
+ * @param {string} reason the emitting event, for the log line
2977
+ */
2978
+ _surfaceContainerVanishedForEnvironment(envId, reason) {
2979
+ try {
2980
+ if (!envId || !this.environmentManager || !this.sessionManager) return
2981
+ const env = this.environmentManager.get?.(envId)
2982
+ if (!env || !Array.isArray(env.sessions) || env.sessions.length === 0) return
2983
+ // Copy the roster: notifyContainerVanished emits synchronously and a
2984
+ // downstream listener could mutate env.sessions mid-iteration.
2985
+ for (const sessionId of [...env.sessions]) {
2986
+ const entry = this.sessionManager.getSession?.(sessionId)
2987
+ const session = entry?.session
2988
+ if (session && typeof session.notifyContainerVanished === 'function') {
2989
+ if (session.notifyContainerVanished()) {
2990
+ log.info(`[${reason}] surfaced CONTAINER_VANISHED for session ${sessionId} in env ${envId}`)
2991
+ }
2992
+ }
2993
+ }
2994
+ } catch (err) {
2995
+ log.warn(`[${reason}] container-vanish fan-out failed for env ${envId}: ${err?.message || err}`)
2996
+ }
2997
+ }
2998
+
2524
2999
  /**
2525
3000
  * Broadcast a session-scoped message to clients viewing that session.
2526
3001
  * Tags the message with `sessionId` so clients can route it to the correct
@@ -2528,6 +3003,11 @@ export class WsServer {
2528
3003
  * matches — prevents cross-session info leakage and bandwidth waste.
2529
3004
  * Pass a custom filter to override the default recipient selection when needed.
2530
3005
  */
3006
+ _sendPreviewRefusal(ws, msg, reason) {
3007
+ if (msg.type !== 'open_dev_preview' || typeof msg.requestId !== 'string' || !msg.requestId || msg.requestId.length > 128 || typeof msg.sessionId !== 'string' || !msg.sessionId || msg.sessionId.length > 256) return
3008
+ this._send(ws, { type: 'dev_preview_status', sessionId: msg.sessionId, requestId: msg.requestId, state: 'failed', reason })
3009
+ }
3010
+
2531
3011
  _broadcastToSession(sessionId, message, filter) {
2532
3012
  this._broadcaster._broadcastToSession(sessionId, message, filter)
2533
3013
  }
@@ -2566,6 +3046,21 @@ export class WsServer {
2566
3046
  )
2567
3047
  }
2568
3048
 
3049
+ /**
3050
+ * #8331: push the daily-daemon update status to the clients allowed to act on
3051
+ * it: STRICT-PRIMARY and unbound (`isPrimaryToken === true && !boundSessionId`),
3052
+ * the same bar `daemon_update_action` enforces. Host-level (`!boundSessionId`)
3053
+ * is NOT enough: a paired phone holds an unbound pairing token, and the status
3054
+ * names the commits and subjects queued for the owner's machine.
3055
+ */
3056
+ _broadcastDaemonUpdateStatus(status) {
3057
+ if (!status) return
3058
+ this._broadcast(
3059
+ { type: 'daemon_update_status', ...status },
3060
+ (client) => client.isPrimaryToken === true && !client.boundSessionId,
3061
+ )
3062
+ }
3063
+
2569
3064
  // #6691: push a single orchestration run delta to host-level (unbound) clients
2570
3065
  // only — runs are host-wide cross-session objects; a session-bound token never
2571
3066
  // receives them. Called by the OrchestrationManager (E-4); the `delta`
@@ -2799,8 +3294,8 @@ export class WsServer {
2799
3294
  }
2800
3295
 
2801
3296
  /** Get list of connected clients for auth_ok payload */
2802
- _getConnectedClientList() {
2803
- return this._clientManager.getConnectedList()
3297
+ _getConnectedClientList(forClient) {
3298
+ return this._clientManager.getConnectedList(forClient)
2804
3299
  }
2805
3300
 
2806
3301
  /** Broadcast client_joined to all OTHER authenticated clients */
@@ -2813,6 +3308,198 @@ export class WsServer {
2813
3308
  this._broadcaster._broadcastClientLeft(departingClient)
2814
3309
  }
2815
3310
 
3311
+ /**
3312
+ * True when the connection authenticated with the PRIMARY token (or auth is
3313
+ * disabled). Fails closed: any session binding, any recorded pairing
3314
+ * credential, or a primary flag that is not exactly `true` means "not primary".
3315
+ */
3316
+ _holdsPrimaryCredential(client) {
3317
+ if (client.boundSessionId != null) return false
3318
+ if (client.pairingCredential != null) return false
3319
+ if (client.principal != null) return false
3320
+ return client.isPrimaryToken === true || !this.authRequired
3321
+ }
3322
+
3323
+ /**
3324
+ * Delivery gate for the client sender. A connection whose stored credential is
3325
+ * no longer live (silent expiry between sweeps), or whose authentication was
3326
+ * stripped after it had authenticated (primary revoke), receives nothing but the
3327
+ * notices that explain it. Frames to a connection that never authenticated
3328
+ * (auth_ok / auth_fail / pairing / key exchange) are not gated here.
3329
+ */
3330
+ _mayDeliverTo(client, message) {
3331
+ const type = message?.type
3332
+ if (type === 'credential_invalidated' || type === 'token_rotated') return true
3333
+ // The authentication flow itself: a connection whose authentication was
3334
+ // stripped may attempt to authenticate again and must be told the outcome.
3335
+ if (AUTH_FLOW_FRAME_TYPES.has(type)) return true
3336
+ if (type === 'error' && REVOKE_NOTICE_ERROR_CODES.has(message.code)) return true
3337
+ if (client.authTime != null && client.authenticated !== true) return false
3338
+ if (client.pairingCredential != null) {
3339
+ return !!this._pairingManager?.isSessionTokenLive(client.pairingCredential)
3340
+ }
3341
+ // #9116: a principal whose credential stopped being valid (revoked, expired, store
3342
+ // untrusted, origin no longer loopback) receives nothing, even if it never sends a
3343
+ // frame; the keepalive sweep and the expiry timer then end the connection.
3344
+ if (client.principal != null) return this._principalState(client) === 'live'
3345
+ return true
3346
+ }
3347
+
3348
+ /**
3349
+ * True only while `client` is still authenticated AND the credential it
3350
+ * authenticated with is still valid. For code that resumes after an await:
3351
+ * the connection may have ended while it was suspended, and the handler still
3352
+ * holds the client record. A stored credential that has silently gone invalid
3353
+ * ends the connection here too, so the answer and the socket agree.
3354
+ */
3355
+ _isConnectionAuthorized(client) {
3356
+ if (!client || client.authenticated !== true) return false
3357
+ if (client.pairingCredential != null &&
3358
+ !this._pairingManager?.isSessionTokenLive(client.pairingCredential)) {
3359
+ for (const [ws, c] of this.clients) {
3360
+ if (c === client) { this._endCredentialConnection(ws, client, 'invalid'); break }
3361
+ }
3362
+ return false
3363
+ }
3364
+ if (client.principal != null) {
3365
+ const state = this._principalState(client)
3366
+ if (state !== 'live') {
3367
+ for (const [ws, c] of this.clients) {
3368
+ if (c === client) { this._endCredentialConnection(ws, client, state); break }
3369
+ }
3370
+ return false
3371
+ }
3372
+ }
3373
+ return true
3374
+ }
3375
+
3376
+ /**
3377
+ * Why a principal connection may not continue: 'live' when it may, otherwise
3378
+ * 'revoked', 'expired', 'disabled' (the kill switch) or 'invalid' (no store, an untrusted
3379
+ * store, an unknown grant, an origin that is no longer loopback, or audit logging down).
3380
+ * Memory only: no disk read per frame.
3381
+ * @param {object} client
3382
+ * @returns {'live'|'revoked'|'expired'|'disabled'|'invalid'}
3383
+ */
3384
+ _principalState(client) {
3385
+ const store = this._principalStore
3386
+ if (!store || client.principal == null) return 'invalid'
3387
+ if (!isLoopbackConnection(client)) return 'invalid'
3388
+ return store.state(client.principal.principalId)
3389
+ }
3390
+
3391
+ /**
3392
+ * Arm the per-connection expiry timer: at the grant's `expiresAt` the connection ends
3393
+ * with `credential_invalidated` and close code 4401, whether or not it sends anything.
3394
+ * Cleared on departure and on end.
3395
+ */
3396
+ _armPrincipalExpiry(ws, client) {
3397
+ this._clearPrincipalExpiry(client)
3398
+ const store = this._principalStore
3399
+ if (!store) return
3400
+ const delay = Math.max(0, client.principal.expiresAt - store.now())
3401
+ const timer = this._principalTimers.setTimeout(() => {
3402
+ client._principalExpiryTimer = null
3403
+ const state = this._principalState(client)
3404
+ if (state !== 'live') this._endCredentialConnection(ws, client, state === 'revoked' || state === 'disabled' ? state : 'expired')
3405
+ // Fired early (the credential is still live): keep watching for the remaining lifetime.
3406
+ else if (client.authenticated) this._armPrincipalExpiry(ws, client)
3407
+ }, delay)
3408
+ timer?.unref?.()
3409
+ client._principalExpiryTimer = timer
3410
+ }
3411
+
3412
+ _clearPrincipalExpiry(client) {
3413
+ if (client._principalExpiryTimer != null) {
3414
+ this._principalTimers.clearTimeout(client._principalExpiryTimer)
3415
+ client._principalExpiryTimer = null
3416
+ }
3417
+ }
3418
+
3419
+ /**
3420
+ * End the connections of the principals a selector names (revoke, kill): each gets
3421
+ * `credential_invalidated` and 4401. The selector is a principalId string, or
3422
+ * `{ principalId }`, `{ label }` or `{ all: true }`.
3423
+ */
3424
+ _endPrincipalConnections(selector, reason = 'revoked') {
3425
+ const sel = typeof selector === 'string' ? { principalId: selector } : (selector ?? {})
3426
+ for (const [ws, client] of [...this.clients]) {
3427
+ const p = client.principal
3428
+ if (p == null) continue
3429
+ if (sel.all === true || (sel.principalId != null && p.principalId === sel.principalId) || (sel.label != null && p.label === sel.label)) {
3430
+ this._endCredentialConnection(ws, client, reason)
3431
+ }
3432
+ }
3433
+ }
3434
+
3435
+ /**
3436
+ * Drop principal-tagged queued work for a selector and return the dropped entries so
3437
+ * the caller can audit each one (`dropped:killed`). There is NO principal queue on
3438
+ * this build (S9 adds it), so there is nothing to drop; the queue S9 builds plugs in
3439
+ * as `this._principalQueues.drain(selector)`.
3440
+ * @returns {object[]}
3441
+ */
3442
+ _drainPrincipalQueues(selector) {
3443
+ const out = this._principalQueues?.drain?.(selector)
3444
+ return Array.isArray(out) ? out : []
3445
+ }
3446
+
3447
+ /**
3448
+ * End every principal connection whose credential is no longer valid. Run by the
3449
+ * keepalive sweep, so a store that became untrusted (deleted, re-moded) or a revoke
3450
+ * made out of band cuts a connection that is sending nothing.
3451
+ */
3452
+ _recheckPrincipals() {
3453
+ const store = this._principalStore
3454
+ if (store) store.refresh()
3455
+ for (const [ws, client] of [...this.clients]) {
3456
+ if (client.principal == null || !client.authenticated) continue
3457
+ const state = this._principalState(client)
3458
+ if (state !== 'live') this._endCredentialConnection(ws, client, state)
3459
+ }
3460
+ }
3461
+
3462
+ /**
3463
+ * End a connection whose credential is no longer valid. Departure runs first
3464
+ * (it reads client state), the client is removed so any frame still in flight
3465
+ * finds no connection to dispatch against, and the socket is closed with a
3466
+ * distinct code so the client re-pairs instead of retrying the dead token.
3467
+ */
3468
+ _endCredentialConnection(ws, client, reason = 'revoked') {
3469
+ // A destroyed pairing manager means the daemon is shutting down, not that this
3470
+ // credential was revoked: end the connection quietly, with no notice (which would
3471
+ // make the client forget a token that is still valid) and no credential close code.
3472
+ if (this._pairingManager?.destroyed === true) {
3473
+ if (client.authenticated) this._handleClientDeparture(client)
3474
+ client.authenticated = false
3475
+ client.isPrimaryToken = false
3476
+ client.pairingCredential = null
3477
+ client.authToken = undefined
3478
+ if (client._keyExchangeTimeout) clearTimeout(client._keyExchangeTimeout)
3479
+ this._clientManager.removeClient(ws)
3480
+ try { ws.close(1001, 'server shutting down') } catch { /* already closing */ }
3481
+ return
3482
+ }
3483
+ // Tell the client WHY through the normal (possibly encrypted) channel first:
3484
+ // that frame is what lets it forget the credential. The close code that
3485
+ // follows only stops the connection.
3486
+ const known = reason === 'revoked' || reason === 'expired' || reason === 'evicted'
3487
+ if (ws.readyState === 1) {
3488
+ this._send(ws, { type: 'credential_invalidated', reason: known ? reason : 'invalid' })
3489
+ }
3490
+ if (client._keyExchangeTimeout) clearTimeout(client._keyExchangeTimeout)
3491
+ this._clearPrincipalExpiry(client)
3492
+ if (client.authenticated) this._handleClientDeparture(client)
3493
+ client.authenticated = false
3494
+ client.isPrimaryToken = false
3495
+ client.pairingCredential = null
3496
+ client.authToken = undefined
3497
+ if (client.principal != null) client.postAuthQueue = null
3498
+ this._clientManager.removeClient(ws)
3499
+ log.info(`Client ${client.id} ended: credential ${reason}`)
3500
+ try { ws.close(WS_CLOSE_CREDENTIAL_INVALID, `credential ${reason}`) } catch { /* already closing */ }
3501
+ }
3502
+
2816
3503
  /**
2817
3504
  * #5555.6 — one keepalive sweep over all authenticated clients.
2818
3505
  *
@@ -2832,6 +3519,9 @@ export class WsServer {
2832
3519
  * then `removeClient` updates the index, then we terminate the socket.
2833
3520
  */
2834
3521
  _keepaliveSweep() {
3522
+ // #9116: cut any principal connection whose credential stopped being valid, however
3523
+ // quiet it is (the outbound gate already withholds frames from it).
3524
+ if (this._principalStore || [...this.clients.values()].some((c) => c.principal != null)) this._recheckPrincipals()
2835
3525
  for (const [ws, client] of this.clients) {
2836
3526
  if (!client.authenticated) continue
2837
3527
  if (ws.readyState !== 1) continue
@@ -2842,6 +3532,16 @@ export class WsServer {
2842
3532
  try { ws.terminate() } catch {}
2843
3533
  continue
2844
3534
  }
3535
+ // A connected, responsive device is in use: slide its pairing token's
3536
+ // expiry so the connection does not outlive its token by simply idling.
3537
+ // A token that cannot be refreshed (expired, removed, or no pairing
3538
+ // store) ends the connection instead of leaving it authenticated.
3539
+ if (client.pairingCredential != null) {
3540
+ if (!this._pairingManager?.touchSessionToken(client.pairingCredential)) {
3541
+ this._endCredentialConnection(ws, client, 'invalid')
3542
+ continue
3543
+ }
3544
+ }
2845
3545
  client.isAlive = false
2846
3546
  try { ws.ping() } catch {}
2847
3547
  }
@@ -2849,6 +3549,10 @@ export class WsServer {
2849
3549
 
2850
3550
  /** Handle cleanup when an authenticated client disconnects or is terminated */
2851
3551
  _handleClientDeparture(departingClient) {
3552
+ this._clearPrincipalExpiry(departingClient)
3553
+ // #9118: a departing principal (disconnect, revoke, expiry) keeps no journal subscription.
3554
+ this._principalSubscriptions?.removeClient(departingClient)
3555
+ void this._devPreview.closeClient(departingClient.id)
2852
3556
  // #5563: vacate primary for every session this client owned. Promotion
2853
3557
  // policy is NOBODY-UNTIL-CLAIM — we clear the slot (broadcast null) rather
2854
3558
  // than auto-promote an observer, so a backgrounded viewer is never silently
@@ -3034,15 +3738,56 @@ export class WsServer {
3034
3738
  return this._clientManager.hasActiveViewers(sessionId)
3035
3739
  }
3036
3740
 
3741
+ /**
3742
+ * The session lookups `frameForPrincipal` / `principalMaySee` need. The lease
3743
+ * lookup is read from `this._principalLeases` once the lease store exists (S8).
3744
+ */
3745
+ _principalPolicyOpts() {
3746
+ return principalPolicyOptsFromCtx({
3747
+ sessions: { sessionManager: this.sessionManager },
3748
+ services: { principalLeases: this._principalLeases },
3749
+ })
3750
+ }
3751
+
3037
3752
  /** Send JSON to a single client (delegates to extracted ws-client-sender) */
3038
3753
  _send(ws, message) {
3039
3754
  const client = this.clients.get(ws)
3755
+ // An agent principal is handled BEFORE the bound-other-session drop: it
3756
+ // carries a sentinel binding, so that drop would discard every frame a
3757
+ // principal may legitimately receive. Deny by default, session frames only
3758
+ // when the grant covers the session (principal-policy.js).
3759
+ if (client && isPrincipalClient(client)) {
3760
+ const frame = frameForPrincipal(client, message, this._principalPolicyOpts())
3761
+ if (frame === null) return true
3762
+ return this._clientSend(ws, client, frame)
3763
+ }
3764
+ // The one outgoing choke point: a session-scoped connection is sent no
3765
+ // host-wide frame and has host-wide fields removed from the rest.
3766
+ if (client && isBoundClient(client)) {
3767
+ // A frame tagged with another session is not for this connection, on a
3768
+ // direct send as on a broadcast.
3769
+ if (message?.[CONVERSATION_FRAME] !== true && typeof message?.sessionId === 'string' && isBoundToOtherSession(client, message.sessionId)) return true
3770
+ const frame = frameForBoundClient(message)
3771
+ if (frame === null) return true
3772
+ message = frame
3773
+ }
3040
3774
  // #5721: propagate the delivery boolean so callers gating crypto state on a
3041
3775
  // frame reaching the wire (the eager handshake's auth_ok) can observe a
3042
3776
  // swallowed send failure. Other callers ignore the return, unchanged.
3043
3777
  return this._clientSend(ws, client, message)
3044
3778
  }
3045
3779
 
3780
+ /**
3781
+ * How many hook-routed permission requests are parked on the daemon right now
3782
+ * (POST /permission held open for a human). Read-only; the idle-only
3783
+ * auto-deploy probe (GET /api/daemon/idle, #8324) reads it so http-routes
3784
+ * never reaches into the private map.
3785
+ * @returns {number}
3786
+ */
3787
+ getHookPendingPermissionCount() {
3788
+ return this._pendingPermissions.size
3789
+ }
3790
+
3046
3791
  /**
3047
3792
  * Clear all pending permission requests across both subsystems.
3048
3793
  *
@@ -3068,7 +3813,22 @@ export class WsServer {
3068
3813
  }
3069
3814
 
3070
3815
  /** Graceful shutdown */
3816
+ settleDevPreviews() {
3817
+ return this._devPreview.closeAll()
3818
+ }
3819
+
3071
3820
  close() {
3821
+ // #9118: flush the journal and mark it cleanly closed, so a restart continues its
3822
+ // seq contiguously. A failure here only leaves it marked unclean (a restart then
3823
+ // treats it as a crash, which is always safe).
3824
+ try { this._principalJournal?.close() } catch (err) { log.warn(`principal journal close failed: ${err?.message || err}`) }
3825
+ // Write any collapsed refusal counts still waiting for their window to end.
3826
+ try { principalAuditor.flushRejections() } catch (err) { log.warn(`principal audit flush failed: ${err?.message || err}`) }
3827
+ if (this._daemonUpdate && this._daemonUpdateChangeHandler && typeof this._daemonUpdate.off === 'function') {
3828
+ this._daemonUpdate.off('change', this._daemonUpdateChangeHandler)
3829
+ this._daemonUpdateChangeHandler = null
3830
+ }
3831
+ try { this._daemonUpdate?.close?.() } catch { /* best effort */ }
3072
3832
  // Remove PairingManager listeners to prevent post-shutdown broadcasts
3073
3833
  if (this._pairingManager && this._pairingRefreshedHandler) {
3074
3834
  this._pairingManager.off('pairing_refreshed', this._pairingRefreshedHandler)
@@ -3078,6 +3838,10 @@ export class WsServer {
3078
3838
  this._pairingManager.off('pending_request_expired', this._pendingRequestExpiredHandler)
3079
3839
  this._pendingRequestExpiredHandler = null
3080
3840
  }
3841
+ if (this._pairingManager && this._sessionTokenRemovedHandler) {
3842
+ this._pairingManager.off('session_token_removed', this._sessionTokenRemovedHandler)
3843
+ this._sessionTokenRemovedHandler = null
3844
+ }
3081
3845
  this._pairRequesters.clear()
3082
3846
 
3083
3847
  // Remove TokenManager listener to prevent post-shutdown broadcasts
@@ -3097,6 +3861,8 @@ export class WsServer {
3097
3861
  }
3098
3862
  if (this._sessionDestroyedHandler) {
3099
3863
  this.sessionManager.off('session_destroyed', this._sessionDestroyedHandler)
3864
+ if (this._sessionRemovedHandler) this.sessionManager.off('session_removed', this._sessionRemovedHandler)
3865
+ this._sessionRemovedHandler = null
3100
3866
  this._sessionDestroyedHandler = null
3101
3867
  }
3102
3868
  if (this._sessionEventAuditHandler) {
@@ -3105,6 +3871,26 @@ export class WsServer {
3105
3871
  }
3106
3872
  }
3107
3873
 
3874
+ // #7552: same reason as the SessionManager listeners above — the
3875
+ // EnvironmentManager outlives a WsServer instance, so a closed server must
3876
+ // not stay subscribed (and must not broadcast on a torn-down socket set).
3877
+ if (this.environmentManager && typeof this.environmentManager.off === 'function' &&
3878
+ this._environmentSessionsChangedHandler) {
3879
+ this.environmentManager.off('environment_sessions_changed', this._environmentSessionsChangedHandler)
3880
+ this._environmentSessionsChangedHandler = null
3881
+ }
3882
+ // #7601: symmetric detach of the stop/restart fast-path subscriptions.
3883
+ if (this.environmentManager && typeof this.environmentManager.off === 'function') {
3884
+ if (this._environmentStoppedHandler) {
3885
+ this.environmentManager.off('environment_stopped', this._environmentStoppedHandler)
3886
+ this._environmentStoppedHandler = null
3887
+ }
3888
+ if (this._environmentRestartedHandler) {
3889
+ this.environmentManager.off('environment_restarted', this._environmentRestartedHandler)
3890
+ this._environmentRestartedHandler = null
3891
+ }
3892
+ }
3893
+
3108
3894
  if (this._pingInterval) {
3109
3895
  clearInterval(this._pingInterval)
3110
3896
  this._pingInterval = null
@@ -3122,9 +3908,9 @@ export class WsServer {
3122
3908
  this._clientManager.clearAllPrimary()
3123
3909
  this._normalizer.destroy()
3124
3910
 
3125
- // Clean up all dev preview tunnels (fire-and-forget; close() is synchronous
3126
- // by contract, and tunnel process cleanup is best-effort before exit)
3127
- void this._devPreview.closeAll()
3911
+ // Socket teardown remains immediate; callers can await confirmed preview
3912
+ // child settlement before exiting the daemon.
3913
+ const previewSettlement = this._devPreview.closeAll()
3128
3914
 
3129
3915
  // Clean up web task manager
3130
3916
  this._webTaskManager.destroy()
@@ -3146,5 +3932,6 @@ export class WsServer {
3146
3932
  this._approvalServer = null
3147
3933
  removeShellApprovalInfo()
3148
3934
  }
3935
+ return previewSettlement
3149
3936
  }
3150
3937
  }