@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  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-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
package/src/ws-history.js CHANGED
@@ -4,23 +4,34 @@
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'
8
- import { PERMISSION_MODES } from './handler-utils.js'
9
- import { listProviders, getProvider } from './providers.js'
7
+ import { toShortModelId, getRegistryForProvider, resolveRosterProvider } from './models.js'
8
+ import { getPermissionModes } from './handler-utils.js'
9
+ import { buildThinkingLevelChanged } from './thinking-level-wire.js'
10
+ import { listProviders, getProvider, getProviderRuntimeInfo, resolveDaemonDefaultProvider } from './providers.js'
10
11
  import { createLogger } from './logger.js'
12
+ import { isBoundClient } from './environments/authority.js'
13
+ import { streamKindOf, permissionOutcomeDecision } from './session-message-history.js'
11
14
  import { createKeyPair, deriveSharedKey, deriveConnectionKey, signExchangeKey } from '@chroxy/store-core/crypto'
12
15
  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'
16
+ import { MAX_SANE_DURATION_MS, REPLAY_BACKPRESSURE_MAX_WAIT_MS } from '@chroxy/protocol'
14
17
 
15
18
  const log = createLogger('ws')
16
19
 
17
- // #4833 — back-pressure pause for chunked replay/flush loops.
20
+ function permissionModesForProvider(provider) {
21
+ let ProviderClass
22
+ try { ProviderClass = provider ? getProvider(provider) : undefined } catch { /* unknown provider */ }
23
+ return getPermissionModes(provider, ProviderClass)
24
+ }
25
+
26
+ // #4833 — back-pressure pause for the chunked send loop.
18
27
  //
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.
28
+ // `sendChunkedWithBackpressure` emits messages in 20-entry chunks separated by
29
+ // setImmediate yields, on behalf of every path that streams a batch to one
30
+ // client: replayHistory, flushPostAuthQueue, and the two conversation-handler
31
+ // replays. On sessions with fat tool_result payloads (200KB+ each), a single
32
+ // chunk can push ws.bufferedAmount past the 1MB EVICT_THRESHOLD in
33
+ // ws-client-sender.js, tripping a post-send 4008 close and surfacing as a
34
+ // "Reconnecting…" loop in the dashboard.
24
35
  //
25
36
  // Before scheduling the next chunk, the loop now polls bufferedAmount and
26
37
  // pauses (via setTimeout, every BACKPRESSURE_POLL_INTERVAL_MS) until it falls
@@ -29,7 +40,7 @@ const log = createLogger('ws')
29
40
  // links. The poll interval (20ms) is short enough to keep the replay
30
41
  // responsive but long enough to give the socket time to actually flush.
31
42
  //
32
- // Both helpers abort the poll once ws.readyState leaves OPEN (client
43
+ // The loop aborts the poll once ws.readyState leaves OPEN (client
33
44
  // disconnected while paused), so the poll chain terminates on socket close
34
45
  // without sending to a closed socket.
35
46
  //
@@ -42,9 +53,18 @@ const log = createLogger('ws')
42
53
  // from scratch, rather than silently leaking a timer against a dead peer. The
43
54
  // cap is comfortably longer than a healthy slow-link drain but far short of
44
55
  // "forever".
56
+ //
57
+ // #7496: the cap is single-sourced in @chroxy/protocol because a client reads it
58
+ // too. While parked this loop emits NOTHING for the stream, so the dashboard's
59
+ // transcript inactivity watchdog (derived from this value there) must be longer
60
+ // than the longest park or it reports a timeout against a healthy replay.
61
+ // A keepalive frame is not the answer: it would queue behind the bytes that are
62
+ // not draining and arrive only after the park had ended. Do not hardcode a
63
+ // number here — `tests/ws-history-backpressure-cap.test.js` pins that the socket
64
+ // is closed at exactly the shared value.
45
65
  const BACKPRESSURE_PAUSE_THRESHOLD = 256 * 1024
46
66
  const BACKPRESSURE_POLL_INTERVAL_MS = 20
47
- const BACKPRESSURE_MAX_WAIT_MS = 30_000
67
+ const BACKPRESSURE_MAX_WAIT_MS = REPLAY_BACKPRESSURE_MAX_WAIT_MS
48
68
 
49
69
  // #5622 — bound the eager X25519 key derivations done SYNCHRONOUSLY per
50
70
  // event-loop iteration.
@@ -156,6 +176,309 @@ export function scheduleAfterDrain(ws, fn) {
156
176
  setTimeout(poll, BACKPRESSURE_POLL_INTERVAL_MS)
157
177
  }
158
178
 
