@chroxy/server 0.10.0

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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,660 @@
1
+ /**
2
+ * Session lifecycle message handlers.
3
+ *
4
+ * Handles: list_sessions, switch_session, create_session, destroy_session,
5
+ * rename_session, subscribe_sessions, unsubscribe_sessions
6
+ */
7
+ import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
8
+ import { auditShellCreate } from '../shell-audit.js'
9
+ 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 { createLogger, loggerForSession } from '../logger.js'
13
+
14
+ const log = createLogger('ws')
15
+
16
+ function handleListSessions(ws, client, _msg, ctx) {
17
+ let sessions = ctx.sessions.sessionManager.listSessions()
18
+ if (client.boundSessionId) {
19
+ sessions = sessions.filter(s => s.sessionId === client.boundSessionId)
20
+ }
21
+ ctx.transport.send(ws, { type: 'session_list', sessions })
22
+ }
23
+
24
+ function handleSwitchSession(ws, client, msg, ctx) {
25
+ const targetId = msg.sessionId
26
+
27
+ if (!targetId) {
28
+ sendSessionError(ws, ctx, 'sessionId is required')
29
+ return
30
+ }
31
+
32
+ // Enforce session token binding: if this client authenticated with a
33
+ // pairing-issued session token that was bound to a specific session,
34
+ // prevent them from switching to any other session.
35
+ if (client.boundSessionId && client.boundSessionId !== targetId) {
36
+ // #4828: session-scoped to the bound session — the binding-mismatch
37
+ // warn belongs to the OWNER of `boundSessionId`, not the request target.
38
+ loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} attempted to switch to session ${targetId} but is bound to ${client.boundSessionId}`)
39
+ ctx.transport.send(ws, {
40
+ type: 'session_error',
41
+ ...buildSessionTokenMismatchPayload({
42
+ sessionManager: ctx.sessions.sessionManager,
43
+ boundSessionId: client.boundSessionId,
44
+ }),
45
+ })
46
+ return
47
+ }
48
+
49
+ const entry = ctx.sessions.sessionManager.getSession(targetId)
50
+ if (!entry) {
51
+ sendSessionError(ws, ctx, `Session not found: ${targetId}`)
52
+ return
53
+ }
54
+ // #5563: route active-session + subscription through the index-maintaining
55
+ // helpers so the sessionId→clients reverse index stays in sync.
56
+ ctx.transport.setActiveSession(client, targetId)
57
+ ctx.transport.subscribeClient(client, targetId)
58
+ // #4835: persist the chosen session for this device so the next reconnect
59
+ // restores it instead of snapping back to defaultSessionId. Bound
60
+ // clients are excluded — their activeSessionId is locked to
61
+ // boundSessionId, so writing it would just churn the file without
62
+ // affecting behaviour. devicePreferences is optional on ctx so tests
63
+ // that don't wire it through (and pre-#4835 callers in general)
64
+ // continue to work.
65
+ if (ctx.services.devicePreferences && !client.boundSessionId && client.deviceInfo?.deviceId) {
66
+ ctx.services.devicePreferences.setActiveSessionId(client.deviceInfo.deviceId, targetId)
67
+ }
68
+ // #4828: session-scoped — the switch is into `targetId`.
69
+ loggerForSession('ws', targetId).info(`Client ${client.id} switched to session ${targetId}`)
70
+ ctx.transport.send(ws, { type: 'session_switched', sessionId: targetId, name: entry.name, cwd: entry.cwd, conversationId: entry.session.resumeSessionId || null })
71
+ ctx.transport.sendSessionInfo(ws, targetId)
72
+ // #5555.3 — forceFull: a session SWITCH gets the authoritative full rebuild,
73
+ // not a cursor delta. Background sessions accumulate live broadcasts in the
74
+ // client's per-session message list while viewed elsewhere, so the replay
75
+ // cursor lags and a delta would re-send/duplicate them. The connect handshake
76
+ // (not this path) is where the cursor delta-replay win applies.
77
+ ctx.transport.replayHistory(ws, targetId, { forceFull: true })
78
+ // Re-send provider-scoped available_models so clients that switch from a
79
+ // Claude session to a Codex/Gemini session (or vice-versa) update their
80
+ // model dropdown immediately (#2956).
81
+ 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 })
84
+ broadcastFocusChanged(client, targetId, ctx)
85
+ }
86
+
87
+ function handleCreateSession(ws, client, msg, ctx) {
88
+ if (client.boundSessionId) {
89
+ // Enrich the error with the bound session's name so the client can render
90
+ // a remediation hint ("This device is paired to session X — disconnect to
91
+ // create new sessions.") rather than an opaque "Not authorized". See #2904.
92
+ // Issue #2912: payload shape is unified across all SESSION_TOKEN_MISMATCH
93
+ // call sites via buildSessionTokenMismatchPayload — every send site produces
94
+ // `{code, message, boundSessionId, boundSessionName}` so clients never see
95
+ // divergent shapes while branching on the code.
96
+ ctx.transport.send(ws, {
97
+ type: 'session_error',
98
+ ...buildSessionTokenMismatchPayload({
99
+ sessionManager: ctx.sessions.sessionManager,
100
+ boundSessionId: client.boundSessionId,
101
+ message: 'Not authorized: client is bound to a specific session',
102
+ }),
103
+ })
104
+ return
105
+ }
106
+
107
+ const name = (typeof msg.name === 'string' && msg.name.trim()) ? msg.name.trim() : undefined
108
+ const cwd = (typeof msg.cwd === 'string' && msg.cwd.trim()) ? msg.cwd.trim() : undefined
109
+ const provider = (typeof msg.provider === 'string' && msg.provider.trim()) ? msg.provider.trim() : undefined
110
+ const model = (typeof msg.model === 'string' && msg.model.trim()) ? msg.model.trim() : undefined
111
+ const rawPermMode = (typeof msg.permissionMode === 'string' && msg.permissionMode.trim()) ? msg.permissionMode.trim() : undefined
112
+ const permissionMode = rawPermMode && ALLOWED_PERMISSION_MODE_IDS.has(rawPermMode) ? rawPermMode : undefined
113
+ const worktree = msg.worktree === true ? true : undefined
114
+ const sandbox = (msg.sandbox && typeof msg.sandbox === 'object' && !Array.isArray(msg.sandbox)) ? msg.sandbox : undefined
115
+ const environmentId = (typeof msg.environmentId === 'string' && msg.environmentId.trim()) ? msg.environmentId.trim() : undefined
116
+ // #4208: opt-in TUI flag — preserve strict booleans so an explicit `false`
117
+ // can override a server-wide `defaultSkipPermissions: true` on a per-session
118
+ // basis. Anything non-boolean (undefined, null, string, etc.) falls through
119
+ // to the SessionManager default rather than overriding it. Server-side this
120
+ // is a no-op for non-TUI providers (ClaudeTuiSession is the only constructor
121
+ // that honours it); we don't gate by provider here — the SessionManager
122
+ // forwards via providerOpts and non-TUI providers ignore the unknown key.
123
+ const skipPermissions = typeof msg.skipPermissions === 'boolean' ? msg.skipPermissions : undefined
124
+ // Mailbox: optional AGENT_COMM_ID to auto-register for this session (#5914
125
+ // follow-up). Trim here; SessionManager.registerAgentCommId (reached via
126
+ // createSession) is the authoritative validator — it re-trims and no-ops on a
127
+ // control-char / over-200-char id, so a bad value silently skips registration
128
+ // rather than failing the create.
129
+ const agentCommId = (typeof msg.agentCommId === 'string' && msg.agentCommId.trim()) ? msg.agentCommId.trim() : undefined
130
+ // Note: isolation is accepted in the schema but always derived server-side
131
+ // from the actual session state (provider capabilities, worktree, sandbox).
132
+
133
+ if (worktree && !cwd) {
134
+ sendSessionError(ws, ctx, 'Worktree requires an explicit CWD')
135
+ return
136
+ }
137
+
138
+ if (cwd) {
139
+ const cwdError = validateCwdAllowed(cwd, ctx.services.config)
140
+ if (cwdError) {
141
+ sendSessionError(ws, ctx, cwdError)
142
+ return
143
+ }
144
+ }
145
+
146
+ // #5985b (epic #5982): a user-shell session spawns the operator's $SHELL
147
+ // (arbitrary host code execution). Require the PRIMARY token class — strictly
148
+ // NOT any pairing-issued token (an unbound linking-mode pairing token is
149
+ // host-authority for ordinary ops but must NOT reach a root shell; swarm-audit
150
+ // finding C1). The `userShell.enabled` flag is separately enforced as the
151
+ // authoritative gate in SessionManager.createSession (covers every spawn
152
+ // path); this is the token-class half, surfaced early with a clean code.
153
+ if (provider === USER_SHELL_PROVIDER && client.isPrimaryToken !== true) {
154
+ ctx.transport.send(ws, {
155
+ type: 'session_error',
156
+ code: 'PRIMARY_TOKEN_REQUIRED',
157
+ message: 'A user-shell session requires the primary token. Pairing-issued tokens (paired devices) cannot create a shell.',
158
+ })
159
+ return
160
+ }
161
+
162
+ // #6004 (epic #5982): require the CURRENT token, not a grace/previous one.
163
+ // After a scheduled rotation the old primary token stays valid through the
164
+ // grace window, and a connection authed with it keeps isPrimaryToken===true —
165
+ // so without this check it could create a NEW user-shell with that grace token,
166
+ // re-establishing shell access the rotation was meant to wind down. (Scheduled
167
+ // rotation keeps live shells; only revoke severs them — and revoke also
168
+ // de-auths the connection, so this gate is specifically the scheduled-rotation
169
+ // residual.) Gate on the connection's auth token still being the current token.
170
+ // Skipped when no TokenManager exists (--no-auth: local trust, the create
171
+ // proceeds). The method guard tolerates test ctx mocks that stub
172
+ // services.tokenManager.
173
+ if (provider === USER_SHELL_PROVIDER) {
174
+ const tokenManager = ctx.services?.tokenManager
175
+ if (tokenManager && typeof tokenManager.isCurrentToken === 'function' &&
176
+ !tokenManager.isCurrentToken(client.authToken)) {
177
+ ctx.transport.send(ws, {
178
+ type: 'session_error',
179
+ code: 'CURRENT_TOKEN_REQUIRED',
180
+ message: 'A user-shell session requires the current token. The token was rotated — reconnect with the new token to open a shell.',
181
+ })
182
+ return
183
+ }
184
+ }
185
+
186
+ // Resolve environment container details if environmentId is specified
187
+ let envOpts = {}
188
+ if (environmentId) {
189
+ if (!ctx.services.environmentManager) {
190
+ sendSessionError(ws, ctx, 'Environment management is not enabled')
191
+ return
192
+ }
193
+ try {
194
+ const info = ctx.services.environmentManager.getContainerInfo(environmentId)
195
+ envOpts = {
196
+ provider: 'docker-sdk',
197
+ containerId: info.containerId,
198
+ containerUser: info.containerUser,
199
+ containerCliPath: info.containerCliPath,
200
+ }
201
+ } catch (err) {
202
+ sendSessionError(ws, ctx, err.message)
203
+ return
204
+ }
205
+ }
206
+
207
+ // #6277 — build the create options + audit identity ONCE; both the synchronous
208
+ // path and the host-approval deferred path replay the identical create.
209
+ const createOptions = { name, cwd, provider, model, permissionMode, worktree, sandbox, skipPermissions, agentCommId, ...envOpts }
210
+ const isUserShell = provider === USER_SHELL_PROVIDER
211
+ // Capture the audit identity at REQUEST time: the deferred (approved) path may
212
+ // run after the requesting socket is gone, so it can't read a live `client`.
213
+ // tokenClass is always 'primary' today — the gate above rejects every
214
+ // non-primary class — but the ternary future-proofs a widened authz.
215
+ const audit = {
216
+ isUserShell,
217
+ tokenClass: client.isPrimaryToken === true ? 'primary' : 'pairing',
218
+ deviceName: client.deviceInfo?.deviceName,
219
+ clientId: client.id,
220
+ }
221
+
222
+ // #6277 — host-local per-spawn approval gate. When `userShell.requireApproval`
223
+ // is on, HOLD the spawn instead of creating it: log a one-time id for the host
224
+ // operator and tell the requester it's pending. The create happens ONLY when
225
+ // the host approves out-of-band (loopback `/api/shell/approve` or
226
+ // `chroxy shell approve <id>`), which replays finalizeShellCreate directly — so
227
+ // this handler is the sole gate and the deferred path never re-enters it.
228
+ // Only HOLD a spawn that would actually be allowed: when userShell.enabled is
229
+ // false the create is rejected upstream by SessionManager anyway, so gating it
230
+ // here would log + hold a doomed approval that 500s on approve (a non-sensical
231
+ // enabled:false + requireApproval:true combo).
232
+ if (isUserShell && isUserShellEnabled(ctx.services?.config) && isUserShellApprovalRequired(ctx.services?.config)) {
233
+ const store = ctx.services?.shellApprovalStore
234
+ if (!store) {
235
+ // 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')
237
+ return
238
+ }
239
+ const { approvalId } = store.createPendingApproval({
240
+ clientId: client.id,
241
+ createSessionOptions: createOptions,
242
+ tokenClass: audit.tokenClass,
243
+ deviceName: audit.deviceName,
244
+ hint: cwd || name || null,
245
+ })
246
+ 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 })
248
+ return
249
+ }
250
+
251
+ try {
252
+ finalizeShellCreate(ws, client, createOptions, ctx, audit)
253
+ } catch (err) {
254
+ // Surface error code (e.g. PROVIDER_BINARY_NOT_FOUND,
255
+ // PROVIDER_CREDENTIAL_MISSING) so the client can render an actionable
256
+ // hint instead of an opaque message. See #2962.
257
+ const payload = { type: 'session_error', message: err.message }
258
+ if (err.code) payload.code = err.code
259
+ ctx.transport.send(ws, payload)
260
+ }
261
+ }
262
+
263
+ /**
264
+ * #6277 — the post-create sequence, shared by the synchronous create path AND
265
+ * the host-approval deferred path. Creates the session exactly once, audits a
266
+ * user-shell spawn, sends the create confirmation to the requester, and
267
+ * broadcasts the new session to everyone else.
268
+ *
269
+ * `ws`/`client` MAY be null: the deferred path runs at approval time, by which
270
+ * point the requesting socket may have disconnected — the create + audit +
271
+ * broadcasts to OTHER clients still complete; only the "notify the requester"
272
+ * steps are skipped. The audit identity is passed in (captured at request time)
273
+ * rather than read off a possibly-gone `client`. Throws on a createSession
274
+ * failure (the caller maps it to a session_error / HTTP 500).
275
+ *
276
+ * @param {WebSocket|null} ws
277
+ * @param {object|null} client
278
+ * @param {object} createOptions - SessionManager.createSession options
279
+ * @param {object} ctx
280
+ * @param {{isUserShell:boolean, tokenClass:string, deviceName?:string, clientId:string}} audit
281
+ * @returns {string} the created sessionId
282
+ */
283
+ export function finalizeShellCreate(ws, client, createOptions, ctx, audit) {
284
+ const sessionId = ctx.sessions.sessionManager.createSession(createOptions)
285
+ // #5563: index-maintaining helpers (skipped if the requester socket is gone).
286
+ if (client) {
287
+ ctx.transport.setActiveSession(client, sessionId)
288
+ ctx.transport.subscribeClient(client, sessionId)
289
+ }
290
+ const entry = ctx.sessions.sessionManager.getSession(sessionId)
291
+ // #5985 audit — a user-shell spawn is host code execution; record who opened
292
+ // it (token class + client id/device), where, and which shell, so shell usage
293
+ // is traceable. The matching destroy entry is emitted by SessionManager.
294
+ if (audit.isUserShell) {
295
+ auditShellCreate({
296
+ sessionId,
297
+ clientId: audit.clientId,
298
+ tokenClass: audit.tokenClass,
299
+ cwd: entry?.cwd,
300
+ shell: entry?.session?._shellPath,
301
+ deviceName: audit.deviceName,
302
+ })
303
+ }
304
+ // #5553: disclose the resolved per-repo session preset on the create
305
+ // confirmation so the client can show the "repo preset applied" badge and
306
+ // stage the seed EDITABLE into the composer (never auto-sent). The preamble
307
+ // 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 }
309
+ const preset = typeof ctx.sessions.sessionManager.getSessionPreset === 'function'
310
+ ? ctx.sessions.sessionManager.getSessionPreset(sessionId)
311
+ : null
312
+ if (preset) sessionSwitched.sessionPreset = preset
313
+ if (ws) {
314
+ ctx.transport.send(ws, sessionSwitched)
315
+ ctx.transport.sendSessionInfo(ws, sessionId)
316
+ }
317
+ ctx.transport.broadcastSessionList()
318
+ autoSubscribeOtherClients(sessionId, ws, ctx)
319
+ if (client) broadcastFocusChanged(client, sessionId, ctx)
320
+ return sessionId
321
+ }
322
+
323
+ async function handleDestroySession(ws, client, msg, ctx) {
324
+ const targetId = msg.sessionId
325
+
326
+ if (client.boundSessionId && client.boundSessionId !== targetId) {
327
+ ctx.transport.send(ws, {
328
+ type: 'session_error',
329
+ ...buildSessionTokenMismatchPayload({
330
+ sessionManager: ctx.sessions.sessionManager,
331
+ boundSessionId: client.boundSessionId,
332
+ }),
333
+ })
334
+ return
335
+ }
336
+
337
+ const targetEntry = ctx.sessions.sessionManager.getSession(targetId)
338
+ if (!targetEntry) {
339
+ sendSessionError(ws, ctx, `Session not found: ${targetId}`)
340
+ return
341
+ }
342
+
343
+ if (ctx.sessions.sessionManager.listSessions().length <= 1) {
344
+ sendSessionError(ws, ctx, 'Cannot destroy the last session')
345
+ return
346
+ }
347
+
348
+ if (ctx.sessions.sessionManager.isSessionLocked?.(targetId)) {
349
+ sendSessionError(ws, ctx, 'Session is being modified by another operation')
350
+ return
351
+ }
352
+
353
+ // #5695: never tear down a session (which also deletes its worktree) while it
354
+ // is actively streaming or has pending background shells — that orphans the
355
+ // in-flight turn and can lose uncommitted worktree work. The CLI won't delete
356
+ // the session you're running in either. Interrupt first, then delete.
357
+ if (targetEntry.session?.isRunning) {
358
+ // #5710: force escape hatch. A wedged session whose `isRunning` is stuck true
359
+ // (a crashed provider that never emits turn-end, or a leaked background-shell
360
+ // tracker entry) could otherwise NEVER be deleted from any client. When the
361
+ // client sends `force: true` (gated behind an explicit "delete anyway?"
362
+ // confirm), bypass the guard and proceed — logged loudly so a forced teardown
363
+ // of a genuinely-running session is auditable.
364
+ if (msg.force === true) {
365
+ log.warn(`Force-destroying session ${targetId} while isRunning=true (client ${client.id}) — bypassing #5695 busy guard`)
366
+ } else {
367
+ sendSessionError(ws, ctx, 'Cannot destroy a session while it is running — interrupt it first, then delete.')
368
+ return
369
+ }
370
+ }
371
+
372
+ if (typeof ctx.sessions.sessionManager.destroySessionLocked === 'function') {
373
+ await ctx.sessions.sessionManager.destroySessionLocked(targetId)
374
+ } else {
375
+ ctx.sessions.sessionManager.destroySession(targetId)
376
+ }
377
+ ctx.transport.clearPrimary(targetId)
378
+
379
+ const firstId = ctx.sessions.sessionManager.firstSessionId
380
+ for (const [clientWs, c] of ctx.transport.clients) {
381
+ // #5563: index-maintaining helpers — unsubscribe every client from the
382
+ // destroyed session, and re-home any client that was actively viewing it.
383
+ ctx.transport.unsubscribeClient(c, targetId)
384
+ if (c.authenticated && c.activeSessionId === targetId) {
385
+ ctx.transport.setActiveSession(c, firstId)
386
+ const entry = ctx.sessions.sessionManager.getSession(firstId)
387
+ if (entry) {
388
+ ctx.transport.send(clientWs, { type: 'session_switched', sessionId: firstId, name: entry.name, cwd: entry.cwd, conversationId: entry.session.resumeSessionId || null })
389
+ ctx.transport.sendSessionInfo(clientWs, firstId)
390
+ // #5555.3 — forced re-home after a destroy: authoritative full rebuild.
391
+ ctx.transport.replayHistory(clientWs, firstId, { forceFull: true })
392
+ }
393
+ broadcastFocusChanged(c, firstId, ctx)
394
+ }
395
+ }
396
+
397
+ ctx.transport.broadcast({ type: 'session_destroyed', sessionId: targetId })
398
+ ctx.transport.broadcastSessionList()
399
+ }
400
+
401
+ function handleRenameSession(ws, client, msg, ctx) {
402
+ const targetId = msg.sessionId
403
+
404
+ if (client.boundSessionId && client.boundSessionId !== targetId) {
405
+ ctx.transport.send(ws, {
406
+ type: 'session_error',
407
+ ...buildSessionTokenMismatchPayload({
408
+ sessionManager: ctx.sessions.sessionManager,
409
+ boundSessionId: client.boundSessionId,
410
+ }),
411
+ })
412
+ return
413
+ }
414
+
415
+ const newName = (typeof msg.name === 'string' && msg.name.trim()) ? msg.name.trim() : null
416
+ if (!newName) {
417
+ sendSessionError(ws, ctx, 'Name is required')
418
+ return
419
+ }
420
+ if (ctx.sessions.sessionManager.isSessionLocked?.(targetId)) {
421
+ sendSessionError(ws, ctx, 'Session is being modified by another operation')
422
+ return
423
+ }
424
+
425
+ const doRename = typeof ctx.sessions.sessionManager.renameSessionLocked === 'function'
426
+ ? () => ctx.sessions.sessionManager.renameSessionLocked(targetId, newName)
427
+ : async () => ctx.sessions.sessionManager.renameSession(targetId, newName)
428
+
429
+ doRename().then(success => {
430
+ if (success) {
431
+ ctx.transport.broadcastSessionList()
432
+ } else {
433
+ sendSessionError(ws, ctx, `Session not found: ${targetId}`)
434
+ }
435
+ }).catch(err => {
436
+ sendSessionError(ws, ctx, err.message)
437
+ })
438
+ }
439
+
440
+ function handleSubscribeSessions(ws, client, msg, ctx) {
441
+ const newlySubscribed = []
442
+ for (const sid of msg.sessionIds) {
443
+ // Bound clients can only subscribe to their bound session
444
+ if (client.boundSessionId && client.boundSessionId !== sid) continue
445
+ if (ctx.sessions.sessionManager.getSession(sid)) {
446
+ if (!client.subscribedSessionIds.has(sid)) {
447
+ newlySubscribed.push(sid)
448
+ }
449
+ // #5563: index-maintaining helper.
450
+ ctx.transport.subscribeClient(client, sid)
451
+ }
452
+ }
453
+ ctx.transport.send(ws, {
454
+ type: 'subscriptions_updated',
455
+ subscribedSessionIds: [...client.subscribedSessionIds],
456
+ })
457
+ for (const sid of newlySubscribed) {
458
+ ctx.transport.sendSessionInfo(ws, sid)
459
+ // #5555.3 — new subscription: authoritative full rebuild (the client may
460
+ // hold stale cached state for this session; cursor delta is connect-only).
461
+ ctx.transport.replayHistory(ws, sid, { forceFull: true })
462
+ }
463
+ }
464
+
465
+ function handleUnsubscribeSessions(ws, client, msg, ctx) {
466
+ for (const sid of msg.sessionIds) {
467
+ if (sid !== client.activeSessionId) {
468
+ // #5563: index-maintaining helper. (The guard keeps the active session
469
+ // subscribed; the helper would also keep it indexed via activeSessionId,
470
+ // but preserving the explicit subscription matches prior behaviour.)
471
+ ctx.transport.unsubscribeClient(client, sid)
472
+ }
473
+ }
474
+ ctx.transport.send(ws, {
475
+ type: 'subscriptions_updated',
476
+ subscribedSessionIds: [...client.subscribedSessionIds],
477
+ })
478
+ }
479
+
480
+ // #5835 Phase 1: opt the client IN to a session's live PTY mirror. Only clients
481
+ // in `terminalSessionIds` receive `terminal_output` (ws-forwarding's filter), so
482
+ // a Chat-tab client never pays for raw bytes it isn't rendering. A bound client
483
+ // may only watch its own session, mirroring handleSubscribeSessions.
484
+ function handleTerminalSubscribe(ws, client, msg, ctx) {
485
+ const sid = msg.sessionId
486
+ if (client.boundSessionId && client.boundSessionId !== sid) return
487
+ // Parity with handleSubscribeSessions: only track a REAL session, so a client
488
+ // can't grow terminalSessionIds unboundedly with junk ids.
489
+ const entry = ctx?.sessions?.sessionManager?.getSession?.(sid)
490
+ if (!entry) return
491
+ // #5985b (epic #5982): subscribing to a user-shell PTY streams raw shell
492
+ // output (live exfil of whatever the operator types/sees), so it requires the
493
+ // PRIMARY token class — not merely the session-scoped viewer check (audit C4).
494
+ // Silent reject, consistent with the other observer rejections here.
495
+ if (isUserShellSession(entry) && client.isPrimaryToken !== true) return
496
+ if (!client.terminalSessionIds) client.terminalSessionIds = new Set()
497
+ const alreadySubscribed = client.terminalSessionIds.has(sid)
498
+ client.terminalSessionIds.add(sid)
499
+ // #5837: re-evaluate the coalescer gate only on an ACTUAL new subscription
500
+ // (symmetric with terminal_unsubscribe, which syncs only when it removed one) —
501
+ // a re-subscribe is a no-op for the gate. This may be the first viewer → ON.
502
+ if (!alreadySubscribed) ctx?.transport?.syncTerminalMirror?.(sid)
503
+ // #5835 Phase 2: tell the new subscriber the authoritative PTY size up front so
504
+ // it can letterbox to the right grid immediately (the size may already differ
505
+ // from the default if another viewer resized it). Gate on the same viewing
506
+ // scope as the broadcast (#5840 review) — opting into a terminal you aren't
507
+ // viewing must not leak its size / that it's a claude-tui session. Only
508
+ // claude-tui sessions have a live PTY / getTerminalSize; others don't send this.
509
+ if (isSessionViewer(client, sid) && typeof entry.session?.getTerminalSize === 'function') {
510
+ const size = entry.session.getTerminalSize()
511
+ ctx.transport.send(ws, { type: 'terminal_size', sessionId: sid, cols: size.cols, rows: size.rows })
512
+ }
513
+ }
514
+
515
+ // #5835 Phase 2: request a resize of a session's live PTY (the remote-viewer
516
+ // mirror). The PTY has ONE size, so only the session's primary owner may drive
517
+ // it — observers ride along and re-letterbox to the `terminal_size` the server
518
+ // broadcasts back (an unclaimed session is open to its first/only viewer, which
519
+ // is the single-operator dashboard case). resizeTerminal clamps + records the
520
+ // size and emits terminal_resize, which ws-forwarding broadcasts to every
521
+ // terminal subscriber. Silent reject: an observer simply doesn't drive the size.
522
+ function handleTerminalResize(ws, client, msg, ctx) {
523
+ const sid = msg.sessionId
524
+ if (client.boundSessionId && client.boundSessionId !== sid) return
525
+ const entry = ctx?.sessions?.sessionManager?.getSession?.(sid)
526
+ if (!entry) return
527
+ // #5985b (epic #5982): resizing a user-shell PTY requires the PRIMARY token
528
+ // class (audit C4) — a paired device must not drive a root shell's grid.
529
+ if (isUserShellSession(entry) && client.isPrimaryToken !== true) return
530
+ // Must be viewing the session to mutate its shared PTY (#5840 review): a
531
+ // non-viewer who merely knows the id must not be able to resize the grid or
532
+ // spam terminal_size at real viewers, even when the session is unclaimed.
533
+ if (!isSessionViewer(client, sid)) return
534
+ const primary = ctx.transport.getPrimary?.(sid)
535
+ if (primary && primary !== client.id) return
536
+ if (typeof entry.session?.resizeTerminal !== 'function') return
537
+ // Return value unused: resizeTerminal emits terminal_resize, which
538
+ // ws-forwarding broadcasts back as terminal_size. A no-op (unchanged size)
539
+ // returns null and simply emits nothing — nothing for the handler to do.
540
+ entry.session.resizeTerminal(msg.cols, msg.rows)
541
+ }
542
+
543
+ // #6313: request a fresh repaint of a session's live PTY mirror — recovery for a
544
+ // WS-backpressure-dropped terminal_output frame that silently desynced the xterm
545
+ // grid (and, since the mirror is interactive, left keystrokes landing at the
546
+ // wrong cursor). The repaint mutates the shared PTY (a SIGWINCH grid size-toggle
547
+ // that makes the shell/TUI redraw), so authority mirrors terminal_resize exactly:
548
+ // a session viewer, primary-owner gated, and user-shell primary-token gated.
549
+ // Silent reject — an observer simply can't drive a repaint.
550
+ function handleTerminalResync(ws, client, msg, ctx) {
551
+ const sid = msg.sessionId
552
+ if (client.boundSessionId && client.boundSessionId !== sid) return
553
+ const entry = ctx?.sessions?.sessionManager?.getSession?.(sid)
554
+ if (!entry) return
555
+ if (isUserShellSession(entry) && client.isPrimaryToken !== true) return
556
+ if (!isSessionViewer(client, sid)) return
557
+ const primary = ctx.transport.getPrimary?.(sid)
558
+ if (primary && primary !== client.id) return
559
+ if (typeof entry.session?.forceTerminalRepaint !== 'function') return
560
+ entry.session.forceTerminalRepaint()
561
+ }
562
+
563
+ // #5835 Phase 1: opt the client OUT of a session's live PTY mirror (e.g. the
564
+ // dashboard leaving the Output tab). Idempotent.
565
+ function handleTerminalUnsubscribe(ws, client, msg, ctx) {
566
+ if (!client.terminalSessionIds) return
567
+ if (!client.terminalSessionIds.delete(msg.sessionId)) return
568
+ // #5837: this may have been the LAST subscriber — turn the coalescer off if so.
569
+ ctx?.transport?.syncTerminalMirror?.(msg.sessionId)
570
+ }
571
+
572
+ // #3404: mobile app sends this when foreground/background state changes so
573
+ // the server can suppress idle/completion pushes only for foreground viewers.
574
+ // Backgrounded clients with still-alive sockets must NOT be treated as active
575
+ // viewers — otherwise the OS keepalive grace period causes false-negative
576
+ // notifications and breaks the phone-first workflow.
577
+ function handleClientVisible(ws, client, msg) {
578
+ client.visible = msg.visible !== false
579
+ }
580
+
581
+ // #5563 (blocker for #5281 shared-session join): explicit primary claim /
582
+ // hand-off. v1 ownership semantics:
583
+ // - First client to claim an UNCLAIMED session becomes its primary; every
584
+ // other subscriber stays an observer (read-only — the input_conflict gate
585
+ // rejects observer input while the session is running).
586
+ // - A claim against a session ANOTHER client already owns is REJECTED unless
587
+ // `force: true` — an explicit operator-driven hand-off / take-over. This is
588
+ // the observe-only guarantee that lets N>2 clients share a session safely.
589
+ // - On the primary disconnecting, the slot is cleared (nobody-until-claim) by
590
+ // the departure path, NOT auto-promoted to an observer.
591
+ // The actual mutation + role broadcast (`session_role` + legacy
592
+ // `primary_changed`) happens in ws-server's _claimPrimary; this handler only
593
+ // validates binding and turns a rejection into a client-facing error.
594
+ function handleClaimPrimary(ws, client, msg, ctx) {
595
+ const targetId = msg.sessionId
596
+ if (!targetId) {
597
+ sendSessionError(ws, ctx, 'sessionId is required')
598
+ return
599
+ }
600
+
601
+ // Bound clients (paired to a single session) may only claim that session.
602
+ if (client.boundSessionId && client.boundSessionId !== targetId) {
603
+ loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} attempted to claim primary on session ${targetId} but is bound to ${client.boundSessionId}`)
604
+ ctx.transport.send(ws, {
605
+ type: 'session_error',
606
+ ...buildSessionTokenMismatchPayload({
607
+ sessionManager: ctx.sessions.sessionManager,
608
+ boundSessionId: client.boundSessionId,
609
+ }),
610
+ })
611
+ return
612
+ }
613
+
614
+ if (!ctx.sessions.sessionManager.getSession(targetId)) {
615
+ sendSessionError(ws, ctx, `Session not found: ${targetId}`)
616
+ return
617
+ }
618
+
619
+ const force = msg.force === true
620
+ const res = ctx.transport.claimPrimary(targetId, client.id, { force })
621
+ if (res.rejected) {
622
+ // Another client owns the session and this was not a forced hand-off.
623
+ // Surface as an input_conflict so existing dashboards render the same
624
+ // calm "another device is driving" notice they already show for the
625
+ // in-flight cross-device send conflict (#5281 ①.3).
626
+ ctx.transport.send(ws, {
627
+ type: 'session_error',
628
+ category: 'input_conflict',
629
+ sessionId: targetId,
630
+ message: 'Another device is the primary for this session. Request a hand-off or wait for it to release.',
631
+ code: 'PRIMARY_HELD',
632
+ primaryClientId: res.primaryClientId,
633
+ })
634
+ return
635
+ }
636
+ // Success (claimed/handed-off) or no-op (already primary). In both cases tell
637
+ // THIS client its authoritative role so a no-op claim still resolves any
638
+ // optimistic local "am I primary?" state.
639
+ ctx.transport.send(ws, {
640
+ type: 'session_role',
641
+ sessionId: targetId,
642
+ primaryClientId: ctx.transport.getPrimary(targetId) ?? null,
643
+ })
644
+ }
645
+
646
+ export const sessionHandlers = {
647
+ list_sessions: handleListSessions,
648
+ switch_session: handleSwitchSession,
649
+ create_session: handleCreateSession,
650
+ destroy_session: handleDestroySession,
651
+ rename_session: handleRenameSession,
652
+ subscribe_sessions: handleSubscribeSessions,
653
+ unsubscribe_sessions: handleUnsubscribeSessions,
654
+ terminal_subscribe: handleTerminalSubscribe,
655
+ terminal_unsubscribe: handleTerminalUnsubscribe,
656
+ terminal_resize: handleTerminalResize,
657
+ terminal_resync: handleTerminalResync,
658
+ client_visible: handleClientVisible,
659
+ claim_primary: handleClaimPrimary,
660
+ }