@chroxy/server 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,841 @@
1
+ /**
2
+ * DockerContainerPool — opt-in idle pool for docker-byok containers (#5022).
3
+ *
4
+ * Background
5
+ * ----------
6
+ * Each `DockerByokSession` already reuses ONE container across every turn
7
+ * in its session — `_startContainer()` is called once in `start()` and
8
+ * the same container id services every tool dispatch until `destroy()`.
9
+ * That's the per-session reuse baseline and is unconditional.
10
+ *
11
+ * What this module adds
12
+ * ---------------------
13
+ * A small ACROSS-SESSION idle pool. When a session calls `destroy()` and
14
+ * the pool is enabled, the container (if still healthy) is released back
15
+ * to the pool instead of being `docker rm -f`'d. The next session whose
16
+ * acquire-key matches picks it up — skipping the `docker run` + `useradd`
17
+ * + `chown` cold-start path (~500ms-2s, or ~10-30s on image pull).
18
+ *
19
+ * Design decisions (matches issue #5022 AC)
20
+ * -----------------------------------------
21
+ * - Default OFF: opt-in via `CHROXY_DOCKER_BYOK_POOL=1` or pool option
22
+ * so today's per-session behaviour is preserved unless asked for.
23
+ * - Cache key: `image|cwd|memoryLimit|cpuLimit|containerUser` —
24
+ * extended with `|<devcontainerFingerprint>` when a session opted
25
+ * into `useDevcontainer` (#5080) so a changed devcontainer.json
26
+ * overlay invalidates pre-existing pooled containers. Cwd is part
27
+ * of the key because the host cwd is bind-mounted at /workspace —
28
+ * reusing a container across cwds would silently leak host paths.
29
+ * Resource limits are part of the key so a session that asked for
30
+ * `--memory 4g` doesn't pick up a 1g container.
31
+ * - Eviction: per-entry idle timeout (default 5 minutes) — a setTimeout
32
+ * fires `docker rm -f` and drops the entry. Caps on pool size per
33
+ * key (default 2) and total pool size (default 8) keep the daemon
34
+ * load bounded; over-cap releases trigger immediate eviction.
35
+ * - Lifecycle:
36
+ * - acquire(key) → first available entry, or null on miss.
37
+ * Removes from pool (a session OWNS it while held).
38
+ * - release(key, containerId)
39
+ * → put back into the pool with a fresh idle timer.
40
+ * Over-cap releases evict instead.
41
+ * - shutdown() → cancel all timers and `docker rm -f` everything.
42
+ * - Health: pool returns containers AS-IS. DockerByokSession is
43
+ * responsible for `_verifyContainer()` after acquire — if the
44
+ * container died while idle (docker daemon restart, OOM kill, host
45
+ * reboot), the session falls back to `_startContainer()`.
46
+ * - Interaction with snapshot/restore (#5043): the pool exposes
47
+ * `markSoiled(containerId)` so when docker-byok grows snapshot
48
+ * support (#5023), a session that took a snapshot can mark its
49
+ * container so the next `release()` call evicts it inline instead of
50
+ * pooling. A soiled container's filesystem may have leaked into a
51
+ * snapshot image layer (or otherwise become coupled to a specific
52
+ * conversation) — handing it to an unrelated session would silently
53
+ * surface another conversation's files / auth. Soiling is a property
54
+ * of the container id, not the session, so it survives across the
55
+ * release call and is cleared once the container is evicted.
56
+ *
57
+ * Why a separate module
58
+ * ---------------------
59
+ * Keeps the pool side-effect free from the session's start/destroy path:
60
+ * if the pool throws or stalls, the session can fall back to direct
61
+ * container ownership without leaking. Tests can drive the pool with no
62
+ * session involvement.
63
+ */
64
+
65
+ import { execFile as defaultExecFile } from 'child_process'
66
+ import { EventEmitter } from 'events'
67
+ import { createLogger } from './logger.js'
68
+
69
+ const log = createLogger('docker-byok-pool')
70
+
71
+ /**
72
+ * Structured event names emitted by `DockerContainerPool` (#5044).
73
+ *
74
+ * The pool is opt-in but, when in use, services every session in the
75
+ * server — log scraping isn't a serious observability path. Listeners
76
+ * (dashboard, metrics exporter, debug tooling) subscribe via the
77
+ * standard `EventEmitter` API:
78
+ *
79
+ * pool.on(POOL_EVENTS.HIT, ({ key, containerId, timestamp }) => ...)
80
+ * pool.on(POOL_EVENTS.MISS, ({ key, timestamp }) => ...)
81
+ * pool.on(POOL_EVENTS.RELEASED, ({ key, containerId, timestamp }) => ...)
82
+ * pool.on(POOL_EVENTS.EVICTED, ({ key, containerId, reason, timestamp }) => ...)
83
+ * pool.on(POOL_EVENTS.SHUTDOWN, ({ drained, timestamp }) => ...)
84
+ *
85
+ * Eviction reasons:
86
+ * - 'idle' — the per-entry idle timer fired
87
+ * - 'over_cap' — release exceeded per-key or total cap
88
+ * - 'shutdown' — pool was drained via `shutdown()` (or release after)
89
+ *
90
+ * (Hook for #5043: a future 'soiled' reason will be added when the
91
+ * snapshot/restore work lands. Treat the reason set as open.)
92
+ */
93
+ export const POOL_EVENTS = Object.freeze({
94
+ HIT: 'pool:hit',
95
+ MISS: 'pool:miss',
96
+ RELEASED: 'pool:released',
97
+ EVICTED: 'pool:evicted',
98
+ SHUTDOWN: 'pool:shutdown',
99
+ })
100
+
101
+ /** Default idle TTL before an entry is evicted (`docker rm -f`'d). */
102
+ export const DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000
103
+
104
+ /** Default cap on entries kept per pool key. */
105
+ export const DEFAULT_MAX_PER_KEY = 2
106
+
107
+ /** Default cap on total pool size across all keys. */
108
+ export const DEFAULT_MAX_TOTAL = 8
109
+
110
+ /**
111
+ * Default hard cap on total container lifetime (#5045). Idle TTL alone
112
+ * cannot evict a container that's continuously reused. Max age is checked
113
+ * on both `acquire()` and `release()`. Pass `Infinity` to opt out.
114
+ */
115
+ export const DEFAULT_MAX_AGE_MS = 30 * 60 * 1000
116
+
117
+ /**
118
+ * Build the canonical cache key for a session's resource shape. Same
119
+ * shape used by `DockerContainerPool#acquire` / `#release` so the
120
+ * session and the pool can compute keys independently.
121
+ *
122
+ * `devcontainerFingerprint` (#5080) is an optional short hash of the
123
+ * resolved devcontainer.json overlay. When `useDevcontainer: true` is
124
+ * set, the session passes a SHA-1 of the **fully-resolved** overlay
125
+ * (after mount validation + env sanitisation, NOT the raw parsed file)
126
+ * so that a change to `mounts` / `containerEnv` / `forwardPorts` /
127
+ * `postCreateCommand` cache-busts the key — otherwise a pool hit would
128
+ * silently return a container provisioned against a STALE
129
+ * devcontainer.json. `image` and `remoteUser` are deliberately omitted
130
+ * from the fingerprint because they're already first-class segments of
131
+ * the pool key.
132
+ *
133
+ * Non-devcontainer sessions pass `null` (or omit the field), preserving
134
+ * backward compatibility — the joined key remains
135
+ * `image|cwd|memoryLimit|cpuLimit|containerUser`, so pre-fingerprint
136
+ * keys still match and devcontainer + non-devcontainer sessions of the
137
+ * same resource shape never collide (the trailing `|<fp>` is only
138
+ * appended when a fingerprint is supplied).
139
+ *
140
+ * @param {object} spec
141
+ * @param {string} spec.image
142
+ * @param {string} spec.cwd
143
+ * @param {string} spec.memoryLimit
144
+ * @param {string} spec.cpuLimit
145
+ * @param {string} spec.containerUser
146
+ * @param {string|null} [spec.devcontainerFingerprint] — optional short
147
+ * hash of the resolved devcontainer overlay (#5080)
148
+ * @returns {string}
149
+ */
150
+ export function buildPoolKey(spec) {
151
+ if (!spec || typeof spec !== 'object') {
152
+ throw new Error('buildPoolKey: spec is required')
153
+ }
154
+ const { image, cwd, memoryLimit, cpuLimit, containerUser, devcontainerFingerprint } = spec
155
+ if (!image || !cwd || !memoryLimit || !cpuLimit || !containerUser) {
156
+ throw new Error('buildPoolKey: image, cwd, memoryLimit, cpuLimit, containerUser are required')
157
+ }
158
+ const base = [image, cwd, memoryLimit, cpuLimit, containerUser].join('|')
159
+ // Only append the fingerprint segment when one was supplied. A
160
+ // non-devcontainer session keeps the original 5-segment key shape,
161
+ // matching pre-#5080 callers exactly so existing entries still hit.
162
+ if (typeof devcontainerFingerprint === 'string' && devcontainerFingerprint.length > 0) {
163
+ return `${base}|${devcontainerFingerprint}`
164
+ }
165
+ return base
166
+ }
167
+
168
+ /**
169
+ * In-memory idle pool of docker-byok containers, keyed by resource shape.
170
+ *
171
+ * Not thread-safe (Node is single-threaded). All public methods are sync
172
+ * except `shutdown()` and `_evict()` which `docker rm -f` via execFile.
173
+ *
174
+ * Extends `EventEmitter` so callers can observe pool activity via the
175
+ * `POOL_EVENTS.*` events without scraping log lines (#5044).
176
+ */
177
+ export class DockerContainerPool extends EventEmitter {
178
+ /**
179
+ * @param {object} [opts]
180
+ * @param {number} [opts.idleTimeoutMs=300000] — TTL per idle entry
181
+ * @param {number} [opts.maxPerKey=2] — cap per resource shape
182
+ * @param {number} [opts.maxTotal=8] — cap across all shapes
183
+ * @param {Function} [opts._execFile] — test seam (execFile)
184
+ * @param {Function} [opts._setTimeout] — test seam (setTimeout)
185
+ * @param {Function} [opts._clearTimeout] — test seam (clearTimeout)
186
+ * @param {Function} [opts._now] — test seam (Date.now)
187
+ */
188
+ constructor(opts = {}) {
189
+ super()
190
+ // The pool is process-wide; uncapped listener counts would mask
191
+ // a runaway subscriber bug, so set a generous-but-finite cap.
192
+ this.setMaxListeners(32)
193
+ this._idleTimeoutMs = Number.isFinite(opts.idleTimeoutMs)
194
+ ? opts.idleTimeoutMs
195
+ : DEFAULT_IDLE_TIMEOUT_MS
196
+ this._maxPerKey = Number.isFinite(opts.maxPerKey)
197
+ ? opts.maxPerKey
198
+ : DEFAULT_MAX_PER_KEY
199
+ this._maxTotal = Number.isFinite(opts.maxTotal)
200
+ ? opts.maxTotal
201
+ : DEFAULT_MAX_TOTAL
202
+ // #6135 slice 2: the operator-configured caps are the CEILING for a
203
+ // runtime `resize()`. Capture them once at construction so resize can only
204
+ // ever TIGHTEN below the configured values — a WS-triggered action must
205
+ // never raise host resource limits above what the operator configured.
206
+ this._configuredMaxPerKey = this._maxPerKey
207
+ this._configuredMaxTotal = this._maxTotal
208
+ // Accept Infinity (not "finite") as a valid opt-out — Number.isFinite
209
+ // rejects it, which is exactly what we don't want here.
210
+ this._maxAgeMs = typeof opts.maxAgeMs === 'number' && opts.maxAgeMs > 0
211
+ ? opts.maxAgeMs
212
+ : DEFAULT_MAX_AGE_MS
213
+ this._execFile = opts._execFile || defaultExecFile
214
+ this._setTimeout = opts._setTimeout || setTimeout
215
+ this._clearTimeout = opts._clearTimeout || clearTimeout
216
+ this._now = typeof opts._now === 'function' ? opts._now : Date.now
217
+ /** @type {Map<string, Array<{ containerId: string, timer: any }>>} */
218
+ this._entries = new Map()
219
+ /**
220
+ * Container ids marked soiled by `markSoiled()`. A soiled id at
221
+ * `release()` time is evicted inline instead of being pooled — see
222
+ * #5043 and the class docstring's snapshot/restore section.
223
+ * @type {Set<string>}
224
+ */
225
+ this._soiledIds = new Set()
226
+ /**
227
+ * createdAt by container id, kept separate from `_entries` so it
228
+ * survives across acquire/release cycles. Cleared on eviction.
229
+ * @type {Map<string, number>}
230
+ */
231
+ this._createdAt = new Map()
232
+ this._shuttingDown = false
233
+ }
234
+
235
+ /**
236
+ * Emit a structured pool event. Wraps `EventEmitter.emit` so the
237
+ * payload always carries a `timestamp` and so an exception in any
238
+ * listener can't tear down the pool — listener errors are logged and
239
+ * dropped. Returns the payload so call sites can chain (e.g. add a
240
+ * debug log of the same shape).
241
+ *
242
+ * @param {string} name
243
+ * @param {object} payload
244
+ * @returns {object}
245
+ */
246
+ _emitPoolEvent(name, payload) {
247
+ const fullPayload = { timestamp: this._now(), ...payload }
248
+ try {
249
+ this.emit(name, fullPayload)
250
+ } catch (err) {
251
+ // Don't let a listener bug crash the pool's acquire/release/
252
+ // shutdown path. A noisy emitter is still better than a wedged
253
+ // pool.
254
+ log.warn(`listener for ${name} threw: ${err && err.message}`)
255
+ }
256
+ return fullPayload
257
+ }
258
+
259
+ /**
260
+ * Try to claim an idle container for `key`. Returns the container id
261
+ * on hit, `null` on miss. The entry is REMOVED from the pool — the
262
+ * caller now owns the container until they call `release()` (to hand
263
+ * it back) or `docker rm -f` it themselves. There is no public
264
+ * `evict()` — eviction is internal (`_evict`); a caller that wants to
265
+ * forcibly destroy an acquired container just runs `docker rm -f` and
266
+ * never calls `release()`.
267
+ *
268
+ * @param {string} key
269
+ * @returns {string|null}
270
+ */
271
+ acquire(key) {
272
+ if (this._shuttingDown) {
273
+ this._emitPoolEvent(POOL_EVENTS.MISS, { key, containerId: null, reason: 'shutdown' })
274
+ log.debug(`pool miss (shutting down) for ${key}`)
275
+ return null
276
+ }
277
+ const bucket = this._entries.get(key)
278
+ if (!bucket || bucket.length === 0) {
279
+ this._emitPoolEvent(POOL_EVENTS.MISS, { key, containerId: null, reason: 'empty' })
280
+ log.debug(`pool miss for ${key}`)
281
+ return null
282
+ }
283
+ // Lazily skip + evict any over-age or soiled entries at the head of
284
+ // the bucket. Over-age is #5045; the soiled check (#5049) is
285
+ // defense-in-depth — the documented session lifecycle never lets
286
+ // `markSoiled(id)` race against `release()` (destroy() nulls
287
+ // _containerId before pool.release()), but the public markSoiled(id)
288
+ // API takes any id, so a future non-session caller could mark an
289
+ // already-pooled id. Without this check the next acquire() would
290
+ // silently hand out a soiled container. The soiled marker is
291
+ // consumed on the inline eviction so the same id isn't poisoned
292
+ // forever — matches the release-path semantics.
293
+ const now = this._now()
294
+ while (bucket.length > 0) {
295
+ const head = bucket[0]
296
+ const age = now - (head.createdAt ?? now)
297
+ const overAge = age > this._maxAgeMs
298
+ const soiled = this._soiledIds.has(head.containerId)
299
+ if (!overAge && !soiled) break
300
+ bucket.shift()
301
+ this._clearTimeout(head.timer)
302
+ this._createdAt.delete(head.containerId)
303
+ if (soiled) {
304
+ this._soiledIds.delete(head.containerId)
305
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId: head.containerId, reason: 'soiled' })
306
+ log.info(`pool soiled on acquire: evicting ${head.containerId.slice(0, 12)}`)
307
+ } else {
308
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId: head.containerId, reason: 'over_age' })
309
+ log.info(`pool over-age on acquire (${age}ms > ${this._maxAgeMs}ms): evicting ${head.containerId.slice(0, 12)}`)
310
+ }
311
+ this._evict(head.containerId).catch((err) => {
312
+ log.warn(`acquire-time eviction of ${head.containerId.slice(0, 12)} failed: ${err.message}`)
313
+ })
314
+ }
315
+ if (bucket.length === 0) {
316
+ this._entries.delete(key)
317
+ this._emitPoolEvent(POOL_EVENTS.MISS, { key, containerId: null, reason: 'empty' })
318
+ return null
319
+ }
320
+ const entry = bucket.shift()
321
+ if (bucket.length === 0) this._entries.delete(key)
322
+ this._clearTimeout(entry.timer)
323
+ this._emitPoolEvent(POOL_EVENTS.HIT, { key, containerId: entry.containerId })
324
+ log.info(`pool hit: ${entry.containerId.slice(0, 12)} for ${key}`)
325
+ return entry.containerId
326
+ }
327
+
328
+ /**
329
+ * Hand a container back to the pool for reuse. If over the per-key or
330
+ * total cap, or if the pool is shutting down, the container is evicted
331
+ * (`docker rm -f`) instead of being kept. Returns `true` if the
332
+ * container was retained, `false` if it was evicted.
333
+ *
334
+ * @param {string} key
335
+ * @param {string} containerId
336
+ * @returns {Promise<boolean>}
337
+ */
338
+ async release(key, containerId) {
339
+ // Guard a null/empty id before any eviction work — a shutdown release
340
+ // with no id was calling `docker rm -f` with an empty argument.
341
+ if (!containerId) return false
342
+ if (this._shuttingDown) {
343
+ this._soiledIds.delete(containerId)
344
+ this._createdAt.delete(containerId)
345
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId, reason: 'shutdown' })
346
+ log.info(`pool release after shutdown; evicting ${containerId.slice(0, 12)}`)
347
+ await this._evict(containerId)
348
+ return false
349
+ }
350
+ // #5043: soiled containers (snapshot taken, or otherwise coupled to a
351
+ // particular conversation) MUST NOT be returned to the pool — the
352
+ // next session of the same shape would silently inherit the previous
353
+ // session's filesystem state. Evict inline and clear the marker so
354
+ // the soiled set doesn't grow unbounded.
355
+ if (this._soiledIds.has(containerId)) {
356
+ this._soiledIds.delete(containerId)
357
+ this._createdAt.delete(containerId)
358
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId, reason: 'soiled' })
359
+ log.info(`pool release: ${containerId.slice(0, 12)} marked soiled; evicting instead of pooling`)
360
+ await this._evict(containerId)
361
+ return false
362
+ }
363
+ // Resolve / record createdAt before any other check so an over-age
364
+ // container that's never been pooled before still gets its real birth
365
+ // time (now) — only re-released containers carry an older createdAt.
366
+ const now = this._now()
367
+ const createdAt = this._createdAt.get(containerId) ?? now
368
+ // Hard max-age cap (#5045): even if the bucket has room, refuse to
369
+ // pool a container that's exceeded total lifetime. Without this, a
370
+ // hot container can survive forever via repeated acquire/release.
371
+ const age = now - createdAt
372
+ if (age > this._maxAgeMs) {
373
+ log.info(`pool over-age on release (${age}ms > ${this._maxAgeMs}ms): evicting ${containerId.slice(0, 12)}`)
374
+ this._createdAt.delete(containerId)
375
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId, reason: 'over_age' })
376
+ await this._evict(containerId)
377
+ return false
378
+ }
379
+ const total = this._totalSize()
380
+ const bucket = this._entries.get(key) || []
381
+ if (bucket.length >= this._maxPerKey || total >= this._maxTotal) {
382
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId, reason: 'over_cap' })
383
+ log.info(`pool over cap (key=${bucket.length}/${this._maxPerKey} total=${total}/${this._maxTotal}); evicting ${containerId.slice(0, 12)}`)
384
+ this._createdAt.delete(containerId)
385
+ await this._evict(containerId)
386
+ return false
387
+ }
388
+ const timer = this._setTimeout(() => {
389
+ this._removeEntry(key, containerId, /*alreadyTimedOut*/ true)
390
+ this._createdAt.delete(containerId)
391
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId, reason: 'idle' })
392
+ this._evict(containerId).catch((err) => {
393
+ log.warn(`idle eviction of ${containerId.slice(0, 12)} failed: ${err.message}`)
394
+ })
395
+ }, this._idleTimeoutMs)
396
+ // setTimeout returns a Timer object on Node; unref so a pooled
397
+ // container doesn't keep the event loop alive on shutdown.
398
+ if (timer && typeof timer.unref === 'function') timer.unref()
399
+ this._createdAt.set(containerId, createdAt)
400
+ // Stamp releasedAt on every pooled entry so `inspect()` (#5052) can
401
+ // report `oldestIdleMs` without iterating timers. We already have
402
+ // `now` from the over-age check above; reuse it so the stamp matches
403
+ // the bookkeeping time exactly.
404
+ bucket.push({ containerId, timer, createdAt, releasedAt: now })
405
+ this._entries.set(key, bucket)
406
+ this._emitPoolEvent(POOL_EVENTS.RELEASED, { key, containerId })
407
+ log.info(`pool release: ${containerId.slice(0, 12)} → ${key} (idle ${this._idleTimeoutMs}ms, age ${age}ms/${this._maxAgeMs}ms)`)
408
+ return true
409
+ }
410
+
411
+ /**
412
+ * Snapshot the current entry count. Useful for tests / dashboards.
413
+ * @returns {number}
414
+ */
415
+ size() {
416
+ return this._totalSize()
417
+ }
418
+
419
+ /**
420
+ * Snapshot the entry count for a specific key.
421
+ * @param {string} key
422
+ * @returns {number}
423
+ */
424
+ sizeOf(key) {
425
+ const bucket = this._entries.get(key)
426
+ return bucket ? bucket.length : 0
427
+ }
428
+
429
+ /**
430
+ * Read-only per-key bucket snapshot (#5052). Returns one
431
+ * `{ key, size, oldestIdleMs }` for every non-empty bucket, sorted by
432
+ * key ascending so output is stable for tests and dashboard diffs.
433
+ *
434
+ * - `size` — number of containers currently parked under
435
+ * this key.
436
+ * - `oldestIdleMs` — `now - min(entry.releasedAt)` across the
437
+ * bucket; i.e. `max(now - releasedAt)`, the idle
438
+ * age of the OLDEST parked container (the one
439
+ * released longest ago). Useful for leak
440
+ * detection and idle-lifetime distribution.
441
+ *
442
+ * Companion to the structured event stream (#5044):
443
+ * - Events answer "what did the pool DO recently?"
444
+ * - `inspect()` answers "what's parked right now?"
445
+ *
446
+ * SHALLOW snapshot: caller mutations on the returned array (or its
447
+ * entry objects) MUST NOT affect pool state. We build fresh plain
448
+ * objects and never expose the internal `_entries` Map.
449
+ *
450
+ * @returns {Array<{ key: string, size: number, oldestIdleMs: number }>}
451
+ */
452
+ inspect() {
453
+ const now = this._now()
454
+ const snapshot = []
455
+ for (const [key, bucket] of this._entries.entries()) {
456
+ if (!bucket || bucket.length === 0) continue
457
+ // `oldestIdleMs` = max(now - releasedAt) across the bucket. The
458
+ // oldest entry is the one with the SMALLEST releasedAt — fall
459
+ // back to `now` (idle 0) if an entry somehow lacks the stamp so
460
+ // the snapshot stays well-formed in pathological cases.
461
+ let oldestReleasedAt = now
462
+ for (const entry of bucket) {
463
+ const ra = typeof entry.releasedAt === 'number' ? entry.releasedAt : now
464
+ if (ra < oldestReleasedAt) oldestReleasedAt = ra
465
+ }
466
+ snapshot.push({
467
+ key,
468
+ size: bucket.length,
469
+ oldestIdleMs: now - oldestReleasedAt,
470
+ })
471
+ }
472
+ snapshot.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
473
+ return snapshot
474
+ }
475
+
476
+ /**
477
+ * Read-only snapshot of the configured pool bounds (#6135 Control Room
478
+ * observability). `maxAgeMs` is `null` when unbounded (Infinity) so the value
479
+ * is JSON-serialisable. Pure — no side effects, no eviction.
480
+ *
481
+ * @returns {{ idleTimeoutMs: number, maxPerKey: number, maxTotal: number, maxAgeMs: number|null }}
482
+ */
483
+ limits() {
484
+ return {
485
+ idleTimeoutMs: this._idleTimeoutMs,
486
+ maxPerKey: this._maxPerKey,
487
+ maxTotal: this._maxTotal,
488
+ maxAgeMs: Number.isFinite(this._maxAgeMs) ? this._maxAgeMs : null,
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Read-only snapshot of the operator-configured cap CEILING (#6135 slice 2).
494
+ * `resize()` clamps to these, so the Control Room can render a valid resize
495
+ * range. Distinct from `limits()`, which reports the CURRENT (possibly
496
+ * resized-down) effective caps.
497
+ *
498
+ * @returns {{ maxPerKey: number, maxTotal: number }}
499
+ */
500
+ configuredLimits() {
501
+ return {
502
+ maxPerKey: this._configuredMaxPerKey,
503
+ maxTotal: this._configuredMaxTotal,
504
+ }
505
+ }
506
+
507
+ /**
508
+ * #6135 slice 2 — drain mutating action. Evict EVERY idle pooled container
509
+ * across all keys WITHOUT terminating the pool (unlike `shutdown()`, the
510
+ * pool stays usable — the next `acquire()` misses and a fresh container is
511
+ * created). Returns the number of containers evicted. No-op (returns 0)
512
+ * while shutting down.
513
+ *
514
+ * @returns {Promise<number>}
515
+ */
516
+ async drainAll() {
517
+ if (this._shuttingDown) return 0
518
+ let total = 0
519
+ for (const key of [...this._entries.keys()]) {
520
+ total += await this._drainBucket(key, 'drained')
521
+ }
522
+ return total
523
+ }
524
+
525
+ /**
526
+ * #6135 slice 2 — recycle mutating action. Evict every idle pooled container
527
+ * under ONE key (per-resource-shape), non-terminally. Returns the number
528
+ * evicted; an unknown / empty key evicts nothing (returns 0). No-op while
529
+ * shutting down.
530
+ *
531
+ * @param {string} key
532
+ * @returns {Promise<number>}
533
+ */
534
+ async recycleKey(key) {
535
+ if (this._shuttingDown) return 0
536
+ if (typeof key !== 'string' || key.length === 0) return 0
537
+ return this._drainBucket(key, 'recycled')
538
+ }
539
+
540
+ /**
541
+ * #6135 slice 2 — resize mutating action. Adjust the runtime per-key / total
542
+ * caps, each clamped to `[1, the operator-configured ceiling]` so a runtime
543
+ * resize can only TIGHTEN below the configured caps, never exceed them.
544
+ * Non-integer / out-of-range / omitted values leave that cap unchanged.
545
+ * After tightening, evicts entries now over the new caps (per-key first,
546
+ * then oldest-idle across all buckets until within the total cap). Returns
547
+ * the new effective `limits`, the `configured` ceiling, and the count
548
+ * `evicted`. No-op (no eviction, current limits) while shutting down.
549
+ *
550
+ * @param {{ maxPerKey?: number, maxTotal?: number }} [opts]
551
+ * @returns {Promise<{ limits: object, configured: object, evicted: number }>}
552
+ */
553
+ async resize(opts = {}) {
554
+ if (this._shuttingDown) {
555
+ return { limits: this.limits(), configured: this.configuredLimits(), evicted: 0 }
556
+ }
557
+ const { maxPerKey, maxTotal } = opts || {}
558
+ if (Number.isInteger(maxPerKey) && maxPerKey >= 1) {
559
+ this._maxPerKey = Math.min(maxPerKey, this._configuredMaxPerKey)
560
+ }
561
+ if (Number.isInteger(maxTotal) && maxTotal >= 1) {
562
+ this._maxTotal = Math.min(maxTotal, this._configuredMaxTotal)
563
+ }
564
+ const evicted = await this._enforceCaps('resized')
565
+ return { limits: this.limits(), configured: this.configuredLimits(), evicted }
566
+ }
567
+
568
+ /**
569
+ * Evict every idle entry under one key, emitting EVICTED with `reason` per
570
+ * container so the stats aggregator buckets the drain/recycle correctly.
571
+ * Shared by `drainAll()` / `recycleKey()`. Returns the count evicted.
572
+ */
573
+ async _drainBucket(key, reason) {
574
+ const bucket = this._entries.get(key)
575
+ if (!bucket || bucket.length === 0) return 0
576
+ const ids = bucket.map((e) => e.containerId)
577
+ for (const entry of bucket) this._clearTimeout(entry.timer)
578
+ this._entries.delete(key)
579
+ for (const containerId of ids) {
580
+ this._createdAt.delete(containerId)
581
+ this._soiledIds.delete(containerId)
582
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId, reason })
583
+ }
584
+ await Promise.all(ids.map((containerId) => this._evict(containerId).catch((err) => {
585
+ log.warn(`${reason} eviction of ${containerId.slice(0, 12)} failed: ${err.message}`)
586
+ })))
587
+ return ids.length
588
+ }
589
+
590
+ /**
591
+ * Evict entries that now exceed the (possibly tightened) caps: trim each
592
+ * bucket to `_maxPerKey` (evicting the oldest-released first), then drop the
593
+ * globally-oldest idle entry until within `_maxTotal`. Returns the count
594
+ * evicted. Used by `resize()`.
595
+ */
596
+ async _enforceCaps(reason) {
597
+ /** @type {string[]} */
598
+ const evictedIds = []
599
+ // Per-key cap: trim from the head (oldest releasedAt) of each bucket.
600
+ for (const [key, bucket] of [...this._entries.entries()]) {
601
+ while (bucket.length > this._maxPerKey) {
602
+ const entry = bucket.shift()
603
+ this._clearTimeout(entry.timer)
604
+ this._createdAt.delete(entry.containerId)
605
+ this._soiledIds.delete(entry.containerId)
606
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId: entry.containerId, reason })
607
+ evictedIds.push(entry.containerId)
608
+ }
609
+ if (bucket.length === 0) this._entries.delete(key)
610
+ }
611
+ // Total cap: evict the globally-oldest idle entries until within the cap.
612
+ // One sorted pass (oldest releasedAt first) rather than a rescan-per-eviction
613
+ // so this stays O(n log n) even if the total ceiling ever grows large.
614
+ const overTotal = this._totalSize() - this._maxTotal
615
+ if (overTotal > 0) {
616
+ const all = []
617
+ for (const [key, bucket] of this._entries.entries()) {
618
+ for (const entry of bucket) {
619
+ all.push({ key, entry, releasedAt: typeof entry.releasedAt === 'number' ? entry.releasedAt : 0 })
620
+ }
621
+ }
622
+ all.sort((a, b) => a.releasedAt - b.releasedAt)
623
+ for (const { key, entry } of all.slice(0, overTotal)) {
624
+ // _removeEntry already clears the idle timer for the matched entry.
625
+ this._removeEntry(key, entry.containerId)
626
+ this._createdAt.delete(entry.containerId)
627
+ this._soiledIds.delete(entry.containerId)
628
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId: entry.containerId, reason })
629
+ evictedIds.push(entry.containerId)
630
+ }
631
+ }
632
+ await Promise.all(evictedIds.map((containerId) => this._evict(containerId).catch((err) => {
633
+ log.warn(`${reason} eviction of ${containerId.slice(0, 12)} failed: ${err.message}`)
634
+ })))
635
+ return evictedIds.length
636
+ }
637
+
638
+ /**
639
+ * Mark a container "soiled" so the next `release()` call evicts it
640
+ * inline instead of returning it to the pool. Used by callers that
641
+ * have done something to the container's filesystem which couples it
642
+ * to the current session — most importantly, taking a Docker snapshot
643
+ * (#5023). A snapshot includes the container's writable layer, so any
644
+ * files the previous session wrote / authenticated would silently leak
645
+ * into the next acquirer of this container.
646
+ *
647
+ * Idempotent — calling twice with the same id is a no-op. Null / empty
648
+ * / non-string ids are silently ignored so callers don't need to
649
+ * branch on whether they actually hold a container. No-ops cleanly
650
+ * when the pool is disabled (the session holds `this._pool = null`
651
+ * and never gets here).
652
+ *
653
+ * @param {string} containerId
654
+ */
655
+ markSoiled(containerId) {
656
+ if (typeof containerId !== 'string' || containerId.length === 0) return
657
+ if (this._soiledIds.has(containerId)) return
658
+ this._soiledIds.add(containerId)
659
+ log.info(`marked container ${containerId.slice(0, 12)} soiled — next release will evict`)
660
+ }
661
+
662
+ /**
663
+ * Whether a container has been marked soiled. Exposed for tests and
664
+ * dashboard introspection; production callers use `markSoiled()` and
665
+ * let `release()` handle the eviction.
666
+ *
667
+ * @param {string} containerId
668
+ * @returns {boolean}
669
+ */
670
+ isSoiled(containerId) {
671
+ if (typeof containerId !== 'string' || containerId.length === 0) return false
672
+ return this._soiledIds.has(containerId)
673
+ }
674
+
675
+ /**
676
+ * Caller-side escape hatch (#5045 review): the caller has acquired a
677
+ * container and decided NOT to release it back to the pool — e.g. the
678
+ * verify step failed and they're going to docker rm -f themselves. Clear
679
+ * the lifetime-tracking entry so it doesn't leak in `_createdAt`, and
680
+ * run docker rm -f. Silently ignores null/empty/non-string ids.
681
+ *
682
+ * @param {string} containerId
683
+ * @returns {Promise<void>}
684
+ */
685
+ async forget(containerId) {
686
+ if (typeof containerId !== 'string' || containerId.length === 0) return
687
+ this._createdAt.delete(containerId)
688
+ this._soiledIds.delete(containerId)
689
+ await this._evict(containerId)
690
+ }
691
+
692
+ /**
693
+ * Cancel all idle timers and `docker rm -f` every entry. After
694
+ * shutdown, `acquire()` always returns null and `release()` evicts
695
+ * inline. Idempotent.
696
+ */
697
+ async shutdown() {
698
+ this._shuttingDown = true
699
+ /** @type {Array<{ key: string, containerId: string }>} */
700
+ const toRemove = []
701
+ for (const [key, bucket] of this._entries.entries()) {
702
+ for (const entry of bucket) {
703
+ this._clearTimeout(entry.timer)
704
+ toRemove.push({ key, containerId: entry.containerId })
705
+ }
706
+ }
707
+ this._entries.clear()
708
+ // Clear the soiled-id + createdAt tracking — a future pool instance
709
+ // (lazy singleton, test reset) starts from a clean slate.
710
+ this._soiledIds.clear()
711
+ this._createdAt.clear()
712
+ log.info(`shutdown: evicting ${toRemove.length} pooled container(s)`)
713
+ // Emit per-container eviction BEFORE the final pool:shutdown so a
714
+ // listener that drains counters into a snapshot has all of them
715
+ // accounted for when the "done" event arrives.
716
+ for (const { key, containerId } of toRemove) {
717
+ this._emitPoolEvent(POOL_EVENTS.EVICTED, { key, containerId, reason: 'shutdown' })
718
+ }
719
+ await Promise.all(toRemove.map(({ containerId }) => this._evict(containerId).catch((err) => {
720
+ log.warn(`shutdown eviction of ${containerId.slice(0, 12)} failed: ${err.message}`)
721
+ })))
722
+ this._emitPoolEvent(POOL_EVENTS.SHUTDOWN, { drained: toRemove.length })
723
+ }
724
+
725
+ // ─────────────────────────────────────────────────────────────────
726
+ // internals
727
+ // ─────────────────────────────────────────────────────────────────
728
+
729
+ _totalSize() {
730
+ let n = 0
731
+ for (const bucket of this._entries.values()) n += bucket.length
732
+ return n
733
+ }
734
+
735
+ /**
736
+ * Remove an entry from the bucket without evicting. Used by the idle
737
+ * timer callback (which then evicts separately) so the pool's view of
738
+ * "what's idle" stays in sync.
739
+ */
740
+ _removeEntry(key, containerId, alreadyTimedOut = false) {
741
+ const bucket = this._entries.get(key)
742
+ if (!bucket) return
743
+ const idx = bucket.findIndex((e) => e.containerId === containerId)
744
+ if (idx === -1) return
745
+ const [entry] = bucket.splice(idx, 1)
746
+ if (!alreadyTimedOut) this._clearTimeout(entry.timer)
747
+ if (bucket.length === 0) this._entries.delete(key)
748
+ }
749
+
750
+ /**
751
+ * `docker rm -f` a container, swallowing the "no such container"
752
+ * error so we don't crash on a container that died on its own.
753
+ */
754
+ _evict(containerId) {
755
+ return new Promise((resolve) => {
756
+ // `execFile` ignores `stdio`; cap the buffer so a misbehaving
757
+ // docker(8) can't OOM us on stderr. 64 KiB is plenty for an error
758
+ // path that should produce a one-line "no such container" at most.
759
+ this._execFile('docker', ['rm', '-f', containerId], { maxBuffer: 64 * 1024 }, (err) => {
760
+ if (err) {
761
+ log.warn(`docker rm -f ${containerId.slice(0, 12)} failed: ${err.message}`)
762
+ }
763
+ resolve()
764
+ })
765
+ })
766
+ }
767
+ }
768
+
769
+ /**
770
+ * Process-wide singleton (lazy). Most callers should go through this so
771
+ * sessions across the server share one pool. Tests inject their own
772
+ * pool via the `_pool` constructor seam.
773
+ *
774
+ * @type {DockerContainerPool|null}
775
+ */
776
+ let _sharedPool = null
777
+
778
+ /**
779
+ * Lazily-construct the shared pool. Returns `null` when pooling is
780
+ * disabled — callers check the return value before using it.
781
+ *
782
+ * Enabled when `CHROXY_DOCKER_BYOK_POOL` is truthy (1, true, yes, on).
783
+ * Optional knobs:
784
+ * - CHROXY_DOCKER_BYOK_POOL_IDLE_MS — override idle TTL (ms)
785
+ * - CHROXY_DOCKER_BYOK_POOL_MAX_PER_KEY — override per-key cap
786
+ * - CHROXY_DOCKER_BYOK_POOL_MAX_TOTAL — override total cap
787
+ *
788
+ * @param {Record<string,string|undefined>} [env=process.env]
789
+ * @returns {DockerContainerPool|null}
790
+ */
791
+ export function getSharedPool(env = process.env) {
792
+ if (!isPoolEnabled(env)) return null
793
+ if (_sharedPool) return _sharedPool
794
+ const idleRaw = env.CHROXY_DOCKER_BYOK_POOL_IDLE_MS
795
+ const perKeyRaw = env.CHROXY_DOCKER_BYOK_POOL_MAX_PER_KEY
796
+ const totalRaw = env.CHROXY_DOCKER_BYOK_POOL_MAX_TOTAL
797
+ const maxAgeRaw = env.CHROXY_DOCKER_BYOK_POOL_MAX_AGE_MS
798
+ const idleTimeoutMs = Number(idleRaw)
799
+ const maxPerKey = Number(perKeyRaw)
800
+ const maxTotal = Number(totalRaw)
801
+ let maxAgeMs
802
+ if (typeof maxAgeRaw === 'string') {
803
+ const trimmed = maxAgeRaw.trim().toLowerCase()
804
+ if (trimmed === 'infinity') {
805
+ maxAgeMs = Infinity
806
+ } else {
807
+ const n = Number(maxAgeRaw)
808
+ if (Number.isFinite(n) && n > 0) maxAgeMs = n
809
+ }
810
+ }
811
+ _sharedPool = new DockerContainerPool({
812
+ idleTimeoutMs: Number.isFinite(idleTimeoutMs) && idleTimeoutMs > 0 ? idleTimeoutMs : undefined,
813
+ maxPerKey: Number.isFinite(maxPerKey) && maxPerKey > 0 ? maxPerKey : undefined,
814
+ maxTotal: Number.isFinite(maxTotal) && maxTotal > 0 ? maxTotal : undefined,
815
+ maxAgeMs,
816
+ })
817
+ return _sharedPool
818
+ }
819
+
820
+ /**
821
+ * Whether the docker-byok pool is enabled in the given env. Exposed so
822
+ * the session constructor can short-circuit pool work entirely when
823
+ * disabled (no map lookups, no allocations).
824
+ *
825
+ * @param {Record<string,string|undefined>} [env=process.env]
826
+ * @returns {boolean}
827
+ */
828
+ export function isPoolEnabled(env = process.env) {
829
+ const raw = env.CHROXY_DOCKER_BYOK_POOL
830
+ if (typeof raw !== 'string') return false
831
+ const norm = raw.trim().toLowerCase()
832
+ return norm === '1' || norm === 'true' || norm === 'yes' || norm === 'on'
833
+ }
834
+
835
+ /**
836
+ * Reset the shared singleton. Tests use this to keep state from leaking
837
+ * across cases. Production code never calls this.
838
+ */
839
+ export function _resetSharedPool() {
840
+ _sharedPool = null
841
+ }