179
+ // #7460 / #7480 / #7485 — THE implementation of the #4833 chunk-and-drain loop.
180
+ // Every path in the server that streams a batch of frames to one client goes
181
+ // through it: `replayHistory` (connect / session-switch), `flushPostAuthQueue`
182
+ // (below), `handleRequestFullHistory` ("Sync Full History") and
183
+ // `handleRequestConversationTranscript` (the read-only transcript viewer), the
184
+ // last two in conversation-handlers.js.
185
+ //
186
+ // They were four hand-copied variants of the same twelve lines, and every
187
+ // copied piece drifted at least once: the `_seq` -> `historySeq` map (#7454),
188
+ // the `result` -> `agent_idle` synthesis (#7459), the bufferedAmount gating on
189
+ // the full-history replay (#7460) and again on the transcript replay (#7480),
190
+ // and a second chunk-size constant with the same value four lines from this
191
+ // one (#7485). A second copy of this loop is how that divergence started, so
192
+ // there is deliberately only one — and `tests/one-chunk-and-drain-loop.test.js`
193
+ // re-derives that claim from this source on every run rather than trusting
194
+ // this sentence, because a comment beside a set that can grow is exactly the
195
+ // shape docs/false-safety-guards.md catalogues.
196
+ const REPLAY_CHUNK_SIZE = 20
197
+
198
+ /**
199
+ * Send `entries` to `ws` in REPLAY_CHUNK_SIZE batches, yielding the event loop
200
+ * between chunks and pausing whenever `ws.bufferedAmount` climbs past
201
+ * BACKPRESSURE_PAUSE_THRESHOLD (#4833). Three gates, of which TWO carry
202
+ * behaviour on their own:
203
+ *
204
+ * - chunk ENTRY (load-bearing) — the first chunk can land on a socket that is
205
+ * already congested from a preceding burst (post-auth info,
206
+ * session_switched), so it is deferred before anything is written. The
207
+ * mid-chunk break only fires *after* a send, so without this gate one fat
208
+ * payload still lands on a near-eviction buffer.
209
+ * - MID-chunk (load-bearing) — REPLAY_CHUNK_SIZE was sized for short messages;
210
+ * two 200KB tool_results blow past the threshold inside a single chunk, so
211
+ * the loop breaks out and resumes from the next UNSENT entry.
212
+ * - chunk SCHEDULING — pauses before queueing the next chunk. Retained as the
213
+ * inherited #4833 shape, but it is NOT independently load-bearing: replacing
214
+ * it with a bare `setImmediate` is an equivalent mutation, because the next
215
+ * `sendChunk` re-checks the chunk-ENTRY gate and enters the same drain wait
216
+ * (with the same #5328 max-wait cap) one tick later. Established by mutation
217
+ * testing and a 48-scenario differential during review of PR #7479; do not
218
+ * read this line as a third independent guard.
219
+ *
220
+ * `emit(entry, index)` writes one entry; `onDone()` runs once every entry has
221
+ * been written. Neither runs after `ws.readyState` leaves OPEN — a client that
222
+ * disconnects mid-replay gets no further frames and no end marker, which is
223
+ * the behaviour every replay caller already relied on.
224
+ *
225
+ * #7485 — three OPTIONAL hooks let a caller carry state across the gate, which
226
+ * is what `flushPostAuthQueue` needs and what kept it a separate copy of this
227
+ * loop until now. Callers that pass none behave exactly as before:
228
+ *
229
+ * - `onPause()` — fires immediately before the loop parks on a drain (the
230
+ * chunk-entry gate, the mid-chunk break, and the between-chunks yield all
231
+ * park through one place).
232
+ * - `onResume()` — fires each time the loop is CLEAR to write, including the
233
+ * first chunk and including the empty slice, which never enters a chunk
234
+ * body. A hook that only fired after a real pause would leave the
235
+ * empty-queue case latched.
236
+ * - `onAbort()` — fires instead of `onDone` when the loop stops because
237
+ * `ws.readyState` left OPEN. It does NOT fire when the socket dies while
238
+ * parked inside `scheduleAfterDrain` (that chain exits silently, as it
239
+ * always has) or when the #5328 max-wait cap closes the socket.
240
+ *
241
+ * @param {WebSocket} ws - The client socket.
242
+ * @param {Array} entries - The full slice to deliver.
243
+ * @param {{startOffset?: number, emit: (entry: any, index: number) => void, onDone: () => void, onPause?: () => void, onResume?: () => void, onAbort?: () => void}} opts
244
+ */
245
+ export function sendChunkedWithBackpressure(ws, entries, { startOffset = 0, emit, onDone, onPause, onResume, onAbort }) {
246
+ const park = (offset) => {
247
+ if (onPause) onPause()
248
+ scheduleAfterDrain(ws, () => sendChunk(offset))
249
+ }
250
+ const abort = () => { if (onAbort) onAbort() }
251
+ const sendChunk = (offset) => {
252
+ if (ws.readyState !== 1) {
253
+ abort()
254
+ return
255
+ }
256
+ if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
257
+ park(offset)
258
+ return
259
+ }
260
+ if (onResume) onResume()
261
+ const end = Math.min(offset + REPLAY_CHUNK_SIZE, entries.length)
262
+ let nextOffset = end
263
+ for (let i = offset; i < end; i++) {
264
+ emit(entries[i], i)
265
+ if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
266
+ nextOffset = i + 1
267
+ break
268
+ }
269
+ }
270
+ if (nextOffset < entries.length) {
271
+ park(nextOffset)
272
+ } else {
273
+ onDone()
274
+ }
275
+ }
276
+ // Both entry paths are gated on OPEN, not just the chunking one. `sendChunk`
277
+ // re-checks readyState itself (it is also the resume point for every
278
+ // scheduled continuation), but the EMPTY-slice path below reaches `onDone`
279
+ // without going through it — so without this check a client that vanished
280
+ // before an already-current replay still had its `history_replay_end` and
281
+ // re-seed burst written at a dead socket, contradicting the contract stated
282
+ // above. That is the comment-stronger-than-code class
283
+ // (docs/false-safety-guards.md), and it hid in the path taken MOST often:
284
+ // the already-current reconnect (Copilot review, PR #7479).
285
+ if (ws.readyState !== 1) {
286
+ abort()
287
+ return
288
+ }
289
+ // An already-current client (startOffset === entries.length) still gets
290
+ // `onDone` — the empty-slice path, and the most common replay of all.
291
+ if (startOffset >= entries.length) {
292
+ if (onResume) onResume()
293
+ onDone()
294
+ } else {
295
+ sendChunk(startOffset)
296
+ }
297
+ }
298
+
299
+ /**
300
+ * #8374: the client capability that says "I can label a `permission_outcome` whose
301
+ * outcome is `stopped`". Advertised in the auth handshake (CLIENT_CAPABILITIES in
302
+ * @chroxy/protocol).
303
+ */
304
+ const CAPABILITY_PERMISSION_OUTCOME_STOPPED = 'permission_outcome_stopped_v1'
305
+
306
+ /**
307
+ * #6630: the client capability that says "a replayed `error` entry is safe to
308
+ * send me". Errors became part of the transcript (they used to be live-only), and
309
+ * a client build from before that raises its usage-limit alert for a rate-limit
310
+ * error even when it arrives in a replay, so an old app would pop the modal on
311
+ * every session switch for a quota that recovered long ago. Only a client that
312
+ * advertises this (the replay-aware builds) is sent the recorded errors; the rest
313
+ * get the transcript as it was, errors absent.
314
+ */
315
+ export const CAPABILITY_HISTORY_ERROR_REPLAY = 'history_error_replay_v1'
316
+
317
+ /**
318
+ * #6630: the client capability that says "a replayed reasoning entry with NO text is
319
+ * safe to send me". Current Claude models send a thinking block with only its
320
+ * signature, and the server records that as a response entry with `kind: 'thinking'`
321
+ * and empty content. A client build from before `kind` was understood renders it as
322
+ * an empty assistant bubble, one per turn, so only a client that advertises this is
323
+ * sent one. A reasoning entry WITH text is unchanged for everyone (older builds
324
+ * showed reasoning as an answer already).
325
+ */
326
+ export const CAPABILITY_HISTORY_THINKING_REPLAY = 'history_thinking_replay_v1'
327
+
328
+ /**
329
+ * #8470: the client capability that says "a replayed `user_question` carrying
330
+ * `superseded: true` is safe to send me". A newer question replaced it while it
331
+ * was open, so nobody answered it. A client build from before the flag was
332
+ * understood ignores the field and builds the question as a LIVE card: its answer
333
+ * controls are enabled until `history_replay_end` (a replay yields between chunks
334
+ * and can pause under backpressure), and it is then stamped "(resolved)", which
335
+ * reads as answered. Neither is true, and there is no older shape that says
336
+ * "replaced": so such a client is not sent the question at all (the `tool_start`
337
+ * for its tool is still replayed). Only the replay-aware builds get the verdict.
338
+ */
339
+ export const CAPABILITY_HISTORY_QUESTION_SUPERSEDED = 'history_question_superseded_v1'
340
+
341
+ /**
342
+ * #9022: the client capability that says "the text an open stream has produced so far
343
+ * may be replayed to me as an unnumbered `response` entry". A client build from before
344
+ * it reconciles that entry by id only: after a tool split it keeps the snapshot AND
345
+ * its own live `-cont-` bubble, and shows the text twice. It keeps main's behaviour
346
+ * (no snapshot) instead.
347
+ */
348
+ export const CAPABILITY_HISTORY_INFLIGHT_REPLY = 'history_inflight_reply_v1'
349
+
350
+ /**
351
+ * Write ONE history entry to a client, the way BOTH replay paths must.
352
+ *
353
+ * Two things happen per entry, and both were forgotten by the second copy of
354
+ * this loop — which is the whole reason this is a function (#7454, #7459):
355
+ *
356
+ * 1. #5555.3 — surface the server-internal `_seq` as `historySeq` (and strip
357
+ * the underscore-prefixed internal field) so the client can advance its
358
+ * per-session cursor as it applies each entry. #7420's live-vs-replayed
359
+ * discriminator keys on that field's PRESENCE, so a missing stamp reads as
360
+ * a live racer — and a fabricated one is just as wrong.
361
+ * 2. #4628 — mirror the live `result` → `agent_idle` fan-out from
362
+ * event-normalizer.js. `agent_idle` is the frame that clears a zombie
363
+ * "Running X" chip left by an orphan tool_start (a dropped PostToolUse
364
+ * hook, the #4628 root cause): the mobile app has no `activeTools` reader
365
+ * at all, and the dashboard's own `case 'result'` sweep is a redundant
366
+ * second copy of the same wipe rather than an independent one. The
367
+ * companion `_emitResult` sweep in BaseSession stops new orphans being
368
+ * persisted; this heals the sessions already wedged, on every replay path
369
+ * a user can reach.
370
+ *
371
+ * THIS PAIRING IS A WIRE CONTRACT, not an implementation detail (#7515).
372
+ * Until #7515 this comment claimed the clients' `case 'result'` was
373
+ * replay-gated "precisely so a replayed result cannot wipe" what
374
+ * `history_replay_start` preserves — which made the two halves of the
375
+ * paragraph contradict each other, since the very next frame wiped it
376
+ * regardless. The dashboard's gate is gone and its `result` sweep is
377
+ * unconditional again; both clients now depend on this synthesis being
378
+ * the authority. Removing it is a client-visible behaviour change, and
379
+ * `tests/ws-history.test.js`'s "emits synthetic agent_idle after each
380
+ * `result` entry …(#4628)" — which asserts the exact frame ORDER — is the
381
+ * test that must go red first if anyone tries.
382
+ *
383
+ * @param {(ws: WebSocket, payload: object) => void} send
384
+ * @param {WebSocket} ws
385
+ * @param {string} sessionId
386
+ * @param {object} entry - A ring-buffer entry, possibly carrying `_seq`.
387
+ * @param {{clientCapabilities?: Set<string>}|null} [client] - The client RECORD
388
+ * (`clients.get(ws)`), which is where the auth handshake stores the capabilities
389
+ * it advertised. NOT `ws`: that is the raw socket and carries none (#8374).
390
+ */
391
+ export function sendHistoryEntry(send, ws, sessionId, entry, client = null, isSessionBusy = () => false) {
392
+ // #6630: a recorded error goes only to a client that said it can take one in a
393
+ // replay (see CAPABILITY_HISTORY_ERROR_REPLAY). Skipped, not downgraded: there is
394
+ // no older shape of an error bubble that is safe. Nothing else about the entry
395
+ // changes, and the stored entry is untouched for the clients that do advertise it.
396
+ if (
397
+ entry && entry.type === 'message' && entry.messageType === 'error'
398
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_ERROR_REPLAY) ?? false)
399
+ ) {
400
+ return
401
+ }
402
+ // #6630: a text-less reasoning entry goes only to a client that can render it (see
403
+ // CAPABILITY_HISTORY_THINKING_REPLAY). Skipped for the same reason as the error: an
404
+ // older build has no safe shape for it.
405
+ if (
406
+ entry && streamKindOf(entry) === 'thinking'
407
+ && (typeof entry.content !== 'string' || entry.content.length === 0)
408
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_THINKING_REPLAY) ?? false)
409
+ ) {
410
+ return
411
+ }
412
+ // #8470: a question a newer one replaced goes only to a client that can read the
413
+ // flag; see CAPABILITY_HISTORY_QUESTION_SUPERSEDED. Both the in-place entry and the
414
+ // tail copy carry it, so both are skipped.
415
+ if (
416
+ entry && entry.type === 'user_question' && entry.superseded === true
417
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_QUESTION_SUPERSEDED) ?? false)
418
+ ) {
419
+ return
420
+ }
421
+ // `sourceToolUseId` (#8336) is server-internal: it lets the restore-time sweep
422
+ // pair a recorded question with its tool_start, and no client reads it. Live
423
+ // broadcasts never carry it (the event normalizer picks fields), so the replay
424
+ // frame must not either.
425
+ // `answered` (#8362) is likewise server-only: the restore-time sweep reads it to
426
+ // leave an answered question unmarked, and a replayed question reads as resolved
427
+ // on the client already.
428
+ const { _seq, sourceToolUseId: _sourceToolUseId, answered: _answered, ...wireEntry } = entry
429
+ // #8374: a client build from before `stopped` existed drops a `permission_outcome`
430
+ // whose outcome it cannot parse, and a full rebuild then loses the record
431
+ // altogether. Say `expired` to a client that did not advertise it can label the
432
+ // new value: the record survives, only its label degrades. The stored entry is
433
+ // untouched (`wireEntry` is a copy), so a capable client still gets `stopped`.
434
+ // #6630: say on the frame that a recorded response was reasoning, including an
435
+ // entry an older run wrote without the field (classified by its message id),
436
+ // so the client rebuilds the thinking bubble the live stream showed rather than
437
+ // an answer. One classifier; the client reads the field and derives nothing.
438
+ if (streamKindOf(entry) === 'thinking') wireEntry.kind = 'thinking'
439
+ // #8503: a `permission_outcome` carries the tool input its prompt was shown with
440
+ // (already sanitized and capped when recorded). A restored entry whose `input`
441
+ // is not a plain object (a damaged or hand-edited state file) is sent without
442
+ // it rather than as something a client would have to defend against.
443
+ if (wireEntry.type === 'permission_outcome' && 'input' in wireEntry
444
+ && !(wireEntry.input && typeof wireEntry.input === 'object' && !Array.isArray(wireEntry.input))) {
445
+ delete wireEntry.input
446
+ }
447
+ // #8503: the decision token an `allowed` outcome carries; a restored entry whose
448
+ // token is not one the recorder would keep is sent without it.
449
+ if (wireEntry.type === 'permission_outcome' && 'decision' in wireEntry
450
+ && permissionOutcomeDecision(wireEntry.outcome, wireEntry.decision) === undefined) {
451
+ delete wireEntry.decision
452
+ }
453
+ if (wireEntry.type === 'permission_outcome' && wireEntry.outcome === 'stopped'
454
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_PERMISSION_OUTCOME_STOPPED) ?? false)) {
455
+ wireEntry.outcome = 'expired'
456
+ }
457
+ // `replayed: true` on a result is the explicit "this is history" mark (#8965): a
458
+ // JSONL full-history slice strips `_seq` (so no historySeq) yet still carries the
459
+ // daemon-written interrupted-turn result, and a client must not read that as the
460
+ // live turn ending.
461
+ send(ws, {
462
+ ...wireEntry,
463
+ sessionId,
464
+ ...(typeof _seq === 'number' ? { historySeq: _seq } : {}),
465
+ ...(entry && entry.type === 'result' ? { replayed: true } : {}),
466
+ })
467
+ // The synthesized `agent_idle` mirrors the live fan-out so a client clears the
468
+ // turn-scoped state a dropped event left behind (#4628). It must NOT be sent
469
+ // while the session is BUSY (#8965): the entry is an OLD turn's result, the
470
+ // client has nothing to clear for the turn that is still running, and the frame
471
+ // flips the client's isIdle to true -- where nothing sets it back until the next
472
+ // stream_start -- so the Send button shows during a run and a second replay of
473
+ // the same turn sees an idle session. Busy is asked per result, because a replay
474
+ // is chunked and a turn can start part-way through it. The JSONL heal
475
+ // (conversation-handlers.js) already holds the same line. An idle session still
476
+ // gets it.
477
+ if (entry && entry.type === 'result' && !isSessionBusy()) {
478
+ send(ws, { type: 'agent_idle', sessionId })
479
+ }
480
+ }
481
+
159
482
  /**
160
483
  * Send all post-authentication info to a newly authenticated client.
161
484
  * This includes auth_ok, server mode, session list, model/permission state,
@@ -167,7 +490,7 @@ export function scheduleAfterDrain(ws, fn) {
167
490
  export function sendPostAuthInfo(ctx, ws, extra = {}) {
168
491
  const {
169
492
  clients, sessionManager, cliSession, defaultSessionId,
170
- serverMode, serverVersion, latestVersion, gitInfo,
493
+ serverMode, serverVersion, latestVersion, dashboardBuildId, gitInfo,
171
494
  encryptionEnabled, localhostBypass, tunnelActive, keyExchangeTimeoutMs,
172
495
  protocolVersion, minProtocolVersion, webTaskManager,
173
496
  // #5721: `send` MUST be `WsServer._send` (which returns the delivery
@@ -186,6 +509,15 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
186
509
  // so clients reveal IDE navigation/editing UI. Optional — absent → false
187
510
  // (fail-closed) for old servers / callers.
188
511
  ideEnabled,
512
+ // #6691: whether the orchestration harness is enabled on this server,
513
+ // surfaced as the `orchestration` capability so the dashboard reveals the
514
+ // Runs surface. Optional — absent → false (fail-closed) for old servers.
515
+ orchestrationEnabled,
516
+ // #8619: whether `allowAutoPermissionMode: true` is set in the local
517
+ // config, surfaced as the `autoPermissionMode` capability so clients can
518
+ // disable Auto in their mode pickers and say why. Optional — absent →
519
+ // false (fail-closed) for old callers / test harnesses.
520
+ autoPermissionModeAllowed,
189
521
  // #6006: whether the server has a rotating TokenManager (i.e. auth is on),
190
522
  // so the operator panic button (`revoke_token`) can fire. Surfaced as the
191
523
  // `tokenRevoke` capability, gated to primary-token clients below. Optional —
@@ -208,21 +540,55 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
208
540
  billingCanary,
209
541
  // #5536: long-lived identity keypair for signing the eager exchange key.
210
542
  serverIdentity,
543
+ // #8331: the daily-daemon update status; sent below to strict-primary,
544
+ // unbound clients only. Optional — absent on old callers and test harnesses.
545
+ daemonUpdate,
546
+ // #7821: configured explicit agent routes. Kept on the history context so
547
+ // auth_ok feature derivation and auth_bootstrap use the same live config.
548
+ agentConnections,
211
549
  } = ctx
212
550
  const client = clients.get(ws)
213
551
 
214
552
  // Get initial session info for auth_ok payload
215
553
  let sessionInfo = {}
554
+ // #6638: the active session's provider, captured for the auth_ok permission-mode
555
+ // copy (Codex gets codex-tuned descriptions). `entry` below is block-scoped, so
556
+ // hoist the provider to function scope. #7811: this is `null` when there is no
557
+ // active session, so it is resolved through `resolveRosterProvider` at the
558
+ // send site below (same as `rosterProvider` further down this function)
559
+ // rather than used directly — otherwise a codex-default daemon would fold
560
+ // the CLAUDE mode copy into auth_ok for a client that has no session yet.
561
+ let authOkProvider = null
216
562
  if (sessionManager) {
217
- let activeId = defaultSessionId
218
- let entry = activeId ? sessionManager.getSession(activeId) : null
563
+ // #6687: resolve the active session with the SAME precedence block 2 uses to
564
+ // restore the client — the per-device persisted active session (#4835) first,
565
+ // then defaultSessionId → firstSessionId, then the bound-session override — so
566
+ // auth_ok's cwd + permission-mode copy describe the session the client is
567
+ // actually switched to, not the server default.
568
+ let activeId = null
569
+ let entry = null
570
+ const persistedDeviceId = client.deviceInfo?.deviceId
571
+ if (devicePreferences && persistedDeviceId) {
572
+ const persistedId = devicePreferences.getActiveSessionId(persistedDeviceId)
573
+ if (persistedId) {
574
+ const persistedEntry = sessionManager.getSession(persistedId)
575
+ if (persistedEntry) {
576
+ activeId = persistedId
577
+ entry = persistedEntry
578
+ }
579
+ }
580
+ }
581
+ if (!entry) {
582
+ activeId = defaultSessionId
583
+ entry = activeId ? sessionManager.getSession(activeId) : null
584
+ }
219
585
  if (!entry) {
220
586
  activeId = sessionManager.firstSessionId
221
587
  entry = activeId ? sessionManager.getSession(activeId) : null
222
588
  }
223
589
  // If client is bound to a specific session, use that session's cwd
224
590
  // instead of the server default to avoid leaking unrelated session info.
225
- if (client.boundSessionId) {
591
+ if (isBoundClient(client)) {
226
592
  const boundEntry = sessionManager.getSession(client.boundSessionId)
227
593
  if (boundEntry) {
228
594
  entry = boundEntry
@@ -232,6 +598,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
232
598
  }
233
599
  if (entry) {
234
600
  sessionInfo.cwd = entry.cwd
601
+ authOkProvider = entry.provider || null
235
602
  }
236
603
  } else if (cliSession) {
237
604
  sessionInfo.cwd = cliSession.cwd
@@ -344,7 +711,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
344
711
  client.eagerKeyExchange = null
345
712
  }
346
713
 
347
- const providers = listProviders()
714
+ const providers = listProviders({ agentConnections })
348
715
  const features = {
349
716
  environments: providers.some(p => p.capabilities?.containerized),
350
717
  }
@@ -376,6 +743,17 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
376
743
  // (older server) fall back to requesting the three lists as before. The
377
744
  // request handlers stay live either way for post-connect refreshes.
378
745
  authBootstrap: true,
746
+ // #7821 — provider_list/auth_bootstrap include versioned, non-secret agent
747
+ // connection descriptors and create_session accepts an explicit connectionId.
748
+ // New clients require this flag before presenting strong route selection;
749
+ // older clients keep provider-only creation and receive a legacy descriptor.
750
+ agentConnections: true,
751
+ // #8303 — `list_directory` accepts an optional `requestId` and `directory_listing`
752
+ // echoes it. The New Session browsability probe sends only to a server that
753
+ // advertises this: an older one answers untagged, and an untagged reply lands
754
+ // in the shared listing slot (autocomplete / the picker), where an error wipes
755
+ // autocomplete's suggestions.
756
+ directoryListingRequestIdV1: true,
379
757
  // #6481 (epic #6469): the opt-in IDE feature surface (file navigator, symbol
380
758
  // navigation, go-to-definition, find-references, edit-in-place) is enabled on
381
759
  // THIS server (config.features.ide / CHROXY_ENABLE_IDE). Clients gate ALL IDE
@@ -383,6 +761,38 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
383
761
  // (fail-closed). A server-wide feature gate, not token-scoped — available to
384
762
  // every client when the operator opts in.
385
763
  ide: ideEnabled === true,
764
+ // #6691: the opt-in orchestration/delegation harness ("committee") is
765
+ // enabled on THIS server (features.orchestration / CHROXY_ENABLE_ORCHESTRATION).
766
+ // Clients gate the Runs surface on this flag; absent/false (default, or older
767
+ // servers) → no orchestration chrome (fail-closed).
768
+ orchestration: orchestrationEnabled === true,
769
+ // #8619: the operator's `allowAutoPermissionMode` opt-in. Server-wide, not
770
+ // token-scoped, and NOT a promise that any one session can switch: a
771
+ // paired (bound) client is still refused (AUTO_MODE_FORBIDDEN_BOUND_CLIENT)
772
+ // and an adapter without `autoPermissionMode` still has no Auto. It tells
773
+ // a client only whether the config gate would admit a switch, so it can
774
+ // disable Auto with the real reason instead of a generic tooltip.
775
+ autoPermissionMode: autoPermissionModeAllowed === true,
776
+ // #6871 (epic #6784): this server has the scheduled-tasks WS surface
777
+ // (scheduled_tasks_request / scheduled_task_action / set_scheduler_enabled +
778
+ // the `scheduled_tasks` snapshot). CONSTANT true — deliberately NOT tied to
779
+ // whether scheduled EXECUTION is enabled. The enable gate is off by default
780
+ // and the registry exists either way, so gating the panel on the gate would
781
+ // hide exactly the banner that tells an operator their saved tasks will never
782
+ // fire. Clients read the real gate state off the snapshot's `scheduler` block.
783
+ scheduledTasks: true,
784
+ // #7822 — this server validates a versioned selected-context envelope,
785
+ // correlates acceptance with clientMessageId, and rejects unsupported
786
+ // kinds/lifetimes instead of letting an older passthrough schema drop them.
787
+ // New clients must gate context sends on this flag; old clients omit the
788
+ // envelope and continue through the legacy input path.
789
+ inputContextV1: true,
790
+ // #7977 — `create_session` accepts a client `requestId` and echoes it on the
791
+ // create-confirm `session_switched` and every error for that create. A client
792
+ // that needs the correlation (agent-control) must refuse to create on a daemon
793
+ // that lacks this flag: an older daemon would create the session and never
794
+ // echo, orphaning it behind a timeout.
795
+ createRequestIdV1: true,
386
796
  // #5986 (epic #5982) — the embedded user-shell terminal is available to THIS
387
797
  // client: the server has it enabled (userShell.enabled) AND this connection
388
798
  // holds the primary token. Both conditions of the create gate are reflected
@@ -446,28 +856,42 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
446
856
  ? streamStallTimeoutMs
447
857
  : DEFAULT_STREAM_STALL_TIMEOUT_MS
448
858
 
859
+ // #7811: same fallback the roster send further down this function applies —
860
+ // fold in the daemon's resolved default when there is no active session,
861
+ // instead of the CLAUDE default copy that `permissionModesForProvider(null)`
862
+ // returns. Otherwise a codex-default daemon's auth_ok would carry Claude's
863
+ // mode picker text.
864
+ const authOkRosterProvider = resolveRosterProvider(authOkProvider, billingCanary?.defaultProvider)
449
865
  const authOkDelivered = send(ws, {
450
866
  type: 'auth_ok',
451
867
  clientId: client.id,
452
868
  serverMode,
453
869
  serverVersion,
454
870
  latestVersion,
871
+ // #8268: id of the dashboard bundle the daemon serves now; a page that loaded a
872
+ // different one is stale. Omitted (not null) when no dist is built.
873
+ ...(dashboardBuildId ? { dashboardBuildId } : {}),
455
874
  serverCommit: gitInfo.commit,
456
875
  cwd: sessionInfo.cwd,
457
- defaultCwd: sessionManager?.defaultCwd || null,
458
- connectedClients: getConnectedClientList(),
876
+ // A session-scoped connection is told about its own session only: not the
877
+ // host's default working directory, and only the peers sharing its session.
878
+ defaultCwd: isBoundClient(client) ? null : (sessionManager?.defaultCwd || null),
879
+ connectedClients: getConnectedClientList(client),
459
880
  encryption: requireEncryption ? 'required' : 'disabled',
460
881
  protocolVersion,
461
882
  minProtocolVersion,
462
883
  maxProtocolVersion: protocolVersion,
463
884
  webFeatures: webTaskManager.getFeatureStatus(),
464
885
  features,
465
- capabilities,
886
+ capabilities: { ...capabilities, ...(extra.sessionToken ? { pairedCredentialConfirmation: true } : {}) },
466
887
  // #5555 — fold the static permission-mode enum into auth_ok so a new
467
888
  // client never has to wait for (or react to) the discrete
468
889
  // `available_permission_modes` burst frame. The discrete frame is still
469
890
  // sent below for older clients that read the enum only from it.
470
- availablePermissionModes: PERMISSION_MODES,
891
+ availablePermissionModes: permissionModesForProvider(authOkRosterProvider),
892
+ // #8224 — the roster is a fact about a provider; name it so the client files
893
+ // it under that provider instead of in a slot the next session inherits.
894
+ availablePermissionModesProvider: authOkRosterProvider,
471
895
  resultTimeoutMs: effectiveResultTimeoutMs,
472
896
  hardTimeoutMs: effectiveHardTimeoutMs,
473
897
  streamStallTimeoutMs: effectiveStreamStallTimeoutMs,
@@ -497,6 +921,8 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
497
921
  ? { newIdentityKey: serverIdentity.publicKey, rotationCert: serverIdentity.rotationCert }
498
922
  : {}),
499
923
  ...extra,
924
+ ...(extra.sessionToken && client.clientCapabilities?.has('paired_credential_confirmation_v1')
925
+ ? { sessionToken: undefined } : {}),
500
926
  })
501
927
 
502
928
  // #5555: now that the plaintext auth_ok (carrying serverPublicKey) has been
@@ -551,13 +977,30 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
551
977
  }, keyExchangeTimeoutMs)
552
978
  }
553
979
 
980
+ // Confirm the credential through the completed transport independently of catalogs.
981
+ if (extra.sessionToken && client.clientCapabilities?.has('paired_credential_confirmation_v1')) {
982
+ send(ws, { type: 'auth_bootstrap', credentialConfirmation: true, sessionToken: extra.sessionToken })
983
+ }
984
+
554
985
  send(ws, { type: 'server_mode', mode: serverMode })
555
986
  send(ws, { type: 'status', connected: true })
556
987
 
988
+ // #8331: the "update ready" banner's data. The SAME bar as the
989
+ // `daemon_update_action` it exists to drive: strict primary token AND unbound.
990
+ // A paired phone (an unbound pairing token) must not be told which commits are
991
+ // queued for the owner's machine, and a bound client sees nothing host-level.
992
+ if (daemonUpdate && client?.isPrimaryToken === true && !isBoundClient(client)) {
993
+ try {
994
+ send(ws, { type: 'daemon_update_status', ...daemonUpdate.getStatus() })
995
+ } catch (err) {
996
+ log.warn(`daemon_update_status failed for ${client.id}: ${err?.message || err}`)
997
+ }
998
+ }
999
+
557
1000
  // Multi-session mode
558
1001
  if (sessionManager) {
559
1002
  let sessions = sessionManager.listSessions()
560
- if (client.boundSessionId) {
1003
+ if (isBoundClient(client)) {
561
1004
  sessions = sessions.filter(s => s.sessionId === client.boundSessionId)
562
1005
  }
563
1006
  send(ws, { type: 'session_list', sessions })
@@ -565,7 +1008,8 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
565
1008
  // #5665: send the current monthly programmatic-credit meter snapshot so a
566
1009
  // freshly-connected dashboard shows it immediately, not only after the next
567
1010
  // billed turn. Machine-wide, so it's sent regardless of boundSessionId.
568
- if (typeof sessionManager.getMonthlyBudgetStatus === 'function') {
1011
+ // Not sent to a session-scoped connection: it is the host's spend, not the session's.
1012
+ if (typeof sessionManager.getMonthlyBudgetStatus === 'function' && !isBoundClient(client)) {
569
1013
  send(ws, { type: 'monthly_budget', ...sessionManager.getMonthlyBudgetStatus() })
570
1014
  }
571
1015
 
@@ -574,12 +1018,13 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
574
1018
  // reconnect after the event fired.
575
1019
  if (typeof sessionManager.getFailedRestores === 'function') {
576
1020
  for (const failed of sessionManager.getFailedRestores()) {
577
- if (client.boundSessionId && failed.sessionId !== client.boundSessionId) continue
1021
+ if (isBoundClient(client) && failed.sessionId !== client.boundSessionId) continue
578
1022
  send(ws, {
579
1023
  type: 'session_restore_failed',
580
1024
  sessionId: failed.sessionId,
581
1025
  name: failed.name,
582
1026
  provider: failed.provider,
1027
+ agentConnection: failed.agentConnection,
583
1028
  cwd: failed.cwd,
584
1029
  model: failed.model,
585
1030
  permissionMode: failed.permissionMode,
@@ -632,7 +1077,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
632
1077
  // any persisted per-device preference. Fail closed: if the bound session
633
1078
  // no longer exists, clear the active session rather than silently falling
634
1079
  // back to a different session (or inheriting an unrelated persisted pref).
635
- if (client.boundSessionId) {
1080
+ if (isBoundClient(client)) {
636
1081
  const boundEntry = sessionManager.getSession(client.boundSessionId)
637
1082
  if (boundEntry) {
638
1083
  activeId = client.boundSessionId
@@ -682,22 +1127,49 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
682
1127
  // class — getRegistryForProvider returns a provider-scoped registry
683
1128
  // seeded from that list. Claude providers share the default registry
684
1129
  // that is fed by `supportedModels()` on each SDK init.
1130
+ // #7728/#7759 — `activeProvider` is null on any post-auth connect with no
1131
+ // active session, and a null TAG is filed in the client's UNTAGGED bucket,
1132
+ // which it serves to a session of any provider while it is the only roster
1133
+ // it knows — a Claude roster labelled "could be anyone's". So the roster is
1134
+ // tagged with the daemon's resolved default instead, and its registry is
1135
+ // resolved from that SAME name (`resolveRosterProvider`) so the tag names
1136
+ // the registry that actually produced the rows.
1137
+ //
1138
+ // `activeProvider` itself is deliberately left as-is for the discovery
1139
+ // refresh below: that must keep no-opping for a client that has no
1140
+ // session. The permission-mode copy is a DIFFERENT statement — #7811: it
1141
+ // used to also read `activeProvider` (null with no session), so a
1142
+ // codex-default daemon paired the correctly-tagged `rosterProvider` roster
1143
+ // above with the CLAUDE mode-picker copy. It now reads `rosterProvider`
1144
+ // too, same as the roster it describes.
685
1145
  const activeProvider = entry?.provider || null
686
- const activeRegistry = getRegistryForProvider(activeProvider)
687
- send(ws, { type: 'available_models', models: activeRegistry.getModels(), defaultModel: activeRegistry.getDefaultModelId(), provider: activeProvider })
1146
+ const rosterProvider = resolveRosterProvider(activeProvider, billingCanary?.defaultProvider)
1147
+ const activeRegistry = getRegistryForProvider(rosterProvider)
1148
+ send(ws, { type: 'available_models', models: activeRegistry.getModels(), defaultModel: activeRegistry.getDefaultModelId(), provider: rosterProvider })
688
1149
  // #5421/#5555: dynamic-discovery refresh (ollama /api/tags). `sendSessionInfo`
689
1150
  // above was told to skip its own `available_models` push (de-dupe on connect),
690
1151
  // so it also skipped scheduling the refresh — this path now owns the single
691
1152
  // schedule. With no active session activeProvider is null and there is nothing
692
1153
  // to refresh (scheduleProviderModelsRefresh no-ops on a null provider).
693
1154
  scheduleProviderModelsRefresh(ctx, ws, activeProvider)
694
- send(ws, { type: 'available_permission_modes', modes: PERMISSION_MODES })
695
- permissions.resendPendingPermissions(ws, client)
1155
+ send(ws, { type: 'available_permission_modes', modes: permissionModesForProvider(rosterProvider), provider: rosterProvider })
1156
+ // #9015: the active session's prompts are NOT sent here. `replayHistory`
1157
+ // above always ends in `resendPendingPermissionsForSession` (its empty-history
1158
+ // early return and its `finishReplay` both call it), which delivers them
1159
+ // after `history_replay_end`; sending them here too put two copies on the
1160
+ // wire ~1 ms apart. Every other session, and ownerless hook-held prompts,
1161
+ // still go out through this unfiltered call.
1162
+ permissions.resendPendingPermissions(ws, client, entry ? { excludeSessionId: activeId } : undefined)
696
1163
  // #5555: fire the connect-time bootstrap burst (providers + slash commands
697
1164
  // + agents) so a new client never sends its 3-request list_* round trip.
698
1165
  // Fire-and-forget — the slash/agent compute is async (disk scans) and the
699
1166
  // synchronous post-auth burst above must not block on it.
700
- sendAuthBootstrap(ctx, ws, { cwd: entry?.cwd || null, provider: activeProvider, sessionId: activeId })
1167
+ // #6823: include the active BYOK session's MCP prompts so the connect-time
1168
+ // burst's slash_commands match the on-demand list_slash_commands response.
1169
+ const bootMcpPrompts = typeof entry?.session?.getMcpPromptCommands === 'function'
1170
+ ? entry.session.getMcpPromptCommands()
1171
+ : []
1172
+ 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 })
701
1173
  return
702
1174
  }
703
1175
 
@@ -720,23 +1192,27 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
720
1192
  // #6368: scope the legacy single-session model list to the ACTIVE provider's
721
1193
  // registry (the cliSession is the default-provider session) instead of the
722
1194
  // Claude-only module-level getModels(). billingCanary.defaultProvider is the
723
- // resolved `config.provider || DEFAULT_PROVIDER`; for Claude (or a null/absent
724
- // canary on old ctx) getRegistryForProvider falls back to the default Claude
725
- // registry, so behaviour is unchanged today.
726
- const legacyProvider = billingCanary?.defaultProvider || null
1195
+ // resolved `config.provider || DEFAULT_PROVIDER`.
1196
+ //
1197
+ // #7759 — an absent canary (old ctx / test fixture) used to leave this
1198
+ // `null`, which resolves to the default Claude registry and then tags the
1199
+ // roster it produced as UNTAGGED at the client. The registry is the same
1200
+ // one either way — DEFAULT_PROVIDER is Claude-family — so what changes is
1201
+ // only that the send now NAMES it.
1202
+ const legacyProvider = resolveRosterProvider(null, billingCanary?.defaultProvider)
727
1203
  const legacyRegistry = getRegistryForProvider(legacyProvider)
728
1204
  send(ws, { type: 'available_models', models: legacyRegistry.getModels(), defaultModel: legacyRegistry.getDefaultModelId(), provider: legacyProvider })
729
1205
  send(ws, {
730
1206
  type: 'permission_mode_changed',
731
1207
  mode: cliSession.permissionMode || 'approve',
732
1208
  })
733
- send(ws, { type: 'available_permission_modes', modes: PERMISSION_MODES })
1209
+ send(ws, { type: 'available_permission_modes', modes: permissionModesForProvider(legacyProvider), provider: legacyProvider })
734
1210
  }
735
1211
 
736
- permissions.resendPendingPermissions(ws)
1212
+ permissions.resendPendingPermissions(ws, client)
737
1213
  // #5555: legacy single-session bootstrap burst — providers + slash commands
738
1214
  // + agents for the cliSession's cwd (no provider scoping in legacy mode).
739
- sendAuthBootstrap(ctx, ws, { cwd: cliSession?.cwd || null, provider: null, sessionId: null })
1215
+ 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 })
740
1216
  }
741
1217
 
742
1218
  /**
@@ -767,16 +1243,35 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
767
1243
  * @param {{ cwd: string|null, provider: string|null, sessionId: string|null }} info
768
1244
  */
