@chroxy/server 0.11.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -121,21 +121,39 @@
121
121
  */
122
122
 
123
123
  import { execFile } from 'child_process'
124
- import { mkdirSync, writeFileSync, unlinkSync } from 'fs'
124
+ import { mkdirSync, writeFileSync, rmSync } from 'fs'
125
125
  import { createHash, randomBytes } from 'crypto'
126
- import { homedir, tmpdir } from 'os'
126
+ import { tmpdir } from 'os'
127
127
  import { isAbsolute, join, posix, resolve, sep } from 'path'
128
128
  import { ClaudeByokSession } from './byok-session.js'
129
+ import { BYOK_CUSTOMIZATION } from './provider-customization.js'
130
+ import { sweepStaleOwnedDirs, ensureOwnedBaseDir, OWNER_PID_FILE } from './utils/stale-session-dirs.js'
129
131
  import {
130
132
  applyEdit,
131
133
  GLOB_PATTERN_SHELL_METACHARS,
132
- buildGlobCommand,
134
+ globPatternEscapeReason,
135
+ globPatternEscapeMessage,
136
+ globPatternComplexityReason,
137
+ globPatternComplexityMessage,
138
+ globMatchEscapesRoot,
133
139
  buildGrepArgs,
134
140
  buildGrepCommand,
141
+ splitGrepNotes,
142
+ buildConfinedContainerCommand,
143
+ buildConfinedGlobBody,
144
+ parseConfinedContainerStdout,
145
+ splitWithheldTrailer,
146
+ confinedContainerFailureMessage,
135
147
  } from './built-in-tools/tool-transforms.js'
136
148
  import { DockerBackend } from './environments/backends/docker.js'
137
- import { classifyDockerError } from './docker-session.js'
149
+ import {
150
+ CONTAINER_VANISHED_MESSAGE,
151
+ classifyDockerError,
152
+ inspectContainerLiveness,
153
+ surfaceContainerVanished,
154
+ } from './docker-session.js'
138
155
  import { buildPoolKey, getSharedPool, isPoolEnabled } from './docker-byok-pool.js'
156
+ import { DEFAULT_LIVENESS_INTERVAL_MS } from './container-liveness-monitor.js'
139
157
  import { getSharedComposeStateStore } from './byok-compose-state-shared.js'
140
158
  import { createLogger } from './logger.js'
141
159
  import { writeFileRestricted } from './platform.js'
