@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
@@ -27,7 +27,20 @@
27
27
  * Bash on the machine can already call `docker pull` directly. This
28
28
  * check prevents the WS handler itself from being used as a
29
29
  * privileged pull primitive.
30
+ *
31
+ * 3. Option-shape refusal (#7296) — the allowlist above constrains the
32
+ * PREFIX of an image reference, never its POSITION in an argv. A
33
+ * pattern's `startsWith` test therefore said nothing about whether
34
+ * the value would be read by `docker run` as an image or as a FLAG,
35
+ * and an exact pattern laundered one outright. The shipped default
36
+ * list was safe only by accident of its prefixes, so the refusal is
37
+ * now explicit: an image reference can never legitimately begin with
38
+ * `-` (nor contain NUL/CR/LF), and `isSafeArgvValue` is the one
39
+ * predicate that decides it. `DockerBackend._startContainer` carries
40
+ * the belt to this braces — a `--` separator immediately before the
41
+ * image positional.
30
42
  */
43
+ import { isSafeArgvValue } from './utils/argv-safety.js'
31
44
 
32
45
  export const DEFAULT_ALLOWED_DOCKER_IMAGES = [
33
46
  // Node.js base images
@@ -51,12 +64,16 @@ export const DEFAULT_ALLOWED_DOCKER_IMAGES = [
51
64
  * Check whether a given image string matches any pattern in the
52
65
  * allowlist. Patterns support a single trailing `*` for wildcarding.
53
66
  *
67
+ * An option-shaped reference is refused BEFORE the patterns are
68
+ * consulted, so no pattern — not a catch-all `*`, not an exact entry —
69
+ * can admit one (#7296).
70
+ *
54
71
  * @param {string} image - The image reference to check (e.g. `node:22`)
55
72
  * @param {string[]} patterns - Allowlist patterns (exact or prefix-with-*)
56
73
  * @returns {boolean}
57
74
  */
58
75
  export function imageMatchesAllowlist(image, patterns) {
59
- if (typeof image !== 'string' || image.length === 0) return false
76
+ if (!isSafeArgvValue(image)) return false
60
77
  if (!Array.isArray(patterns) || patterns.length === 0) return false
61
78
  for (const pattern of patterns) {
62
79
  if (typeof pattern !== 'string' || pattern.length === 0) continue
@@ -85,6 +102,11 @@ export function validateDockerImage(image, config = null) {
85
102
  // No image specified — caller gets the environment manager's
86
103
  // built-in default, which is always safe.
87
104
  if (!image) return null
105
+ // #7296 — answered before the allowlist so the denial reason is the real
106
+ // one (position, not membership) whatever the operator's patterns say.
107
+ if (!isSafeArgvValue(image)) {
108
+ return `Docker image ${JSON.stringify(String(image).slice(0, 64))} is not a valid image reference.`
109
+ }
88
110
  const configured = Array.isArray(config?.allowedDockerImages)
89
111
  ? config.allowedDockerImages
90
112
  : null
@@ -1,7 +1,7 @@
1
1
  import { execFile } from 'child_process'
2
2
  import { SdkSession } from './sdk-session.js'
3
3
  import { createLogger } from './logger.js'
4
- import { classifyDockerError } from './docker-session.js'
4
+ import { classifyDockerError, CONTAINER_VANISHED, CONTAINER_VANISHED_MESSAGE, probeContainerGone, surfaceContainerVanished } from './docker-session.js'
5
5
  import { DockerBackend, FORWARDED_ENV_KEYS, DEFAULT_CONTAINER_CLI_PATH } from './environments/backends/docker.js'
6
6
  import { BILLING_CLASSES } from './billing-class.js'
7
7
  import { VALID_USERNAME_RE } from './utils/validation-patterns.js'
@@ -62,8 +62,25 @@ export class DockerSdkSession extends SdkSession {
62
62
  */
63
63
  static get preflight() {
64
64
  const parent = SdkSession.preflight
65
+ // #7986 review S4 / #8031: `minVersion`, `recommendedVersion`,
66
+ // `requiresDirectExec` and `updateHint` are all about the HOST `claude`
67
+ // binary that SdkSession's version/shim gates enforce — docker-sdk never
68
+ // spawns that binary at all; the container runs its own installed
69
+ // `claude` (see #8027). runProviderPreflight itself skips containerised
70
+ // providers entirely, but `doctor.js`'s `checkProvider` does not, so
71
+ // inheriting these via a wholesale `...parent.binary` spread would make
72
+ // `chroxy doctor` / `chroxy start` fail a docker-sdk install over an old,
73
+ // shimmed, or SDK-lagging HOST claude that this provider never touches.
74
+ const {
75
+ minVersion: _minVersion,
76
+ recommendedVersion: _recommendedVersion,
77
+ requiresDirectExec: _requiresDirectExec,
78
+ updateHint: _updateHint,
79
+ ...binary
80
+ } = parent.binary
65
81
  return {
66
82
  ...parent,
83
+ binary,
67
84
  credentials: {
68
85
  envVars: ['ANTHROPIC_API_KEY'],
69
86
  hint: 'set ANTHROPIC_API_KEY on the host so it is forwarded into the container (no OAuth fallback inside the container — the container has no ~/.claude state)',
@@ -129,6 +146,8 @@ export class DockerSdkSession extends SdkSession {
129
146
  }
130
147
  this._containerUser = user
131
148
  this._containerCliPath = containerCliPath
149
+ // #7601 — the CONTAINER_VANISHED idempotency latch (see surfaceContainerVanished).
150
+ this._containerVanishedNotified = false
132
151
  // #3468 + #3501: `_stdinForwardingDisabled` is initialised by the
133
152
  // SdkSession parent constructor from the `stdinForwardingDisabled` opt
134
153
  // (see #3540 + #3576 — restored sessions hydrate the latched flag via
@@ -331,7 +350,7 @@ export class DockerSdkSession extends SdkSession {
331
350
  log.warn('No container ID — spawnClaudeCodeProcess will not be injected')
332
351
  return
333
352
  }
334
- options.spawnClaudeCodeProcess = this._createSpawnCallback()
353
+ options.spawnClaudeCodeProcess = this._createSpawnCallback(options.pathToClaudeCodeExecutable)
335
354
  }
336
355
 
337
356
  /**
@@ -349,7 +368,7 @@ export class DockerSdkSession extends SdkSession {
349
368
  * disabled mid-turn. The proc emits a one-shot `'stdin_disabled'` signal at
350
369
  * that point — subscribe so the loss is observable instead of silent.
351
370
  */
352
- _createSpawnCallback() {
371
+ _createSpawnCallback(hostClaudePath) {
353
372
  const backend = this._backend || (this._backend = new DockerBackend())
354
373
  const containerId = this._containerId
355
374
  const containerCliPath = this._containerCliPath || DEFAULT_CONTAINER_CLI_PATH
@@ -367,6 +386,7 @@ export class DockerSdkSession extends SdkSession {
367
386
  containerUser,
368
387
  containerCliPath,
369
388
  hostCwd,
389
+ hostClaudePath,
370
390
  })
371
391
  // Attach default warn-log listeners for SidecarProcess stdin failure
372
392
  // signals (#3402, #3468, #3474). Docker procs are plain ChildProcess
@@ -381,6 +401,155 @@ export class DockerSdkSession extends SdkSession {
381
401
  }
382
402
  }
383
403
 
404
+ /**
405
+ * #7599 — classify a turn failure as a vanished container (overrides the
406
+ * SdkSession no-op).
407
+ *
408
+ * A containerized turn runs `docker exec` into the session's container; when
409
+ * the container has been stopped / restarted / removed underneath the live
410
+ * session (including a plain `docker stop` performed OUTSIDE chroxy), that exec
411
+ * fails and the SDK's query() rejects. The rejection message does NOT carry the
412
+ * docker stderr, so we probe the container directly and treat only a confirmed
413
+ * container-gone as a vanish — an API/model error with a healthy container
414
+ * falls through to the generic surface.
415
+ *
416
+ * Never nulls `_containerId` (the #7561 fresh-container trap): the session
417
+ * stays bound so a returning env container can be reconnected (#7602). On the
418
+ * next turn a still-gone container re-detects and re-surfaces once more; it is
419
+ * never resurrected onto the host or a fresh default container.
420
+ *
421
+ * @param {Error} _err
422
+ * @returns {Promise<{code:string,message:string,recoverable:boolean}|null>}
423
+ */
424
+ async _classifyContainerFailure(_err) {
425
+ if (!this._containerId) return null
426
+ const gone = await this._probeContainerGone()
427
+ if (!gone) return null
428
+ // #7601: latch so a proactive liveness-poll tick doesn't ALSO surface this
429
+ // same vanish. The SDK reactive path still RETURNS the payload for
430
+ // SdkSession to emit (its deliberate per-turn re-surface is unchanged — the
431
+ // latch gates only the poll, not this return), so a still-gone container
432
+ // re-surfaces on the next turn exactly as in #7599.
433
+ this._containerVanishedNotified = true
434
+ // Only `code` (+ `message`) survives the generic error normalizer to the
435
+ // wire; the code is the surfaced signal (reconnectability is a #7602
436
+ // server-side decision, not a wire flag).
437
+ return {
438
+ code: CONTAINER_VANISHED,
439
+ message: CONTAINER_VANISHED_MESSAGE,
440
+ }
441
+ }
442
+
443
+ /**
444
+ * #7601 — surface a CONTAINER_VANISHED error once for this session (idempotent).
445
+ * Called by the proactive liveness poll / environment_stopped fast-path; the
446
+ * shared latch keeps it from double-emitting with the reactive turn-reject path.
447
+ * @returns {boolean} true if it emitted
448
+ */
449
+ notifyContainerVanished() {
450
+ return surfaceContainerVanished(this)
451
+ }
452
+
453
+ /**
454
+ * #7601 — reset the CONTAINER_VANISHED latch after the container is observed
455
+ * running again, so a later vanish re-surfaces. Called by the liveness poll on
456
+ * a healthy inspect.
457
+ *
458
+ * #7602 — returns whether this call actually FLIPPED the latch (the gone→
459
+ * running recovery edge), symmetric with `notifyContainerVanished`'s "true if
460
+ * it emitted". That edge, and only that edge, drives the live re-attach in
461
+ * `SessionManager._reattachEnvironmentBoundSession`.
462
+ *
463
+ * @returns {boolean} true when the latch transitioned
464
+ */
465
+ clearContainerVanished() {
466
+ if (!this._containerVanishedNotified) return false
467
+ this._containerVanishedNotified = false
468
+ return true
469
+ }
470
+
471
+ /**
472
+ * #7602 — the live re-attach contract: re-affirm this session's binding to an
473
+ * environment container that has come back, so the next turn's `docker exec`
474
+ * resumes inside it.
475
+ *
476
+ * Why the SDK provider is the one that has this: an `environmentId` create is
477
+ * forced to `provider: 'docker-sdk'` (`handlers/session-handlers.js`), env
478
+ * containers are launched NAMED and WITHOUT `--rm`, so they survive a stop and
479
+ * keep their id — the only reconnect target there is. `DockerSession`'s and a
480
+ * self-owned `DockerSdkSession`'s containers are `--rm` and are REMOVED when
481
+ * they stop; those stay terminal / fail-visible-only, which is why
482
+ * `_containerOwned` is refused below and why `DockerSession` exposes no
483
+ * `reattachContainer` at all (the SessionManager feature-detects this method
484
+ * exactly the way #7601 feature-detects `notifyContainerVanished`).
485
+ *
486
+ * There is no in-container process to respawn — a containerized turn spawns a
487
+ * fresh `docker exec` per query via `_createSpawnCallback`, which reads
488
+ * `_containerId` / `_containerCliPath` / `_containerUser` at spawn time. So a
489
+ * re-attach is exactly: confirm the binding still points at the container the
490
+ * environment owns, and refresh the exec parameters. The caller has already
491
+ * checked the id against the live `EnvironmentManager`; the equality check
492
+ * here is defence in depth, and it is what makes "never a new container" (the
493
+ * #7561 trap) true at BOTH layers.
494
+ *
495
+ * `_containerId` is never nulled and never widened to a different container:
496
+ * a stop/start preserves the container's writable layer, so the in-container
497
+ * `claude` install, the non-root user and the SDK transcript under its HOME
498
+ * are all still there and the resumed turn is genuinely the same conversation.
499
+ * A DIFFERENT id would be a REBUILT container with none of that — resuming
500
+ * into it would silently produce a blank session, which is the one outcome
501
+ * #7602 must not accept. Hence: refuse, and stay fail-visible.
502
+ *
503
+ * @param {{containerId?: string, containerUser?: string, containerCliPath?: string}} binding
504
+ * @returns {boolean} true when the binding was re-affirmed
505
+ */
506
+ reattachContainer(binding = {}) {
507
+ if (this._destroying) return false
508
+ // A self-owned `--rm` container is terminal — it cannot come back, and
509
+ // re-binding one would be the #7561 fresh-container trap by another route.
510
+ if (this._containerOwned) return false
511
+ // The `typeof` test is load-bearing, not defensive dressing: it is what
512
+ // keeps a non-string `containerId` from throwing on `.trim()`.
513
+ const containerId = typeof binding.containerId === 'string' ? binding.containerId.trim() : ''
514
+ // ONE clause, deliberately. The binding must name EXACTLY the container this
515
+ // session is already in; a missing, blank or non-string id normalises to ''
516
+ // and can never equal a real container id, and `_containerId` is never ''
517
+ // (the constructor maps a blank to null, and a null id means
518
+ // `_containerOwned`, already refused above). An extra "is it empty" test
519
+ // would be a guard nothing could ever make fail — see
520
+ // docs/false-safety-guards.md.
521
+ if (containerId !== this._containerId) return false
522
+
523
+ const cliPath = typeof binding.containerCliPath === 'string' ? binding.containerCliPath.trim() : ''
524
+ if (cliPath) this._containerCliPath = cliPath
525
+ const user = typeof binding.containerUser === 'string' ? binding.containerUser.trim() : ''
526
+ // Same validation the constructor applies — a re-attach must not be a way to
527
+ // smuggle an unvalidated username into the `docker exec --user` argv. The
528
+ // constructor THROWS here; a re-attach cannot (it would strand a session over
529
+ // a field it does not need), so it keeps the existing user — but says so,
530
+ // rather than dropping the update silently.
531
+ if (user && !VALID_USERNAME_RE.test(user)) {
532
+ log.warn(`Ignoring invalid containerUser "${user}" on re-attach — keeping "${this._containerUser}"`)
533
+ } else if (user) {
534
+ this._containerUser = user
535
+ }
536
+
537
+ log.info(`Re-attached to container ${this._containerId.slice(0, 12)} — next turn resumes inside it`)
538
+ return true
539
+ }
540
+
541
+ /**
542
+ * Probe whether the bound container is gone via `docker exec <id> true`.
543
+ * Delegates to the shared `probeContainerGone` helper (same probe the
544
+ * docker-cli path uses). Resolves true ONLY on a container-gone classification;
545
+ * a healthy probe, a dead daemon, or any other failure resolves false.
546
+ *
547
+ * @returns {Promise<boolean>}
548
+ */
549
+ _probeContainerGone() {
550
+ return probeContainerGone(this._containerId)
551
+ }
552
+
384
553
  /**
385
554
  * Destroy the session: interrupt active query, optionally remove the container,
386
555
  * and clean up SdkSession state.
@@ -4,9 +4,102 @@ import { CliSession } from './cli-session.js'
4
4
  import { createLogger } from './logger.js'
5
5
  import { BILLING_CLASSES } from './billing-class.js'
6
6
  import { getChroxyHostEnv } from './chroxy-host-metadata.js'
7
+ import { containerUnsetEnvPrefix } from './environments/backends/container-claude-spawn.js'
7
8
 
8
9
  const log = createLogger('docker-session')
9
10
 
11
+ /**
12
+ * #7599 — the error `code` a containerized session emits when it detects that
13
+ * its container has vanished underneath a live turn (stopped / restarted /
14
+ * killed, including a plain `docker stop` performed OUTSIDE chroxy). Distinct
15
+ * from a code crash (`cli_respawn_exhausted`) and from a dead daemon: the
16
+ * container is gone but the daemon and the session live on, so the session is
17
+ * kept (not dropped) for the reconnect that acts on it (#7602). Rides the
18
+ * existing error rails — it is emitted as an `error` event and the generic
19
+ * normalizer (event-normalizer.js) forwards its `code` to clients unchanged (the
20
+ * same path `cli_respawn_exhausted` / `stream_stall` / `resume_unknown` use), so
21
+ * no wire change is needed.
22
+ */
23
+ export const CONTAINER_VANISHED = 'CONTAINER_VANISHED'
24
+
25
+ /**
26
+ * #7599/#7601 — the single message surfaced with a CONTAINER_VANISHED error, on
27
+ * every path that detects a vanish (reactive exec-close, reactive turn-reject,
28
+ * the proactive liveness poll, and the environment_stopped/restarted fast-path).
29
+ * One const so those four sites cannot drift on the wording (the
30
+ * adjacent-field-wire-cap lesson).
31
+ */
32
+ export const CONTAINER_VANISHED_MESSAGE =
33
+ 'The container for this session is no longer running (it may have been stopped, restarted, or removed).'
34
+
35
+ /**
36
+ * #7601 — surface CONTAINER_VANISHED on a containerized session AT MOST ONCE per
37
+ * vanish. Idempotent via the session's `_containerVanishedNotified` latch so the
38
+ * proactive liveness poll (which re-checks the same container every interval)
39
+ * and the reactive close path cannot double-emit for one vanish. The latch is
40
+ * reset ONLY by `clearContainerVanished`, which the liveness poll calls when it
41
+ * observes the container running again — so a stop → start → stop cycle
42
+ * re-surfaces on the second stop. That reset is therefore poll-owned: the sole
43
+ * production entrypoint (server-cli) always wires the poll, but a hypothetical
44
+ * embedding that constructs a SessionManager WITHOUT a `containerInspect` seam
45
+ * would latch the docker-cli reactive close after the first stop and not clear
46
+ * it (the docker-sdk turn path is unaffected — it re-emits per turn regardless).
47
+ *
48
+ * Suppressed (returns false, emits nothing) when the session is tearing down
49
+ * (emitting on a destroy()'d EventEmitter throws — #7599 review), when it has
50
+ * already been notified, or when no container is bound. NEVER nulls
51
+ * `_containerId` (the #7561 trap: an absent id reads as owned → a fresh default
52
+ * container). Returns true only when it actually emitted.
53
+ *
54
+ * @param {import('events').EventEmitter & {_destroying?:boolean, _containerVanishedNotified?:boolean, _containerId?:string|null}} session
55
+ * @returns {boolean}
56
+ */
57
+ export function surfaceContainerVanished(session) {
58
+ if (session._destroying || session._containerVanishedNotified || !session._containerId) return false
59
+ session._containerVanishedNotified = true
60
+ session.emit('error', { code: CONTAINER_VANISHED, message: CONTAINER_VANISHED_MESSAGE })
61
+ return true
62
+ }
63
+
64
+ /**
65
+ * #7601 — the liveness verdict the proactive poll acts on, derived from a
66
+ * `docker inspect` of a single container (backend.getEnvironmentStatus →
67
+ * _inspectContainer). Returns one of:
68
+ * 'running' — inspect reports `State.Running: true`
69
+ * 'gone' — the container is STOPPED (`Running: false`) OR REMOVED (inspect
70
+ * rejects with a container-missing error)
71
+ * 'unknown' — any OTHER failure (Docker daemon down, timeout, permission)
72
+ *
73
+ * The 'unknown' bucket is load-bearing: a naive "inspect rejected → gone" would
74
+ * turn a transient Docker-daemon outage into a CONTAINER_VANISHED surfaced on
75
+ * EVERY containerized session at once. So a rejection is classified with the
76
+ * SAME `classifyDockerError` the reactive probe uses — only a positively
77
+ * recognised container-missing error is 'gone'; `docker_not_running` and
78
+ * anything unrecognised are 'unknown' and the poll leaves the session untouched
79
+ * (the #7599 daemon-down guard, applied to the poll).
80
+ *
81
+ * `docker inspect` reports a removed container as `no such object` (verified
82
+ * against the CLI) — distinct from `docker exec`'s `No such container` that
83
+ * `classifyDockerError` already matches — so that phrasing is recognised here
84
+ * explicitly.
85
+ *
86
+ * @param {(containerId: string) => Promise<boolean>} getStatus backend.getEnvironmentStatus
87
+ * @param {string} containerId
88
+ * @returns {Promise<'running'|'gone'|'unknown'>}
89
+ */
90
+ export async function inspectContainerLiveness(getStatus, containerId) {
91
+ try {
92
+ const running = await getStatus(containerId)
93
+ return running ? 'running' : 'gone'
94
+ } catch (err) {
95
+ const { code } = classifyDockerError(err, err?.stderr || '')
96
+ if (code === 'container_gone') return 'gone'
97
+ const combined = `${err?.message || ''} ${err?.stderr || ''}`.toLowerCase()
98
+ if (combined.includes('no such object') || combined.includes('no such container')) return 'gone'
99
+ return 'unknown'
100
+ }
101
+ }
102
+
10
103
  /**
11
104
  * Classify a Docker error into a structured error with a specific code.
12
105
  *
@@ -43,6 +136,18 @@ export function classifyDockerError(err, stderrText = '') {
43
136
  : 'Docker image not found. Run: docker pull <image>'
44
137
  return { code: 'docker_image_not_found', message }
45
138
  }
139
+ // #7599: the container is gone — stopped, restarted, or removed. Docker reports
140
+ // `Container <id> is not running` for a stopped one and `No such container` for
141
+ // a removed one. `is not running` REQUIRES `container` alongside it so a generic
142
+ // "<daemon/service> is not running" can't false-match a vanished container
143
+ // (#7604 Copilot review). Checked AFTER the daemon + image buckets (whose
144
+ // patterns don't overlap these) and BEFORE the generic fallback.
145
+ if (
146
+ combined.includes('no such container') ||
147
+ (combined.includes('is not running') && combined.includes('container'))
148
+ ) {
149
+ return { code: 'container_gone', message: 'The container for this session is no longer running (it may have been stopped, restarted, or removed).' }
150
+ }
46
151
  if (
47
152
  combined.includes('permission denied') ||
48
153
  combined.includes('access denied')
@@ -52,6 +157,34 @@ export function classifyDockerError(err, stderrText = '') {
52
157
  return { code: 'docker_error', message: err.message }
53
158
  }
54
159
 
160
+ /**
161
+ * #7599 — actively probe whether a container is gone by running
162
+ * `docker exec <id> true` and classifying the PROBE's own stderr (pure
163
+ * docker-client output — never the session's application stderr). Resolves
164
+ * `true` only on a `container_gone` classification; a healthy probe, a dead
165
+ * daemon, or any other error resolves `false` (not a per-container vanish).
166
+ *
167
+ * This is the reliable container-liveness signal both exec-based session paths
168
+ * use — the docker-sdk path because the SDK's query rejection does not carry the
169
+ * docker stderr, and the docker-cli path because the exec child's merged stderr
170
+ * mixes docker-client errors with the app's own output (so trusting it produced
171
+ * both false positives and false negatives — #7599 review).
172
+ *
173
+ * @param {string} containerId
174
+ * @param {Function} [exec] injectable execFile-shaped fn (for tests)
175
+ * @returns {Promise<boolean>}
176
+ */
177
+ export function probeContainerGone(containerId, exec = execFile) {
178
+ return new Promise((resolve) => {
179
+ if (!containerId) return resolve(false)
180
+ exec('docker', ['exec', containerId, 'true'], { encoding: 'utf-8', timeout: 10_000 }, (err, _stdout, stderr) => {
181
+ if (!err) return resolve(false)
182
+ const { code } = classifyDockerError(err, stderr || err.stderr || '')
183
+ resolve(code === 'container_gone')
184
+ })
185
+ })
186
+ }
187
+
55
188
  /**
56
189
  * Env vars explicitly forwarded into the Docker container.
57
190
  * Only vars needed for Claude Code operation — never forward the full host env.
@@ -75,6 +208,28 @@ const FORWARDED_ENV_KEYS = [
75
208
  'PATH',
76
209
  ]
77
210
 
211
+ // #7337: `CHROXY_PERMISSION_MODE_FILE` is DELIBERATELY absent from the list
212
+ // above, and must stay absent until the sidecar is actually reachable from
213
+ // inside the container.
214
+ //
215
+ // CliSession creates the sidecar under the HOST's tmpdir and publishes its
216
+ // path in the child env, so `permission-hook.sh` can re-read the live
217
+ // permission mode on every tool call instead of the spawn-frozen
218
+ // CHROXY_PERMISSION_MODE. A container has its own filesystem and `docker exec`
219
+ // cannot add a mount (mounts are fixed at `docker run`), so forwarding the key
220
+ // would name a host path that does not exist in the container. The hook's
221
+ // `[ -r ... ]` guard makes that fall back to CHROXY_PERMISSION_MODE — correct,
222
+ // but only by accident, and it would read as "containers have the live channel"
223
+ // when they do not.
224
+ //
225
+ // The consequence is that a containerized CLI session still needs the respawn
226
+ // to pick up a mode change, exactly as before #7337. Giving it the live channel
227
+ // needs a bind mount established in `_startContainer()`; tracked separately.
228
+ // tests/cli-permission-mode-sidecar.test.js pins the omission (with a
229
+ // CHROXY_PERMISSION_MODE positive control) so it cannot be "fixed" by adding
230
+ // the key alone. NOT docker-session.test.js — that file drives a hand-written
231
+ // mirror of _spawnPersistentProcess and never reads the real array.
232
+
78
233
  /**
79
234
  * DockerSession runs Claude Code inside an isolated Docker container.
80
235
  *
@@ -174,6 +329,45 @@ export class DockerSession extends CliSession {
174
329
  this._image = opts.image || 'node:22-slim'
175
330
  this._memoryLimit = opts.memoryLimit || '2g'
176
331
  this._cpuLimit = opts.cpuLimit || '2'
332
+ // #7601 — the CONTAINER_VANISHED idempotency latch (see surfaceContainerVanished).
333
+ this._containerVanishedNotified = false
334
+ }
335
+
336
+ /**
337
+ * #7601 — surface a CONTAINER_VANISHED error once for this session (idempotent).
338
+ * Called by the reactive exec-close path AND the proactive liveness poll /
339
+ * environment_stopped fast-path; the shared latch keeps them from double-emitting.
340
+ * @returns {boolean} true if it emitted
341
+ */
342
+ notifyContainerVanished() {
343
+ return surfaceContainerVanished(this)
344
+ }
345
+
346
+ /**
347
+ * #7601 — reset the CONTAINER_VANISHED latch after the container is observed
348
+ * running again, so a later vanish re-surfaces. Called by the liveness poll on
349
+ * a healthy inspect.
350
+ *
351
+ * #7602 — returns whether this call actually FLIPPED the latch (the gone→
352
+ * running recovery edge), symmetric with `notifyContainerVanished`'s "true if
353
+ * it emitted". The poll uses that edge to trigger the live re-attach; a
354
+ * 'running' verdict on a session that never vanished must not.
355
+ *
356
+ * DockerSession itself is never a re-attach target and deliberately exposes no
357
+ * `reattachContainer`: its container is ALWAYS self-owned and launched with
358
+ * `--rm` (`_startContainer`), and the constructor ignores `opts.containerId`
359
+ * entirely, so a docker-cli session can never be bound to an environment's
360
+ * container. A `--rm` container that stops is REMOVED, so it can never be
361
+ * observed running again — the recovery edge below is unreachable for a real
362
+ * one, and #7602's terminal/fail-visible-only classification of this provider
363
+ * holds by construction rather than by a check that could rot.
364
+ *
365
+ * @returns {boolean} true when the latch transitioned
366
+ */
367
+ clearContainerVanished() {
368
+ if (!this._containerVanishedNotified) return false
369
+ this._containerVanishedNotified = false
370
+ return true
177
371
  }
178
372
 
179
373
  /**
@@ -247,6 +441,26 @@ export class DockerSession extends CliSession {
247
441
  })
248
442
  }
249
443
 
444
+ /**
445
+ * Spawn seam (#7374).
446
+ *
447
+ * Exists so a test can observe the argv `_spawnPersistentProcess` ACTUALLY
448
+ * builds. Before this, the rule that `CHROXY_PERMISSION_MODE_FILE` must not
449
+ * reach the container was pinned only by a source-level grep of the
450
+ * `FORWARDED_ENV_KEYS` literal — which stays green when a key is pushed into
451
+ * `dockerArgs` OUTSIDE the allowlist loop. That is not hypothetical: there
452
+ * are already two such explicit pushes immediately below the loop
453
+ * (`CHROXY_HOST`, `getChroxyHostEnv()`), so the allowlist is demonstrably not
454
+ * the only way in.
455
+ *
456
+ * Kept as a one-line override point rather than a constructor opt so it adds
457
+ * no BaseSession opt to forward (see BASE_SESSION_OPT_KEYS and
458
+ * scripts/lint-session-opt-forwarding.sh).
459
+ */
460
+ _spawnDocker(dockerArgs) {
461
+ return spawn('docker', dockerArgs, { stdio: ['pipe', 'pipe', 'pipe'] })
462
+ }
463
+
250
464
  /**
251
465
  * Override CliSession._spawnPersistentProcess to use `docker exec -i`
252
466
  * instead of spawning `claude` directly.
@@ -294,13 +508,13 @@ export class DockerSession extends CliSession {
294
508
  dockerArgs.push('--env', `${key}=${val}`)
295
509
  }
296
510
 
297
- dockerArgs.push(this._containerId, 'claude', ...claudeArgs)
511
+ // Run claude with CLAUDE_CONFIG_DIR unset: an image-defined value cannot move its
512
+ // config directory somewhere the permission floor does not recognise.
513
+ dockerArgs.push(this._containerId, ...containerUnsetEnvPrefix(), 'claude', ...claudeArgs)
298
514
 
299
515
  log.info(`Exec into container ${this._containerId.slice(0, 12)} (model: ${this.model || 'default'})`)
300
516
 
301
- const child = spawn('docker', dockerArgs, {
302
- stdio: ['pipe', 'pipe', 'pipe'],
303
- })
517
+ const child = this._spawnDocker(dockerArgs)
304
518
 
305
519
  this._child = child
306
520
 
@@ -353,11 +567,9 @@ export class DockerSession extends CliSession {
353
567
  // sendMessage() sets _isBusy, so the loop sends at most one message.
354
568
  // Remaining items stay in the queue and are drained one-by-one via
355
569
  // _clearMessageState() after each result.
356
- while (this._pendingQueue.length > 0 && !this._isBusy) {
357
- const pending = this._pendingQueue.shift()
358
- log.info(`Dequeuing pending message (${this._pendingQueue.length} remaining)`)
359
- this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
360
- }
570
+ // Through the inherited drain, so a queued message whose sender is no longer
571
+ // authorized is dropped instead of dispatched.
572
+ this._drainPendingQueue()
361
573
  }
362
574
 
363
575
  // #4473: log the container-specific exit line under the docker-session
@@ -366,11 +578,73 @@ export class DockerSession extends CliSession {
366
578
  // lands first so `docker logs <ctr>` correlation by operators stays easy.
367
579
  _handleChildClose(code) {
368
580
  if (!this._destroying && !this._respawning) {
369
- log.info(`Container exec exited (code ${code}), scheduling respawn`)
581
+ log.info(`Container exec exited (code ${code})`)
370
582
  }
371
583
  super._handleChildClose(code)
372
584
  }
373
585
 
586
+ /**
587
+ * #7599 — container-vanish hook (overrides CliSession's no-op).
588
+ *
589
+ * Called by CliSession._handleChildClose for a genuine unexpected exit — i.e.
590
+ * AFTER the intentional-stop and resume-unknown branches have returned, and
591
+ * just BEFORE the generic "exited unexpectedly → respawn" tail. Returns a
592
+ * Promise, so the base defers the generic respawn until it resolves.
593
+ *
594
+ * It ACTIVELY PROBES the container (`docker exec <id> true`) rather than
595
+ * trusting the closed exec's merged stderr: that stream mixes docker-client
596
+ * errors with the app's own stderr, so a benign app line containing "is not
597
+ * running" would have falsely suppressed the respawn, and an in-flight kill
598
+ * (exit 137, no docker-client line) would have been missed on the first close
599
+ * (#7599 review). The probe classifies pure docker-client output and is the
600
+ * same signal the docker-sdk path uses.
601
+ *
602
+ * On a confirmed vanish it surfaces one coded CONTAINER_VANISHED session error
603
+ * and resolves `true` so the respawn is suppressed — respawning a `docker exec`
604
+ * into a stopped/removed container would only flap toward `cli_respawn_exhausted`.
605
+ * The session is deliberately NOT torn down and `_containerId` is NOT nulled
606
+ * (the #7561 trap: a null id reads as `_containerOwned` and would launch a fresh
607
+ * default container), so the reconnect path (#7602) can re-attach an env-backed
608
+ * container that returns.
609
+ *
610
+ * Returns a plain `false` synchronously when there is no container to probe
611
+ * (so a no-container close respawns inline, exactly as before), and a
612
+ * `Promise<boolean>` only when it actually probes.
613
+ *
614
+ * @param {number} code exit code of the closed exec child
615
+ * @returns {boolean|Promise<boolean>} true if handled as a vanish (suppress respawn)
616
+ */
617
+ _handleContainerGoneOnClose(code) {
618
+ if (!this._containerId) return false
619
+ return this._probeContainerGone().then((gone) => {
620
+ // Re-check teardown after the async probe: a destroy() that lands in the
621
+ // probe window has already removed listeners, so emitting here would fire
622
+ // on a dead EventEmitter (Node throws on an unhandled 'error') — #7599 review.
623
+ if (!gone || this._destroying) return this._destroying
624
+ ;(this._log || log).warn(
625
+ `Container for this session is gone (exec exit ${code}) — surfacing CONTAINER_VANISHED, not respawning`,
626
+ )
627
+ // #7601: route through the shared idempotent surface so a proactive
628
+ // liveness-poll tick that already surfaced this vanish can't be
629
+ // double-emitted here (and vice-versa). Only `code` (+ `message`) reach
630
+ // clients — the generic error normalizer caps adjacent fields, so the CODE
631
+ // is the surfaced signal; reconnectability is a #7602 server-side decision.
632
+ // Suppress the respawn on a confirmed vanish regardless of whether the
633
+ // latch had already fired.
634
+ this.notifyContainerVanished()
635
+ return true
636
+ })
637
+ }
638
+
639
+ /**
640
+ * Probe whether the bound container is gone. Extracted as an instance method
641
+ * so tests can stub it. Delegates to the shared `probeContainerGone` helper.
642
+ * @returns {Promise<boolean>}
643
+ */
644
+ _probeContainerGone() {
645
+ return probeContainerGone(this._containerId)
646
+ }
647
+
374
648
  /**
375
649
  * Destroy the session: stop the exec process, remove the container,
376
650
  * then call super.destroy() to clean up CliSession state.