@chroxy/server 0.11.0 → 0.11.10

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