@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,1945 @@
1
+ /**
2
+ * Control Room v2 (#5174) — Host/Repo Status WS handler.
3
+ *
4
+ * Handles: host_status_request, runner_status_request (#5253),
5
+ * integration_status_request (#5499), integration_action (#5500/#5502)
6
+ *
7
+ * Wires the host survey (control-room/repo-set.js + control-room/survey.js) to
8
+ * the WS protocol. On a `host_status_request` the handler:
9
+ * - resolves the repo set (config.repos ∪ auto-discovered under the root)
10
+ * - runs the survey, passing the cwds of currently-active chroxy sessions so
11
+ * the survey can mark session-bound repos `live`
12
+ * - replies to the requesting client with a single `host_status_snapshot`
13
+ * (the survey result + the `type` field), echoing the optional `requestId`
14
+ *
15
+ * Bearer-token authority (see docs/security/bearer-token-authority.md):
16
+ * The survey returns host-wide metadata about EVERY repo the host knows about
17
+ * — broader than any single session's scope. We therefore serve it only to
18
+ * clients holding host-level authority (the primary token or an unbound
19
+ * linking-mode pairing token, both of which have `client.boundSessionId`
20
+ * unset). A pairing-bound (share-a-session) client is scoped to one session
21
+ * and must NOT receive a cross-repo host survey, so it gets a permission
22
+ * error. Authentication itself is already enforced before dispatch in
23
+ * ws-server._handleMessage, so this handler only adds the
24
+ * bound-vs-unbound authority check.
25
+ *
26
+ * Concurrency: a host survey shells out to git/gh once per repo. To stop a
27
+ * spamming client from piling up overlapping surveys we keep a single in-flight
28
+ * survey per client (keyed by the client object via a WeakSet) and reject
29
+ * additional requests until the current one settles.
30
+ */
31
+ import { realpathSync } from 'fs'
32
+ import { resolve } from 'path'
33
+ import { createLogger } from '../logger.js'
34
+ import { resolveRepoSet, DEFAULT_CONTROL_ROOM_ROOT } from '../control-room/repo-set.js'
35
+ import { surveyRepos } from '../control-room/survey.js'
36
+ import { surveyRunners, DEFAULT_RUNNER_ROOT } from '../control-room/runners.js'
37
+ import { surveyContainers } from '../control-room/containers.js'
38
+ import { surveyRepoRuntimeConfig, hostRuntimeDefaults } from '../control-room/repo-runtime-config.js'
39
+ import { surveyByokPool } from '../control-room/byok-pool.js'
40
+ import { isPoolEnabled, getSharedPool } from '../docker-byok-pool.js'
41
+ import { surveyHostPrune, runHostPrune, PRUNE_KINDS } from '../control-room/host-prune.js'
42
+ import { surveySimulators, runSimulatorAction, SIMULATOR_ACTIONS } from '../control-room/simulators.js'
43
+ import { surveyEmulators, runEmulatorAction, EMULATOR_ACTIONS } from '../control-room/emulators.js'
44
+ import { surveyWsl, runWslAction, WSL_ACTIONS } from '../control-room/wsl.js'
45
+ import { surveyIntegrations, runRepoMemoryIndex, runRepoRelayRerun } from '../control-room/integrations.js'
46
+ import { surveySkillsInventory } from '../control-room/skills-inventory.js'
47
+ import { makeSurveyHandler, makeSyncHostSurvey, makeActionError } from '../control-room/handler-factory.js'
48
+ import { getErrorMessage } from '../utils/error-message.js'
49
+
50
+ const log = createLogger('ws')
51
+
52
+ // Per-client in-flight guard. A WeakSet keyed by the client object means we
53
+ // never leak entries when a client disconnects (the client object is GC'd) and
54
+ // we never need an explicit cleanup path.
55
+ const inFlight = new WeakSet()
56
+ // #5253: a separate in-flight guard for the runner survey, so a runner refresh
57
+ // and a host refresh don't block each other (they shell out to different tools).
58
+ const runnerInFlight = new WeakSet()
59
+ // #5499: same again for the integrations survey — independent of both above.
60
+ const integrationInFlight = new WeakSet()
61
+ // #5554: same again for the skills inventory survey — independent of all above.
62
+ const skillsInventoryInFlight = new WeakSet()
63
+ // #6133: same again for the containers & environments survey — independent of all above.
64
+ const containersInFlight = new WeakSet()
65
+ // #6139: same again for the per-repo runtime config survey — independent of all above.
66
+ const repoRuntimeConfigInFlight = new WeakSet()
67
+ // #6135: same again for the BYOK pool stats survey — independent of all above.
68
+ const byokPoolInFlight = new WeakSet()
69
+ // #6140: same again for the host prune guardrails survey — independent of all above.
70
+ const hostPruneInFlight = new WeakSet()
71
+ // #6136: same again for the iOS simulator survey — independent of all above.
72
+ const simulatorInFlight = new WeakSet()
73
+ // #6137: same again for the Android emulator survey — independent of all above.
74
+ const emulatorInFlight = new WeakSet()
75
+ // #6138: same again for the WSL distro survey — independent of all above.
76
+ const wslInFlight = new WeakSet()
77
+
78
+ /**
79
+ * #5377 — shared builder for the survey error-snapshots. The error reply is a
80
+ * schema-conformant but empty snapshot (empty repos, zeroed summary, the real
81
+ * root + a fresh timestamp) plus an additive `error` (and echoed `requestId`)
82
+ * the dashboard branches on — so the consumer never special-cases a malformed
83
+ * reply. `errorSnapshot` and `runnerErrorSnapshot` are identical apart from
84
+ * their `type` and the keys of the zeroed `summary`; this is the single place
85
+ * the envelope is shaped, so a schema change touches one function and a future
86
+ * survey reuses it.
87
+ *
88
+ * @param {string} type - the snapshot message type.
89
+ * @param {object} emptySummary - the zeroed, type-specific summary object.
90
+ * @param {string} root - effective discovery/install root to report.
91
+ * @param {string|null} requestId - correlation id to echo, or null.
92
+ * @param {{ code: string, message: string }} error
93
+ * @returns {object} a schema-conformant status snapshot carrying the error.
94
+ */
95
+ function buildSurveyErrorSnapshot(type, emptySummary, root, requestId, error) {
96
+ return {
97
+ type,
98
+ requestId,
99
+ generatedAt: new Date().toISOString(),
100
+ root,
101
+ summary: emptySummary,
102
+ repos: [],
103
+ error,
104
+ }
105
+ }
106
+
107
+ /** `host_status_snapshot` error reply — see {@link buildSurveyErrorSnapshot}. */
108
+ function errorSnapshot(root, requestId, error) {
109
+ return buildSurveyErrorSnapshot(
110
+ 'host_status_snapshot',
111
+ { live: 0, onboarded: 0, abandoned: 0, investigate: 0, recent: 0 },
112
+ root, requestId, error,
113
+ )
114
+ }
115
+
116
+ /**
117
+ * Derive the set of cwds for currently-active chroxy sessions, used by the
118
+ * survey to mark session-bound repos as `live`. Reads from the SessionManager's
119
+ * `listSessions()` snapshot (each entry carries `cwd`).
120
+ *
121
+ * @param {object} sessionManager
122
+ * @returns {string[]} de-duped, non-empty cwd strings.
123
+ */
124
+ function activeSessionCwds(sessionManager) {
125
+ if (!sessionManager || typeof sessionManager.listSessions !== 'function') return []
126
+ let sessions
127
+ try {
128
+ sessions = sessionManager.listSessions()
129
+ } catch {
130
+ return []
131
+ }
132
+ const out = new Set()
133
+ for (const s of Array.isArray(sessions) ? sessions : []) {
134
+ if (s && typeof s.cwd === 'string' && s.cwd.length > 0) out.add(s.cwd)
135
+ }
136
+ return [...out]
137
+ }
138
+
139
+ const handleHostStatusRequest = makeSurveyHandler({
140
+ inFlight,
141
+ logName: 'host_status_request',
142
+ // Effective discovery root: the configured root, else resolveRepoSet's own
143
+ // default (~/Projects). Resolve it HERE — not as an undefined passed down —
144
+ // so the snapshot's `root` reports the directory we actually scanned rather
145
+ // than '' when controlRoomRoot is unset. Computed pre-gate so the degraded
146
+ // replies (incl. the FORBIDDEN one) report the real root.
147
+ prepare: ({ ctx }) => {
148
+ const config = ctx?.services?.config || {}
149
+ const root = typeof config.controlRoomRoot === 'string' && config.controlRoomRoot.length > 0
150
+ ? config.controlRoomRoot
151
+ : DEFAULT_CONTROL_ROOM_ROOT
152
+ return { root, repos: Array.isArray(config.repos) ? config.repos : [] }
153
+ },
154
+ forbidden: ({ requestId, prep }) => errorSnapshot(prep.root, requestId, {
155
+ code: 'FORBIDDEN',
156
+ message: 'host_status_request requires host-level authority (a session-bound token cannot survey the host)',
157
+ }),
158
+ inProgress: ({ requestId, prep }) => errorSnapshot(prep.root, requestId, {
159
+ code: 'SURVEY_IN_PROGRESS',
160
+ message: 'A host status survey is already in progress for this client',
161
+ }),
162
+ failed: ({ requestId, prep, err }) => errorSnapshot(prep.root, requestId, {
163
+ code: 'SURVEY_FAILED',
164
+ message: getErrorMessage(err, 'host status survey failed'),
165
+ }),
166
+ run: async ({ ctx, requestId, prep }) => {
167
+ // Tests can inject `ctx.surveyRepos` / `ctx.resolveRepoSet` to stub the
168
+ // filesystem + git/gh calls without patching modules. Production never sets
169
+ // them and falls through to the real implementations.
170
+ const resolveFn = typeof ctx?.resolveRepoSet === 'function' ? ctx.resolveRepoSet : resolveRepoSet
171
+ const surveyFn = typeof ctx?.surveyRepos === 'function' ? ctx.surveyRepos : surveyRepos
172
+ const repoSet = resolveFn({ repos: prep.repos, root: prep.root })
173
+ const snapshot = await surveyFn(repoSet, {
174
+ activeSessionCwds: activeSessionCwds(ctx?.sessions?.sessionManager),
175
+ root: prep.root,
176
+ })
177
+ return {
178
+ type: 'host_status_snapshot',
179
+ requestId,
180
+ generatedAt: snapshot.generatedAt,
181
+ root: snapshot.root,
182
+ summary: snapshot.summary,
183
+ repos: snapshot.repos,
184
+ }
185
+ },
186
+ })
187
+
188
+ /** #5253 — `runner_status_snapshot` error reply — see {@link buildSurveyErrorSnapshot}. */
189
+ function runnerErrorSnapshot(root, requestId, error) {
190
+ return buildSurveyErrorSnapshot(
191
+ 'runner_status_snapshot',
192
+ { total: 0, busy: 0, idle: 0, offline: 0, stopped: 0, unregistered: 0 },
193
+ root, requestId, error,
194
+ )
195
+ }
196
+
197
+ /**
198
+ * #5253 — self-hosted runner status survey handler. Same authority +
199
+ * in-flight + degraded-reply contract as `handleHostStatusRequest`: the survey
200
+ * exposes host-wide runner metadata, so it is served only to host-level
201
+ * (unbound) clients, one survey per client at a time.
202
+ */
203
+ const handleRunnerStatusRequest = makeSurveyHandler({
204
+ inFlight: runnerInFlight,
205
+ logName: 'runner_status_request',
206
+ prepare: ({ ctx }) => {
207
+ const config = ctx?.services?.config || {}
208
+ const root = typeof config.controlRoomRunnerRoot === 'string' && config.controlRoomRunnerRoot.length > 0
209
+ ? config.controlRoomRunnerRoot
210
+ : DEFAULT_RUNNER_ROOT
211
+ return { config, root }
212
+ },
213
+ forbidden: ({ requestId, prep }) => runnerErrorSnapshot(prep.root, requestId, {
214
+ code: 'FORBIDDEN',
215
+ message: 'runner_status_request requires host-level authority (a session-bound token cannot survey the host)',
216
+ }),
217
+ inProgress: ({ requestId, prep }) => runnerErrorSnapshot(prep.root, requestId, {
218
+ code: 'SURVEY_IN_PROGRESS',
219
+ message: 'A runner status survey is already in progress for this client',
220
+ }),
221
+ failed: ({ requestId, prep, err }) => runnerErrorSnapshot(prep.root, requestId, {
222
+ code: 'SURVEY_FAILED',
223
+ message: getErrorMessage(err, 'runner status survey failed'),
224
+ }),
225
+ run: async ({ ctx, requestId, prep }) => {
226
+ // Tests inject `ctx.surveyRunners` to stub the fs/exec calls.
227
+ const surveyFn = typeof ctx?.surveyRunners === 'function' ? ctx.surveyRunners : surveyRunners
228
+ // #5260: gh enrichment is on by default; an operator disables it (faster,
229
+ // local-only survey, or no `gh` auth) by setting controlRoomRunnerIncludeGithub
230
+ // false. Only an explicit `false` turns it off — unset/undefined stays true.
231
+ const includeGithub = prep.config.controlRoomRunnerIncludeGithub !== false
232
+ const snapshot = await surveyFn({ root: prep.root, includeGithub })
233
+ return {
234
+ type: 'runner_status_snapshot',
235
+ requestId,
236
+ generatedAt: snapshot.generatedAt,
237
+ root: snapshot.root,
238
+ summary: snapshot.summary,
239
+ repos: snapshot.repos,
240
+ }
241
+ },
242
+ })
243
+
244
+ /**
245
+ * #6133 — `containers_status_snapshot` error reply. The containers survey uses a
246
+ * flat `containers` shape (no `root`/`repos`), so it builds its own degraded
247
+ * snapshot rather than the shared `buildSurveyErrorSnapshot` (which sets
248
+ * `repos: []`). Empty containers + zeroed summary + the typed `error`.
249
+ */
250
+ function containersErrorSnapshot(requestId, error) {
251
+ return {
252
+ type: 'containers_status_snapshot',
253
+ requestId,
254
+ generatedAt: new Date().toISOString(),
255
+ summary: { total: 0, running: 0, stopped: 0, other: 0 },
256
+ containers: [],
257
+ dockerStatsNote: null,
258
+ error,
259
+ }
260
+ }
261
+
262
+ /**
263
+ * #6133 (epic #5530) — containers & environments survey handler. Same authority
264
+ * + in-flight + degraded-reply contract as the sibling surveys: it exposes
265
+ * host-wide runtime metadata, so it is served only to host-level (unbound)
266
+ * clients, one survey per client at a time. Surveys ONLY chroxy's own
267
+ * EnvironmentManager records (never arbitrary host containers).
268
+ */
269
+ const handleContainersStatusRequest = makeSurveyHandler({
270
+ inFlight: containersInFlight,
271
+ logName: 'containers_status_request',
272
+ forbidden: ({ requestId }) => containersErrorSnapshot(requestId, {
273
+ code: 'FORBIDDEN',
274
+ message: 'containers_status_request requires host-level authority (a session-bound token cannot survey the host)',
275
+ }),
276
+ inProgress: ({ requestId }) => containersErrorSnapshot(requestId, {
277
+ code: 'SURVEY_IN_PROGRESS',
278
+ message: 'A containers status survey is already in progress for this client',
279
+ }),
280
+ failed: ({ requestId, err }) => containersErrorSnapshot(requestId, {
281
+ code: 'SURVEY_FAILED',
282
+ message: getErrorMessage(err, 'containers status survey failed'),
283
+ }),
284
+ run: async ({ ctx, requestId }) => {
285
+ // Tests inject `ctx.surveyContainers` to stub the docker/exec calls.
286
+ const surveyFn = typeof ctx?.surveyContainers === 'function' ? ctx.surveyContainers : surveyContainers
287
+ // The EnvironmentManager may be absent (container support disabled) — degrade
288
+ // to an empty inventory rather than erroring.
289
+ const envManager = ctx?.services?.environmentManager || null
290
+ // #6133: `docker stats` enrichment is on by default; an operator on a slow or
291
+ // socketless docker disables it (inventory-only survey) by setting
292
+ // controlRoomContainersIncludeStats false. Only an explicit `false` turns it
293
+ // off — unset/undefined stays true. Mirrors the runner survey's includeGithub.
294
+ const config = ctx?.services?.config || {}
295
+ const includeStats = config.controlRoomContainersIncludeStats !== false
296
+ const snapshot = await surveyFn({
297
+ listEnvironments: () => (typeof envManager?.list === 'function' ? envManager.list() : []),
298
+ includeStats,
299
+ })
300
+ return {
301
+ type: 'containers_status_snapshot',
302
+ requestId,
303
+ generatedAt: snapshot.generatedAt,
304
+ summary: snapshot.summary,
305
+ containers: snapshot.containers,
306
+ dockerStatsNote: snapshot.dockerStatsNote ?? null,
307
+ }
308
+ },
309
+ })
310
+
311
+ /**
312
+ * #6139 — `repo_runtime_config_snapshot` error reply. Like the containers
313
+ * survey, this uses a flat shape (no shared `root`/`repos` envelope), so it
314
+ * builds its own degraded snapshot: empty repos + zeroed summary + the typed
315
+ * `error`.
316
+ *
317
+ * `hostDefaults` (optional) carries the real config-derived host-level fields
318
+ * (backend / backendSource / isolation / allowlist) so a degraded reply to an
319
+ * AUTHORIZED host-level client (SURVEY_IN_PROGRESS / SURVEY_FAILED) still
320
+ * reports the effective defaults instead of placeholders. When omitted (the
321
+ * FORBIDDEN path — an unauthorized session-bound client) it falls back to safe
322
+ * placeholders: a session-bound token must NOT learn the host's backend or
323
+ * allowlist patterns (the same leak boundary as effectiveAllowlist's note).
324
+ */
325
+ function repoRuntimeConfigErrorSnapshot(requestId, error, hostDefaults = null) {
326
+ const d = hostDefaults || {
327
+ backend: 'docker',
328
+ backendSource: 'default',
329
+ isolation: 'worktree-before-docker',
330
+ allowlist: { source: 'default', patterns: [] },
331
+ }
332
+ return {
333
+ type: 'repo_runtime_config_snapshot',
334
+ requestId,
335
+ generatedAt: new Date().toISOString(),
336
+ backend: d.backend,
337
+ backendSource: d.backendSource,
338
+ isolation: d.isolation,
339
+ allowlist: d.allowlist,
340
+ repos: [],
341
+ summary: { total: 0, withDevcontainer: 0, withCompose: 0, imagesDenied: 0, errored: 0 },
342
+ error,
343
+ }
344
+ }
345
+
346
+ /**
347
+ * #6139 (epic #5530) — per-repo runtime config survey handler. Read-only. Same
348
+ * authority + in-flight + degraded-reply contract as the sibling surveys: it
349
+ * exposes host-wide runtime metadata (the resolved repo set + the host's
350
+ * backend/allowlist defaults), so it's served only to host-level (unbound)
351
+ * clients, one survey per client at a time.
352
+ */
353
+ const handleRepoRuntimeConfigRequest = makeSurveyHandler({
354
+ inFlight: repoRuntimeConfigInFlight,
355
+ logName: 'repo_runtime_config_request',
356
+ // FORBIDDEN replies use safe placeholders (no hostDefaults) — a session-bound
357
+ // token must not learn the host's backend/allowlist.
358
+ forbidden: ({ requestId }) => repoRuntimeConfigErrorSnapshot(requestId, {
359
+ code: 'FORBIDDEN',
360
+ message: 'repo_runtime_config_request requires host-level authority (a session-bound token cannot survey the host)',
361
+ }),
362
+ // Past the authority gate the client is host-level, so degraded snapshots may
363
+ // carry the real config-derived host defaults (computed without touching the
364
+ // filesystem) rather than placeholders. hostDefaults is resolved ONLY on these
365
+ // non-bound paths — never in `forbidden` — to preserve the leak boundary.
366
+ inProgress: ({ ctx, requestId }) => repoRuntimeConfigErrorSnapshot(requestId, {
367
+ code: 'SURVEY_IN_PROGRESS',
368
+ message: 'A repo runtime config survey is already in progress for this client',
369
+ }, hostRuntimeDefaults(ctx?.services?.config || {})),
370
+ failed: ({ ctx, requestId, err }) => repoRuntimeConfigErrorSnapshot(requestId, {
371
+ code: 'SURVEY_FAILED',
372
+ message: getErrorMessage(err, 'repo runtime config survey failed'),
373
+ }, hostRuntimeDefaults(ctx?.services?.config || {})),
374
+ run: async ({ ctx, requestId }) => {
375
+ const config = ctx?.services?.config || {}
376
+ // Same repo-set resolution as host_status_request: configured root else the
377
+ // default, config.repos plus auto-discovered git repos.
378
+ const root = typeof config.controlRoomRoot === 'string' && config.controlRoomRoot.length > 0
379
+ ? config.controlRoomRoot
380
+ : DEFAULT_CONTROL_ROOM_ROOT
381
+ const repos = Array.isArray(config.repos) ? config.repos : []
382
+ // Tests inject `ctx.resolveRepoSet` / `ctx.surveyRepoRuntimeConfig` to stub
383
+ // the filesystem + devcontainer-parse touches.
384
+ const resolveFn = typeof ctx?.resolveRepoSet === 'function' ? ctx.resolveRepoSet : resolveRepoSet
385
+ const surveyFn = typeof ctx?.surveyRepoRuntimeConfig === 'function' ? ctx.surveyRepoRuntimeConfig : surveyRepoRuntimeConfig
386
+ const repoSet = resolveFn({ repos, root })
387
+ const snapshot = await surveyFn({ repoSet, config })
388
+ return {
389
+ type: 'repo_runtime_config_snapshot',
390
+ requestId,
391
+ generatedAt: snapshot.generatedAt,
392
+ backend: snapshot.backend,
393
+ backendSource: snapshot.backendSource,
394
+ isolation: snapshot.isolation,
395
+ allowlist: snapshot.allowlist,
396
+ repos: snapshot.repos,
397
+ summary: snapshot.summary,
398
+ }
399
+ },
400
+ })
401
+
402
+ /**
403
+ * #6135 — `byok_pool_status_snapshot` error reply. Flat shape (no `root`/`repos`
404
+ * envelope), so it builds its own degraded snapshot: a disabled pool + null
405
+ * limits/stats + the typed `error`.
406
+ */
407
+ function byokPoolErrorSnapshot(requestId, error) {
408
+ return {
409
+ type: 'byok_pool_status_snapshot',
410
+ requestId,
411
+ generatedAt: new Date().toISOString(),
412
+ enabled: false,
413
+ note: null,
414
+ limits: null,
415
+ stats: null,
416
+ error,
417
+ }
418
+ }
419
+
420
+ /**
421
+ * #6135 (epic #5530) — BYOK container-pool stats survey handler. Read-only. Same
422
+ * authority + in-flight + degraded-reply contract as the sibling surveys: it
423
+ * exposes host-wide pool metadata, so it is served only to host-level (unbound)
424
+ * clients, one survey per client at a time. The pool being OFF is a first-class
425
+ * `enabled: false` snapshot, not an error.
426
+ */
427
+ const handleByokPoolStatusRequest = makeSurveyHandler({
428
+ inFlight: byokPoolInFlight,
429
+ logName: 'byok_pool_status_request',
430
+ forbidden: ({ requestId }) => byokPoolErrorSnapshot(requestId, {
431
+ code: 'FORBIDDEN',
432
+ message: 'byok_pool_status_request requires host-level authority (a session-bound token cannot survey the host)',
433
+ }),
434
+ inProgress: ({ requestId }) => byokPoolErrorSnapshot(requestId, {
435
+ code: 'SURVEY_IN_PROGRESS',
436
+ message: 'A BYOK pool status survey is already in progress for this client',
437
+ }),
438
+ failed: ({ requestId, err }) => byokPoolErrorSnapshot(requestId, {
439
+ code: 'SURVEY_FAILED',
440
+ message: getErrorMessage(err, 'BYOK pool status survey failed'),
441
+ }),
442
+ run: async ({ ctx, requestId }) => {
443
+ // Tests inject `ctx.surveyByokPool` to stub the pool/stats singletons.
444
+ const surveyFn = typeof ctx?.surveyByokPool === 'function' ? ctx.surveyByokPool : surveyByokPool
445
+ const snapshot = await surveyFn()
446
+ return {
447
+ type: 'byok_pool_status_snapshot',
448
+ requestId,
449
+ generatedAt: snapshot.generatedAt,
450
+ enabled: snapshot.enabled,
451
+ note: snapshot.note ?? null,
452
+ limits: snapshot.limits ?? null,
453
+ stats: snapshot.stats ?? null,
454
+ }
455
+ },
456
+ })
457
+
458
+ /** #5499 — `integration_status_snapshot` error reply — see {@link buildSurveyErrorSnapshot}. */
459
+ function integrationErrorSnapshot(root, requestId, error) {
460
+ return buildSurveyErrorSnapshot(
461
+ 'integration_status_snapshot',
462
+ { total: 0, configured: 0, notConfigured: 0, degraded: 0 },
463
+ root, requestId, error,
464
+ )
465
+ }
466
+
467
+ /**
468
+ * #5499/#5501 (epic #5498) — Integrations survey handler (repo-memory and
469
+ * repo-relay observability). Same authority + in-flight + degraded-reply contract as
470
+ * `handleHostStatusRequest`: the survey exposes host-wide per-repo metadata,
471
+ * so it is served only to host-level (unbound) clients, one survey per client
472
+ * at a time. The repo set is the same one the host survey resolves
473
+ * (config.repos ∪ auto-discovered under controlRoomRoot).
474
+ */
475
+ const handleIntegrationStatusRequest = makeSurveyHandler({
476
+ inFlight: integrationInFlight,
477
+ logName: 'integration_status_request',
478
+ prepare: ({ ctx }) => {
479
+ const config = ctx?.services?.config || {}
480
+ const root = typeof config.controlRoomRoot === 'string' && config.controlRoomRoot.length > 0
481
+ ? config.controlRoomRoot
482
+ : DEFAULT_CONTROL_ROOM_ROOT
483
+ return { config, root, repos: Array.isArray(config.repos) ? config.repos : [] }
484
+ },
485
+ forbidden: ({ requestId, prep }) => integrationErrorSnapshot(prep.root, requestId, {
486
+ code: 'FORBIDDEN',
487
+ message: 'integration_status_request requires host-level authority (a session-bound token cannot survey the host)',
488
+ }),
489
+ inProgress: ({ requestId, prep }) => integrationErrorSnapshot(prep.root, requestId, {
490
+ code: 'SURVEY_IN_PROGRESS',
491
+ message: 'An integration status survey is already in progress for this client',
492
+ }),
493
+ failed: ({ requestId, prep, err }) => integrationErrorSnapshot(prep.root, requestId, {
494
+ code: 'SURVEY_FAILED',
495
+ message: getErrorMessage(err, 'integration status survey failed'),
496
+ }),
497
+ run: async ({ ctx, requestId, prep }) => {
498
+ // Tests inject `ctx.resolveRepoSet` / `ctx.surveyIntegrations` to stub the
499
+ // fs/exec calls without patching modules.
500
+ const resolveFn = typeof ctx?.resolveRepoSet === 'function' ? ctx.resolveRepoSet : resolveRepoSet
501
+ const surveyFn = typeof ctx?.surveyIntegrations === 'function' ? ctx.surveyIntegrations : surveyIntegrations
502
+ // Optional explicit repo-memory binary path — skips the PATH probe (useful
503
+ // when the daemon runs with a GUI/launchd PATH that misses npm globals).
504
+ const bin = typeof prep.config.controlRoomRepoMemoryBin === 'string' && prep.config.controlRoomRepoMemoryBin.length > 0
505
+ ? prep.config.controlRoomRepoMemoryBin
506
+ : undefined
507
+ const repoSet = resolveFn({ repos: prep.repos, root: prep.root })
508
+ const snapshot = await surveyFn(repoSet, { root: prep.root, bin })
509
+ return {
510
+ type: 'integration_status_snapshot',
511
+ requestId,
512
+ generatedAt: snapshot.generatedAt,
513
+ root: snapshot.root,
514
+ summary: snapshot.summary,
515
+ repos: snapshot.repos,
516
+ repoMemoryCli: snapshot.repoMemoryCli,
517
+ // #5501: snapshot-level gh CLI note for the repo-relay columns.
518
+ ghCli: snapshot.ghCli,
519
+ }
520
+ },
521
+ })
522
+
523
+ // ───────────────────────────────────────────────────────────────────────────
524
+ // #5554 (epic #5159) — Skills inventory survey handler.
525
+ // ───────────────────────────────────────────────────────────────────────────
526
+
527
+ /**
528
+ * #5554 — `skills_inventory_snapshot` error reply. The skills snapshot has a
529
+ * different shape from the host/runner/integration trio (global/repos tiers,
530
+ * no `summary`), so it gets its own degraded-snapshot builder rather than
531
+ * reusing `buildSurveyErrorSnapshot`. Same posture though: a schema-valid empty
532
+ * snapshot (empty global + repos, the real root, a fresh timestamp) plus an
533
+ * additive `error` the dashboard branches on, with the request's `requestId`
534
+ * echoed.
535
+ */
536
+ function skillsInventoryErrorSnapshot(root, requestId, error) {
537
+ return {
538
+ type: 'skills_inventory_snapshot',
539
+ requestId,
540
+ generatedAt: new Date().toISOString(),
541
+ root,
542
+ global: [],
543
+ globalError: null,
544
+ repos: [],
545
+ error,
546
+ }
547
+ }
548
+
549
+ /**
550
+ * #5554 — Skills inventory survey handler. Same authority + in-flight +
551
+ * degraded-reply contract as the sibling surveys: the inventory exposes
552
+ * host-wide skill metadata (the global tier + every surveyed repo's overlay),
553
+ * so it is served only to host-level (unbound) clients, one survey per client
554
+ * at a time. The repo set is the same one the host survey resolves
555
+ * (config.repos ∪ auto-discovered under controlRoomRoot).
556
+ *
557
+ * Scan-on-request only — the global + per-repo overlay scans are NOT part of
558
+ * the periodic survey. SECURITY: skill BODIES never leave the server; the
559
+ * survey carries names / descriptions / metadata only (see
560
+ * control-room/skills-inventory.js).
561
+ */
562
+ const handleSkillsInventoryRequest = makeSurveyHandler({
563
+ inFlight: skillsInventoryInFlight,
564
+ logName: 'skills_inventory_request',
565
+ prepare: ({ ctx }) => {
566
+ const config = ctx?.services?.config || {}
567
+ const root = typeof config.controlRoomRoot === 'string' && config.controlRoomRoot.length > 0
568
+ ? config.controlRoomRoot
569
+ : DEFAULT_CONTROL_ROOM_ROOT
570
+ return { root, repos: Array.isArray(config.repos) ? config.repos : [] }
571
+ },
572
+ forbidden: ({ requestId, prep }) => skillsInventoryErrorSnapshot(prep.root, requestId, {
573
+ code: 'FORBIDDEN',
574
+ message: 'skills_inventory_request requires host-level authority (a session-bound token cannot survey the host)',
575
+ }),
576
+ inProgress: ({ requestId, prep }) => skillsInventoryErrorSnapshot(prep.root, requestId, {
577
+ code: 'SURVEY_IN_PROGRESS',
578
+ message: 'A skills inventory survey is already in progress for this client',
579
+ }),
580
+ failed: ({ requestId, prep, err }) => skillsInventoryErrorSnapshot(prep.root, requestId, {
581
+ code: 'SURVEY_FAILED',
582
+ message: getErrorMessage(err, 'skills inventory survey failed'),
583
+ }),
584
+ run: async ({ ctx, requestId, prep }) => {
585
+ // Tests inject `ctx.resolveRepoSet` / `ctx.surveySkillsInventory` to stub the
586
+ // fs scans without patching modules.
587
+ const resolveFn = typeof ctx?.resolveRepoSet === 'function' ? ctx.resolveRepoSet : resolveRepoSet
588
+ const surveyFn = typeof ctx?.surveySkillsInventory === 'function' ? ctx.surveySkillsInventory : surveySkillsInventory
589
+ // Per-skill usage aggregates from the recorder (when the daemon wired one).
590
+ // Absent → the inventory simply reports zeroed usage.
591
+ const recorder = ctx?.services?.skillsUsageRecorder
592
+ const usage = recorder && typeof recorder.aggregatesByName === 'function'
593
+ ? recorder.aggregatesByName()
594
+ : null
595
+ const repoSet = resolveFn({ repos: prep.repos, root: prep.root })
596
+ const snapshot = await surveyFn(repoSet, { root: prep.root, usage })
597
+ return {
598
+ type: 'skills_inventory_snapshot',
599
+ requestId,
600
+ generatedAt: snapshot.generatedAt,
601
+ root: snapshot.root,
602
+ global: snapshot.global,
603
+ globalError: snapshot.globalError ?? null,
604
+ repos: snapshot.repos,
605
+ }
606
+ },
607
+ })
608
+
609
+ // ───────────────────────────────────────────────────────────────────────────
610
+ // #5500/#5502 (epic #5498) — integration_action: repo-memory Reindex and
611
+ // repo-relay Re-run
612
+ // ───────────────────────────────────────────────────────────────────────────
613
+
614
+ /**
615
+ * #5500: per-repo in-flight guard for ALL integration actions, keyed by the
616
+ * repo's CANONICAL realpath (so a symlinked alias can't sidestep the overlap
617
+ * check). A plain Map (not a WeakSet like the survey guards) because the key
618
+ * is a string and entries are explicitly deleted in the handler's `finally`
619
+ * — nothing leaks across client disconnects since completion always settles
620
+ * the promise. Map.size doubles as the global concurrency gauge.
621
+ *
622
+ * #5502: deliberately ONE bucket across action kinds (reindex + relay
623
+ * re-run share it): a repo gets at most one mutating integration action at a
624
+ * time, and the global cap bounds total subprocess fan-out regardless of
625
+ * which buttons the operator mashes. Actions are rare operator clicks — a
626
+ * shared bucket is the simplest cap that still can't be sidestepped by
627
+ * mixing action kinds.
628
+ */
629
+ const actionInFlight = new Map()
630
+ /**
631
+ * #5500: global concurrency cap — the action buttons must not be able to
632
+ * fork-bomb the host. No queue by design: a request above the cap is
633
+ * rejected with a legible "busy" error and the operator retries.
634
+ */
635
+ export const MAX_CONCURRENT_INTEGRATION_ACTIONS = 2
636
+
637
+ /**
638
+ * #5500: shared INTEGRATION_ACTION_FAILED reply. Mirrors how the
639
+ * CANCEL_ACTIVITY_FAILED session_error is built in input-handlers.js: the
640
+ * `session_error` envelope with a stable `code`, a `reason` discriminator,
641
+ * and the request's correlation fields (`requestId` / `action` / `repoPath`,
642
+ * plus `runId` for #5502 re-runs) echoed so the dashboard can clear the
643
+ * exact row's pending state.
644
+ */
645
+ const integrationActionError = makeActionError('INTEGRATION_ACTION_FAILED', (msg) => ({
646
+ action: typeof msg?.action === 'string' ? msg.action : null,
647
+ repoPath: typeof msg?.repoPath === 'string' ? msg.repoPath : null,
648
+ runId: Number.isInteger(msg?.runId) ? msg.runId : null,
649
+ }))
650
+
651
+ /**
652
+ * #5500/#5502 — integration action registry. The shared handler below runs
653
+ * the authority / repoPath / repo-set-membership / in-flight gates ONCE for
654
+ * every action; each entry only contributes:
655
+ * - `validate(msg)` — action-specific request-shape checks, run before any
656
+ * path resolution. Returns `[reason, message]` to reject, or null.
657
+ * - `run({ msg, ctx, config, targetKey })` — the exec, against the
658
+ * CANONICAL realpath. Resolves the action-specific ack fields (spread
659
+ * into the `integration_action_ack`); throws (optionally with a machine
660
+ * `.reason`) to fail.
661
+ * - `failureReason` — the fallback `reason` when a thrown error has none.
662
+ *
663
+ * The schema's closed enum already rejects unknown actions at the wire; the
664
+ * registry lookup is defence in depth for in-process callers/future drift.
665
+ */
666
+ const integrationActions = {
667
+ /**
668
+ * #5500: `repo-memory index <repoRoot>` — prewarm/refresh the summary
669
+ * cache (there is no watcher — the cache only refreshes on agent reads or
670
+ * an explicit index run). Acks with the parsed scanned/summarized/fresh/
671
+ * skipped counts (or `counts: null` when the CLI output is unparseable).
672
+ * Safe alongside live sessions: repo-memory's cache is SQLite in WAL mode,
673
+ * so a concurrent index is safe next to an agent session reading summaries.
674
+ */
675
+ repo_memory_reindex: {
676
+ failureReason: 'index-failed',
677
+ validate: () => null,
678
+ async run({ ctx, config, targetKey }) {
679
+ const runFn = typeof ctx?.runRepoMemoryIndex === 'function' ? ctx.runRepoMemoryIndex : runRepoMemoryIndex
680
+ const bin = typeof config.controlRoomRepoMemoryBin === 'string' && config.controlRoomRepoMemoryBin.length > 0
681
+ ? config.controlRoomRepoMemoryBin
682
+ : undefined
683
+ const result = await runFn(targetKey, { bin })
684
+ return { counts: result && result.counts ? result.counts : null }
685
+ },
686
+ },
687
+ /**
688
+ * #5502: `gh run rerun <databaseId> -R <owner>/<repo>` for a FAILED
689
+ * repo-relay run. The client's `runId` is only a lookup key —
690
+ * runRepoRelayRerun re-fetches the run list server-side and requires the
691
+ * id to name a surfaced run with conclusion 'failure' before any exec.
692
+ * The rerun ack echoes the runId and carries `counts: null` (nothing to
693
+ * count — the new attempt shows as in_progress on the next refresh).
694
+ */
695
+ repo_relay_rerun: {
696
+ failureReason: 'rerun-failed',
697
+ validate(msg) {
698
+ if (!Number.isInteger(msg?.runId) || msg.runId < 0) {
699
+ return ['invalid-run-id',
700
+ 'repo_relay_rerun requires an integer runId (the databaseId of a surveyed failed run)']
701
+ }
702
+ return null
703
+ },
704
+ async run({ msg, ctx, targetKey }) {
705
+ const runFn = typeof ctx?.runRepoRelayRerun === 'function' ? ctx.runRepoRelayRerun : runRepoRelayRerun
706
+ const result = await runFn(targetKey, msg.runId)
707
+ return { runId: result && Number.isInteger(result.runId) ? result.runId : msg.runId, counts: null }
708
+ },
709
+ },
710
+ // #5502 Part 2 (BLOCKED upstream) — `repo_relay_dispatch` ("Sync now")
711
+ // slots in HERE once blamechris/repo-relay#168 ships a workflow_dispatch
712
+ // trigger: same shared gates, `gh workflow run repo-relay.yml -R
713
+ // <owner>/<repo> -f ...`, additionally gated on the repo's pinned
714
+ // repo-relay version supporting dispatch (the #5501 drift data already
715
+ // carries the pin). Lands as its own PR when upstream releases.
716
+ }
717
+
718
+ /**
719
+ * #5500/#5502 (epic #5498) — `integration_action` handler. Dispatches to the
720
+ * `integrationActions` registry above; success replies with an
721
+ * `integration_action_ack` (the registry entry's fields + the correlation
722
+ * echo), every failure replies with exactly one INTEGRATION_ACTION_FAILED
723
+ * session_error.
724
+ *
725
+ * SECURITY (docs/security/bearer-token-authority.md checklist): every action
726
+ * execs a binary against a host filesystem path, so two gates run BEFORE any
727
+ * exec — shared here, never per-action:
728
+ * 1. Host-level authority — same bound-vs-unbound check as the surveys: a
729
+ * pairing-bound (share-a-session) client is scoped to one session and
730
+ * must not run host-wide actions.
731
+ * 2. Repo-set membership — the client-supplied `repoPath` is resolved to
732
+ * its realpath and MUST match the realpath of a repo in the surveyed
733
+ * set (config.repos ∪ auto-discovered under controlRoomRoot, the same
734
+ * set `integration_status_request` reports on). A path the survey never
735
+ * showed the operator is rejected; the exec then targets the CANONICAL
736
+ * realpath, never the raw client string — so traversal tricks
737
+ * (`repo/../../etc`) and symlink aliases collapse before comparison.
738
+ *
739
+ * Concurrency: one in-flight action per repo (overlapping requests on the
740
+ * same repo are rejected with a clear error) plus a global cap of
741
+ * MAX_CONCURRENT_INTEGRATION_ACTIONS across all repos and action kinds —
742
+ * rejected, not queued (see the `actionInFlight` note on the shared bucket).
743
+ */
744
+ async function handleIntegrationAction(ws, client, msg, ctx) {
745
+ const config = ctx?.services?.config || {}
746
+
747
+ // Authority gate (#1 above): host-level (unbound) clients only.
748
+ if (client?.boundSessionId) {
749
+ integrationActionError(ws, ctx, msg, 'forbidden',
750
+ 'integration_action requires host-level authority (a session-bound token cannot run host actions)')
751
+ return
752
+ }
753
+
754
+ // Registry lookup (Object.hasOwn so '__proto__'/'constructor' can't match
755
+ // inherited keys). The schema's closed enum already rejects unknown
756
+ // actions at the wire; this is defence in depth.
757
+ const action = typeof msg?.action === 'string' ? msg.action : ''
758
+ const actionEntry = Object.hasOwn(integrationActions, action) ? integrationActions[action] : null
759
+ if (!actionEntry) {
760
+ integrationActionError(ws, ctx, msg, 'unsupported-action',
761
+ `Unsupported integration action: ${action.length > 0 ? action : '(none)'}`)
762
+ return
763
+ }
764
+
765
+ // Defence in depth behind the schema's `min(1)` bound: an absent/empty
766
+ // repoPath must hard-fail HERE, before `resolve()` — `resolve('')` is the
767
+ // daemon's cwd, so falling through would let a malformed in-process message
768
+ // target whatever directory the daemon happened to be launched from.
769
+ const repoPath = typeof msg?.repoPath === 'string' ? msg.repoPath : ''
770
+ if (repoPath.length === 0) {
771
+ integrationActionError(ws, ctx, msg, 'invalid-repo-path',
772
+ 'integration_action requires a non-empty repoPath')
773
+ return
774
+ }
775
+
776
+ // Action-specific request-shape validation (e.g. #5502's required runId),
777
+ // still before any path resolution or exec.
778
+ const invalid = actionEntry.validate(msg)
779
+ if (invalid) {
780
+ integrationActionError(ws, ctx, msg, invalid[0], invalid[1])
781
+ return
782
+ }
783
+
784
+ const root = typeof config.controlRoomRoot === 'string' && config.controlRoomRoot.length > 0
785
+ ? config.controlRoomRoot
786
+ : DEFAULT_CONTROL_ROOM_ROOT
787
+ const repos = Array.isArray(config.repos) ? config.repos : []
788
+
789
+ // Tests inject ctx.resolveRepoSet / ctx.realpath (and the per-action run
790
+ // seams, ctx.runRepoMemoryIndex / ctx.runRepoRelayRerun) to stub fs/exec;
791
+ // production falls through to the real implementations.
792
+ const resolveFn = typeof ctx?.resolveRepoSet === 'function' ? ctx.resolveRepoSet : resolveRepoSet
793
+ const realpathFn = typeof ctx?.realpath === 'function' ? ctx.realpath : realpathSync
794
+
795
+ // Repo-set membership gate (#2 above): canonicalize, then compare.
796
+ let targetKey
797
+ try {
798
+ targetKey = realpathFn(resolve(repoPath))
799
+ } catch {
800
+ integrationActionError(ws, ctx, msg, 'unknown-repo',
801
+ `repoPath does not resolve to a surveyed repo: ${repoPath}`)
802
+ return
803
+ }
804
+ let isMember = false
805
+ try {
806
+ for (const repo of resolveFn({ repos, root })) {
807
+ if (!repo || typeof repo.path !== 'string') continue
808
+ let memberKey
809
+ try {
810
+ memberKey = realpathFn(resolve(repo.path))
811
+ } catch {
812
+ continue
813
+ }
814
+ if (memberKey === targetKey) {
815
+ isMember = true
816
+ break
817
+ }
818
+ }
819
+ } catch (err) {
820
+ integrationActionError(ws, ctx, msg, 'repo-set-failed',
821
+ `Could not resolve the surveyed repo set: ${getErrorMessage(err, 'unknown error')}`)
822
+ return
823
+ }
824
+ if (!isMember) {
825
+ integrationActionError(ws, ctx, msg, 'unknown-repo',
826
+ `repoPath is not a member of the surveyed repo set: ${repoPath}`)
827
+ return
828
+ }
829
+
830
+ // Per-repo overlap guard, then the global cap (reject, never queue). One
831
+ // shared bucket across action kinds — see the `actionInFlight` note.
832
+ if (actionInFlight.has(targetKey)) {
833
+ integrationActionError(ws, ctx, msg, 'action-in-progress',
834
+ `An integration action (${actionInFlight.get(targetKey)}) is already in progress for ${targetKey}`)
835
+ return
836
+ }
837
+ if (actionInFlight.size >= MAX_CONCURRENT_INTEGRATION_ACTIONS) {
838
+ integrationActionError(ws, ctx, msg, 'busy',
839
+ `The host is busy: ${actionInFlight.size} integration actions are already in flight (max ${MAX_CONCURRENT_INTEGRATION_ACTIONS}) — retry when one finishes`)
840
+ return
841
+ }
842
+
843
+ actionInFlight.set(targetKey, action)
844
+ try {
845
+ // Exec against the canonical realpath — never the raw client string.
846
+ const ackFields = await actionEntry.run({ msg, ctx, config, targetKey })
847
+ log.info(`integration_action ${action} completed for ${targetKey} (client=${client?.id})`)
848
+ ctx.transport.send(ws, {
849
+ type: 'integration_action_ack',
850
+ action,
851
+ // Echo the CLIENT-supplied path so the dashboard's pending state
852
+ // (keyed by what it sent) correlates even through a symlink alias.
853
+ repoPath,
854
+ requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
855
+ ...ackFields,
856
+ })
857
+ } catch (err) {
858
+ const message = getErrorMessage(err, `${action} failed`)
859
+ log.warn(`integration_action ${action} failed for ${targetKey}: ${message}`)
860
+ const reason = err && typeof err.reason === 'string' && err.reason.length > 0
861
+ ? err.reason
862
+ : actionEntry.failureReason
863
+ integrationActionError(ws, ctx, msg, reason, message)
864
+ } finally {
865
+ actionInFlight.delete(targetKey)
866
+ }
867
+ }
868
+
869
+ // ───────────────────────────────────────────────────────────────────────────
870
+ // #6134 (epic #5530) — containers_action: stop / restart / destroy a
871
+ // chroxy-managed container or environment.
872
+ // ───────────────────────────────────────────────────────────────────────────
873
+
874
+ /**
875
+ * #6134: per-environment in-flight guard for container lifecycle actions, keyed
876
+ * by environmentId. Independent of the integration-action bucket (different key
877
+ * space, different subprocess fan-out) — same string-keyed Map shape, entries
878
+ * deleted in the handler's `finally`, `.size` doubling as the global gauge.
879
+ */
880
+ const containerActionInFlight = new Map()
881
+ /** #6134: global cap on concurrent container actions (reject, never queue). */
882
+ export const MAX_CONCURRENT_CONTAINER_ACTIONS = 2
883
+
884
+ /**
885
+ * #6134: shared CONTAINER_ACTION_FAILED reply. Mirrors `integrationActionError`:
886
+ * a `session_error` envelope with the stable code, a `reason` discriminator, and
887
+ * the request's correlation fields (`action` / `environmentId` / `requestId`)
888
+ * echoed so the dashboard can clear the exact row's pending state.
889
+ */
890
+ const containerActionError = makeActionError('CONTAINER_ACTION_FAILED', (msg) => ({
891
+ action: typeof msg?.action === 'string' ? msg.action : null,
892
+ environmentId: typeof msg?.environmentId === 'string' ? msg.environmentId : null,
893
+ }))
894
+
895
+ /** #6134: failure `reason` discriminator per action (for CONTAINER_ACTION_FAILED). */
896
+ const CONTAINER_ACTION_FAILURE_REASON = {
897
+ stop: 'stop-failed',
898
+ restart: 'restart-failed',
899
+ destroy: 'destroy-failed',
900
+ }
901
+
902
+ /**
903
+ * #6134 (epic #5530) — `containers_action` handler. Stop / restart / destroy a
904
+ * chroxy-managed environment, replying with exactly one `containers_action_ack`
905
+ * on success or one CONTAINER_ACTION_FAILED `session_error` on failure.
906
+ *
907
+ * SECURITY (docs/security/bearer-token-authority.md checklist):
908
+ * 1. Host-level authority — a pairing-bound (share-a-session) client is scoped
909
+ * to one session and must not run host-wide lifecycle actions.
910
+ * 2. Survey membership — the client-supplied `environmentId` MUST name a live
911
+ * environment the EnvironmentManager tracks (the same set the containers
912
+ * survey reports). An unknown id is rejected; the client id is a lookup
913
+ * key, never a trusted target. Only chroxy's own environments are touchable
914
+ * — never an arbitrary host container.
915
+ *
916
+ * Concurrency: one in-flight action per environment, plus a global cap of
917
+ * MAX_CONCURRENT_CONTAINER_ACTIONS (rejected, not queued).
918
+ */
919
+ async function handleContainersAction(ws, client, msg, ctx) {
920
+ // Authority gate (#1): host-level (unbound) clients only.
921
+ if (client?.boundSessionId) {
922
+ containerActionError(ws, ctx, msg, 'forbidden',
923
+ 'containers_action requires host-level authority (a session-bound token cannot run host actions)')
924
+ return
925
+ }
926
+
927
+ const action = typeof msg?.action === 'string' ? msg.action : ''
928
+ if (action !== 'stop' && action !== 'restart' && action !== 'destroy') {
929
+ containerActionError(ws, ctx, msg, 'unsupported-action',
930
+ `Unsupported container action: ${action.length > 0 ? action : '(none)'}`)
931
+ return
932
+ }
933
+
934
+ const environmentId = typeof msg?.environmentId === 'string' ? msg.environmentId : ''
935
+ if (environmentId.length === 0) {
936
+ containerActionError(ws, ctx, msg, 'invalid-environment-id',
937
+ 'containers_action requires a non-empty environmentId')
938
+ return
939
+ }
940
+
941
+ const envManager = ctx?.services?.environmentManager || null
942
+ if (!envManager || typeof envManager.get !== 'function') {
943
+ containerActionError(ws, ctx, msg, 'no-environment-manager',
944
+ 'Container environments are not enabled on this server')
945
+ return
946
+ }
947
+
948
+ // Survey membership gate (#2): the id MUST name a live environment.
949
+ const env = envManager.get(environmentId)
950
+ if (!env) {
951
+ containerActionError(ws, ctx, msg, 'unknown-environment',
952
+ `environmentId does not name a surveyed environment: ${environmentId}`)
953
+ return
954
+ }
955
+
956
+ // Per-environment overlap guard, then the global cap (reject, never queue).
957
+ if (containerActionInFlight.has(environmentId)) {
958
+ containerActionError(ws, ctx, msg, 'action-in-progress',
959
+ `A container action (${containerActionInFlight.get(environmentId)}) is already in progress for ${environmentId}`)
960
+ return
961
+ }
962
+ if (containerActionInFlight.size >= MAX_CONCURRENT_CONTAINER_ACTIONS) {
963
+ containerActionError(ws, ctx, msg, 'busy',
964
+ `The host is busy: ${containerActionInFlight.size} container actions are already in flight (max ${MAX_CONCURRENT_CONTAINER_ACTIONS}) — retry when one finishes`)
965
+ return
966
+ }
967
+
968
+ containerActionInFlight.set(environmentId, action)
969
+ try {
970
+ let status
971
+ if (action === 'stop') {
972
+ status = await envManager.stop(environmentId)
973
+ } else if (action === 'restart') {
974
+ status = await envManager.restart(environmentId)
975
+ } else {
976
+ await envManager.destroy(environmentId)
977
+ status = 'destroyed'
978
+ }
979
+ log.info(`containers_action ${action} completed for ${environmentId} (client=${client?.id})`)
980
+ ctx.transport.send(ws, {
981
+ type: 'containers_action_ack',
982
+ action,
983
+ environmentId,
984
+ requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
985
+ status: typeof status === 'string' ? status : null,
986
+ })
987
+ } catch (err) {
988
+ const message = getErrorMessage(err, `${action} failed`)
989
+ log.warn(`containers_action ${action} failed for ${environmentId}: ${message}`)
990
+ containerActionError(ws, ctx, msg, CONTAINER_ACTION_FAILURE_REASON[action], message)
991
+ } finally {
992
+ containerActionInFlight.delete(environmentId)
993
+ }
994
+ }
995
+
996
+ // ───────────────────────────────────────────────────────────────────────────
997
+ // #6135 slice 2 (epic #5530) — byok_pool_action: drain / recycle / resize the
998
+ // BYOK warm-container pool.
999
+ // ───────────────────────────────────────────────────────────────────────────
1000
+
1001
+ /**
1002
+ * #6135 slice 2: the BYOK pool is a process-wide singleton, so a single global
1003
+ * in-flight flag serializes all pool mutations (drain/recycle/resize) — they all
1004
+ * mutate the same shared state and must not race. Rejected, never queued.
1005
+ */
1006
+ let byokPoolActionInFlight = false
1007
+
1008
+ /**
1009
+ * #6135 slice 2: shared BYOK_POOL_ACTION_FAILED reply. Mirrors
1010
+ * `containerActionError`: a `session_error` envelope with the stable code, a
1011
+ * `reason` discriminator, and the request's correlation fields (`action` / `key`
1012
+ * / `requestId`) echoed so the dashboard can clear the exact row's pending state.
1013
+ */
1014
+ const byokPoolActionError = makeActionError('BYOK_POOL_ACTION_FAILED', (msg) => ({
1015
+ action: typeof msg?.action === 'string' ? msg.action : null,
1016
+ key: typeof msg?.key === 'string' ? msg.key : null,
1017
+ }))
1018
+
1019
+ /**
1020
+ * #6135 slice 2 (epic #5530) — `byok_pool_action` handler. Drain / recycle /
1021
+ * resize the BYOK warm-container pool, replying with exactly one
1022
+ * `byok_pool_action_ack` on success or one BYOK_POOL_ACTION_FAILED
1023
+ * `session_error` on failure.
1024
+ *
1025
+ * SECURITY (docs/security/bearer-token-authority.md checklist):
1026
+ * 1. Host-level authority — a pairing-bound (share-a-session) client is scoped
1027
+ * to one session and must not run host-wide pool actions.
1028
+ * 2. Survey membership — for `recycle`, the client-supplied `key` MUST name a
1029
+ * bucket the pool's OWN survey (`inspect()`) currently enumerates. An
1030
+ * unknown key is rejected; the client key is a lookup key, never a trusted
1031
+ * target. drain/resize have no client-supplied target — drain acts on all
1032
+ * buckets the pool itself owns; resize is bounded server-side to the
1033
+ * operator-configured ceiling (the pool clamps, never the client).
1034
+ *
1035
+ * Concurrency: a single global in-flight flag — pool mutations are host-wide and
1036
+ * serialized (rejected, not queued).
1037
+ */
1038
+ async function handleByokPoolAction(ws, client, msg, ctx) {
1039
+ // Authority gate (#1): host-level (unbound) clients only.
1040
+ if (client?.boundSessionId) {
1041
+ byokPoolActionError(ws, ctx, msg, 'forbidden',
1042
+ 'byok_pool_action requires host-level authority (a session-bound token cannot run host actions)')
1043
+ return
1044
+ }
1045
+
1046
+ const action = typeof msg?.action === 'string' ? msg.action : ''
1047
+ if (action !== 'drain' && action !== 'recycle' && action !== 'resize') {
1048
+ byokPoolActionError(ws, ctx, msg, 'unsupported-action',
1049
+ `Unsupported BYOK pool action: ${action.length > 0 ? action : '(none)'}`)
1050
+ return
1051
+ }
1052
+
1053
+ // Pool-enabled gate — degrade cleanly when the pool is off (the default).
1054
+ const poolEnabled = typeof ctx?.isPoolEnabled === 'function' ? ctx.isPoolEnabled() : isPoolEnabled(process.env)
1055
+ if (!poolEnabled) {
1056
+ byokPoolActionError(ws, ctx, msg, 'pool-disabled',
1057
+ 'The BYOK container pool is disabled (set CHROXY_DOCKER_BYOK_POOL to enable)')
1058
+ return
1059
+ }
1060
+
1061
+ // Tests inject `ctx.byokPool`; production resolves the shared singleton.
1062
+ const pool = 'byokPool' in (ctx || {}) ? ctx.byokPool : getSharedPool(process.env)
1063
+ if (!pool || typeof pool.drainAll !== 'function') {
1064
+ byokPoolActionError(ws, ctx, msg, 'no-pool',
1065
+ 'BYOK pool is enabled but no pool instance is available yet')
1066
+ return
1067
+ }
1068
+
1069
+ // Validate the recycle target against the pool's OWN survey (#2) BEFORE taking
1070
+ // the in-flight lock, so a bad request fails fast and doesn't block real work.
1071
+ let key = null
1072
+ if (action === 'recycle') {
1073
+ key = typeof msg?.key === 'string' ? msg.key : ''
1074
+ if (key.length === 0) {
1075
+ byokPoolActionError(ws, ctx, msg, 'invalid-key', 'recycle requires a non-empty key')
1076
+ return
1077
+ }
1078
+ // The survey is the ONLY source of truth for a valid target. If the pool
1079
+ // can't be surveyed, fail with a distinct reason rather than misreporting
1080
+ // every key as unknown — the target can't be validated, so we refuse.
1081
+ if (typeof pool.inspect !== 'function') {
1082
+ byokPoolActionError(ws, ctx, msg, 'no-pool',
1083
+ 'BYOK pool cannot be surveyed to validate the recycle target')
1084
+ return
1085
+ }
1086
+ const surveyedKeys = pool.inspect().map((b) => b.key)
1087
+ if (!surveyedKeys.includes(key)) {
1088
+ byokPoolActionError(ws, ctx, msg, 'unknown-key',
1089
+ `key does not name a surveyed pool bucket: ${key}`)
1090
+ return
1091
+ }
1092
+ }
1093
+
1094
+ // Validate resize params: at least one cap, positive integers (the pool clamps
1095
+ // to the configured ceiling — we only reject malformed input here).
1096
+ if (action === 'resize') {
1097
+ const hasPerKey = msg?.maxPerKey !== undefined
1098
+ const hasTotal = msg?.maxTotal !== undefined
1099
+ if (!hasPerKey && !hasTotal) {
1100
+ byokPoolActionError(ws, ctx, msg, 'invalid-resize',
1101
+ 'resize requires at least one of maxPerKey / maxTotal')
1102
+ return
1103
+ }
1104
+ if (hasPerKey && !(Number.isInteger(msg.maxPerKey) && msg.maxPerKey >= 1)) {
1105
+ byokPoolActionError(ws, ctx, msg, 'invalid-resize', 'maxPerKey must be a positive integer')
1106
+ return
1107
+ }
1108
+ if (hasTotal && !(Number.isInteger(msg.maxTotal) && msg.maxTotal >= 1)) {
1109
+ byokPoolActionError(ws, ctx, msg, 'invalid-resize', 'maxTotal must be a positive integer')
1110
+ return
1111
+ }
1112
+ }
1113
+
1114
+ // Global serialization (reject, never queue) — one pool mutation at a time.
1115
+ if (byokPoolActionInFlight) {
1116
+ byokPoolActionError(ws, ctx, msg, 'action-in-progress',
1117
+ 'A BYOK pool action is already in progress')
1118
+ return
1119
+ }
1120
+
1121
+ byokPoolActionInFlight = true
1122
+ try {
1123
+ const ack = {
1124
+ type: 'byok_pool_action_ack',
1125
+ action,
1126
+ key: key || null,
1127
+ requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
1128
+ drained: null,
1129
+ evicted: null,
1130
+ limits: null,
1131
+ configured: null,
1132
+ }
1133
+ if (action === 'drain') {
1134
+ ack.drained = await pool.drainAll()
1135
+ } else if (action === 'recycle') {
1136
+ ack.drained = await pool.recycleKey(key)
1137
+ } else {
1138
+ const result = await pool.resize({ maxPerKey: msg?.maxPerKey, maxTotal: msg?.maxTotal })
1139
+ ack.evicted = result?.evicted ?? 0
1140
+ ack.limits = result?.limits ?? null
1141
+ ack.configured = result?.configured ?? null
1142
+ }
1143
+ log.info(`byok_pool_action ${action} completed (client=${client?.id})`)
1144
+ ctx.transport.send(ws, ack)
1145
+ } catch (err) {
1146
+ const message = getErrorMessage(err, `${action} failed`)
1147
+ log.warn(`byok_pool_action ${action} failed: ${message}`)
1148
+ byokPoolActionError(ws, ctx, msg, `${action}-failed`, message)
1149
+ } finally {
1150
+ byokPoolActionInFlight = false
1151
+ }
1152
+ }
1153
+
1154
+ // ───────────────────────────────────────────────────────────────────────────
1155
+ // #6140 (epic #5530) — host prune guardrails: survey reclaimable chroxy-scoped
1156
+ // orphan docker pressure (host_prune_status_request) + prune it (host_prune_action).
1157
+ // ───────────────────────────────────────────────────────────────────────────
1158
+
1159
+ /** #6140: schema-conformant error reply for the host-prune survey. */
1160
+ function hostPruneErrorSnapshot(requestId, error) {
1161
+ return {
1162
+ type: 'host_prune_status_snapshot',
1163
+ requestId: requestId ?? null,
1164
+ generatedAt: new Date().toISOString(),
1165
+ dockerAvailable: false,
1166
+ note: null,
1167
+ containers: [],
1168
+ images: [],
1169
+ summary: { containerCount: 0, imageCount: 0, reclaimableBytes: 0 },
1170
+ error,
1171
+ }
1172
+ }
1173
+
1174
+ /**
1175
+ * #6140 — host prune survey handler (read-only). Host-authority + per-client
1176
+ * in-flight + degraded-reply contract as the sibling surveys. Surveys ONLY
1177
+ * chroxy's own orphan resources (never arbitrary host containers/images).
1178
+ */
1179
+ const handleHostPruneStatusRequest = makeSurveyHandler({
1180
+ inFlight: hostPruneInFlight,
1181
+ logName: 'host_prune_status_request',
1182
+ forbidden: ({ requestId }) => hostPruneErrorSnapshot(requestId, {
1183
+ code: 'FORBIDDEN',
1184
+ message: 'host_prune_status_request requires host-level authority (a session-bound token cannot survey the host)',
1185
+ }),
1186
+ inProgress: ({ requestId }) => hostPruneErrorSnapshot(requestId, {
1187
+ code: 'SURVEY_IN_PROGRESS',
1188
+ message: 'A host prune survey is already in progress for this client',
1189
+ }),
1190
+ failed: ({ requestId, err }) => hostPruneErrorSnapshot(requestId, {
1191
+ code: 'SURVEY_FAILED',
1192
+ message: getErrorMessage(err, 'host prune survey failed'),
1193
+ }),
1194
+ run: async ({ ctx, requestId }) => {
1195
+ const surveyFn = typeof ctx?.surveyHostPrune === 'function' ? ctx.surveyHostPrune : surveyHostPrune
1196
+ const envManager = ctx?.services?.environmentManager || null
1197
+ const snapshot = await surveyFn({
1198
+ listEnvironments: () => (typeof envManager?.list === 'function' ? envManager.list() : []),
1199
+ })
1200
+ return {
1201
+ type: 'host_prune_status_snapshot',
1202
+ requestId,
1203
+ generatedAt: snapshot.generatedAt,
1204
+ dockerAvailable: snapshot.dockerAvailable,
1205
+ note: snapshot.note ?? null,
1206
+ containers: snapshot.containers,
1207
+ images: snapshot.images,
1208
+ summary: snapshot.summary,
1209
+ }
1210
+ },
1211
+ })
1212
+
1213
+ /**
1214
+ * #6140: a host prune mutates host-wide docker state, so a single global flag
1215
+ * serializes prune actions (rejected, never queued).
1216
+ */
1217
+ let hostPruneActionInFlight = false
1218
+
1219
+ /** #6140: shared HOST_PRUNE_ACTION_FAILED reply (mirrors byokPoolActionError). */
1220
+ const hostPruneActionError = makeActionError('HOST_PRUNE_ACTION_FAILED', (msg) => ({
1221
+ kind: typeof msg?.kind === 'string' ? msg.kind : null,
1222
+ }))
1223
+
1224
+ /**
1225
+ * #6140 (epic #5530) — `host_prune_action` handler. Removes reclaimable
1226
+ * chroxy-scoped orphan docker resources, replying with exactly one
1227
+ * `host_prune_action_ack` on success or one HOST_PRUNE_ACTION_FAILED
1228
+ * `session_error` on failure.
1229
+ *
1230
+ * SECURITY: host-level authority only. The action takes NO target list — it
1231
+ * re-surveys the chroxy-scoped orphan set server-side (`runHostPrune`) and removes
1232
+ * only those exact ids; the client supplies only a `kind` selector. Never a
1233
+ * blanket docker prune, never a running/tracked/non-chroxy resource.
1234
+ */
1235
+ async function handleHostPruneAction(ws, client, msg, ctx) {
1236
+ if (client?.boundSessionId) {
1237
+ hostPruneActionError(ws, ctx, msg, 'forbidden',
1238
+ 'host_prune_action requires host-level authority (a session-bound token cannot run host actions)')
1239
+ return
1240
+ }
1241
+ const kind = typeof msg?.kind === 'string' ? msg.kind : ''
1242
+ if (!PRUNE_KINDS.includes(kind)) {
1243
+ hostPruneActionError(ws, ctx, msg, 'unsupported-kind',
1244
+ `Unsupported prune kind: ${kind.length > 0 ? kind : '(none)'}`)
1245
+ return
1246
+ }
1247
+ if (hostPruneActionInFlight) {
1248
+ hostPruneActionError(ws, ctx, msg, 'action-in-progress', 'A host prune action is already in progress')
1249
+ return
1250
+ }
1251
+ const runFn = typeof ctx?.runHostPrune === 'function' ? ctx.runHostPrune : runHostPrune
1252
+ const envManager = ctx?.services?.environmentManager || null
1253
+ hostPruneActionInFlight = true
1254
+ try {
1255
+ const result = await runFn({
1256
+ kind,
1257
+ listEnvironments: () => (typeof envManager?.list === 'function' ? envManager.list() : []),
1258
+ })
1259
+ log.info(`host_prune_action ${kind} removed ${result.removedContainers}c/${result.removedImages}i (client=${client?.id})`)
1260
+ ctx.transport.send(ws, {
1261
+ type: 'host_prune_action_ack',
1262
+ kind: result.kind,
1263
+ requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
1264
+ dockerAvailable: result.dockerAvailable,
1265
+ removedContainers: result.removedContainers,
1266
+ removedImages: result.removedImages,
1267
+ reclaimedBytes: result.reclaimedBytes,
1268
+ failures: result.failures,
1269
+ })
1270
+ } catch (err) {
1271
+ const message = getErrorMessage(err, 'host prune failed')
1272
+ log.warn(`host_prune_action ${kind} failed: ${message}`)
1273
+ hostPruneActionError(ws, ctx, msg, 'prune-failed', message)
1274
+ } finally {
1275
+ hostPruneActionInFlight = false
1276
+ }
1277
+ }
1278
+
1279
+ // ───────────────────────────────────────────────────────────────────────────
1280
+ // #6136 (epic #5530) — iOS simulator survey (simulator_status_request).
1281
+ // ───────────────────────────────────────────────────────────────────────────
1282
+
1283
+ /** #6136: schema-conformant error reply for the simulator survey. */
1284
+ function simulatorErrorSnapshot(requestId, error) {
1285
+ return {
1286
+ type: 'simulator_status_snapshot',
1287
+ requestId: requestId ?? null,
1288
+ generatedAt: new Date().toISOString(),
1289
+ available: false,
1290
+ note: null,
1291
+ devices: [],
1292
+ readyForMaestro: { ready: false, bootedSimulator: null, metroReachable: false, mockServerReachable: false, reasons: [] },
1293
+ error,
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * #6136 — iOS simulator survey handler (read-only). Host-authority + per-client
1299
+ * in-flight + degraded-reply contract as the sibling surveys. Off macOS / no
1300
+ * xcrun, the survey itself returns a first-class `available:false` snapshot.
1301
+ */
1302
+ const handleSimulatorStatusRequest = makeSurveyHandler({
1303
+ inFlight: simulatorInFlight,
1304
+ logName: 'simulator_status_request',
1305
+ forbidden: ({ requestId }) => simulatorErrorSnapshot(requestId, {
1306
+ code: 'FORBIDDEN',
1307
+ message: 'simulator_status_request requires host-level authority (a session-bound token cannot survey the host)',
1308
+ }),
1309
+ inProgress: ({ requestId }) => simulatorErrorSnapshot(requestId, {
1310
+ code: 'SURVEY_IN_PROGRESS',
1311
+ message: 'A simulator survey is already in progress for this client',
1312
+ }),
1313
+ failed: ({ requestId, err }) => simulatorErrorSnapshot(requestId, {
1314
+ code: 'SURVEY_FAILED',
1315
+ message: getErrorMessage(err, 'simulator survey failed'),
1316
+ }),
1317
+ run: async ({ ctx, requestId }) => {
1318
+ const surveyFn = typeof ctx?.surveySimulators === 'function' ? ctx.surveySimulators : surveySimulators
1319
+ const snapshot = await surveyFn({})
1320
+ return {
1321
+ type: 'simulator_status_snapshot',
1322
+ requestId,
1323
+ generatedAt: snapshot.generatedAt,
1324
+ available: snapshot.available,
1325
+ note: snapshot.note ?? null,
1326
+ devices: snapshot.devices,
1327
+ readyForMaestro: snapshot.readyForMaestro,
1328
+ }
1329
+ },
1330
+ })
1331
+
1332
+ // ───────────────────────────────────────────────────────────────────────────
1333
+ // #6136 slice 2 (epic #5530) — simulator_action: boot / shutdown an iOS sim.
1334
+ // ───────────────────────────────────────────────────────────────────────────
1335
+
1336
+ /**
1337
+ * #6136 slice 2: per-udid in-flight guard for simulator lifecycle actions, keyed
1338
+ * by udid. Same string-keyed Map shape as `containerActionInFlight`; entries
1339
+ * deleted in the handler's `finally`, `.size` doubling as the global gauge.
1340
+ */
1341
+ const simulatorActionInFlight = new Map()
1342
+ /** #6136 slice 2: global cap on concurrent simulator actions (reject, never queue). */
1343
+ export const MAX_CONCURRENT_SIMULATOR_ACTIONS = 2
1344
+
1345
+ /** #6136 slice 2: shared SIMULATOR_ACTION_FAILED reply (mirrors containerActionError). */
1346
+ const simulatorActionError = makeActionError('SIMULATOR_ACTION_FAILED', (msg) => ({
1347
+ action: typeof msg?.action === 'string' ? msg.action : null,
1348
+ udid: typeof msg?.udid === 'string' ? msg.udid : null,
1349
+ }))
1350
+
1351
+ /** #6136 slice 2: failure `reason` discriminator per action (for SIMULATOR_ACTION_FAILED). */
1352
+ const SIMULATOR_ACTION_FAILURE_REASON = {
1353
+ boot: 'boot-failed',
1354
+ shutdown: 'shutdown-failed',
1355
+ }
1356
+
1357
+ /**
1358
+ * #6136 slice 2 (epic #5530) — `simulator_action` handler. Boot / shut down a
1359
+ * surveyed iOS simulator, replying with exactly one `simulator_action_ack` on
1360
+ * success or one SIMULATOR_ACTION_FAILED `session_error` on failure.
1361
+ *
1362
+ * SECURITY (docs/security/bearer-token-authority.md checklist):
1363
+ * 1. Host-level authority — a pairing-bound (share-a-session) client is scoped
1364
+ * to one session and must not run host-wide simulator actions.
1365
+ * 2. Survey membership — the client-supplied `udid` MUST name a device the
1366
+ * fresh `surveySimulators` enumerates. An unknown udid is rejected; the
1367
+ * client id is a lookup key, never a trusted target. State-gated too: boot
1368
+ * only a non-booted device, shutdown only a booted one (clear reasons, and
1369
+ * avoids a pointless simctl error on an already-{booted,shutdown} device).
1370
+ *
1371
+ * Non-destructive (no data loss), so no UI confirm gate. Concurrency: one
1372
+ * in-flight action per udid, plus a global cap of MAX_CONCURRENT_SIMULATOR_ACTIONS
1373
+ * (rejected, not queued).
1374
+ */
1375
+ async function handleSimulatorAction(ws, client, msg, ctx) {
1376
+ // Authority gate (#1): host-level (unbound) clients only.
1377
+ if (client?.boundSessionId) {
1378
+ simulatorActionError(ws, ctx, msg, 'forbidden',
1379
+ 'simulator_action requires host-level authority (a session-bound token cannot run host actions)')
1380
+ return
1381
+ }
1382
+
1383
+ const action = typeof msg?.action === 'string' ? msg.action : ''
1384
+ if (!SIMULATOR_ACTIONS.includes(action)) {
1385
+ simulatorActionError(ws, ctx, msg, 'unsupported-action',
1386
+ `Unsupported simulator action: ${action.length > 0 ? action : '(none)'}`)
1387
+ return
1388
+ }
1389
+
1390
+ const udid = typeof msg?.udid === 'string' ? msg.udid : ''
1391
+ if (udid.length === 0) {
1392
+ simulatorActionError(ws, ctx, msg, 'invalid-udid',
1393
+ 'simulator_action requires a non-empty udid')
1394
+ return
1395
+ }
1396
+
1397
+ // Concurrency guard BEFORE the expensive survey: fast-reject a duplicate
1398
+ // same-udid request (or a host-busy one) WITHOUT shelling out to simctl + port
1399
+ // probes. The `.has()` check and the `.set()` below are synchronous-adjacent
1400
+ // (no await between them), so the guard stays race-free. Mirrors the host-prune
1401
+ // handler, which guards in-flight before its survey-bearing run.
1402
+ if (simulatorActionInFlight.has(udid)) {
1403
+ simulatorActionError(ws, ctx, msg, 'action-in-progress',
1404
+ `A simulator action (${simulatorActionInFlight.get(udid)}) is already in progress for ${udid}`)
1405
+ return
1406
+ }
1407
+ if (simulatorActionInFlight.size >= MAX_CONCURRENT_SIMULATOR_ACTIONS) {
1408
+ simulatorActionError(ws, ctx, msg, 'busy',
1409
+ `The host is busy: ${simulatorActionInFlight.size} simulator actions are already in flight (max ${MAX_CONCURRENT_SIMULATOR_ACTIONS}) — retry when one finishes`)
1410
+ return
1411
+ }
1412
+
1413
+ const surveyFn = typeof ctx?.surveySimulators === 'function' ? ctx.surveySimulators : surveySimulators
1414
+ const runFn = typeof ctx?.runSimulatorAction === 'function' ? ctx.runSimulatorAction : runSimulatorAction
1415
+ simulatorActionInFlight.set(udid, action)
1416
+ try {
1417
+ // Survey membership gate (#2): re-survey and validate the target server-side.
1418
+ let snapshot
1419
+ try {
1420
+ snapshot = await surveyFn({})
1421
+ } catch (err) {
1422
+ simulatorActionError(ws, ctx, msg, 'survey-failed',
1423
+ getErrorMessage(err, 'simulator survey failed'))
1424
+ return
1425
+ }
1426
+ if (!snapshot?.available) {
1427
+ simulatorActionError(ws, ctx, msg, 'unavailable',
1428
+ snapshot?.note || 'iOS simulators are not available on this host')
1429
+ return
1430
+ }
1431
+ const device = (Array.isArray(snapshot.devices) ? snapshot.devices : []).find((d) => d.udid === udid) || null
1432
+ if (!device) {
1433
+ simulatorActionError(ws, ctx, msg, 'unknown-device',
1434
+ `udid does not name a surveyed simulator: ${udid}`)
1435
+ return
1436
+ }
1437
+ // State gate: boot a non-booted device, shutdown a booted one.
1438
+ if (action === 'boot' && device.state === 'Booted') {
1439
+ simulatorActionError(ws, ctx, msg, 'already-booted',
1440
+ `Simulator ${device.name} is already booted`)
1441
+ return
1442
+ }
1443
+ if (action === 'shutdown' && device.state !== 'Booted') {
1444
+ simulatorActionError(ws, ctx, msg, 'not-booted',
1445
+ `Simulator ${device.name} is not booted (state: ${device.state})`)
1446
+ return
1447
+ }
1448
+
1449
+ // Pass the server-trusted, survey-validated udid (not the raw client string)
1450
+ // to the exec — makes the trust boundary self-evident at the call site and
1451
+ // survives any future loosening of the `.find` match predicate above.
1452
+ const status = await runFn({ action, udid: device.udid })
1453
+ log.info(`simulator_action ${action} completed for ${udid} (client=${client?.id})`)
1454
+ ctx.transport.send(ws, {
1455
+ type: 'simulator_action_ack',
1456
+ action,
1457
+ udid,
1458
+ requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
1459
+ status: typeof status === 'string' ? status : null,
1460
+ })
1461
+ } catch (err) {
1462
+ const message = getErrorMessage(err, `${action} failed`)
1463
+ log.warn(`simulator_action ${action} failed for ${udid}: ${message}`)
1464
+ simulatorActionError(ws, ctx, msg, SIMULATOR_ACTION_FAILURE_REASON[action], message)
1465
+ } finally {
1466
+ simulatorActionInFlight.delete(udid)
1467
+ }
1468
+ }
1469
+
1470
+ // ───────────────────────────────────────────────────────────────────────────
1471
+ // #6137 (epic #5530) — Android emulator survey (emulator_status_request) +
1472
+ // boot/kill action (emulator_action). Shares the Device runtimes tab with iOS.
1473
+ // ───────────────────────────────────────────────────────────────────────────
1474
+
1475
+ /** #6137: schema-conformant error reply for the emulator survey. */
1476
+ function emulatorErrorSnapshot(requestId, error) {
1477
+ return {
1478
+ type: 'emulator_status_snapshot',
1479
+ requestId: requestId ?? null,
1480
+ generatedAt: new Date().toISOString(),
1481
+ available: false,
1482
+ note: null,
1483
+ devices: [],
1484
+ readyForMaestro: { ready: false, runningDevice: null, metroReachable: false, mockServerReachable: false, reasons: [] },
1485
+ error,
1486
+ }
1487
+ }
1488
+
1489
+ /**
1490
+ * #6137 — Android emulator survey handler (read-only). Same host-authority +
1491
+ * per-client in-flight + degraded-reply contract as the iOS sibling. No Android
1492
+ * SDK → the survey itself returns a first-class `available:false` snapshot.
1493
+ */
1494
+ const handleEmulatorStatusRequest = makeSurveyHandler({
1495
+ inFlight: emulatorInFlight,
1496
+ logName: 'emulator_status_request',
1497
+ forbidden: ({ requestId }) => emulatorErrorSnapshot(requestId, {
1498
+ code: 'FORBIDDEN',
1499
+ message: 'emulator_status_request requires host-level authority (a session-bound token cannot survey the host)',
1500
+ }),
1501
+ inProgress: ({ requestId }) => emulatorErrorSnapshot(requestId, {
1502
+ code: 'SURVEY_IN_PROGRESS',
1503
+ message: 'An emulator survey is already in progress for this client',
1504
+ }),
1505
+ failed: ({ requestId, err }) => emulatorErrorSnapshot(requestId, {
1506
+ code: 'SURVEY_FAILED',
1507
+ message: getErrorMessage(err, 'emulator survey failed'),
1508
+ }),
1509
+ run: async ({ ctx, requestId }) => {
1510
+ const surveyFn = typeof ctx?.surveyEmulators === 'function' ? ctx.surveyEmulators : surveyEmulators
1511
+ const snapshot = await surveyFn({})
1512
+ return {
1513
+ type: 'emulator_status_snapshot',
1514
+ requestId,
1515
+ generatedAt: snapshot.generatedAt,
1516
+ available: snapshot.available,
1517
+ note: snapshot.note ?? null,
1518
+ devices: snapshot.devices,
1519
+ readyForMaestro: snapshot.readyForMaestro,
1520
+ }
1521
+ },
1522
+ })
1523
+
1524
+ /**
1525
+ * #6137: per-target in-flight guard for emulator lifecycle actions, keyed by the
1526
+ * target id (the avd for boot, the serial for kill). Same string-keyed Map shape
1527
+ * as the simulator action guard; `.size` doubles as the global gauge.
1528
+ */
1529
+ const emulatorActionInFlight = new Map()
1530
+ /** #6137: global cap on concurrent emulator actions (reject, never queue). */
1531
+ export const MAX_CONCURRENT_EMULATOR_ACTIONS = 2
1532
+
1533
+ /** #6137: shared EMULATOR_ACTION_FAILED reply (mirrors simulatorActionError). */
1534
+ const emulatorActionError = makeActionError('EMULATOR_ACTION_FAILED', (msg) => ({
1535
+ action: typeof msg?.action === 'string' ? msg.action : null,
1536
+ avd: typeof msg?.avd === 'string' ? msg.avd : null,
1537
+ serial: typeof msg?.serial === 'string' ? msg.serial : null,
1538
+ }))
1539
+
1540
+ /** #6137: failure `reason` discriminator per action (for EMULATOR_ACTION_FAILED). */
1541
+ const EMULATOR_ACTION_FAILURE_REASON = {
1542
+ boot: 'boot-failed',
1543
+ kill: 'kill-failed',
1544
+ }
1545
+
1546
+ /**
1547
+ * #6137 (epic #5530) — `emulator_action` handler. Boot an AVD / kill a running
1548
+ * emulator, replying with exactly one `emulator_action_ack` on success or one
1549
+ * EMULATOR_ACTION_FAILED `session_error` on failure.
1550
+ *
1551
+ * SECURITY (docs/security/bearer-token-authority.md checklist):
1552
+ * 1. Host-level authority — a pairing-bound client cannot run host actions.
1553
+ * 2. Survey membership — the client-supplied target (`avd` for boot, `serial`
1554
+ * for kill) MUST name a device the fresh `surveyEmulators` enumerates, in
1555
+ * the right state (boot a STOPPED avd, kill a RUNNING serial). The client
1556
+ * value is a lookup key, never a trusted path — kill never targets a
1557
+ * non-enumerated device.
1558
+ *
1559
+ * Non-destructive (an emulator holds no unsaved host state), so no confirm gate.
1560
+ * Concurrency: one in-flight action per target, plus a global cap of
1561
+ * MAX_CONCURRENT_EMULATOR_ACTIONS (rejected, not queued).
1562
+ */
1563
+ async function handleEmulatorAction(ws, client, msg, ctx) {
1564
+ if (client?.boundSessionId) {
1565
+ emulatorActionError(ws, ctx, msg, 'forbidden',
1566
+ 'emulator_action requires host-level authority (a session-bound token cannot run host actions)')
1567
+ return
1568
+ }
1569
+
1570
+ const action = typeof msg?.action === 'string' ? msg.action : ''
1571
+ if (!EMULATOR_ACTIONS.includes(action)) {
1572
+ emulatorActionError(ws, ctx, msg, 'unsupported-action',
1573
+ `Unsupported emulator action: ${action.length > 0 ? action : '(none)'}`)
1574
+ return
1575
+ }
1576
+
1577
+ // The target id depends on the action: boot keys on the avd, kill on serial.
1578
+ const avd = typeof msg?.avd === 'string' ? msg.avd : ''
1579
+ const serial = typeof msg?.serial === 'string' ? msg.serial : ''
1580
+ const targetId = action === 'boot' ? avd : serial
1581
+ if (targetId.length === 0) {
1582
+ emulatorActionError(ws, ctx, msg, action === 'boot' ? 'invalid-avd' : 'invalid-serial',
1583
+ action === 'boot' ? 'emulator_action boot requires a non-empty avd' : 'emulator_action kill requires a non-empty serial')
1584
+ return
1585
+ }
1586
+
1587
+ // Concurrency guard BEFORE the expensive survey (fast-reject duplicates without
1588
+ // shelling out). `.has()`/`.set()` stay synchronous-adjacent so it's race-free.
1589
+ if (emulatorActionInFlight.has(targetId)) {
1590
+ emulatorActionError(ws, ctx, msg, 'action-in-progress',
1591
+ `An emulator action (${emulatorActionInFlight.get(targetId)}) is already in progress for ${targetId}`)
1592
+ return
1593
+ }
1594
+ if (emulatorActionInFlight.size >= MAX_CONCURRENT_EMULATOR_ACTIONS) {
1595
+ emulatorActionError(ws, ctx, msg, 'busy',
1596
+ `The host is busy: ${emulatorActionInFlight.size} emulator actions are already in flight (max ${MAX_CONCURRENT_EMULATOR_ACTIONS}) — retry when one finishes`)
1597
+ return
1598
+ }
1599
+
1600
+ const surveyFn = typeof ctx?.surveyEmulators === 'function' ? ctx.surveyEmulators : surveyEmulators
1601
+ const runFn = typeof ctx?.runEmulatorAction === 'function' ? ctx.runEmulatorAction : runEmulatorAction
1602
+ emulatorActionInFlight.set(targetId, action)
1603
+ try {
1604
+ // Survey membership gate (#2): re-survey and validate the target server-side.
1605
+ let snapshot
1606
+ try {
1607
+ snapshot = await surveyFn({})
1608
+ } catch (err) {
1609
+ emulatorActionError(ws, ctx, msg, 'survey-failed',
1610
+ getErrorMessage(err, 'emulator survey failed'))
1611
+ return
1612
+ }
1613
+ if (!snapshot?.available) {
1614
+ emulatorActionError(ws, ctx, msg, 'unavailable',
1615
+ snapshot?.note || 'Android emulators are not available on this host')
1616
+ return
1617
+ }
1618
+ const devices = Array.isArray(snapshot.devices) ? snapshot.devices : []
1619
+ if (action === 'boot') {
1620
+ const device = devices.find((d) => d.avd === avd) || null
1621
+ if (!device) {
1622
+ emulatorActionError(ws, ctx, msg, 'unknown-avd', `avd does not name a surveyed emulator: ${avd}`)
1623
+ return
1624
+ }
1625
+ // Reject if it's already live (running OR starting) — booting again would
1626
+ // spawn a duplicate emulator process.
1627
+ if (device.state !== 'stopped') {
1628
+ emulatorActionError(ws, ctx, msg, 'already-running', `Emulator ${avd} is already ${device.state}`)
1629
+ return
1630
+ }
1631
+ } else {
1632
+ const device = devices.find((d) => d.serial === serial) || null
1633
+ if (!device) {
1634
+ emulatorActionError(ws, ctx, msg, 'unknown-serial', `serial does not name a surveyed emulator: ${serial}`)
1635
+ return
1636
+ }
1637
+ // Kill targets any live emulator (running OR starting) — only a stopped
1638
+ // device (no live process) is invalid.
1639
+ if (device.state === 'stopped') {
1640
+ emulatorActionError(ws, ctx, msg, 'not-running', `Emulator ${serial} is not running`)
1641
+ return
1642
+ }
1643
+ }
1644
+
1645
+ const status = await runFn({
1646
+ action,
1647
+ avd: action === 'boot' ? avd : undefined,
1648
+ serial: action === 'kill' ? serial : undefined,
1649
+ headless: msg?.headless === true,
1650
+ })
1651
+ log.info(`emulator_action ${action} completed for ${targetId} (client=${client?.id})`)
1652
+ ctx.transport.send(ws, {
1653
+ type: 'emulator_action_ack',
1654
+ action,
1655
+ avd: action === 'boot' ? avd : null,
1656
+ serial: action === 'kill' ? serial : null,
1657
+ requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
1658
+ status: typeof status === 'string' ? status : null,
1659
+ })
1660
+ } catch (err) {
1661
+ const message = getErrorMessage(err, `${action} failed`)
1662
+ log.warn(`emulator_action ${action} failed for ${targetId}: ${message}`)
1663
+ emulatorActionError(ws, ctx, msg, EMULATOR_ACTION_FAILURE_REASON[action], message)
1664
+ } finally {
1665
+ emulatorActionInFlight.delete(targetId)
1666
+ }
1667
+ }
1668
+
1669
+ // ───────────────────────────────────────────────────────────────────────────
1670
+ // #6138 (epic #5530) — WSL2 distro survey (wsl_status_request) + start/terminate
1671
+ // action (wsl_action). Shares the Device runtimes tab. Windows-host-only; off
1672
+ // Windows the survey itself returns a first-class available:false snapshot.
1673
+ // ───────────────────────────────────────────────────────────────────────────
1674
+
1675
+ /** #6138: schema-conformant error reply for the WSL survey. */
1676
+ function wslErrorSnapshot(requestId, error) {
1677
+ return {
1678
+ type: 'wsl_status_snapshot',
1679
+ requestId: requestId ?? null,
1680
+ generatedAt: new Date().toISOString(),
1681
+ available: false,
1682
+ note: null,
1683
+ defaultDistro: null,
1684
+ distros: [],
1685
+ error,
1686
+ }
1687
+ }
1688
+
1689
+ /**
1690
+ * #6138 — WSL2 distro survey handler (read-only). Same host-authority +
1691
+ * per-client in-flight + degraded-reply contract as the iOS/Android siblings.
1692
+ * Off Windows / no wsl.exe, the survey itself returns available:false.
1693
+ */
1694
+ const handleWslStatusRequest = makeSurveyHandler({
1695
+ inFlight: wslInFlight,
1696
+ logName: 'wsl_status_request',
1697
+ forbidden: ({ requestId }) => wslErrorSnapshot(requestId, {
1698
+ code: 'FORBIDDEN',
1699
+ message: 'wsl_status_request requires host-level authority (a session-bound token cannot survey the host)',
1700
+ }),
1701
+ inProgress: ({ requestId }) => wslErrorSnapshot(requestId, {
1702
+ code: 'SURVEY_IN_PROGRESS',
1703
+ message: 'A WSL survey is already in progress for this client',
1704
+ }),
1705
+ failed: ({ requestId, err }) => wslErrorSnapshot(requestId, {
1706
+ code: 'SURVEY_FAILED',
1707
+ message: getErrorMessage(err, 'WSL survey failed'),
1708
+ }),
1709
+ run: async ({ ctx, requestId }) => {
1710
+ const surveyFn = typeof ctx?.surveyWsl === 'function' ? ctx.surveyWsl : surveyWsl
1711
+ const snapshot = await surveyFn({})
1712
+ return {
1713
+ type: 'wsl_status_snapshot',
1714
+ requestId,
1715
+ generatedAt: snapshot.generatedAt,
1716
+ available: snapshot.available,
1717
+ note: snapshot.note ?? null,
1718
+ defaultDistro: snapshot.defaultDistro ?? null,
1719
+ distros: snapshot.distros,
1720
+ }
1721
+ },
1722
+ })
1723
+
1724
+ /**
1725
+ * #6138: per-distro in-flight guard for WSL lifecycle actions, keyed by distro
1726
+ * name. Same string-keyed Map shape as the emulator guard; `.size` doubles as
1727
+ * the global gauge.
1728
+ */
1729
+ const wslActionInFlight = new Map()
1730
+ /** #6138: global cap on concurrent WSL actions (reject, never queue). */
1731
+ export const MAX_CONCURRENT_WSL_ACTIONS = 2
1732
+
1733
+ /** #6138: shared WSL_ACTION_FAILED reply (mirrors emulatorActionError). */
1734
+ const wslActionError = makeActionError('WSL_ACTION_FAILED', (msg) => ({
1735
+ action: typeof msg?.action === 'string' ? msg.action : null,
1736
+ distro: typeof msg?.distro === 'string' ? msg.distro : null,
1737
+ }))
1738
+
1739
+ /** #6138: failure `reason` discriminator per action (for WSL_ACTION_FAILED). */
1740
+ const WSL_ACTION_FAILURE_REASON = {
1741
+ start: 'start-failed',
1742
+ terminate: 'terminate-failed',
1743
+ }
1744
+
1745
+ /**
1746
+ * #6138 (epic #5530) — `wsl_action` handler. Start / terminate a surveyed WSL2
1747
+ * distro, replying with exactly one `wsl_action_ack` on success or one
1748
+ * WSL_ACTION_FAILED `session_error` on failure.
1749
+ *
1750
+ * SECURITY (docs/security/bearer-token-authority.md checklist):
1751
+ * 1. Host-level authority — a session-bound token cannot run host actions.
1752
+ * 2. Survey membership — the client-supplied `distro` MUST name a distro the
1753
+ * fresh `surveyWsl` enumerates; the client value is a lookup key, never a
1754
+ * trusted target. State-gated: start a non-running distro, terminate a
1755
+ * running one (terminate never targets a distro the survey didn't list).
1756
+ *
1757
+ * Concurrency: one in-flight action per distro, plus a global cap of
1758
+ * MAX_CONCURRENT_WSL_ACTIONS (rejected, not queued). The duplicate fast-reject
1759
+ * happens before the survey (the .has()/.set() stay synchronous-adjacent).
1760
+ */
1761
+ async function handleWslAction(ws, client, msg, ctx) {
1762
+ if (client?.boundSessionId) {
1763
+ wslActionError(ws, ctx, msg, 'forbidden',
1764
+ 'wsl_action requires host-level authority (a session-bound token cannot run host actions)')
1765
+ return
1766
+ }
1767
+
1768
+ const action = typeof msg?.action === 'string' ? msg.action : ''
1769
+ if (!WSL_ACTIONS.includes(action)) {
1770
+ wslActionError(ws, ctx, msg, 'unsupported-action',
1771
+ `Unsupported WSL action: ${action.length > 0 ? action : '(none)'}`)
1772
+ return
1773
+ }
1774
+
1775
+ const distro = typeof msg?.distro === 'string' ? msg.distro : ''
1776
+ if (distro.length === 0) {
1777
+ wslActionError(ws, ctx, msg, 'invalid-distro', 'wsl_action requires a non-empty distro')
1778
+ return
1779
+ }
1780
+
1781
+ // Concurrency guard BEFORE the expensive survey (fast-reject duplicates).
1782
+ if (wslActionInFlight.has(distro)) {
1783
+ wslActionError(ws, ctx, msg, 'action-in-progress',
1784
+ `A WSL action (${wslActionInFlight.get(distro)}) is already in progress for ${distro}`)
1785
+ return
1786
+ }
1787
+ if (wslActionInFlight.size >= MAX_CONCURRENT_WSL_ACTIONS) {
1788
+ wslActionError(ws, ctx, msg, 'busy',
1789
+ `The host is busy: ${wslActionInFlight.size} WSL actions are already in flight (max ${MAX_CONCURRENT_WSL_ACTIONS}) — retry when one finishes`)
1790
+ return
1791
+ }
1792
+
1793
+ const surveyFn = typeof ctx?.surveyWsl === 'function' ? ctx.surveyWsl : surveyWsl
1794
+ const runFn = typeof ctx?.runWslAction === 'function' ? ctx.runWslAction : runWslAction
1795
+ wslActionInFlight.set(distro, action)
1796
+ try {
1797
+ let snapshot
1798
+ try {
1799
+ snapshot = await surveyFn({})
1800
+ } catch (err) {
1801
+ wslActionError(ws, ctx, msg, 'survey-failed', getErrorMessage(err, 'WSL survey failed'))
1802
+ return
1803
+ }
1804
+ if (!snapshot?.available) {
1805
+ wslActionError(ws, ctx, msg, 'unavailable', snapshot?.note || 'WSL is not available on this host')
1806
+ return
1807
+ }
1808
+ const device = (Array.isArray(snapshot.distros) ? snapshot.distros : []).find((d) => d.name === distro) || null
1809
+ if (!device) {
1810
+ wslActionError(ws, ctx, msg, 'unknown-distro', `distro does not name a surveyed WSL distro: ${distro}`)
1811
+ return
1812
+ }
1813
+ // State gates are DEFAULT-CLOSED (#6174, matching the emulator sibling): start
1814
+ // only an explicitly Stopped distro, terminate only a Running one. A distro in
1815
+ // a transitional state ("Installing"/"Converting"/…) matches neither, so we
1816
+ // don't poke wsl.exe mid-transition.
1817
+ if (action === 'start' && device.state !== 'Stopped') {
1818
+ wslActionError(ws, ctx, msg, 'not-stopped', `Distro ${distro} is not stopped (state: ${device.state})`)
1819
+ return
1820
+ }
1821
+ if (action === 'terminate' && device.state !== 'Running') {
1822
+ wslActionError(ws, ctx, msg, 'not-running', `Distro ${distro} is not running (state: ${device.state})`)
1823
+ return
1824
+ }
1825
+
1826
+ const status = await runFn({ action, distro })
1827
+ log.info(`wsl_action ${action} completed for ${distro} (client=${client?.id})`)
1828
+ ctx.transport.send(ws, {
1829
+ type: 'wsl_action_ack',
1830
+ action,
1831
+ distro,
1832
+ requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
1833
+ status: typeof status === 'string' ? status : null,
1834
+ })
1835
+ } catch (err) {
1836
+ const message = getErrorMessage(err, `${action} failed`)
1837
+ log.warn(`wsl_action ${action} failed for ${distro}: ${message}`)
1838
+ wslActionError(ws, ctx, msg, WSL_ACTION_FAILURE_REASON[action], message)
1839
+ } finally {
1840
+ wslActionInFlight.delete(distro)
1841
+ }
1842
+ }
1843
+
1844
+ /**
1845
+ * #5914 follow-up — reply to a `mailbox_status_request` with a point-in-time
1846
+ * snapshot of the daemon's mailbox state for the Control Room "Mailbox" tab:
1847
+ * the live `agentCommId -> session` registrations plus a bounded ring buffer of
1848
+ * recent live-interrupt deliveries (newest first). Reads in-memory SessionManager
1849
+ * state only (no git/gh survey), so unlike the host/runner surveys it is
1850
+ * synchronous and has no in-flight guard.
1851
+ *
1852
+ * Host-level survey: a pairing-bound (share-a-session) token is rejected, like
1853
+ * `host_status_request`. On refusal it still replies with a schema-valid
1854
+ * snapshot (empty arrays) carrying an additive `error` annotation so the tab can
1855
+ * render the refusal rather than spin forever.
1856
+ */
1857
+ const handleMailboxStatusRequest = makeSyncHostSurvey({
1858
+ type: 'mailbox_status_snapshot',
1859
+ emptyFields: { registrations: [], recentEvents: [] },
1860
+ forbiddenMessage: 'mailbox_status_request requires host-level authority (a session-bound token cannot survey the host)',
1861
+ resolve: (ctx) => {
1862
+ const sm = ctx?.sessions?.sessionManager
1863
+ return {
1864
+ registrations: typeof sm?.listAgentCommRegistrations === 'function' ? sm.listAgentCommRegistrations() : [],
1865
+ recentEvents: typeof sm?.getMailboxEvents === 'function' ? sm.getMailboxEvents() : [],
1866
+ }
1867
+ },
1868
+ })
1869
+
1870
+ /**
1871
+ * #5969 (epic #5422 phase 4) — reply to an `external_sessions_request` with a
1872
+ * point-in-time snapshot of the LIVE external Claude Code sessions the daemon
1873
+ * learned about over `POST /api/events` (sessions it did NOT launch). Read-only:
1874
+ * mission control renders these alongside daemon-managed sessions but offers no
1875
+ * control affordances (there is no PTY/handle for an external session). Reads
1876
+ * in-memory SessionManager state only, so — like the mailbox survey — it is
1877
+ * synchronous and has no in-flight guard.
1878
+ *
1879
+ * Host-level survey: a pairing-bound (share-a-session) token is rejected, like
1880
+ * `host_status_request`. On refusal it still replies with a schema-valid empty
1881
+ * snapshot carrying an additive `error` so the view renders the refusal rather
1882
+ * than spin.
1883
+ */
1884
+ const handleExternalSessionsRequest = makeSyncHostSurvey({
1885
+ type: 'external_sessions_snapshot',
1886
+ emptyFields: { sessions: [] },
1887
+ forbiddenMessage: 'external_sessions_request requires host-level authority (a session-bound token cannot survey the host)',
1888
+ resolve: (ctx) => {
1889
+ const sm = ctx?.sessions?.sessionManager
1890
+ return {
1891
+ sessions: typeof sm?.getExternalSessions === 'function' ? sm.getExternalSessions() : [],
1892
+ }
1893
+ },
1894
+ })
1895
+
1896
+ /**
1897
+ * #5966 (epic #5422 phase 5) — reply to a `repo_events_request` with a
1898
+ * point-in-time snapshot of the GitHub-webhook repo events the daemon buffered
1899
+ * in its bounded RepoEventStore (github-webhook.js, HMAC-verified ingest #6468).
1900
+ * Reads the in-memory store only (no git/gh survey), so — like the mailbox /
1901
+ * external-session surveys — it is synchronous and has no in-flight guard. The
1902
+ * store is lazily created on the first webhook delivery, so a null store is the
1903
+ * valid "nothing buffered yet" state and yields an empty (schema-valid) feed.
1904
+ *
1905
+ * A bounded tail (`limit: 50`) keeps the snapshot small even though the store
1906
+ * caps at 200 — the pane shows recent activity, not the whole ring. Host-level
1907
+ * survey: a pairing-bound (share-a-session) token is rejected, like
1908
+ * `host_status_request`, still with a schema-valid empty snapshot carrying an
1909
+ * additive `error` so the pane renders the refusal rather than spinning.
1910
+ */
1911
+ const handleRepoEventsRequest = makeSyncHostSurvey({
1912
+ type: 'repo_events_snapshot',
1913
+ emptyFields: { events: [] },
1914
+ forbiddenMessage: 'repo_events_request requires host-level authority (a session-bound token cannot survey the host)',
1915
+ resolve: (ctx) => {
1916
+ const store = ctx?.services?.repoEventStore
1917
+ return {
1918
+ events: typeof store?.list === 'function' ? store.list({ limit: 50 }) : [],
1919
+ }
1920
+ },
1921
+ })
1922
+
1923
+ export const controlRoomHandlers = {
1924
+ host_status_request: handleHostStatusRequest,
1925
+ runner_status_request: handleRunnerStatusRequest,
1926
+ containers_status_request: handleContainersStatusRequest,
1927
+ repo_runtime_config_request: handleRepoRuntimeConfigRequest,
1928
+ byok_pool_status_request: handleByokPoolStatusRequest,
1929
+ host_prune_status_request: handleHostPruneStatusRequest,
1930
+ simulator_status_request: handleSimulatorStatusRequest,
1931
+ emulator_status_request: handleEmulatorStatusRequest,
1932
+ wsl_status_request: handleWslStatusRequest,
1933
+ containers_action: handleContainersAction,
1934
+ byok_pool_action: handleByokPoolAction,
1935
+ host_prune_action: handleHostPruneAction,
1936
+ simulator_action: handleSimulatorAction,
1937
+ emulator_action: handleEmulatorAction,
1938
+ wsl_action: handleWslAction,
1939
+ integration_status_request: handleIntegrationStatusRequest,
1940
+ skills_inventory_request: handleSkillsInventoryRequest,
1941
+ mailbox_status_request: handleMailboxStatusRequest,
1942
+ external_sessions_request: handleExternalSessionsRequest,
1943
+ repo_events_request: handleRepoEventsRequest,
1944
+ integration_action: handleIntegrationAction,
1945
+ }