@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,2172 @@
1
+ /**
2
+ * docker-byok provider (#4053) — runs the claude-byok agent loop on the
3
+ * host (chroxy speaks HTTPS to api.anthropic.com directly), but redirects
4
+ * built-in tool execution (Read / Write / Edit / Bash / Glob / Grep) into
5
+ * an isolated Docker container.
6
+ *
7
+ * Design summary
8
+ * --------------
9
+ * BYOK is in-process: the agent loop runs inside chroxy and there is no
10
+ * subprocess for the model. The isolation boundary here is the TOOLS —
11
+ * the model can still read and write files, but those file ops act on
12
+ * the CONTAINER'S filesystem (which mounts the host cwd at /workspace),
13
+ * and Bash commands the model wants to run execute inside the container
14
+ * with `--cap-drop ALL`, a pids cap, and a non-root user. Anything else
15
+ * — model streaming, permission gating, MCP dispatch, cost accounting —
16
+ * is inherited unchanged from ClaudeByokSession.
17
+ *
18
+ * What's in v1 (this file)
19
+ * ------------------------
20
+ * - Container lifecycle: start (with preflight `docker info`), destroy
21
+ * - Workspace volume mount at /workspace (cwd → /workspace, same as
22
+ * docker-sdk-session.js)
23
+ * - Tool dispatch override (`_dispatchBuiltinTool`) for the file/bash
24
+ * surface. Read uses `cat`; Write uses `tee` via stdin; Edit reads,
25
+ * mutates host-side, writes back; Bash/Glob/Grep run via
26
+ * `bash -c` inside the container.
27
+ * - ANTHROPIC_API_KEY forwarded into the container at `docker run`
28
+ * time (the AC asks for it; the running agent in chroxy is what
29
+ * actually authenticates to the Anthropic API — the container has
30
+ * the env in case a Bash command needs it, e.g. a `claude -p` smoke
31
+ * test inside the container).
32
+ * - TodoWrite + WebFetch stay host-side (TodoWrite is an in-memory
33
+ * map; WebFetch is HTTP from chroxy and doesn't touch the FS).
34
+ * - MCP, Task subagent, permission gating, cost accounting — all
35
+ * inherited verbatim from ClaudeByokSession.
36
+ *
37
+ * Deferred (follow-up issues)
38
+ * ---------------------------
39
+ * - (none currently tracked — see "Recently added" below)
40
+ *
41
+ * Recently added
42
+ * --------------
43
+ * - Per-session container reuse / pooling (#5022 — landed)
44
+ * - DevContainer / Compose-driven environments (#5024 — landed)
45
+ * - Snapshot / restore (#5023 — landed)
46
+ * - postCreateCommand hook (#5025) — opt-in DevContainer-style setup
47
+ * command (single string or array) that runs once inside the
48
+ * container before any tool dispatch. Marker-cached on /tmp so a
49
+ * pooled container that already ran the same command skips it.
50
+ * This is the explicit ctor opt with marker caching + timeout +
51
+ * error handling. The `useDevcontainer` overlay parses a
52
+ * devcontainer.json's own `postCreateCommand` field separately and
53
+ * runs it non-fatally inside `_startContainer` — that path predates
54
+ * #5025 and remains the devcontainer-config integration.
55
+ *
56
+ * DevContainer + Compose (#5024)
57
+ * -----------------------------
58
+ * - `useDevcontainer: true` — start() parses .devcontainer/
59
+ * devcontainer.json (or .devcontainer.json) from cwd, validates
60
+ * mounts/env via the shared `devcontainer-config.js` helper, then
61
+ * overlays `image` / `remoteUser` / `containerEnv` / `mounts` /
62
+ * `forwardPorts` / `postCreateCommand` onto the bare-image launch.
63
+ * Explicit constructor opts always win — devcontainer.json is the
64
+ * fallback default.
65
+ * - `composeFile: '<path>'` + optional `composeService: '<name>'` —
66
+ * start() shells `docker compose up -d` against the file (under a
67
+ * session-scoped project id), identifies the named service's
68
+ * container, and attaches to it. destroy() runs `docker compose
69
+ * down --remove-orphans` against the same project so the whole
70
+ * stack tears down. Pooling is disabled in compose mode.
71
+ * - Default (neither opt) — original v1 bare-image launch path.
72
+ *
73
+ * DevContainer build / dockerFile / dockerComposeFile (#5078)
74
+ * ----------------------------------------------------------
75
+ * - `build` (object: dockerfile / context / args / target) or the
76
+ * legacy `dockerFile` string in devcontainer.json — start() shells
77
+ * `docker build` against the project dir and uses the resulting tag
78
+ * as the image. The tag is a deterministic SHA-256 of the build
79
+ * inputs, so a repeat session with identical inputs reuses the
80
+ * already-built image (docker's own layer cache makes the rebuild a
81
+ * fast no-op). `build.target` threads to `docker build --target`.
82
+ * `build.context` (and `..`) resolves relative to the
83
+ * devcontainer.json DIRECTORY, then is contained to the project cwd —
84
+ * a context that escapes the workspace is refused. An explicit `image`
85
+ * constructor opt always wins over a devcontainer build.
86
+ * - `dockerComposeFile` (string | array) in devcontainer.json — when
87
+ * `useDevcontainer` is set and no explicit `composeFile` opt was
88
+ * passed, the file (resolved relative to the devcontainer.json dir)
89
+ * is treated as if the operator passed `composeFile`, and the primary
90
+ * service is taken from devcontainer.json's `service` field. The same
91
+ * compose lifecycle (up / attach / down) and pooling-disabled posture
92
+ * as the explicit `composeFile` opt applies. Arrays are threaded
93
+ * through in full as a base + override overlay — `_composeUp`/
94
+ * `_composeDown` emit one `-f <file>` per entry in declared order so
95
+ * compose merges them (later files override earlier ones). (#5124)
96
+ *
97
+ * Snapshot / restore (#5023)
98
+ * --------------------------
99
+ * - `snapshot({ name? })` runs `docker commit <containerId>
100
+ * chroxy-byok-snap:<rand>-<ts>` via the backend, marks the live
101
+ * container "soiled" so the pool evicts it on release (#5043), and
102
+ * writes a small metadata JSON to `snapshotsDir` (defaults to
103
+ * `~/.chroxy/snapshots/`, override via `CHROXY_CONFIG_DIR`) so ops
104
+ * can list snapshot names without parsing `docker image ls`.
105
+ * - To restore, pass `snapshotImage: <tag>` to the constructor. The
106
+ * session uses that tag as the image at `docker run` time and skips
107
+ * the `useradd` + `chown` setup (the snapshot already has those
108
+ * baked in). The restored container is auto-soiled — restoring
109
+ * previous state into a live container couples it to the snapshot's
110
+ * original conversation history.
111
+ * - Pool interaction: a snapshotted or restored container goes
112
+ * through `release()` as normal, but the pool sees the soil marker
113
+ * and evicts inline instead of pooling. UI / multi-snapshot listing
114
+ * is deferred to a follow-up.
115
+ *
116
+ * Per `project_worktree_before_docker.md` in project memory: worktree
117
+ * isolation happens BEFORE Docker. This class does not own worktree
118
+ * setup — the SessionManager / environment-manager already worktree the
119
+ * cwd before constructing the session, and we mount whatever cwd the
120
+ * SessionManager hands us.
121
+ */
122
+
123
+ import { execFile } from 'child_process'
124
+ import { mkdirSync, writeFileSync, unlinkSync } from 'fs'
125
+ import { createHash, randomBytes } from 'crypto'
126
+ import { homedir, tmpdir } from 'os'
127
+ import { isAbsolute, join, posix, resolve, sep } from 'path'
128
+ import { ClaudeByokSession } from './byok-session.js'
129
+ import {
130
+ applyEdit,
131
+ GLOB_PATTERN_SHELL_METACHARS,
132
+ buildGlobCommand,
133
+ buildGrepArgs,
134
+ buildGrepCommand,
135
+ } from './built-in-tools/tool-transforms.js'
136
+ import { DockerBackend } from './environments/backends/docker.js'
137
+ import { classifyDockerError } from './docker-session.js'
138
+ import { buildPoolKey, getSharedPool, isPoolEnabled } from './docker-byok-pool.js'
139
+ import { getSharedComposeStateStore } from './byok-compose-state-shared.js'
140
+ import { createLogger } from './logger.js'
141
+ import { writeFileRestricted } from './platform.js'
142
+ import {
143
+ parseDevContainer,
144
+ validateMounts,
145
+ sanitizeContainerEnv,
146
+ } from './devcontainer-config.js'
147
+ import { isOperatorTimeoutInRange } from './duration.js'
148
+ import { getErrorMessage } from './utils/error-message.js'
149
+ import { VALID_USERNAME_RE } from './utils/validation-patterns.js'
150
+
151
+ const log = createLogger('docker-byok')
152
+
153
+ const DEFAULT_IMAGE = 'node:22-slim'
154
+ const DEFAULT_MEMORY_LIMIT = '2g'
155
+ const DEFAULT_CPU_LIMIT = '2'
156
+ const DEFAULT_USER = 'chroxy'
157
+ const CONTAINER_WORKSPACE = '/workspace'
158
+
159
+ /**
160
+ * Cap on Read output size to keep tool_result payloads bounded.
161
+ * Mirrors the host-side `readFileTool` philosophy — large files should
162
+ * be sliced via `offset`/`limit`.
163
+ */
164
+ const READ_MAX_BYTES = 256 * 1024
165
+
166
+ /**
167
+ * Cap on Write payload size. Larger writes should be done by the model
168
+ * via a sequence of smaller writes or — better — a Bash command that
169
+ * stages the content from a file already inside the container.
170
+ */
171
+ const WRITE_MAX_BYTES = 512 * 1024
172
+
173
+ /**
174
+ * Default cap on how long a postCreateCommand can run before it's
175
+ * treated as a hang. Five minutes mirrors what DevContainer-style
176
+ * setups (npm install, apt-get install) typically need on first run
177
+ * while still bounding a runaway script. Callers can override via the
178
+ * `postCreateTimeoutMs` ctor opt (#5025).
179
+ */
180
+ const DEFAULT_POST_CREATE_TIMEOUT_MS = 5 * 60 * 1000
181
+
182
+ /**
183
+ * Where the post-create completion marker lives inside the container.
184
+ * `/tmp` survives across `docker exec` invocations within the same
185
+ * container (the layered FS persists for the container's lifetime), so
186
+ * a future session that reuses the same container via the pool can
187
+ * probe this file and skip re-running an already-applied setup.
188
+ *
189
+ * The marker filename embeds a SHA-256 fingerprint of the command, so
190
+ * a CHANGED command produces a different marker and is re-applied.
191
+ */
192
+ const POST_CREATE_MARKER_PREFIX = '/tmp/.chroxy-post-create-'
193
+
194
+ /**
195
+ * #5067 — Per-stream cap on captured postCreateCommand output included
196
+ * in the `post_create_command_failed` error event payload. Sized so the
197
+ * trailing tail of a typical `npm install` failure (the lines that
198
+ * actually identify the broken package) survives, while a runaway
199
+ * script that spammed MBs of progress can't push the WS frame past the
200
+ * encryption ceiling. We keep the TAIL because diagnostic info (the
201
+ * actual exception, ENOENT, exit codes) almost always lands at the end.
202
+ */
203
+ const POST_CREATE_OUTPUT_CAP_BYTES = 4 * 1024
204
+
205
+ /**
206
+ * Truncate a captured stream to the last `cap` bytes, emitting a
207
+ * `[truncated — first N bytes omitted]` prefix when we drop anything.
208
+ * The header is a single line so log scrapers can detect truncation
209
+ * without parsing the whole payload. Bytes (not chars) — a UTF-8
210
+ * multibyte sequence at the cut boundary will be replaced by U+FFFD
211
+ * when decoded, which is acceptable for a diagnostic tail.
212
+ */
213
+ function tailCapture(text, cap = POST_CREATE_OUTPUT_CAP_BYTES) {
214
+ if (typeof text !== 'string' || text.length === 0) return ''
215
+ const buf = Buffer.from(text, 'utf8')
216
+ if (buf.length <= cap) return text
217
+ const omitted = buf.length - cap
218
+ const tail = buf.subarray(buf.length - cap).toString('utf8')
219
+ return `[truncated — first ${omitted} bytes omitted]\n${tail}`
220
+ }
221
+
222
+ /**
223
+ * Map a host-absolute file_path under this.cwd into the container's
224
+ * /workspace mount. Defends against path traversal by refusing absolute
225
+ * paths that aren't under cwd. Relative paths are joined onto
226
+ * /workspace using POSIX semantics — the container is always Linux.
227
+ *
228
+ * Returns a string the model can pass into a `docker exec` command, or
229
+ * throws an Error whose message is safe to surface as a tool_result.
230
+ *
231
+ * @param {string} filePath
232
+ * @param {string} hostCwd
233
+ */
234
+ export function remapToContainerPath(filePath, hostCwd) {
235
+ if (typeof filePath !== 'string' || filePath.length === 0) {
236
+ const err = new Error('file_path is required')
237
+ err.code = 'EINVAL'
238
+ throw err
239
+ }
240
+ if (typeof hostCwd !== 'string' || hostCwd.length === 0) {
241
+ const err = new Error('host cwd is not configured')
242
+ err.code = 'EINVAL'
243
+ throw err
244
+ }
245
+ // POSIX containers — normalise the host cwd to a POSIX-style mount
246
+ // root so prefix-matching works on Windows hosts too. Trailing
247
+ // slashes get stripped so `cwd === '/Users/foo'` and the file
248
+ // `/Users/foo` itself map to '/workspace' rather than '/workspace/'.
249
+ const normHostCwd = hostCwd.replace(/\/+$/, '')
250
+ if (isAbsolute(filePath)) {
251
+ if (filePath === normHostCwd) return CONTAINER_WORKSPACE
252
+ if (filePath.startsWith(normHostCwd + '/')) {
253
+ const suffix = filePath.slice(normHostCwd.length)
254
+ const joined = posix.join(CONTAINER_WORKSPACE, suffix)
255
+ // The suffix preserves a leading `/`, so a payload like
256
+ // `${cwd}/../etc/passwd` makes posix.join() see the second
257
+ // argument as absolute and DISCARD the /workspace prefix — the
258
+ // result would be `/etc/passwd`. Re-assert the same containment
259
+ // guard as the relative branch so a `..` after the cwd prefix
260
+ // can't escape the workspace mount.
261
+ if (joined !== CONTAINER_WORKSPACE && !joined.startsWith(CONTAINER_WORKSPACE + '/')) {
262
+ const err = new Error(`path outside workspace: ${filePath} resolves to ${joined}`)
263
+ err.code = 'EACCES'
264
+ throw err
265
+ }
266
+ return joined
267
+ }
268
+ const err = new Error(`path outside workspace: ${filePath} is not under ${normHostCwd}`)
269
+ err.code = 'EACCES'
270
+ throw err
271
+ }
272
+ // Relative path → join onto /workspace.
273
+ const joined = posix.join(CONTAINER_WORKSPACE, filePath)
274
+ if (joined !== CONTAINER_WORKSPACE && !joined.startsWith(CONTAINER_WORKSPACE + '/')) {
275
+ // posix.join() collapses `../` segments — if the result escapes
276
+ // /workspace, refuse the call. The `+ '/'` is important so that
277
+ // `/workspaceX` (some sibling path that happens to share the
278
+ // prefix) can't masquerade as the workspace.
279
+ const err = new Error(`path outside workspace: ${filePath} resolves to ${joined}`)
280
+ err.code = 'EACCES'
281
+ throw err
282
+ }
283
+ return joined
284
+ }
285
+
286
+ /**
287
+ * Quote a string for safe interpolation inside single-quoted bash
288
+ * arguments. Mirrors the shellQuote pattern used elsewhere in chroxy.
289
+ */
290
+ function shellQuote(s) {
291
+ return `'${String(s).replace(/'/g, `'\\''`)}'`
292
+ }
293
+
294
+ /**
295
+ * Coerce a `postCreateCommand` opt into a single shell-string that the
296
+ * container can run via `bash -c`. DevContainer's spec allows either a
297
+ * single command string or an array of strings; we honour both. Arrays
298
+ * are joined with ` && ` so every step must succeed — if step 1 fails,
299
+ * step 2 doesn't run, and the overall exit code is non-zero (which the
300
+ * session treats as a setup failure).
301
+ *
302
+ * Returns `null` when the opt is missing, an empty string, or an empty
303
+ * array — those all mean "no post-create hook" and let `start()` skip
304
+ * the marker probe entirely (#5025).
305
+ *
306
+ * Strictness: any non-string entry inside an array throws (#5063 review
307
+ * — Copilot). Silently dropping a non-string entry would mask
308
+ * misconfiguration (e.g. `postCreateCommand: ['npm install', null,
309
+ * 'npm test']` would have run install + test, skipping the failed
310
+ * middle slot, instead of failing loudly at construction). The same
311
+ * goes for empty-string entries — those almost certainly indicate a
312
+ * typo / templating bug and should be surfaced.
313
+ */
314
+ export function normalizePostCreateCommand(value) {
315
+ if (value == null) return null
316
+ if (typeof value === 'string') {
317
+ const trimmed = value.trim()
318
+ return trimmed.length > 0 ? trimmed : null
319
+ }
320
+ if (Array.isArray(value)) {
321
+ if (value.length === 0) return null
322
+ const parts = value.map((entry, idx) => {
323
+ if (typeof entry !== 'string') {
324
+ throw new Error(
325
+ `postCreateCommand[${idx}] must be a string (got ${entry === null ? 'null' : typeof entry})`,
326
+ )
327
+ }
328
+ const trimmed = entry.trim()
329
+ if (trimmed.length === 0) {
330
+ throw new Error(`postCreateCommand[${idx}] must be a non-empty string`)
331
+ }
332
+ return trimmed
333
+ })
334
+ return parts.join(' && ')
335
+ }
336
+ throw new Error('postCreateCommand must be a string or an array of strings')
337
+ }
338
+
339
+ export class DockerByokSession extends ClaudeByokSession {
340
+ // #5891: declare Claude-family membership explicitly rather than inheriting it
341
+ // from ClaudeByokSession. Docker-BYOK runs Claude/Anthropic-key models in a
342
+ // container, so it IS Claude-family — its model ids take the soft-fallback path
343
+ // (an unknown id falls back to a Claude default) rather than the strict
344
+ // rejection non-Claude providers get; same as the base. Made explicit so a
345
+ // future non-Claude subclass can't silently inherit `true` (enforced by
346
+ // scripts/lint-claude-family-explicit.sh).
347
+ static claudeFamily = true
348
+
349
+ static get displayLabel() {
350
+ return 'Claude (BYOK — Docker container)'
351
+ }
352
+
353
+ static get capabilities() {
354
+ return { ...ClaudeByokSession.capabilities, containerized: true }
355
+ }
356
+
357
+ /**
358
+ * #5069 — surface streamed `postCreateCommand` output. `setup_log` is a
359
+ * transient event carrying one chunk of the container-setup command's
360
+ * stdout/stderr as it runs, so the dashboard / mobile client can show
361
+ * progress during a multi-minute `npm install` / `apt-get` instead of a
362
+ * silent session. session-manager.js:_wireSessionEvents reads
363
+ * `customEvents` to build the TRANSIENT_EVENTS set it bridges to
364
+ * `session_event` listeners; an event missing from this list fires on the
365
+ * local EventEmitter and never reaches ws-forwarding. We extend (rather
366
+ * than replace) the inherited BYOK set so tool_start / tool_result /
367
+ * tool_input_delta / agent_* keep flowing.
368
+ */
369
+ static get customEvents() {
370
+ return [...ClaudeByokSession.customEvents, 'setup_log']
371
+ }
372
+
373
+ /**
374
+ * Preflight credentials block. Same shape as ClaudeByokSession — the
375
+ * agent loop still runs on the host so the credential set / hint /
376
+ * required-ness is identical to host-side BYOK. The container itself
377
+ * does NOT need to be authenticated to talk to Anthropic; chroxy
378
+ * does that. ANTHROPIC_API_KEY is forwarded as a convenience for the
379
+ * model's Bash command (e.g. a one-off `curl api.anthropic.com`).
380
+ */
381
+ static get preflight() {
382
+ return {
383
+ ...ClaudeByokSession.preflight,
384
+ label: 'Claude (BYOK — Docker container)',
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Reuse ClaudeByokSession's resolveAuth: same env vars, same
390
+ * credential file path, same readiness rules. The container's
391
+ * absence of ~/.chroxy state does NOT change anything here — the
392
+ * agent loop runs on the host.
393
+ */
394
+ static resolveAuth(env, helpers) {
395
+ return ClaudeByokSession.resolveAuth(env, helpers)
396
+ }
397
+
398
+ /**
399
+ * @param {object} [opts]
400
+ * @param {string} [opts.image='node:22-slim'] Container image
401
+ * @param {string} [opts.memoryLimit='2g'] `docker run --memory`
402
+ * @param {string} [opts.cpuLimit='2'] `docker run --cpus`
403
+ * @param {string} [opts.containerUser='chroxy'] Non-root user inside container
404
+ * @param {string} [opts.containerId] Attach to an existing container
405
+ * instead of launching one (env-manager managed). When omitted, the
406
+ * session owns the container and tears it down on destroy().
407
+ * @param {boolean} [opts.useDevcontainer=false] #5024: Opt-in flag
408
+ * — when true, parse `.devcontainer/devcontainer.json` (or the
409
+ * `.devcontainer.json` sidecar) from cwd and overlay its
410
+ * `image` / `remoteUser` / `containerEnv` / `mounts` /
411
+ * `forwardPorts` / `postCreateCommand` onto the launch. Explicit
412
+ * constructor opts always win; devcontainer.json is the fallback
413
+ * default. No-op when the file is absent or malformed.
414
+ *
415
+ * This is opt-in (not auto-discovery from cwd) so existing
416
+ * sessions whose cwd happens to contain a devcontainer.json don't
417
+ * silently change behaviour. The caller (CLI flag, dashboard
418
+ * toggle, env-manager) is responsible for setting this when the
419
+ * user has asked for devcontainer-driven environments.
420
+ * @param {string} [opts.composeFile] #5024: Path to a
421
+ * `docker-compose.yml`. When set, start() runs `docker compose up
422
+ * -d` under a session-scoped project id and attaches to the named
423
+ * service container. destroy() runs `docker compose down
424
+ * --remove-orphans` to tear the whole stack down. Pooling is
425
+ * disabled in this mode.
426
+ *
427
+ * This is opt-in (not auto-discovery from cwd) — see the note on
428
+ * `useDevcontainer` above. The caller passes the path explicitly.
429
+ * @param {string} [opts.composeService] #5024: Optional
430
+ * service name from the compose file to attach to (the "primary"
431
+ * service). When omitted, the first service from `docker compose
432
+ * ps` is picked.
433
+ * @param {string|string[]} [opts.postCreateCommand=null]
434
+ * #5025: DevContainer-style setup command(s) that run inside the
435
+ * container once after launch and before the session is marked
436
+ * ready. Strings run verbatim; arrays are joined with ` && ` so
437
+ * every step must succeed. A SHA-256 marker file on /tmp prevents
438
+ * re-execution when the same container is reused across sessions
439
+ * (#5022 pool). Only runs for owned containers — externally-managed
440
+ * containers are the caller's responsibility. This ctor opt is
441
+ * independent of (and runs in addition to) any `postCreateCommand`
442
+ * field parsed from devcontainer.json under `useDevcontainer`.
443
+ * @param {number} [opts.postCreateTimeoutMs=300_000]
444
+ * #5025: Cap on how long postCreateCommand can run before it's
445
+ * treated as a hang (default 5 minutes).
446
+ * @param {string} [opts.snapshotImage] Restore from a snapshot tag
447
+ * produced by a previous `snapshot()` call (#5023). When set, the
448
+ * container is launched from this image instead of `opts.image`, the
449
+ * `useradd` setup is skipped (the snapshot has the user baked in),
450
+ * and the live container is auto-soiled so it does NOT return to the
451
+ * pool (a restored container's FS is coupled to the snapshot's
452
+ * original conversation).
453
+ * @param {string} [opts.snapshotsDir] Override the directory
454
+ * snapshot metadata JSONs are written to. Defaults to
455
+ * `${CHROXY_CONFIG_DIR ?? ~/.chroxy}/snapshots`. Tests inject a tmp dir.
456
+ * @param {string} [opts.sourceSessionId] Optional session id to
457
+ * embed in snapshot metadata. The session itself has no sessionId
458
+ * field; the SessionManager owns the id and can pass it through.
459
+ * @param {object} [opts._dockerBackend] Test seam — pre-built backend
460
+ * @param {Function} [opts._execFile] Test seam — used by preflight
461
+ * (defaults to child_process.execFile)
462
+ * @param {object} [opts._pool] Test seam — explicit pool
463
+ * instance. When omitted and pooling is enabled (via env), the shared
464
+ * process-wide pool is used. When omitted and pooling is disabled,
465
+ * pooling is skipped entirely (per-session lifecycle only).
466
+ * @param {Record<string,string>} [opts._poolEnv] Test seam — alternate env
467
+ * for pool enablement, defaults to `process.env`.
468
+ */
469
+ constructor(opts = {}) {
470
+ // Forward every BaseSession/ClaudeByokSession opt verbatim via
471
+ // spread (`...opts`) so the lint-session-opt-forwarding linter is
472
+ // satisfied and we never accidentally drop a BaseSession opt
473
+ // (`feedback_jsonl_subprocess_middle_layer.md` in project memory).
474
+ // Override `provider` so the session reports `docker-byok` for
475
+ // wire-protocol consumers (display label, capabilities matrix).
476
+ super({ ...opts, provider: opts.provider || 'docker-byok' })
477
+
478
+ // #5024: DevContainer auto-discovery (off by default). When set,
479
+ // start() reads `.devcontainer/devcontainer.json` from cwd and
480
+ // overlays its `image` / `remoteUser` / `containerEnv` / `mounts` /
481
+ // `forwardPorts` / `postCreateCommand` onto the session defaults.
482
+ // Explicit constructor opts always win — devcontainer.json acts as
483
+ // the "fallback default" when the operator hasn't set a field.
484
+ this._useDevcontainer = opts.useDevcontainer === true
485
+ // Record raw caller opts now so the merge in start() can tell
486
+ // "caller set image=X" apart from "default".
487
+ this._explicitImage = opts.image
488
+ this._explicitContainerUser = opts.containerUser
489
+ this._dcConfig = null
490
+ // #5078: normalised devcontainer.json `build` / `dockerFile` spec,
491
+ // resolved in `_resolveDevContainer()`. Stays null until then (or
492
+ // when no build is declared / an explicit image opt wins).
493
+ this._dcBuild = null
494
+ // #5080: short SHA-1 of the resolved devcontainer overlay, used to
495
+ // namespace the pool key so a changed devcontainer.json invalidates
496
+ // any pooled container provisioned against the old config. Stays
497
+ // null until `_resolveDevContainer()` runs (or `useDevcontainer` is
498
+ // false), which keeps the pool key shape backward-compatible for
499
+ // non-devcontainer sessions.
500
+ this._devcontainerFingerprint = null
501
+
502
+ // #5024: Docker Compose support. When `composeFile` is set, start()
503
+ // shells out `docker compose up -d` against that file and attaches
504
+ // to the named service container instead of running a fresh image.
505
+ // The compose stack is owned by THIS session: destroy() tears it
506
+ // down with `docker compose down --remove-orphans`. To attach to a
507
+ // pre-existing compose stack, pass `containerId` instead.
508
+ this._composeFile = typeof opts.composeFile === 'string' && opts.composeFile.trim()
509
+ ? opts.composeFile.trim()
510
+ : null
511
+ this._composeService = typeof opts.composeService === 'string' && opts.composeService.trim()
512
+ ? opts.composeService.trim()
513
+ : null
514
+ // Compose project id — a session-scoped suffix so two sessions
515
+ // pointed at the same compose file get isolated stacks. Mirrors
516
+ // environment-manager's `chroxy-${envId}` naming. Resolved lazily
517
+ // in start() so construction stays deterministic.
518
+ this._composeProject = null
519
+ // #5079 — host-side tmpfile path for the compose env-file. Written
520
+ // at compose-up time when ANTHROPIC_API_KEY is present in the host
521
+ // env, passed to every `docker exec` via `--env-file` so the key is
522
+ // forwarded into model-spawned commands WITHOUT exposing it on the
523
+ // host's process-listing (`docker exec --env KEY=secret` is visible
524
+ // in `ps`). The file is mode 0600 and lives under os.tmpdir(); it's
525
+ // unlinked on destroy() (and best-effort on start-failure paths).
526
+ this._composeEnvFile = null
527
+ // Test seam: override the writer / unlinker so tests can assert the
528
+ // file lifecycle without touching the real filesystem.
529
+ this._writeEnvFile = opts._writeEnvFile || ((p, c) => writeFileSync(p, c, { mode: 0o600 }))
530
+ this._unlinkEnvFile = opts._unlinkEnvFile || ((p) => { try { unlinkSync(p) } catch { /* ignore */ } })
531
+ this._envForApiKey = opts._envForApiKey || process.env
532
+ // #5081 — crash-durable record of the compose project id so a daemon
533
+ // crash between `compose up` and `compose down` leaves an on-disk paper
534
+ // trail the boot-time sweep can clean up. record()'d after a successful
535
+ // `compose up`, forget()'d after a clean `compose down`. Resolved lazily
536
+ // in `_getComposeStateStore()` to the shared singleton (so the boot sweep
537
+ // and live sessions agree on one state file) ONLY in compose mode —
538
+ // non-compose sessions never touch it, keeping their test paths off the
539
+ // real home. Injectable for tests.
540
+ this._composeStateStore = opts._composeStateStore || null
541
+
542
+ const user = opts.containerUser || DEFAULT_USER
543
+ if (!VALID_USERNAME_RE.test(user)) {
544
+ throw new Error(`Invalid containerUser "${user}" — must match POSIX username rules`)
545
+ }
546
+ this._containerUser = user
547
+ this._image = opts.image || DEFAULT_IMAGE
548
+ this._memoryLimit = opts.memoryLimit || DEFAULT_MEMORY_LIMIT
549
+ this._cpuLimit = opts.cpuLimit || DEFAULT_CPU_LIMIT
550
+ // External container support — when an env-manager hands us an
551
+ // already-running containerId we attach to it and DON'T tear it
552
+ // down on destroy.
553
+ const containerId = typeof opts.containerId === 'string' ? opts.containerId.trim() : null
554
+ this._containerId = containerId || null
555
+ this._containerOwned = !containerId
556
+ this._dockerBackend = opts._dockerBackend || new DockerBackend()
557
+ this._execFile = opts._execFile || execFile
558
+ this._containerReady = false
559
+ // #5023 snapshot / restore opts. All string opts are trimmed before
560
+ // the length check so callers passing whitespace-only values (e.g.
561
+ // `' '`) get the same default as no-opt-at-all — matches how
562
+ // composeFile / composeService / containerId / snapshotImage handle
563
+ // their inputs (#5100 review).
564
+ this._snapshotImage = typeof opts.snapshotImage === 'string' && opts.snapshotImage.trim().length > 0
565
+ ? opts.snapshotImage.trim()
566
+ : null
567
+ this._snapshotsDir = typeof opts.snapshotsDir === 'string' && opts.snapshotsDir.trim().length > 0
568
+ ? opts.snapshotsDir.trim()
569
+ : join(process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'), 'snapshots')
570
+ this._sourceSessionId = typeof opts.sourceSessionId === 'string' && opts.sourceSessionId.trim().length > 0
571
+ ? opts.sourceSessionId.trim()
572
+ : null
573
+ // #5022: across-session idle pool. Off by default — opted in via env
574
+ // or by passing an explicit `_pool` instance. Per-session reuse of
575
+ // the same container across multiple turns is unconditional and
576
+ // independent of pooling.
577
+ // #5024: pooling is also disabled when the session manages a
578
+ // compose stack — the pool key is shaped for single-container
579
+ // resource shape (image/memory/cpu/user) and would silently reuse
580
+ // a bare-image container for a compose session. The destroy() path
581
+ // for compose unconditionally runs `docker compose down`.
582
+ const poolEnv = opts._poolEnv || process.env
583
+ if (opts._pool) {
584
+ this._pool = opts._pool
585
+ } else if (!opts.containerId && !this._composeFile && isPoolEnabled(poolEnv)) {
586
+ this._pool = getSharedPool(poolEnv)
587
+ } else {
588
+ this._pool = null
589
+ }
590
+ // Set to `true` if the container picked up THIS session originated
591
+ // from the pool — used at destroy() time to decide between pool
592
+ // release and inline `docker rm -f`.
593
+ this._acquiredFromPool = false
594
+
595
+ // #5025 — DevContainer-style postCreateCommand hook. Normalised to
596
+ // a single string (arrays joined with ` && `) and SHA-256-hashed so
597
+ // a marker file on /tmp lets a reused pool container skip the run
598
+ // when the same command was already applied. `null` (the default)
599
+ // disables the hook entirely — start() takes no extra round trips.
600
+ //
601
+ // Timeout is validated via the shared `isOperatorTimeoutInRange`
602
+ // helper (#5063 review — Copilot). Same MAX_SANE_DURATION_MS (24h)
603
+ // ceiling the protocol schemas + ws-history apply — a typoed
604
+ // `postCreateTimeoutMs: 99999999999` (extra digit) silently falls
605
+ // back to the 5-minute default and logs a warning instead of
606
+ // creating a many-hours `docker exec` hang.
607
+ this._postCreateCommand = normalizePostCreateCommand(opts.postCreateCommand)
608
+ this._postCreateTimeoutMs = isOperatorTimeoutInRange(opts.postCreateTimeoutMs, {
609
+ name: 'postCreateTimeoutMs',
610
+ log,
611
+ })
612
+ ? opts.postCreateTimeoutMs
613
+ : DEFAULT_POST_CREATE_TIMEOUT_MS
614
+ this._postCreateMarkerPath = this._postCreateCommand
615
+ ? `${POST_CREATE_MARKER_PREFIX}${createHash('sha256').update(this._postCreateCommand).digest('hex').slice(0, 16)}`
616
+ : null
617
+ }
618
+
619
+ /**
620
+ * Preflight check: confirm the local Docker daemon is reachable
621
+ * before any state mutation. Resolves true on success, rejects with
622
+ * a classified error (code:'docker_not_running' etc.) on failure.
623
+ *
624
+ * Exposed as a method so callers (tests, dashboards) can probe
625
+ * docker readiness without instantiating the full session.
626
+ */
627
+ _preflightDocker() {
628
+ return new Promise((resolve, reject) => {
629
+ this._execFile('docker', ['info'], { encoding: 'utf-8', timeout: 10_000 }, (err, _stdout, stderr) => {
630
+ if (err) {
631
+ const classified = classifyDockerError(err, stderr)
632
+ const error = new Error(classified.message)
633
+ error.code = classified.code
634
+ reject(error)
635
+ return
636
+ }
637
+ resolve(true)
638
+ })
639
+ })
640
+ }
641
+
642
+ /**
643
+ * Launch the container if we own it, then call super.start() so the
644
+ * Anthropic client / MCP fleet / ready event all wire up normally.
645
+ *
646
+ * When attaching to an external container (env-manager managed),
647
+ * skips the launch but still preflights `docker info` so a dead
648
+ * daemon doesn't silently fail the first tool call.
649
+ */
650
+ async start() {
651
+ try {
652
+ await this._preflightDocker()
653
+ } catch (err) {
654
+ // Surface preflight failures as a session error (same shape as
655
+ // docker-sdk-session uses for its own start-failure path) and
656
+ // tear down — the session can't function without Docker.
657
+ this.emit('error', {
658
+ code: err.code || 'docker_error',
659
+ message: `docker-byok preflight: ${err.message}`,
660
+ })
661
+ await this.destroy()
662
+ return
663
+ }
664
+
665
+ if (this._containerOwned) {
666
+ try {
667
+ await this._acquireOrStartContainer()
668
+ } catch (err) {
669
+ this.emit('error', {
670
+ code: err.code || 'docker_error',
671
+ message: `docker-byok failed to start container: ${err.message}`,
672
+ })
673
+ await this.destroy()
674
+ return
675
+ }
676
+
677
+ // #5025: run the DevContainer-style postCreateCommand after the
678
+ // container is up but before super.start() — that way a setup
679
+ // failure (missing package.json, broken npm script) fails the
680
+ // session start instead of silently surfacing on the first tool
681
+ // call. Only runs for OWNED containers; externally-managed ones
682
+ // are the caller's responsibility (e.g. an env-manager that
683
+ // already drove its own post-create).
684
+ if (this._postCreateCommand) {
685
+ try {
686
+ await this._runPostCreateCommandIfNeeded()
687
+ } catch (err) {
688
+ // #5068: distinguish two failure modes that previously shared
689
+ // one error code. A `post_create_marker_write_failed` tag on
690
+ // the throw means the command itself succeeded — only the
691
+ // SHA-256 marker `touch` failed. The session is functional
692
+ // (setup was applied inside this container), but a future
693
+ // pool reuse will re-run setup because the cache marker
694
+ // wasn't stamped. Surface that as a non-fatal warning and
695
+ // keep the session alive. Anything else (or a missing tag)
696
+ // is a real command failure: tear down the owned container.
697
+ if (err && err.code === 'post_create_marker_write_failed') {
698
+ log.warn(`docker-byok postCreateCommand marker write failed (non-fatal — command did succeed): ${err.message}`)
699
+ // #5089 review (Copilot, comment id 3349977279): soil the
700
+ // pool container so it isn't recycled. Without this, the
701
+ // next session that acquires this container sees no marker,
702
+ // re-runs the full postCreateCommand, and almost certainly
703
+ // re-fails the marker write for the same underlying reason
704
+ // (read-only /tmp, no space, AppArmor profile). That re-run
705
+ // is wasteful for idempotent commands like `npm install`
706
+ // and potentially incorrect for non-idempotent ones like
707
+ // `apt-get install`. Soiling makes the pool evict THIS
708
+ // container on release() and start a fresh one for the
709
+ // next acquire, while the current session continues to
710
+ // ready — the command DID succeed inside this container.
711
+ this.markActiveContainerSoiled()
712
+ this.emit('error', {
713
+ code: 'post_create_marker_write_failed',
714
+ message: `docker-byok postCreateCommand marker write failed: ${err.message}`,
715
+ fatal: false,
716
+ })
717
+ } else {
718
+ // #5067 — Surface BOTH captured streams so the operator can
719
+ // diagnose without re-running the failed setup. The backend's
720
+ // `execInEnvironment` (docker.js) attaches `stdout` / `stderr`
721
+ // on the rejected Error; we tail-cap each to keep the event
722
+ // payload bounded. `err.stdout` / `err.stderr` are guaranteed
723
+ // to be strings (empty when not captured) for the docker-backed
724
+ // path; the `?? ''` guards a synthetic throw (e.g. invalid user
725
+ // regex) that didn't pass through the docker exec callback.
726
+ this.emit('error', {
727
+ code: 'post_create_command_failed',
728
+ message: `docker-byok postCreateCommand failed: ${err.message}`,
729
+ stdout: tailCapture(err.stdout ?? ''),
730
+ stderr: tailCapture(err.stderr ?? ''),
731
+ })
732
+ await this.destroy()
733
+ return
734
+ }
735
+ }
736
+ }
737
+ } else {
738
+ // External container — verify it's reachable before we lie to
739
+ // the model about being ready.
740
+ try {
741
+ await this._verifyContainer()
742
+ } catch (err) {
743
+ this.emit('error', {
744
+ code: err.code || 'docker_error',
745
+ message: `docker-byok external container not reachable: ${err.message}`,
746
+ })
747
+ await this.destroy()
748
+ return
749
+ }
750
+ }
751
+
752
+ // Fix for PR #5021 review (Copilot, comment id 3348029212): only
753
+ // mark the container ready AFTER super.start() succeeds, and
754
+ // self-destroy on its failure. Pre-fix, super.start()'s missing-
755
+ // creds path emitted 'error' and returned without setting
756
+ // _processReady — leaving the owned container running with
757
+ // _containerReady === true and nobody guaranteed to call destroy().
758
+ try {
759
+ await super.start()
760
+ } catch (err) {
761
+ this.emit('error', {
762
+ code: 'session_start_failed',
763
+ message: `docker-byok session start failed: ${err.message}`,
764
+ })
765
+ await this.destroy()
766
+ return
767
+ }
768
+ if (!this._processReady) {
769
+ // super.start() emitted its own 'error' event (e.g. missing
770
+ // creds) and returned without marking the session ready. Tear
771
+ // down the owned container so we don't leak it.
772
+ await this.destroy()
773
+ return
774
+ }
775
+ this._containerReady = true
776
+
777
+ // #5023: a container restored from a snapshot inherits the
778
+ // snapshot's writable layer — auth files, history, scratch state.
779
+ // Mark it soiled so it does NOT return to the pool for an unrelated
780
+ // session to acquire. No-ops cleanly when pooling is disabled.
781
+ if (this._snapshotImage && this._containerOwned) {
782
+ this.markActiveContainerSoiled()
783
+ }
784
+ }
785
+
786
+ /**
787
+ * Compute the pool key for this session's resource shape. Same shape
788
+ * used by `DockerContainerPool` so acquire / release lookups match.
789
+ *
790
+ * The host cwd is part of the key because /workspace is bind-mounted
791
+ * from cwd — reusing a container across cwds would silently surface
792
+ * files from another workspace.
793
+ *
794
+ * #5080: When `useDevcontainer` is set, the resolved devcontainer
795
+ * overlay's SHA-1 fingerprint is also part of the key so a changed
796
+ * `.devcontainer/devcontainer.json` (new mount, different
797
+ * `containerEnv`, etc.) cannot silently reuse a container provisioned
798
+ * against the OLD config. Non-devcontainer sessions pass null and the
799
+ * key shape stays exactly as it was — those sessions can still pool
800
+ * with each other.
801
+ */
802
+ _poolKey() {
803
+ return buildPoolKey({
804
+ image: this._image,
805
+ cwd: this.cwd || process.cwd(),
806
+ memoryLimit: this._memoryLimit,
807
+ cpuLimit: this._cpuLimit,
808
+ containerUser: this._containerUser,
809
+ devcontainerFingerprint: this._devcontainerFingerprint,
810
+ })
811
+ }
812
+
813
+ /**
814
+ * Mark this session's live container "soiled" — its filesystem has
815
+ * been coupled to the current conversation (most often by taking a
816
+ * Docker snapshot) and MUST NOT be handed to a future session via the
817
+ * pool. The pool intercepts the next `release()` and evicts inline.
818
+ *
819
+ * Integration point for #5023 (docker-byok snapshot/restore): when
820
+ * snapshot support lands, the snapshot helper must call this AFTER
821
+ * `docker commit` succeeds (the snapshot includes the writable layer,
822
+ * so the container's auth / files / artifacts are now part of an
823
+ * image that's tied to this conversation). The restore-from-snapshot
824
+ * path does the same — restoring previous state into the live
825
+ * container couples it to a specific session's history.
826
+ *
827
+ * No-ops cleanly when pooling is disabled (no `_pool`) or when the
828
+ * session does not hold a container (no `_containerId` yet). Safe to
829
+ * call multiple times — `markSoiled` is idempotent.
830
+ */
831
+ markActiveContainerSoiled() {
832
+ if (!this._pool) return
833
+ if (!this._containerId) return
834
+ this._pool.markSoiled(this._containerId)
835
+ }
836
+
837
+ /**
838
+ * Snapshot the live container's writable layer into a Docker image
839
+ * tag via `docker commit`, then mark the container "soiled" so the
840
+ * pool evicts it on release. Writes a small metadata JSON to
841
+ * `snapshotsDir` so ops can list snapshot names without parsing
842
+ * `docker image ls` — see class docstring's snapshot/restore section.
843
+ *
844
+ * Returns a `{ tag, name, createdAt, sourceCwd, sourceImage,
845
+ * sourceSessionId }` shape. The `tag` is what a future session passes
846
+ * to the constructor as `snapshotImage` to restore.
847
+ *
848
+ * Throws when the container is not ready (no `start()`, or
849
+ * `destroy()` already ran). Surfaces backend errors (out-of-disk,
850
+ * daemon dead) as a plain Error — callers decide whether to retry.
851
+ *
852
+ * #5023.
853
+ *
854
+ * @param {object} [opts]
855
+ * @param {string} [opts.name] Human-readable name for the snapshot
856
+ * @returns {Promise<{tag:string, name:string, createdAt:string,
857
+ * sourceCwd:string, sourceImage:string, sourceSessionId:string|null}>}
858
+ */
859
+ async snapshot({ name } = {}) {
860
+ if (!this._containerReady || !this._containerId) {
861
+ const err = new Error('docker-byok snapshot(): container is not ready')
862
+ err.code = 'docker_byok_not_ready'
863
+ throw err
864
+ }
865
+ const tag = this._generateSnapshotTag()
866
+ const sourceCwd = this.cwd || process.cwd()
867
+ const sourceImage = this._snapshotImage || this._image
868
+ const snapName = this._resolveSnapshotName(name, tag)
869
+ const createdAt = new Date().toISOString()
870
+
871
+ log.info(`snapshot: committing ${this._containerId.slice(0, 12)} → ${tag}`)
872
+ await this._dockerBackend.commitEnvironment(this._containerId, tag)
873
+
874
+ // Mark soiled BEFORE writing metadata. If metadata persistence
875
+ // fails (disk full, permission denied) we still want the soil
876
+ // marker stuck on — the snapshot tag exists in the daemon and the
877
+ // container's writable layer has leaked into it.
878
+ this.markActiveContainerSoiled()
879
+
880
+ const metadata = {
881
+ tag,
882
+ name: snapName,
883
+ createdAt,
884
+ sourceCwd,
885
+ sourceImage,
886
+ sourceSessionId: this._sourceSessionId,
887
+ }
888
+ try {
889
+ this._persistSnapshotMetadata(tag, metadata)
890
+ } catch (err) {
891
+ // Persistence is best-effort — the snapshot tag in the daemon is
892
+ // the source of truth. Log and continue so the caller still gets
893
+ // the tag. Defensive message extraction (#5100 review) so a
894
+ // non-Error throw (string / plain object) doesn't crash the
895
+ // log call itself — the whole point of this branch is to keep
896
+ // snapshot() reliable when metadata persistence fails.
897
+ const msg = err && typeof err.message === 'string' ? err.message : String(err)
898
+ log.warn(`snapshot: failed to persist metadata for ${tag}: ${msg}`)
899
+ }
900
+ log.info(`snapshot: ${tag} (name="${snapName}") committed`)
901
+ return metadata
902
+ }
903
+
904
+ /**
905
+ * Validate `opts.name` against Docker tag rules so the field stays
906
+ * safe to surface into the image tag later (#5076).
907
+ *
908
+ * - undefined / null → fall back to the tag slug (the
909
+ * "name is optional" contract: omitted = auto-generated slug)
910
+ * - non-string → EINVAL
911
+ * - empty / whitespace-only → EINVAL (per #5076 AC: a string that
912
+ * trims to nothing is not "omitted" — the caller passed
913
+ * something and it carries no usable identifier, so reject at
914
+ * the API boundary rather than silently substituting the slug)
915
+ * - > 64 chars (post-trim) → EINVAL (Docker caps at 128; we cap
916
+ * at 64 to leave headroom for a `<name>-<ts>` composite tag)
917
+ * - uppercase or chars → EINVAL
918
+ * outside `[a-z0-9._-]`,
919
+ * or leading `.` / `-` → EINVAL (Docker tag grammar requires
920
+ * the leading char to be `[a-zA-Z0-9_]`; we mirror that minus
921
+ * the uppercase half)
922
+ *
923
+ * Returns the trimmed, validated name (or the tag-slug fallback for
924
+ * the omitted case).
925
+ *
926
+ * @param {unknown} name
927
+ * @param {string} tag The auto-generated tag, used for the fallback
928
+ * @returns {string}
929
+ */
930
+ _resolveSnapshotName(name, tag) {
931
+ if (name === undefined || name === null) {
932
+ return tag.split(':').pop()
933
+ }
934
+ if (typeof name !== 'string') {
935
+ const err = new Error(
936
+ `docker-byok snapshot(): name must be a string, got ${typeof name}`,
937
+ )
938
+ err.code = 'EINVAL'
939
+ throw err
940
+ }
941
+ const trimmed = name.trim()
942
+ if (trimmed.length === 0) {
943
+ // Whitespace-only — the caller passed *something*, but it
944
+ // carries no usable identifier. Per #5076 AC, this is EINVAL at
945
+ // the API boundary rather than a silent fallback (which would
946
+ // mask the caller's bug and produce repeated warn-line noise).
947
+ const err = new Error(
948
+ 'docker-byok snapshot(): name must not be empty or whitespace-only',
949
+ )
950
+ err.code = 'EINVAL'
951
+ throw err
952
+ }
953
+ // 64 chars leaves room for a `<name>-<13-digit-ts>` composite tag
954
+ // under Docker's 128-char ceiling. Bias toward strictness now so
955
+ // tightening later is not a breaking change.
956
+ if (trimmed.length > 64) {
957
+ const err = new Error(
958
+ `docker-byok snapshot(): name is ${trimmed.length} chars; max is 64`,
959
+ )
960
+ err.code = 'EINVAL'
961
+ throw err
962
+ }
963
+ // Docker tag charset: lowercase ASCII letters, digits, `.`, `_`,
964
+ // `-`. The leading character must be `[a-z0-9_]` — Docker's own
965
+ // grammar permits a leading underscore (`[a-zA-Z0-9_][a-zA-Z0-9._-]
966
+ // {0,127}`), so we mirror that minus the uppercase half. `.` and
967
+ // `-` are still forbidden as the leading char per the reference
968
+ // grammar.
969
+ if (!/^[a-z0-9_][a-z0-9._-]*$/.test(trimmed)) {
970
+ const err = new Error(
971
+ 'docker-byok snapshot(): name must be lowercase and contain only [a-z0-9._-], starting with [a-z0-9_]',
972
+ )
973
+ err.code = 'EINVAL'
974
+ throw err
975
+ }
976
+ return trimmed
977
+ }
978
+
979
+ /**
980
+ * Build a snapshot tag of the form `chroxy-byok-snap:<16-hex>-<ts>`.
981
+ * 8 bytes of randomness + a millisecond timestamp keep tags unique
982
+ * within a single host. Image tags must be lowercase ASCII;
983
+ * `randomBytes` hex satisfies the Docker tag rules.
984
+ */
985
+ _generateSnapshotTag() {
986
+ const rand = randomBytes(8).toString('hex')
987
+ const ts = Date.now()
988
+ return `chroxy-byok-snap:${rand}-${ts}`
989
+ }
990
+
991
+ /**
992
+ * Write the snapshot metadata JSON next to its siblings in
993
+ * `_snapshotsDir`. The filename uses the tag's identifier portion so
994
+ * a future ops listing reads back deterministically.
995
+ *
996
+ * Best-effort, sync I/O: we hold a docker tag whether or not the
997
+ * sidecar JSON lands. The mkdir is recursive so a brand-new
998
+ * `~/.chroxy/snapshots/` is created on demand.
999
+ *
1000
+ * Uses the shared `writeFileRestricted` helper (#5100 review) so the
1001
+ * write is atomic (temp+rename) and the file lands at 0600 on POSIX
1002
+ * with the same cross-platform contract every other
1003
+ * `$CHROXY_CONFIG_DIR` state file uses (session-state, credentials,
1004
+ * device-preferences, models cache). Dir is 0o700 on POSIX; the dir
1005
+ * mode is ignored on Windows where ACLs are the right mechanism.
1006
+ */
1007
+ _persistSnapshotMetadata(tag, metadata) {
1008
+ mkdirSync(this._snapshotsDir, { recursive: true, mode: 0o700 })
1009
+ // Tag is `chroxy-byok-snap:<rand>-<ts>` — split on ':' to get the
1010
+ // filename-safe slug. Defensive replace in case a custom tag ever
1011
+ // surfaces here.
1012
+ const slug = tag.split(':').pop().replace(/[^a-zA-Z0-9_.-]/g, '_')
1013
+ const filePath = join(this._snapshotsDir, `${slug}.json`)
1014
+ writeFileRestricted(filePath, JSON.stringify(metadata, null, 2) + '\n')
1015
+ }
1016
+
1017
+ /**
1018
+ * If pooling is enabled, try to claim a warm container for this
1019
+ * session's resource shape. On a hit, verify the container still
1020
+ * responds to `docker exec` — if so, skip `_startContainer()`
1021
+ * entirely. On a miss (or on a verify failure), fall back to a fresh
1022
+ * launch.
1023
+ *
1024
+ * #5022 — across-session idle pool. Per-session reuse of the same
1025
+ * container across turns is handled in `_dispatchBuiltinTool` and
1026
+ * does not depend on the pool.
1027
+ *
1028
+ * #5023 — when `_snapshotImage` is set the pool is BYPASSED. The
1029
+ * pool key derives from `_image`, not `_snapshotImage`, so a hit
1030
+ * would hand back a stock container and `_startContainer()` would
1031
+ * never run — the snapshot tag would be silently ignored. Worse,
1032
+ * the recycled container's writable layer (auth, scratch state) is
1033
+ * unrelated to the snapshot the caller asked to restore. Restored
1034
+ * containers are auto-soiled anyway so they can't return to the
1035
+ * pool — skipping the acquire path is the consistent move.
1036
+ *
1037
+ * #5080 — When `useDevcontainer: true`, parsing the
1038
+ * `.devcontainer/devcontainer.json` overlay happens BEFORE the pool
1039
+ * lookup, and the resolved overlay's SHA-1 fingerprint is folded into
1040
+ * the pool key. Concretely:
1041
+ * - the resolved `image` and `remoteUser` are part of the key as
1042
+ * first-class segments (they change which image is pulled / which
1043
+ * user the container runs as), AND
1044
+ * - the fingerprint covers `mounts`, `containerEnv`, `forwardPorts`,
1045
+ * and `postCreateCommand` — these ARE applied to `docker run` (as
1046
+ * `-v`, `-e`, `-p`) and the post-create exec, but they are NOT
1047
+ * part of the base 5-segment key shape, so they need the
1048
+ * fingerprint to invalidate a stale pooled container.
1049
+ * If any of those change, the next acquire misses and a fresh
1050
+ * container is launched. Non-devcontainer sessions pass a null
1051
+ * fingerprint and their pool key shape is unchanged.
1052
+ */
1053
+ async _acquireOrStartContainer() {
1054
+ // #5024: devcontainer parsing must happen BEFORE the compose +
1055
+ // pool branches because the resolved devcontainer overlay can ITSELF
1056
+ // declare a compose stack (#5078 `dockerComposeFile`) or a
1057
+ // build-from-Dockerfile image, and the resolved image/user are part
1058
+ // of the pool key. #5080: the same call also computes
1059
+ // `_devcontainerFingerprint`, folded into the pool key so a changed
1060
+ // devcontainer.json overlay invalidates any pooled container
1061
+ // provisioned against the old config.
1062
+ if (this._useDevcontainer) {
1063
+ this._resolveDevContainer()
1064
+ }
1065
+ // #5024 / #5078: compose mode short-circuits the entire pool +
1066
+ // bare-image path. The compose stack owns its own container;
1067
+ // destroy() unwinds it with `docker compose down`. `_composeFile`
1068
+ // may have been set by an explicit constructor opt OR by the
1069
+ // devcontainer.json `dockerComposeFile` field resolved just above.
1070
+ if (this._composeFile) {
1071
+ await this._startComposeStack()
1072
+ return
1073
+ }
1074
+ // #5078: build-from-Dockerfile. When the resolved devcontainer
1075
+ // overlay declares a `build` / `dockerFile`, shell `docker build`
1076
+ // against the project dir and use the resulting tag as the image.
1077
+ // Cached by tag so a repeat session with the same build inputs
1078
+ // reuses the already-built image. Runs BEFORE the pool lookup so the
1079
+ // built tag is the image segment of the pool key.
1080
+ if (this._dcBuild && !this._explicitImage) {
1081
+ await this._buildDevcontainerImage()
1082
+ }
1083
+ if (this._pool && !this._snapshotImage) {
1084
+ const key = this._poolKey()
1085
+ const reused = this._pool.acquire(key)
1086
+ if (reused) {
1087
+ this._containerId = reused
1088
+ try {
1089
+ await this._verifyContainer()
1090
+ // Pool hit: skip `useradd` + `chown` — the previous session
1091
+ // ran them inside THIS container, and we're reusing the same
1092
+ // running container (it never stopped, so `/etc/passwd` and
1093
+ // `/workspace` ownership stay put). If pooling ever switches
1094
+ // to stop/start (or commit/restart), this assumption needs to
1095
+ // be revisited — a stopped-then-restarted container preserves
1096
+ // its layered FS but the previous-session assumption about
1097
+ // "the user already exists" still holds at the FS level.
1098
+ this._acquiredFromPool = true
1099
+ log.info(`reused pooled container ${reused.slice(0, 12)}`)
1100
+ return
1101
+ } catch (err) {
1102
+ // The pooled container died while idle (daemon restart, OOM
1103
+ // kill). Forget it and fall through to a fresh launch. Use
1104
+ // the pool's `forget()` helper so `_createdAt` gets cleared
1105
+ // alongside the `docker rm -f` — otherwise the map slowly
1106
+ // leaks across long-running servers (#5045 review). Fire-and-
1107
+ // forget; we don't block start on cleanup of a dead id.
1108
+ log.warn(`pooled container ${reused.slice(0, 12)} failed verify: ${err.message} — launching fresh`)
1109
+ this._containerId = null
1110
+ this._pool.forget(reused).catch(() => {})
1111
+ }
1112
+ }
1113
+ }
1114
+ await this._startContainer()
1115
+ }
1116
+
1117
+ /**
1118
+ * #5024: Parse `.devcontainer/devcontainer.json` from cwd and
1119
+ * overlay supported fields onto this session's state. Explicit
1120
+ * constructor opts always win — devcontainer.json is the fallback.
1121
+ * No-op when no devcontainer.json exists or the file is malformed
1122
+ * (the parser logs and returns `{}`).
1123
+ *
1124
+ * Stores the parsed config in `this._dcConfig` so `_startContainer`
1125
+ * can apply `mounts` / `containerEnv` / `forwardPorts` /
1126
+ * `postCreateCommand` to the `docker run` and `docker exec` calls.
1127
+ */
1128
+ _resolveDevContainer() {
1129
+ const cwd = this.cwd || process.cwd()
1130
+ const config = parseDevContainer(cwd, { logger: log })
1131
+ if (config && Object.keys(config).length > 0) {
1132
+ log.info(`devcontainer.json overlay active (cwd=${cwd})`)
1133
+ }
1134
+ // image: caller opt wins over devcontainer.json wins over DEFAULT_IMAGE.
1135
+ if (!this._explicitImage && config.image) {
1136
+ this._image = config.image
1137
+ }
1138
+ // remoteUser: caller opt wins over devcontainer.json wins over DEFAULT_USER.
1139
+ if (!this._explicitContainerUser && config.remoteUser) {
1140
+ // Validate the user name — devcontainer.json is untrusted input.
1141
+ if (VALID_USERNAME_RE.test(config.remoteUser)) {
1142
+ this._containerUser = config.remoteUser
1143
+ } else {
1144
+ log.warn(`devcontainer.json remoteUser "${config.remoteUser}" rejected — keeping ${this._containerUser}`)
1145
+ }
1146
+ }
1147
+ // Validate mounts and env now so a bad value surfaces at start time
1148
+ // instead of when docker rejects the run call.
1149
+ this._dcConfig = {
1150
+ ...config,
1151
+ mounts: validateMounts(config.mounts, cwd, { logger: log }),
1152
+ containerEnv: sanitizeContainerEnv(config.containerEnv, { logger: log }),
1153
+ }
1154
+ // #5078 — devcontainer.json may declare a build (Dockerfile) or a
1155
+ // compose stack. Resolve those onto session state here so
1156
+ // `_acquireOrStartContainer` can branch on them. Explicit constructor
1157
+ // opts (image / composeFile) always win — devcontainer.json is the
1158
+ // fallback, mirroring the image/remoteUser precedence above.
1159
+ this._resolveDevContainerBuild(config, cwd)
1160
+ this._resolveDevContainerCompose(config, cwd)
1161
+ // #5080: Compute the pool-key fingerprint from the FULLY-RESOLVED
1162
+ // overlay (after mount validation + env sanitisation), not the raw
1163
+ // parsed file. That way two devcontainer.json files that differ
1164
+ // only in rejected fields produce the same fingerprint (and reuse a
1165
+ // container) while any genuine config change cache-busts the key.
1166
+ // The fingerprint covers ONLY non-key overlay fields (mounts,
1167
+ // containerEnv, forwardPorts, postCreateCommand) — image and
1168
+ // remoteUser are already first-class segments of the pool key, so
1169
+ // including them in the fingerprint would cause spurious cache
1170
+ // misses when an explicit constructor opt has overridden them but
1171
+ // the devcontainer.json file value changed.
1172
+ this._devcontainerFingerprint = this._computeDevcontainerFingerprint(this._dcConfig)
1173
+ }
1174
+
1175
+ /**
1176
+ * #5078 — Resolve a devcontainer.json `build` / `dockerFile` declaration
1177
+ * onto session state. Stores a normalised build spec in `this._dcBuild`
1178
+ * with absolute, contained paths:
1179
+ * - `context` absolute project-relative build context (defaults to
1180
+ * the devcontainer.json directory; honours `..`)
1181
+ * - `dockerfile` path passed to `docker build -f`
1182
+ * - `target` multi-stage build target (→ `--target`)
1183
+ * - `args` validated `--build-arg KEY=VALUE` pairs
1184
+ *
1185
+ * The build context is resolved relative to the devcontainer.json
1186
+ * DIRECTORY (the spec), not the session cwd, then contained to the
1187
+ * project cwd — a `context: '../..'` that escapes the project tree is
1188
+ * rejected so a malicious devcontainer.json can't hand `docker build` a
1189
+ * context outside the workspace.
1190
+ *
1191
+ * No-op when the overlay declares no build, OR when an explicit
1192
+ * constructor `image` was passed (the operator's image wins — same
1193
+ * precedence the image overlay uses).
1194
+ */
1195
+ _resolveDevContainerBuild(config, cwd) {
1196
+ this._dcBuild = null
1197
+ if (!config || !config.build) return
1198
+ if (this._explicitImage) {
1199
+ log.info('devcontainer.json build ignored — explicit image opt wins')
1200
+ return
1201
+ }
1202
+ // The devcontainer spec treats `image` and `build` as mutually
1203
+ // exclusive. If both are present we honour `build` (it overwrites the
1204
+ // image overlay applied just above) — surface a warning so the
1205
+ // operator knows the declared `image` field was superseded.
1206
+ if (config.image) {
1207
+ log.warn(`devcontainer.json declares both "image" (${config.image}) and "build" — building from the Dockerfile; "image" is ignored`)
1208
+ }
1209
+ const dcDir = config.dir || cwd
1210
+ const absCwd = resolve(cwd)
1211
+ const cwdPrefix = absCwd.endsWith(sep) ? absCwd : absCwd + sep
1212
+
1213
+ // Context defaults to the devcontainer.json dir per spec. Resolve it
1214
+ // relative to that dir so `..` walks up from there, then contain to
1215
+ // the project cwd.
1216
+ const contextResolved = resolve(dcDir, config.build.context || '.')
1217
+ if (contextResolved !== absCwd && !contextResolved.startsWith(cwdPrefix)) {
1218
+ log.warn(
1219
+ `devcontainer.json build.context "${config.build.context}" resolves outside the project dir (${contextResolved}) — ignoring build`,
1220
+ )
1221
+ return
1222
+ }
1223
+
1224
+ // Dockerfile is resolved relative to the build context (docker's own
1225
+ // default) and must also stay inside the project tree.
1226
+ const dockerfileResolved = resolve(contextResolved, config.build.dockerfile)
1227
+ if (dockerfileResolved !== absCwd && !dockerfileResolved.startsWith(cwdPrefix)) {
1228
+ log.warn(
1229
+ `devcontainer.json build.dockerfile "${config.build.dockerfile}" resolves outside the project dir (${dockerfileResolved}) — ignoring build`,
1230
+ )
1231
+ return
1232
+ }
1233
+
1234
+ this._dcBuild = {
1235
+ context: contextResolved,
1236
+ dockerfile: dockerfileResolved,
1237
+ target: typeof config.build.target === 'string' ? config.build.target : null,
1238
+ args: config.build.args && typeof config.build.args === 'object' ? config.build.args : null,
1239
+ }
1240
+ }
1241
+
1242
+ /**
1243
+ * #5078 — Resolve a devcontainer.json `dockerComposeFile` declaration
1244
+ * into the session's compose opts. When present (and no explicit
1245
+ * `composeFile` constructor opt was passed), sets `_composeFile` to the
1246
+ * compose file(s) resolved relative to the devcontainer.json dir,
1247
+ * picks the primary service from devcontainer.json's `service` field,
1248
+ * and disables pooling (compose stacks own their container lifecycle).
1249
+ *
1250
+ * #5124 — The devcontainer spec allows an ARRAY of compose files (a base
1251
+ * file plus one or more overrides). Compose merges them via a repeated
1252
+ * `-f` flag in declared order, so we thread the FULL resolved array (each
1253
+ * entry resolved relative to the devcontainer.json dir) through to the
1254
+ * backend `_composeUp`/`_composeDown` rather than attaching only to the
1255
+ * first file. A single declared file resolves to a lone string for
1256
+ * backward compatibility.
1257
+ *
1258
+ * No-op when the overlay declares no compose file or an explicit
1259
+ * `composeFile` constructor opt already won.
1260
+ */
1261
+ _resolveDevContainerCompose(config, cwd) {
1262
+ if (!config || !Array.isArray(config.dockerComposeFile) || config.dockerComposeFile.length === 0) return
1263
+ if (this._composeFile) {
1264
+ log.info('devcontainer.json dockerComposeFile ignored — explicit composeFile opt wins')
1265
+ return
1266
+ }
1267
+ const dcDir = config.dir || cwd
1268
+ const files = config.dockerComposeFile.map((f) => resolve(dcDir, f))
1269
+ // Thread the full set so `_composeUp` emits `-f <base> -f <override>`
1270
+ // in declared order. A lone file stays a plain string so single-file
1271
+ // callers and persisted state are unaffected.
1272
+ this._composeFile = files.length === 1 ? files[0] : files
1273
+ // Primary service: devcontainer.json `service` field wins; otherwise
1274
+ // fall back to the first service the backend reports.
1275
+ if (!this._composeService && config.service) {
1276
+ this._composeService = config.service
1277
+ }
1278
+ // Compose stacks own their container — pooling is disabled (mirrors
1279
+ // the constructor's compose-mode pool guard).
1280
+ this._pool = null
1281
+ }
1282
+
1283
+ /**
1284
+ * #5078 — Build a Docker image from a devcontainer.json `build` /
1285
+ * `dockerFile` declaration via `docker build`, then use the resulting
1286
+ * tag as `this._image`. Cached by tag: the tag is a deterministic
1287
+ * SHA-256 fingerprint of the build inputs (context, dockerfile, target,
1288
+ * args), so a repeat session with identical inputs produces the same
1289
+ * tag and `docker build`'s own layer cache makes the rebuild a fast
1290
+ * no-op (the image already exists locally).
1291
+ *
1292
+ * Security: every value is passed to `_execFile` as a discrete argv
1293
+ * entry — never string-interpolated into a shell. `--build-arg
1294
+ * KEY=VALUE` pairs use keys already constrained to POSIX env-var shape
1295
+ * by `parseBuild`; values are passed verbatim as a single argv token so
1296
+ * shell metacharacters in a value are inert.
1297
+ */
1298
+ _buildDevcontainerImage() {
1299
+ return new Promise((resolve, reject) => {
1300
+ const build = this._dcBuild
1301
+ const tag = this._computeBuildTag(build)
1302
+ const buildArgs = ['build', '-t', tag, '-f', build.dockerfile]
1303
+ if (build.target) buildArgs.push('--target', build.target)
1304
+ if (build.args) {
1305
+ for (const [key, value] of Object.entries(build.args)) {
1306
+ buildArgs.push('--build-arg', `${key}=${value}`)
1307
+ }
1308
+ }
1309
+ // Context is the final positional argument.
1310
+ buildArgs.push(build.context)
1311
+
1312
+ log.info(`docker-byok building image ${tag} (context=${build.context} dockerfile=${build.dockerfile}${build.target ? ` target=${build.target}` : ''})`)
1313
+ this._execFile('docker', buildArgs, { encoding: 'utf-8', timeout: 600_000 }, (err, _stdout, stderr) => {
1314
+ if (err) {
1315
+ const classified = classifyDockerError(err, stderr)
1316
+ const error = new Error(`docker build failed: ${classified.message}`)
1317
+ error.code = classified.code || 'docker_build_failed'
1318
+ reject(error)
1319
+ return
1320
+ }
1321
+ this._image = tag
1322
+ log.info(`docker-byok built image ${tag}`)
1323
+ resolve()
1324
+ })
1325
+ })
1326
+ }
1327
+
1328
+ /**
1329
+ * #5078 — Deterministic, lowercase, Docker-tag-safe image tag derived
1330
+ * from the build inputs. Same inputs → same tag → `docker build` hits
1331
+ * its local layer cache and the image is reused across sessions.
1332
+ */
1333
+ _computeBuildTag(build) {
1334
+ const fingerprint = createHash('sha256')
1335
+ .update(this._canonicalStringify({
1336
+ context: build.context,
1337
+ dockerfile: build.dockerfile,
1338
+ target: build.target,
1339
+ args: build.args,
1340
+ }))
1341
+ .digest('hex')
1342
+ .slice(0, 16)
1343
+ return `chroxy-byok-build:${fingerprint}`
1344
+ }
1345
+
1346
+ /**
1347
+ * #5080: Compute a short, stable SHA-1 fingerprint of the resolved
1348
+ * devcontainer overlay. The full SHA-1 is overkill for a cache-bust
1349
+ * key and bloats logs — the first 16 hex chars are 64 bits of
1350
+ * entropy, which is enough to make accidental collisions effectively
1351
+ * impossible within a single host's pool.
1352
+ *
1353
+ * Fingerprinted fields are **only** the non-key overlay state —
1354
+ * `mounts`, `containerEnv`, `forwardPorts`, `postCreateCommand`. The
1355
+ * resolved `image` and `remoteUser` are NOT fingerprinted because
1356
+ * they're already first-class segments of the pool key (and because
1357
+ * an explicit constructor opt may have overridden the devcontainer.json
1358
+ * value, in which case a change to the file's `image` field doesn't
1359
+ * actually change the resolved launch shape).
1360
+ *
1361
+ * Note on stability: #5103 — the input is canonicalised via
1362
+ * `_canonicalStringify` (object keys sorted recursively) before
1363
+ * hashing, so semantically identical overlays produce the same
1364
+ * fingerprint regardless of source-side key order. Arrays are
1365
+ * preserved in declared order because devcontainer.json arrays
1366
+ * (mounts, forwardPorts) are order-sensitive.
1367
+ *
1368
+ * @param {object|null} resolved
1369
+ * @returns {string|null}
1370
+ */
1371
+ _computeDevcontainerFingerprint(resolved) {
1372
+ if (!resolved || typeof resolved !== 'object') return null
1373
+ // Project the resolved overlay down to only the fields that
1374
+ // affect container provisioning but are NOT already in the base
1375
+ // pool key. Key order here is irrelevant — _canonicalStringify
1376
+ // sorts before hashing.
1377
+ const fingerprintInput = {
1378
+ mounts: resolved.mounts,
1379
+ containerEnv: resolved.containerEnv,
1380
+ forwardPorts: resolved.forwardPorts,
1381
+ postCreateCommand: resolved.postCreateCommand,
1382
+ }
1383
+ return createHash('sha1').update(this._canonicalStringify(fingerprintInput)).digest('hex').slice(0, 16)
1384
+ }
1385
+
1386
+ /**
1387
+ * #5103: Canonical (stable) JSON-shaped stringifier that sorts object
1388
+ * keys recursively. Arrays preserve their declared order because
1389
+ * devcontainer.json arrays (mounts, forwardPorts, runArgs) are
1390
+ * order-sensitive — the consuming tool may treat the first mount
1391
+ * differently from the last, and forwarded ports surface in the UI
1392
+ * in declared order.
1393
+ *
1394
+ * Used by `_computeDevcontainerFingerprint` so an editor that
1395
+ * alphabetises object keys (or a hand-edit that reorders them)
1396
+ * cannot bust the pool key for a semantically unchanged overlay.
1397
+ *
1398
+ * NOT a full JSON serialiser — this only handles values reachable
1399
+ * from a parsed devcontainer.json (object, array, string, number,
1400
+ * boolean, null, undefined). It deliberately omits exotic JSON.stringify
1401
+ * features (toJSON, replacer, BigInt) — the call site never sees them.
1402
+ *
1403
+ * Matches JSON.stringify's `undefined` semantics so an "empty overlay"
1404
+ * (where mounts/containerEnv/forwardPorts/postCreateCommand are all
1405
+ * absent) serialises to a clean `{}` rather than emitting non-JSON
1406
+ * `...:undefined` slots: object properties whose value is `undefined`
1407
+ * are dropped, and a top-level `undefined` yields the empty string —
1408
+ * exactly as `JSON.stringify` does.
1409
+ *
1410
+ * @param {unknown} value
1411
+ * @returns {string}
1412
+ */
1413
+ _canonicalStringify(value) {
1414
+ if (Array.isArray(value)) {
1415
+ // JSON.stringify renders an undefined array element as `null`.
1416
+ return '[' + value.map(v => (v === undefined ? 'null' : this._canonicalStringify(v))).join(',') + ']'
1417
+ }
1418
+ if (value && typeof value === 'object') {
1419
+ const keys = Object.keys(value)
1420
+ .filter(k => value[k] !== undefined) // JSON.stringify omits undefined props
1421
+ .sort()
1422
+ return '{' + keys.map(k => JSON.stringify(k) + ':' + this._canonicalStringify(value[k])).join(',') + '}'
1423
+ }
1424
+ // JSON.stringify(undefined) === undefined (not a string); normalise to ''.
1425
+ return JSON.stringify(value) ?? ''
1426
+ }
1427
+
1428
+ /**
1429
+ * #5024: Bring up the compose stack and identify the primary service
1430
+ * container. The stack is owned by THIS session — destroy() runs
1431
+ * `docker compose down --remove-orphans` against the same project id.
1432
+ *
1433
+ * Mirrors EnvironmentManager._createComposeEnvironment so the
1434
+ * security posture is identical: the named service container has its
1435
+ * non-root user created the same way the bare-image path does, the
1436
+ * host cwd is mounted at /workspace via the compose file (the user
1437
+ * is responsible for that volume mapping), and tool dispatch goes
1438
+ * through the same `_execAsContainerUser` path.
1439
+ *
1440
+ * #5079 — ANTHROPIC_API_KEY forwarding. The bare-image path forwards
1441
+ * the key via `docker run --env`; compose mode does the same job via
1442
+ * an `--env-file` tmpfile so the key is symmetric with the bare path
1443
+ * without being exposed in `ps` output. The tmpfile is written at
1444
+ * 0600 under os.tmpdir() and:
1445
+ * - passed to `docker compose --env-file <path>` so a service that
1446
+ * references `${ANTHROPIC_API_KEY}` in its compose file resolves
1447
+ * the value during interpolation; and
1448
+ * - reused on every `_execAsContainerUser` dispatch so a Bash command
1449
+ * the model spawns inside the container (e.g. `curl
1450
+ * api.anthropic.com` or a one-off `claude -p`) sees the key.
1451
+ * destroy() unlinks the file. When `ANTHROPIC_API_KEY` is not set in
1452
+ * the host env, no tmpfile is created — the path stays at `null` and
1453
+ * `_execAsContainerUser` skips the `--env-file` flag.
1454
+ */
1455
+ async _startComposeStack() {
1456
+ if (!this._composeProject) {
1457
+ this._composeProject = `chroxy-byok-${randomBytes(6).toString('hex')}`
1458
+ }
1459
+ const cwd = this.cwd || process.cwd()
1460
+ // #5079: write the ANTHROPIC_API_KEY tmpfile BEFORE compose up so
1461
+ // the file is on disk for both compose interpolation AND for the
1462
+ // exec dispatches that follow. Created at 0600 under os.tmpdir()
1463
+ // with a session-scoped random suffix to avoid collision between
1464
+ // parallel byok sessions on the same host.
1465
+ const apiKey = this._envForApiKey?.ANTHROPIC_API_KEY
1466
+ if (apiKey) {
1467
+ const envFilePath = join(tmpdir(), `chroxy-byok-${this._composeProject}.env`)
1468
+ try {
1469
+ this._writeEnvFile(envFilePath, `ANTHROPIC_API_KEY=${apiKey}\n`)
1470
+ this._composeEnvFile = envFilePath
1471
+ } catch (err) {
1472
+ // Non-fatal: log and proceed without the env file. The model
1473
+ // running inside the container won't see the key (matching the
1474
+ // pre-#5079 behaviour) but the host-side agent loop is what
1475
+ // actually authenticates to Anthropic, so the session still
1476
+ // functions for the common case.
1477
+ log.warn(`docker-byok compose: failed to write env-file ${envFilePath}: ${err.message}`)
1478
+ this._composeEnvFile = null
1479
+ }
1480
+ }
1481
+ log.info(`docker-byok compose stack starting (file=${this._composeFile} project=${this._composeProject} service=${this._composeService || '<first>'})`)
1482
+ let result
1483
+ try {
1484
+ result = await this._dockerBackend.createComposeEnvironment({
1485
+ envId: this._composeProject,
1486
+ cwd,
1487
+ composeFile: this._composeFile,
1488
+ composeProject: this._composeProject,
1489
+ containerUser: this._containerUser,
1490
+ primaryService: this._composeService,
1491
+ envFile: this._composeEnvFile,
1492
+ })
1493
+ } catch (err) {
1494
+ // Compose up failed — unlink the tmpfile before re-throwing so a
1495
+ // start-failure path doesn't leak the key on disk.
1496
+ if (this._composeEnvFile) {
1497
+ this._unlinkEnvFile(this._composeEnvFile)
1498
+ this._composeEnvFile = null
1499
+ }
1500
+ const error = new Error(`docker compose start failed: ${err.message}`)
1501
+ error.code = err.code || 'compose_start_failed'
1502
+ throw error
1503
+ }
1504
+ this._containerId = result.containerId
1505
+ log.info(`docker-byok compose primary container: ${this._containerId.slice(0, 12)}`)
1506
+ // #5081 — only AFTER a successful `compose up` do we persist the project
1507
+ // id. Recording earlier would leave a phantom entry on disk for a stack
1508
+ // that never started; the boot sweep would then `compose down` a project
1509
+ // that was never up (harmless but noisy). record() is best-effort:
1510
+ // persistence failures must not fail an otherwise-healthy session.
1511
+ try {
1512
+ this._getComposeStateStore().record({
1513
+ projectId: this._composeProject,
1514
+ composeFile: this._composeFile,
1515
+ cwd,
1516
+ })
1517
+ } catch (err) {
1518
+ log.warn(`docker-byok compose: failed to persist project id: ${err.message}`)
1519
+ }
1520
+ }
1521
+
1522
+ /**
1523
+ * #5081 — resolve the compose-state store for THIS session. Returns the
1524
+ * injected store when present (tests), otherwise the process-wide shared
1525
+ * singleton. Only ever called on the compose path, so non-compose sessions
1526
+ * never construct the default (and never touch the real ~/.chroxy state).
1527
+ */
1528
+ _getComposeStateStore() {
1529
+ if (!this._composeStateStore) {
1530
+ this._composeStateStore = getSharedComposeStateStore()
1531
+ }
1532
+ return this._composeStateStore
1533
+ }
1534
+
1535
+ /**
1536
+ * Launch a long-lived container with the host cwd mounted at
1537
+ * /workspace and the standard chroxy hardening (cap-drop, pids
1538
+ * limit, no-new-privileges, non-root user). Mirrors the runArgs
1539
+ * shape used by docker-sdk-session.js so the security posture is
1540
+ * identical across the two providers.
1541
+ *
1542
+ * When `_snapshotImage` is set (#5023), the container is launched
1543
+ * from that image instead of `_image` and the `useradd` + `chown`
1544
+ * setup is SKIPPED — the snapshot already has the non-root user
1545
+ * baked in. Re-running useradd would fail with "user already exists"
1546
+ * and abort start. The restored container is auto-soiled by
1547
+ * `start()` after this resolves so the pool evicts on release.
1548
+ */
1549
+ _startContainer() {
1550
+ return new Promise((resolve, reject) => {
1551
+ const runArgs = [
1552
+ 'run', '-d', '--init', '--rm',
1553
+ '--memory', this._memoryLimit,
1554
+ '--cpus', this._cpuLimit,
1555
+ '--pids-limit', '512',
1556
+ '--cap-drop', 'ALL',
1557
+ '--security-opt', 'no-new-privileges',
1558
+ '-v', `${this.cwd || process.cwd()}:${CONTAINER_WORKSPACE}`,
1559
+ '-w', CONTAINER_WORKSPACE,
1560
+ ]
1561
+
1562
+ // Issue AC: forward ANTHROPIC_API_KEY at `docker run` time. The
1563
+ // agent loop on the host is what actually authenticates to the
1564
+ // Anthropic API, but the model may want to invoke `curl` or a
1565
+ // CLI inside the container that expects this env var.
1566
+ const apiKey = process.env.ANTHROPIC_API_KEY
1567
+ if (apiKey) {
1568
+ runArgs.push('--env', `ANTHROPIC_API_KEY=${apiKey}`)
1569
+ }
1570
+
1571
+ // #5024: devcontainer.json overlay — extra mounts, env, and port
1572
+ // forwards. Mounts and env were already validated/sanitized by
1573
+ // `_resolveDevContainer()`; whatever survived is safe to pass
1574
+ // straight through. `forwardPorts` accepts integers and
1575
+ // "host:container" strings — both shapes emit `-p X:Y`.
1576
+ const dc = this._dcConfig
1577
+ if (dc) {
1578
+ if (Array.isArray(dc.mounts)) {
1579
+ for (const mount of dc.mounts) {
1580
+ runArgs.push('--mount', mount)
1581
+ }
1582
+ }
1583
+ if (dc.containerEnv && typeof dc.containerEnv === 'object') {
1584
+ for (const [key, value] of Object.entries(dc.containerEnv)) {
1585
+ runArgs.push('--env', `${key}=${value}`)
1586
+ }
1587
+ }
1588
+ if (Array.isArray(dc.forwardPorts)) {
1589
+ for (const port of dc.forwardPorts) {
1590
+ if (typeof port === 'number' && Number.isFinite(port) && port > 0 && port < 65536) {
1591
+ runArgs.push('-p', `${port}:${port}`)
1592
+ } else if (typeof port === 'string' && /^\d+(:\d+)?$/.test(port)) {
1593
+ // Bare-port strings ("3000") would otherwise become
1594
+ // `docker run -p 3000`, which Docker treats as "publish
1595
+ // container port 3000 to a RANDOM host port" — surprising
1596
+ // for a DevContainer-style forward where the model
1597
+ // expects 3000:3000. Normalise to host:container when the
1598
+ // colon is missing so the numeric and string forms
1599
+ // behave identically.
1600
+ const normalized = port.includes(':') ? port : `${port}:${port}`
1601
+ runArgs.push('-p', normalized)
1602
+ } else {
1603
+ log.warn(`devcontainer.json forwardPorts entry rejected (invalid): ${port}`)
1604
+ }
1605
+ }
1606
+ }
1607
+ }
1608
+
1609
+ if (process.platform === 'linux') {
1610
+ runArgs.push('--add-host', 'host.docker.internal:host-gateway')
1611
+ }
1612
+
1613
+ const imageToRun = this._snapshotImage || this._image
1614
+ runArgs.push(imageToRun, 'sleep', 'infinity')
1615
+
1616
+ log.info(
1617
+ this._snapshotImage
1618
+ ? `restoring container from snapshot ${this._snapshotImage} (memory=${this._memoryLimit} cpus=${this._cpuLimit})`
1619
+ : `starting container (image=${imageToRun} memory=${this._memoryLimit} cpus=${this._cpuLimit})`,
1620
+ )
1621
+
1622
+ this._execFile('docker', runArgs, { encoding: 'utf-8', timeout: 120_000 }, (err, stdout, stderr) => {
1623
+ if (err) {
1624
+ const classified = classifyDockerError(err, stderr)
1625
+ const error = new Error(classified.message)
1626
+ error.code = classified.code
1627
+ reject(error)
1628
+ return
1629
+ }
1630
+ this._containerId = stdout.trim()
1631
+ log.info(`container started: ${this._containerId.slice(0, 12)}`)
1632
+
1633
+ // Restore path: the snapshot has useradd + chown baked in, so
1634
+ // skip the setup step. Re-running useradd would fail
1635
+ // ("user already exists") and abort start.
1636
+ if (this._snapshotImage) {
1637
+ resolve()
1638
+ return
1639
+ }
1640
+
1641
+ // Set up non-root user + chown workspace so the model isn't
1642
+ // running as root inside the container. Same script
1643
+ // docker-sdk-session uses — keep the two in lockstep.
1644
+ const setupCmd = [
1645
+ `useradd -m -s /bin/bash ${this._containerUser}`,
1646
+ `chown ${this._containerUser}:${this._containerUser} ${CONTAINER_WORKSPACE}`,
1647
+ ].join(' && ')
1648
+
1649
+ this._execFile('docker', [
1650
+ 'exec', this._containerId, 'bash', '-c', setupCmd,
1651
+ ], { encoding: 'utf-8', timeout: 30_000 }, (setupErr) => {
1652
+ if (setupErr) {
1653
+ reject(new Error(`Failed to create container user: ${setupErr.message}`))
1654
+ return
1655
+ }
1656
+ log.info(`created non-root user "${this._containerUser}" in container`)
1657
+
1658
+ // #5024: devcontainer.json postCreateCommand. Runs once,
1659
+ // after useradd, as the non-root user. Failures are
1660
+ // non-fatal — log a warning so the session can still start.
1661
+ // postCreateCommand in devcontainer.json is primarily for
1662
+ // installing language toolchains; bound at 5 minutes here,
1663
+ // same ceiling DockerBackend._runPostCreateCommand uses.
1664
+ const dcLocal = this._dcConfig
1665
+ if (dcLocal && typeof dcLocal.postCreateCommand === 'string' && dcLocal.postCreateCommand.length > 0) {
1666
+ this._execFile('docker', [
1667
+ 'exec', '-u', this._containerUser, this._containerId, 'bash', '-c', dcLocal.postCreateCommand,
1668
+ ], { encoding: 'utf-8', timeout: 300_000 }, (postErr) => {
1669
+ if (postErr) {
1670
+ log.warn(`postCreateCommand failed (non-fatal): ${postErr.message}`)
1671
+ } else {
1672
+ log.info('postCreateCommand completed')
1673
+ }
1674
+ resolve()
1675
+ })
1676
+ return
1677
+ }
1678
+ resolve()
1679
+ })
1680
+ })
1681
+ })
1682
+ }
1683
+
1684
+ /**
1685
+ * #5025 — DevContainer-style postCreateCommand hook.
1686
+ *
1687
+ * Idempotency contract: a SHA-256-derived marker file lives at
1688
+ * `/tmp/.chroxy-post-create-<hash>` inside the container. If the
1689
+ * probe (`test -f <marker>`) succeeds, the command has already been
1690
+ * applied to THIS container and we skip the run entirely — that's
1691
+ * the whole reason the #5022 pool layer is useful for setup-heavy
1692
+ * workspaces. A different command produces a different hash, so a
1693
+ * change to `postCreateCommand` between sessions reuses the same
1694
+ * container but re-runs setup.
1695
+ *
1696
+ * Failure surface: any non-zero exit on the command itself (timeout,
1697
+ * backend reject, etc.) throws bare — the caller in `start()` converts
1698
+ * the throw into a `post_create_command_failed` error event and tears
1699
+ * the session down. A failure on the marker `touch` step throws an
1700
+ * error tagged with `code: 'post_create_marker_write_failed'` so the
1701
+ * caller can distinguish: the command DID succeed, only the cache
1702
+ * stamp didn't land, and the session is still functional (#5068).
1703
+ * The marker is only written on full success of the command, so a
1704
+ * half-applied state can never be cached as "already applied".
1705
+ */
1706
+ async _runPostCreateCommandIfNeeded() {
1707
+ if (!this._postCreateCommand || !this._postCreateMarkerPath) return
1708
+ // Probe for the marker. The backend rejects on non-zero exit, so a
1709
+ // `test -f` that finds the marker resolves clean and a missing
1710
+ // marker throws. Catch the throw and fall through to the run path
1711
+ // — any OTHER failure (daemon down, exec disabled) will also throw
1712
+ // here, and the run path will rediscover the underlying error.
1713
+ let markerPresent = false
1714
+ try {
1715
+ await this._execAsContainerUser({
1716
+ cmd: `test -f ${shellQuote(this._postCreateMarkerPath)}`,
1717
+ timeout: 10_000,
1718
+ })
1719
+ markerPresent = true
1720
+ } catch {
1721
+ markerPresent = false
1722
+ }
1723
+ if (markerPresent) {
1724
+ log.info(`postCreateCommand already applied (marker ${this._postCreateMarkerPath.slice(-12)}) — skipping`)
1725
+ return
1726
+ }
1727
+
1728
+ log.info(`running postCreateCommand (timeout=${this._postCreateTimeoutMs}ms)`)
1729
+ // Run the command. The backend's execInEnvironment forwards both
1730
+ // stdout and stderr and rejects on non-zero exit, so we don't need
1731
+ // to inspect an exit code here — a throw IS the failure path.
1732
+ //
1733
+ // #5069 — stream output to the session log surface as bytes arrive so
1734
+ // the operator gets progress during a multi-minute setup instead of a
1735
+ // silent dashboard. Each chunk becomes a transient `setup_log` event
1736
+ // (forwarded via DockerByokSession.customEvents). The backend STILL
1737
+ // accumulates stdout/stderr and attaches the last-N-KiB tail to the
1738
+ // rejected Error on failure (#5067), so the failure-event payload is
1739
+ // unchanged — streaming is purely additive.
1740
+ await this._execAsContainerUser({
1741
+ cmd: this._postCreateCommand,
1742
+ timeout: this._postCreateTimeoutMs,
1743
+ onData: (chunk, stream) => {
1744
+ // Defensive: never let a malformed chunk break the run loop.
1745
+ if (typeof chunk !== 'string' || chunk.length === 0) return
1746
+ this.emit('setup_log', { phase: 'post_create', stream, chunk })
1747
+ },
1748
+ })
1749
+
1750
+ // Stamp the marker so the next session that lands on this container
1751
+ // skips the run. `mkdir -p` on the prefix would be wrong (the prefix
1752
+ // is /tmp, which always exists), so just `touch` the file. Failure
1753
+ // here is rethrown with a distinct `post_create_marker_write_failed`
1754
+ // tag (#5068) so the caller in start() can tell it apart from a
1755
+ // command failure — the command DID succeed for THIS session, but
1756
+ // without a marker write a future pool reuse will re-run setup,
1757
+ // which is wasteful for idempotent commands like `npm install` and
1758
+ // potentially incorrect for non-idempotent ones like `apt-get install`.
1759
+ try {
1760
+ await this._execAsContainerUser({
1761
+ cmd: `touch ${shellQuote(this._postCreateMarkerPath)}`,
1762
+ timeout: 10_000,
1763
+ })
1764
+ } catch (err) {
1765
+ const wrapped = new Error(getErrorMessage(err, String(err)))
1766
+ wrapped.code = 'post_create_marker_write_failed'
1767
+ wrapped.cause = err
1768
+ throw wrapped
1769
+ }
1770
+ log.info(`postCreateCommand applied — marker stamped at ${this._postCreateMarkerPath.slice(-12)}`)
1771
+ }
1772
+
1773
+ /**
1774
+ * Confirm an externally-managed container is reachable via
1775
+ * `docker exec`. Used when `containerId` was supplied at construction.
1776
+ */
1777
+ _verifyContainer() {
1778
+ return new Promise((resolve, reject) => {
1779
+ this._execFile('docker', [
1780
+ 'exec', this._containerId, 'true',
1781
+ ], { encoding: 'utf-8', timeout: 10_000 }, (err, _stdout, stderr) => {
1782
+ if (err) {
1783
+ const classified = classifyDockerError(err, stderr)
1784
+ const error = new Error(classified.message)
1785
+ error.code = classified.code
1786
+ reject(error)
1787
+ return
1788
+ }
1789
+ resolve()
1790
+ })
1791
+ })
1792
+ }
1793
+
1794
+ /**
1795
+ * Override ClaudeByokSession's dispatcher: route file ops and Bash
1796
+ * into the container instead of running them in-process on the host.
1797
+ *
1798
+ * TodoWrite stays host-side (it's a pure in-memory map). WebFetch
1799
+ * stays host-side (it's HTTP and never touches the host FS — putting
1800
+ * it in the container would only add latency).
1801
+ */
1802
+ async _dispatchBuiltinTool({ toolName, input, signal }) {
1803
+ if (!this._containerReady || !this._containerId) {
1804
+ return {
1805
+ content: `docker-byok: container not ready (tool ${toolName})`,
1806
+ isError: true,
1807
+ }
1808
+ }
1809
+ try {
1810
+ switch (toolName) {
1811
+ case 'Read':
1812
+ return await this._containerRead(input)
1813
+ case 'Write':
1814
+ return await this._containerWrite(input)
1815
+ case 'Edit':
1816
+ return await this._containerEdit(input)
1817
+ case 'Bash':
1818
+ return await this._containerBash(input, signal)
1819
+ case 'Glob':
1820
+ return await this._containerGlob(input, signal)
1821
+ case 'Grep':
1822
+ return await this._containerGrep(input, signal)
1823
+ case 'TodoWrite':
1824
+ case 'WebFetch':
1825
+ case 'AskUserQuestion':
1826
+ // Host-side execution is correct for these — see class docstring.
1827
+ return await super._dispatchBuiltinTool({ toolName, input, signal })
1828
+ default:
1829
+ return await super._dispatchBuiltinTool({ toolName, input, signal })
1830
+ }
1831
+ } catch (err) {
1832
+ // Mirror byok-tool-executor.js's catch-all: surface as an
1833
+ // is_error tool_result so the model can recover or report up.
1834
+ return {
1835
+ content: `Tool ${toolName} failed in docker-byok: ${err?.message || String(err)}`,
1836
+ isError: true,
1837
+ }
1838
+ }
1839
+ }
1840
+
1841
+ // ─────────────────────────────────────────────────────────────────────────
1842
+ // Tool implementations — container-side
1843
+ // ─────────────────────────────────────────────────────────────────────────
1844
+
1845
+ /**
1846
+ * Run a bash command inside the container as the non-root container
1847
+ * user. Single source of truth for every tool dispatch so the `useradd`
1848
+ * + `chown /workspace` setup done at container start is actually
1849
+ * respected. Mirrors `streamCliInEnvironment`'s `-u <user>` behaviour.
1850
+ *
1851
+ * Fix for PR #5021 review (Copilot, comment id 3348029166): pre-fix,
1852
+ * every tool ran as root in the container because the backend's
1853
+ * execInEnvironment didn't forward a `-u` flag. The hardening
1854
+ * (`--cap-drop ALL`, `no-new-privileges`) still capped what root could
1855
+ * do, but the explicit non-root design intent was silently violated.
1856
+ *
1857
+ * #5079: in compose mode, when a tmpfile holding ANTHROPIC_API_KEY was
1858
+ * written at start time, forward it via `--env-file` so the model's
1859
+ * Bash commands inside the container see the key — without exposing
1860
+ * it on the host's `ps` output (`--env KEY=secret` would). Bare-image
1861
+ * sessions don't need this: their `docker run --env ANTHROPIC_API_KEY`
1862
+ * already attached the key to the container env at launch time.
1863
+ */
1864
+ _execAsContainerUser({ cmd, timeout = 30_000, onData } = {}) {
1865
+ return this._dockerBackend.execInEnvironment(this._containerId, {
1866
+ cmd,
1867
+ timeout,
1868
+ user: this._containerUser,
1869
+ envFile: this._composeEnvFile || undefined,
1870
+ // #5069: forward an optional streaming callback. When absent the
1871
+ // backend keeps the buffered `execFile` path, so every existing tool
1872
+ // dispatch (Read/Write/Bash/...) is unchanged.
1873
+ onData,
1874
+ })
1875
+ }
1876
+
1877
+ async _containerRead(input) {
1878
+ const containerPath = remapToContainerPath(input?.file_path, this.cwd)
1879
+ // Use sed for offset/limit slicing inside the container so we
1880
+ // don't transfer megabytes only to throw them away on the host.
1881
+ // Default cap mirrors readFileTool's "2000 lines" — apply both a
1882
+ // line cap (sed -n) AND a byte cap (head -c) so a single 1GB line
1883
+ // can't blow the tool_result payload.
1884
+ const offset = Number(input?.offset)
1885
+ const limit = Number(input?.limit)
1886
+ const startLine = Number.isFinite(offset) && offset > 0 ? offset : 1
1887
+ const lineCap = Number.isFinite(limit) && limit > 0 ? limit : 2000
1888
+ const endLine = startLine + lineCap - 1
1889
+ // Fix for PR #5021 review (Copilot, comment id 3348029235): match
1890
+ // the host-side BYOK Read output format (5-space-padded line number,
1891
+ // arrow separator) so the model sees the same line-numbered shape
1892
+ // regardless of provider. The `awk` runs INSIDE the container after
1893
+ // the `sed | head` slice, so we still apply the line cap and the
1894
+ // byte cap before formatting (a 1GB line stays bounded).
1895
+ const cmd = `sed -n '${startLine},${endLine}p' ${shellQuote(containerPath)} | head -c ${READ_MAX_BYTES} | awk -v start=${startLine} 'BEGIN{n=start} {printf "%5d→%s\\n", n, $0; n++}'`
1896
+ const { stdout, stderr } = await this._execAsContainerUser({ cmd, timeout: 30_000 })
1897
+ if (stderr && stderr.trim()) {
1898
+ return { content: `Read failed: ${stderr.trim()}`, isError: true }
1899
+ }
1900
+ return { content: stdout, isError: false }
1901
+ }
1902
+
1903
+ async _containerWrite(input) {
1904
+ const containerPath = remapToContainerPath(input?.file_path, this.cwd)
1905
+ // Fix for PR #5021 review (Copilot, comment id 3348029266): host-side
1906
+ // writeFileTool returns EINVAL when content is missing/non-string;
1907
+ // pre-fix this branch silently truncated the file to zero bytes.
1908
+ // Allow an empty string (the model may legitimately want to clear a
1909
+ // file) but refuse undefined / number / boolean / null.
1910
+ if (typeof input?.content !== 'string') {
1911
+ return { content: 'EINVAL: content is required (string)', isError: true }
1912
+ }
1913
+ const content = input.content
1914
+ if (Buffer.byteLength(content, 'utf8') > WRITE_MAX_BYTES) {
1915
+ return {
1916
+ content: `Write refused: content exceeds ${WRITE_MAX_BYTES} bytes — split into smaller writes`,
1917
+ isError: true,
1918
+ }
1919
+ }
1920
+ // Stream the content via a heredoc-style pipe. `tee` is friendly
1921
+ // when stdin is provided; `mkdir -p` ensures parent dirs exist.
1922
+ // We base64-encode on the way in to dodge any quoting hazards
1923
+ // with newlines / single quotes / backticks in `content`.
1924
+ const encoded = Buffer.from(content, 'utf8').toString('base64')
1925
+ const parentDir = posix.dirname(containerPath)
1926
+ const cmd = [
1927
+ `mkdir -p ${shellQuote(parentDir)}`,
1928
+ `echo ${shellQuote(encoded)} | base64 -d > ${shellQuote(containerPath)}`,
1929
+ `wc -c < ${shellQuote(containerPath)}`,
1930
+ ].join(' && ')
1931
+ const { stdout, stderr } = await this._execAsContainerUser({ cmd, timeout: 30_000 })
1932
+ if (stderr && stderr.trim()) {
1933
+ return { content: `Write failed: ${stderr.trim()}`, isError: true }
1934
+ }
1935
+ const bytesWritten = Number(stdout.trim()) || 0
1936
+ return {
1937
+ content: `Wrote ${bytesWritten} bytes to ${input.file_path}.`,
1938
+ isError: false,
1939
+ }
1940
+ }
1941
+
1942
+ async _containerEdit(input) {
1943
+ const containerPath = remapToContainerPath(input?.file_path, this.cwd)
1944
+ const oldString = typeof input?.old_string === 'string' ? input.old_string : ''
1945
+ if (oldString.length === 0) {
1946
+ return { content: 'Edit refused: old_string is required', isError: true }
1947
+ }
1948
+ // Read the file via the same execInEnvironment path so a missing
1949
+ // file surfaces as a tool_result rather than an exception.
1950
+ const { stdout: existing, stderr: readErr } = await this._execAsContainerUser({
1951
+ cmd: `cat ${shellQuote(containerPath)}`,
1952
+ timeout: 30_000,
1953
+ })
1954
+ if (readErr && readErr.trim()) {
1955
+ return { content: `Edit failed: ${readErr.trim()}`, isError: true }
1956
+ }
1957
+ // Strict-unique-match + NO_CHANGE guard + LITERAL replacement via the shared
1958
+ // transform (same one the host file-ops Edit uses) — #5882 closes the drift
1959
+ // where this path lacked the NO_CHANGE guard and used slice vs the host's
1960
+ // replace. Map the codes to this provider's existing message wording.
1961
+ const result = applyEdit(existing, {
1962
+ oldString,
1963
+ newString: typeof input?.new_string === 'string' ? input.new_string : '',
1964
+ replaceAll: input?.replace_all === true,
1965
+ })
1966
+ if (!result.ok) {
1967
+ const msg = result.code === 'NOT_FOUND'
1968
+ ? `Edit failed: old_string not found in ${input.file_path}`
1969
+ : result.code === 'NOT_UNIQUE'
1970
+ ? `Edit failed: old_string matches multiple sites in ${input.file_path}; add context or pass replace_all`
1971
+ : result.code === 'NO_CHANGE'
1972
+ ? 'Edit refused: old_string and new_string are identical'
1973
+ : 'Edit refused: old_string is required'
1974
+ return { content: msg, isError: true }
1975
+ }
1976
+ const writeResult = await this._containerWrite({ file_path: input.file_path, content: result.next })
1977
+ if (writeResult.isError) return writeResult
1978
+ return {
1979
+ content: `Replaced ${result.replacements} occurrence(s) in ${input.file_path}.`,
1980
+ isError: false,
1981
+ }
1982
+ }
1983
+
1984
+ async _containerBash(input, signal) {
1985
+ const command = input?.command
1986
+ if (typeof command !== 'string' || command.length === 0) {
1987
+ return { content: 'EINVAL: command is required', isError: true }
1988
+ }
1989
+ if (signal?.aborted) {
1990
+ return { content: 'Interrupted before docker exec', isError: true }
1991
+ }
1992
+ const requested = Number(input?.timeout)
1993
+ // 600s ceiling mirrors the host-side Bash tool — long enough for
1994
+ // a slow test suite but bounded so the session never strands on a
1995
+ // runaway loop.
1996
+ const timeoutMs = Number.isFinite(requested) && requested > 0
1997
+ ? Math.min(requested, 600_000)
1998
+ : 30_000
1999
+ const { stdout, stderr } = await this._execAsContainerUser({
2000
+ cmd: command,
2001
+ timeout: timeoutMs,
2002
+ })
2003
+ const parts = []
2004
+ if (stdout) parts.push(`stdout:\n${stdout}`)
2005
+ if (stderr) parts.push(`stderr:\n${stderr}`)
2006
+ parts.push('[exit=0]')
2007
+ return { content: parts.join('\n\n'), isError: false }
2008
+ }
2009
+
2010
+ async _containerGlob(input, signal) {
2011
+ const pattern = input?.pattern
2012
+ if (typeof pattern !== 'string' || pattern.length === 0) {
2013
+ return { content: 'EINVAL: pattern is required', isError: true }
2014
+ }
2015
+ if (GLOB_PATTERN_SHELL_METACHARS.test(pattern)) {
2016
+ return {
2017
+ content: 'EINVAL: glob pattern contains shell-dangerous characters',
2018
+ isError: true,
2019
+ }
2020
+ }
2021
+ if (signal?.aborted) {
2022
+ return { content: 'Interrupted before docker exec', isError: true }
2023
+ }
2024
+ const root = input?.path
2025
+ ? remapToContainerPath(input.path, this.cwd)
2026
+ : CONTAINER_WORKSPACE
2027
+ const cmd = buildGlobCommand(pattern, root)
2028
+ const { stdout, stderr } = await this._execAsContainerUser({ cmd, timeout: 30_000 })
2029
+ if (!stdout && stderr && stderr.trim()) {
2030
+ return { content: `Glob failed: ${stderr.trim()}`, isError: true }
2031
+ }
2032
+ const files = stdout.split('\n').filter(Boolean)
2033
+ if (files.length === 0) return { content: `No matches for ${pattern}`, isError: false }
2034
+ return { content: files.join('\n'), isError: false }
2035
+ }
2036
+
2037
+ async _containerGrep(input, signal) {
2038
+ const pattern = input?.pattern
2039
+ if (typeof pattern !== 'string' || pattern.length === 0) {
2040
+ return { content: 'EINVAL: pattern is required', isError: true }
2041
+ }
2042
+ if (signal?.aborted) {
2043
+ return { content: 'Interrupted before docker exec', isError: true }
2044
+ }
2045
+ const root = input?.path
2046
+ ? remapToContainerPath(input.path, this.cwd)
2047
+ : CONTAINER_WORKSPACE
2048
+ // Shared builders (#5882) — identical rg/grep shaping as the host Grep.
2049
+ // `maskExit:true` appends `; true` because execInEnvironment rejects on any
2050
+ // non-zero exit, and both rg and grep -r exit 1 on "no matches" (PR #5021
2051
+ // review, Copilot comment 3348029186) — without the mask the legitimate
2052
+ // "No matches" branch below would be unreachable.
2053
+ const { ci, ln, globArg } = buildGrepArgs(input)
2054
+ const cmd = buildGrepCommand({ pattern, root, ci, ln, globArg, maskExit: true })
2055
+ const { stdout, stderr } = await this._execAsContainerUser({ cmd, timeout: 30_000 })
2056
+ if (!stdout && stderr && stderr.trim()) {
2057
+ return { content: `Grep failed: ${stderr.trim()}`, isError: true }
2058
+ }
2059
+ if (!stdout) return { content: `No matches for ${pattern}`, isError: false }
2060
+ return { content: stdout, isError: false }
2061
+ }
2062
+
2063
+ /**
2064
+ * Tear down the container we own, then call super.destroy() so the
2065
+ * agent-loop teardown (MCP fleet, permissions, listeners) runs.
2066
+ * When attached to an external container, leave it running.
2067
+ *
2068
+ * #5022: when pooling is enabled and the session went start-clean
2069
+ * (`_containerReady` was set), the container is released back to the
2070
+ * pool for the next session of the same resource shape to claim. On
2071
+ * any error path — or if pooling is disabled — fall back to inline
2072
+ * `docker rm -f`.
2073
+ */
2074
+ async destroy() {
2075
+ const containerId = this._containerId
2076
+ const owned = this._containerOwned
2077
+ const wasReady = this._containerReady
2078
+ const pool = this._pool
2079
+ const acquiredFromPool = this._acquiredFromPool
2080
+ // #5024: compose teardown uses `docker compose down` against the
2081
+ // session-scoped project id. Snapshot the project + file BEFORE
2082
+ // nulling state so the finally-block has them.
2083
+ const composeFile = this._composeFile
2084
+ const composeProject = this._composeProject
2085
+ // #5079: unlink the ANTHROPIC_API_KEY tmpfile created at compose-up
2086
+ // time. Snapshot the path BEFORE nulling so the finally-block has
2087
+ // it; unlink AFTER `compose down` runs (the tmpfile is referenced
2088
+ // by the down call indirectly via the project metadata, and we want
2089
+ // a clean teardown order — compose first, then secret material).
2090
+ const composeEnvFile = this._composeEnvFile
2091
+ const cwd = this.cwd || process.cwd()
2092
+ this._containerId = null
2093
+ this._containerReady = false
2094
+ this._acquiredFromPool = false
2095
+ this._composeEnvFile = null
2096
+ try {
2097
+ await super.destroy()
2098
+ } finally {
2099
+ if (composeFile && composeProject) {
2100
+ // Compose mode: tear the whole stack down. The pool is
2101
+ // disabled in compose mode so we never need the release path.
2102
+ log.info(`removing compose stack ${composeProject} (file=${composeFile})`)
2103
+ try {
2104
+ await this._dockerBackend.destroyComposeEnvironment({
2105
+ composeFile,
2106
+ composeProject,
2107
+ cwd,
2108
+ })
2109
+ // #5081 — only drop the on-disk record after a clean teardown. If
2110
+ // `compose down` threw (daemon gone), the entry has to survive so
2111
+ // the next boot's sweep retries the teardown.
2112
+ try {
2113
+ this._getComposeStateStore().forget(composeProject)
2114
+ } catch (err) {
2115
+ log.warn(`docker-byok compose: failed to forget project id: ${err.message}`)
2116
+ }
2117
+ } catch (err) {
2118
+ log.warn(`compose destroy failed: ${err.message}`)
2119
+ }
2120
+ // Unlink the env-file last — best-effort, silent on missing.
2121
+ if (composeEnvFile) {
2122
+ this._unlinkEnvFile(composeEnvFile)
2123
+ }
2124
+ } else if (!containerId || !owned) {
2125
+ // Nothing for us to clean up — externally-managed container
2126
+ // stays running for whoever owns it.
2127
+ } else if (pool && wasReady) {
2128
+ // Healthy session end → hand back to the pool. The pool may
2129
+ // still evict (over cap, shutting down) but that's its call.
2130
+ log.info(`releasing container ${containerId.slice(0, 12)} to pool`)
2131
+ try {
2132
+ await pool.release(this._poolKeyFor(containerId), containerId)
2133
+ } catch (err) {
2134
+ log.warn(`pool release of ${containerId.slice(0, 12)} failed: ${err.message} — falling back to docker rm -f`)
2135
+ await this._rmContainer(containerId)
2136
+ }
2137
+ } else {
2138
+ log.info(`removing container ${containerId.slice(0, 12)}${acquiredFromPool ? ' (was pooled)' : ''}`)
2139
+ await this._rmContainer(containerId)
2140
+ }
2141
+ }
2142
+ }
2143
+
2144
+ /**
2145
+ * Inline `docker rm -f` fallback. Swallows errors — the alternative
2146
+ * is leaking a container, which is worse than a warn log.
2147
+ */
2148
+ _rmContainer(containerId) {
2149
+ return new Promise((resolve) => {
2150
+ // `execFile` ignores `stdio`; cap `maxBuffer` so a misbehaving
2151
+ // docker(8) can't OOM us on stderr.
2152
+ this._execFile('docker', ['rm', '-f', containerId], { maxBuffer: 64 * 1024 }, (err) => {
2153
+ if (err) log.warn(`failed to remove container ${containerId.slice(0, 12)}: ${err.message}`)
2154
+ resolve()
2155
+ })
2156
+ })
2157
+ }
2158
+
2159
+ /**
2160
+ * Pool key for a specific container id. Currently this just computes
2161
+ * from the session's resource shape — the containerId arg is here
2162
+ * because the destroy() path may be called after `this._containerId`
2163
+ * has been nulled out. Kept as a method so a future variant (per-
2164
+ * container key derived from labels) can override.
2165
+ */
2166
+ _poolKeyFor(_containerId) {
2167
+ return this._poolKey()
2168
+ }
2169
+ }
2170
+
2171
+ // Re-exported for tests + dashboard introspection.
2172
+ export { CONTAINER_WORKSPACE }