@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-history.js CHANGED
@@ -4,23 +4,36 @@
4
4
  * Extracted from ws-server.js to separate the post-authentication
5
5
  * handshake and history replay concerns from core server orchestration.
6
6
  */
7
- import { toShortModelId, getRegistryForProvider } from './models.js'
7
+ import { toShortModelId, getRegistryForProvider, resolveRosterProvider } from './models.js'
8
8
  import { getPermissionModes } from './handler-utils.js'
9
- import { listProviders, getProvider } from './providers.js'
9
+ import { buildThinkingLevelChanged } from './thinking-level-wire.js'
10
+ import { buildFolderTrustStateMessageForDisplay, noteFolderTrustFrame } from './folder-trust-wire.js'
11
+ import { listProviders, getProvider, getProviderRuntimeInfo, resolveDaemonDefaultProvider } from './providers.js'
10
12
  import { createLogger } from './logger.js'
13
+ import { isBoundClient } from './environments/authority.js'
14
+ import { sendRawTransport, isPrincipalClient } from './principal-policy.js'
15
+ import { streamKindOf, permissionOutcomeDecision } from './session-message-history.js'
11
16
  import { createKeyPair, deriveSharedKey, deriveConnectionKey, signExchangeKey } from '@chroxy/store-core/crypto'
12
17
  import { DEFAULT_RESULT_TIMEOUT_MS, DEFAULT_HARD_TIMEOUT_MS, DEFAULT_STREAM_STALL_TIMEOUT_MS } from './base-session.js'
13
- import { MAX_SANE_DURATION_MS } from '@chroxy/protocol'
18
+ import { MAX_SANE_DURATION_MS, REPLAY_BACKPRESSURE_MAX_WAIT_MS } from '@chroxy/protocol'
14
19
 
15
20
  const log = createLogger('ws')
16
21
 
17
- // #4833 — back-pressure pause for chunked replay/flush loops.
22
+ function permissionModesForProvider(provider) {
23
+ let ProviderClass
24
+ try { ProviderClass = provider ? getProvider(provider) : undefined } catch { /* unknown provider */ }
25
+ return getPermissionModes(provider, ProviderClass)
26
+ }
27
+
28
+ // #4833 — back-pressure pause for the chunked send loop.
18
29
  //
19
- // Both replayHistory and flushPostAuthQueue emit messages in 20-entry chunks
20
- // separated by setImmediate yields. On sessions with fat tool_result payloads
21
- // (200KB+ each), a single chunk can push ws.bufferedAmount past the 1MB
22
- // EVICT_THRESHOLD in ws-client-sender.js, tripping a post-send 4008 close and
23
- // surfacing as a "Reconnecting…" loop in the dashboard.
30
+ // `sendChunkedWithBackpressure` emits messages in 20-entry chunks separated by
31
+ // setImmediate yields, on behalf of every path that streams a batch to one
32
+ // client: replayHistory, flushPostAuthQueue, and the two conversation-handler
33
+ // replays. On sessions with fat tool_result payloads (200KB+ each), a single
34
+ // chunk can push ws.bufferedAmount past the 1MB EVICT_THRESHOLD in
35
+ // ws-client-sender.js, tripping a post-send 4008 close and surfacing as a
36
+ // "Reconnecting…" loop in the dashboard.
24
37
  //
25
38
  // Before scheduling the next chunk, the loop now polls bufferedAmount and
26
39
  // pauses (via setTimeout, every BACKPRESSURE_POLL_INTERVAL_MS) until it falls
@@ -29,7 +42,7 @@ const log = createLogger('ws')
29
42
  // links. The poll interval (20ms) is short enough to keep the replay
30
43
  // responsive but long enough to give the socket time to actually flush.
31
44
  //
32
- // Both helpers abort the poll once ws.readyState leaves OPEN (client
45
+ // The loop aborts the poll once ws.readyState leaves OPEN (client
33
46
  // disconnected while paused), so the poll chain terminates on socket close
34
47
  // without sending to a closed socket.
35
48
  //
@@ -42,9 +55,18 @@ const log = createLogger('ws')
42
55
  // from scratch, rather than silently leaking a timer against a dead peer. The
43
56
  // cap is comfortably longer than a healthy slow-link drain but far short of
44
57
  // "forever".
58
+ //
59
+ // #7496: the cap is single-sourced in @chroxy/protocol because a client reads it
60
+ // too. While parked this loop emits NOTHING for the stream, so the dashboard's
61
+ // transcript inactivity watchdog (derived from this value there) must be longer
62
+ // than the longest park or it reports a timeout against a healthy replay.
63
+ // A keepalive frame is not the answer: it would queue behind the bytes that are
64
+ // not draining and arrive only after the park had ended. Do not hardcode a
65
+ // number here — `tests/ws-history-backpressure-cap.test.js` pins that the socket
66
+ // is closed at exactly the shared value.
45
67
  const BACKPRESSURE_PAUSE_THRESHOLD = 256 * 1024
46
68
  const BACKPRESSURE_POLL_INTERVAL_MS = 20
47
- const BACKPRESSURE_MAX_WAIT_MS = 30_000
69
+ const BACKPRESSURE_MAX_WAIT_MS = REPLAY_BACKPRESSURE_MAX_WAIT_MS
48
70
 
49
71
  // #5622 — bound the eager X25519 key derivations done SYNCHRONOUSLY per
50
72
  // event-loop iteration.
@@ -156,6 +178,331 @@ export function scheduleAfterDrain(ws, fn) {
156
178
  setTimeout(poll, BACKPRESSURE_POLL_INTERVAL_MS)
157
179
  }
158
180
 
