@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,95 @@
1
+ /**
2
+ * #7596 — environment-surface authority for pairing-bound (share-a-session)
3
+ * clients.
4
+ *
5
+ * The container-environment surface is host-level: an environment outlives any
6
+ * one session and its descriptor carries host metadata (the `sessions` roster
7
+ * wired #7552, plus `cwd` = an absolute host path, `image`, `containerId`,
8
+ * `containerUser`, `containerCliPath`). docs/security/bearer-token-authority.md's
9
+ * rule is that a bound token learns NOTHING host-level: every Control Room host
10
+ * survey (containers, repo-runtime, byok-pool, …) and `destroy_environment`
11
+ * (#7571) already REFUSE bound clients rather than hand them a partial view.
12
+ *
13
+ * #7576 briefly redacted just the `sessions` roster for bound clients on the
14
+ * theory they might need the env ids for a picker; #7596 retired that — a bound
15
+ * client cannot `create_session` (that handler refuses bound tokens), so it has
16
+ * no picker, and the sessions-only redaction still leaked the host metadata
17
+ * above. So bound clients are REFUSED `list_environments` / `get_environment`
18
+ * and are excluded from the `environment_list` broadcasts entirely, matching the
19
+ * rest of the host surface.
20
+ *
21
+ * WHO IS "BOUND" — fail SAFE. A client is treated as bound unless it is
22
+ * DEFINITELY an unbound host client: a real client object whose `boundSessionId`
23
+ * is null/undefined. This matches the server's canonical `boundSessionId == null`
24
+ * bound-check (ws-server.js, #4787), which deliberately treats the unlikely
25
+ * empty-string id as bound — a truthy `client.boundSessionId` check would
26
+ * misclassify `''` as unbound and leak the surface (Copilot, #7595 review). It
27
+ * also fails CLOSED on a nullish client, the safe direction for a security check,
28
+ * even though WS dispatch guarantees an authenticated client here.
29
+ */
30
+
31
+ /**
32
+ * Fail-safe bound check: everything that is not provably an unbound host client
33
+ * is treated as bound. `boundSessionId == null` is true only for null/undefined,
34
+ * so `''` and any real id are bound; a nullish client is bound too.
35
+ */
36
+ export function isBoundClient(client) {
37
+ return !client || client.boundSessionId != null
38
+ }
39
+
40
+ /**
41
+ * True when `client` is session-bound (fail-safe, see `isBoundClient`) to a
42
+ * session other than `sessionId`: such a client receives no data for
43
+ * `sessionId` — no frame tagged with it and no subscription to it. This is the
44
+ * ONE predicate behind the broadcaster's delivery paths and the client
45
+ * manager's subscription index; a client bound to `sessionId` itself, and an
46
+ * unbound client, are never "bound to another session".
47
+ */
48
+ export function isBoundToOtherSession(client, sessionId) {
49
+ return client.boundSessionId != null && client.boundSessionId !== sessionId
50
+ }
51
+
52
+ /**
53
+ * May `recipient` be told that `peer` is connected? An unscoped recipient may
54
+ * hear about every peer. A session-scoped one only about peers on its OWN
55
+ * session (the same binding): the other connections' names and platforms are not
56
+ * part of its session. Fail-safe like `isBoundClient`: an empty or non-string
57
+ * binding on the recipient is a binding, and matches no unscoped peer.
58
+ */
59
+ export function canSeePeer(recipient, peer) {
60
+ if (!isBoundClient(recipient)) return true
61
+ const own = recipient?.boundSessionId
62
+ return typeof own === 'string' && own.length > 0 && peer?.boundSessionId === own
63
+ }
64
+
65
+ /**
66
+ * Fan an `environment_list` out to UNBOUND (host-authority) clients only. The
67
+ * `environment_list` payload carries the whole descriptor (host metadata + the
68
+ * #7552 sessions roster), so a bound client must not receive it — not on a pull
69
+ * (list/get refuse) and not on a push. The #7552 sessions-changed re-broadcast
70
+ * fires on every session open/close, so a plain broadcast would stream the
71
+ * surface to every bound listener continuously.
72
+ *
73
+ * @param {(msg: object, filter: (client: object) => boolean) => void} broadcast
74
+ * a FILTERED broadcast fn (`ctx.transport.broadcast` / `WsServer._broadcast`).
75
+ * @param {object[]} environments full descriptors (EnvironmentManager.list()).
76
+ */
77
+ export function broadcastEnvironmentList(broadcast, environments) {
78
+ broadcast({ type: 'environment_list', environments }, (client) => !isBoundClient(client))
79
+ }
80
+
81
+ /**
82
+ * A transcript replay frame names a CONVERSATION in its `sessionId` field (there
83
+ * is no live session behind a closed conversation), so the "tagged with another
84
+ * session" delivery rule must not read it as a session id. The handler that
85
+ * produced it, after authorising the conversation, marks the frame with this
86
+ * symbol (not serialised, not settable from the wire) and the delivery check
87
+ * skips the tag test for it.
88
+ */
89
+ export const CONVERSATION_FRAME = Symbol('conversation-frame')
90
+
91
+ /** @template T @param {T} frame @returns {T} */
92
+ export function markConversationFrame(frame) {
93
+ Object.defineProperty(frame, CONVERSATION_FRAME, { value: true, enumerable: false })
94
+ return frame
95
+ }
@@ -0,0 +1,94 @@
1
+ import { normalize } from 'path'
2
+
3
+ const JS_CLI_RE = /\.(?:c|m)?js$/i
4
+
5
+ /**
6
+ * Is `p` the path of a claude executable (native binary), judged by its
7
+ * basename on either path flavour? The SDK's own platform binary is named
8
+ * `claude` (`claude.exe` on Windows), and so is the `claude` we pin through
9
+ * `pathToClaudeCodeExecutable` (#7986).
10
+ */
11
+ function isNativeClaudeCommand(p) {
12
+ if (typeof p !== 'string' || p.length === 0) return false
13
+ const base = p.split(/[\\/]/).pop()
14
+ return base === 'claude' || base === 'claude.exe'
15
+ }
16
+
17
+ const CLAUDE_CLI_JS_SUFFIX = '@anthropic-ai/claude-code/cli.js'
18
+
19
+ /**
20
+ * Is `p` the claude-code cli.js? Separators are normalised first so a Windows
21
+ * host path matches, and the path must END with the package's cli.js (a mere
22
+ * substring elsewhere in an argument does not count), or equal the pinned path.
23
+ */
24
+ function isClaudeJsScript(p, pinned) {
25
+ if (typeof p !== 'string' || p.length === 0) return false
26
+ if (isPinnedPath(p, pinned)) return true
27
+ const norm = p.replace(/\\/g, '/')
28
+ return norm === CLAUDE_CLI_JS_SUFFIX || norm.endsWith('/' + CLAUDE_CLI_JS_SUFFIX)
29
+ }
30
+
31
+ function isPinnedPath(cmd, pinned) {
32
+ if (typeof cmd !== 'string' || cmd.length === 0) return false
33
+ if (typeof pinned !== 'string' || pinned.length === 0) return false
34
+ return normalize(cmd) === normalize(pinned)
35
+ }
36
+
37
+ /**
38
+ * Map the SDK's spawn request for the claude CLI onto what the container can
39
+ * exec (#8027). The SDK hands `spawnClaudeCodeProcess({ command, args })` HOST
40
+ * paths, in one of two shapes:
41
+ *
42
+ * - JS cli (old): `command` = `node`, `args[0]` = `<host>/@anthropic-ai/claude-code/cli.js`
43
+ * - native: `command` = absolute host path to a `claude` binary (a darwin
44
+ * Mach-O on a Mac, which a Linux container cannot exec), `args[0]` = a flag
45
+ *
46
+ * Both must run the container's own claude (`containerCliPath`), keeping every
47
+ * other arg. The claude spawn is identified positively (the native shape by the
48
+ * basename of `command`; the JS shape by `args[0]` naming the claude-code
49
+ * cli.js), so any other command passes through untouched. The result does not
50
+ * depend on how the host path is shaped, which is the point.
51
+ *
52
+ * A `containerCliPath` ending in .js/.mjs/.cjs is the npm-installed cli.js and
53
+ * is run via `node`; any other path is itself the container's claude executable.
54
+ *
55
+ * `hostClaudePath` is the pinned host executable the caller gave the SDK as
56
+ * `pathToClaudeCodeExecutable`; a `cmd` equal to it (after normalisation) is the
57
+ * claude spawn whatever its basename (`claude.cmd`, a versioned file, ...).
58
+ *
59
+ * @param {{ cmd: string, args?: string[], containerCliPath: string, hostClaudePath?: string }} spec
60
+ * @returns {{ cmd: string, args: string[], remapped: boolean }}
61
+ */
62
+ export function remapClaudeSpawn({ cmd, args = [], containerCliPath, hostClaudePath }) {
63
+ const viaNode = JS_CLI_RE.test(containerCliPath)
64
+
65
+ if (isNativeClaudeCommand(cmd) || isPinnedPath(cmd, hostClaudePath)) {
66
+ return viaNode
67
+ ? { cmd: 'node', args: [containerCliPath, ...args], remapped: true }
68
+ : { cmd: containerCliPath, args: [...args], remapped: true }
69
+ }
70
+
71
+ if (isClaudeJsScript(args[0], hostClaudePath)) {
72
+ // JS shape (`node|bun <host cli.js> ...`): drop the host runtime and script
73
+ // and run the container's claude, via node when it is a JS file.
74
+ return viaNode
75
+ ? { cmd: 'node', args: [containerCliPath, ...args.slice(1)], remapped: true }
76
+ : { cmd: containerCliPath, args: args.slice(1), remapped: true }
77
+ }
78
+
79
+ return { cmd, args: [...args], remapped: false }
80
+ }
81
+
82
+ /**
83
+ * Claude resolves its config directory from `CLAUDE_CONFIG_DIR` when the container
84
+ * image or pod defines it, which can put it somewhere the permission floor does not
85
+ * recognise. A claude spawn in a container therefore runs with the variable unset,
86
+ * so claude uses its own `<HOME>/.claude` (recognised by name) and its credentials
87
+ * and global config stay where they are. One definition for every container path.
88
+ */
89
+ export const CONTAINER_UNSET_ENV = Object.freeze(['CLAUDE_CONFIG_DIR'])
90
+
91
+ /** The argv prefix that runs a command with {@link CONTAINER_UNSET_ENV} unset (`env -u VAR ...`). */
92
+ export function containerUnsetEnvPrefix() {
93
+ return ['env', ...CONTAINER_UNSET_ENV.flatMap((name) => ['-u', name])]
94
+ }
@@ -1,6 +1,9 @@
1
1
  import { execFile, spawn } from 'child_process'
