@chroxy/server 0.11.0 → 0.11.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -5,18 +5,23 @@
5
5
  * rename_session, subscribe_sessions, unsubscribe_sessions
6
6
  */
7
7
  import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
8
+ import { authorizedFor } from '../connection-authority.js'
9
+ import { isBoundClient } from '../environments/authority.js'
10
+ import { isPrincipalClient, refusePrincipalHandler } from '../principal-policy.js'
8
11
  import { auditShellCreate } from '../shell-audit.js'
9
- import { validateCwdAllowed, broadcastFocusChanged, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError, isSessionViewer, isUserShellSession, ALLOWED_PERMISSION_MODE_IDS, getPermissionModes } from '../handler-utils.js'
10
- import { getRegistryForProvider } from '../models.js'
12
+ import { validateCwdAllowed, broadcastFocusChanged, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError, isSessionViewer, isUserShellSession, ALLOWED_PERMISSION_MODE_IDS } from '../handler-utils.js'
13
+ import { getRegistryForProvider, resolveRosterProvider } from '../models.js'
14
+ import { resolveDaemonDefaultProvider } from '../providers.js'
11
15
  import { CODEX_SANDBOX_MODES } from '../codex-session.js'
12
- import { isUserShellEnabled, isUserShellApprovalRequired } from '../config.js'
16
+ import { isUserShellEnabled, isUserShellApprovalRequired, validateSessionArchivePolicy, writeSessionArchiveToConfig } from '../config.js'
17
+ import { getErrorMessage } from '../utils/error-message.js'
13
18
  import { createLogger, loggerForSession } from '../logger.js'
14
19
 
15
20
  const log = createLogger('ws')
16
21
 
17
22
  function handleListSessions(ws, client, _msg, ctx) {
18
23
  let sessions = ctx.sessions.sessionManager.listSessions()
19
- if (client.boundSessionId) {
24
+ if (isBoundClient(client)) {
20
25
  sessions = sessions.filter(s => s.sessionId === client.boundSessionId)
21
26
  }
22
27
  ctx.transport.send(ws, { type: 'session_list', sessions })
@@ -79,16 +84,43 @@ function handleSwitchSession(ws, client, msg, ctx) {
79
84
  // Re-send provider-scoped available_models so clients that switch from a
80
85
  // Claude session to a Codex/Gemini session (or vice-versa) update their
81
86
  // model dropdown immediately (#2956).
87
+ //
88
+ // #7759 — an entry that reports no provider used to tag this roster `null`,
89
+ // which `getRegistryForProvider` answers with the CLAUDE registry and the
90
+ // client files in its UNTAGGED bucket ("a pre-provider daemon"), then serves
91
+ // to a session of any provider. Tag the daemon's resolved default instead —
92
+ // `resolveDaemonDefaultProvider(config)`, the same value
93
+ // `billingCanary.defaultProvider` carries to the ws-history senders (#8189:
94
+ // was the raw `ctx.services.config?.provider` field, re-deriving the same
95
+ // precedence by hand instead of calling the shared helper every other call
96
+ // site of `resolveRosterProvider` already uses) — and resolve the registry
97
+ // from that same name so the tag names whatever produced the rows. #7811 —
98
+ // the permission-mode copy below now reads the SAME resolved roster
99
+ // provider: a provider-less entry runs as the daemon default, so the
100
+ // default's mode copy is the one that describes it.
82
101
  const switchProvider = entry.provider || null
83
- const switchRegistry = getRegistryForProvider(switchProvider)
84
- ctx.transport.send(ws, { type: 'available_models', models: switchRegistry.getModels(), defaultModel: switchRegistry.getDefaultModelId(), provider: switchProvider })
85
- // #6638: also re-send the permission-mode copy so switching to/from a Codex
86
- // session updates the mode descriptions (Codex has different tools + no plan mode).
87
- ctx.transport.send(ws, { type: 'available_permission_modes', modes: getPermissionModes(switchProvider) })
102
+ const switchRosterProvider = resolveRosterProvider(switchProvider, resolveDaemonDefaultProvider(ctx.services.config))
103
+ const switchRegistry = getRegistryForProvider(switchRosterProvider)
104
+ ctx.transport.send(ws, { type: 'available_models', models: switchRegistry.getModels(), defaultModel: switchRegistry.getDefaultModelId(), provider: switchRosterProvider })
105
+ // #6638/#8224: the permission-mode roster (provider-tuned copy, Plan support)
106
+ // is sent by `sendSessionInfo` above, tagged with the session's provider,
107
+ // because `setActiveSession` made this session the client's active one.
88
108
  broadcastFocusChanged(client, targetId, ctx)
89
109
  }
90
110
 
91
111
  function handleCreateSession(ws, client, msg, ctx) {
112
+ // #7977: an optional client-supplied correlation id, echoed on EVERY reply to
113
+ // this create (success, shell-pending, and each error path). It is the only
114
+ // thing that tells a create reply from the `session_switched` the daemon also
115
+ // sends when it re-homes a client — which never carries one. Absent for old
116
+ // clients; the reply is then byte-identical to before.
117
+ const requestId = (typeof msg.requestId === 'string' && msg.requestId) ? msg.requestId : undefined
118
+ const rid = requestId !== undefined ? { requestId } : {}
119
+ const sendError = (message) => ctx.transport.send(ws, { type: 'session_error', message, ...rid })
120
+ // Principal branch, BEFORE the bound refusal below (a principal carries a
121
+ // sentinel binding, so it would otherwise be refused as a bound client). It
122
+ // never falls into the host path and never touches the active session.
123
+ if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, null)
92
124
  if (client.boundSessionId) {
93
125
  // Enrich the error with the bound session's name so the client can render
94
126
  // a remediation hint ("This device is paired to session X — disconnect to
@@ -104,6 +136,7 @@ function handleCreateSession(ws, client, msg, ctx) {
104
136
  boundSessionId: client.boundSessionId,
105
137
  message: 'Not authorized: client is bound to a specific session',
106
138
  }),
139
+ ...rid,
107
140
  })