181
+ // #7460 / #7480 / #7485 — THE implementation of the #4833 chunk-and-drain loop.
182
+ // Every path in the server that streams a batch of frames to one client goes
183
+ // through it: `replayHistory` (connect / session-switch), `flushPostAuthQueue`
184
+ // (below), `handleRequestFullHistory` ("Sync Full History") and
185
+ // `handleRequestConversationTranscript` (the read-only transcript viewer), the
186
+ // last two in conversation-handlers.js.
187
+ //
188
+ // They were four hand-copied variants of the same twelve lines, and every
189
+ // copied piece drifted at least once: the `_seq` -> `historySeq` map (#7454),
190
+ // the `result` -> `agent_idle` synthesis (#7459), the bufferedAmount gating on
191
+ // the full-history replay (#7460) and again on the transcript replay (#7480),
192
+ // and a second chunk-size constant with the same value four lines from this
193
+ // one (#7485). A second copy of this loop is how that divergence started, so
194
+ // there is deliberately only one — and `tests/one-chunk-and-drain-loop.test.js`
195
+ // re-derives that claim from this source on every run rather than trusting
196
+ // this sentence, because a comment beside a set that can grow is exactly the
197
+ // shape docs/false-safety-guards.md catalogues.
198
+ const REPLAY_CHUNK_SIZE = 20
199
+
200
+ /**
201
+ * Send `entries` to `ws` in REPLAY_CHUNK_SIZE batches, yielding the event loop
202
+ * between chunks and pausing whenever `ws.bufferedAmount` climbs past
203
+ * BACKPRESSURE_PAUSE_THRESHOLD (#4833). Three gates, of which TWO carry
204
+ * behaviour on their own:
205
+ *
206
+ * - chunk ENTRY (load-bearing) — the first chunk can land on a socket that is
207
+ * already congested from a preceding burst (post-auth info,
208
+ * session_switched), so it is deferred before anything is written. The
209
+ * mid-chunk break only fires *after* a send, so without this gate one fat
210
+ * payload still lands on a near-eviction buffer.
211
+ * - MID-chunk (load-bearing) — REPLAY_CHUNK_SIZE was sized for short messages;
212
+ * two 200KB tool_results blow past the threshold inside a single chunk, so
213
+ * the loop breaks out and resumes from the next UNSENT entry.
214
+ * - chunk SCHEDULING — pauses before queueing the next chunk. Retained as the
215
+ * inherited #4833 shape, but it is NOT independently load-bearing: replacing
216
+ * it with a bare `setImmediate` is an equivalent mutation, because the next
217
+ * `sendChunk` re-checks the chunk-ENTRY gate and enters the same drain wait
218
+ * (with the same #5328 max-wait cap) one tick later. Established by mutation
219
+ * testing and a 48-scenario differential during review of PR #7479; do not
220
+ * read this line as a third independent guard.
221
+ *
222
+ * `emit(entry, index)` writes one entry; `onDone()` runs once every entry has
223
+ * been written. Neither runs after `ws.readyState` leaves OPEN — a client that
224
+ * disconnects mid-replay gets no further frames and no end marker, which is
225
+ * the behaviour every replay caller already relied on.
226
+ *
227
+ * #7485 — three OPTIONAL hooks let a caller carry state across the gate, which
228
+ * is what `flushPostAuthQueue` needs and what kept it a separate copy of this
229
+ * loop until now. Callers that pass none behave exactly as before:
230
+ *
231
+ * - `onPause()` — fires immediately before the loop parks on a drain (the
232
+ * chunk-entry gate, the mid-chunk break, and the between-chunks yield all
233
+ * park through one place).
234
+ * - `onResume()` — fires each time the loop is CLEAR to write, including the
235
+ * first chunk and including the empty slice, which never enters a chunk
236
+ * body. A hook that only fired after a real pause would leave the
237
+ * empty-queue case latched.
238
+ * - `onAbort()` — fires instead of `onDone` when the loop stops because
239
+ * `ws.readyState` left OPEN. It does NOT fire when the socket dies while
240
+ * parked inside `scheduleAfterDrain` (that chain exits silently, as it
241
+ * always has) or when the #5328 max-wait cap closes the socket.
242
+ *
243
+ * @param {WebSocket} ws - The client socket.
244
+ * @param {Array} entries - The full slice to deliver.
245
+ * @param {{startOffset?: number, emit: (entry: any, index: number) => void, onDone: () => void, onPause?: () => void, onResume?: () => void, onAbort?: () => void}} opts
246
+ */
247
+ export function sendChunkedWithBackpressure(ws, entries, { startOffset = 0, emit, onDone, onPause, onResume, onAbort }) {
248
+ const park = (offset) => {
249
+ if (onPause) onPause()
250
+ scheduleAfterDrain(ws, () => sendChunk(offset))
251
+ }
252
+ const abort = () => { if (onAbort) onAbort() }
253
+ const sendChunk = (offset) => {
254
+ if (ws.readyState !== 1) {
255
+ abort()
256
+ return
257
+ }
258
+ if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
259
+ park(offset)
260
+ return
261
+ }
262
+ if (onResume) onResume()
263
+ const end = Math.min(offset + REPLAY_CHUNK_SIZE, entries.length)
264
+ let nextOffset = end
265
+ for (let i = offset; i < end; i++) {
266
+ emit(entries[i], i)
267
+ if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
268
+ nextOffset = i + 1
269
+ break
270
+ }
271
+ }
272
+ if (nextOffset < entries.length) {
273
+ park(nextOffset)
274
+ } else {
275
+ onDone()
276
+ }
277
+ }
278
+ // Both entry paths are gated on OPEN, not just the chunking one. `sendChunk`
279
+ // re-checks readyState itself (it is also the resume point for every
280
+ // scheduled continuation), but the EMPTY-slice path below reaches `onDone`
281
+ // without going through it — so without this check a client that vanished
282
+ // before an already-current replay still had its `history_replay_end` and
283
+ // re-seed burst written at a dead socket, contradicting the contract stated
284
+ // above. That is the comment-stronger-than-code class
285
+ // (docs/false-safety-guards.md), and it hid in the path taken MOST often:
286
+ // the already-current reconnect (Copilot review, PR #7479).
287
+ if (ws.readyState !== 1) {
288
+ abort()
289
+ return
290
+ }
291
+ // An already-current client (startOffset === entries.length) still gets
292
+ // `onDone` — the empty-slice path, and the most common replay of all.
293
+ if (startOffset >= entries.length) {
294
+ if (onResume) onResume()
295
+ onDone()
296
+ } else {
297
+ sendChunk(startOffset)
298
+ }
299
+ }
300
+
301
+ /**
302
+ * #8374: the client capability that says "I can label a `permission_outcome` whose
303
+ * outcome is `stopped`". Advertised in the auth handshake (CLIENT_CAPABILITIES in
304
+ * @chroxy/protocol).
305
+ */
306
+ const CAPABILITY_PERMISSION_OUTCOME_STOPPED = 'permission_outcome_stopped_v1'
307
+
308
+ /**
309
+ * #6630: the client capability that says "a replayed `error` entry is safe to
310
+ * send me". Errors became part of the transcript (they used to be live-only), and
311
+ * a client build from before that raises its usage-limit alert for a rate-limit
312
+ * error even when it arrives in a replay, so an old app would pop the modal on
313
+ * every session switch for a quota that recovered long ago. Only a client that
314
+ * advertises this (the replay-aware builds) is sent the recorded errors; the rest
315
+ * get the transcript as it was, errors absent.
316
+ */
317
+ export const CAPABILITY_HISTORY_ERROR_REPLAY = 'history_error_replay_v1'
318
+
319
+ /**
320
+ * #6630: the client capability that says "a replayed reasoning entry with NO text is
321
+ * safe to send me". Current Claude models send a thinking block with only its
322
+ * signature, and the server records that as a response entry with `kind: 'thinking'`
323
+ * and empty content. A client build from before `kind` was understood renders it as
324
+ * an empty assistant bubble, one per turn, so only a client that advertises this is
325
+ * sent one. A reasoning entry WITH text is unchanged for everyone (older builds
326
+ * showed reasoning as an answer already).
327
+ */
328
+ export const CAPABILITY_HISTORY_THINKING_REPLAY = 'history_thinking_replay_v1'
329
+
330
+ /**
331
+ * #8470: the client capability that says "a replayed `user_question` carrying
332
+ * `superseded: true` is safe to send me". A newer question replaced it while it
333
+ * was open, so nobody answered it. A client build from before the flag was
334
+ * understood ignores the field and builds the question as a LIVE card: its answer
335
+ * controls are enabled until `history_replay_end` (a replay yields between chunks
336
+ * and can pause under backpressure), and it is then stamped "(resolved)", which
337
+ * reads as answered. Neither is true, and there is no older shape that says
338
+ * "replaced": so such a client is not sent the question at all (the `tool_start`
339
+ * for its tool is still replayed). Only the replay-aware builds get the verdict.
340
+ */
341
+ export const CAPABILITY_HISTORY_QUESTION_SUPERSEDED = 'history_question_superseded_v1'
342
+
343
+ /**
344
+ * #9022: the client capability that says "the text an open stream has produced so far
345
+ * may be replayed to me as an unnumbered `response` entry". A client build from before
346
+ * it reconciles that entry by id only: after a tool split it keeps the snapshot AND
347
+ * its own live `-cont-` bubble, and shows the text twice. It keeps main's behaviour
348
+ * (no snapshot) instead.
349
+ */
350
+ export const CAPABILITY_HISTORY_INFLIGHT_REPLY = 'history_inflight_reply_v1'
351
+
352
+ /**
353
+ * #8415: the client capability that says "I can apply a `tool_input_backfill` frame". A
354
+ * delta replay starts after the client's cursor, so the input the server learned for a
355
+ * tool card the client already holds (recorded without it) never reached it. A client
356
+ * that advertises this is sent that input as a reconcile-only frame; an older build does
357
+ * not know the frame and is sent nothing.
358
+ */
359
+ export const CAPABILITY_HISTORY_TOOL_INPUT_BACKFILL = 'history_tool_input_backfill_v1'
360
+
361
+ // #8415: private tag on a replay-slice item that is a `tool_input_backfill` frame, not
362
+ // a history entry. It lets the frames ride the same chunked, backpressure-aware,
363
+ // abort-guarded loop as the entries without passing through `sendHistoryEntry`
364
+ // (which would stamp `historySeq` on them).
365
+ const TOOL_INPUT_BACKFILL_FRAME = Symbol('toolInputBackfillFrame')
366
+
367
+ /**
368
+ * Write ONE history entry to a client, the way BOTH replay paths must.
369
+ *
370
+ * Two things happen per entry, and both were forgotten by the second copy of
371
+ * this loop — which is the whole reason this is a function (#7454, #7459):
372
+ *
373
+ * 1. #5555.3 — surface the server-internal `_seq` as `historySeq` (and strip
374
+ * the underscore-prefixed internal field) so the client can advance its
375
+ * per-session cursor as it applies each entry. #7420's live-vs-replayed
376
+ * discriminator keys on that field's PRESENCE, so a missing stamp reads as
377
+ * a live racer — and a fabricated one is just as wrong.
378
+ * 2. #4628 — mirror the live `result` → `agent_idle` fan-out from
379
+ * event-normalizer.js. `agent_idle` is the frame that clears a zombie
380
+ * "Running X" chip left by an orphan tool_start (a dropped PostToolUse
381
+ * hook, the #4628 root cause): the mobile app has no `activeTools` reader
382
+ * at all, and the dashboard's own `case 'result'` sweep is a redundant
383
+ * second copy of the same wipe rather than an independent one. The
384
+ * companion `_emitResult` sweep in BaseSession stops new orphans being
385
+ * persisted; this heals the sessions already wedged, on every replay path
386
+ * a user can reach.
387
+ *
388
+ * THIS PAIRING IS A WIRE CONTRACT, not an implementation detail (#7515).
389
+ * Until #7515 this comment claimed the clients' `case 'result'` was
390
+ * replay-gated "precisely so a replayed result cannot wipe" what
391
+ * `history_replay_start` preserves — which made the two halves of the
392
+ * paragraph contradict each other, since the very next frame wiped it
393
+ * regardless. The dashboard's gate is gone and its `result` sweep is
394
+ * unconditional again; both clients now depend on this synthesis being
395
+ * the authority. Removing it is a client-visible behaviour change, and
396
+ * `tests/ws-history.test.js`'s "emits synthetic agent_idle after each
397
+ * `result` entry …(#4628)" — which asserts the exact frame ORDER — is the
398
+ * test that must go red first if anyone tries.
399
+ *
400
+ * @param {(ws: WebSocket, payload: object) => void} send
401
+ * @param {WebSocket} ws
402
+ * @param {string} sessionId
403
+ * @param {object} entry - A ring-buffer entry, possibly carrying `_seq`.
404
+ * @param {{clientCapabilities?: Set<string>}|null} client - REQUIRED. The client
405
+ * RECORD (`clients.get(ws)`), which is where the auth handshake stores the
406
+ * capabilities it advertised. NOT `ws`: that is the raw socket and carries none
407
+ * (#8374). Omitting it (`undefined`) throws: a caller that forgot it used to
408
+ * downgrade every client to the older shape without a sound (#8431). `null` is
409
+ * the explicit, deliberate "no record, no capabilities" and is the only way to
410
+ * ask for that.
411
+ */
412
+ export function sendHistoryEntry(send, ws, sessionId, entry, client, isSessionBusy = () => false) {
413
+ if (client === undefined) {
414
+ throw new TypeError('sendHistoryEntry: `client` is required (pass clients.get(ws), or null for a deliberately capability-less replay)')
415
+ }
416
+ // #6630: a recorded error goes only to a client that said it can take one in a
417
+ // replay (see CAPABILITY_HISTORY_ERROR_REPLAY). Skipped, not downgraded: there is
418
+ // no older shape of an error bubble that is safe. Nothing else about the entry
419
+ // changes, and the stored entry is untouched for the clients that do advertise it.
420
+ if (
421
+ entry && entry.type === 'message' && entry.messageType === 'error'
422
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_ERROR_REPLAY) ?? false)
423
+ ) {
424
+ return
425
+ }
426
+ // #6630: a text-less reasoning entry goes only to a client that can render it (see
427
+ // CAPABILITY_HISTORY_THINKING_REPLAY). Skipped for the same reason as the error: an
428
+ // older build has no safe shape for it.
429
+ if (
430
+ entry && streamKindOf(entry) === 'thinking'
431
+ && (typeof entry.content !== 'string' || entry.content.length === 0)
432
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_THINKING_REPLAY) ?? false)
433
+ ) {
434
+ return
435
+ }
436
+ // #8470: a question a newer one replaced goes only to a client that can read the
437
+ // flag; see CAPABILITY_HISTORY_QUESTION_SUPERSEDED. Both the in-place entry and the
438
+ // tail copy carry it, so both are skipped.
439
+ if (
440
+ entry && entry.type === 'user_question' && entry.superseded === true
441
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_QUESTION_SUPERSEDED) ?? false)
442
+ ) {
443
+ return
444
+ }
445
+ // `sourceToolUseId` (#8336) is server-internal: it lets the restore-time sweep
446
+ // pair a recorded question with its tool_start, and no client reads it. Live
447
+ // broadcasts never carry it (the event normalizer picks fields), so the replay
448
+ // frame must not either.
449
+ // `answered` (#8362) is likewise server-only: the restore-time sweep reads it to
450
+ // leave an answered question unmarked, and a replayed question reads as resolved
451
+ // on the client already.
452
+ const { _seq, sourceToolUseId: _sourceToolUseId, answered: _answered, ...wireEntry } = entry
453
+ // #8374: a client build from before `stopped` existed drops a `permission_outcome`
454
+ // whose outcome it cannot parse, and a full rebuild then loses the record
455
+ // altogether. Say `expired` to a client that did not advertise it can label the
456
+ // new value: the record survives, only its label degrades. The stored entry is
457
+ // untouched (`wireEntry` is a copy), so a capable client still gets `stopped`.
458
+ // #6630: say on the frame that a recorded response was reasoning, including an
459
+ // entry an older run wrote without the field (classified by its message id),
460
+ // so the client rebuilds the thinking bubble the live stream showed rather than
461
+ // an answer. One classifier; the client reads the field and derives nothing.
462
+ if (streamKindOf(entry) === 'thinking') wireEntry.kind = 'thinking'
463
+ // #8503: a `permission_outcome` carries the tool input its prompt was shown with
464
+ // (already sanitized and capped when recorded). A restored entry whose `input`
465
+ // is not a plain object (a damaged or hand-edited state file) is sent without
466
+ // it rather than as something a client would have to defend against.
467
+ if (wireEntry.type === 'permission_outcome' && 'input' in wireEntry
468
+ && !(wireEntry.input && typeof wireEntry.input === 'object' && !Array.isArray(wireEntry.input))) {
469
+ delete wireEntry.input
470
+ }
471
+ // #8503: the decision token an `allowed` outcome carries; a restored entry whose
472
+ // token is not one the recorder would keep is sent without it.
473
+ if (wireEntry.type === 'permission_outcome' && 'decision' in wireEntry
474
+ && permissionOutcomeDecision(wireEntry.outcome, wireEntry.decision) === undefined) {
475
+ delete wireEntry.decision
476
+ }
477
+ if (wireEntry.type === 'permission_outcome' && wireEntry.outcome === 'stopped'
478
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_PERMISSION_OUTCOME_STOPPED) ?? false)) {
479
+ wireEntry.outcome = 'expired'
480
+ }
481
+ // `replayed: true` on a result is the explicit "this is history" mark (#8965): a
482
+ // JSONL full-history slice strips `_seq` (so no historySeq) yet still carries the
483
+ // daemon-written interrupted-turn result, and a client must not read that as the
484
+ // live turn ending.
485
+ send(ws, {
486
+ ...wireEntry,
487
+ sessionId,
488
+ ...(typeof _seq === 'number' ? { historySeq: _seq } : {}),
489
+ ...(entry && entry.type === 'result' ? { replayed: true } : {}),
490
+ })
491
+ // The synthesized `agent_idle` mirrors the live fan-out so a client clears the
492
+ // turn-scoped state a dropped event left behind (#4628). It must NOT be sent
493
+ // while the session is BUSY (#8965): the entry is an OLD turn's result, the
494
+ // client has nothing to clear for the turn that is still running, and the frame
495
+ // flips the client's isIdle to true -- where nothing sets it back until the next
496
+ // stream_start -- so the Send button shows during a run and a second replay of
497
+ // the same turn sees an idle session. Busy is asked per result, because a replay
498
+ // is chunked and a turn can start part-way through it. The JSONL heal
499
+ // (conversation-handlers.js) already holds the same line. An idle session still
500
+ // gets it.
501
+ if (entry && entry.type === 'result' && !isSessionBusy()) {
502
+ send(ws, { type: 'agent_idle', sessionId })
503
+ }
504
+ }
505
+
159
506
  /**
160
507
  * Send all post-authentication info to a newly authenticated client.
161
508
  * This includes auth_ok, server mode, session list, model/permission state,
@@ -167,7 +514,7 @@ export function scheduleAfterDrain(ws, fn) {
167
514
  export function sendPostAuthInfo(ctx, ws, extra = {}) {
168
515
  const {
169
516
  clients, sessionManager, cliSession, defaultSessionId,
170
- serverMode, serverVersion, latestVersion, gitInfo,
517
+ serverMode, serverVersion, latestVersion, dashboardBuildId, gitInfo,
171
518
  encryptionEnabled, localhostBypass, tunnelActive, keyExchangeTimeoutMs,
172
519
  protocolVersion, minProtocolVersion, webTaskManager,
173
520
  // #5721: `send` MUST be `WsServer._send` (which returns the delivery
@@ -190,6 +537,16 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
190
537
  // surfaced as the `orchestration` capability so the dashboard reveals the
191
538
  // Runs surface. Optional — absent → false (fail-closed) for old servers.
192
539
  orchestrationEnabled,
540
+ // #8619: whether `allowAutoPermissionMode: true` is set in the local
541
+ // config, surfaced as the `autoPermissionMode` capability so clients can
542
+ // disable Auto in their mode pickers and say why. Optional — absent →
543
+ // false (fail-closed) for old callers / test harnesses.
544
+ autoPermissionModeAllowed,
545
+ // Whether this daemon names an unnamed new session after its project ("chroxy 7"),
546
+ // i.e. SessionManager runs with sessionNaming 'project'. Surfaced as the
547
+ // `projectSessionNames` capability so a client can stop prefilling/requiring a name.
548
+ // Optional — absent → false (fail-closed): an older daemon keeps today's client behaviour.
549
+ projectSessionNames,
193
550
  // #6006: whether the server has a rotating TokenManager (i.e. auth is on),
194
551
  // so the operator panic button (`revoke_token`) can fire. Surfaced as the
195
552
  // `tokenRevoke` capability, gated to primary-token clients below. Optional —
@@ -212,6 +569,12 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
212
569
  billingCanary,
213
570
  // #5536: long-lived identity keypair for signing the eager exchange key.
214
571
  serverIdentity,
572
+ // #8331: the daily-daemon update status; sent below to strict-primary,
573
+ // unbound clients only. Optional — absent on old callers and test harnesses.
574
+ daemonUpdate,
575
+ // #7821: configured explicit agent routes. Kept on the history context so
576
+ // auth_ok feature derivation and auth_bootstrap use the same live config.
577
+ agentConnections,
215
578
  } = ctx
216
579
  const client = clients.get(ws)
217
580
 
@@ -219,7 +582,11 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
219
582
  let sessionInfo = {}
220
583
  // #6638: the active session's provider, captured for the auth_ok permission-mode
221
584
  // copy (Codex gets codex-tuned descriptions). `entry` below is block-scoped, so
222
- // hoist the provider to function scope.
585
+ // hoist the provider to function scope. #7811: this is `null` when there is no
586
+ // active session, so it is resolved through `resolveRosterProvider` at the
587
+ // send site below (same as `rosterProvider` further down this function)
588
+ // rather than used directly — otherwise a codex-default daemon would fold
589
+ // the CLAUDE mode copy into auth_ok for a client that has no session yet.
223
590
  let authOkProvider = null
224
591
  if (sessionManager) {
225
592
  // #6687: resolve the active session with the SAME precedence block 2 uses to
@@ -250,7 +617,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
250
617
  }
251
618
  // If client is bound to a specific session, use that session's cwd
252
619
  // instead of the server default to avoid leaking unrelated session info.
253
- if (client.boundSessionId) {
620
+ if (isBoundClient(client)) {
254
621
  const boundEntry = sessionManager.getSession(client.boundSessionId)
255
622
  if (boundEntry) {
256
623
  entry = boundEntry
@@ -373,7 +740,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
373
740
  client.eagerKeyExchange = null
374
741
  }
375
742
 
376
- const providers = listProviders()
743
+ const providers = listProviders({ agentConnections })
377
744
  const features = {
378
745
  environments: providers.some(p => p.capabilities?.containerized),
379
746
  }
@@ -405,6 +772,17 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
405
772
  // (older server) fall back to requesting the three lists as before. The
406
773
  // request handlers stay live either way for post-connect refreshes.
407
774
  authBootstrap: true,
775
+ // #7821 — provider_list/auth_bootstrap include versioned, non-secret agent
776
+ // connection descriptors and create_session accepts an explicit connectionId.
777
+ // New clients require this flag before presenting strong route selection;
778
+ // older clients keep provider-only creation and receive a legacy descriptor.
779
+ agentConnections: true,
780
+ // #8303 — `list_directory` accepts an optional `requestId` and `directory_listing`
781
+ // echoes it. The New Session browsability probe sends only to a server that
782
+ // advertises this: an older one answers untagged, and an untagged reply lands
783
+ // in the shared listing slot (autocomplete / the picker), where an error wipes
784
+ // autocomplete's suggestions.
785
+ directoryListingRequestIdV1: true,
408
786
  // #6481 (epic #6469): the opt-in IDE feature surface (file navigator, symbol
409
787
  // navigation, go-to-definition, find-references, edit-in-place) is enabled on
410
788
  // THIS server (config.features.ide / CHROXY_ENABLE_IDE). Clients gate ALL IDE
@@ -417,6 +795,15 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
417
795
  // Clients gate the Runs surface on this flag; absent/false (default, or older
418
796
  // servers) → no orchestration chrome (fail-closed).
419
797
  orchestration: orchestrationEnabled === true,
798
+ // #8619: the operator's `allowAutoPermissionMode` opt-in. Server-wide, not
799
+ // token-scoped, and NOT a promise that any one session can switch: a
800
+ // paired (bound) client is still refused (AUTO_MODE_FORBIDDEN_BOUND_CLIENT)
801
+ // and an adapter without `autoPermissionMode` still has no Auto. It tells
802
+ // a client only whether the config gate would admit a switch, so it can
803
+ // disable Auto with the real reason instead of a generic tooltip.
804
+ autoPermissionMode: autoPermissionModeAllowed === true,
805
+ // Unnamed sessions are named after their project by this daemon (sessionNaming 'project').
806
+ projectSessionNames: projectSessionNames === true,
420
807
  // #6871 (epic #6784): this server has the scheduled-tasks WS surface
421
808
  // (scheduled_tasks_request / scheduled_task_action / set_scheduler_enabled +
422
809
  // the `scheduled_tasks` snapshot). CONSTANT true — deliberately NOT tied to
@@ -425,6 +812,18 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
425
812
  // hide exactly the banner that tells an operator their saved tasks will never
426
813
  // fire. Clients read the real gate state off the snapshot's `scheduler` block.
427
814
  scheduledTasks: true,
815
+ // #7822 — this server validates a versioned selected-context envelope,
816
+ // correlates acceptance with clientMessageId, and rejects unsupported
817
+ // kinds/lifetimes instead of letting an older passthrough schema drop them.
818
+ // New clients must gate context sends on this flag; old clients omit the
819
+ // envelope and continue through the legacy input path.
820
+ inputContextV1: true,
821
+ // #7977 — `create_session` accepts a client `requestId` and echoes it on the
822
+ // create-confirm `session_switched` and every error for that create. A client
823
+ // that needs the correlation (agent-control) must refuse to create on a daemon
824
+ // that lacks this flag: an older daemon would create the session and never
825
+ // echo, orphaning it behind a timeout.
826
+ createRequestIdV1: true,
428
827
  // #5986 (epic #5982) — the embedded user-shell terminal is available to THIS
429
828
  // client: the server has it enabled (userShell.enabled) AND this connection
430
829
  // holds the primary token. Both conditions of the create gate are reflected
@@ -488,28 +887,43 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
488
887
  ? streamStallTimeoutMs
489
888
  : DEFAULT_STREAM_STALL_TIMEOUT_MS
490
889
 
890
+ // #7811: same fallback the roster send further down this function applies —
891
+ // fold in the daemon's resolved default when there is no active session,
892
+ // instead of the CLAUDE default copy that `permissionModesForProvider(null)`
893
+ // returns. Otherwise a codex-default daemon's auth_ok would carry Claude's
894
+ // mode picker text.
895
+ const authOkRosterProvider = resolveRosterProvider(authOkProvider, billingCanary?.defaultProvider)
491
896
  const authOkDelivered = send(ws, {
492
897
  type: 'auth_ok',
493
898
  clientId: client.id,
494
899
  serverMode,
495
900
  serverVersion,
496
901
  latestVersion,
902
+ // #8268: id of the dashboard bundle the daemon serves now; a page that loaded a
903
+ // different one is stale. Omitted (not null) when no dist is built.
904
+ ...(dashboardBuildId ? { dashboardBuildId } : {}),
497
905
  serverCommit: gitInfo.commit,
498
- cwd: sessionInfo.cwd,
499
- defaultCwd: sessionManager?.defaultCwd || null,
500
- connectedClients: getConnectedClientList(),
906
+ // A principal is told nothing about any session or peer at the source (#9116).
907
+ cwd: isPrincipalClient(client) ? null : sessionInfo.cwd,
908
+ // A session-scoped connection is told about its own session only: not the
909
+ // host's default working directory, and only the peers sharing its session.
910
+ defaultCwd: isBoundClient(client) ? null : (sessionManager?.defaultCwd || null),
911
+ connectedClients: isPrincipalClient(client) ? [] : getConnectedClientList(client),
501
912
  encryption: requireEncryption ? 'required' : 'disabled',
502
913
  protocolVersion,
503
914
  minProtocolVersion,
504
915
  maxProtocolVersion: protocolVersion,
505
916
  webFeatures: webTaskManager.getFeatureStatus(),
506
917
  features,
507
- capabilities,
918
+ capabilities: { ...capabilities, ...(extra.sessionToken ? { pairedCredentialConfirmation: true } : {}) },
508
919
  // #5555 — fold the static permission-mode enum into auth_ok so a new
509
920
  // client never has to wait for (or react to) the discrete
510
921
  // `available_permission_modes` burst frame. The discrete frame is still
511
922
  // sent below for older clients that read the enum only from it.
512
- availablePermissionModes: getPermissionModes(authOkProvider),
923
+ availablePermissionModes: permissionModesForProvider(authOkRosterProvider),
924
+ // #8224 — the roster is a fact about a provider; name it so the client files
925
+ // it under that provider instead of in a slot the next session inherits.
926
+ availablePermissionModesProvider: authOkRosterProvider,
513
927
  resultTimeoutMs: effectiveResultTimeoutMs,
514
928
  hardTimeoutMs: effectiveHardTimeoutMs,
515
929
  streamStallTimeoutMs: effectiveStreamStallTimeoutMs,
@@ -539,6 +953,8 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
539
953
  ? { newIdentityKey: serverIdentity.publicKey, rotationCert: serverIdentity.rotationCert }
540
954
  : {}),
541
955
  ...extra,
956
+ ...(extra.sessionToken && client.clientCapabilities?.has('paired_credential_confirmation_v1')
957
+ ? { sessionToken: undefined } : {}),
542
958
  })
543
959
 
544
960
  // #5555: now that the plaintext auth_ok (carrying serverPublicKey) has been
@@ -580,7 +996,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
580
996
  client.encryptionPending = false
581
997
  client.postAuthQueue = null
582
998
  try {
583
- ws.send(JSON.stringify({ type: 'server_error', message: 'Encryption required but key exchange timed out. Please reconnect.', recoverable: false }))
999
+ sendRawTransport(ws, client, { type: 'server_error', message: 'Encryption required but key exchange timed out. Please reconnect.', recoverable: false })
584
1000
  } catch (_) {}
585
1001
  // Guard close() too: if the socket is already CLOSING/CLOSED when this
586
1002
  // timer fires (a race with a concurrent client disconnect), a bare
@@ -593,13 +1009,37 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
593
1009
  }, keyExchangeTimeoutMs)
594
1010
  }
595
1011
 
1012
+ // #9116: an agent principal's bootstrap ENDS at auth_ok (plus the key exchange it
1013
+ // gates). It is sent no session list, no replay and none of the host-wide burst below:
1014
+ // its reads are the `principal_*` family, and what it may see is decided per frame at
1015
+ // the outgoing choke point. Stopping here also keeps the sentinel binding out of every
1016
+ // bound-session lookup that follows.
1017
+ if (isPrincipalClient(client)) return
1018
+
1019
+ // Confirm the credential through the completed transport independently of catalogs.
1020
+ if (extra.sessionToken && client.clientCapabilities?.has('paired_credential_confirmation_v1')) {
1021
+ send(ws, { type: 'auth_bootstrap', credentialConfirmation: true, sessionToken: extra.sessionToken })
1022
+ }
1023
+
596
1024
  send(ws, { type: 'server_mode', mode: serverMode })
597
1025
  send(ws, { type: 'status', connected: true })
598
1026
 
1027
+ // #8331: the "update ready" banner's data. The SAME bar as the
1028
+ // `daemon_update_action` it exists to drive: strict primary token AND unbound.
1029
+ // A paired phone (an unbound pairing token) must not be told which commits are
1030
+ // queued for the owner's machine, and a bound client sees nothing host-level.
1031
+ if (daemonUpdate && client?.isPrimaryToken === true && !isBoundClient(client)) {
1032
+ try {
1033
+ send(ws, { type: 'daemon_update_status', ...daemonUpdate.getStatus() })
1034
+ } catch (err) {
1035
+ log.warn(`daemon_update_status failed for ${client.id}: ${err?.message || err}`)
1036
+ }
1037
+ }
1038
+
599
1039
  // Multi-session mode
600
1040
  if (sessionManager) {
601
1041
  let sessions = sessionManager.listSessions()
602
- if (client.boundSessionId) {
1042
+ if (isBoundClient(client)) {
603
1043
  sessions = sessions.filter(s => s.sessionId === client.boundSessionId)
604
1044
  }
605
1045
  send(ws, { type: 'session_list', sessions })
@@ -607,7 +1047,8 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
607
1047
  // #5665: send the current monthly programmatic-credit meter snapshot so a
608
1048
  // freshly-connected dashboard shows it immediately, not only after the next
609
1049
  // billed turn. Machine-wide, so it's sent regardless of boundSessionId.
610
- if (typeof sessionManager.getMonthlyBudgetStatus === 'function') {
1050
+ // Not sent to a session-scoped connection: it is the host's spend, not the session's.
1051
+ if (typeof sessionManager.getMonthlyBudgetStatus === 'function' && !isBoundClient(client)) {
611
1052
  send(ws, { type: 'monthly_budget', ...sessionManager.getMonthlyBudgetStatus() })
612
1053
  }
613
1054
 
@@ -616,12 +1057,13 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
616
1057
  // reconnect after the event fired.
617
1058
  if (typeof sessionManager.getFailedRestores === 'function') {
618
1059
  for (const failed of sessionManager.getFailedRestores()) {
619
- if (client.boundSessionId && failed.sessionId !== client.boundSessionId) continue
1060
+ if (isBoundClient(client) && failed.sessionId !== client.boundSessionId) continue
620
1061
  send(ws, {
621
1062
  type: 'session_restore_failed',
622
1063
  sessionId: failed.sessionId,
623
1064
  name: failed.name,
624
1065
  provider: failed.provider,
1066
+ agentConnection: failed.agentConnection,
625
1067
  cwd: failed.cwd,
626
1068
  model: failed.model,
627
1069
  permissionMode: failed.permissionMode,
@@ -674,7 +1116,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
674
1116
  // any persisted per-device preference. Fail closed: if the bound session
675
1117
  // no longer exists, clear the active session rather than silently falling
676
1118
  // back to a different session (or inheriting an unrelated persisted pref).
677
- if (client.boundSessionId) {
1119
+ if (isBoundClient(client)) {
678
1120
  const boundEntry = sessionManager.getSession(client.boundSessionId)
679
1121
  if (boundEntry) {
680
1122
  activeId = client.boundSessionId
@@ -724,17 +1166,39 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
724
1166
  // class — getRegistryForProvider returns a provider-scoped registry
725
1167
  // seeded from that list. Claude providers share the default registry
726
1168
  // that is fed by `supportedModels()` on each SDK init.
1169
+ // #7728/#7759 — `activeProvider` is null on any post-auth connect with no
1170
+ // active session, and a null TAG is filed in the client's UNTAGGED bucket,
1171
+ // which it serves to a session of any provider while it is the only roster
1172
+ // it knows — a Claude roster labelled "could be anyone's". So the roster is
1173
+ // tagged with the daemon's resolved default instead, and its registry is
1174
+ // resolved from that SAME name (`resolveRosterProvider`) so the tag names
1175
+ // the registry that actually produced the rows.
1176
+ //
1177
+ // `activeProvider` itself is deliberately left as-is for the discovery
1178
+ // refresh below: that must keep no-opping for a client that has no
1179
+ // session. The permission-mode copy is a DIFFERENT statement — #7811: it
1180
+ // used to also read `activeProvider` (null with no session), so a
1181
+ // codex-default daemon paired the correctly-tagged `rosterProvider` roster
1182
+ // above with the CLAUDE mode-picker copy. It now reads `rosterProvider`
1183
+ // too, same as the roster it describes.
727
1184
  const activeProvider = entry?.provider || null
728
- const activeRegistry = getRegistryForProvider(activeProvider)
729
- send(ws, { type: 'available_models', models: activeRegistry.getModels(), defaultModel: activeRegistry.getDefaultModelId(), provider: activeProvider })
1185
+ const rosterProvider = resolveRosterProvider(activeProvider, billingCanary?.defaultProvider)
1186
+ const activeRegistry = getRegistryForProvider(rosterProvider)
1187
+ send(ws, { type: 'available_models', models: activeRegistry.getModels(), defaultModel: activeRegistry.getDefaultModelId(), provider: rosterProvider })
730
1188
  // #5421/#5555: dynamic-discovery refresh (ollama /api/tags). `sendSessionInfo`
731
1189
  // above was told to skip its own `available_models` push (de-dupe on connect),
732
1190
  // so it also skipped scheduling the refresh — this path now owns the single
733
1191
  // schedule. With no active session activeProvider is null and there is nothing
734
1192
  // to refresh (scheduleProviderModelsRefresh no-ops on a null provider).
735
1193
  scheduleProviderModelsRefresh(ctx, ws, activeProvider)
736
- send(ws, { type: 'available_permission_modes', modes: getPermissionModes(activeProvider) })
737
- permissions.resendPendingPermissions(ws, client)
1194
+ send(ws, { type: 'available_permission_modes', modes: permissionModesForProvider(rosterProvider), provider: rosterProvider })
1195
+ // #9015: the active session's prompts are NOT sent here. `replayHistory`
1196
+ // above always ends in `resendPendingPermissionsForSession` (its empty-history
1197
+ // early return and its `finishReplay` both call it), which delivers them
1198
+ // after `history_replay_end`; sending them here too put two copies on the
1199
+ // wire ~1 ms apart. Every other session, and ownerless hook-held prompts,
1200
+ // still go out through this unfiltered call.
1201
+ permissions.resendPendingPermissions(ws, client, entry ? { excludeSessionId: activeId } : undefined)
738
1202
  // #5555: fire the connect-time bootstrap burst (providers + slash commands
739
1203
  // + agents) so a new client never sends its 3-request list_* round trip.
740
1204
  // Fire-and-forget — the slash/agent compute is async (disk scans) and the
@@ -744,7 +1208,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
744
1208
  const bootMcpPrompts = typeof entry?.session?.getMcpPromptCommands === 'function'
745
1209
  ? entry.session.getMcpPromptCommands()
746
1210
  : []
747
- sendAuthBootstrap(ctx, ws, { cwd: entry?.cwd || null, provider: activeProvider, sessionId: activeId, mcpPrompts: bootMcpPrompts })
1211
+ sendAuthBootstrap(ctx, ws, { scoped: isBoundClient(client), cwd: entry?.cwd || null, provider: activeProvider, sessionId: activeId, mcpPrompts: bootMcpPrompts, sessionToken: client.clientCapabilities?.has('paired_credential_confirmation_v1') ? undefined : extra.sessionToken })
748
1212
  return
749
1213
  }
750
1214
 
@@ -767,23 +1231,27 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
767
1231
  // #6368: scope the legacy single-session model list to the ACTIVE provider's
768
1232
  // registry (the cliSession is the default-provider session) instead of the
769
1233
  // Claude-only module-level getModels(). billingCanary.defaultProvider is the
770
- // resolved `config.provider || DEFAULT_PROVIDER`; for Claude (or a null/absent
771
- // canary on old ctx) getRegistryForProvider falls back to the default Claude
772
- // registry, so behaviour is unchanged today.
773
- const legacyProvider = billingCanary?.defaultProvider || null
1234
+ // resolved `config.provider || DEFAULT_PROVIDER`.
1235
+ //
1236
+ // #7759 — an absent canary (old ctx / test fixture) used to leave this
1237
+ // `null`, which resolves to the default Claude registry and then tags the
1238
+ // roster it produced as UNTAGGED at the client. The registry is the same
1239
+ // one either way — DEFAULT_PROVIDER is Claude-family — so what changes is
1240
+ // only that the send now NAMES it.
1241
+ const legacyProvider = resolveRosterProvider(null, billingCanary?.defaultProvider)
774
1242
  const legacyRegistry = getRegistryForProvider(legacyProvider)
775
1243
  send(ws, { type: 'available_models', models: legacyRegistry.getModels(), defaultModel: legacyRegistry.getDefaultModelId(), provider: legacyProvider })
776
1244
  send(ws, {
777
1245
  type: 'permission_mode_changed',
778
1246
  mode: cliSession.permissionMode || 'approve',
779
1247
  })
780
- send(ws, { type: 'available_permission_modes', modes: getPermissionModes(legacyProvider) })
1248
+ send(ws, { type: 'available_permission_modes', modes: permissionModesForProvider(legacyProvider), provider: legacyProvider })
781
1249
  }
782
1250
 
783
- permissions.resendPendingPermissions(ws)
1251
+ permissions.resendPendingPermissions(ws, client)
784
1252
  // #5555: legacy single-session bootstrap burst — providers + slash commands
785
1253
  // + agents for the cliSession's cwd (no provider scoping in legacy mode).
786
- sendAuthBootstrap(ctx, ws, { cwd: cliSession?.cwd || null, provider: null, sessionId: null })
1254
+ sendAuthBootstrap(ctx, ws, { scoped: isBoundClient(client), cwd: cliSession?.cwd || null, provider: null, sessionId: null, sessionToken: client.clientCapabilities?.has('paired_credential_confirmation_v1') ? undefined : extra.sessionToken })
787
1255
  }
788
1256
 
789
1257
  /**
@@ -814,8 +1282,18 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
814
1282
  * @param {{ cwd: string|null, provider: string|null, sessionId: string|null }} info
815
1283
  */