2
2
  import { createLogger } from '../../logger.js'
3
3
  import { VALID_USERNAME_RE } from '../../utils/validation-patterns.js'
4
+ import { getChroxyHostEnv } from '../../chroxy-host-metadata.js'
5
+ import { remapClaudeSpawn } from './container-claude-spawn.js'
6
+ import { containerUnsetEnvPrefix } from './container-claude-spawn.js'
4
7
 
5
8
  const log = createLogger('docker-backend')
6
9
 
@@ -484,6 +487,7 @@ export class DockerBackend {
484
487
  * @param {string} [opts.containerUser] - Non-root user inside the container (default: 'chroxy')
485
488
  * @param {string} [opts.containerCliPath] - Container path to claude-code CLI (default fallback)
486
489
  * @param {string} [opts.hostCwd] - Host CWD mount root (default: opts.cwd)
490
+ * @param {string} [opts.hostClaudePath] - Pinned host claude executable handed to the SDK; a `cmd` equal to it is the claude spawn
487
491
  * @returns {import('child_process').ChildProcess}
488
492
  */
489
493
  streamCliInEnvironment(containerId, opts = {}) {
@@ -492,6 +496,7 @@ export class DockerBackend {
492
496
  containerUser = 'chroxy',
493
497
  containerCliPath = DEFAULT_CONTAINER_CLI_PATH,
494
498
  hostCwd,
499
+ hostClaudePath,
495
500
  } = opts
496
501
 
497
502
  const dockerArgs = ['exec', '-i', '-u', containerUser]
@@ -515,23 +520,31 @@ export class DockerBackend {
515
520
  }
516
521
  }
517
522
  }
