@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,931 @@
1
+ import { execFile, spawn } from 'child_process'
2
+ import { createLogger } from '../../logger.js'
3
+ import { VALID_USERNAME_RE } from '../../utils/validation-patterns.js'
4
+
5
+ const log = createLogger('docker-backend')
6
+
7
+ const DEFAULT_CONTAINER_CLI_PATH = '/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js'
8
+
9
+ /**
10
+ * #6155 — first-class docker labels stamped on the chroxy resources created via
11
+ * `docker run` (`_startContainer`) and `docker commit` (`_commitContainer`), so
12
+ * the Control Room host-prune survey can identify them by label (robust) with the
13
+ * legacy name/tag convention (`chroxy-env-*` / `chroxy-env:` / `chroxy-byok-snap:`)
14
+ * as a fallback. NOTE: compose-managed containers (`_composeUp` → `docker compose
15
+ * up`) do NOT receive these CLI `--label` flags — they're covered by the
16
+ * `chroxy-env-*` name fallback instead (their compose project is `chroxy-env-<id>`).
17
+ * `MANAGED` marks ownership; `KIND` distinguishes a live env container from a
18
+ * committed snapshot image. Kept here (the producer) and imported by
19
+ * `control-room/host-prune.js`.
20
+ */
21
+ export const CHROXY_MANAGED_LABEL = 'com.chroxy.managed'
22
+ export const CHROXY_LABEL_KIND = 'com.chroxy.kind'
23
+
24
+ /**
25
+ * #5127 — Cap on the per-stream buffer the streaming execInEnvironment path
26
+ * retains for the resolved value / failure tail. The buffered execFile path
27
+ * rejects past Node's 1 MB maxBuffer; the streaming path used to accumulate
28
+ * without limit, so a postCreateCommand that printed hundreds of MB grew the
29
+ * daemon's retained buffer unbounded.
30
+ *
31
+ * We keep the LAST N bytes (the tail) because the failure event only surfaces
32
+ * a 4 KiB tail (POST_CREATE_OUTPUT_CAP_BYTES in docker-byok-session.js) and
33
+ * diagnostic info (the actual exception, exit codes) lands at the end. 256 KiB
34
+ * is comfortably larger than the 4 KiB failure tail while staying bounded.
35
+ *
36
+ * onData STILL fires for every chunk — streaming is not truncated, only the
37
+ * retained accumulator is capped.
38
+ */
39
+ const STREAM_RETAINED_BUFFER_CAP_BYTES = 256 * 1024
40
+
41
+ /**
42
+ * #5126 — Grace period after a SIGTERM-on-timeout before escalating to
43
+ * SIGKILL. A child that ignores SIGTERM (or is stuck uninterruptibly) would
44
+ * otherwise leave the streaming promise pending forever, since it only settles
45
+ * on the subsequent `close`.
46
+ */
47
+ const STREAM_SIGKILL_GRACE_MS = 5_000
48
+
49
+ /**
50
+ * Append `chunk` to `buf` keeping at most `cap` UTF-16 code units (the tail).
51
+ * Uses string length as a cheap proxy for byte size — exact byte accounting
52
+ * isn't required since the value is a diagnostic tail and the downstream
53
+ * failure event re-caps to 4 KiB. A multibyte sequence clipped at the cut
54
+ * boundary decodes to U+FFFD, which is acceptable for a tail.
55
+ */
56
+ function appendCapped(buf, chunk, cap = STREAM_RETAINED_BUFFER_CAP_BYTES) {
57
+ const next = buf + chunk
58
+ if (next.length <= cap) return next
59
+ return next.slice(next.length - cap)
60
+ }
61
+
62
+ /**
63
+ * Env vars explicitly forwarded into the container during streamCliInEnvironment.
64
+ * Mirrors the allowlist in docker-sdk-session.js — keep both in sync.
65
+ *
66
+ * Only vars needed for Claude Code operation; never forward the full host env.
67
+ * HOME and PATH are set explicitly per-call rather than forwarded from the host.
68
+ */
69
+ const FORWARDED_ENV_KEYS = [
70
+ 'ANTHROPIC_API_KEY',
71
+ 'NODE_ENV',
72
+ ]
73
+
74
+ /**
75
+ * DockerBackend implements the Backend interface (see types.js) using the local
76
+ * Docker CLI (`docker` / `docker compose`).
77
+ *
78
+ * This class owns ALL Docker shellout operations. It has no environment state
79
+ * of its own — every method receives the handle (containerId or compose project
80
+ * name) from the manager's in-memory record.
81
+ *
82
+ * Injecting `_execFile` in the constructor lets existing tests pass their
83
+ * mock execFile through EnvironmentManager → DockerBackend without any test
84
+ * changes.
85
+ */
86
+ export class DockerBackend {
87
+ constructor({ _execFile: injectedExecFile, _spawn: injectedSpawn } = {}) {
88
+ this._execFile = injectedExecFile || execFile
89
+ this._spawn = injectedSpawn || spawn
90
+ }
91
+
92
+ // ─────────────────────────────────────────────────────────────────────────
93
+ // createEnvironment — start a standalone container + run setup
94
+ // ─────────────────────────────────────────────────────────────────────────
95
+
96
+ /**
97
+ * @param {Object} opts - See Backend interface in types.js
98
+ * @returns {Promise<{ containerId: string, containerCliPath: string }>}
99
+ */
100
+ async createEnvironment(opts) {
101
+ const { envId, cwd, image, memoryLimit, cpuLimit, containerUser,
102
+ containerEnv, forwardPorts, mounts, postCreateCommand } = opts
103
+
104
+ const containerId = await this._startContainer({
105
+ envId, cwd, image, memoryLimit, cpuLimit, containerEnv, forwardPorts, mounts,
106
+ })
107
+
108
+ let containerCliPath
109
+ try {
110
+ await this._setupContainer(containerId, containerUser)
111
+ containerCliPath = await this._discoverCliPath(containerId)
112
+ if (postCreateCommand) {
113
+ await this._runPostCreateCommand(containerId, postCreateCommand)
114
+ }
115
+ } catch (err) {
116
+ log.warn(`Environment setup failed, removing container ${containerId.slice(0, 12)}: ${err.message}`)
117
+ await this._removeContainer(containerId)
118
+ throw err
119
+ }
120
+
121
+ return { containerId, containerCliPath }
122
+ }
123
+
124
+ // ─────────────────────────────────────────────────────────────────────────
125
+ // createComposeEnvironment — start a compose stack + setup primary service
126
+ // ─────────────────────────────────────────────────────────────────────────
127
+
128
+ /**
129
+ * @param {Object} opts - See Backend interface in types.js
130
+ * @returns {Promise<{ containerId: string, containerCliPath: string, services: Array }>}
131
+ */
132
+ async createComposeEnvironment(opts) {
133
+ const { cwd, composeFile, composeProject, containerUser, primaryService, envFile } = opts
134
+
135
+ await this._composeUp(composeFile, composeProject, cwd, envFile)
136
+
137
+ let containerId
138
+ try {
139
+ containerId = await this._composePrimaryContainerId(composeProject, primaryService)
140
+ } catch (err) {
141
+ log.warn(`Failed to identify primary container, tearing down: ${err.message}`)
142
+ await this._composeDown(composeFile, composeProject, cwd)
143
+ throw err
144
+ }
145
+
146
+ let containerCliPath
147
+ try {
148
+ await this._setupContainer(containerId, containerUser)
149
+ containerCliPath = await this._discoverCliPath(containerId)
150
+ } catch (err) {
151
+ log.warn(`Compose environment setup failed, tearing down: ${err.message}`)
152
+ await this._composeDown(composeFile, composeProject, cwd)
153
+ throw err
154
+ }
155
+
156
+ const services = await this._composeServices(composeProject)
157
+
158
+ return { containerId, containerCliPath, services }
159
+ }
160
+
161
+ // ─────────────────────────────────────────────────────────────────────────
162
+ // destroyEnvironment — force-remove a standalone container
163
+ // ─────────────────────────────────────────────────────────────────────────
164
+
165
+ /** @returns {Promise<void>} */
166
+ destroyEnvironment(containerId) {
167
+ return this._removeContainer(containerId)
168
+ }
169
+
170
+ // ─────────────────────────────────────────────────────────────────────────
171
+ // destroyComposeEnvironment — tear down a compose stack
172
+ // ─────────────────────────────────────────────────────────────────────────
173
+
174
+ /** @returns {Promise<void>} */
175
+ destroyComposeEnvironment({ composeFile, composeProject, cwd }) {
176
+ return this._composeDown(composeFile, composeProject, cwd)
177
+ }
178
+
179
+ // ─────────────────────────────────────────────────────────────────────────
180
+ // stop / start / restart — standalone-container lifecycle (#6134)
181
+ //
182
+ // Unlike `_removeContainer` (which swallows so a teardown never blocks), these
183
+ // REJECT on failure so the EnvironmentManager / containers_action handler can
184
+ // surface a CONTAINER_ACTION_FAILED to the operator rather than silently
185
+ // claiming success.
186
+ // ─────────────────────────────────────────────────────────────────────────
187
+
188
+ /** @returns {Promise<void>} */
189
+ stopEnvironment(containerId) {
190
+ return this._dockerLifecycle('stop', containerId)
191
+ }
192
+
193
+ /** @returns {Promise<void>} */
194
+ startEnvironment(containerId) {
195
+ return this._dockerLifecycle('start', containerId)
196
+ }
197
+
198
+ /** @returns {Promise<void>} */
199
+ restartEnvironment(containerId) {
200
+ return this._dockerLifecycle('restart', containerId)
201
+ }
202
+
203
+ _dockerLifecycle(verb, containerId) {
204
+ return new Promise((resolve, reject) => {
205
+ this._execFile('docker', [verb, containerId], { stdio: 'ignore' }, (err) => {
206
+ if (err) {
207
+ log.warn(`docker ${verb} ${containerId.slice(0, 12)} failed: ${err.message}`)
208
+ reject(new Error(`docker ${verb} failed: ${err.message}`))
209
+ return
210
+ }
211
+ resolve()
212
+ })
213
+ })
214
+ }
215
+
216
+ // ─────────────────────────────────────────────────────────────────────────
217
+ // removeImage — delete a local Docker image
218
+ // ─────────────────────────────────────────────────────────────────────────
219
+
220
+ /** @returns {Promise<void>} */
221
+ removeImage(imageTag) {
222
+ return this._removeImage(imageTag)
223
+ }
224
+
225
+ // ─────────────────────────────────────────────────────────────────────────
226
+ // execInEnvironment — run a shell command inside a container
227
+ // ─────────────────────────────────────────────────────────────────────────
228
+
229
+ /**
230
+ * @param {string} containerId
231
+ * @param {{ cmd: string, env?: Object.<string,string>, envFile?: string, cwd?: string, timeout?: number, user?: string, onData?: (chunk: string, stream: 'stdout'|'stderr') => void }} opts
232
+ * @returns {Promise<{ stdout: string, stderr: string }>}
233
+ *
234
+ * opts.onData — OPTIONAL streaming callback (#5069). When provided, the
235
+ * command runs via a streaming `spawn` instead of the buffered `execFile`,
236
+ * and `onData(chunk, 'stdout'|'stderr')` is invoked with each decoded chunk
237
+ * as bytes arrive. This lets a caller surface progress for multi-minute
238
+ * setups (npm install, apt-get) instead of staring at a silent dashboard.
239
+ * The buffered last-N-KiB tail is STILL accumulated and attached to the
240
+ * rejected Error on failure (#5067 contract preserved), so streaming and
241
+ * the failure-tail capture coexist. When `onData` is absent the original
242
+ * buffered `execFile` path is used unchanged — every existing caller keeps
243
+ * its exact behaviour.
244
+ *
245
+ * opts.env — all key/value pairs are forwarded as `--env KEY=VAL` flags.
246
+ * Entries whose value is null or undefined are skipped with a `log.warn`
247
+ * (caller mistake — passing them would produce `KEY=null` / `KEY=undefined`
248
+ * which is hard to debug; the warn surfaces it in server logs without
249
+ * breaking the call). All other values are coerced to String explicitly.
250
+ * No allowlist filter is applied here: unlike streamCliInEnvironment (which
251
+ * runs the long-lived Claude Code CLI and must never leak the full host env),
252
+ * execInEnvironment is a general-purpose helper invoked with an explicit env
253
+ * object constructed by the caller. The caller is responsible for passing only
254
+ * the vars required for the command. process.env is never consulted.
255
+ *
256
+ * opts.envFile — forwarded as `--env-file <path>`. Useful for secrets that
257
+ * must not appear in `ps` output (`docker exec --env KEY=secret` exposes
258
+ * the value in the process listing). The file format follows Docker's own
259
+ * env file spec: one `KEY=VALUE` pair per line, no quoting required.
260
+ * Callers are responsible for creating the file with 0600 permissions and
261
+ * unlinking it when no longer needed. docker-byok (#5079) uses this to
262
+ * forward `ANTHROPIC_API_KEY` into compose-managed containers without
263
+ * exposing the key in argv.
264
+ *
265
+ * opts.cwd — forwarded as `--workdir <cwd>`. The path must already be an
266
+ * absolute path *inside* the container; callers are responsible for remapping
267
+ * host paths to container paths if necessary.
268
+ *
269
+ * opts.user — forwarded as `-u <user>` so the command runs as a non-root
270
+ * container user. Validated against the same POSIX username regex as
271
+ * `streamCliInEnvironment` to refuse shell-injection payloads. Optional
272
+ * for backward compatibility (docker-sdk's CLI bootstrap path runs as
273
+ * root for `npm install -g`, then `streamCliInEnvironment` switches to
274
+ * the non-root user for the long-lived Claude process). docker-byok
275
+ * (#5021) passes it for every tool dispatch so file ops respect the
276
+ * `useradd` + `chown /workspace` setup done at container start.
277
+ */
278
+ execInEnvironment(containerId, { cmd, env, envFile, cwd, timeout = 30_000, user, onData } = {}) {
279
+ return new Promise((resolve, reject) => {
280
+ const execArgs = ['exec']
281
+
282
+ if (user) {
283
+ // Refuse anything but a POSIX username so a caller-supplied string
284
+ // can't smuggle a `docker exec` flag (VALID_USERNAME_RE is shared).
285
+ if (!VALID_USERNAME_RE.test(user)) {
286
+ reject(new Error(`Invalid user "${user}" — must match POSIX username rules`))
287
+ return
288
+ }
289
+ execArgs.push('-u', user)
290
+ }
291
+
292
+ if (cwd) {
293
+ execArgs.push('--workdir', cwd)
294
+ }
295
+
296
+ if (envFile) {
297
+ execArgs.push('--env-file', envFile)
298
+ }
299
+
300
+ if (env) {
301
+ for (const [key, val] of Object.entries(env)) {
302
+ if (val == null) {
303
+ // Caller-provided key is JSON-encoded before interpolation to prevent
304
+ // log forging via embedded control characters (newlines, ANSI escapes).
305
+ log.warn(`execInEnvironment: skipping null/undefined value for env key ${JSON.stringify(key)}`)
306
+ continue
307
+ }
308
+ execArgs.push('--env', `${key}=${String(val)}`)
309
+ }
310
+ }
311
+
312
+ execArgs.push(containerId, 'bash', '-c', cmd)
313
+
314
+ // #5069 — Streaming path. When the caller supplies `onData`, run the
315
+ // command via `spawn` so stdout/stderr surface incrementally as bytes
316
+ // arrive (long-running setup like `npm install` / `apt-get`). We still
317
+ // accumulate the full stdout/stderr so the resolved value and the
318
+ // failure-tail attached to the rejected Error (#5067) are identical to
319
+ // the buffered path. When `onData` is absent we keep the original
320
+ // `execFile` call untouched for every existing caller.
321
+ if (typeof onData === 'function') {
322
+ const child = this._spawn('docker', execArgs, { stdio: ['ignore', 'pipe', 'pipe'] })
323
+
324
+ let stdout = ''
325
+ let stderr = ''
326
+ let settled = false
327
+ let timedOut = false
328
+ let timer = null
329
+ // #5126 — SIGKILL escalation timer, armed only after the SIGTERM-on-
330
+ // timeout fires. Cleared on close so a child that exits promptly never
331
+ // gets force-killed.
332
+ let killTimer = null
333
+
334
+ const settle = (fn, arg) => {
335
+ if (settled) return
336
+ settled = true
337
+ if (timer) clearTimeout(timer)
338
+ if (killTimer) clearTimeout(killTimer)
339
+ fn(arg)
340
+ }
341
+
342
+ if (timeout && timeout > 0) {
343
+ timer = setTimeout(() => {
344
+ timedOut = true
345
+ // SIGTERM the docker exec wrapper so we don't leak the process
346
+ // on a stuck setup. Matches execFile's `timeout` semantics.
347
+ if (child && !child.killed) {
348
+ try { child.kill('SIGTERM') } catch { /* already gone */ }
349
+ }
350
+ // #5126 — Escalate to SIGKILL if the child ignores SIGTERM. The
351
+ // promise otherwise only settles on `close`; a child stuck in an
352
+ // uninterruptible state would leave it pending forever. Cleared on
353
+ // close via settle(); unref'd so it never holds the loop open.
354
+ //
355
+ // Gate on `!settled` (the `close` hasn't fired) rather than
356
+ // `!child.killed`: Node flips `child.killed` to true the moment a
357
+ // signal is *delivered*, even if the process keeps running, so a
358
+ // `!child.killed` guard would skip the SIGKILL on exactly the
359
+ // stuck-child case this is meant to handle.
360
+ killTimer = setTimeout(() => {
361
+ if (!settled && child) {
362
+ try { child.kill('SIGKILL') } catch { /* already gone */ }
363
+ }
364
+ }, STREAM_SIGKILL_GRACE_MS)
365
+ if (killTimer && typeof killTimer.unref === 'function') killTimer.unref()
366
+ }, timeout)
367
+ // Don't let the timeout keep the event loop alive on its own.
368
+ if (timer && typeof timer.unref === 'function') timer.unref()
369
+ }
370
+
371
+ if (child.stdout) {
372
+ child.stdout.setEncoding('utf-8')
373
+ child.stdout.on('data', (chunk) => {
374
+ // #5127 — retain a bounded tail, not the full stream. onData still
375
+ // fires for every chunk below (streaming is never truncated).
376
+ stdout = appendCapped(stdout, chunk)
377
+ // Never let an onData throw escape and orphan the child.
378
+ try { onData(chunk, 'stdout') } catch { /* listener error — ignore */ }
379
+ })
380
+ }
381
+ if (child.stderr) {
382
+ child.stderr.setEncoding('utf-8')
383
+ child.stderr.on('data', (chunk) => {
384
+ stderr = appendCapped(stderr, chunk)
385
+ try { onData(chunk, 'stderr') } catch { /* listener error — ignore */ }
386
+ })
387
+ }
388
+
389
+ child.on('error', (err) => {
390
+ // spawn failure (docker binary missing, etc.) — surface with the
391
+ // same enriched-Error shape the buffered path uses.
392
+ const wrapped = new Error(stderr ? stderr.trim() : err.message)
393
+ wrapped.stdout = stdout
394
+ wrapped.stderr = stderr
395
+ if (err.code) wrapped.code = err.code
396
+ settle(reject, wrapped)
397
+ })
398
+
399
+ child.on('close', (code, signal) => {
400
+ if (timedOut) {
401
+ const err = new Error(`Command timed out after ${timeout}ms`)
402
+ err.killed = true
403
+ err.signal = signal || 'SIGTERM'
404
+ err.stdout = stdout
405
+ err.stderr = stderr
406
+ settle(reject, err)
407
+ return
408
+ }
409
+ if (code === 0) {
410
+ settle(resolve, { stdout, stderr })
411
+ return
412
+ }
413
+ // Non-zero exit — mirror the buffered-path enriched Error so the
414
+ // #5067 stdout/stderr capture is preserved for the failure event.
415
+ const wrapped = new Error(stderr ? stderr.trim() : `Command exited with code ${code}`)
416
+ wrapped.stdout = stdout
417
+ wrapped.stderr = stderr
418
+ if (code != null) wrapped.code = code
419
+ if (signal) wrapped.signal = signal
420
+ settle(reject, wrapped)
421
+ })
422
+ return
423
+ }
424
+
425
+ this._execFile('docker', execArgs, { encoding: 'utf-8', timeout }, (err, stdout, stderr) => {
426
+ if (err) {
427
+ // #5067 — Preserve both captured streams on failure. The error
428
+ // message stays stderr-first (existing callers rely on that
429
+ // shape for log lines), but we attach raw `stdout` / `stderr`
430
+ // properties so the caller can surface BOTH streams in a
431
+ // user-facing error event without re-running the command.
432
+ //
433
+ // npm install, repo bootstrap scripts, and apt-get commonly
434
+ // print the actually-useful diagnostic on stdout; dropping it
435
+ // here turned every post-create failure into a guess-and-retry.
436
+ //
437
+ // Falls through to err.message when stderr is empty, matching
438
+ // the pre-#5067 behaviour for stderr-silent commands. The
439
+ // post-create caller in docker-byok-session.js applies its own
440
+ // POST_CREATE_OUTPUT_CAP_BYTES truncation before serialising
441
+ // into the error event payload.
442
+ const wrapped = new Error(stderr ? stderr.trim() : err.message)
443
+ wrapped.stdout = stdout || ''
444
+ wrapped.stderr = stderr || ''
445
+ if (err.code) wrapped.code = err.code
446
+ if (err.signal) wrapped.signal = err.signal
447
+ if (typeof err.killed === 'boolean') wrapped.killed = err.killed
448
+ reject(wrapped)
449
+ } else {
450
+ resolve({ stdout: stdout || '', stderr: stderr || '' })
451
+ }
452
+ })
453
+ })
454
+ }
455
+
456
+ // ─────────────────────────────────────────────────────────────────────────
457
+ // streamCliInEnvironment — spawn a long-lived process, return ChildProcess
458
+ // ─────────────────────────────────────────────────────────────────────────
459
+
460
+ /**
461
+ * Spawn a process inside the container via `docker exec -i` and return the
462
+ * ChildProcess directly. Node's ChildProcess satisfies the SpawnedProcess
463
+ * interface (stdout/stderr/stdin streams + 'exit' event) that the SDK expects.
464
+ *
465
+ * Security hardening (must match `_createSpawnCallback` in docker-sdk-session.js):
466
+ * - `containerUser` is honored via `docker exec -u <user>` (never run as root)
467
+ * - Only env vars in `FORWARDED_ENV_KEYS` are forwarded from `opts.env`
468
+ * - `HOME` / `PATH` are set explicitly for the container user
469
+ * - The host's absolute path to `cli.js` (passed as `args[0]` by the SDK) is
470
+ * remapped to the container's installed CLI path
471
+ * - The host `cwd` is remapped to the container mount point (`/workspace`)
472
+ * - stderr is logged for debugging
473
+ *
474
+ * `docker-sdk-session.js#_createSpawnCallback` delegates here so there is a
475
+ * single source of truth for the docker-exec invocation shape.
476
+ *
477
+ * @param {string} containerId
478
+ * @param {Object} opts - See Backend interface in types.js
479
+ * @param {string} opts.cmd
480
+ * @param {string[]} [opts.args]
481
+ * @param {Object.<string,string>} [opts.env]
482
+ * @param {string} [opts.cwd] - Host CWD (remapped to container path)
483
+ * @param {AbortSignal} [opts.signal]
484
+ * @param {string} [opts.containerUser] - Non-root user inside the container (default: 'chroxy')
485
+ * @param {string} [opts.containerCliPath] - Container path to claude-code CLI (default fallback)
486
+ * @param {string} [opts.hostCwd] - Host CWD mount root (default: opts.cwd)
487
+ * @returns {import('child_process').ChildProcess}
488
+ */
489
+ streamCliInEnvironment(containerId, opts = {}) {
490
+ const {
491
+ cmd, args = [], env, cwd, signal,
492
+ containerUser = 'chroxy',
493
+ containerCliPath = DEFAULT_CONTAINER_CLI_PATH,
494
+ hostCwd,
495
+ } = opts
496
+
497
+ const dockerArgs = ['exec', '-i', '-u', containerUser]
498
+
499
+ // Remap host cwd to container mount point — the SDK passes the host's
500
+ // absolute path but the container only has /workspace.
501
+ if (cwd) {
502
+ const mountRoot = hostCwd || cwd
503
+ const containerCwd = cwd.startsWith(mountRoot)
504
+ ? '/workspace' + cwd.slice(mountRoot.length)
505
+ : '/workspace'
506
+ dockerArgs.push('--workdir', containerCwd)
507
+ }
508
+
509
+ // Forward only allowlisted env vars — never leak the whole host env.
510
+ if (env) {
511
+ for (const key of FORWARDED_ENV_KEYS) {
512
+ const val = env[key]
513
+ if (val !== undefined) {
514
+ dockerArgs.push('--env', `${key}=${val}`)
515
+ }
516
+ }
517
+ }
518
+
519
+ // Override HOME and PATH for the container user.
520
+ dockerArgs.push('--env', `HOME=/home/${containerUser}`)
521
+ dockerArgs.push('--env', 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin')
522
+
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
530
+ }
531
+
532
+ dockerArgs.push(containerId, cmd, ...containerArgs)
533
+
534
+ log.info(`docker exec stream: ${containerId.slice(0, 12)} ${cmd} ${containerArgs.slice(0, 2).join(' ')}`)
535
+
536
+ const child = (this._spawn || spawn)('docker', dockerArgs, {
537
+ stdio: ['pipe', 'pipe', 'pipe'],
538
+ })
539
+
540
+ // Log stderr for debugging.
541
+ if (child.stderr) {
542
+ child.stderr.on('data', (chunk) => {
543
+ const text = chunk.toString().trim()
544
+ if (text) log.info(`container stderr: ${text}`)
545
+ })
546
+ }
547
+
548
+ if (signal) {
549
+ if (signal.aborted) {
550
+ child.kill('SIGTERM')
551
+ } else {
552
+ signal.addEventListener('abort', () => {
553
+ if (!child.killed) child.kill('SIGTERM')
554
+ }, { once: true })
555
+ }
556
+ }
557
+
558
+ return child
559
+ }
560
+
561
+ // ─────────────────────────────────────────────────────────────────────────
562
+ // getEnvironmentStatus — inspect a container for running state
563
+ // ─────────────────────────────────────────────────────────────────────────
564
+
565
+ /** @returns {Promise<boolean>} */
566
+ getEnvironmentStatus(containerId) {
567
+ return this._inspectContainer(containerId)
568
+ }
569
+
570
+ // ─────────────────────────────────────────────────────────────────────────
571
+ // listEnvironments — enumerate all chroxy-env-* containers
572
+ // ─────────────────────────────────────────────────────────────────────────
573
+
574
+ /** @returns {Promise<string[]>} */
575
+ listEnvironments() {
576
+ return this._listChroxyContainers()
577
+ }
578
+
579
+ // ─────────────────────────────────────────────────────────────────────────
580
+ // commitEnvironment — docker commit (snapshot)
581
+ // ─────────────────────────────────────────────────────────────────────────
582
+
583
+ /** @returns {Promise<string>} image SHA */
584
+ commitEnvironment(containerId, imageTag) {
585
+ return this._commitContainer(containerId, imageTag)
586
+ }
587
+
588
+ // ─────────────────────────────────────────────────────────────────────────
589
+ // renameEnvironment — rename a container (used during atomic restore)
590
+ // ─────────────────────────────────────────────────────────────────────────
591
+
592
+ /** @returns {Promise<void>} */
593
+ renameEnvironment(containerId, newName) {
594
+ return this._renameContainer(containerId, newName)
595
+ }
596
+
597
+ // ─────────────────────────────────────────────────────────────────────────
598
+ // restoreEnvironment — start a snapshot image without re-running setup
599
+ // ─────────────────────────────────────────────────────────────────────────
600
+
601
+ /**
602
+ * @param {Object} opts - See Backend interface in types.js
603
+ * @returns {Promise<string>} Full container ID of the newly-started container
604
+ */
605
+ restoreEnvironment(opts) {
606
+ return this._startContainer(opts)
607
+ }
608
+
609
+ // ──────────────────────────────────────────────────────────────────────────
610
+ // Private Docker shellout helpers
611
+ // ──────────────────────────────────────────────────────────────────────────
612
+
613
+ _startContainer({ envId, cwd, image, memoryLimit, cpuLimit, containerEnv, forwardPorts, mounts }) {
614
+ return new Promise((resolve, reject) => {
615
+ const runArgs = [
616
+ 'run', '-d', '--init',
617
+ '--name', `chroxy-env-${envId}`,
618
+ // #6155: first-class ownership labels (survey identity, name as fallback).
619
+ '--label', `${CHROXY_MANAGED_LABEL}=true`,
620
+ '--label', `${CHROXY_LABEL_KIND}=env`,
621
+ '--memory', memoryLimit,
622
+ '--cpus', cpuLimit,
623
+ '--pids-limit', '512',
624
+ '--cap-drop', 'ALL',
625
+ '--security-opt', 'no-new-privileges',
626
+ '-v', `${cwd}:/workspace`,
627
+ '-w', '/workspace',
628
+ ]
629
+
630
+ const apiKey = process.env.ANTHROPIC_API_KEY
631
+ if (apiKey) {
632
+ runArgs.push('--env', `ANTHROPIC_API_KEY=${apiKey}`)
633
+ }
634
+
635
+ // DevContainer: extra environment variables
636
+ if (containerEnv) {
637
+ for (const [key, value] of Object.entries(containerEnv)) {
638
+ runArgs.push('--env', `${key}=${value}`)
639
+ }
640
+ }
641
+
642
+ // DevContainer: port forwards
643
+ if (forwardPorts) {
644
+ for (const port of forwardPorts) {
645
+ runArgs.push('-p', `${port}:${port}`)
646
+ }
647
+ }
648
+
649
+ // DevContainer: additional mounts
650
+ if (mounts) {
651
+ for (const mount of mounts) {
652
+ runArgs.push('-v', mount)
653
+ }
654
+ }
655
+
656
+ if (process.platform === 'linux') {
657
+ runArgs.push('--add-host', 'host.docker.internal:host-gateway')
658
+ }
659
+
660
+ runArgs.push(image, 'sleep', 'infinity')
661
+
662
+ this._execFile('docker', runArgs, { encoding: 'utf-8', timeout: 120_000 }, (err, stdout, stderr) => {
663
+ if (err) {
664
+ reject(new Error(stderr ? stderr.trim() : err.message))
665
+ return
666
+ }
667
+ resolve(stdout.trim())
668
+ })
669
+ })
670
+ }
671
+
672
+ _setupContainer(containerId, user) {
673
+ return new Promise((resolve, reject) => {
674
+ const setupCmd = [
675
+ `useradd -m -s /bin/bash ${user}`,
676
+ `chown ${user}:${user} /workspace`,
677
+ ].join(' && ')
678
+
679
+ this._execFile('docker', [
680
+ 'exec', containerId, 'bash', '-c', setupCmd,
681
+ ], { encoding: 'utf-8', timeout: 10_000 }, (err) => {
682
+ if (err) reject(new Error(`Failed to create container user: ${err.message}`))
683
+ else resolve()
684
+ })
685
+ })
686
+ }
687
+
688
+ _installClaudeCode(containerId) {
689
+ return new Promise((resolve, reject) => {
690
+ this._execFile('docker', [
691
+ 'exec', containerId, 'npm', 'install', '-g', '@anthropic-ai/claude-code',
692
+ ], { encoding: 'utf-8', timeout: 120_000 }, (err) => {
693
+ if (err) reject(new Error(`Failed to install Claude Code: ${err.message}`))
694
+ else resolve()
695
+ })
696
+ })
697
+ }
698
+
699
+ async _discoverCliPath(containerId) {
700
+ await this._installClaudeCode(containerId)
701
+
702
+ return new Promise((resolve) => {
703
+ this._execFile('docker', [
704
+ 'exec', containerId, 'npm', 'prefix', '-g',
705
+ ], { encoding: 'utf-8', timeout: 10_000 }, (err, stdout) => {
706
+ if (!err && stdout?.trim()) {
707
+ resolve(`${stdout.trim()}/lib/node_modules/@anthropic-ai/claude-code/cli.js`)
708
+ } else {
709
+ log.warn('Could not determine CLI path, using default')
710
+ resolve(DEFAULT_CONTAINER_CLI_PATH)
711
+ }
712
+ })
713
+ })
714
+ }
715
+
716
+ _commitContainer(containerId, imageTag) {
717
+ return new Promise((resolve, reject) => {
718
+ // #6155: stamp ownership labels onto the committed snapshot image (both env
719
+ // snapshots and BYOK pool snapshots commit through here) via `--change LABEL`,
720
+ // so host-prune can identify it by label with the `chroxy-*` tag as fallback.
721
+ const commitArgs = [
722
+ 'commit',
723
+ '--change', `LABEL ${CHROXY_MANAGED_LABEL}=true`,
724
+ '--change', `LABEL ${CHROXY_LABEL_KIND}=snapshot`,
725
+ containerId, imageTag,
726
+ ]
727
+ this._execFile('docker', commitArgs, { encoding: 'utf-8', timeout: 120_000 }, (err, stdout, stderr) => {
728
+ if (err) {
729
+ reject(new Error(stderr ? stderr.trim() : err.message))
730
+ return
731
+ }
732
+ resolve(stdout.trim())
733
+ })
734
+ })
735
+ }
736
+
737
+ _renameContainer(containerId, newName) {
738
+ return new Promise((resolve) => {
739
+ this._execFile('docker', ['rename', containerId, newName], { encoding: 'utf-8', timeout: 10_000 }, (err) => {
740
+ if (err) log.warn(`Failed to rename container ${containerId.slice(0, 12)}: ${err.message}`)
741
+ resolve()
742
+ })
743
+ })
744
+ }
745
+
746
+ _removeContainer(containerId) {
747
+ return new Promise((resolve) => {
748
+ this._execFile('docker', ['rm', '-f', containerId], { stdio: 'ignore' }, (err) => {
749
+ if (err) log.warn(`Failed to remove container ${containerId.slice(0, 12)}: ${err.message}`)
750
+ resolve()
751
+ })
752
+ })
753
+ }
754
+
755
+ _removeImage(imageTag) {
756
+ return new Promise((resolve) => {
757
+ this._execFile('docker', ['rmi', imageTag], { stdio: 'ignore' }, (err) => {
758
+ if (err) log.warn(`Failed to remove image ${imageTag}: ${err.message}`)
759
+ resolve()
760
+ })
761
+ })
762
+ }
763
+
764
+ _inspectContainer(containerId) {
765
+ return new Promise((resolve, reject) => {
766
+ this._execFile('docker', [
767
+ 'inspect', '--format', '{{.State.Running}}', containerId,
768
+ ], { encoding: 'utf-8', timeout: 10_000 }, (err, stdout) => {
769
+ if (err) {
770
+ reject(err)
771
+ return
772
+ }
773
+ resolve(stdout.trim() === 'true')
774
+ })
775
+ })
776
+ }
777
+
778
+ _listChroxyContainers() {
779
+ return new Promise((resolve, reject) => {
780
+ // --no-trunc is required: without it, `docker ps -q` returns 12-char
781
+ // truncated IDs that never match the full 64-char IDs persisted by
782
+ // createEnvironment, causing reconcile() to destroy every known
783
+ // container as an "orphan" (#3314).
784
+ this._execFile('docker', [
785
+ 'ps', '-q', '--no-trunc', '--filter', 'name=chroxy-env',
786
+ ], { encoding: 'utf-8', timeout: 10_000 }, (err, stdout) => {
787
+ if (err) {
788
+ reject(new Error(err.message))
789
+ return
790
+ }
791
+ const ids = stdout.trim().split('\n').filter(Boolean)
792
+ resolve(ids)
793
+ })
794
+ })
795
+ }
796
+
797
+ _runPostCreateCommand(containerId, command) {
798
+ return new Promise((resolve, reject) => {
799
+ log.info(`Running postCreateCommand: ${command}`)
800
+ this._execFile('docker', [
801
+ 'exec', containerId, 'bash', '-c', command,
802
+ ], { encoding: 'utf-8', timeout: 120_000 }, (err) => {
803
+ if (err) reject(new Error(`postCreateCommand failed: ${err.message}`))
804
+ else resolve()
805
+ })
806
+ })
807
+ }
808
+
809
+ // #5124: `composeFile` may be a single path or an ARRAY of paths
810
+ // (devcontainer.json `dockerComposeFile` base + overrides). Normalise a
811
+ // lone string to a single-element array and drop non-string/empty entries
812
+ // so every call site emits `-f <file>` flags in declared order.
813
+ // Backward-compatible: existing single-file callers pass a string and get
814
+ // one `-f`.
815
+ _composeFileList(composeFile) {
816
+ const files = Array.isArray(composeFile) ? composeFile : [composeFile]
817
+ return files.filter((f) => typeof f === 'string' && f.length > 0)
818
+ }
819
+
820
+ _composeUp(composeFile, project, cwd, envFile) {
821
+ return new Promise((resolve, reject) => {
822
+ // `docker compose --env-file <path>` (before the subcommand) sets the
823
+ // env used for compose-file interpolation, so a compose service that
824
+ // declares `environment: [ANTHROPIC_API_KEY]` or `${ANTHROPIC_API_KEY}`
825
+ // picks the value up without the operator having to hand-edit their
826
+ // compose file. The file is short-lived (tmpfile created + unlinked
827
+ // by the caller) and lives at 0600 so the key never appears in `ps`
828
+ // output. (#5079)
829
+ //
830
+ // #5124: compose merges a base + overrides via a repeated `-f` flag in
831
+ // DECLARED ORDER (later files override earlier ones), so we emit one
832
+ // `-f <file>` per entry rather than a single `-f`.
833
+ const files = this._composeFileList(composeFile)
834
+ // Fail fast on an empty/invalid file set rather than letting
835
+ // `docker compose up` silently fall back to a default compose file in
836
+ // cwd. The pre-#5124 single-`-f` path errored on an undefined file, so
837
+ // this preserves that fail-fast contract for the array path too.
838
+ if (files.length === 0) {
839
+ reject(new Error('docker compose up requires at least one compose file'))
840
+ return
841
+ }
842
+ const args = ['compose']
843
+ if (envFile) args.push('--env-file', envFile)
844
+ for (const file of files) {
845
+ args.push('-f', file)
846
+ }
847
+ args.push('-p', project, 'up', '-d')
848
+ this._execFile('docker', args, { encoding: 'utf-8', timeout: 120_000, cwd }, (err, _stdout, stderr) => {
849
+ if (err) {
850
+ reject(new Error(stderr ? stderr.trim() : err.message))
851
+ return
852
+ }
853
+ resolve()
854
+ })
855
+ })
856
+ }
857
+
858
+ _composeDown(composeFile, project, cwd) {
859
+ return new Promise((resolve) => {
860
+ // #5124: tear the stack down with the SAME `-f` file set used to bring
861
+ // it up, in declared order, so the merged config resolves identically.
862
+ const args = ['compose']
863
+ for (const file of this._composeFileList(composeFile)) {
864
+ args.push('-f', file)
865
+ }
866
+ args.push('-p', project, 'down', '--remove-orphans')
867
+ this._execFile('docker', args, { encoding: 'utf-8', timeout: 30_000, cwd }, (err) => {
868
+ if (err) log.warn(`docker compose down failed: ${err.message}`)
869
+ resolve()
870
+ })
871
+ })
872
+ }
873
+
874
+ _composePrimaryContainerId(project, primaryService) {
875
+ return new Promise((resolve, reject) => {
876
+ const args = ['compose', '-p', project, 'ps', '--format', 'json']
877
+ if (primaryService) args.push(primaryService)
878
+
879
+ this._execFile('docker', args, { encoding: 'utf-8', timeout: 10_000 }, (err, stdout) => {
880
+ if (err) {
881
+ reject(new Error(`Failed to list compose containers: ${err.message}`))
882
+ return
883
+ }
884
+ // docker compose ps --format json outputs one JSON object per line
885
+ const lines = stdout.trim().split('\n').filter(Boolean)
886
+ if (lines.length === 0) {
887
+ reject(new Error('No running containers found in compose project'))
888
+ return
889
+ }
890
+ try {
891
+ const container = JSON.parse(lines[0])
892
+ resolve(container.ID || container.Id)
893
+ } catch {
894
+ reject(new Error('Failed to parse compose container info'))
895
+ }
896
+ })
897
+ })
898
+ }
899
+
900
+ _composeServices(project) {
901
+ return new Promise((resolve) => {
902
+ this._execFile('docker', [
903
+ 'compose', '-p', project, 'ps', '--format', 'json',
904
+ ], { encoding: 'utf-8', timeout: 10_000 }, (err, stdout) => {
905
+ if (err) {
906
+ log.warn(`Failed to list compose services for project "${project}": ${err.message}`)
907
+ resolve([])
908
+ return
909
+ }
910
+ try {
911
+ const lines = stdout.trim().split('\n').filter(Boolean)
912
+ const services = lines.map(line => {
913
+ const c = JSON.parse(line)
914
+ return {
915
+ name: c.Service || c.Name,
916
+ status: c.State || 'unknown',
917
+ primary: false,
918
+ }
919
+ })
920
+ resolve(services)
921
+ } catch (parseErr) {
922
+ log.warn(`Failed to parse compose services for project "${project}": ${parseErr.message}`)
923
+ resolve([])
924
+ }
925
+ })
926
+ })
927
+ }
928
+ }
929
+
930
+ // Re-exported for parity with docker-sdk-session.js and for tests
931
+ export { FORWARDED_ENV_KEYS, DEFAULT_CONTAINER_CLI_PATH }