@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -5,17 +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
11
  import { validateCwdAllowed, broadcastFocusChanged, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError, isSessionViewer, isUserShellSession, ALLOWED_PERMISSION_MODE_IDS } from '../handler-utils.js'
10
- import { getRegistryForProvider } from '../models.js'
11
- import { isUserShellEnabled, isUserShellApprovalRequired } from '../config.js'
12
+ import { getRegistryForProvider, resolveRosterProvider } from '../models.js'
13
+ import { resolveDaemonDefaultProvider } from '../providers.js'
14
+ import { CODEX_SANDBOX_MODES } from '../codex-session.js'
15
+ import { isUserShellEnabled, isUserShellApprovalRequired, validateSessionArchivePolicy, writeSessionArchiveToConfig } from '../config.js'
16
+ import { getErrorMessage } from '../utils/error-message.js'
12
17
  import { createLogger, loggerForSession } from '../logger.js'
13
18
 
14
19
  const log = createLogger('ws')
15
20
 
16
21
  function handleListSessions(ws, client, _msg, ctx) {
17
22
  let sessions = ctx.sessions.sessionManager.listSessions()
18
- if (client.boundSessionId) {
23
+ if (isBoundClient(client)) {
19
24
  sessions = sessions.filter(s => s.sessionId === client.boundSessionId)
20
25
  }
21
26
  ctx.transport.send(ws, { type: 'session_list', sessions })
@@ -78,13 +83,39 @@ function handleSwitchSession(ws, client, msg, ctx) {
78
83
  // Re-send provider-scoped available_models so clients that switch from a
79
84
  // Claude session to a Codex/Gemini session (or vice-versa) update their
80
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.
81
100
  const switchProvider = entry.provider || null
82
- const switchRegistry = getRegistryForProvider(switchProvider)
83
- ctx.transport.send(ws, { type: 'available_models', models: switchRegistry.getModels(), defaultModel: switchRegistry.getDefaultModelId(), provider: 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.
84
107
  broadcastFocusChanged(client, targetId, ctx)
85
108
  }
86
109
 
87
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 })
88
119
  if (client.boundSessionId) {
89
120
  // Enrich the error with the bound session's name so the client can render
90
121
  // a remediation hint ("This device is paired to session X — disconnect to
@@ -100,6 +131,7 @@ function handleCreateSession(ws, client, msg, ctx) {
100
131
  boundSessionId: client.boundSessionId,
101
132
  message: 'Not authorized: client is bound to a specific session',
102
133
  }),
134
+ ...rid,
103
135
  })
104
136
  return
105
137
  }