769
1245
  function sendAuthBootstrap(ctx, ws, info = {}) {
770
- const { send, services } = ctx
1246
+ const { send, services, agentConnections } = ctx
771
1247
  const fileOps = ctx.fileOps || services?.fileOps || null
1248
+ // #8151 round-2 review (Critical 1) — the real WsServer's `_historyCtx`
1249
+ // carries `config` FLAT (matching `fileOps`/`tunnelUrl` above), never
1250
+ // nested under `services` (that nesting is `_handlerCtx`'s shape, used by
1251
+ // settings-handlers.js's list_providers). Reading ONLY `services?.config`
1252
+ // here silently resolved to `undefined` on every real connection — never
1253
+ // caught because the round-2 test built its ctx by hand, with exactly
1254
+ // the `services.config` shape the (buggy) code expected. Same
1255
+ // either-shape fallback as `fileOps`, so a differently-shaped test ctx
1256
+ // (or a future caller) still works.
1257
+ const config = ctx.config || services?.config || null
772
1258
  const cwd = info.cwd || null
773
1259
  const provider = info.provider || null
1260
+ // #6823: MCP prompts to fold into the bootstrap slash-command list (empty for
1261
+ // non-BYOK / legacy sessions).
1262
+ const mcpPrompts = Array.isArray(info.mcpPrompts) ? info.mcpPrompts : []
774
1263
 
775
1264
  // providers is a cheap synchronous read off the registry — same source as
776
1265
  // the list_providers handler.
1266
+ // A session-scoped connection gets neither: the provider list carries the
1267
+ // host's credential readiness and configured connections, and the slash-command
1268
+ // and agent catalogs fall back to the user-level directories when no session
1269
+ // directory resolves. Both still arrive per request for what the connection is
1270
+ // allowed to ask (its own session's catalogs).
1271
+ const scoped = info.scoped === true
777
1272
  let providers = []
778
1273
  try {
779
- providers = listProviders()
1274
+ providers = scoped ? [] : listProviders({ agentConnections })
780
1275
  } catch (err) {
781
1276
  log.warn(`auth_bootstrap: listProviders failed: ${err.message}`)
782
1277
  providers = []
@@ -784,17 +1279,20 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
784
1279
 
785
1280
  // slash commands + agents are async disk scans; compute in parallel and
786
1281
  // tolerate either failing on its own.
787
- const slashP = fileOps && typeof fileOps.computeSlashCommands === 'function'
788
- ? fileOps.computeSlashCommands(cwd, provider).catch(err => {
1282
+ const catalogsAllowed = !scoped || cwd !== null
1283
+ const slashP = catalogsAllowed && fileOps && typeof fileOps.computeSlashCommands === 'function'
1284
+ ? fileOps.computeSlashCommands(cwd, provider, mcpPrompts, { projectOnly: scoped }).catch(err => {
789
1285
  log.warn(`auth_bootstrap: computeSlashCommands failed: ${err.message}`)
790
1286
  return []
791
1287
  })
792
1288
  : Promise.resolve([])
793
1289
  const userAgentsDirs = ctx.userAgentsDirs
794
- const agentsOpts = Array.isArray(userAgentsDirs) && userAgentsDirs.length > 0
795
- ? { userAgentsDirs }
796
- : {}
797
- const agentsP = fileOps && typeof fileOps.computeAgents === 'function'
1290
+ const agentsOpts = {
1291
+ ...(Array.isArray(userAgentsDirs) && userAgentsDirs.length > 0 ? { userAgentsDirs } : {}),
1292
+ // A session-scoped connection is bootstrapped with the project's agents only.
1293
+ projectOnly: scoped,
1294
+ }
1295
+ const agentsP = catalogsAllowed && fileOps && typeof fileOps.computeAgents === 'function'
798
1296
  ? fileOps.computeAgents(cwd, agentsOpts).catch(err => {
799
1297
  log.warn(`auth_bootstrap: computeAgents failed: ${err.message}`)
800
1298
  return []
@@ -807,7 +1305,11 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
807
1305
  if (ws.readyState !== 1) return
808
1306
  send(ws, {
809
1307
  type: 'auth_bootstrap',
1308
+ ...(info.sessionToken ? { sessionToken: info.sessionToken } : {}),
810
1309
  providers,
1310
+ // #8151 (C3) — same field/derivation as list_providers' response; see
1311
+ // handleListProviders (settings-handlers.js).
1312
+ defaultProvider: resolveDaemonDefaultProvider(config),
811
1313
  slashCommands,
812
1314
  agents,
813
1315
  ...(info.sessionId ? { sessionId: info.sessionId } : {}),
@@ -841,6 +1343,25 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
841
1343
  * Advisory only — this path feeds the picker; model VALIDATION for ollama
842
1344
  * stays unrestricted via getAllowedModels() returning null (a user can
843
1345
  * `ollama pull` mid-session or use an alias the tag list doesn't spell out).
1346
+ *
1347
+ * #8036 — this is also the ONLY production call site that reaches
1348
+ * `CodexSession.refreshModels()` with no live client: `probeCodexCatalog`
1349
+ * (codex-model-catalog.js) then spawns a short-lived `codex app-server` from
1350
+ * `ProviderClass.resolvedBinary` — a fresh, UNVERIFIED resolve — to answer
1351
+ * `model/list` on every post-auth `available_models` push. A `bin` thunk built
1352
+ * from `SessionManager.verifyOneShotExecutable(ProviderClass)` (#8030's
1353
+ * verified one-shot gate, generalized to take a provider class) is threaded
1354
+ * into `refreshModels(deps)` so that spawn is refused exactly like a fresh
1355
+ * codex chat session would be in `binaryProvenance.mode: 'block'`. Harmless
1356
+ * for every OTHER `refreshModels` implementation (ollama's HTTP `/api/tags`
1357
+ * probe, the anthropic-compatible catalog probe) — neither reads a `bin` key
1358
+ * from `deps`, so the extra property is simply ignored.
1359
+ *
1360
+ * Fails CLOSED when `ctx.sessionManager` is unavailable or too old to expose
1361
+ * `verifyOneShotExecutable` (a stubbed/minimal ctx in a test, or a future
1362
+ * refactor): the `bin` thunk still refuses rather than silently falling back
1363
+ * to `ProviderClass`'s own unverified default — same convention
1364
+ * `summarize-handlers.js` uses for the #8030 summarizer gate.
844
1365
  */
845
1366
  export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
846
1367
  if (!providerName) return
@@ -851,8 +1372,16 @@ export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
851
1372
  return // unknown provider — nothing to refresh
852
1373
  }
853
1374
  if (typeof ProviderClass?.refreshModels !== 'function') return
1375
+ const sessionManager = ctx?.sessionManager
1376
+ const verifyBin = typeof sessionManager?.verifyOneShotExecutable === 'function'
1377
+ ? () => sessionManager.verifyOneShotExecutable(ProviderClass)
1378
+ : () => {
1379
+ const err = new Error(`model refresh for provider ${providerName}: sessionManager.verifyOneShotExecutable is unavailable — refusing an unverified spawn (#8036)`)
1380
+ err.code = 'PROVIDER_BINARY_UNVERIFIED'
1381
+ throw err
1382
+ }
854
1383
  Promise.resolve()
855
- .then(() => ProviderClass.refreshModels())
1384
+ .then(() => ProviderClass.refreshModels({ bin: verifyBin }))
856
1385
  .then((models) => {
857
1386
  if (!Array.isArray(models) || models.length === 0) return
858
1387
  if (ws.readyState !== undefined && ws.readyState !== 1) return // client gone
@@ -883,33 +1412,74 @@ export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
883
1412
  * re-tags the dashboard's provider.
884
1413
  */
885
1414
  export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
886
- const { sessionManager, send } = ctx
1415
+ const { sessionManager, send, billingCanary, clients } = ctx
887
1416
  const entry = sessionManager?.getSession(sessionId)
888
1417
  if (!entry) return
889
1418
  const session = entry.session
890
1419
 
1420
+ if (entry.declaredStatus) send(ws, { type: 'session_status', sessionId, declaredStatus: { ...entry.declaredStatus } })
1421
+
1422
+ send(ws, {
1423
+ type: 'provider_runtime_info',
1424
+ sessionId,
1425
+ ...getProviderRuntimeInfo(entry.provider, session),
1426
+ })
1427
+
891
1428
  if (session.isReady) {
892
1429
  send(ws, { type: 'claude_ready', sessionId })
893
1430
  }
894
1431
  // #4302: push the new session's provider-scoped model list on every
895
- // switch. Without this, the dashboard's `availableModelsProvider` stays
896
- // tagged with whichever provider the client saw last (set on auth via
897
- // `sendPostAuthInfo`), and `modelsMatchProvider` in App.tsx suppresses
898
- // the model picker for any session whose provider differs from the
899
- // initial one — most visibly, a claude-cli session created after a
900
- // TUI/SDK session loses its picker entirely.
1432
+ // switch. Without this a client never learns the roster of a provider it
1433
+ // did not see at auth time (`sendPostAuthInfo`) — pre-#7728 that showed up
1434
+ // as the dashboard's single `availableModelsProvider` tag staying pinned to
1435
+ // the provider seen last, suppressing the picker for every other session;
1436
+ // since #7728 each roster is keyed by provider, so what a missing push
1437
+ // leaves behind is an EMPTY roster for that provider — no picker, and no
1438
+ // ids belonging to a provider that TAGGED its broadcast.
1439
+ //
1440
+ // #7759 — and no UNTAGGED roster either, on any send path: an entry that
1441
+ // reports no provider (and `sendPostAuthInfo`'s no-active-session case) used
1442
+ // to tag `null`, which the client files in the bucket that means "a
1443
+ // pre-provider daemon" and then serves to a session of any provider. The tag
1444
+ // is the daemon's resolved default in that case, and the registry is
1445
+ // resolved from that same name.
901
1446
  if (!opts.skipModels) {
902
- const activeProvider = entry.provider || null
903
- const activeRegistry = getRegistryForProvider(activeProvider)
1447
+ const rosterProvider = resolveRosterProvider(entry.provider, billingCanary?.defaultProvider)
1448
+ const activeRegistry = getRegistryForProvider(rosterProvider)
904
1449
  send(ws, {
905
1450
  type: 'available_models',
906
1451
  models: activeRegistry.getModels(),
907
1452
  defaultModel: activeRegistry.getDefaultModelId(),
908
- provider: activeProvider,
1453
+ provider: rosterProvider,
909
1454
  })
1455
+ // #8224 — and the permission-mode roster for that same provider. Plan,
1456
+ // Auto and the mode copy differ per provider (claude-tui cannot plan,
1457
+ // claude-sdk can), and this is the one call every path that makes a session
1458
+ // the client's ACTIVE one already makes — create, switch, destroy re-home,
1459
+ // conversation resume, checkpoint rewind of another client — where
1460
+ // `switch_session` used to be the only one that sent it, so a
1461
+ // create-and-auto-switch left the PREVIOUS session's roster in place
1462
+ // ("Plan (unavailable)" on a fresh claude-sdk session beside an active
1463
+ // claude-tui one). Tagged with the provider, so a client keys it by provider.
1464
+ //
1465
+ // Sent ONLY for the client's active session. `handleSubscribeSessions` calls
1466
+ // this for every background session on every `session_list`; a client older
1467
+ // than #8224 keeps one flat roster slot and would end each connect on a
1468
+ // BACKGROUND session's roster. Clients that key by provider lose nothing: the
1469
+ // connect burst, create and switch each cover the active session. (The
1470
+ // connect burst passes `skipModels` and sends its own tagged roster.)
1471
+ if (clients?.get(ws)?.activeSessionId === sessionId) {
1472
+ send(ws, {
1473
+ type: 'available_permission_modes',
1474
+ modes: getPermissionModes(rosterProvider, session.constructor),
1475
+ provider: rosterProvider,
1476
+ })
1477
+ }
910
1478
  // #5421: background dynamic-discovery refresh (ollama /api/tags); a
911
- // changed list is re-pushed to this client when the probe lands.
912
- scheduleProviderModelsRefresh(ctx, ws, activeProvider)
1479
+ // changed list is re-pushed to this client when the probe lands. Keyed on
1480
+ // the session's OWN provider, not the roster tag — a session that reports
1481
+ // none has nothing to probe.
1482
+ scheduleProviderModelsRefresh(ctx, ws, entry.provider || null)
913
1483
  }
914
1484
  send(ws, {
915
1485
  type: 'model_changed',
@@ -929,19 +1499,38 @@ export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
929
1499
  sessionId,
930
1500
  })
931
1501
  // Always sync thinking level on reconnect so stale dashboard state is overwritten
932
- const thinkingLevel = session.thinkingLevel
933
- if (thinkingLevel !== undefined) {
934
- send(ws, {
935
- type: 'thinking_level_changed',
936
- level: thinkingLevel || 'default',
937
- sessionId,
938
- })
1502
+ const thinkingLevelMsg = buildThinkingLevelChanged(session)
1503
+ if (thinkingLevelMsg) {
1504
+ send(ws, { ...thinkingLevelMsg, sessionId })
939
1505
  }
940
- // Replay permission rules so reconnecting clients have current whitelist
1506
+ // Replay permission rules so reconnecting clients have current whitelist.
1507
+ // #6771 — also replay durable per-project rules (persistentRules) so the
1508
+ // rules surfaces show standing "always allow" grants on session load, not
1509
+ // only after a fresh allowAlways in the current session.
941
1510
  if (typeof session.getPermissionRules === 'function') {
942
1511
  const rules = session.getPermissionRules()
943
- if (rules.length > 0) {
944
- send(ws, { type: 'permission_rules_updated', rules, sessionId })
1512
+ const persistentRules = typeof session.getPersistentPermissionRules === 'function'
1513
+ ? session.getPersistentPermissionRules()
1514
+ : []
1515
+ if (rules.length > 0 || persistentRules.length > 0) {
1516
+ send(ws, { type: 'permission_rules_updated', rules, persistentRules, sessionId })
1517
+ }
1518
+ }
1519
+
1520
+ // #6832: replay the last-known `mcp_servers` list so a client subscribing
1521
+ // to an already-warmed session (dashboard reconnect, second client joining
1522
+ // a shared session) sees the current server list without waiting on the
1523
+ // next emission. `mcp_servers` is a transient event (not recorded in
1524
+ // history) — sdk/cli sessions emit it once at the stream-json `system/init`
1525
+ // and claude-tui re-derives it on warmup/respawn (#6820/#6831), so a late
1526
+ // joiner previously saw "No MCP servers" until the next respawn. The
1527
+ // session caches the last payload (BaseSession `getMcpServersSnapshot()`,
1528
+ // set via a self-listener on `mcp_servers`); null means this session has
1529
+ // never emitted one, so there is nothing to replay.
1530
+ if (typeof session.getMcpServersSnapshot === 'function') {
1531
+ const mcpSnapshot = session.getMcpServersSnapshot()
1532
+ if (mcpSnapshot) {
1533
+ send(ws, { ...mcpSnapshot, sessionId })
945
1534
  }
946
1535
  }
947
1536
 
@@ -1061,6 +1650,198 @@ export function resolveReplayPlan(sessionManager, history, sessionId, lastSeq, l
1061
1650
  return { fullHistory: false, startOffset }
1062
1651
  }
1063
1652
 
1653
+ /**
1654
+ * #7509 F7 -- read a list off a provider session for a replay follow-up, and turn
1655
+ * a provider that cannot answer into a LOGGED, empty result instead of a throw.
1656
+ *
1657
+ * `getActiveAgents()` and `getPendingQuestions()` are defined on BaseSession, but
1658
+ * `validateProviderClass` (providers.js) only requires six prototype methods, so
1659
+ * a custom provider that does not extend BaseSession can lack either -- and both
1660
+ * follow-ups run inside `finishReplay`, a `setImmediate` continuation, where a
1661
+ * throw is an uncaught exception that also skips every follow-up after it.
1662
+ *
1663
+ * This is deliberately NOT a feature-detect: the method is still called, so a
1664
+ * provider that lacks it or throws is reported (session id, method, cause) at
1665
+ * error level rather than treated as "nothing to send". It is the ONE place both
1666
+ * follow-ups read through, so a third caller inherits it.
1667
+ *
1668
+ * @param {object} session
1669
+ * @param {string} sessionId
1670
+ * @param {'getActiveAgents' | 'getPendingQuestions'} method
1671
+ * @returns {Array}
1672
+ */
1673
+ function readProviderList(session, sessionId, method) {
1674
+ try {
1675
+ const list = session[method]()
1676
+ if (!Array.isArray(list)) {
1677
+ throw new TypeError(`${method}() returned ${list === null ? 'null' : typeof list}, expected an array`)
1678
+ }
1679
+ return list
1680
+ } catch (err) {
1681
+ log.error(`Replay follow-up ${method}() failed on session ${sessionId}: ${err?.message || err} -- skipping it, the replay still finishes`)
1682
+ return []
1683
+ }
1684
+ }
1685
+
1686
+ /**
1687
+ * #7340 — re-seed a client's `activeAgents` after a history replay.
1688
+ *
1689
+ * Both clients WIPE `activeAgents` on `history_replay_start` (dashboard
1690
+ * `message-handler.ts`, app `message-handler.ts`) because `agent_spawned` /
1691
+ * `agent_completed` are transient and never replayed from history, so anything
1692
+ * they still held could be stale from before the disconnect. That wipe is
1693
+ * correct and is KEPT — it is the only thing that drops a completion the
1694
+ * client missed while offline. What was missing is the other half: nothing
1695
+ * re-asserted the subagents that ARE still running, so a reconnect or a tab
1696
+ * switch silently emptied the badge list.
1697
+ *
1698
+ * Sending the live set here turns the pair into a snapshot REPLACE, mirroring
1699
+ * `activity_snapshot`'s snapshot-on-subscribe and `background_work_changed`'s
1700
+ * full-snapshot philosophy. It runs AFTER `history_replay_end` deliberately:
1701
+ * `sendSessionInfo` is called BEFORE `replayHistory` on both the connect
1702
+ * handshake and the session-switch path, so anything seeded there is erased by
1703
+ * the wipe that follows it.
1704
+ *
1705
+ * Idempotent — both clients dedupe `agent_spawned` by `toolUseId`, so a client
1706
+ * that never lost the entry sees no change.
1707
+ *
1708
+ * Before #7340 this was reachable but pointless (nothing survived a turn end,
1709
+ * so the live set was empty on every replay); with the turn-end exemption a
1710
+ * confirmed-backgrounded subagent is exactly what is in it.
1711
+ */
1712
+ export function reseedActiveAgents(ctx, ws, sessionId) {
1713
+ const { sessionManager, send } = ctx
1714
+ // No `typeof session.getActiveAgents === 'function'` guard: it is defined on
1715
+ // BaseSession, which every provider extends, so it can never be missing --
1716
+ // and a feature-detect that can never fail turns a future regression into a
1717
+ // silent no-op instead of a crash ("cannot check this" read as "nothing to
1718
+ // check", docs/false-safety-guards.md).
1719
+ //
1720
+ // What `readProviderList` adds is the opposite of a feature-detect: the call
1721
+ // is still made, and a provider that lacks it or throws is LOGGED loudly
1722
+ // (#7509 F7), never swallowed -- and never allowed to escape a `setImmediate`
1723
+ // continuation as an uncaught exception that skips the follow-ups after it.
1724
+ const session = sessionManager?.getSession(sessionId)?.session
1725
+ if (!session) return
1726
+ for (const agent of readProviderList(session, sessionId, 'getActiveAgents')) {
1727
+ send(ws, { type: 'agent_spawned', sessionId, ...agent })
1728
+ }
1729
+ }
1730
+
1731
+ /**
1732
+ * #7457 -- re-send the AskUserQuestion prompts a session is still BLOCKED on,
1733
+ * as LIVE frames, immediately after a replay's `history_replay_end`.
1734
+ *
1735
+ * The bug this closes is the non-racing half of #7420. `history_replay_end`
1736
+ * stamps `answered: '(resolved)'` on every unanswered `prompt` the sweep is
1737
+ * entitled to touch, on the premise that anything in history is already
1738
+ * resolved. #7453 carved out the question that arrived LIVE during the replay
1739
+ * and deliberately could not carve out the still-pending one: `user_question`
1740
+ * is not in `builtinTransient`, so it IS in the ring buffer, so the replay
1741
+ * re-delivers it carrying `historySeq` -- correctly classified as
1742
+ * replay-delivered by the only discriminator there is. Background the phone
1743
+ * mid-question, reopen it, and the prompt is a resolved pill with the agent
1744
+ * still blocked on the resolver until it times out.
1745
+ *
1746
+ * Two properties make this the fix rather than a mitigation, and BOTH are why
1747
+ * it lives in `finishReplay` rather than beside `resendPendingPermissions` in
1748
+ * the post-auth block (the issue's own suggestion):
1749
+ *
1750
+ * 1. ORDER. `replayHistory` is chunked and yields the event loop between
1751
+ * chunks, so a call placed after `replayHistory(...)` RETURNS still runs
1752
+ * before `history_replay_end` reaches the client -- which is precisely why
1753
+ * the sweep's own comment can say `resendPendingPermissions` runs "after
1754
+ * replayHistory has already sent its first chunk". Permissions do not care
1755
+ * (they are excluded from the sweep by `requestId`); a question's whole
1756
+ * defence is landing after the end frame, so it must be sequenced by the
1757
+ * replay's completion, not by its invocation.
1758
+ * 2. COVERAGE. `finishReplay` is the ONE exit both replay paths share (#7340),
1759
+ * and `replayHistory` serves connect, `switch_session` (forceFull rebuild),
1760
+ * `subscribe_sessions` and the checkpoint restore alike. Bolted onto the
1761
+ * post-auth block instead, every one of those but connect stays broken.
1762
+ *
1763
+ * The frame carries NO `historySeq`, which is what makes the client treat it as
1764
+ * live: `dispatchUserQuestion` keys #7420's discriminator on that field's
1765
+ * presence. It is otherwise byte-identical to the dispatch-time frame -- no
1766
+ * wire-shape change, no protocol bump, and both clients supersede the copy they
1767
+ * already hold by `toolUseId` rather than stacking a duplicate bubble.
1768
+ *
1769
+ * `getPendingQuestions()` carries no feature-detect for the same reason
1770
+ * `getActiveAgents()` above does not: BaseSession defines it, so a detect here
1771
+ * could never fail and would only convert a future regression into a silent
1772
+ * no-op. It IS read through `readProviderList` (#7509 F7), so a custom provider
1773
+ * that lacks it or throws is logged with the session id and method rather than
1774
+ * escaping `finishReplay`'s `setImmediate` as an uncaught exception.
1775
+ *
1776
+ * No route registration: `_questionSessionMap` entries are pruned only when the
1777
+ * question resolves or its session is destroyed, so a still-pending question is
1778
+ * still mapped, and `handleUserQuestionResponse`'s viewer check is the same
1779
+ * predicate `_broadcastToSession` uses -- a client being replayed this session
1780
+ * necessarily passes it.
1781
+ *
1782
+ * @param {object} ctx
1783
+ * @param {WebSocket} ws
1784
+ * @param {string} sessionId
1785
+ */
1786
+ export function resendPendingQuestions(ctx, ws, sessionId) {
1787
+ const { sessionManager, send } = ctx
1788
+ const session = sessionManager?.getSession(sessionId)?.session
1789
+ if (!session) return
1790
+ for (const { toolUseId, questions } of readProviderList(session, sessionId, 'getPendingQuestions')) {
1791
+ // An entry with no id is unanswerable: `handleUserQuestionResponse` routes
1792
+ // strictly by `toolUseId` and fails closed on one it cannot find. Skip it
1793
+ // rather than send a prompt whose answer can only be dropped -- and skip
1794
+ // only IT, so a malformed entry can't strand the valid ones behind it
1795
+ // (#6054's per-entry isolation, same reason).
1796
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) {
1797
+ log.warn(`Skipping pending question with no toolUseId on session ${sessionId}`)
1798
+ continue
1799
+ }
1800
+ send(ws, { type: 'user_question', sessionId, toolUseId, questions })
1801
+ }
1802
+ }
1803
+
1804
+ /**
1805
+ * #8328 — re-assert the permission prompts a session is still blocked on, to
1806
+ * ONE client, after a replay of that session.
1807
+ *
1808
+ * `permission_request` is in `builtinTransient`: never in the ring buffer, so a
1809
+ * replay cannot deliver it, and a FULL-rebuild replay (`switch_session`'s
1810
+ * `forceFull`, `subscribe_sessions`) swaps in a message list built from history
1811
+ * alone — dropping the prompt card the client appended LIVE while the session
1812
+ * was a background one. The turn then sits at "Running Bash..." with no card
1813
+ * until the request's timeout denies it. Same shape as `resendPendingQuestions`
1814
+ * above, same fix, and the same reason it hangs off the replay's exit rather
1815
+ * than off `switch_session`: every replay path needs it.
1816
+ *
1817
+ * It delegates to `permissions.resendPendingPermissions` — the ONE
1818
+ * implementation, which the connect-time (unfiltered) resend also uses — and
1819
+ * covers both the SDK-held and the hook-held (claude-tui, the default
1820
+ * provider) pending sets.
1821
+ *
1822
+ * `ctx.permissions` is the permission handler; ctx fixtures that never built
1823
+ * one have nothing to re-send, hence the optional chain on it alone — the
1824
+ * method on a real handler is called unguarded so drift fails loudly.
1825
+ *
1826
+ * Connect (#9015): `sendPostAuthInfo` also does an unfiltered resend, but it
1827
+ * EXCLUDES the active session it is about to replay — this replay-exit call owns
1828
+ * that session's prompts, so they arrive exactly once, after `history_replay_end`.
1829
+ * The unfiltered call still delivers every other session's prompts (and
1830
+ * ownerless hook-held ones); a BACKGROUND session's later `subscribe_sessions`
1831
+ * full-rebuild replay re-asserts its card via this function, which is the
1832
+ * intended second delivery there (clients update in place by `requestId`).
1833
+ *
1834
+ * @param {object} ctx
1835
+ * @param {WebSocket} ws
1836
+ * @param {string} sessionId
1837
+ */
1838
+ export function resendPendingPermissionsForSession(ctx, ws, sessionId) {
1839
+ const { permissions, clients } = ctx
1840
+ if (!permissions) return
1841
+ const client = clients && typeof clients.get === 'function' ? clients.get(ws) : undefined
1842
+ permissions.resendPendingPermissions(ws, client, { sessionId })
1843
+ }
1844
+
1064
1845
  /**
1065
1846
  * Replay message history for a session to a single client.
1066
1847
  * Sends the retained ring buffer in batches to yield the event loop.
@@ -1087,7 +1868,15 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1087
1868
  const { sessionManager, send, clients } = ctx
1088
1869
  if (!sessionManager) return
1089
1870
  const history = sessionManager.getHistory(sessionId)
1090
- if (history.length === 0) return
1871
+ if (history.length === 0) {
1872
+ // #8328: no replay frames means the client does not rebuild this session's
1873
+ // messages, so nothing it holds is dropped here — but a client that never
1874
+ // received the live broadcast (it was not subscribed when the request was
1875
+ // raised) still needs the prompt, and an in-place update by `requestId`
1876
+ // makes the re-send free for one that did.
1877
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
1878
+ return
1879
+ }
1091
1880
 
1092
1881
  const truncated = sessionManager.isHistoryTruncated(sessionId)
1093
1882
 
@@ -1118,134 +1907,186 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1118
1907
 
1119
1908
  send(ws, { type: 'history_replay_start', sessionId, truncated, fullHistory, latestSeq })
1120
1909
 
1121
- const CHUNK_SIZE = 20
1122
- const sendChunk = (offset) => {
1123
- if (ws.readyState !== 1) return
1124
- // #4833 follow-up: gate chunk *entry* on bufferedAmount too, not just
1125
- // chunk *scheduling*. The recursive setImmediate-via-scheduleAfterDrain
1126
- // path is already gated, but the very first sendChunk(0) call can land
1127
- // on a socket that's already congested from the preceding
1128
- // sendPostAuthInfo / session_switched burst. Without this check, the
1129
- // first history entry would be sent unconditionally and the mid-chunk
1130
- // break (which only fires *after* a send) wouldn't trip until i=1 —
1131
- // meaning we still push one fat tool_result onto an already-congested
1132
- // socket and can trip the 1MB EVICT_THRESHOLD.
1133
- if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1134
- scheduleAfterDrain(ws, () => sendChunk(offset))
1135
- return
1136
- }
1137
- const end = Math.min(offset + CHUNK_SIZE, history.length)
1138
- let nextOffset = end
1139
- for (let i = offset; i < end; i++) {
1140
- const entry = history[i]
1141
- // #5555.3 — surface the server-internal `_seq` to the client as
1142
- // `historySeq` (and strip the underscore-prefixed internal field) so the
1143
- // client can advance its per-session cursor as it applies each entry.
1144
- const { _seq, ...wireEntry } = entry
1145
- send(ws, { ...wireEntry, sessionId, ...(typeof _seq === 'number' ? { historySeq: _seq } : {}) })
1146
- // #4628: mirror the live `result → agent_idle` fan-out from
1147
- // event-normalizer.js. The dashboard's handler dispatch table has
1148
- // no `result` entry — only `agent_idle` — so a raw `result` in
1149
- // history-replay is silently dropped, and `handleAgentIdle`
1150
- // (which clears activeTools as the #4308 safety net) never fires.
1151
- // Without this, a session that completed cleanly but had an
1152
- // orphan tool_start in history (e.g. dropped PostToolUse hook,
1153
- // #4628 root cause) shows a zombie "Running X" chip every time
1154
- // the dashboard reconnects, until the next chroxy restart. The
1155
- // companion `_emitResult` sweep in BaseSession prevents new
1156
- // orphans from being persisted; this heals the existing wedged
1157
- // sessions on reconnect without requiring a restart.
1158
- if (entry && entry.type === 'result') {
1159
- send(ws, { type: 'agent_idle', sessionId })
1160
- }
1161
- // #4833: break out of the chunk early if bufferedAmount already
1162
- // crossed the pause threshold mid-burst. The CHUNK_SIZE=20 cap was
1163
- // designed for short messages; a session with fat tool_result
1164
- // payloads (200KB+) can blow past the 1MB EVICT_THRESHOLD inside
1165
- // a single chunk, before the post-chunk scheduleAfterDrain ever
1166
- // gets to inspect bufferedAmount. Pause + resume from the next
1167
- // unsent entry instead.
1168
- if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1169
- nextOffset = i + 1
1170
- break
1171
- }
1172
- }
1173
- if (nextOffset < history.length) {
1174
- // #4833: pause if the socket is already congested before scheduling
1175
- // the next chunk. Without this, every setImmediate fires another
1176
- // burst regardless of buffer pressure, blowing past the 1MB
1177
- // EVICT_THRESHOLD in ws-client-sender.js on sessions with fat
1178
- // tool_result payloads.
1179
- scheduleAfterDrain(ws, () => sendChunk(nextOffset))
1180
- } else {
1910
+ // #7340: ONE exit from the replay, because there are two ways out of it (an
1911
+ // empty slice and a drained final chunk) and the re-seed must follow BOTH.
1912
+ // Two `history_replay_end` sends with the follow-up bolted onto only one of
1913
+ // them leaves the empty-slice path — the quick reconnect, the most common
1914
+ // replay of all — silently unfixed.
1915
+ const finishReplay = () => {
1916
+ // #9015: the permission re-send is the ONLY delivery of the active
1917
+ // session's pending prompt on connect (the post-auth resend excludes it), so
1918
+ // it runs in a `finally`: a throw from the end frame or the agent re-seed
1919
+ // must not drop the sole copy. The success path still sends it exactly once.
1920
+ //
1921
+ // #8357: PERMISSIONS BEFORE QUESTIONS. A question card is withheld until its
1922
+ // own AskUserQuestion permission is allowed, and the client can only know
1923
+ // that permission exists once it has arrived. Sent the other way round, a
1924
+ // reconnecting client holds the re-sent question with no permission to gate
1925
+ // it, and can show and answer it before the permission lands: not a
1926
+ // millisecond race, a whole resend apart.
1927
+ try {
1181
1928
  send(ws, { type: 'history_replay_end', sessionId, latestSeq })
1929
+ reseedActiveAgents(ctx, ws, sessionId)
1930
+ } finally {
1931
+ try {
1932
+ // #8328: AFTER the end frame. A full-rebuild replay swaps in a
1933
+ // history-only message list at `history_replay_end`, dropping the live
1934
+ // permission card the client held for this session; `permission_request`
1935
+ // is transient, so the replay itself cannot restore it. Sent after the
1936
+ // swap, the re-send lands on the rebuilt list and is kept.
1937
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
1938
+ } finally {
1939
+ // #7457: AFTER the end frame, never before it. The client's replay-end
1940
+ // sweep has already run by the time this lands, which is the entire
1941
+ // reason a still-pending question survives the reconnect. In its own
1942
+ // `finally` so a failed permission re-send cannot lose the question.
1943
+ resendPendingQuestions(ctx, ws, sessionId)
1944
+ }
1182
1945
  }
1183
1946
  }
1947
+
1948
+ // A manager that cannot answer reads as idle, as in the JSONL heal's own check
1949
+ // (conversation-handlers.js); asked again for each replayed result.
1950
+ const isSessionBusy = () => typeof sessionManager.isSessionBusy === 'function'
1951
+ ? sessionManager.isSessionBusy(sessionId)
1952
+ : false
1953
+
1184
1954
  // #5555.3 — start at the resolved offset: 0 for a full replay, the
1185
1955
  // first-newer-than-cursor index for a delta replay. When the client is
1186
- // already current (startOffset === history.length) this immediately falls
1187
- // through to the empty-slice path and emits start+end with nothing between.
1188
- if (startOffset >= history.length) {
1189
- send(ws, { type: 'history_replay_end', sessionId, latestSeq })
1190
- } else {
1191
- sendChunk(startOffset)
1956
+ // already current (startOffset === history.length) sendChunkedWithBackpressure
1957
+ // falls straight through to the empty-slice path and emits start+end with
1958
+ // nothing between.
1959
+ //
1960
+ // #7460 — the chunk-and-drain machinery and the per-entry wire mapping both
1961
+ // live in ONE place now (above), because `handleRequestFullHistory` is the
1962
+ // second caller of exactly this loop and every hand-copied piece of it has
1963
+ // drifted: the `_seq` map (#7454), the `result` → `agent_idle` synthesis
1964
+ // (#7459), and the bufferedAmount gating (#7460) were each missing there.
1965
+ // #9022 -- a reply is recorded only when its stream closes, so a turn paused
1966
+ // mid-stream (on a permission prompt) has its text in no entry. Splice what has
1967
+ // streamed so far in, at its place in the transcript. The position matters for a
1968
+ // DELTA replay, which appends in arrival order; a full replay's provenance sort
1969
+ // puts the (unnumbered) snapshot after the numbered entries (#9024).
1970
+ const pending = client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_INFLIGHT_REPLY)
1971
+ ? pendingStreamEntries(sessionManager, sessionId)
1972
+ : []
1973
+ const replayEntries = pending.length > 0
1974
+ ? spliceInPendingStreams(history.slice(startOffset), pending)
1975
+ : history
1976
+ sendChunkedWithBackpressure(ws, replayEntries, {
1977
+ startOffset: pending.length > 0 ? 0 : startOffset,
1978
+ // #9015: a throwing entry ABORTS the replay and never claims completion (no
1979
+ // `history_replay_end` carrying `latestSeq` — the client would commit a
1980
+ // partial transcript and its cursor). Permission recovery is independent of
1981
+ // replay success, though: the connect-time resend excludes the active
1982
+ // session, so this abort path delivers its pending prompt (once — the loop
1983
+ // stops and `finishReplay` never runs) and then rethrows, as before.
1984
+ emit: (entry) => {
1985
+ try {
1986
+ sendHistoryEntry(send, ws, sessionId, entry, client, isSessionBusy)
1987
+ } catch (err) {
1988
+ try {
1989
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
1990
+ } catch (resendErr) {
1991
+ log.warn(`Permission re-send after an aborted replay of ${sessionId} failed: ${resendErr?.message ?? resendErr}`)
1992
+ }
1993
+ throw err
1994
+ }
1995
+ },
1996
+ onDone: finishReplay,
1997
+ })
1998
+ }
1999
+
2000
+ /**
2001
+ * #9022 -- the still-open reply streams of a session as replayable entries.
2002
+ *
2003
+ * Sent on a delta replay too, whatever the client's cursor: the client dedups a
2004
+ * reply it already holds by id, completes one it holds only the start of (#8444's
2005
+ * `completeHeldResponseStream`, which also refills deltas missed in a dropped
2006
+ * connection), and keeps one that has run ahead of the snapshot. A cursor filter
2007
+ * would not be a sound "did the client see this stream start" test anyway: live
2008
+ * frames carry no `historySeq`, so a cursor says nothing about a stream's start.
2009
+ *
2010
+ * The entries carry no `_seq`, so a client advances no cursor off them, and no
2011
+ * field the stream's own completed entry lacks: when the stream closes, the
2012
+ * recorded entry has the same `messageId`, so a client that kept this one dedups.
2013
+ */
2014
+ function pendingStreamEntries(sessionManager, sessionId) {
2015
+ if (typeof sessionManager.getPendingResponseStreams !== 'function') return []
2016
+ const streams = sessionManager.getPendingResponseStreams(sessionId)
2017
+ const now = Date.now()
2018
+ return streams.map((s) => ({
2019
+ startSeq: s.startSeq,
2020
+ entry: {
2021
+ type: 'message',
2022
+ messageType: 'response',
2023
+ content: s.content,
2024
+ messageId: s.messageId,
2025
+ timestamp: now,
2026
+ },
2027
+ }))
2028
+ }
2029
+
2030
+ /**
2031
+ * Put each pending-stream entry before the first recorded entry that came after
2032
+ * its stream opened (the end, when none did). Returns a new array; `entries` is
2033
+ * the ring buffer's own and is not touched.
2034
+ */
2035
+ function spliceInPendingStreams(entries, pending) {
2036
+ const out = entries.slice()
2037
+ // Latest-opened first, so an earlier splice never shifts the index a later one
2038
+ // was computed for.
2039
+ const ordered = [...pending].sort((a, b) => b.startSeq - a.startSeq)
2040
+ for (const { startSeq, entry } of ordered) {
2041
+ let at = out.findIndex((e) => typeof e._seq === 'number' && e._seq >= startSeq)
2042
+ if (at === -1) at = out.length
2043
+ out.splice(at, 0, entry)
1192
2044
  }
2045
+ return out
1193
2046
  }
1194
2047
 
1195
2048
  /**
1196
- * Flush queued post-auth messages in batches to yield the event loop.
1197
- * Same chunking pattern as replayHistory.
2049
+ * Flush queued post-auth messages to a client through the shared chunk +
2050
+ * back-pressure loop.
2051
+ *
2052
+ * #7485 — this was the last hand-copied instance of that loop: its own
2053
+ * `CHUNK_SIZE = 20` four lines from `REPLAY_CHUNK_SIZE`, its own readyState
2054
+ * exit, its own chunk-entry gate, its own mid-chunk break and its own
2055
+ * scheduling gate, all maintained in parallel since #4845. What kept it
2056
+ * separate is the queue state it owns on top of the loop, and each piece maps
2057
+ * onto one of the hooks `sendChunkedWithBackpressure` now takes:
2058
+ *
2059
+ * - `_flushing` is the gate ws-client-sender.js reads. It must be TRUE
2060
+ * whenever this flush is parked, so a concurrent `send` lands in
2061
+ * `_flushOverflow` behind the queued messages instead of overtaking them,
2062
+ * and FALSE while a chunk is actually being written — which is exactly
2063
+ * onPause / onResume.
2064
+ * - a socket that leaves OPEN mid-flush must drop BOTH `_flushing` (or every
2065
+ * later send is swallowed by a gate nothing will ever release) and
2066
+ * `_flushOverflow` (nothing will drain it) — onAbort.
2067
+ * - the terminal branch recurses into whatever arrived while we were parked,
2068
+ * rather than sending an end frame — onDone.
1198
2069
  */
1199
2070
  export function flushPostAuthQueue(ctx, ws, queue) {
1200
2071
  const { clients, send } = ctx
1201
2072
  const client = clients.get(ws)
1202
2073
  if (client) client._flushing = true
1203
- const CHUNK_SIZE = 20
1204
- const drainChunk = (offset) => {
1205
- if (ws.readyState !== 1) {
2074
+ sendChunkedWithBackpressure(ws, queue, {
2075
+ emit: (message) => send(ws, message),
2076
+ onPause: () => { if (client) client._flushing = true },
2077
+ onResume: () => { if (client) client._flushing = false },
2078
+ onAbort: () => {
1206
2079
  if (client) {
1207
2080
  client._flushing = false
1208
2081
  client._flushOverflow = null
1209
2082
  }
1210
- return
1211
- }
1212
- // #4833 follow-up: gate chunk *entry* on bufferedAmount too — same
1213
- // rationale as replayHistory.sendChunk above. drainChunk(0) is invoked
1214
- // synchronously from flushPostAuthQueue, so the very first queued
1215
- // message can land on an already-congested socket (e.g. fat post-auth
1216
- // payloads that were queued during the encryption handshake) before the
1217
- // mid-chunk break (which only fires after a send) gets a chance to
1218
- // pause. Keep _flushing = true so any callers using ws-client-sender's
1219
- // _flushing buffer still queue overflow instead of blasting past us.
1220
- if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1221
- if (client) client._flushing = true
1222
- scheduleAfterDrain(ws, () => drainChunk(offset))
1223
- return
1224
- }
1225
- const end = Math.min(offset + CHUNK_SIZE, queue.length)
1226
- if (client) client._flushing = false
1227
- let nextOffset = end
1228
- for (let i = offset; i < end; i++) {
1229
- send(ws, queue[i])
1230
- // #4833: break early if a fat queued message just tipped bufferedAmount
1231
- // past the pause threshold — same rationale as replayHistory above.
1232
- if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1233
- nextOffset = i + 1
1234
- break
1235
- }
1236
- }
1237
- if (nextOffset < queue.length) {
1238
- if (client) client._flushing = true
1239
- // #4833: pause if the socket is already congested before scheduling
1240
- // the next chunk — same rationale as replayHistory above.
1241
- scheduleAfterDrain(ws, () => drainChunk(nextOffset))
1242
- } else if (client) {
1243
- if (client._flushOverflow?.length) {
2083
+ },
2084
+ onDone: () => {
2085
+ if (client?._flushOverflow?.length) {
1244
2086
  const overflow = client._flushOverflow
1245
2087
  client._flushOverflow = null
1246
2088
  flushPostAuthQueue(ctx, ws, overflow)
1247
2089
  }
1248
- }
1249
- }
1250
- drainChunk(0)
2090
+ },
2091
+ })
1251
2092
  }