523
+ // #6633: also forward Chroxy's own (non-sensitive) host identity so an agent
524
+ // INSIDE the container can answer "what build am I in?". Sourced from the
525
+ // authoritative computed block (not `env`), so it lands regardless of how the
526
+ // caller built its env.
527
+ for (const [key, val] of Object.entries(getChroxyHostEnv())) {
528
+ dockerArgs.push('--env', `${key}=${val}`)
529
+ }
518
530
 
519
531
  // Override HOME and PATH for the container user.
520
532
  dockerArgs.push('--env', `HOME=/home/${containerUser}`)
521
533
  dockerArgs.push('--env', 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin')
522
534
 
523
- // Remap host cli.js path to container path (SDK passes host's absolute path).
524
- const containerArgs = [...args]
525
- if (containerArgs.length > 0 &&
526
- typeof containerArgs[0] === 'string' &&
527
- containerArgs[0].includes('@anthropic-ai/claude-code/cli.js')) {
528
- log.info(`Remapped CLI path: ${containerArgs[0]} -> ${containerCliPath}`)
529
- containerArgs[0] = containerCliPath
535
+ // Remap the SDK's host-path claude spawn (JS cli.js or native binary) to the
536
+ // container's claude (#8027).
537
+ const remap = remapClaudeSpawn({ cmd, args, containerCliPath, hostClaudePath })
538
+ const containerCmd = remap.cmd
539
+ const containerArgs = remap.args
540
+ if (remap.remapped) {
541
+ log.info(`Remapped claude spawn: ${cmd} ${args[0] ?? ''} -> ${containerCmd} ${containerArgs[0] ?? ''}`)
530
542
  }
531
543
 
532
- dockerArgs.push(containerId, cmd, ...containerArgs)
544
+ // A claude spawn runs with CLAUDE_CONFIG_DIR unset (see container-claude-spawn.js).
545
+ dockerArgs.push(containerId, ...(remap.remapped ? containerUnsetEnvPrefix() : []), containerCmd, ...containerArgs)
533
546
 
534
- log.info(`docker exec stream: ${containerId.slice(0, 12)} ${cmd} ${containerArgs.slice(0, 2).join(' ')}`)
547
+ log.info(`docker exec stream: ${containerId.slice(0, 12)} ${containerCmd} ${containerArgs.slice(0, 2).join(' ')}`)
535
548
 
536
549
  const child = (this._spawn || spawn)('docker', dockerArgs, {
537
550
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -657,7 +670,23 @@ export class DockerBackend {
657
670
  runArgs.push('--add-host', 'host.docker.internal:host-gateway')
658
671
  }
659
672
 
660
- runArgs.push(image, 'sleep', 'infinity')
673
+ // #7296 — `image` reaches here from the wire (`create_environment`), and
674
+ // a bare positional is option-parsed by `docker run`. The allowlist
675
+ // refuses a dash-leading reference; this terminates option parsing so
676
+ // the refusal is not the only thing standing between a flag and the
677
+ // daemon. Measured on Docker 29.7.2: `docker run -- --help sleep
678
+ // infinity` does NOT print help (the `--` is consumed and `--help`
679
+ // becomes the image), while the same argv without `--` does.
680
+ //
681
+ // What the separator needs from the argv above it is narrow and worth
682
+ // stating exactly: every FLAG NAME there is a chroxy literal, so no
683
+ // earlier token is a bare `--` that would terminate option parsing
684
+ // ahead of this one. The flag VALUES are not all chroxy's own
685
+ // (memoryLimit/cpuLimit arrive from the wire; containerEnv, mounts and
686
+ // forwardPorts from devcontainer.json) — but each sits in a slot pflag
687
+ // consumes as the preceding flag's argument, so it is a bad-value error
688
+ // there, never a new option.
689
+ runArgs.push('--', image, 'sleep', 'infinity')
661
690
 
662
691
  this._execFile('docker', runArgs, { encoding: 'utf-8', timeout: 120_000 }, (err, stdout, stderr) => {
663
692
  if (err) {
@@ -4,6 +4,9 @@ import { PassThrough } from 'stream'
4
4
  import { KubeConfig, CoreV1Api, PortForward } from '@kubernetes/client-node'
5
5
  import WebSocket from 'ws'
6
6
  import { createLogger } from '../../logger.js'
7
+ import { getChroxyHostEnv } from '../../chroxy-host-metadata.js'
8
+ import { assertSafeArgvValue } from '../../utils/argv-safety.js'
9
+ import { remapClaudeSpawn, CONTAINER_UNSET_ENV, containerUnsetEnvPrefix } from './container-claude-spawn.js'
7
10
 
8
11
  const log = createLogger('k8s-backend')
9
12
 
@@ -304,26 +307,35 @@ const DEFAULT_WORKSPACE_MOUNT_PATH = '/workspace'
304
307
 
305
308
  /**
306
309
  * Reject argv values that git would interpret as an option rather than a
307
- * positional argument (argument-injection hardening, #3193).
310
+ * positional argument (argument-injection hardening, #3193) — routed through
311
+ * the shared guard in `utils/argv-safety.js` (#7869).
312
+ *
313
+ * This was previously a locally-scoped spelling — `typeof value === 'string'
314
+ * && value.startsWith('-')` — that git-ops.js's own comment named as "a THIRD
315
+ * … still live and NOT folded in" after #7290 folded a second, equally weak
316
+ * copy out of ws-file-ops/reader.js. It was strictly weaker than the shared
317
+ * guard: it fell through (accepted) on a non-string, an empty string, and a
318
+ * value carrying an embedded NUL/CR/LF, all of which `assertSafeArgvValue`
319
+ * rejects. A newline in particular matters because several CLIs (including
320
+ * git's own `--stdin` modes) treat one as a record separator, letting an
321
+ * embedded newline smuggle a second argument into a single slot.
308
322
  *
309
323
  * git-clone argv is NOT passed through a shell — the init container runs
310
324
  * `command: ['git']` with an explicit `args` array — so classic shell
311
325
  * metacharacter injection (`;`, `|`, `$()`, backticks) is structurally
312
- * impossible. The residual risk is *argument* injection: a value beginning
313
- * with `-` (e.g. `--upload-pack=…`, `--config=…`) would be parsed by git as a
314
- * flag. We reject any value whose first character is `-`; the clone argv also
315
- * uses `--` to terminate option parsing as belt-and-braces.
326
+ * impossible. The residual risk is *argument* injection, which
327
+ * `assertSafeArgvValue` covers in full; the clone argv also uses `--` to
328
+ * terminate option parsing as belt-and-braces.
316
329
  *
317
330
  * @param {string} value
318
331
  * @param {string} field - Field name for the error message
319
- * @throws {Error} If the value starts with '-'
332
+ * @throws {Error} If the value is unsafe to place in the git clone argv.
320
333
  */
321
- function rejectGitOptionLike(value, field) {
322
- if (typeof value === 'string' && value.startsWith('-')) {
323
- throw new Error(
324
- `createEnvironment: opts.gitRepo.${field} must not start with "-" ` +
325
- '(rejected to prevent git argument injection)',
326
- )
334
+ function assertGitRepoFieldSafe(value, field) {
335
+ try {
336
+ assertSafeArgvValue(value, `opts.gitRepo.${field}`)
337
+ } catch (err) {
338
+ throw new Error(`createEnvironment: ${err.message} (rejected to prevent git argument injection)`)
327
339
  }
328
340
  }
329
341
 
@@ -377,20 +389,20 @@ function validateGitRepo(gitRepo, cwd, workspacePVC) {
377
389
  'createEnvironment: opts.gitRepo.url must be a non-empty string',
378
390
  )
379
391
  }
380
- rejectGitOptionLike(spec.url, 'url')
392
+ assertGitRepoFieldSafe(spec.url, 'url')
381
393
 
382
394
  if (spec.branch != null) {
383
395
  if (typeof spec.branch !== 'string' || spec.branch.length === 0) {
384
396
  throw new Error('createEnvironment: opts.gitRepo.branch must be a non-empty string')
385
397
  }
386
- rejectGitOptionLike(spec.branch, 'branch')
398
+ assertGitRepoFieldSafe(spec.branch, 'branch')
387
399
  }
388
400
 
389
401
  if (spec.commit != null) {
390
402
  if (typeof spec.commit !== 'string' || spec.commit.length === 0) {
391
403
  throw new Error('createEnvironment: opts.gitRepo.commit must be a non-empty string')
392
404
  }
393
- rejectGitOptionLike(spec.commit, 'commit')
405
+ assertGitRepoFieldSafe(spec.commit, 'commit')
394
406
  }
395
407
 
396
408
  let depth = null
@@ -1230,6 +1242,14 @@ export class K8sBackend {
1230
1242
  }
1231
1243
  }
1232
1244
 
1245
+ // #6633: Chroxy's own (non-sensitive) host identity, so an agent exec'd into
1246
+ // the pod can answer "what build am I in?" — pod-spec env is inherited by
1247
+ // `kubectl exec` processes. Added after containerEnv so the computed identity
1248
+ // is authoritative.
1249
+ for (const [name, value] of Object.entries(getChroxyHostEnv())) {
1250
+ env.push({ name, value: String(value) })
1251
+ }
1252
+
1233
1253
  // 4. Resolve imagePullPolicy: per-call opt > constructor opt > omit (K8s default)
1234
1254
  const imagePullPolicy = callImagePullPolicy || this._imagePullPolicy
1235
1255
 
@@ -1628,6 +1648,7 @@ export class K8sBackend {
1628
1648
  cmd, args = [], env, cwd, signal,
1629
1649
  containerCliPath = DEFAULT_CONTAINER_CLI_PATH,
1630
1650
  hostCwd,
1651
+ hostClaudePath,
1631
1652
  } = opts
1632
1653
  const ns = this._namespaceForCall(opts, 'streamCliInEnvironment')
1633
1654
 
@@ -1639,15 +1660,27 @@ export class K8sBackend {
1639
1660
  || this._agentTokens.get(podName)
1640
1661
  || this._readAgentToken(podName, ns)
1641
1662
 
1642
- // Remap host cli.js path to container path, mirroring DockerBackend.
1643
- const containerArgs = [...args]
1644
- if (containerArgs.length > 0 &&
1645
- typeof containerArgs[0] === 'string' &&
1646
- containerArgs[0].includes('@anthropic-ai/claude-code/cli.js')) {
1647
- log.info(`Remapped CLI path: ${containerArgs[0]} -> ${containerCliPath}`)
1648
- containerArgs[0] = containerCliPath
1663
+ // Remap the SDK's host-path claude spawn (JS cli.js or native binary) to the
1664
+ // Pod's claude, mirroring DockerBackend (#8027).
1665
+ const remap = remapClaudeSpawn({ cmd, args, containerCliPath, hostClaudePath })
1666
+ const containerCmd = remap.cmd
1667
+ const containerArgs = remap.args
1668
+ if (remap.remapped) {
1669
+ log.info(`Remapped claude spawn: ${cmd} ${args[0] ?? ''} -> ${containerCmd} ${containerArgs[0] ?? ''}`)
1649
1670
  }
1650
1671
 
1672
+ // A claude spawn runs with CLAUDE_CONFIG_DIR unset, so claude uses its own
1673
+ // `<HOME>/.claude`. Two layers: the command is wrapped in `env -u ...` (holds with
1674
+ // any sidecar image version) and the frame asks the sidecar to remove it from the
1675
+ // merged env (`unsetEnv`; an older sidecar ignores it). See container-claude-spawn.js.
1676
+ const unsetEnv = remap.remapped ? [...CONTAINER_UNSET_ENV] : undefined
1677
+ const spawnEnv = env && unsetEnv
1678
+ ? Object.fromEntries(Object.entries(env).filter(([key]) => !unsetEnv.includes(key)))
1679
+ : env
1680
+
1681
+ const spawnCmd = unsetEnv ? containerUnsetEnvPrefix()[0] : containerCmd
1682
+ const spawnArgs = unsetEnv ? [...containerUnsetEnvPrefix().slice(1), containerCmd, ...containerArgs] : containerArgs
1683
+
1651
1684
  // Remap host cwd to /workspace inside the Pod when provided.
1652
1685
  let containerCwd = cwd
1653
1686
  if (cwd && hostCwd) {
@@ -1710,7 +1743,7 @@ export class K8sBackend {
1710
1743
  }
1711
1744
 
1712
1745
  _wireWsToProc(ws, proc, {
1713
- cmd, args: containerArgs, env, cwd: containerCwd, signal, cleanup,
1746
+ cmd: spawnCmd, args: spawnArgs, env: spawnEnv, unsetEnv, cwd: containerCwd, signal, cleanup,
1714
1747
  })
1715
1748
  }).catch((err) => {
1716
1749
  log.warn(`streamCliInEnvironment dial failed for ${podName}: ${err.message}`)
@@ -2294,7 +2327,7 @@ class SidecarProcess extends EventEmitter {
2294
2327
  * @param {AbortSignal} [spawnOpts.signal]
2295
2328
  * @param {Function} [spawnOpts.cleanup] - Optional teardown for portforward bridge
2296
2329
  */
2297
- function _wireWsToProc(ws, proc, { cmd, args = [], env, cwd, signal, cleanup } = {}) {
2330
+ function _wireWsToProc(ws, proc, { cmd, args = [], env, unsetEnv, cwd, signal, cleanup } = {}) {
2298
2331
  // Distinguish initial wiring (spawn) from a reconnect (resume).
2299
2332
  const isReconnect = Boolean(proc._sessionId)
2300
2333
 
@@ -2393,6 +2426,7 @@ function _wireWsToProc(ws, proc, { cmd, args = [], env, cwd, signal, cleanup } =
2393
2426
  // sidecar protocol default introduced by #3329.
2394
2427
  frame = { type: 'spawn', cmd, args, stdin: 'pipe' }
2395
2428
  if (env && Object.keys(env).length > 0) frame.env = env
2429
+ if (unsetEnv && unsetEnv.length > 0) frame.unsetEnv = unsetEnv
2396
2430
  if (cwd) frame.cwd = cwd
2397
2431
  log.info(`Sent spawn frame: ${cmd} ${args.slice(0, 2).join(' ')}`)
2398
2432
  }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * #7562 — the ONE funnel for "destroy this environment", shared by both wire
3
+ * paths (`destroy_environment` in feature-handlers.js and `containers_action`
4
+ * with `action: 'destroy'` in control-room-handlers.js).
5
+ *
6
+ * POLICY (adjudicated 2026-08-30, recorded in
7
+ * docs/decisions/2026-08-destroy-environment-live-sessions.md):
8
+ *
9
+ * REFUSE when the environment has live sessions; `force: true` escapes, and
10
+ * force means CASCADE — destroy those sessions CLEANLY first, then the
11
+ * environment.
12
+ *
13
+ * Why cascade rather than detach: destroying an environment runs `docker rm -f`
14
+ * on its container, which kills every process inside it. The attached sessions
15
+ * die either way — the only question is whether they die cleanly (provider
16
+ * teardown, synthetic `stream_end` for in-flight streams, `session_destroyed`
17
+ * broadcast so clients drop the tab, state flushed, the environment tag
18
+ * removed) or are left sitting in `SessionManager._sessions` pointing at a
19
+ * container that no longer exists. "Detach and keep running" is not available:
20
+ * a `docker-sdk` session whose container is gone cannot run, and one that
21
+ * silently fell back to a fresh container would be #7561's containment escape.
22
+ *
23
+ * Why the refusal lives in `EnvironmentManager.destroy()` and not here: that is
24
+ * the single chokepoint every caller reaches, including any future one. A check
25
+ * duplicated per handler is the "guard wired to only some of its callers" shape
26
+ * catalogued in docs/false-safety-guards.md — which is how `containers_action`
27
+ * ended up with no guard at all while the dashboard had one.
28
+ */
29
+ import { createLogger } from '../logger.js'
30
+ import { assertAuthorized } from '../connection-authority.js'
31
+
32
+ const log = createLogger('destroy-environment')
33
+
34
+ /**
35
+ * `err.code` on the refusal thrown by `EnvironmentManager.destroy()` when the
36
+ * environment still has sessions attached and `force` was not set. Also the
37
+ * `code` echoed on the `environment_error` wire reply.
38
+ */
39
+ export const ENVIRONMENT_HAS_LIVE_SESSIONS = 'ENVIRONMENT_HAS_LIVE_SESSIONS'
40
+
41
+ /**
42
+ * How many times the cascade re-reads `env.sessions` before giving up on
43
+ * draining it. A session can attach between the read and the destroy (nothing
44
+ * holds the environment lock across `createSession`), so one snapshot is not
45
+ * enough; an unbounded loop would let a client that creates sessions in a loop
46
+ * wedge an operator's force-destroy. Bounded, then the destroy proceeds — the
47
+ * operator asked for `force`, and a straggler is a session the container
48
+ * teardown was going to kill anyway.
49
+ */
50
+ export const MAX_CASCADE_PASSES = 5
51
+
52
+ /**
53
+ * Build the structured refusal. Exported so `EnvironmentManager.destroy()` and
54
+ * this module cannot drift on the shape the handlers destructure.
55
+ * @param {{id: string, name?: string, sessions: string[]}} env
56
+ * @returns {Error & {code: string, environmentId: string, sessions: string[]}}
57
+ */
58
+ export function liveSessionsError(env) {
59
+ const sessions = [...env.sessions]
60
+ const err = new Error(
61
+ `Environment "${env.name || env.id}" has ${sessions.length} live session(s) running in it ` +
62
+ `(${sessions.join(', ')}). Destroying the container would kill them. ` +
63
+ `Close the sessions first, or resend with force to destroy them and the environment together.`,
64
+ )
65
+ err.code = ENVIRONMENT_HAS_LIVE_SESSIONS
66
+ err.environmentId = env.id
67
+ err.sessions = sessions
68
+ return err
69
+ }
70
+
71
+ /**
72
+ * Destroy an environment, honouring the live-session policy.
73
+ *
74
+ * @param {object} args
75
+ * @param {object} args.environmentManager - the live EnvironmentManager
76
+ * @param {object|null} [args.sessionManager] - the live SessionManager; only needed for the cascade
77
+ * @param {string} args.environmentId
78
+ * @param {boolean} [args.force=false] - destroy the attached sessions first, then the environment
79
+ * @returns {Promise<{destroyedSessions: string[]}>}
80
+ * @throws the structured `ENVIRONMENT_HAS_LIVE_SESSIONS` refusal (unforced, sessions attached),
81
+ * or whatever `EnvironmentManager.destroy()` throws (unknown id, backend failure).
82
+ */
83
+ export async function destroyEnvironmentWithSessions({
84
+ environmentManager,
85
+ sessionManager = null,
86
+ environmentId,
87
+ force = false,
88
+ isAuthorized,
89
+ }) {
90
+ const destroyedSessions = []
91
+ assertAuthorized(isAuthorized)
92
+
93
+ if (force) {
94
+ // Drain first, so every session gets a real teardown while its container is
95
+ // still alive. Re-read between passes: `env.sessions` is mutated by
96
+ // `_cleanupSessionMaps` as each destroy lands, and a session can attach
97
+ // mid-cascade.
98
+ if (sessionManager && typeof sessionManager.destroySession === 'function') {
99
+ for (let pass = 0; pass < MAX_CASCADE_PASSES; pass++) {
100
+ const live = [...(environmentManager.get?.(environmentId)?.sessions || [])]
101
+ const pending = live.filter((id) => !destroyedSessions.includes(id))
102
+ if (pending.length === 0) break
103
+ for (const sessionId of pending) {
104
+ // Push BEFORE the destroy, deliberately (#7571 review S2). This list
105
+ // is two things at once: the caller's report, and — via the `pending`
106
+ // filter above — the loop's own record of what it has already
107
+ // attempted. Pushing after a successful destroy would make a session
108
+ // whose `destroySession` throws deterministically re-enter `pending`
109
+ // on every pass, so ONE broken session could consume all
110
+ // MAX_CASCADE_PASSES and starve the sessions behind it of a clean
111
+ // teardown — the exact outcome the cascade exists to prevent.
112
+ //
113
+ // The cost is that `destroyedSessions` can name a session whose
114
+ // teardown threw, so it is "attempted", not "confirmed". That
115
+ // misreport is confined to the handlers' `log.warn` summary; nothing
116
+ // branches on the list, and the environment goes away regardless.
117
+ // Attempted-once-each is the right trade against
118
+ // starve-the-rest-for-one-bad-session.
119
+ destroyedSessions.push(sessionId)
120
+ try {
121
+ sessionManager.destroySession(sessionId)
122
+ } catch (err) {
123
+ // A session that fails to tear down must not block the destroy the
124
+ // operator explicitly forced — the container teardown below ends it
125
+ // regardless. Log loudly; never rethrow.
126
+ log.error(`force-destroy: failed to destroy session ${sessionId} in ${environmentId}: ${err?.stack || err}`)
127
+ }
128
+ }
129
+ }
130
+ } else if ((environmentManager.get?.(environmentId)?.sessions || []).length > 0) {
131
+ log.warn(`force-destroy: ${environmentId} has attached sessions but no SessionManager is wired — they cannot be torn down cleanly`)
132
+ }
133
+ }
134
+
135
+ // Always route through the manager, and always pass `force` through: after a
136
+ // successful drain the refusal would not fire anyway, but a session that
137
+ // attached after the last pass must not turn an explicit force into a
138
+ // failure.
139
+ assertAuthorized(isAuthorized)
140
+ await environmentManager.destroy(environmentId, { force, isAuthorized })
141
+ return { destroyedSessions }
142
+ }