@@ -107,11 +139,16 @@ function handleCreateSession(ws, client, msg, ctx) {
107
139
  const name = (typeof msg.name === 'string' && msg.name.trim()) ? msg.name.trim() : undefined
108
140
  const cwd = (typeof msg.cwd === 'string' && msg.cwd.trim()) ? msg.cwd.trim() : undefined
109
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
110
143
  const model = (typeof msg.model === 'string' && msg.model.trim()) ? msg.model.trim() : undefined
111
144
  const rawPermMode = (typeof msg.permissionMode === 'string' && msg.permissionMode.trim()) ? msg.permissionMode.trim() : undefined
112
145
  const permissionMode = rawPermMode && ALLOWED_PERMISSION_MODE_IDS.has(rawPermMode) ? rawPermMode : undefined
113
146
  const worktree = msg.worktree === true ? true : undefined
114
147
  const sandbox = (msg.sandbox && typeof msg.sandbox === 'object' && !Array.isArray(msg.sandbox)) ? msg.sandbox : undefined
148
+ // #6638: per-session codex sandbox mode. Schema-gated to the valid enum; the
149
+ // guard keeps an unexpected value from reaching the session (→ env/default).
150
+ const rawCodexSandbox = (typeof msg.codexSandbox === 'string' && msg.codexSandbox.trim()) ? msg.codexSandbox.trim() : undefined
151
+ const codexSandbox = rawCodexSandbox && CODEX_SANDBOX_MODES.includes(rawCodexSandbox) ? rawCodexSandbox : undefined
115
152
  const environmentId = (typeof msg.environmentId === 'string' && msg.environmentId.trim()) ? msg.environmentId.trim() : undefined
116
153
  // #4208: opt-in TUI flag — preserve strict booleans so an explicit `false`
117
154
  // can override a server-wide `defaultSkipPermissions: true` on a per-session
@@ -131,14 +168,14 @@ function handleCreateSession(ws, client, msg, ctx) {
131
168
  // from the actual session state (provider capabilities, worktree, sandbox).
132
169
 
133
170
  if (worktree && !cwd) {
134
- sendSessionError(ws, ctx, 'Worktree requires an explicit CWD')
171
+ sendError('Worktree requires an explicit CWD')
135
172
  return
136
173
  }
137
174
 
138
175
  if (cwd) {
139
176
  const cwdError = validateCwdAllowed(cwd, ctx.services.config)
140
177
  if (cwdError) {
141
- sendSessionError(ws, ctx, cwdError)
178
+ sendError(cwdError)
142
179
  return
143
180
  }
144
181
  }
@@ -155,6 +192,7 @@ function handleCreateSession(ws, client, msg, ctx) {
155
192
  type: 'session_error',
156
193
  code: 'PRIMARY_TOKEN_REQUIRED',
157
194
  message: 'A user-shell session requires the primary token. Pairing-issued tokens (paired devices) cannot create a shell.',
195
+ ...rid,
158
196
  })
159
197
  return
160
198
  }
@@ -178,6 +216,7 @@ function handleCreateSession(ws, client, msg, ctx) {
178
216
  type: 'session_error',
179
217
  code: 'CURRENT_TOKEN_REQUIRED',
180
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,
181
220
  })
182
221
  return
183
222
  }