@@ -147,9 +165,61 @@ import {
147
165
  import { isOperatorTimeoutInRange } from './duration.js'
148
166
  import { getErrorMessage } from './utils/error-message.js'
149
167
  import { VALID_USERNAME_RE } from './utils/validation-patterns.js'
168
+ import { configPath } from './config-dir.js'
150
169
 
151
170
  const log = createLogger('docker-byok')
152
171
 
172
+ /**
173
+ * #7609 — how long a post-failure `docker inspect` that found the container
174
+ * RUNNING suppresses further inspects for that same container. A failing
175
+ * container-routed tool is routine (every non-zero exit rejects), so without
176
+ * this a burst of failures is a burst of inspect spawns, each up to 10s on a
177
+ * slow daemon, on the error path the model is waiting on.
178
+ *
179
+ * It is the #7601 poll's own interval on purpose: the poll already re-checks
180
+ * every session's container that often, so a vanish the cooldown hides from
181
+ * the tool path is surfaced by the next poll tick at most that long after the
182
+ * vanish — the cooldown never makes detection later than the poll would
183
+ * already make it. Only the NEGATIVE ('running') result is cached; a vanish is
184
+ * never cached away (see _inspectLiveness).
185
+ */
186
+ export const INSPECT_ALIVE_COOLDOWN_MS = DEFAULT_LIVENESS_INTERVAL_MS
187
+
188
+ /**
189
+ * #7609 — the cooldown after an 'unknown' probe (inspect timed out, the daemon
190
+ * is down or hung, an unclassified error). 'unknown' proved nothing about the
191
+ * container, so it must NOT start the long window above: that would let one
192
+ * hiccup hide a real vanish for 30s. But re-spawning an inspect that already
193
+ * burned its 10s timeout on every following failure is exactly the cost this
194
+ * issue exists to bound, so a SHORT window applies. Trade-off: a container
195
+ * that vanishes in the 5s right after a daemon hiccup is reported by the poll
196
+ * rather than by the tool failure — a delay, never a miss.
197
+ */
198
+ export const INSPECT_UNKNOWN_COOLDOWN_MS = 5_000
199
+
200
+ /**
201
+ * The built-in tools `_dispatchBuiltinTool` routes INTO the container, keyed
202
+ * to their implementations (every one goes through `_execAsContainerUser`).
203
+ * Anything not in here — TodoWrite (a pure in-memory map), WebFetch (HTTP,
204
+ * never touches the host FS), AskUserQuestion, and any tool the base class
205
+ * grows later — runs host-side via the super dispatcher.
206
+ *
207
+ * #7600 — this ONE map is both the dispatch table and the post-failure probe
208
+ * gate: a throw from a tool routed through it may mean the container vanished,
209
+ * while a host-side tool never touches Docker and never probes. Keeping the
210
+ * routing and the gate on a single roster is deliberate — a separate list of
211
+ * "container tools" beside the switch was the hardcoded-list-next-to-a-growing-
212
+ * set defect (#7607 review: dropping five names from it left every test green).
213
+ */
214
+ const CONTAINER_ROUTED_TOOLS = new Map([
215
+ ['Read', (session, input) => session._containerRead(input)],
216
+ ['Write', (session, input) => session._containerWrite(input)],
217
+ ['Edit', (session, input) => session._containerEdit(input)],
218
+ ['Bash', (session, input, signal) => session._containerBash(input, signal)],
219
+ ['Glob', (session, input, signal) => session._containerGlob(input, signal)],
220
+ ['Grep', (session, input, signal) => session._containerGrep(input, signal)],
221
+ ])
222
+
153
223
  const DEFAULT_IMAGE = 'node:22-slim'
154
224
  const DEFAULT_MEMORY_LIMIT = '2g'
155
225
  const DEFAULT_CPU_LIMIT = '2'
@@ -337,6 +407,24 @@ export function normalizePostCreateCommand(value) {
337
407
  }
338
408
 
339
409
  export class DockerByokSession extends ClaudeByokSession {
410
+ // #8876: opt out of the manager's provider start deadline. Its async start()
411
+ // builds/pulls an image and runs a postCreateCommand, each phase separately
412
+ // bounded (docker build 600 s, docker run 120 s, postCreateCommand 5 min by
413
+ // default and configurable), so a healthy start can exceed the default
414
+ // deadline; do not kill a legitimate container start.
415
+ static get startDeadlineMs() { return null }
416
+
417
+ static get customizationDescriptor() {
418
+ return {
419
+ ...BYOK_CUSTOMIZATION,
420
+ chroxyChannels: BYOK_CUSTOMIZATION.chroxyChannels.map((entry) => ({
421
+ ...entry,
422
+ content: entry.content.filter((content) => content !== 'project-instructions'),
423
+ })),
424
+ byteBudgets: { ...BYOK_CUSTOMIZATION.byteBudgets, projectInstructions: 'unsupported' },
425
+ }
426
+ }
427
+
340
428
  // #5891: declare Claude-family membership explicitly rather than inheriting it
341
429
  // from ClaudeByokSession. Docker-BYOK runs Claude/Anthropic-key models in a
342
430
  // container, so it IS Claude-family — its model ids take the soft-fallback path
@@ -465,6 +553,8 @@ export class DockerByokSession extends ClaudeByokSession {
465
553
  * pooling is skipped entirely (per-session lifecycle only).
466
554
  * @param {Record<string,string>} [opts._poolEnv] Test seam — alternate env
467
555
  * for pool enablement, defaults to `process.env`.
556
+ * @param {() => number} [opts._now] Test seam — clock for the
557
+ * #7609 post-failure inspect cooldown (defaults to `Date.now`).
468
558
  */
469
559
  constructor(opts = {}) {
470
560
  // Forward every BaseSession/ClaudeByokSession opt verbatim via
@@ -521,13 +611,29 @@ export class DockerByokSession extends ClaudeByokSession {
521
611
  // env, passed to every `docker exec` via `--env-file` so the key is
522
612
  // forwarded into model-spawned commands WITHOUT exposing it on the
523
613
  // 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).
614
+ // in `ps`). #7373 — the file no longer sits flat in os.tmpdir(): it
615
+ // lives inside `_composeEnvDir`, a dedicated `owner.pid`-stamped
616
+ // per-session dir under ENV_FILE_BASE (same shape as claude-tui's
617
+ // hook-sink dirs and claude-cli's permission-mode sidecar), so a
618
+ // SIGKILL/crash leaves the boot-time sweep able to remove an orphaned
619
+ // credential file instead of leaking it in /tmp forever. The file is
620
+ // mode 0600; destroy() removes the whole per-session dir (and
621
+ // best-effort on start-failure paths).
526
622
  this._composeEnvFile = null
527
- // Test seam: override the writer / unlinker so tests can assert the
623
+ this._composeEnvDir = null
624
+ // Test seam: override the writer / remover so tests can assert the
528
625
  // file lifecycle without touching the real filesystem.
529
626
  this._writeEnvFile = opts._writeEnvFile || ((p, c) => writeFileSync(p, c, { mode: 0o600 }))
530
- this._unlinkEnvFile = opts._unlinkEnvFile || ((p) => { try { unlinkSync(p) } catch { /* ignore */ } })
627
+ // #8047 review N2/N6 — named `_removeEnvDir`, not `_unlinkEnvFile`: it
628
+ // takes a DIRECTORY (not the bare file) and removes it recursively, so
629
+ // the owner.pid stamp is removed along with the credential. Every
630
+ // regular call site (_startComposeStack's two cleanup paths, destroy()'s
631
+ // primary path) passes the owning dir. The one exception is destroy()'s
632
+ // `composeEnvFile` fallback — a defensive branch for a state that
633
+ // should not arise (dir tracking lost while the file path survived) —
634
+ // which passes the bare file; rmSync handles a plain file the same as a
635
+ // dir, so the credential is still removed either way.
636
+ this._removeEnvDir = opts._removeEnvDir || ((p) => { try { rmSync(p, { recursive: true, force: true }) } catch { /* ignore */ } })
531
637
  this._envForApiKey = opts._envForApiKey || process.env
532
638
  // #5081 — crash-durable record of the compose project id so a daemon
533
639
  // crash between `compose up` and `compose down` leaves an on-disk paper
@@ -556,6 +662,18 @@ export class DockerByokSession extends ClaudeByokSession {
556
662
  this._dockerBackend = opts._dockerBackend || new DockerBackend()
557
663
  this._execFile = opts._execFile || execFile
558
664
  this._containerReady = false
665
+ // #7600 — the CONTAINER_VANISHED idempotency latch (see
666
+ // surfaceContainerVanished in docker-session.js; same field the
667
+ // DockerSession / DockerSdkSession surfaces use).
668
+ this._containerVanishedNotified = false
669
+ // #7609 — post-failure inspect throttle. `_inspectCooldown` is
670
+ // `{ containerId, status, until }` for the last probe that learned
671
+ // something non-fatal; `_inspectInFlight` is `{ containerId, promise }`
672
+ // so concurrent failing tools share one inspect. `_now` is the test seam
673
+ // for the clock (the cooldown is wall-clock, not timer-driven).
674
+ this._now = opts._now || Date.now
675
+ this._inspectCooldown = null
676
+ this._inspectInFlight = null
559
677
  // #5023 snapshot / restore opts. All string opts are trimmed before
560
678
  // the length check so callers passing whitespace-only values (e.g.
561
679
  // `' '`) get the same default as no-opt-at-all — matches how
@@ -566,7 +684,7 @@ export class DockerByokSession extends ClaudeByokSession {
566
684
  : null
567
685
  this._snapshotsDir = typeof opts.snapshotsDir === 'string' && opts.snapshotsDir.trim().length > 0
568
686
  ? opts.snapshotsDir.trim()
569
- : join(process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'), 'snapshots')
687
+ : configPath('snapshots')
570
688
  this._sourceSessionId = typeof opts.sourceSessionId === 'string' && opts.sourceSessionId.trim().length > 0
571
689
  ? opts.sourceSessionId.trim()
572
690
  : null
@@ -834,6 +952,164 @@ export class DockerByokSession extends ClaudeByokSession {
834
952
  this._pool.markSoiled(this._containerId)
835
953
  }
836
954
 
955
+ /**
956
+ * #7600 — the CONTAINER_VANISHED surface for docker-byok, mirroring the
957
+ * DockerSession / DockerSdkSession methods (#7599 / #7601). Exposing
958
+ * `notifyContainerVanished` is what enrols this session in the
959
+ * SessionManager's proactive liveness poll (its target enumeration
960
+ * feature-detects the method) — and that poll is the ONLY idle-time
961
+ * detection a byok session gets: the agent loop runs on the host and the
962
+ * container only ever sees discrete `docker exec` calls, so there is no
963
+ * long-lived in-container process whose exit could report the vanish.
964
+ *
965
+ * Beyond the shared once-per-vanish emit, a vanish has two byok-specific
966
+ * consequences that live HERE rather than in the shared helper:
967
+ * - `_containerReady` flips false, so every later tool dispatch is
968
+ * refused up-front ("container not ready"). The model keeps getting an
969
+ * is_error tool_result and NOTHING falls back to host execution.
970
+ * - the dead id is marked soiled in the shared pool, so a `release()`
971
+ * evicts it instead of pooling it for a successor session (and the
972
+ * `_containerReady === false` above already routes destroy() to
973
+ * `docker rm -f` rather than release). Compose-stack and externally-
974
+ * owned sessions carry no pool; the mark is a no-op for them.
975
+ *
976
+ * Both consequences are gated on the latch transition (the helper
977
+ * returning true): a repeat poll verdict re-runs neither, and a session
978
+ * that is already tearing down (`_destroying`) is left to destroy().
979
+ * `_containerId` is never nulled here (the #7561 trap) — destroy() needs it,
980
+ * and so does clearContainerVanished, which restores readiness when the
981
+ * poll sees the same container running again.
982
+ *
983
+ * @returns {boolean} true when this call surfaced the error
984
+ */
985
+ notifyContainerVanished() {
986
+ if (!surfaceContainerVanished(this)) return false
987
+ this._inspectCooldown = null // #7609 — a vanish is never cached away
988
+ this._containerReady = false
989
+ this.markActiveContainerSoiled()
990
+ return true
991
+ }
992
+
993
+ /**
994
+ * #7601 — reset the latch after the liveness poll observes the container
995
+ * running again, so a later vanish re-surfaces. Poll-owned.
996
+ *
997
+ * #7600 — for byok the SAME transition also restores `_containerReady`.
998
+ * A container observed running again under the same id is one that was
999
+ * stopped and started (a Control Room restart of an env-backed container,
1000
+ * `docker compose restart`, a manual `docker start`): its writable layer —
1001
+ * the `useradd` / `chown` setup, the workspace, the run-time env — is
1002
+ * intact, and byok has no in-container process to rebind, so the next
1003
+ * `docker exec` simply works. That is the whole of a byok re-attach (the
1004
+ * exec-based providers' version is #7602). Leaving readiness off here
1005
+ * would brick exactly those sessions, which self-healed before #7600. A
1006
+ * per-session `--rm` container can never be observed running again, so
1007
+ * this branch is only ever taken for a container that genuinely returned.
1008
+ *
1009
+ * Gated on the latch transition: a 'running' verdict on a session that
1010
+ * never vanished must NOT set readiness — the poll enumerates a session as
1011
+ * soon as it holds a container id, which is before start() finishes the
1012
+ * in-container setup. The pool's soiled mark is left in place: a container
1013
+ * that was stopped underneath a session is not offered to a successor.
1014
+ *
1015
+ * #7602 — returns whether the latch transitioned, so the poll can tell a
1016
+ * recovery edge from a routine healthy tick. byok exposes no
1017
+ * `reattachContainer`, so that edge is a no-op for it: the readiness restore
1018
+ * above already IS the byok re-attach, and the exec-based re-attach is
1019
+ * `DockerSdkSession`'s.
1020
+ *
1021
+ * @returns {boolean} true when the latch transitioned
1022
+ */
1023
+ clearContainerVanished() {
1024
+ if (!this._containerVanishedNotified) return false
1025
+ this._containerVanishedNotified = false
1026
+ this._inspectCooldown = null // #7609 — back from a vanish: judge it afresh
1027
+ if (this._containerId && !this._destroying) this._containerReady = true
1028
+ return true
1029
+ }
1030
+
1031
+ /**
1032
+ * #7600 — after a container-routed tool dispatch throws, ask Docker whether
1033
+ * the container is still there. Resolves true ONLY on a confirmed vanish
1034
+ * (inspect verdict 'gone') — i.e. "the container really is gone", which is
1035
+ * what the caller's tool_result text reports. It calls
1036
+ * notifyContainerVanished on the way, but that call is a no-op when the
1037
+ * vanish was already surfaced (the poll got there first) or the session is
1038
+ * tearing down, and the verdict is still true in both cases: the fact is
1039
+ * real even when nothing new is emitted (#7607 Copilot review).
1040
+ *
1041
+ * The exec error text alone is not proof: a restart window reports
1042
+ * `container <id> is not running` for a container that is back a moment
1043
+ * later, and a command killed mid-exec reports nothing container-shaped at
1044
+ * all — so the inspect is the arbiter. Its 'running' verdict (transient
1045
+ * exec failure) and its 'unknown' verdict (daemon down / unclassified
1046
+ * error) both resolve false and surface nothing: a Docker outage must not
1047
+ * be reported as every session's container vanishing (the #7601
1048
+ * false-safety guard, see inspectContainerLiveness). A backend without an
1049
+ * inspect (older test stubs) is 'unknown' too, never a vanish.
1050
+ *
1051
+ * #7609 — the inspect itself goes through `_inspectLiveness`, which bounds
1052
+ * the rate (negative-result cooldown + one shared in-flight probe).
1053
+ */
1054
+ async _probeContainerVanished() {
1055
+ const containerId = this._containerId
1056
+ const backend = this._dockerBackend
1057
+ if (!containerId || typeof backend?.getEnvironmentStatus !== 'function') return false
1058
+ const status = await this._inspectLiveness(containerId, backend)
1059
+ if (status !== 'gone') return false
1060
+ log.warn(`container ${containerId.slice(0, 12)} is gone (inspect after a failed tool dispatch) — surfacing CONTAINER_VANISHED`)
1061
+ this.notifyContainerVanished()
1062
+ return true
1063
+ }
1064
+
1065
+ /**
1066
+ * #7609 — the rate-bounded `docker inspect` behind _probeContainerVanished.
1067
+ * Resolves 'running' | 'gone' | 'unknown'.
1068
+ *
1069
+ * - Within a cooldown armed for THIS container id, the inspect is skipped
1070
+ * and the remembered verdict returned ('running' for the long window,
1071
+ * 'unknown' for the short one) — both mean "not a confirmed vanish".
1072
+ * - Only 'running' and 'unknown' arm a cooldown. 'gone' never does: it is
1073
+ * the positive result, it runs the vanish path (which also clears any
1074
+ * cooldown), and the readiness flip stops further probes by itself.
1075
+ * - A cooldown is bound to the container id it was armed for, so a
1076
+ * respawned / re-acquired container (new id) is never judged by its
1077
+ * predecessor's verdict; notify/clearContainerVanished drop it too, which
1078
+ * covers the same-id restart.
1079
+ * - Concurrent failing tools share one in-flight inspect for the same id
1080
+ * instead of each spawning their own.
1081
+ *
1082
+ * What the cooldown can hide is bounded: a vanish inside the window is not
1083
+ * seen by the tool path, but the #7601 poll (same period as the long window)
1084
+ * surfaces it, and the tool still returns its plain error meanwhile.
1085
+ */
1086
+ _inspectLiveness(containerId, backend) {
1087
+ const cooldown = this._inspectCooldown
1088
+ if (cooldown && cooldown.containerId === containerId && this._now() < cooldown.until) {
1089
+ return Promise.resolve(cooldown.status)
1090
+ }
1091
+ const inFlight = this._inspectInFlight
1092
+ if (inFlight && inFlight.containerId === containerId) return inFlight.promise
1093
+
1094
+ const entry = { containerId, promise: null }
1095
+ entry.promise = (async () => {
1096
+ try {
1097
+ const status = await inspectContainerLiveness((id) => backend.getEnvironmentStatus(id), containerId)
1098
+ if (status === 'gone') {
1099
+ this._inspectCooldown = null
1100
+ } else {
1101
+ const ms = status === 'running' ? INSPECT_ALIVE_COOLDOWN_MS : INSPECT_UNKNOWN_COOLDOWN_MS
1102
+ this._inspectCooldown = { containerId, status, until: this._now() + ms }
1103
+ }
1104
+ return status
1105
+ } finally {
1106
+ if (this._inspectInFlight === entry) this._inspectInFlight = null
1107
+ }
1108
+ })()
1109
+ this._inspectInFlight = entry
1110
+ return entry.promise
1111
+ }
1112
+
837
1113
  /**
838
1114
  * Snapshot the live container's writable layer into a Docker image
839
1115
  * tag via `docker commit`, then mark the container "soiled" so the
@@ -1425,6 +1701,34 @@ export class DockerByokSession extends ClaudeByokSession {
1425
1701
  return JSON.stringify(value) ?? ''
1426
1702
  }
1427
1703
 
1704
+ /**
1705
+ * Base dir the per-session compose env-file dirs live under (#7373).
1706
+ * Named once so `_startComposeStack()` and the boot sweep cannot drift
1707
+ * onto two different paths. Mirrors `CliSession.PERMISSION_MODE_SIDECAR_BASE`
1708
+ * and `ClaudeTuiSession.SINK_BASE`.
1709
+ */
1710
+ static get ENV_FILE_BASE() { return join(tmpdir(), 'chroxy-byok') }
1711
+
1712
+ /**
1713
+ * #7373 — boot-time sweep of compose env-file dirs orphaned by a crash.
1714
+ * destroy() removes a session's own dir, but a SIGKILL leaks it, so a
1715
+ * long-lived host accumulates one per crashed compose-mode session that
1716
+ * ever forwarded ANTHROPIC_API_KEY — a leaked API KEY, not just a leaked
1717
+ * directory. Same ownership rule and implementation as the claude-tui sink
1718
+ * sweep and the claude-cli sidecar sweep — only dirs whose `owner.pid` is
1719
+ * DEAD are removed, so a live daemon's dirs (including this one's) are
1720
+ * kept and the sweep is safe to run unconditionally at boot.
1721
+ *
1722
+ * @param {object} [logger] - logger with info/warn (defaults to module log)
1723
+ * @returns {{swept:number, kept:number}}
1724
+ */
1725
+ static sweepStaleEnvDirs(logger = log) {
1726
+ return sweepStaleOwnedDirs(DockerByokSession.ENV_FILE_BASE, {
1727
+ logger,
1728
+ label: 'docker-byok compose env-file',
1729
+ })
1730
+ }
1731
+
1428
1732
  /**
1429
1733
  * #5024: Bring up the compose stack and identify the primary service
1430
1734
  * container. The stack is owned by THIS session — destroy() runs
@@ -1440,42 +1744,74 @@ export class DockerByokSession extends ClaudeByokSession {
1440
1744
  * #5079 — ANTHROPIC_API_KEY forwarding. The bare-image path forwards
1441
1745
  * the key via `docker run --env`; compose mode does the same job via
1442
1746
  * 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:
1747
+ * without being exposed in `ps` output. #7373 — the tmpfile is written
1748
+ * at 0600 inside an `owner.pid`-stamped, 0700 per-session dir under
1749
+ * `ENV_FILE_BASE` (not bare under os.tmpdir()) and:
1445
1750
  * - passed to `docker compose --env-file <path>` so a service that
1446
1751
  * references `${ANTHROPIC_API_KEY}` in its compose file resolves
1447
1752
  * the value during interpolation; and
1448
1753
  * - reused on every `_execAsContainerUser` dispatch so a Bash command
1449
1754
  * the model spawns inside the container (e.g. `curl
1450
1755
  * 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.
1756
+ * destroy() removes the whole per-session dir (not just the file), and a
1757
+ * boot-time sweep (`sweepStaleEnvDirs`) removes a crashed session's dir
1758
+ * too. When `ANTHROPIC_API_KEY` is not set in the host env, no dir is
1759
+ * created — the path stays at `null` and `_execAsContainerUser` skips the
1760
+ * `--env-file` flag.
1454
1761
  */
1455
1762
  async _startComposeStack() {
1456
1763
  if (!this._composeProject) {
1457
1764
  this._composeProject = `chroxy-byok-${randomBytes(6).toString('hex')}`
1458
1765
  }
1459
1766
  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.
1767
+ // #5079/#7373: write the ANTHROPIC_API_KEY tmpfile BEFORE compose up so
1768
+ // the file is on disk for both compose interpolation AND for the exec
1769
+ // dispatches that follow. #7373 — the file lives inside a dedicated,
1770
+ // `owner.pid`-stamped per-session dir under ENV_FILE_BASE rather than
1771
+ // flat in os.tmpdir(), so a crash leaves the boot-time sweep able to
1772
+ // tell a dead session's leftover credential from a live one's and
1773
+ // remove only the dead one (the same shape ClaudeTuiSession's sink dirs
1774
+ // and CliSession's permission-mode sidecar use — see
1775
+ // utils/stale-session-dirs.js).
1465
1776
  const apiKey = this._envForApiKey?.ANTHROPIC_API_KEY
1466
1777
  if (apiKey) {
1467
- const envFilePath = join(tmpdir(), `chroxy-byok-${this._composeProject}.env`)
1778
+ // #8047 review S1 — declared OUTSIDE the try so the catch can clean up
1779
+ // a dir that was successfully created (and stamped with owner.pid)
1780
+ // even when the LATER `_writeEnvFile` call is what throws (ENOSPC,
1781
+ // EIO, a partial write). Without this, that dir — owner.pid plus
1782
+ // whatever fragment of the key made it to disk — had nothing tracking
1783
+ // it (`_composeEnvDir` is about to be nulled in the catch below), so
1784
+ // destroy() would never remove it and the boot sweep would keep it
1785
+ // forever: owner.pid still names this live daemon.
1786
+ let dir = null
1468
1787
  try {
1788
+ const base = ensureOwnedBaseDir(DockerByokSession.ENV_FILE_BASE)
1789
+ dir = join(base, `s-${this._composeProject}`)
1790
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
1791
+ // Stamp the owning pid so the boot-time sweep can tell a live
1792
+ // daemon's dir from one orphaned by a crash. Best-effort: a missing
1793
+ // pidfile just makes the dir sweep-eligible after a grace window —
1794
+ // the safe default for an orphan.
1795
+ try { writeFileSync(join(dir, OWNER_PID_FILE), String(process.pid)) } catch { /* best effort */ }
1796
+ const envFilePath = join(dir, `${this._composeProject}.env`)
1469
1797
  this._writeEnvFile(envFilePath, `ANTHROPIC_API_KEY=${apiKey}\n`)
1470
1798
  this._composeEnvFile = envFilePath
1799
+ this._composeEnvDir = dir
1471
1800
  } catch (err) {
1472
1801
  // Non-fatal: log and proceed without the env file. The model
1473
1802
  // running inside the container won't see the key (matching the
1474
1803
  // pre-#5079 behaviour) but the host-side agent loop is what
1475
1804
  // actually authenticates to Anthropic, so the session still
1476
1805
  // functions for the common case.
1477
- log.warn(`docker-byok compose: failed to write env-file ${envFilePath}: ${err.message}`)
1806
+ //
1807
+ // `dir` is only non-null once `ensureOwnedBaseDir` has already
1808
+ // returned successfully, so this never touches an attacker's
1809
+ // symlink target — a refusal from `ensureOwnedBaseDir` itself
1810
+ // leaves `dir` at `null` and this is a no-op.
1811
+ if (dir) this._removeEnvDir(dir)
1812
+ log.warn(`docker-byok compose: failed to write env-file for ${this._composeProject}: ${err.message}`)
1478
1813
  this._composeEnvFile = null
1814
+ this._composeEnvDir = null
1479
1815
  }
1480
1816
  }
1481
1817
  log.info(`docker-byok compose stack starting (file=${this._composeFile} project=${this._composeProject} service=${this._composeService || '<first>'})`)
@@ -1491,12 +1827,14 @@ export class DockerByokSession extends ClaudeByokSession {
1491
1827
  envFile: this._composeEnvFile,
1492
1828
  })
1493
1829
  } catch (err) {
1494
- // Compose up failed — unlink the tmpfile before re-throwing so a
1830
+ // Compose up failed — remove the whole per-session env dir (the
1831
+ // tmpfile AND its owner.pid stamp) before re-throwing so a
1495
1832
  // start-failure path doesn't leak the key on disk.
1496
- if (this._composeEnvFile) {
1497
- this._unlinkEnvFile(this._composeEnvFile)
1498
- this._composeEnvFile = null
1833
+ if (this._composeEnvDir) {
1834
+ this._removeEnvDir(this._composeEnvDir)
1835
+ this._composeEnvDir = null
1499
1836
  }
1837
+ this._composeEnvFile = null
1500
1838
  const error = new Error(`docker compose start failed: ${err.message}`)
1501
1839
  error.code = err.code || 'compose_start_failed'
1502
1840
  throw error
@@ -1801,38 +2139,45 @@ export class DockerByokSession extends ClaudeByokSession {
1801
2139
  */
1802
2140
  async _dispatchBuiltinTool({ toolName, input, signal }) {
1803
2141
  if (!this._containerReady || !this._containerId) {
2142
+ // #7600 — after a surfaced vanish, say so on EVERY refused dispatch, not
2143
+ // only the one that detected it: a generic "not ready" reads to the model
2144
+ // as a transient startup state and invites retrying up to the round cap.
2145
+ const why = this._containerVanishedNotified
2146
+ ? CONTAINER_VANISHED_MESSAGE
2147
+ : 'container not ready'
1804
2148
  return {
1805
- content: `docker-byok: container not ready (tool ${toolName})`,
2149
+ content: `docker-byok: ${why} (tool ${toolName})`,
1806
2150
  isError: true,
1807
2151
  }
1808
2152
  }
1809
2153
  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
- }
2154
+ const containerImpl = CONTAINER_ROUTED_TOOLS.get(toolName)
2155
+ if (containerImpl) return await containerImpl(this, input, signal)
2156
+ // Host-side execution is correct for everything else — see the map's
2157
+ // docstring and the class docstring.
2158
+ return await super._dispatchBuiltinTool({ toolName, input, signal })
1831
2159
  } catch (err) {
2160
+ // #7600 — a container-routed tool may have thrown BECAUSE the container
2161
+ // vanished (docker exec: `No such container` / `container <id> is not
2162
+ // running`). Confirm with an inspect before surfacing anything at the
2163
+ // session level; a transient failure keeps the plain error text. Either
2164
+ // way this stays an is_error tool_result — never a host-side retry. The
2165
+ // probe is fenced so that even a throw from inside it (an 'error' emit
2166
+ // with no listener attached) still yields a tool_result, not a rejected
2167
+ // dispatch.
2168
+ let vanished = false
2169
+ if (CONTAINER_ROUTED_TOOLS.has(toolName)) {
2170
+ try {
2171
+ vanished = await this._probeContainerVanished()
2172
+ } catch (probeErr) {
2173
+ log.warn(`vanish probe after a failed ${toolName} dispatch threw: ${probeErr?.message || probeErr}`)
2174
+ }
2175
+ }
1832
2176
  // Mirror byok-tool-executor.js's catch-all: surface as an
1833
2177
  // is_error tool_result so the model can recover or report up.
2178
+ const detail = vanished ? CONTAINER_VANISHED_MESSAGE : (err?.message || String(err))
1834
2179
  return {
1835
- content: `Tool ${toolName} failed in docker-byok: ${err?.message || String(err)}`,
2180
+ content: `Tool ${toolName} failed in docker-byok: ${detail}`,
1836
2181
  isError: true,
1837
2182
  }
1838
2183
  }
@@ -1874,6 +2219,41 @@ export class DockerByokSession extends ClaudeByokSession {
1874
2219
  })
1875
2220
  }
1876
2221
 
2222
+ /**
2223
+ * SECURITY (#7354) — the operator's view of the containment seam.
2224
+ *
2225
+ * Every other outcome of these three tools is visible to SOMEBODY: a refusal
2226
+ * reaches the model as `isError`, a match reaches it as content. A WITHHELD
2227
+ * match reaches nobody — the tool_result is byte-identical to "matched
2228
+ * nothing", deliberately, because anything else is an existence oracle on a
2229
+ * tool `acceptEdits` auto-approves. That leaves an operator unable to tell a
2230
+ * containment that is holding from one that was never wired up, which is the
2231
+ * false-safety shape itself. This line is the difference.
2232
+ *
2233
+ * Counts only. The names of what was withheld, and the paths they resolved
2234
+ * to, are exactly what containment refused to disclose — putting them in the
2235
+ * daemon log would move the leak rather than close it.
2236
+ */
2237
+ _logContainment(label, detail) {
2238
+ const session = this._sourceSessionId || '-'
2239
+ const container = typeof this._containerId === 'string' ? this._containerId.slice(0, 12) : '-'
2240
+ log.warn(`[container-confine] ${label}: ${detail} (session=${session} container=${container})`)
2241
+ }
2242
+
2243
+ /** #7354 — one line per Glob that withheld something, or whose count was lost. */
2244
+ _logWithheldGlobMatches(inContainer, lexical) {
2245
+ if (inContainer === null) {
2246
+ // Not a containment failure — the withholding already happened in the
2247
+ // container. It IS an observability failure, and saying so beats
2248
+ // reporting a count of zero we did not measure.
2249
+ this._logContainment('Glob', `withheld-count unavailable from the container; ${lexical} withheld by the host lexical layer`)
2250
+ return
2251
+ }
2252
+ const total = inContainer + lexical
2253
+ if (total === 0) return
2254
+ this._logContainment('Glob', `withheld ${total} match(es) resolving outside ${CONTAINER_WORKSPACE} (in-container ${inContainer}, host-lexical ${lexical})`)
2255
+ }
2256
+
1877
2257
  async _containerRead(input) {
1878
2258
  const containerPath = remapToContainerPath(input?.file_path, this.cwd)
1879
2259
  // Use sed for offset/limit slicing inside the container so we
@@ -1892,14 +2272,46 @@ export class DockerByokSession extends ClaudeByokSession {
1892
2272
  // regardless of provider. The `awk` runs INSIDE the container after
1893
2273
  // the `sed | head` slice, so we still apply the line cap and the
1894
2274
  // 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++}'`
2275
+ //
2276
+ // #7354 — `remapToContainerPath` is LEXICAL, so `esc/passwd` (where
2277
+ // `/workspace/esc` is a symlink to `/etc` inside the container) passes it
2278
+ // untouched. The confinement preamble resolves the path physically in the
2279
+ // container and hands the body the RESOLVED path in `"$__cx_target"`.
2280
+ const cmd = buildConfinedContainerCommand({
2281
+ target: containerPath,
2282
+ body: `sed -n '${startLine},${endLine}p' "$__cx_target" | head -c ${READ_MAX_BYTES} | awk -v start=${startLine} 'BEGIN{n=start} {printf "%5d→%s\\n", n, $0; n++}'`,
2283
+ })
1896
2284
  const { stdout, stderr } = await this._execAsContainerUser({ cmd, timeout: 30_000 })
2285
+ const confined = parseConfinedContainerStdout(stdout)
2286
+ if (!confined.ok) {
2287
+ this._logContainment('Read', `refused a path (${confined.reason})`)
2288
+ return {
2289
+ content: confinedContainerFailureMessage('Read', confined.reason, input?.file_path),
2290
+ isError: true,
2291
+ }
2292
+ }
1897
2293
  if (stderr && stderr.trim()) {
1898
2294
  return { content: `Read failed: ${stderr.trim()}`, isError: true }
1899
2295
  }
1900
- return { content: stdout, isError: false }
2296
+ return { content: confined.body, isError: false }
1901
2297
  }
1902
2298
 
2299
+ /**
2300
+ * SECURITY (#7876) — confined INSIDE the container, like Read/Glob/Grep.
2301
+ * `remapToContainerPath` is lexical and cannot see a symlinked directory in
2302
+ * /workspace (the link is on the CONTAINER's filesystem), so the write runs
2303
+ * under `buildConfinedContainerCommand` in `'create'` mode: the
2304
+ * deepest-existing-ancestor walk resolves the longest existing prefix of the
2305
+ * path physically, refuses unless it lands inside the resolved workspace, and
2306
+ * re-appends the not-yet-existing remainder. The body then `mkdir -p`s,
2307
+ * writes and measures ONLY `"$__cx_target"` — every directory it creates is
2308
+ * created under the RESOLVED ancestor, never under the lexical alias, so a
2309
+ * link swapped on the alias after the check cannot redirect the write.
2310
+ *
2311
+ * Known residual: a link swapped INSIDE the already-resolved prefix between
2312
+ * the check and the write — the same check-then-use window the host-side
2313
+ * tools and #7354 accept.
2314
+ */
1903
2315
  async _containerWrite(input) {
1904
2316
  const containerPath = remapToContainerPath(input?.file_path, this.cwd)
1905
2317
  // Fix for PR #5021 review (Copilot, comment id 3348029266): host-side
@@ -1922,23 +2334,53 @@ export class DockerByokSession extends ClaudeByokSession {
1922
2334
  // We base64-encode on the way in to dodge any quoting hazards
1923
2335
  // with newlines / single quotes / backticks in `content`.
1924
2336
  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(' && ')
2337
+ // `${__cx_target%/*}` is the resolved parent. `__cx_target` is always an
2338
+ // absolute path under the resolved workspace (the preamble refused
2339
+ // anything else), so it can neither be empty nor begin with `-`.
2340
+ const cmd = buildConfinedContainerCommand({
2341
+ target: containerPath,
2342
+ mode: 'create',
2343
+ body: [
2344
+ 'mkdir -p "${__cx_target%/*}"',
2345
+ `echo ${shellQuote(encoded)} | base64 -d > "$__cx_target"`,
2346
+ 'wc -c < "$__cx_target"',
2347
+ ].join(' && '),
2348
+ })
1931
2349
  const { stdout, stderr } = await this._execAsContainerUser({ cmd, timeout: 30_000 })
2350
+ const confined = parseConfinedContainerStdout(stdout)
2351
+ if (!confined.ok) {
2352
+ // The message names only the path the caller supplied — never where it
2353
+ // resolved (existence-oracle rule, #7341/#7354).
2354
+ this._logContainment('Write', `refused a path (${confined.reason})`)
2355
+ return {
2356
+ content: confinedContainerFailureMessage('Write', confined.reason, input?.file_path),
2357
+ isError: true,
2358
+ }
2359
+ }
1932
2360
  if (stderr && stderr.trim()) {
1933
2361
  return { content: `Write failed: ${stderr.trim()}`, isError: true }
1934
2362
  }
1935
- const bytesWritten = Number(stdout.trim()) || 0
2363
+ const bytesWritten = Number(confined.body.trim()) || 0
1936
2364
  return {
1937
2365
  content: `Wrote ${bytesWritten} bytes to ${input.file_path}.`,
1938
2366
  isError: false,
1939
2367
  }
1940
2368
  }
1941
2369
 
2370
+ /**
2371
+ * SECURITY (#7876) — the READ half (`cat`) runs under the same in-container
2372
+ * confinement as `_containerWrite`, so a symlinked directory inside
2373
+ * /workspace can neither be read through nor, since a refused read returns
2374
+ * before the write-back, written through.
2375
+ *
2376
+ * `'create'` mode, not the default read mode: both resolve a path whose leaf
2377
+ * exists identically, but `'create'` is the resolver the write-back uses, so
2378
+ * the file Edit reads and the file it writes are resolved by the same walk. A
2379
+ * missing file (at any depth) still resolves to an in-workspace path and
2380
+ * surfaces as `cat`'s own "No such file", not as a containment error — the
2381
+ * Read route's contract. The write-back through `_containerWrite` resolves
2382
+ * again, independently; that second resolution is a second check, not a gap.
2383
+ */
1942
2384
  async _containerEdit(input) {
1943
2385
  const containerPath = remapToContainerPath(input?.file_path, this.cwd)
1944
2386
  const oldString = typeof input?.old_string === 'string' ? input.old_string : ''
@@ -1947,13 +2389,26 @@ export class DockerByokSession extends ClaudeByokSession {
1947
2389
  }
1948
2390
  // Read the file via the same execInEnvironment path so a missing
1949
2391
  // file surfaces as a tool_result rather than an exception.
1950
- const { stdout: existing, stderr: readErr } = await this._execAsContainerUser({
1951
- cmd: `cat ${shellQuote(containerPath)}`,
2392
+ const { stdout: readOut, stderr: readErr } = await this._execAsContainerUser({
2393
+ cmd: buildConfinedContainerCommand({
2394
+ target: containerPath,
2395
+ mode: 'create',
2396
+ body: 'cat "$__cx_target"',
2397
+ }),
1952
2398
  timeout: 30_000,
1953
2399
  })
2400
+ const confined = parseConfinedContainerStdout(readOut)
2401
+ if (!confined.ok) {
2402
+ this._logContainment('Edit', `refused a path (${confined.reason})`)
2403
+ return {
2404
+ content: confinedContainerFailureMessage('Edit', confined.reason, input?.file_path),
2405
+ isError: true,
2406
+ }
2407
+ }
1954
2408
  if (readErr && readErr.trim()) {
1955
2409
  return { content: `Edit failed: ${readErr.trim()}`, isError: true }
1956
2410
  }
2411
+ const existing = confined.body
1957
2412
  // Strict-unique-match + NO_CHANGE guard + LITERAL replacement via the shared
1958
2413
  // transform (same one the host file-ops Edit uses) — #5882 closes the drift
1959
2414
  // where this path lacked the NO_CHANGE guard and used slice vs the host's
@@ -2018,18 +2473,108 @@ export class DockerByokSession extends ClaudeByokSession {
2018
2473
  isError: true,
2019
2474
  }
2020
2475
  }
2476
+ // #7341 — same containment rule as the host Glob, from the same shared
2477
+ // validator, so the two cannot drift. Here it is the ONLY layer: the host
2478
+ // additionally realpath-confines the expanded matches, which is impossible
2479
+ // from out here because the matches are produced inside the container.
2480
+ // What it escapes into is the container filesystem (the image's /etc, the
2481
+ // container user's ~), not the host's — lower severity than the host hole,
2482
+ // same defect.
2483
+ const escapeReason = globPatternEscapeReason(pattern)
2484
+ if (escapeReason) {
2485
+ return { content: globPatternEscapeMessage(escapeReason), isError: true }
2486
+ }
2487
+ // #7898 round 4 — same cap as the host (byok-tool-executor.js's runGlob),
2488
+ // from the same shared check: an over-long or deeply brace-nested pattern
2489
+ // costs nothing beyond this scan on the host, but on the container it
2490
+ // would still be shipped into `buildConfinedGlobBody` and shelled out via
2491
+ // `docker exec` for bash's own brace expansion to chew on. Rejecting it
2492
+ // here, before that round-trip, keeps host and container refusing the
2493
+ // same input for the same reason rather than only one of them.
2494
+ const complexityReason = globPatternComplexityReason(pattern)
2495
+ if (complexityReason) {
2496
+ return { content: globPatternComplexityMessage(complexityReason), isError: true }
2497
+ }
2021
2498
  if (signal?.aborted) {
2022
2499
  return { content: 'Interrupted before docker exec', isError: true }
2023
2500
  }
2024
2501
  const root = input?.path
2025
2502
  ? remapToContainerPath(input.path, this.cwd)
2026
2503
  : CONTAINER_WORKSPACE
2027
- const cmd = buildGlobCommand(pattern, root)
2504
+ // #7354 — TWO layers now, and the lexical one below is still the first.
2505
+ // The preamble resolves `root` physically inside the container and refuses
2506
+ // when it lands outside /workspace (the `path` route), and the body resolves
2507
+ // each MATCH before emitting it (the `pattern` route). Both are things only
2508
+ // the container can answer: the symlink lives on ITS filesystem.
2509
+ const cmd = buildConfinedContainerCommand({
2510
+ target: root,
2511
+ // `cd -P` into the resolved root, so `$PWD` and `$__cx_target` are the
2512
+ // same physical directory and the per-match comparison in the body is
2513
+ // against the place the glob actually ran in.
2514
+ setup: '{ unset CDPATH; cd -P -- "$__cx_target"; }',
2515
+ body: buildConfinedGlobBody(pattern),
2516
+ })
2028
2517
  const { stdout, stderr } = await this._execAsContainerUser({ cmd, timeout: 30_000 })
2029
- if (!stdout && stderr && stderr.trim()) {
2518
+ const confined = parseConfinedContainerStdout(stdout)
2519
+ if (!confined.ok) {
2520
+ // An escaping `path` ARGUMENT is an explicit refusal — the caller named
2521
+ // that directory outright, so the error tells them nothing they did not
2522
+ // already supply. Matches that escape are a different thing entirely and
2523
+ // are dropped silently in the container (see buildConfinedGlobBody).
2524
+ this._logContainment('Glob', `refused a path (${confined.reason})`)
2525
+ return {
2526
+ content: confinedContainerFailureMessage('Glob', confined.reason, input?.path),
2527
+ isError: true,
2528
+ }
2529
+ }
2530
+ // #7354 — the withheld-count trailer is stripped BEFORE anything else looks
2531
+ // at the body: it must never reach the model (no-oracle), and it must never
2532
+ // make the "no stdout, but stderr" branch below unreachable by keeping the
2533
+ // body permanently non-empty.
2534
+ const { body: globBody, withheld: withheldInContainer } = splitWithheldTrailer(confined.body)
2535
+ if (!globBody && stderr && stderr.trim()) {
2030
2536
  return { content: `Glob failed: ${stderr.trim()}`, isError: true }
2031
2537
  }
2032
- const files = stdout.split('\n').filter(Boolean)
2538
+ // #7341 — confine the RESULTS, not just the pattern. This is the layer
2539
+ // that actually holds: it inspects what the shell PRODUCED (a leading `/`
2540
+ // or a `..` segment) rather than trying to predict what it will produce,
2541
+ // and every one of the six expansion bypasses found in review is plainly
2542
+ // visible here while being invisible in the pattern text.
2543
+ //
2544
+ // #7354 KEPT IT, and deliberately: the in-container resolution above is
2545
+ // strictly stronger, but it is also the layer that can be defeated by an
2546
+ // image whose `readlink` is missing or whose shell misbehaves, and this one
2547
+ // needs neither. Deleting it would trade a check that cannot fail for one
2548
+ // that depends on the guest's userland. The two are independent — one reads
2549
+ // the string, the other reads the filesystem — so they are not the
2550
+ // "shared rule = free pass" pairing.
2551
+ //
2552
+ // Withheld matches read as no match TO THE MODEL — no count, no marker.
2553
+ // Anything that distinguishes "matched, but outside" from "matched nothing"
2554
+ // is an existence oracle on a tool auto-approved in `acceptEdits`. The
2555
+ // operator gets the count instead, in the daemon log (#7354).
2556
+ //
2557
+ // #7357 — split on NUL, matching `buildConfinedGlobBody`'s delimiter: a
2558
+ // filename may legally contain a newline, and a `\n`-split here would
2559
+ // turn one such match into two entries, one of them a nonexistent path.
2560
+ // `filter(Boolean)` drops the single empty tail element the trailing NUL
2561
+ // produces (and would drop nothing else — an empty match can't exist).
2562
+ const emitted = globBody.split('\0').filter(Boolean)
2563
+ const containmentOk = emitted.filter((f) => !globMatchEscapesRoot(f))
2564
+ // A match that survived containment but still contains a newline is
2565
+ // dropped from what reaches the model — the tool_result itself is
2566
+ // `\n`-joined text, so there is no way to keep it in the OUTPUT without
2567
+ // reintroducing the exact split this fix removes from the TRANSFER. This
2568
+ // is a display-format decision, not a containment one (the host Glob
2569
+ // drops the same shape, for the same reason — byok-tool-executor.js's
2570
+ // `runGlob`), so it gets its own log line rather than being folded into
2571
+ // the security-relevant withheld count below.
2572
+ const files = containmentOk.filter((f) => !f.includes('\n'))
2573
+ const droppedForNewline = containmentOk.length - files.length
2574
+ this._logWithheldGlobMatches(withheldInContainer, emitted.length - containmentOk.length)
2575
+ if (droppedForNewline > 0) {
2576
+ this._logContainment('Glob', `dropped ${droppedForNewline} match(es) containing an embedded newline (unambiguous single-line output only, #7357)`)
2577
+ }
2033
2578
  if (files.length === 0) return { content: `No matches for ${pattern}`, isError: false }
2034
2579
  return { content: files.join('\n'), isError: false }
2035
2580
  }
@@ -2050,14 +2595,35 @@ export class DockerByokSession extends ClaudeByokSession {
2050
2595
  // non-zero exit, and both rg and grep -r exit 1 on "no matches" (PR #5021
2051
2596
  // review, Copilot comment 3348029186) — without the mask the legitimate
2052
2597
  // "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 })
2598
+ const { ci, ln, globArg, grepGlob } = buildGrepArgs(input)
2599
+ // #7354 — the `path` route is shared with Read/Glob and is lexical, so
2600
+ // `{"path":"esc"}` searched `/etc` through a symlinked directory. Resolve
2601
+ // it in-container and search the RESOLVED root (`rootExpr`), which is what
2602
+ // the host already does — it passes `safeResolveRoot`'s realpath, never the
2603
+ // alias it was handed.
2604
+ const cmd = buildConfinedContainerCommand({
2605
+ target: root,
2606
+ body: buildGrepCommand({
2607
+ pattern, rootExpr: '"$__cx_target"', ci, ln, globArg, grepGlob, maskExit: true,
2608
+ }),
2609
+ })
2055
2610
  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 }
2611
+ const confined = parseConfinedContainerStdout(stdout)
2612
+ if (!confined.ok) {
2613
+ this._logContainment('Grep', `refused a path (${confined.reason})`)
2614
+ return {
2615
+ content: confinedContainerFailureMessage('Grep', confined.reason, input?.path),
2616
+ isError: true,
2617
+ }
2058
2618
  }
2059
- if (!stdout) return { content: `No matches for ${pattern}`, isError: false }
2060
- return { content: stdout, isError: false }
2619
+ // Informational notes (a skipped unreadable directory) are not failures;
2620
+ // refusals and real grep errors are, and carry no note prefix (#7981).
2621
+ const grepErrors = splitGrepNotes(stderr).errors
2622
+ if (!confined.body && grepErrors) {
2623
+ return { content: `Grep failed: ${grepErrors}`, isError: true }
2624
+ }
2625
+ if (!confined.body) return { content: `No matches for ${pattern}`, isError: false }
2626
+ return { content: confined.body, isError: false }
2061
2627
  }
2062
2628
 
2063
2629
  /**
@@ -2082,17 +2648,20 @@ export class DockerByokSession extends ClaudeByokSession {
2082
2648
  // nulling state so the finally-block has them.
2083
2649
  const composeFile = this._composeFile
2084
2650
  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).
2651
+ // #5079/#7373: remove the ANTHROPIC_API_KEY tmpfile's owning dir
2652
+ // created at compose-up time. Snapshot the path BEFORE nulling so the
2653
+ // finally-block has it; remove AFTER `compose down` runs (the tmpfile
2654
+ // is referenced by the down call indirectly via the project metadata,
2655
+ // and we want a clean teardown order — compose first, then secret
2656
+ // material).
2090
2657
  const composeEnvFile = this._composeEnvFile
2658
+ const composeEnvDir = this._composeEnvDir
2091
2659
  const cwd = this.cwd || process.cwd()
2092
2660
  this._containerId = null
2093
2661
  this._containerReady = false
2094
2662
  this._acquiredFromPool = false
2095
2663
  this._composeEnvFile = null
2664
+ this._composeEnvDir = null
2096
2665
  try {
2097
2666
  await super.destroy()
2098
2667
  } finally {
@@ -2117,9 +2686,14 @@ export class DockerByokSession extends ClaudeByokSession {
2117
2686
  } catch (err) {
2118
2687
  log.warn(`compose destroy failed: ${err.message}`)
2119
2688
  }
2120
- // Unlink the env-file last — best-effort, silent on missing.
2121
- if (composeEnvFile) {
2122
- this._unlinkEnvFile(composeEnvFile)
2689
+ // Remove the env-file's owning dir last — best-effort, silent on
2690
+ // missing. `composeEnvFile` alone (no dir) is a defensive fallback
2691
+ // for a state that should not arise, so the credential is never
2692
+ // left behind even if `_composeEnvDir` was somehow lost.
2693
+ if (composeEnvDir) {
2694
+ this._removeEnvDir(composeEnvDir)
2695
+ } else if (composeEnvFile) {
2696
+ this._removeEnvDir(composeEnvFile)
2123
2697
  }
2124
2698
  } else if (!containerId || !owned) {
2125
2699
  // Nothing for us to clean up — externally-managed container
@@ -2132,13 +2706,39 @@ export class DockerByokSession extends ClaudeByokSession {
2132
2706
  await pool.release(this._poolKeyFor(containerId), containerId)
2133
2707
  } catch (err) {
2134
2708
  log.warn(`pool release of ${containerId.slice(0, 12)} failed: ${err.message} — falling back to docker rm -f`)
2135
- await this._rmContainer(containerId)
2709
+ await this._discardContainer(containerId, pool)
2136
2710
  }
2137
2711
  } else {
2138
2712
  log.info(`removing container ${containerId.slice(0, 12)}${acquiredFromPool ? ' (was pooled)' : ''}`)
2139
- await this._rmContainer(containerId)
2713
+ await this._discardContainer(containerId, pool)
2714
+ }
2715
+ }
2716
+ }
2717
+
2718
+ /**
2719
+ * Remove a container this session owns and will NOT release to the pool
2720
+ * (a vanish flips `_containerReady` off, so destroy() lands here instead
2721
+ * of `pool.release()`; so does a session that never went ready).
2722
+ *
2723
+ * #7610: when a pool is attached, go through `pool.forget()` — it runs the
2724
+ * same `docker rm -f` AND drops the id from `_soiledIds` / `_createdAt`,
2725
+ * which `notifyContainerVanished()` / `acquire()` left behind. A bare
2726
+ * `_rmContainer` here leaked one Set entry plus one Map entry per vanished
2727
+ * container for the life of the daemon. `forget()` already ran the removal,
2728
+ * so do not also call `_rmContainer` (a second `docker rm -f`). An id the
2729
+ * pool never tracked (a fresh, never-pooled container) is a no-op delete.
2730
+ * With no pool there is no bookkeeping, so the plain removal stands.
2731
+ */
2732
+ async _discardContainer(containerId, pool) {
2733
+ if (pool && typeof pool.forget === 'function') {
2734
+ try {
2735
+ await pool.forget(containerId)
2736
+ return
2737
+ } catch (err) {
2738
+ log.warn(`pool forget of ${containerId.slice(0, 12)} failed: ${err.message} — falling back to docker rm -f`)
2140
2739
  }
2141
2740
  }
2741
+ await this._rmContainer(containerId)
2142
2742
  }
2143
2743
 
2144
2744
  /**