108
141
  return
109
142
  }
@@ -111,6 +144,7 @@ function handleCreateSession(ws, client, msg, ctx) {
111
144
  const name = (typeof msg.name === 'string' && msg.name.trim()) ? msg.name.trim() : undefined
112
145
  const cwd = (typeof msg.cwd === 'string' && msg.cwd.trim()) ? msg.cwd.trim() : undefined
113
146
  const provider = (typeof msg.provider === 'string' && msg.provider.trim()) ? msg.provider.trim() : undefined
147
+ const connectionId = (typeof msg.connectionId === 'string' && msg.connectionId.trim()) ? msg.connectionId.trim() : undefined
114
148
  const model = (typeof msg.model === 'string' && msg.model.trim()) ? msg.model.trim() : undefined
115
149
  const rawPermMode = (typeof msg.permissionMode === 'string' && msg.permissionMode.trim()) ? msg.permissionMode.trim() : undefined
116
150
  const permissionMode = rawPermMode && ALLOWED_PERMISSION_MODE_IDS.has(rawPermMode) ? rawPermMode : undefined
@@ -139,14 +173,14 @@ function handleCreateSession(ws, client, msg, ctx) {
139
173
  // from the actual session state (provider capabilities, worktree, sandbox).
140
174
 
141
175
  if (worktree && !cwd) {
142
- sendSessionError(ws, ctx, 'Worktree requires an explicit CWD')
176
+ sendError('Worktree requires an explicit CWD')
143
177
  return
144
178
  }
145
179
 
146
180
  if (cwd) {
147
181
  const cwdError = validateCwdAllowed(cwd, ctx.services.config)
148
182
  if (cwdError) {
149
- sendSessionError(ws, ctx, cwdError)
183
+ sendError(cwdError)
150
184
  return
151
185
  }
152
186
  }
@@ -163,6 +197,7 @@ function handleCreateSession(ws, client, msg, ctx) {
163
197
  type: 'session_error',
164
198
  code: 'PRIMARY_TOKEN_REQUIRED',
165
199
  message: 'A user-shell session requires the primary token. Pairing-issued tokens (paired devices) cannot create a shell.',
200
+ ...rid,
166
201
  })
167
202
  return
168
203
  }
@@ -186,6 +221,7 @@ function handleCreateSession(ws, client, msg, ctx) {
186
221
  type: 'session_error',
187
222
  code: 'CURRENT_TOKEN_REQUIRED',
188
223
  message: 'A user-shell session requires the current token. The token was rotated — reconnect with the new token to open a shell.',
224
+ ...rid,
189
225
  })
190
226
  return
191
227
  }