@@ -187,26 +226,34 @@ function handleCreateSession(ws, client, msg, ctx) {
187
226
  let envOpts = {}
188
227
  if (environmentId) {
189
228
  if (!ctx.services.environmentManager) {
190
- sendSessionError(ws, ctx, 'Environment management is not enabled')
229
+ sendError('Environment management is not enabled')
191
230
  return
192
231
  }
193
232
  try {
194
233
  const info = ctx.services.environmentManager.getContainerInfo(environmentId)
195
234
  envOpts = {
196
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,
197
244
  containerId: info.containerId,
198
245
  containerUser: info.containerUser,
199
246
  containerCliPath: info.containerCliPath,
200
247
  }
201
248
  } catch (err) {
202
- sendSessionError(ws, ctx, err.message)
249
+ sendError(err.message)
203
250
  return
204
251
  }
205
252
  }
206
253
 
207
254
  // #6277 — build the create options + audit identity ONCE; both the synchronous
208
255
  // path and the host-approval deferred path replay the identical create.
209
- const createOptions = { name, cwd, provider, model, permissionMode, worktree, sandbox, skipPermissions, agentCommId, ...envOpts }
256
+ const createOptions = { name, cwd, provider, connectionId, model, permissionMode, worktree, sandbox, codexSandbox, skipPermissions, agentCommId, ...envOpts }
210
257
  const isUserShell = provider === USER_SHELL_PROVIDER
211
258
  // Capture the audit identity at REQUEST time: the deferred (approved) path may
212
259
  // run after the requesting socket is gone, so it can't read a live `client`.
@@ -217,6 +264,7 @@ function handleCreateSession(ws, client, msg, ctx) {
217
264
  tokenClass: client.isPrimaryToken === true ? 'primary' : 'pairing',
218
265
  deviceName: client.deviceInfo?.deviceName,
219
266
  clientId: client.id,
267
+ requestId,
220
268
  }
221
269
 
222
270
  // #6277 — host-local per-spawn approval gate. When `userShell.requireApproval`
@@ -233,7 +281,7 @@ function handleCreateSession(ws, client, msg, ctx) {
233
281
  const store = ctx.services?.shellApprovalStore
234
282
  if (!store) {
235
283
  // Fail-closed: approval is required but the service isn't wired.
236
- 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')
237
285
  return
238
286
  }
239
287
  const { approvalId } = store.createPendingApproval({
@@ -242,9 +290,10 @@ function handleCreateSession(ws, client, msg, ctx) {
242
290
  tokenClass: audit.tokenClass,
243
291
  deviceName: audit.deviceName,
244
292
  hint: cwd || name || null,
293
+ requestId,
245
294
  })
246
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}`)
247
- 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 })
248
297
  return
249
298
  }
250
299
 
@@ -254,7 +303,7 @@ function handleCreateSession(ws, client, msg, ctx) {
254
303
  // Surface error code (e.g. PROVIDER_BINARY_NOT_FOUND,
255
304
  // PROVIDER_CREDENTIAL_MISSING) so the client can render an actionable
256
305
  // hint instead of an opaque message. See #2962.
257
- const payload = { type: 'session_error', message: err.message }
306
+ const payload = { type: 'session_error', message: err.message, ...rid }
258
307
  if (err.code) payload.code = err.code
259
308
  ctx.transport.send(ws, payload)
260
309
  }
@@ -305,7 +354,17 @@ export function finalizeShellCreate(ws, client, createOptions, ctx, audit) {
305
354
  // confirmation so the client can show the "repo preset applied" badge and
306
355
  // stage the seed EDITABLE into the composer (never auto-sent). The preamble
307
356
  // TEXT never crosses the wire — only its length + seed + trust metadata.
308
- 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
309
368
  const preset = typeof ctx.sessions.sessionManager.getSessionPreset === 'function'
310
369
  ? ctx.sessions.sessionManager.getSessionPreset(sessionId)
311
370
  : null
@@ -370,7 +429,7 @@ async function handleDestroySession(ws, client, msg, ctx) {
370
429
  }
371
430
 
372
431
  if (typeof ctx.sessions.sessionManager.destroySessionLocked === 'function') {
373
- await ctx.sessions.sessionManager.destroySessionLocked(targetId)
432
+ await ctx.sessions.sessionManager.destroySessionLocked(targetId, { isAuthorized: authorizedFor(ctx, client) })
374
433
  } else {
375
434
  ctx.sessions.sessionManager.destroySession(targetId)
376
435
  }
@@ -381,6 +440,18 @@ async function handleDestroySession(ws, client, msg, ctx) {
381
440
  // #5563: index-maintaining helpers — unsubscribe every client from the
382
441
  // destroyed session, and re-home any client that was actively viewing it.
383
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
+ }
384
455
  if (c.authenticated && c.activeSessionId === targetId) {
385
456
  ctx.transport.setActiveSession(c, firstId)
386
457
  const entry = ctx.sessions.sessionManager.getSession(firstId)
@@ -423,7 +494,7 @@ function handleRenameSession(ws, client, msg, ctx) {
423
494
  }
424
495
 
425
496
  const doRename = typeof ctx.sessions.sessionManager.renameSessionLocked === 'function'
426
- ? () => ctx.sessions.sessionManager.renameSessionLocked(targetId, newName)
497
+ ? () => ctx.sessions.sessionManager.renameSessionLocked(targetId, newName, { isAuthorized: authorizedFor(ctx, client) })
427
498
  : async () => ctx.sessions.sessionManager.renameSession(targetId, newName)
428
499
 
429
500
  doRename().then(success => {
@@ -643,6 +714,457 @@ function handleClaimPrimary(ws, client, msg, ctx) {
643
714
  })
644
715
  }
645
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
+
646
1168
  export const sessionHandlers = {
647
1169
  list_sessions: handleListSessions,
648
1170
  switch_session: handleSwitchSession,
@@ -657,4 +1179,12 @@ export const sessionHandlers = {
657
1179
  terminal_resync: handleTerminalResync,
658
1180
  client_visible: handleClientVisible,
659
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,
660
1190
  }