816
1284
  function sendAuthBootstrap(ctx, ws, info = {}) {
817
- const { send, services } = ctx
1285
+ const { send, services, agentConnections } = ctx
818
1286
  const fileOps = ctx.fileOps || services?.fileOps || null
1287
+ // #8151 round-2 review (Critical 1) — the real WsServer's `_historyCtx`
1288
+ // carries `config` FLAT (matching `fileOps`/`tunnelUrl` above), never
1289
+ // nested under `services` (that nesting is `_handlerCtx`'s shape, used by
1290
+ // settings-handlers.js's list_providers). Reading ONLY `services?.config`
1291
+ // here silently resolved to `undefined` on every real connection — never
1292
+ // caught because the round-2 test built its ctx by hand, with exactly
1293
+ // the `services.config` shape the (buggy) code expected. Same
1294
+ // either-shape fallback as `fileOps`, so a differently-shaped test ctx
1295
+ // (or a future caller) still works.
1296
+ const config = ctx.config || services?.config || null
819
1297
  const cwd = info.cwd || null
820
1298
  const provider = info.provider || null
821
1299
  // #6823: MCP prompts to fold into the bootstrap slash-command list (empty for
@@ -824,9 +1302,15 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
824
1302
 
825
1303
  // providers is a cheap synchronous read off the registry — same source as
826
1304
  // the list_providers handler.
1305
+ // A session-scoped connection gets neither: the provider list carries the
1306
+ // host's credential readiness and configured connections, and the slash-command
1307
+ // and agent catalogs fall back to the user-level directories when no session
1308
+ // directory resolves. Both still arrive per request for what the connection is
1309
+ // allowed to ask (its own session's catalogs).
1310
+ const scoped = info.scoped === true
827
1311
  let providers = []
828
1312
  try {
829
- providers = listProviders()
1313
+ providers = scoped ? [] : listProviders({ agentConnections })
830
1314
  } catch (err) {
831
1315
  log.warn(`auth_bootstrap: listProviders failed: ${err.message}`)
832
1316
  providers = []
@@ -834,17 +1318,20 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
834
1318
 
835
1319
  // slash commands + agents are async disk scans; compute in parallel and
836
1320
  // tolerate either failing on its own.
837
- const slashP = fileOps && typeof fileOps.computeSlashCommands === 'function'
838
- ? fileOps.computeSlashCommands(cwd, provider, mcpPrompts).catch(err => {
1321
+ const catalogsAllowed = !scoped || cwd !== null
1322
+ const slashP = catalogsAllowed && fileOps && typeof fileOps.computeSlashCommands === 'function'
1323
+ ? fileOps.computeSlashCommands(cwd, provider, mcpPrompts, { projectOnly: scoped }).catch(err => {
839
1324
  log.warn(`auth_bootstrap: computeSlashCommands failed: ${err.message}`)
840
1325
  return []
841
1326
  })
842
1327
  : Promise.resolve([])
843
1328
  const userAgentsDirs = ctx.userAgentsDirs
844
- const agentsOpts = Array.isArray(userAgentsDirs) && userAgentsDirs.length > 0
845
- ? { userAgentsDirs }
846
- : {}
847
- const agentsP = fileOps && typeof fileOps.computeAgents === 'function'
1329
+ const agentsOpts = {
1330
+ ...(Array.isArray(userAgentsDirs) && userAgentsDirs.length > 0 ? { userAgentsDirs } : {}),
1331
+ // A session-scoped connection is bootstrapped with the project's agents only.
1332
+ projectOnly: scoped,
1333
+ }
1334
+ const agentsP = catalogsAllowed && fileOps && typeof fileOps.computeAgents === 'function'
848
1335
  ? fileOps.computeAgents(cwd, agentsOpts).catch(err => {
849
1336
  log.warn(`auth_bootstrap: computeAgents failed: ${err.message}`)
850
1337
  return []
@@ -857,7 +1344,11 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
857
1344
  if (ws.readyState !== 1) return
858
1345
  send(ws, {
859
1346
  type: 'auth_bootstrap',
1347
+ ...(info.sessionToken ? { sessionToken: info.sessionToken } : {}),
860
1348
  providers,
1349
+ // #8151 (C3) — same field/derivation as list_providers' response; see
1350
+ // handleListProviders (settings-handlers.js).
1351
+ defaultProvider: resolveDaemonDefaultProvider(config),
861
1352
  slashCommands,
862
1353
  agents,
863
1354
  ...(info.sessionId ? { sessionId: info.sessionId } : {}),
@@ -891,6 +1382,25 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
891
1382
  * Advisory only — this path feeds the picker; model VALIDATION for ollama
892
1383
  * stays unrestricted via getAllowedModels() returning null (a user can
893
1384
  * `ollama pull` mid-session or use an alias the tag list doesn't spell out).
1385
+ *
1386
+ * #8036 — this is also the ONLY production call site that reaches
1387
+ * `CodexSession.refreshModels()` with no live client: `probeCodexCatalog`
1388
+ * (codex-model-catalog.js) then spawns a short-lived `codex app-server` from
1389
+ * `ProviderClass.resolvedBinary` — a fresh, UNVERIFIED resolve — to answer
1390
+ * `model/list` on every post-auth `available_models` push. A `bin` thunk built
1391
+ * from `SessionManager.verifyOneShotExecutable(ProviderClass)` (#8030's
1392
+ * verified one-shot gate, generalized to take a provider class) is threaded
1393
+ * into `refreshModels(deps)` so that spawn is refused exactly like a fresh
1394
+ * codex chat session would be in `binaryProvenance.mode: 'block'`. Harmless
1395
+ * for every OTHER `refreshModels` implementation (ollama's HTTP `/api/tags`
1396
+ * probe, the anthropic-compatible catalog probe) — neither reads a `bin` key
1397
+ * from `deps`, so the extra property is simply ignored.
1398
+ *
1399
+ * Fails CLOSED when `ctx.sessionManager` is unavailable or too old to expose
1400
+ * `verifyOneShotExecutable` (a stubbed/minimal ctx in a test, or a future
1401
+ * refactor): the `bin` thunk still refuses rather than silently falling back
1402
+ * to `ProviderClass`'s own unverified default — same convention
1403
+ * `summarize-handlers.js` uses for the #8030 summarizer gate.
894
1404
  */
895
1405
  export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
896
1406
  if (!providerName) return
@@ -901,8 +1411,16 @@ export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
901
1411
  return // unknown provider — nothing to refresh
902
1412
  }
903
1413
  if (typeof ProviderClass?.refreshModels !== 'function') return
1414
+ const sessionManager = ctx?.sessionManager
1415
+ const verifyBin = typeof sessionManager?.verifyOneShotExecutable === 'function'
1416
+ ? () => sessionManager.verifyOneShotExecutable(ProviderClass)
1417
+ : () => {
1418
+ const err = new Error(`model refresh for provider ${providerName}: sessionManager.verifyOneShotExecutable is unavailable — refusing an unverified spawn (#8036)`)
1419
+ err.code = 'PROVIDER_BINARY_UNVERIFIED'
1420
+ throw err
1421
+ }
904
1422
  Promise.resolve()
905
- .then(() => ProviderClass.refreshModels())
1423
+ .then(() => ProviderClass.refreshModels({ bin: verifyBin }))
906
1424
  .then((models) => {
907
1425
  if (!Array.isArray(models) || models.length === 0) return
908
1426
  if (ws.readyState !== undefined && ws.readyState !== 1) return // client gone
@@ -933,33 +1451,74 @@ export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
933
1451
  * re-tags the dashboard's provider.
934
1452
  */
935
1453
  export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
936
- const { sessionManager, send } = ctx
1454
+ const { sessionManager, send, billingCanary, clients } = ctx
937
1455
  const entry = sessionManager?.getSession(sessionId)
938
1456
  if (!entry) return
939
1457
  const session = entry.session
940
1458
 
1459
+ if (entry.declaredStatus) send(ws, { type: 'session_status', sessionId, declaredStatus: { ...entry.declaredStatus } })
1460
+
1461
+ send(ws, {
1462
+ type: 'provider_runtime_info',
1463
+ sessionId,
1464
+ ...getProviderRuntimeInfo(entry.provider, session),
1465
+ })
1466
+
941
1467
  if (session.isReady) {
942
1468
  send(ws, { type: 'claude_ready', sessionId })
943
1469
  }
944
1470
  // #4302: push the new session's provider-scoped model list on every
945
- // switch. Without this, the dashboard's `availableModelsProvider` stays
946
- // tagged with whichever provider the client saw last (set on auth via
947
- // `sendPostAuthInfo`), and `modelsMatchProvider` in App.tsx suppresses
948
- // the model picker for any session whose provider differs from the
949
- // initial one — most visibly, a claude-cli session created after a
950
- // TUI/SDK session loses its picker entirely.
1471
+ // switch. Without this a client never learns the roster of a provider it
1472
+ // did not see at auth time (`sendPostAuthInfo`) — pre-#7728 that showed up
1473
+ // as the dashboard's single `availableModelsProvider` tag staying pinned to
1474
+ // the provider seen last, suppressing the picker for every other session;
1475
+ // since #7728 each roster is keyed by provider, so what a missing push
1476
+ // leaves behind is an EMPTY roster for that provider — no picker, and no
1477
+ // ids belonging to a provider that TAGGED its broadcast.
1478
+ //
1479
+ // #7759 — and no UNTAGGED roster either, on any send path: an entry that
1480
+ // reports no provider (and `sendPostAuthInfo`'s no-active-session case) used
1481
+ // to tag `null`, which the client files in the bucket that means "a
1482
+ // pre-provider daemon" and then serves to a session of any provider. The tag
1483
+ // is the daemon's resolved default in that case, and the registry is
1484
+ // resolved from that same name.
951
1485
  if (!opts.skipModels) {
952
- const activeProvider = entry.provider || null
953
- const activeRegistry = getRegistryForProvider(activeProvider)
1486
+ const rosterProvider = resolveRosterProvider(entry.provider, billingCanary?.defaultProvider)
1487
+ const activeRegistry = getRegistryForProvider(rosterProvider)
954
1488
  send(ws, {
955
1489
  type: 'available_models',
956
1490
  models: activeRegistry.getModels(),
957
1491
  defaultModel: activeRegistry.getDefaultModelId(),
958
- provider: activeProvider,
1492
+ provider: rosterProvider,
959
1493
  })
1494
+ // #8224 — and the permission-mode roster for that same provider. Plan,
1495
+ // Auto and the mode copy differ per provider (claude-tui cannot plan,
1496
+ // claude-sdk can), and this is the one call every path that makes a session
1497
+ // the client's ACTIVE one already makes — create, switch, destroy re-home,
1498
+ // conversation resume, checkpoint rewind of another client — where
1499
+ // `switch_session` used to be the only one that sent it, so a
1500
+ // create-and-auto-switch left the PREVIOUS session's roster in place
1501
+ // ("Plan (unavailable)" on a fresh claude-sdk session beside an active
1502
+ // claude-tui one). Tagged with the provider, so a client keys it by provider.
1503
+ //
1504
+ // Sent ONLY for the client's active session. `handleSubscribeSessions` calls
1505
+ // this for every background session on every `session_list`; a client older
1506
+ // than #8224 keeps one flat roster slot and would end each connect on a
1507
+ // BACKGROUND session's roster. Clients that key by provider lose nothing: the
1508
+ // connect burst, create and switch each cover the active session. (The
1509
+ // connect burst passes `skipModels` and sends its own tagged roster.)
1510
+ if (clients?.get(ws)?.activeSessionId === sessionId) {
1511
+ send(ws, {
1512
+ type: 'available_permission_modes',
1513
+ modes: getPermissionModes(rosterProvider, session.constructor),
1514
+ provider: rosterProvider,
1515
+ })
1516
+ }
960
1517
  // #5421: background dynamic-discovery refresh (ollama /api/tags); a
961
- // changed list is re-pushed to this client when the probe lands.
962
- scheduleProviderModelsRefresh(ctx, ws, activeProvider)
1518
+ // changed list is re-pushed to this client when the probe lands. Keyed on
1519
+ // the session's OWN provider, not the roster tag — a session that reports
1520
+ // none has nothing to probe.
1521
+ scheduleProviderModelsRefresh(ctx, ws, entry.provider || null)
963
1522
  }
964
1523
  send(ws, {
965
1524
  type: 'model_changed',
@@ -979,13 +1538,9 @@ export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
979
1538
  sessionId,
980
1539
  })
981
1540
  // Always sync thinking level on reconnect so stale dashboard state is overwritten
982
- const thinkingLevel = session.thinkingLevel
983
- if (thinkingLevel !== undefined) {
984
- send(ws, {
985
- type: 'thinking_level_changed',
986
- level: thinkingLevel || 'default',
987
- sessionId,
988
- })
1541
+ const thinkingLevelMsg = buildThinkingLevelChanged(session)
1542
+ if (thinkingLevelMsg) {
1543
+ send(ws, { ...thinkingLevelMsg, sessionId })
989
1544
  }
990
1545
  // Replay permission rules so reconnecting clients have current whitelist.
991
1546
  // #6771 — also replay durable per-project rules (persistentRules) so the
@@ -1018,6 +1573,18 @@ export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
1018
1573
  }
1019
1574
  }
1020
1575
 
1576
+ // Whether the session folder's project settings are loaded, so the banner
1577
+ // shows on a switch or a fresh subscribe and not only after the next turn.
1578
+ // The scan runs on a worker thread, so it neither delays nor reorders any frame
1579
+ // above or below; the frame itself is sent strictly after them.
1580
+ buildFolderTrustStateMessageForDisplay(sessionId, entry)
1581
+ .then((trustMsg) => {
1582
+ if (!trustMsg) return
1583
+ noteFolderTrustFrame(ctx.sessionManager, trustMsg)
1584
+ send(ws, trustMsg)
1585
+ })
1586
+ .catch((err) => { log.debug?.(`folder trust state failed: ${err?.message}`) })
1587
+
1021
1588
  // #5731 T5 / #5623 / #5613: re-sync the session's primary owner so the
1022
1589
  // presence badge ("Observing" / "Take over" / driver name) doesn't go
1023
1590
  // stale across a reconnect or tab switch. `session_role` is otherwise only
@@ -1134,6 +1701,198 @@ export function resolveReplayPlan(sessionManager, history, sessionId, lastSeq, l
1134
1701
  return { fullHistory: false, startOffset }
1135
1702
  }
1136
1703
 
1704
+ /**
1705
+ * #7509 F7 -- read a list off a provider session for a replay follow-up, and turn
1706
+ * a provider that cannot answer into a LOGGED, empty result instead of a throw.
1707
+ *
1708
+ * `getActiveAgents()` and `getPendingQuestions()` are defined on BaseSession, but
1709
+ * `validateProviderClass` (providers.js) only requires six prototype methods, so
1710
+ * a custom provider that does not extend BaseSession can lack either -- and both
1711
+ * follow-ups run inside `finishReplay`, a `setImmediate` continuation, where a
1712
+ * throw is an uncaught exception that also skips every follow-up after it.
1713
+ *
1714
+ * This is deliberately NOT a feature-detect: the method is still called, so a
1715
+ * provider that lacks it or throws is reported (session id, method, cause) at
1716
+ * error level rather than treated as "nothing to send". It is the ONE place both
1717
+ * follow-ups read through, so a third caller inherits it.
1718
+ *
1719
+ * @param {object} session
1720
+ * @param {string} sessionId
1721
+ * @param {'getActiveAgents' | 'getPendingQuestions'} method
1722
+ * @returns {Array}
1723
+ */
1724
+ function readProviderList(session, sessionId, method) {
1725
+ try {
1726
+ const list = session[method]()
1727
+ if (!Array.isArray(list)) {
1728
+ throw new TypeError(`${method}() returned ${list === null ? 'null' : typeof list}, expected an array`)
1729
+ }
1730
+ return list
1731
+ } catch (err) {
1732
+ log.error(`Replay follow-up ${method}() failed on session ${sessionId}: ${err?.message || err} -- skipping it, the replay still finishes`)
1733
+ return []
1734
+ }
1735
+ }
1736
+
1737
+ /**
1738
+ * #7340 — re-seed a client's `activeAgents` after a history replay.
1739
+ *
1740
+ * Both clients WIPE `activeAgents` on `history_replay_start` (dashboard
1741
+ * `message-handler.ts`, app `message-handler.ts`) because `agent_spawned` /
1742
+ * `agent_completed` are transient and never replayed from history, so anything
1743
+ * they still held could be stale from before the disconnect. That wipe is
1744
+ * correct and is KEPT — it is the only thing that drops a completion the
1745
+ * client missed while offline. What was missing is the other half: nothing
1746
+ * re-asserted the subagents that ARE still running, so a reconnect or a tab
1747
+ * switch silently emptied the badge list.
1748
+ *
1749
+ * Sending the live set here turns the pair into a snapshot REPLACE, mirroring
1750
+ * `activity_snapshot`'s snapshot-on-subscribe and `background_work_changed`'s
1751
+ * full-snapshot philosophy. It runs AFTER `history_replay_end` deliberately:
1752
+ * `sendSessionInfo` is called BEFORE `replayHistory` on both the connect
1753
+ * handshake and the session-switch path, so anything seeded there is erased by
1754
+ * the wipe that follows it.
1755
+ *
1756
+ * Idempotent — both clients dedupe `agent_spawned` by `toolUseId`, so a client
1757
+ * that never lost the entry sees no change.
1758
+ *
1759
+ * Before #7340 this was reachable but pointless (nothing survived a turn end,
1760
+ * so the live set was empty on every replay); with the turn-end exemption a
1761
+ * confirmed-backgrounded subagent is exactly what is in it.
1762
+ */
1763
+ export function reseedActiveAgents(ctx, ws, sessionId) {
1764
+ const { sessionManager, send } = ctx
1765
+ // No `typeof session.getActiveAgents === 'function'` guard: it is defined on
1766
+ // BaseSession, which every provider extends, so it can never be missing --
1767
+ // and a feature-detect that can never fail turns a future regression into a
1768
+ // silent no-op instead of a crash ("cannot check this" read as "nothing to
1769
+ // check", docs/false-safety-guards.md).
1770
+ //
1771
+ // What `readProviderList` adds is the opposite of a feature-detect: the call
1772
+ // is still made, and a provider that lacks it or throws is LOGGED loudly
1773
+ // (#7509 F7), never swallowed -- and never allowed to escape a `setImmediate`
1774
+ // continuation as an uncaught exception that skips the follow-ups after it.
1775
+ const session = sessionManager?.getSession(sessionId)?.session
1776
+ if (!session) return
1777
+ for (const agent of readProviderList(session, sessionId, 'getActiveAgents')) {
1778
+ send(ws, { type: 'agent_spawned', sessionId, ...agent })
1779
+ }
1780
+ }
1781
+
1782
+ /**
1783
+ * #7457 -- re-send the AskUserQuestion prompts a session is still BLOCKED on,
1784
+ * as LIVE frames, immediately after a replay's `history_replay_end`.
1785
+ *
1786
+ * The bug this closes is the non-racing half of #7420. `history_replay_end`
1787
+ * stamps `answered: '(resolved)'` on every unanswered `prompt` the sweep is
1788
+ * entitled to touch, on the premise that anything in history is already
1789
+ * resolved. #7453 carved out the question that arrived LIVE during the replay
1790
+ * and deliberately could not carve out the still-pending one: `user_question`
1791
+ * is not in `builtinTransient`, so it IS in the ring buffer, so the replay
1792
+ * re-delivers it carrying `historySeq` -- correctly classified as
1793
+ * replay-delivered by the only discriminator there is. Background the phone
1794
+ * mid-question, reopen it, and the prompt is a resolved pill with the agent
1795
+ * still blocked on the resolver until it times out.
1796
+ *
1797
+ * Two properties make this the fix rather than a mitigation, and BOTH are why
1798
+ * it lives in `finishReplay` rather than beside `resendPendingPermissions` in
1799
+ * the post-auth block (the issue's own suggestion):
1800
+ *
1801
+ * 1. ORDER. `replayHistory` is chunked and yields the event loop between
1802
+ * chunks, so a call placed after `replayHistory(...)` RETURNS still runs
1803
+ * before `history_replay_end` reaches the client -- which is precisely why
1804
+ * the sweep's own comment can say `resendPendingPermissions` runs "after
1805
+ * replayHistory has already sent its first chunk". Permissions do not care
1806
+ * (they are excluded from the sweep by `requestId`); a question's whole
1807
+ * defence is landing after the end frame, so it must be sequenced by the
1808
+ * replay's completion, not by its invocation.
1809
+ * 2. COVERAGE. `finishReplay` is the ONE exit both replay paths share (#7340),
1810
+ * and `replayHistory` serves connect, `switch_session` (forceFull rebuild),
1811
+ * `subscribe_sessions` and the checkpoint restore alike. Bolted onto the
1812
+ * post-auth block instead, every one of those but connect stays broken.
1813
+ *
1814
+ * The frame carries NO `historySeq`, which is what makes the client treat it as
1815
+ * live: `dispatchUserQuestion` keys #7420's discriminator on that field's
1816
+ * presence. It is otherwise byte-identical to the dispatch-time frame -- no
1817
+ * wire-shape change, no protocol bump, and both clients supersede the copy they
1818
+ * already hold by `toolUseId` rather than stacking a duplicate bubble.
1819
+ *
1820
+ * `getPendingQuestions()` carries no feature-detect for the same reason
1821
+ * `getActiveAgents()` above does not: BaseSession defines it, so a detect here
1822
+ * could never fail and would only convert a future regression into a silent
1823
+ * no-op. It IS read through `readProviderList` (#7509 F7), so a custom provider
1824
+ * that lacks it or throws is logged with the session id and method rather than
1825
+ * escaping `finishReplay`'s `setImmediate` as an uncaught exception.
1826
+ *
1827
+ * No route registration: `_questionSessionMap` entries are pruned only when the
1828
+ * question resolves or its session is destroyed, so a still-pending question is
1829
+ * still mapped, and `handleUserQuestionResponse`'s viewer check is the same
1830
+ * predicate `_broadcastToSession` uses -- a client being replayed this session
1831
+ * necessarily passes it.
1832
+ *
1833
+ * @param {object} ctx
1834
+ * @param {WebSocket} ws
1835
+ * @param {string} sessionId
1836
+ */
1837
+ export function resendPendingQuestions(ctx, ws, sessionId) {
1838
+ const { sessionManager, send } = ctx
1839
+ const session = sessionManager?.getSession(sessionId)?.session
1840
+ if (!session) return
1841
+ for (const { toolUseId, questions } of readProviderList(session, sessionId, 'getPendingQuestions')) {
1842
+ // An entry with no id is unanswerable: `handleUserQuestionResponse` routes
1843
+ // strictly by `toolUseId` and fails closed on one it cannot find. Skip it
1844
+ // rather than send a prompt whose answer can only be dropped -- and skip
1845
+ // only IT, so a malformed entry can't strand the valid ones behind it
1846
+ // (#6054's per-entry isolation, same reason).
1847
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) {
1848
+ log.warn(`Skipping pending question with no toolUseId on session ${sessionId}`)
1849
+ continue
1850
+ }
1851
+ send(ws, { type: 'user_question', sessionId, toolUseId, questions })
1852
+ }
1853
+ }
1854
+
1855
+ /**
1856
+ * #8328 — re-assert the permission prompts a session is still blocked on, to
1857
+ * ONE client, after a replay of that session.
1858
+ *
1859
+ * `permission_request` is in `builtinTransient`: never in the ring buffer, so a
1860
+ * replay cannot deliver it, and a FULL-rebuild replay (`switch_session`'s
1861
+ * `forceFull`, `subscribe_sessions`) swaps in a message list built from history
1862
+ * alone — dropping the prompt card the client appended LIVE while the session
1863
+ * was a background one. The turn then sits at "Running Bash..." with no card
1864
+ * until the request's timeout denies it. Same shape as `resendPendingQuestions`
1865
+ * above, same fix, and the same reason it hangs off the replay's exit rather
1866
+ * than off `switch_session`: every replay path needs it.
1867
+ *
1868
+ * It delegates to `permissions.resendPendingPermissions` — the ONE
1869
+ * implementation, which the connect-time (unfiltered) resend also uses — and
1870
+ * covers both the SDK-held and the hook-held (claude-tui, the default
1871
+ * provider) pending sets.
1872
+ *
1873
+ * `ctx.permissions` is the permission handler; ctx fixtures that never built
1874
+ * one have nothing to re-send, hence the optional chain on it alone — the
1875
+ * method on a real handler is called unguarded so drift fails loudly.
1876
+ *
1877
+ * Connect (#9015): `sendPostAuthInfo` also does an unfiltered resend, but it
1878
+ * EXCLUDES the active session it is about to replay — this replay-exit call owns
1879
+ * that session's prompts, so they arrive exactly once, after `history_replay_end`.
1880
+ * The unfiltered call still delivers every other session's prompts (and
1881
+ * ownerless hook-held ones); a BACKGROUND session's later `subscribe_sessions`
1882
+ * full-rebuild replay re-asserts its card via this function, which is the
1883
+ * intended second delivery there (clients update in place by `requestId`).
1884
+ *
1885
+ * @param {object} ctx
1886
+ * @param {WebSocket} ws
1887
+ * @param {string} sessionId
1888
+ */
1889
+ export function resendPendingPermissionsForSession(ctx, ws, sessionId) {
1890
+ const { permissions, clients } = ctx
1891
+ if (!permissions) return
1892
+ const client = clients && typeof clients.get === 'function' ? clients.get(ws) : undefined
1893
+ permissions.resendPendingPermissions(ws, client, { sessionId })
1894
+ }
1895
+
1137
1896
  /**
1138
1897
  * Replay message history for a session to a single client.
1139
1898
  * Sends the retained ring buffer in batches to yield the event loop.
@@ -1160,7 +1919,15 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1160
1919
  const { sessionManager, send, clients } = ctx
1161
1920
  if (!sessionManager) return
1162
1921
  const history = sessionManager.getHistory(sessionId)
1163
- if (history.length === 0) return
1922
+ if (history.length === 0) {
1923
+ // #8328: no replay frames means the client does not rebuild this session's
1924
+ // messages, so nothing it holds is dropped here — but a client that never
1925
+ // received the live broadcast (it was not subscribed when the request was
1926
+ // raised) still needs the prompt, and an in-place update by `requestId`
1927
+ // makes the re-send free for one that did.
1928
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
1929
+ return
1930
+ }
1164
1931
 
1165
1932
  const truncated = sessionManager.isHistoryTruncated(sessionId)
1166
1933
 
@@ -1176,7 +1943,7 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1176
1943
  // replay would re-send (and, with mismatched ids, duplicate) them. Forcing a
1177
1944
  // full rebuild on switch keeps the long-standing authoritative-replace
1178
1945
  // semantics and the atomic swap (#5555.4) hides the rebuild with no flash.
1179
- const client = clients && typeof clients.get === 'function' ? clients.get(ws) : null
1946
+ const client = (clients && typeof clients.get === 'function' ? clients.get(ws) : null) ?? null
1180
1947
  const lastSeq = opts.forceFull ? undefined : client?.historyCursors?.[sessionId]
1181
1948
 
1182
1949
  // `latestSeq` rides the start frame so the client can advance its cursor even
@@ -1191,134 +1958,202 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1191
1958
 
1192
1959
  send(ws, { type: 'history_replay_start', sessionId, truncated, fullHistory, latestSeq })
1193
1960
 
1194
- const CHUNK_SIZE = 20
1195
- const sendChunk = (offset) => {
1196
- if (ws.readyState !== 1) return
1197
- // #4833 follow-up: gate chunk *entry* on bufferedAmount too, not just
1198
- // chunk *scheduling*. The recursive setImmediate-via-scheduleAfterDrain
1199
- // path is already gated, but the very first sendChunk(0) call can land
1200
- // on a socket that's already congested from the preceding
1201
- // sendPostAuthInfo / session_switched burst. Without this check, the
1202
- // first history entry would be sent unconditionally and the mid-chunk
1203
- // break (which only fires *after* a send) wouldn't trip until i=1 —
1204
- // meaning we still push one fat tool_result onto an already-congested
1205
- // socket and can trip the 1MB EVICT_THRESHOLD.
1206
- if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1207
- scheduleAfterDrain(ws, () => sendChunk(offset))
1208
- return
1209
- }
1210
- const end = Math.min(offset + CHUNK_SIZE, history.length)
1211
- let nextOffset = end
1212
- for (let i = offset; i < end; i++) {
1213
- const entry = history[i]
1214
- // #5555.3 — surface the server-internal `_seq` to the client as
1215
- // `historySeq` (and strip the underscore-prefixed internal field) so the
1216
- // client can advance its per-session cursor as it applies each entry.
1217
- const { _seq, ...wireEntry } = entry
1218
- send(ws, { ...wireEntry, sessionId, ...(typeof _seq === 'number' ? { historySeq: _seq } : {}) })
1219
- // #4628: mirror the live `result → agent_idle` fan-out from
1220
- // event-normalizer.js. The dashboard's handler dispatch table has
1221
- // no `result` entry — only `agent_idle` — so a raw `result` in
1222
- // history-replay is silently dropped, and `handleAgentIdle`
1223
- // (which clears activeTools as the #4308 safety net) never fires.
1224
- // Without this, a session that completed cleanly but had an
1225
- // orphan tool_start in history (e.g. dropped PostToolUse hook,
1226
- // #4628 root cause) shows a zombie "Running X" chip every time
1227
- // the dashboard reconnects, until the next chroxy restart. The
1228
- // companion `_emitResult` sweep in BaseSession prevents new
1229
- // orphans from being persisted; this heals the existing wedged
1230
- // sessions on reconnect without requiring a restart.
1231
- if (entry && entry.type === 'result') {
1232
- send(ws, { type: 'agent_idle', sessionId })
1233
- }
1234
- // #4833: break out of the chunk early if bufferedAmount already
1235
- // crossed the pause threshold mid-burst. The CHUNK_SIZE=20 cap was
1236
- // designed for short messages; a session with fat tool_result
1237
- // payloads (200KB+) can blow past the 1MB EVICT_THRESHOLD inside
1238
- // a single chunk, before the post-chunk scheduleAfterDrain ever
1239
- // gets to inspect bufferedAmount. Pause + resume from the next
1240
- // unsent entry instead.
1241
- if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1242
- nextOffset = i + 1
1243
- break
1244
- }
1245
- }
1246
- if (nextOffset < history.length) {
1247
- // #4833: pause if the socket is already congested before scheduling
1248
- // the next chunk. Without this, every setImmediate fires another
1249
- // burst regardless of buffer pressure, blowing past the 1MB
1250
- // EVICT_THRESHOLD in ws-client-sender.js on sessions with fat
1251
- // tool_result payloads.
1252
- scheduleAfterDrain(ws, () => sendChunk(nextOffset))
1253
- } else {
1961
+ // #7340: ONE exit from the replay, because there are two ways out of it (an
1962
+ // empty slice and a drained final chunk) and the re-seed must follow BOTH.
1963
+ // Two `history_replay_end` sends with the follow-up bolted onto only one of
1964
+ // them leaves the empty-slice path — the quick reconnect, the most common
1965
+ // replay of all — silently unfixed.
1966
+ const finishReplay = () => {
1967
+ // #9015: the permission re-send is the ONLY delivery of the active
1968
+ // session's pending prompt on connect (the post-auth resend excludes it), so
1969
+ // it runs in a `finally`: a throw from the end frame or the agent re-seed
1970
+ // must not drop the sole copy. The success path still sends it exactly once.
1971
+ //
1972
+ // #8357: PERMISSIONS BEFORE QUESTIONS. A question card is withheld until its
1973
+ // own AskUserQuestion permission is allowed, and the client can only know
1974
+ // that permission exists once it has arrived. Sent the other way round, a
1975
+ // reconnecting client holds the re-sent question with no permission to gate
1976
+ // it, and can show and answer it before the permission lands: not a
1977
+ // millisecond race, a whole resend apart.
1978
+ try {
1254
1979
  send(ws, { type: 'history_replay_end', sessionId, latestSeq })
1980
+ reseedActiveAgents(ctx, ws, sessionId)
1981
+ } finally {
1982
+ try {
1983
+ // #8328: AFTER the end frame. A full-rebuild replay swaps in a
1984
+ // history-only message list at `history_replay_end`, dropping the live
1985
+ // permission card the client held for this session; `permission_request`
1986
+ // is transient, so the replay itself cannot restore it. Sent after the
1987
+ // swap, the re-send lands on the rebuilt list and is kept.
1988
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
1989
+ } finally {
1990
+ // #7457: AFTER the end frame, never before it. The client's replay-end
1991
+ // sweep has already run by the time this lands, which is the entire
1992
+ // reason a still-pending question survives the reconnect. In its own
1993
+ // `finally` so a failed permission re-send cannot lose the question.
1994
+ resendPendingQuestions(ctx, ws, sessionId)
1995
+ }
1255
1996
  }
1256
1997
  }
1998
+
1999
+ // A manager that cannot answer reads as idle, as in the JSONL heal's own check
2000
+ // (conversation-handlers.js); asked again for each replayed result.
2001
+ const isSessionBusy = () => typeof sessionManager.isSessionBusy === 'function'
2002
+ ? sessionManager.isSessionBusy(sessionId)
2003
+ : false
2004
+
1257
2005
  // #5555.3 — start at the resolved offset: 0 for a full replay, the
1258
2006
  // first-newer-than-cursor index for a delta replay. When the client is
1259
- // already current (startOffset === history.length) this immediately falls
1260
- // through to the empty-slice path and emits start+end with nothing between.
1261
- if (startOffset >= history.length) {
1262
- send(ws, { type: 'history_replay_end', sessionId, latestSeq })
1263
- } else {
1264
- sendChunk(startOffset)
2007
+ // already current (startOffset === history.length) sendChunkedWithBackpressure
2008
+ // falls straight through to the empty-slice path and emits start+end with
2009
+ // nothing between.
2010
+ //
2011
+ // #7460 — the chunk-and-drain machinery and the per-entry wire mapping both
2012
+ // live in ONE place now (above), because `handleRequestFullHistory` is the
2013
+ // second caller of exactly this loop and every hand-copied piece of it has
2014
+ // drifted: the `_seq` map (#7454), the `result` → `agent_idle` synthesis
2015
+ // (#7459), and the bufferedAmount gating (#7460) were each missing there.
2016
+ // #9022 -- a reply is recorded only when its stream closes, so a turn paused
2017
+ // mid-stream (on a permission prompt) has its text in no entry. Splice what has
2018
+ // streamed so far in, at its place in the transcript. The position matters for a
2019
+ // DELTA replay, which appends in arrival order; a full replay's provenance sort
2020
+ // puts the (unnumbered) snapshot after the numbered entries (#9024).
2021
+ const pending = client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_INFLIGHT_REPLY)
2022
+ ? pendingStreamEntries(sessionManager, sessionId)
2023
+ : []
2024
+ // #8415 -- DELTA replays only: a full replay's `tool_start` entries carry their
2025
+ // input. The frames lead the slice (after `history_replay_start`, before the end).
2026
+ // The typeof guard tolerates stub/test managers. The frames carry the stored input,
2027
+ // already capped by sanitizeToolInput, so there is no second cap here.
2028
+ const backfills = !fullHistory && typeof lastSeq === 'number'
2029
+ && typeof sessionManager.getToolInputBackfills === 'function'
2030
+ && client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_TOOL_INPUT_BACKFILL)
2031
+ ? sessionManager.getToolInputBackfills(sessionId, lastSeq).map((b) => ({
2032
+ [TOOL_INPUT_BACKFILL_FRAME]: { ...b, type: 'tool_input_backfill', sessionId },
2033
+ }))
2034
+ : []
2035
+ const replayEntries = pending.length > 0 || backfills.length > 0
2036
+ ? [...backfills, ...(pending.length > 0
2037
+ ? spliceInPendingStreams(history.slice(startOffset), pending)
2038
+ : history.slice(startOffset))]
2039
+ : history
2040
+ sendChunkedWithBackpressure(ws, replayEntries, {
2041
+ startOffset: pending.length > 0 || backfills.length > 0 ? 0 : startOffset,
2042
+ // #9015: a throwing entry ABORTS the replay and never claims completion (no
2043
+ // `history_replay_end` carrying `latestSeq` — the client would commit a
2044
+ // partial transcript and its cursor). Permission recovery is independent of
2045
+ // replay success, though: the connect-time resend excludes the active
2046
+ // session, so this abort path delivers its pending prompt (once — the loop
2047
+ // stops and `finishReplay` never runs) and then rethrows, as before.
2048
+ emit: (entry) => {
2049
+ try {
2050
+ if (entry[TOOL_INPUT_BACKFILL_FRAME]) send(ws, entry[TOOL_INPUT_BACKFILL_FRAME])
2051
+ else sendHistoryEntry(send, ws, sessionId, entry, client, isSessionBusy)
2052
+ } catch (err) {
2053
+ try {
2054
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
2055
+ } catch (resendErr) {
2056
+ log.warn(`Permission re-send after an aborted replay of ${sessionId} failed: ${resendErr?.message ?? resendErr}`)
2057
+ }
2058
+ throw err
2059
+ }
2060
+ },
2061
+ onDone: finishReplay,
2062
+ })
2063
+ }
2064
+
2065
+ /**
2066
+ * #9022 -- the still-open reply streams of a session as replayable entries.
2067
+ *
2068
+ * Sent on a delta replay too, whatever the client's cursor: the client dedups a
2069
+ * reply it already holds by id, completes one it holds only the start of (#8444's
2070
+ * `completeHeldResponseStream`, which also refills deltas missed in a dropped
2071
+ * connection), and keeps one that has run ahead of the snapshot. A cursor filter
2072
+ * would not be a sound "did the client see this stream start" test anyway: live
2073
+ * frames carry no `historySeq`, so a cursor says nothing about a stream's start.
2074
+ *
2075
+ * The entries carry no `_seq`, so a client advances no cursor off them, and no
2076
+ * field the stream's own completed entry lacks: when the stream closes, the
2077
+ * recorded entry has the same `messageId`, so a client that kept this one dedups.
2078
+ */
2079
+ function pendingStreamEntries(sessionManager, sessionId) {
2080
+ if (typeof sessionManager.getPendingResponseStreams !== 'function') return []
2081
+ const streams = sessionManager.getPendingResponseStreams(sessionId)
2082
+ const now = Date.now()
2083
+ return streams.map((s) => ({
2084
+ startSeq: s.startSeq,
2085
+ entry: {
2086
+ type: 'message',
2087
+ messageType: 'response',
2088
+ content: s.content,
2089
+ messageId: s.messageId,
2090
+ // #9024: where tool calls have interrupted it so far, as the closing entry will say.
2091
+ ...(s.splits?.length ? { splits: s.splits } : {}),
2092
+ timestamp: now,
2093
+ },
2094
+ }))
2095
+ }
2096
+
2097
+ /**
2098
+ * Put each pending-stream entry before the first recorded entry that came after
2099
+ * its stream opened (the end, when none did). Returns a new array; `entries` is
2100
+ * the ring buffer's own and is not touched.
2101
+ */
2102
+ function spliceInPendingStreams(entries, pending) {
2103
+ const out = entries.slice()
2104
+ // Latest-opened first, so an earlier splice never shifts the index a later one
2105
+ // was computed for.
2106
+ const ordered = [...pending].sort((a, b) => b.startSeq - a.startSeq)
2107
+ for (const { startSeq, entry } of ordered) {
2108
+ let at = out.findIndex((e) => typeof e._seq === 'number' && e._seq >= startSeq)
2109
+ if (at === -1) at = out.length
2110
+ out.splice(at, 0, entry)
1265
2111
  }
2112
+ return out
1266
2113
  }
1267
2114
 
1268
2115
  /**
1269
- * Flush queued post-auth messages in batches to yield the event loop.
1270
- * Same chunking pattern as replayHistory.
2116
+ * Flush queued post-auth messages to a client through the shared chunk +
2117
+ * back-pressure loop.
2118
+ *
2119
+ * #7485 — this was the last hand-copied instance of that loop: its own
2120
+ * `CHUNK_SIZE = 20` four lines from `REPLAY_CHUNK_SIZE`, its own readyState
2121
+ * exit, its own chunk-entry gate, its own mid-chunk break and its own
2122
+ * scheduling gate, all maintained in parallel since #4845. What kept it
2123
+ * separate is the queue state it owns on top of the loop, and each piece maps
2124
+ * onto one of the hooks `sendChunkedWithBackpressure` now takes:
2125
+ *
2126
+ * - `_flushing` is the gate ws-client-sender.js reads. It must be TRUE
2127
+ * whenever this flush is parked, so a concurrent `send` lands in
2128
+ * `_flushOverflow` behind the queued messages instead of overtaking them,
2129
+ * and FALSE while a chunk is actually being written — which is exactly
2130
+ * onPause / onResume.
2131
+ * - a socket that leaves OPEN mid-flush must drop BOTH `_flushing` (or every
2132
+ * later send is swallowed by a gate nothing will ever release) and
2133
+ * `_flushOverflow` (nothing will drain it) — onAbort.
2134
+ * - the terminal branch recurses into whatever arrived while we were parked,
2135
+ * rather than sending an end frame — onDone.
1271
2136
  */
1272
2137
  export function flushPostAuthQueue(ctx, ws, queue) {
1273
2138
  const { clients, send } = ctx
1274
2139
  const client = clients.get(ws)
1275
2140
  if (client) client._flushing = true
1276
- const CHUNK_SIZE = 20
1277
- const drainChunk = (offset) => {
1278
- if (ws.readyState !== 1) {
2141
+ sendChunkedWithBackpressure(ws, queue, {
2142
+ emit: (message) => send(ws, message),
2143
+ onPause: () => { if (client) client._flushing = true },
2144
+ onResume: () => { if (client) client._flushing = false },
2145
+ onAbort: () => {
1279
2146
  if (client) {
1280
2147
  client._flushing = false
1281
2148
  client._flushOverflow = null
1282
2149
  }
1283
- return
1284
- }
1285
- // #4833 follow-up: gate chunk *entry* on bufferedAmount too — same
1286
- // rationale as replayHistory.sendChunk above. drainChunk(0) is invoked
1287
- // synchronously from flushPostAuthQueue, so the very first queued
1288
- // message can land on an already-congested socket (e.g. fat post-auth
1289
- // payloads that were queued during the encryption handshake) before the
1290
- // mid-chunk break (which only fires after a send) gets a chance to
1291
- // pause. Keep _flushing = true so any callers using ws-client-sender's
1292
- // _flushing buffer still queue overflow instead of blasting past us.
1293
- if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1294
- if (client) client._flushing = true
1295
- scheduleAfterDrain(ws, () => drainChunk(offset))
1296
- return
1297
- }
1298
- const end = Math.min(offset + CHUNK_SIZE, queue.length)
1299
- if (client) client._flushing = false
1300
- let nextOffset = end
1301
- for (let i = offset; i < end; i++) {
1302
- send(ws, queue[i])
1303
- // #4833: break early if a fat queued message just tipped bufferedAmount
1304
- // past the pause threshold — same rationale as replayHistory above.
1305
- if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1306
- nextOffset = i + 1
1307
- break
1308
- }
1309
- }
1310
- if (nextOffset < queue.length) {
1311
- if (client) client._flushing = true
1312
- // #4833: pause if the socket is already congested before scheduling
1313
- // the next chunk — same rationale as replayHistory above.
1314
- scheduleAfterDrain(ws, () => drainChunk(nextOffset))
1315
- } else if (client) {
1316
- if (client._flushOverflow?.length) {
2150
+ },
2151
+ onDone: () => {
2152
+ if (client?._flushOverflow?.length) {
1317
2153
  const overflow = client._flushOverflow
1318
2154
  client._flushOverflow = null
1319
2155
  flushPostAuthQueue(ctx, ws, overflow)
1320
2156
  }
1321
- }
1322
- }
1323
- drainChunk(0)
2157
+ },
2158
+ })
1324
2159
  }