@@ -195,26 +231,36 @@ function handleCreateSession(ws, client, msg, ctx) {
195
231
  let envOpts = {}
196
232
  if (environmentId) {
197
233
  if (!ctx.services.environmentManager) {
198
- sendSessionError(ws, ctx, 'Environment management is not enabled')
234
+ sendError('Environment management is not enabled')
199
235
  return
200
236
  }
201
237
  try {
202
238
  const info = ctx.services.environmentManager.getContainerInfo(environmentId)
203
239
  envOpts = {
204
240
  provider: 'docker-sdk',
241
+ // #7552: carry the environment ID itself, not only the container it
242
+ // resolves to. SessionManager tags the environment with the new session
243
+ // id (and untags it on teardown), which is what makes the dashboard's
244
+ // "Disconnect all sessions first" destroy guard able to engage at all —
245
+ // before this, `EnvironmentInfo.sessions` was `[]` at runtime forever.
246
+ // Both create paths carry it: the deferred user-shell approval path
247
+ // replays this exact `createOptions` object.
248
+ environmentId,
205
249
  containerId: info.containerId,
206
250
  containerUser: info.containerUser,
207
251
  containerCliPath: info.containerCliPath,
208
252
  }
209
253
  } catch (err) {
210
- sendSessionError(ws, ctx, err.message)
254
+ sendError(err.message)
211
255
  return
212
256
  }
213
257
  }
214
258
 
215
259
  // #6277 — build the create options + audit identity ONCE; both the synchronous
216
260
  // path and the host-approval deferred path replay the identical create.
217
- const createOptions = { name, cwd, provider, model, permissionMode, worktree, sandbox, codexSandbox, skipPermissions, agentCommId, ...envOpts }
261
+ // `requestId` doubles as the naming idempotency key: a retried create (same id) is answered
262
+ // with the same reserved project number instead of burning another one.
263
+ const createOptions = { name, cwd, provider, connectionId, model, permissionMode, worktree, sandbox, codexSandbox, skipPermissions, agentCommId, ...(requestId !== undefined ? { nameIdempotencyKey: requestId } : {}), ...envOpts }
218
264
  const isUserShell = provider === USER_SHELL_PROVIDER
219
265
  // Capture the audit identity at REQUEST time: the deferred (approved) path may
220
266
  // run after the requesting socket is gone, so it can't read a live `client`.
@@ -225,6 +271,7 @@ function handleCreateSession(ws, client, msg, ctx) {
225
271
  tokenClass: client.isPrimaryToken === true ? 'primary' : 'pairing',
226
272
  deviceName: client.deviceInfo?.deviceName,
227
273
  clientId: client.id,
274
+ requestId,
228
275
  }
229
276
 
230
277
  // #6277 — host-local per-spawn approval gate. When `userShell.requireApproval`
@@ -241,7 +288,7 @@ function handleCreateSession(ws, client, msg, ctx) {
241
288
  const store = ctx.services?.shellApprovalStore
242
289
  if (!store) {
243
290
  // Fail-closed: approval is required but the service isn't wired.
244
- sendSessionError(ws, ctx, 'User-shell approval is required but the approval service is unavailable')
291
+ sendError('User-shell approval is required but the approval service is unavailable')
245
292
  return
246
293
  }
247
294
  const { approvalId } = store.createPendingApproval({
@@ -250,9 +297,10 @@ function handleCreateSession(ws, client, msg, ctx) {
250
297
  tokenClass: audit.tokenClass,
251
298
  deviceName: audit.deviceName,
252
299
  hint: cwd || name || null,
300
+ requestId,
253
301
  })
254
302
  log.warn(`[shell-approval] user-shell spawn HELD pending host approval — id=${approvalId} client=${client.id} cwd=${cwd || '(default)'} device=${audit.deviceName || '(unknown)'}. Approve on the host with: chroxy shell approve ${approvalId}`)
255
- ctx.transport.send(ws, { type: 'shell_pending_approval', approvalId, hint: cwd || name || undefined })
303
+ ctx.transport.send(ws, { type: 'shell_pending_approval', approvalId, hint: cwd || name || undefined, ...rid })
256
304
  return
257
305
  }
258
306
 
@@ -262,7 +310,7 @@ function handleCreateSession(ws, client, msg, ctx) {
262
310
  // Surface error code (e.g. PROVIDER_BINARY_NOT_FOUND,
263
311
  // PROVIDER_CREDENTIAL_MISSING) so the client can render an actionable
264
312
  // hint instead of an opaque message. See #2962.
265
- const payload = { type: 'session_error', message: err.message }
313
+ const payload = { type: 'session_error', message: err.message, ...rid }
266
314
  if (err.code) payload.code = err.code
267
315
  ctx.transport.send(ws, payload)
268
316
  }
@@ -313,7 +361,17 @@ export function finalizeShellCreate(ws, client, createOptions, ctx, audit) {
313
361
  // confirmation so the client can show the "repo preset applied" badge and
314
362
  // stage the seed EDITABLE into the composer (never auto-sent). The preamble
315
363
  // TEXT never crosses the wire — only its length + seed + trust metadata.
316
- const sessionSwitched = { type: 'session_switched', sessionId, name: entry.name, cwd: entry.cwd, conversationId: entry.session.resumeSessionId || null }
364
+ const sessionSwitched = {
365
+ type: 'session_switched',
366
+ sessionId,
367
+ name: entry.name,
368
+ cwd: entry.cwd,
369
+ conversationId: entry.session.resumeSessionId || null,
370
+ agentConnection: entry.agentConnection,
371
+ }
372
+ // #7977: echo the create's correlation id. Only this create-confirm carries
373
+ // one; every re-home/switch `session_switched` stays id-less by construction.
374
+ if (audit.requestId) sessionSwitched.requestId = audit.requestId
317
375
  const preset = typeof ctx.sessions.sessionManager.getSessionPreset === 'function'
318
376
  ? ctx.sessions.sessionManager.getSessionPreset(sessionId)
319
377
  : null
@@ -329,6 +387,8 @@ export function finalizeShellCreate(ws, client, createOptions, ctx, audit) {
329
387
  }
330
388
 
331
389
  async function handleDestroySession(ws, client, msg, ctx) {
390
+ // Principal branch: the target resolves through principalMaySee, never the host path.
391
+ if (isPrincipalClient(client)) return refusePrincipalHandler(ws, client, msg, ctx, 'drive')
332
392
  const targetId = msg.sessionId
333
393
 
334
394
  if (client.boundSessionId && client.boundSessionId !== targetId) {
@@ -378,7 +438,7 @@ async function handleDestroySession(ws, client, msg, ctx) {
378
438
  }
379
439
 
380
440
  if (typeof ctx.sessions.sessionManager.destroySessionLocked === 'function') {
381
- await ctx.sessions.sessionManager.destroySessionLocked(targetId)
441
+ await ctx.sessions.sessionManager.destroySessionLocked(targetId, { isAuthorized: authorizedFor(ctx, client) })
382
442
  } else {
383
443
  ctx.sessions.sessionManager.destroySession(targetId)
384
444
  }
@@ -389,6 +449,18 @@ async function handleDestroySession(ws, client, msg, ctx) {
389
449
  // #5563: index-maintaining helpers — unsubscribe every client from the
390
450
  // destroyed session, and re-home any client that was actively viewing it.
391
451
  ctx.transport.unsubscribeClient(c, targetId)
452
+ // A session-bound client is scoped to its bound session and is never moved
453
+ // onto another one: it keeps its unsubscribe and the `session_destroyed`
454
+ // broadcast below, but gets no `session_switched`, session info, replay or
455
+ // focus change for `firstId`. Same rule as the checkpoint-restore re-home
456
+ // (checkpoint-handlers.js, #5700), which also leaves `activeSessionId` as is.
457
+ if (isBoundClient(c)) {
458
+ // The one session a bound client may be active on is gone: clear it so the
459
+ // client is left on no session rather than on (and indexed under) a
460
+ // destroyed one. A client bound to a different session is untouched.
461
+ if (c.boundSessionId === targetId) ctx.transport.setActiveSession(c, null)
462
+ continue
463
+ }
392
464
  if (c.authenticated && c.activeSessionId === targetId) {
393
465
  ctx.transport.setActiveSession(c, firstId)
394
466
  const entry = ctx.sessions.sessionManager.getSession(firstId)
@@ -431,7 +503,7 @@ function handleRenameSession(ws, client, msg, ctx) {
431
503
  }
432
504
 
433
505
  const doRename = typeof ctx.sessions.sessionManager.renameSessionLocked === 'function'
434
- ? () => ctx.sessions.sessionManager.renameSessionLocked(targetId, newName)
506
+ ? () => ctx.sessions.sessionManager.renameSessionLocked(targetId, newName, { isAuthorized: authorizedFor(ctx, client) })
435
507
  : async () => ctx.sessions.sessionManager.renameSession(targetId, newName)
436
508
 
437
509
  doRename().then(success => {
@@ -651,6 +723,457 @@ function handleClaimPrimary(ws, client, msg, ctx) {
651
723
  })
652
724
  }
653
725
 
726
+ /**
727
+ * #7625 — the parked failed-restore roster.
728
+ *
729
+ * REFUSES pairing-bound clients, matching `list_environments` (#7596) rather
730
+ * than redacting. Each row carries `cwd` (an absolute host path) plus the
731
+ * provider and error detail for a session the bound token is not scoped to,
732
+ * and a bound token learns nothing host-level. The roster is also, literally,
733
+ * a list of sibling sessions — the thing the bearer-token doc forbids a bound
734
+ * token from enumerating.
735
+ *
736
+ * The gate runs FIRST, before any SessionManager lookup, so the refusal cannot
737
+ * be used to distinguish "there are failed restores" from "there are none".
738
+ */
739
+ function handleListFailedRestores(ws, client, _msg, ctx) {
740
+ if (isBoundClient(client)) {
741
+ // A DEGRADED snapshot of this survey's own type, not a session_error —
742
+ // the §4 survey shape. `session_error` also carries no `code` field, so a
743
+ // refusal sent that way could not name the reason at all.
744
+ ctx.transport.send(ws, {
745
+ type: 'failed_restores_list',
746
+ generatedAt: new Date().toISOString(),
747
+ restores: [],
748
+ refused: true,
749
+ code: 'FAILED_RESTORES_LIST_FORBIDDEN_BOUND_CLIENT',
750
+ })
751
+ return
752
+ }
753
+ const sm = ctx.sessions.sessionManager
754
+ const restores = typeof sm.getFailedRestores === 'function' ? sm.getFailedRestores() : []
755
+ ctx.transport.send(ws, { type: 'failed_restores_list', generatedAt: new Date().toISOString(), restores })
756
+ }
757
+
758
+ /**
759
+ * #7625 — retry one parked failed restore.
760
+ *
761
+ * AUTHORITY: the UNBOUND bar, not strict primary. Per the bearer-token doc's §9
762
+ * step 4 the question is "can a caller choose a binary, argv, or environment
763
+ * this daemon will spawn?" — and here it cannot: the only caller-supplied value
764
+ * is a sessionId, while the provider, cwd, model and every spawn input come
765
+ * from the entry the daemon itself persisted. That makes this
766
+ * `destroy_environment` (acts on state that already exists) rather than
767
+ * `create_environment` (caller-chooses cwd/name/limits, hence strict primary).
768
+ * The daemon already performs exactly this restore at every boot with no token
769
+ * involved at all.
770
+ *
771
+ * Bound clients are refused before the lookup, for the same existence-oracle
772
+ * reason as the list above. The user-shell refusal lives in SessionManager, so
773
+ * it covers callers other than this handler.
774
+ */
775
+ async function handleRetryFailedRestore(ws, client, msg, ctx) {
776
+ const sessionId = typeof msg?.sessionId === 'string' ? msg.sessionId : ''
777
+ if (isBoundClient(client)) {
778
+ // Refused BEFORE the sessionId is even validated, let alone looked up, so
779
+ // the reply cannot distinguish a real parked id from a fabricated one.
780
+ ctx.transport.send(ws, {
781
+ type: 'retry_failed_restore_result',
782
+ sessionId,
783
+ ok: false,
784
+ code: 'RETRY_FAILED_RESTORE_FORBIDDEN_BOUND_CLIENT',
785
+ message: 'Pairing-issued session tokens cannot retry a failed restore — this requires a host-level (unbound) client, such as the primary token.',
786
+ })
787
+ return
788
+ }
789
+ if (!sessionId) {
790
+ ctx.transport.send(ws, {
791
+ type: 'retry_failed_restore_result',
792
+ sessionId: '',
793
+ ok: false,
794
+ code: 'RETRY_FAILED_RESTORE_INVALID',
795
+ message: 'retry_failed_restore requires a sessionId',
796
+ })
797
+ return
798
+ }
799
+
800
+ const result = await ctx.sessions.sessionManager.retryFailedRestore(sessionId, { isAuthorized: authorizedFor(ctx, client) })
801
+
802
+ if (result.ok) {
803
+ // The retried session is live again, so it now belongs in session_list.
804
+ // Nothing broadcasts that on its own — createSession does not emit a list
805
+ // — so every sibling flow (create/destroy/rename) calls this explicitly and
806
+ // so must this one, or other connected clients keep showing it as failed.
807
+ ctx.transport.broadcastSessionList()
808
+ log.info(`Retry of failed restore ${sessionId} succeeded`)
809
+ }
810
+
811
+ ctx.transport.send(ws, {
812
+ // The id the manager actually restored, which is NOT always the one asked
813
+ // for: createSession falls back to a random id when preserveId is malformed
814
+ // or collides, so echoing the request would leave the client unable to find
815
+ // the session it just recovered (Copilot, #7630 review). The same holds for
816
+ // a retry whose provider start() rejected (#8861): the session is re-parked
817
+ // under the id createSession used. Falls back to the requested id on the
818
+ // other failure arms, where nothing was created.
819
+ sessionId: typeof result.sessionId === 'string' && result.sessionId ? result.sessionId : sessionId,
820
+ type: 'retry_failed_restore_result',
821
+ ok: result.ok === true,
822
+ ...(result.ok ? {} : { code: result.code, message: result.message }),
823
+ })
824
+ }
825
+
826
+ /**
827
+ * #8860 — read one page of a parked failed restore's preserved history.
828
+ *
829
+ * READ-ONLY and no new authority: the native-resume contract is untouched (this
830
+ * resumes, rebuilds and creates nothing). It exists because a session parked
831
+ * for a missing native locator can never be restored and the roster publishes
832
+ * only a count.
833
+ *
834
+ * AUTHORITY: at least as strict as `list_failed_restores` — it REFUSES
835
+ * pairing-bound clients, never redacts. The history is transcript content
836
+ * (prompts, tool inputs, tool output) of a session the bound token is not
837
+ * scoped to, which is strictly more sensitive than the roster's `cwd`. The gate
838
+ * runs FIRST, before the sessionId is validated or any SessionManager lookup,
839
+ * so the refusal cannot tell a real parked id from a fabricated one. The reply
840
+ * is a degraded, schema-valid `failed_restore_history` (`ok: false, refused:
841
+ * true, code`), not a `session_error`, so the caller never waits on a reply
842
+ * that never comes.
843
+ */
844
+ function handleGetFailedRestoreHistory(ws, client, msg, ctx) {
845
+ const sessionId = typeof msg?.sessionId === 'string' ? msg.sessionId : ''
846
+ if (isBoundClient(client)) {
847
+ ctx.transport.send(ws, {
848
+ type: 'failed_restore_history',
849
+ sessionId,
850
+ ok: false,
851
+ refused: true,
852
+ code: 'FAILED_RESTORE_HISTORY_FORBIDDEN_BOUND_CLIENT',
853
+ message: "Pairing-issued session tokens cannot read a failed restore's history — this requires a host-level (unbound) client, such as the primary token.",
854
+ })
855
+ return
856
+ }
857
+ if (!sessionId) {
858
+ ctx.transport.send(ws, {
859
+ type: 'failed_restore_history',
860
+ sessionId: '',
861
+ ok: false,
862
+ code: 'FAILED_RESTORE_HISTORY_INVALID',
863
+ message: 'get_failed_restore_history requires a sessionId',
864
+ })
865
+ return
866
+ }
867
+ const sm = ctx.sessions.sessionManager
868
+ const result = typeof sm.getFailedRestoreHistory === 'function'
869
+ ? sm.getFailedRestoreHistory(sessionId, { offset: msg.offset, limit: msg.limit })
870
+ : { ok: false, code: 'FAILED_RESTORE_NOT_FOUND', message: `No failed-restore entry for session ${sessionId}` }
871
+ ctx.transport.send(ws, { type: 'failed_restore_history', sessionId, ...result })
872
+ }
873
+
874
+ const ARCHIVE_FORBIDDEN_MESSAGE = 'Pairing-issued session tokens cannot read or delete archived sessions — this requires a host-level (unbound) client, such as the primary token.'
875
+ // Matches the protocol's archiveId bound (client.ts); the manager's own check
876
+ // (32 lowercase hex AND present in the index) is the real gate.
877
+ const ARCHIVE_ID_MAX_CHARS = 256
878
+ // JSON budget for the rows of one archived_sessions_list frame.
879
+ const ARCHIVE_LIST_MAX_BYTES = 512 * 1024
880
+
881
+ /**
882
+ * Provider-neutral session archive — the roster of archived sessions.
883
+ *
884
+ * READ-ONLY. AUTHORITY: at least as strict as `get_failed_restore_history`: the
885
+ * rows name sessions (cwd, provider, name) the bound token is not scoped to, so
886
+ * pairing-bound clients are REFUSED, never redacted, with a degraded
887
+ * schema-valid `archived_sessions_list` (`refused: true, code`) so the caller
888
+ * never waits on a reply that never comes. The gate runs FIRST.
889
+ */
890
+ function handleListArchivedSessions(ws, client, _msg, ctx) {
891
+ if (isBoundClient(client)) {
892
+ ctx.transport.send(ws, {
893
+ type: 'archived_sessions_list',
894
+ generatedAt: new Date().toISOString(),
895
+ policy: { enabled: false, maxEntries: 0, maxAgeDays: 0, maxMegabytes: 0 },
896
+ sessions: [],
897
+ refused: true,
898
+ code: 'ARCHIVED_SESSIONS_LIST_FORBIDDEN_BOUND_CLIENT',
899
+ })
900
+ return
901
+ }
902
+ const sm = ctx.sessions.sessionManager
903
+ const { policy, sessions } = typeof sm.listArchivedSessions === 'function'
904
+ ? sm.listArchivedSessions()
905
+ : { policy: { enabled: false, maxEntries: 0, maxAgeDays: 0, maxMegabytes: 0 }, sessions: [] }
906
+ // The roster is ONE frame: send the newest rows that fit a byte budget (the
907
+ // rows arrive newest-first) and say so when the rest were cut.
908
+ const kept = []
909
+ let bytes = 0
910
+ let truncated = false
911
+ for (const row of sessions) {
912
+ const size = Buffer.byteLength(JSON.stringify(row)) + 1
913
+ if (bytes + size > ARCHIVE_LIST_MAX_BYTES && kept.length > 0) { truncated = true; break }
914
+ kept.push(row)
915
+ bytes += size
916
+ }
917
+ ctx.transport.send(ws, {
918
+ type: 'archived_sessions_list',
919
+ generatedAt: new Date().toISOString(),
920
+ policy,
921
+ sessions: kept,
922
+ ...(truncated ? { truncated: true } : {}),
923
+ })
924
+ }
925
+
926
+ /**
927
+ * Provider-neutral session archive — read one page of an archived session's
928
+ * history. READ-ONLY. Refuses pairing-bound clients FIRST, before the archiveId
929
+ * is validated or looked up (no existence oracle), with a degraded schema-valid
930
+ * `archived_session_history` (`ok: false, refused: true, code`).
931
+ */
932
+ async function handleGetArchivedSessionHistory(ws, client, msg, ctx) {
933
+ const archiveId = typeof msg?.archiveId === 'string' ? msg.archiveId.slice(0, ARCHIVE_ID_MAX_CHARS) : ''
934
+ if (isBoundClient(client)) {
935
+ ctx.transport.send(ws, {
936
+ type: 'archived_session_history',
937
+ archiveId,
938
+ ok: false,
939
+ refused: true,
940
+ code: 'ARCHIVED_SESSION_FORBIDDEN_BOUND_CLIENT',
941
+ message: ARCHIVE_FORBIDDEN_MESSAGE,
942
+ })
943
+ return
944
+ }
945
+ if (!archiveId) {
946
+ ctx.transport.send(ws, {
947
+ type: 'archived_session_history',
948
+ archiveId: '',
949
+ ok: false,
950
+ code: 'ARCHIVED_SESSION_INVALID',
951
+ message: 'get_archived_session_history requires an archiveId',
952
+ })
953
+ return
954
+ }
955
+ const sm = ctx.sessions.sessionManager
956
+ const result = typeof sm.getArchivedSessionHistory === 'function'
957
+ ? await sm.getArchivedSessionHistory(archiveId, { offset: msg.offset, limit: msg.limit })
958
+ : { ok: false, code: 'ARCHIVED_SESSION_NOT_FOUND', message: 'No archived session with that id' }
959
+ ctx.transport.send(ws, { type: 'archived_session_history', archiveId, ...result })
960
+ }
961
+
962
+ /**
963
+ * Provider-neutral session archive — delete one archive record (`archiveId`) or
964
+ * all of them (`all: true`). Removes only archive records: it touches no live
965
+ * session and no failed restore. Refuses pairing-bound clients FIRST with a
966
+ * degraded schema-valid `delete_archived_session_result`. Exactly one of
967
+ * `archiveId` / `all: true` is required (the protocol schema enforces it; this
968
+ * re-checks because the handler is the enforcement point for a message that
969
+ * bypassed schema validation).
970
+ */
971
+ function handleDeleteArchivedSession(ws, client, msg, ctx) {
972
+ const archiveId = typeof msg?.archiveId === 'string' ? msg.archiveId.slice(0, ARCHIVE_ID_MAX_CHARS) : ''
973
+ if (isBoundClient(client)) {
974
+ ctx.transport.send(ws, {
975
+ type: 'delete_archived_session_result',
976
+ ok: false,
977
+ deleted: 0,
978
+ ...(archiveId ? { archiveId } : {}),
979
+ refused: true,
980
+ code: 'ARCHIVED_SESSION_FORBIDDEN_BOUND_CLIENT',
981
+ message: ARCHIVE_FORBIDDEN_MESSAGE,
982
+ })
983
+ return
984
+ }
985
+ const all = msg?.all === true
986
+ if ((archiveId !== '') === all) {
987
+ ctx.transport.send(ws, {
988
+ type: 'delete_archived_session_result',
989
+ ok: false,
990
+ deleted: 0,
991
+ code: 'ARCHIVED_SESSION_INVALID',
992
+ message: 'delete_archived_session requires exactly one of archiveId or all: true',
993
+ })
994
+ return
995
+ }
996
+ const sm = ctx.sessions.sessionManager
997
+ if (all) {
998
+ const { deleted, failed } = typeof sm.deleteAllArchivedSessions === 'function'
999
+ ? sm.deleteAllArchivedSessions()
1000
+ : { deleted: 0, failed: 0 }
1001
+ log.info(`Deleted ${deleted} archived session(s)${failed > 0 ? ` (${failed} could not be removed)` : ''}`)
1002
+ // A partial delete is NOT a success: some transcripts are still on disk, and
1003
+ // the reply says so (with the count that did go) rather than claiming ok.
1004
+ ctx.transport.send(ws, failed > 0
1005
+ ? {
1006
+ type: 'delete_archived_session_result',
1007
+ ok: false,
1008
+ deleted,
1009
+ code: 'ARCHIVED_SESSIONS_DELETE_PARTIAL',
1010
+ message: `Deleted ${deleted} archived session(s), but ${failed} could not be removed and are still on disk`,
1011
+ }
1012
+ : { type: 'delete_archived_session_result', ok: true, deleted })
1013
+ return
1014
+ }
1015
+ const outcome = typeof sm.deleteArchivedSession === 'function' ? sm.deleteArchivedSession(archiveId) : 'not_found'
1016
+ if (outcome === 'deleted') {
1017
+ log.info('Deleted an archived session')
1018
+ ctx.transport.send(ws, { type: 'delete_archived_session_result', ok: true, deleted: 1, archiveId })
1019
+ return
1020
+ }
1021
+ ctx.transport.send(ws, outcome === 'failed'
1022
+ ? {
1023
+ type: 'delete_archived_session_result',
1024
+ ok: false,
1025
+ deleted: 0,
1026
+ archiveId,
1027
+ code: 'ARCHIVED_SESSION_DELETE_FAILED',
1028
+ message: 'The archived session could not be removed and is still on disk',
1029
+ }
1030
+ : {
1031
+ type: 'delete_archived_session_result',
1032
+ ok: false,
1033
+ deleted: 0,
1034
+ archiveId,
1035
+ code: 'ARCHIVED_SESSION_NOT_FOUND',
1036
+ message: 'No archived session with that id',
1037
+ })
1038
+ }
1039
+
1040
+ /**
1041
+ * #8866 — continue an archived session, because the user asked to: `mode:
1042
+ * 'native'` resumes the same conversation (the boot / retry recipe) and the
1043
+ * record leaves the archive; `mode: 'new_thread'` starts a NEW session in the
1044
+ * archived directory that carries the archived transcript with its first
1045
+ * message, and the record stays. Nothing restores unless this message arrives;
1046
+ * viewing an archived session stays read-only.
1047
+ *
1048
+ * AUTHORITY: the UNBOUND bar, the same as `retry_failed_restore` and the other
1049
+ * archive messages, and for the same reason: the caller supplies only an
1050
+ * archiveId and a mode, and every spawn input (provider, cwd, model, container
1051
+ * binding) comes from the record the daemon wrote itself. A bound client is
1052
+ * refused FIRST, before the archiveId is validated or looked up (no existence
1053
+ * oracle), with a degraded schema-valid `restore_archived_session_result`
1054
+ * (`refused: true`).
1055
+ */
1056
+ async function handleRestoreArchivedSession(ws, client, msg, ctx) {
1057
+ const archiveId = typeof msg?.archiveId === 'string' ? msg.archiveId.slice(0, ARCHIVE_ID_MAX_CHARS) : ''
1058
+ const mode = msg?.mode === 'native' || msg?.mode === 'new_thread' ? msg.mode : undefined
1059
+ const reply = (body) => ctx.transport.send(ws, {
1060
+ type: 'restore_archived_session_result',
1061
+ archiveId,
1062
+ ...(mode ? { mode } : {}),
1063
+ ...body,
1064
+ })
1065
+ if (isBoundClient(client)) {
1066
+ reply({
1067
+ ok: false,
1068
+ refused: true,
1069
+ code: 'ARCHIVED_SESSION_FORBIDDEN_BOUND_CLIENT',
1070
+ message: 'Pairing-issued session tokens cannot restore archived sessions — this requires a host-level (unbound) client, such as the primary token.',
1071
+ })
1072
+ return
1073
+ }
1074
+ if (!archiveId || !mode) {
1075
+ reply({
1076
+ ok: false,
1077
+ code: 'ARCHIVED_SESSION_INVALID',
1078
+ message: 'restore_archived_session requires an archiveId and a mode of "native" or "new_thread"',
1079
+ })
1080
+ return
1081
+ }
1082
+ const sm = ctx.sessions.sessionManager
1083
+ const result = typeof sm.restoreArchivedSession === 'function'
1084
+ ? await sm.restoreArchivedSession(archiveId, mode, { isAuthorized: authorizedFor(ctx, client) })
1085
+ : { ok: false, mode, code: 'ARCHIVED_SESSION_NOT_FOUND', message: 'No archived session with that id' }
1086
+ if (result.ok || result.sessionId) {
1087
+ // A live session (or a re-parked one) now exists that no client has been
1088
+ // told about: createSession does not announce itself.
1089
+ ctx.transport.broadcastSessionList()
1090
+ }
1091
+ log.info(`Restore of an archived session (${mode}) ${result.ok ? 'succeeded' : `refused (${result.code})`}`)
1092
+ const { mode: _mode, ...rest } = result
1093
+ reply(rest)
1094
+ }
1095
+
1096
+ /**
1097
+ * Dashboard Settings → Session archive (#8869): replace the retention policy of
1098
+ * the running daemon and persist it to config. UNBOUND-ONLY, the same bar as
1099
+ * `delete_archived_session` (which can already delete every record): a
1100
+ * pairing-bound client is refused FIRST (before validation, so the refusal says nothing about
1101
+ * the policy) with a degraded schema-valid `session_archive_policy_result`.
1102
+ *
1103
+ * Order: validate (the config validator's rules; an over-max `maxEntries` is
1104
+ * rejected, not clamped; `purge` needs `enabled: false`) -> persist -> apply to
1105
+ * the running archive (retention re-runs) and the in-memory config -> optional
1106
+ * purge. A persist failure applies NOTHING. A partial purge is ok:false but the
1107
+ * policy change stood, so the reply still carries `policy`.
1108
+ */
1109
+ function handleSetSessionArchivePolicy(ws, client, msg, ctx) {
1110
+ const requestId = typeof msg?.requestId === 'string' ? { requestId: msg.requestId } : {}
1111
+ const reply = (body) => ctx.transport.send(ws, { type: 'session_archive_policy_result', ...body, ...requestId })
1112
+ if (isBoundClient(client)) {
1113
+ reply({
1114
+ ok: false,
1115
+ refused: true,
1116
+ code: 'SESSION_ARCHIVE_POLICY_FORBIDDEN_BOUND_CLIENT',
1117
+ message: 'Pairing-issued session tokens cannot change the session archive policy — this requires a host-level (unbound) client, such as the primary token.',
1118
+ })
1119
+ return
1120
+ }
1121
+ const policy = {
1122
+ enabled: msg?.enabled,
1123
+ maxEntries: msg?.maxEntries,
1124
+ maxAgeDays: msg?.maxAgeDays,
1125
+ maxMegabytes: msg?.maxMegabytes,
1126
+ }
1127
+ const problem = validateSessionArchivePolicy(policy)
1128
+ if (problem) {
1129
+ reply({ ok: false, code: 'SESSION_ARCHIVE_POLICY_INVALID', message: problem.message })
1130
+ return
1131
+ }
1132
+ const purge = msg?.purge === true
1133
+ if (msg?.purge !== undefined && typeof msg.purge !== 'boolean') {
1134
+ reply({ ok: false, code: 'SESSION_ARCHIVE_POLICY_INVALID', message: 'purge: expected boolean' })
1135
+ return
1136
+ }
1137
+ if (purge && policy.enabled !== false) {
1138
+ reply({ ok: false, code: 'SESSION_ARCHIVE_POLICY_INVALID', message: 'purge: deleting all archives is only valid when archiving is turned off (enabled: false)' })
1139
+ return
1140
+ }
1141
+ try {
1142
+ writeSessionArchiveToConfig(policy)
1143
+ } catch (err) {
1144
+ log.error(`Failed to persist sessionArchive policy: ${getErrorMessage(err)}`)
1145
+ reply({ ok: false, code: 'SESSION_ARCHIVE_POLICY_PERSIST_FAILED', message: `Could not save the archive policy to config, so nothing was changed: ${getErrorMessage(err)}` })
1146
+ return
1147
+ }
1148
+ const sm = ctx.sessions.sessionManager
1149
+ const applied = (typeof sm.setArchiveRetentionPolicy === 'function' ? sm.setArchiveRetentionPolicy(policy) : null) || policy
1150
+ const config = ctx?.services?.config
1151
+ if (config && typeof config === 'object') {
1152
+ const existing = config.sessionArchive && typeof config.sessionArchive === 'object' && !Array.isArray(config.sessionArchive) ? config.sessionArchive : {}
1153
+ config.sessionArchive = { ...existing, ...policy }
1154
+ }
1155
+ log.info(`Session archive policy set by the primary client: enabled=${applied.enabled} maxEntries=${applied.maxEntries} maxAgeDays=${applied.maxAgeDays} maxMegabytes=${applied.maxMegabytes}${purge ? ' (purging existing archives)' : ''}`)
1156
+ if (!purge) {
1157
+ reply({ ok: true, policy: applied })
1158
+ return
1159
+ }
1160
+ const { deleted, failed } = typeof sm.deleteAllArchivedSessions === 'function'
1161
+ ? sm.deleteAllArchivedSessions()
1162
+ : { deleted: 0, failed: 0 }
1163
+ log.info(`Deleted ${deleted} archived session(s) while turning archiving off${failed > 0 ? ` (${failed} could not be removed)` : ''}`)
1164
+ if (failed > 0) {
1165
+ reply({
1166
+ ok: false,
1167
+ policy: applied,
1168
+ deleted,
1169
+ code: 'SESSION_ARCHIVE_PURGE_PARTIAL',
1170
+ message: `Archiving is turned off, but only ${deleted} archived session(s) were deleted; ${failed} could not be removed and are still on disk`,
1171
+ })
1172
+ return
1173
+ }
1174
+ reply({ ok: true, policy: applied, deleted })
1175
+ }
1176
+
654
1177
  export const sessionHandlers = {
655
1178
  list_sessions: handleListSessions,
656
1179
  switch_session: handleSwitchSession,
@@ -665,4 +1188,12 @@ export const sessionHandlers = {
665
1188
  terminal_resync: handleTerminalResync,
666
1189
  client_visible: handleClientVisible,
667
1190
  claim_primary: handleClaimPrimary,
1191
+ list_failed_restores: handleListFailedRestores,
1192
+ retry_failed_restore: handleRetryFailedRestore,
1193
+ get_failed_restore_history: handleGetFailedRestoreHistory,
1194
+ list_archived_sessions: handleListArchivedSessions,
1195
+ get_archived_session_history: handleGetArchivedSessionHistory,
1196
+ delete_archived_session: handleDeleteArchivedSession,
1197
+ restore_archived_session: handleRestoreArchivedSession,
1198
+ set_session_archive_policy: handleSetSessionArchivePolicy,
668
1199
  }