@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,753 @@
1
+ import { EventEmitter } from 'events'
2
+ import { randomBytes } from 'crypto'
3
+ import { execFile } from 'child_process'
4
+ import { existsSync, readFileSync, mkdirSync } from 'fs'
5
+ import { dirname, join } from 'path'
6
+ import { homedir } from 'os'
7
+ import { writeFileRestricted } from './platform.js'
8
+ import { createLogger } from './logger.js'
9
+ import { VALID_USERNAME_RE } from './utils/validation-patterns.js'
10
+ import { DockerBackend } from './environments/backends/docker.js'
11
+ import {
12
+ parseDevContainer,
13
+ validateMounts,
14
+ sanitizeContainerEnv,
15
+ } from './devcontainer-config.js'
16
+
17
+ const log = createLogger('environment-manager')
18
+
19
+ const DEFAULT_STATE_PATH = join(homedir(), '.chroxy', 'environments.json')
20
+ const DEFAULT_IMAGE = 'node:22-slim'
21
+ const DEFAULT_MEMORY_LIMIT = '2g'
22
+ const DEFAULT_CPU_LIMIT = '2'
23
+ const DEFAULT_CONTAINER_USER = 'chroxy'
24
+
25
+ // Re-export `UNREACHABLE_STATUSES` from the dedicated constants module so
26
+ // existing importers (tests, future consumers) continue to work. The
27
+ // canonical definition lives in `environment-statuses.js` so `server-cli.js`
28
+ // can pull the set without eagerly loading this module's `DockerBackend`
29
+ // transitive dependency — see the file header in environment-statuses.js.
30
+ export { UNREACHABLE_STATUSES } from './environment-statuses.js'
31
+
32
+ /**
33
+ * Manages persistent container environments that outlive individual sessions.
34
+ *
35
+ * Environments are long-lived Docker containers that multiple sessions can
36
+ * connect to. The EnvironmentManager handles container creation, destruction,
37
+ * persistence to disk, and reconnection after server restart.
38
+ *
39
+ * SessionManager uses EnvironmentManager to look up container details when
40
+ * creating sessions with an environmentId.
41
+ */
42
+ export class EnvironmentManager extends EventEmitter {
43
+ /**
44
+ * @param {Object} [opts]
45
+ * @param {string} [opts.statePath] - On-disk path for environments.json
46
+ * @param {Function} [opts._execFile] - Injected execFile (testing seam)
47
+ * @param {Object} [opts.backend] - Pluggable backend (defaults to DockerBackend)
48
+ * @param {Object} [opts.workspacePVCDefault] - #4556: operator-configured
49
+ * PVC workspace strategy applied to every `create()` call that doesn't pass
50
+ * an explicit `opts.workspacePVC`. Wires the chroxy-config
51
+ * `environments.k8s.workspace` block into the manager. Shape mirrors
52
+ * `K8sBackend.validateWorkspacePVC()`: `{ claimName, mountPath?, readOnly? }`.
53
+ * Forwarded verbatim to the backend; non-K8s backends ignore it. Shape
54
+ * validation lives in `validateConfig()` at load-time and (defensively
55
+ * again) in `K8sBackend.validateWorkspacePVC()` at create-time — the
56
+ * manager performs no validation of its own.
57
+ */
58
+ constructor({ statePath, _execFile, backend, workspacePVCDefault } = {}) {
59
+ super()
60
+ this._statePath = statePath || DEFAULT_STATE_PATH
61
+ this._environments = new Map()
62
+ // Per-environment mutex: Map<envId, Promise> — serializes operations
63
+ this._locks = new Map()
64
+ // Injected for testing — falls back to real execFile.
65
+ // _execFile is forwarded to DockerBackend so existing tests that inject a
66
+ // mock execFile continue to work without modification.
67
+ this._execFile = _execFile || execFile
68
+ // Pluggable backend — defaults to DockerBackend with the same _execFile
69
+ // so the existing _execFile test seam still reaches Docker shellouts.
70
+ this._backend = backend || new DockerBackend({ _execFile: this._execFile })
71
+ // #4556: configured PVC workspace default (operator surface). When set,
72
+ // every create() that doesn't pass workspacePVC falls back to this value.
73
+ // null when no `environments.k8s.workspace` block is configured.
74
+ this._workspacePVCDefault = workspacePVCDefault ?? null
75
+ }
76
+
77
+ /**
78
+ * Acquire a per-environment mutex. Returns a release function.
79
+ * All operations on the same envId serialize through this lock.
80
+ * Operations on different envIds run in parallel.
81
+ */
82
+ async _acquireLock(envId) {
83
+ while (this._locks.has(envId)) {
84
+ await this._locks.get(envId)
85
+ }
86
+ let release
87
+ const lock = new Promise(resolve => { release = resolve })
88
+ this._locks.set(envId, lock)
89
+ return () => {
90
+ this._locks.delete(envId)
91
+ release()
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Look up a tracked environment by id, throwing the canonical
97
+ * `Environment not found: <id>` error when it is absent. Callers that
98
+ * want a graceful miss (e.g. session add/remove) check `_environments`
99
+ * directly instead — this helper is only for the throw-on-missing paths.
100
+ *
101
+ * @param {string} envId
102
+ * @returns {Object} the environment record
103
+ */
104
+ _getEnvironmentOrThrow(envId) {
105
+ const env = this._environments.get(envId)
106
+ if (!env) throw new Error(`Environment not found: ${envId}`)
107
+ return env
108
+ }
109
+
110
+ /**
111
+ * Create a new persistent environment.
112
+ *
113
+ * Starts a Docker container with security constraints, creates a non-root
114
+ * user, installs Claude Code CLI, and persists the environment to disk.
115
+ *
116
+ * @param {Object} opts
117
+ * @param {string} opts.name - Human-readable environment name
118
+ * @param {string} opts.cwd - Host working directory to mount as /workspace
119
+ * @param {string} [opts.image] - Docker image (default: node:22-slim)
120
+ * @param {string} [opts.memoryLimit] - Memory limit (default: 2g)
121
+ * @param {string} [opts.cpuLimit] - CPU limit (default: 2)
122
+ * @param {Object} [opts.resources] - K8s-only: structured resource requests/limits
123
+ * `{ cpu, memory, cpuLimit, memoryLimit }` (#3195). Forwarded verbatim to the backend;
124
+ * only K8sBackend acts on it (DockerBackend and others ignore it). On K8s these values
125
+ * take precedence over the flat `memoryLimit`/`cpuLimit` above; unset fields fall back to
126
+ * the backend's configured defaults.
127
+ * @param {string} [opts.containerUser] - Non-root user (default: chroxy)
128
+ * @param {Object} [opts.workspacePVC] - K8s-only: mount a pre-provisioned
129
+ * PersistentVolumeClaim as the workspace instead of the host `cwd` directory.
130
+ * See `K8sBackend.createEnvironment` (#3385) for the full shape and semantics
131
+ * (`{ claimName, mountPath?, readOnly? }`). Forwarded verbatim to the backend;
132
+ * DockerBackend and other non-K8s backends ignore it. Mutually exclusive with
133
+ * `opts.cwd`-as-hostPath on K8sBackend — the backend validates and throws.
134
+ *
135
+ * #4556 — when the operator has configured `environments.k8s.workspace` in
136
+ * chroxy config (wired via the constructor's `workspacePVCDefault` option),
137
+ * a `create()` call that omits this field falls back to the configured
138
+ * default. An explicit value here always wins (per-call override surface
139
+ * for any future dashboard/CLI input).
140
+ * @returns {Promise<Object>} The created environment object
141
+ */
142
+ async create({ name, cwd, image, memoryLimit, cpuLimit, resources, containerUser, compose, primaryService, devcontainer, workspacePVC } = {}) {
143
+ if (!name?.trim()) throw new Error('Environment name is required')
144
+ if (!cwd?.trim()) throw new Error('Environment cwd is required')
145
+
146
+ // Merge devcontainer.json when requested (explicit opts win).
147
+ // Parsing/validation logic lives in `devcontainer-config.js` so the
148
+ // persistent-environment path here and the per-session DockerByokSession
149
+ // path share one source of truth (#5077).
150
+ let dcConfig = {}
151
+ if (devcontainer) {
152
+ dcConfig = parseDevContainer(cwd, { logger: log })
153
+ }
154
+
155
+ const user = containerUser || dcConfig.remoteUser || DEFAULT_CONTAINER_USER
156
+ if (!VALID_USERNAME_RE.test(user)) {
157
+ throw new Error(`Invalid containerUser "${user}" — must match POSIX username rules`)
158
+ }
159
+
160
+ const id = 'env-' + randomBytes(8).toString('hex')
161
+ const composeProject = compose ? `chroxy-${id}` : null
162
+
163
+ if (compose) {
164
+ return this._createComposeEnvironment({ id, name, cwd, user, compose, primaryService, composeProject })
165
+ }
166
+
167
+ const resolvedImage = image || dcConfig.image || DEFAULT_IMAGE
168
+ const resolvedMemory = memoryLimit || DEFAULT_MEMORY_LIMIT
169
+ const resolvedCpu = cpuLimit || DEFAULT_CPU_LIMIT
170
+
171
+ log.info(`Creating environment "${name}" (id: ${id}, image: ${resolvedImage})`)
172
+
173
+ // Validate devcontainer mounts and env before passing to Docker.
174
+ // Shared helpers from `devcontainer-config.js` (#5077).
175
+ const validatedMounts = validateMounts(dcConfig.mounts, cwd, { logger: log })
176
+ const validatedEnv = sanitizeContainerEnv(dcConfig.containerEnv, { logger: log })
177
+
178
+ // #4556: caller-supplied workspacePVC wins; otherwise fall back to the
179
+ // configured default (when the operator has set `environments.k8s.workspace`
180
+ // in chroxy config). Resolved here so the backend always sees the final
181
+ // effective value and the manager remains the single wiring point.
182
+ const effectiveWorkspacePVC = workspacePVC !== undefined ? workspacePVC : (this._workspacePVCDefault ?? undefined)
183
+
184
+ const { containerId, containerCliPath } = await this._backend.createEnvironment({
185
+ envId: id,
186
+ cwd,
187
+ image: resolvedImage,
188
+ memoryLimit: resolvedMemory,
189
+ cpuLimit: resolvedCpu,
190
+ // #3195: structured K8s resource requests/limits, forwarded verbatim.
191
+ // Only K8sBackend acts on it; the manager does no shape validation
192
+ // (that lives in K8sBackend.buildResourceBlock). undefined → backend defaults.
193
+ resources,
194
+ containerUser: user,
195
+ containerEnv: validatedEnv,
196
+ forwardPorts: dcConfig.forwardPorts,
197
+ mounts: validatedMounts,
198
+ postCreateCommand: dcConfig.postCreateCommand,
199
+ // #4548: forward verbatim — only K8sBackend acts on this. Manager does no
200
+ // shape validation; that lives in K8sBackend.validateWorkspacePVC().
201
+ // #4556: `effectiveWorkspacePVC` resolves the caller-vs-config-default
202
+ // precedence so the backend sees a single value.
203
+ workspacePVC: effectiveWorkspacePVC,
204
+ })
205
+
206
+ const env = {
207
+ id,
208
+ name: name.trim(),
209
+ cwd: cwd.trim(),
210
+ image: resolvedImage,
211
+ containerId,
212
+ containerUser: user,
213
+ containerCliPath,
214
+ status: 'running',
215
+ sessions: [],
216
+ createdAt: new Date().toISOString(),
217
+ memoryLimit: resolvedMemory,
218
+ cpuLimit: resolvedCpu,
219
+ compose: null,
220
+ composeProject: null,
221
+ }
222
+
223
+ this._environments.set(id, env)
224
+ this._persist()
225
+ this.emit('environment_created', env)
226
+ log.info(`Environment "${name}" created (container: ${containerId.slice(0, 12)})`)
227
+ return env
228
+ }
229
+
230
+ /**
231
+ * Create a Compose-backed environment.
232
+ * Starts all services via docker compose, identifies the primary container,
233
+ * sets up the non-root user, and installs Claude Code.
234
+ */
235
+ async _createComposeEnvironment({ id, name, cwd, user, compose, primaryService, composeProject }) {
236
+ log.info(`Creating compose environment "${name}" (id: ${id}, compose: ${compose})`)
237
+
238
+ const { containerId, containerCliPath, services } = await this._backend.createComposeEnvironment({
239
+ envId: id,
240
+ cwd,
241
+ composeFile: compose,
242
+ composeProject,
243
+ containerUser: user,
244
+ primaryService,
245
+ })
246
+
247
+ const env = {
248
+ id,
249
+ name: name.trim(),
250
+ cwd: cwd.trim(),
251
+ image: 'compose',
252
+ containerId,
253
+ containerUser: user,
254
+ containerCliPath,
255
+ status: 'running',
256
+ sessions: [],
257
+ createdAt: new Date().toISOString(),
258
+ memoryLimit: null,
259
+ cpuLimit: null,
260
+ compose,
261
+ composeProject,
262
+ primaryService: primaryService || null,
263
+ services,
264
+ }
265
+
266
+ this._environments.set(id, env)
267
+ this._persist()
268
+ this.emit('environment_created', env)
269
+ log.info(`Compose environment "${name}" created (primary: ${containerId.slice(0, 12)}, services: ${services.length})`)
270
+ return env
271
+ }
272
+
273
+ /**
274
+ * Create a snapshot of a running environment via docker commit.
275
+ *
276
+ * @param {string} envId - Environment ID
277
+ * @param {Object} [opts]
278
+ * @param {string} [opts.name] - Human-readable snapshot name
279
+ * @returns {Promise<Object>} Snapshot metadata { id, name, image, createdAt }
280
+ */
281
+ async snapshot(envId, { name } = {}) {
282
+ const release = await this._acquireLock(envId)
283
+ try {
284
+ const env = this._getEnvironmentOrThrow(envId)
285
+ if (env.status !== 'running') throw new Error(`Environment "${env.name}" is not running (status: ${env.status})`)
286
+ const snapshotId = 'snap-' + randomBytes(8).toString('hex')
287
+ const timestamp = Date.now()
288
+ const imageTag = `chroxy-env:${envId}-${timestamp}`
289
+
290
+ log.info(`Creating snapshot "${name || snapshotId}" for environment "${env.name}"`)
291
+
292
+ await this._backend.commitEnvironment(env.containerId, imageTag)
293
+
294
+ const snap = {
295
+ id: snapshotId,
296
+ name: name || snapshotId,
297
+ image: imageTag,
298
+ createdAt: new Date().toISOString(),
299
+ }
300
+
301
+ if (!Array.isArray(env.snapshots)) {
302
+ env.snapshots = []
303
+ }
304
+ env.snapshots.push(snap)
305
+
306
+ this._persist()
307
+ this.emit('environment_snapshot', { envId, snapshot: snap })
308
+ log.info(`Snapshot "${snap.name}" created (image: ${imageTag})`)
309
+ return snap
310
+ } finally {
311
+ release()
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Restore an environment from a snapshot.
317
+ *
318
+ * Stops the current container and starts a new one from the snapshot image,
319
+ * preserving the same security constraints.
320
+ *
321
+ * @param {string} envId - Environment ID
322
+ * @param {string} snapshotId - Snapshot ID to restore
323
+ * @returns {Promise<Object>} Updated environment object
324
+ */
325
+ async restore(envId, snapshotId) {
326
+ const release = await this._acquireLock(envId)
327
+ try {
328
+ const env = this._getEnvironmentOrThrow(envId)
329
+
330
+ const snapshots = env.snapshots || []
331
+ const snap = snapshots.find(s => s.id === snapshotId)
332
+ if (!snap) throw new Error(`Snapshot not found: ${snapshotId}`)
333
+ log.info(`Restoring environment "${env.name}" from snapshot "${snap.name}"`)
334
+
335
+ const oldContainerId = env.containerId
336
+
337
+ // Rename old container so the new one can reuse the chroxy-env-{envId} name
338
+ await this._backend.renameEnvironment(oldContainerId, `chroxy-env-${envId}-old`)
339
+
340
+ // Start new container from snapshot BEFORE removing old one.
341
+ // Use restoreEnvironment (not createEnvironment) because the snapshot
342
+ // image already has the user, CLI, and workspace baked in — re-running
343
+ // full setup would fail on a pre-configured image.
344
+ const containerId = await this._backend.restoreEnvironment({
345
+ envId,
346
+ cwd: env.cwd,
347
+ image: snap.image,
348
+ memoryLimit: env.memoryLimit || DEFAULT_MEMORY_LIMIT,
349
+ cpuLimit: env.cpuLimit || DEFAULT_CPU_LIMIT,
350
+ })
351
+
352
+ // Health check: verify the new container is running
353
+ let healthy = false
354
+ try {
355
+ healthy = await this._backend.getEnvironmentStatus(containerId)
356
+ } catch (err) {
357
+ log.warn(`Restore health check inspect failed for container ${containerId.slice(0, 12)}: ${err.message}`)
358
+ }
359
+
360
+ if (!healthy) {
361
+ // New container failed — clean it up and preserve the old one
362
+ log.warn(`Restore health check failed for new container ${containerId.slice(0, 12)}, rolling back`)
363
+ await this._backend.destroyEnvironment(containerId)
364
+ throw new Error(`Restored container health check failed for environment "${env.name}"`)
365
+ }
366
+
367
+ // New container is healthy — remove the old one
368
+ await this._backend.destroyEnvironment(oldContainerId)
369
+
370
+ env.containerId = containerId
371
+ env.status = 'running'
372
+
373
+ this._persist()
374
+ this.emit('environment_restored', { envId, snapshotId, containerId })
375
+ log.info(`Environment "${env.name}" restored (container: ${containerId.slice(0, 12)})`)
376
+ return env
377
+ } finally {
378
+ release()
379
+ }
380
+ }
381
+
382
+ /**
383
+ * Destroy an environment and its container.
384
+ * @param {string} envId - Environment ID
385
+ */
386
+ async destroy(envId) {
387
+ const release = await this._acquireLock(envId)
388
+ try {
389
+ const env = this._getEnvironmentOrThrow(envId)
390
+ log.info(`Destroying environment "${env.name}" (${envId})`)
391
+
392
+ if (env.compose && env.composeProject) {
393
+ await this._backend.destroyComposeEnvironment({
394
+ composeFile: env.compose,
395
+ composeProject: env.composeProject,
396
+ cwd: env.cwd,
397
+ })
398
+ } else if (env.containerId) {
399
+ // #6134: remove the container whenever one exists — NOT only when
400
+ // status==='running'. Now that stop() makes 'stopped' a reachable state,
401
+ // gating on 'running' would orphan a stopped container (the manager
402
+ // entry is deleted but `docker rm -f` never runs). `docker rm -f` works
403
+ // on stopped/exited containers too, and _removeContainer swallows a
404
+ // "no such container" for one that never started.
405
+ await this._backend.destroyEnvironment(env.containerId)
406
+ }
407
+
408
+ // Clean up snapshot images
409
+ if (Array.isArray(env.snapshots)) {
410
+ for (const snap of env.snapshots) {
411
+ await this._backend.removeImage(snap.image)
412
+ }
413
+ }
414
+
415
+ this._environments.delete(envId)
416
+ this._persist()
417
+ this.emit('environment_destroyed', { id: envId, name: env.name })
418
+ log.info(`Environment "${env.name}" destroyed`)
419
+ } finally {
420
+ release()
421
+ }
422
+ }
423
+
424
+ /**
425
+ * #6134 — stop a running standalone environment's container (the backing
426
+ * container survives, so it can be restarted). Returns the resulting status.
427
+ * No-op (returns the current status) when the environment is already stopped.
428
+ *
429
+ * Compose environments are not supported yet (a compose stack needs
430
+ * `docker compose stop`, tracked as a follow-up) — they throw. Backends that
431
+ * don't implement the lifecycle (k8s/rancher today) throw a clear error that
432
+ * the handler surfaces as CONTAINER_ACTION_FAILED.
433
+ */
434
+ async stop(envId) {
435
+ const release = await this._acquireLock(envId)
436
+ try {
437
+ const env = this._getEnvironmentOrThrow(envId)
438
+ if (env.compose) throw new Error(`Stop is not supported for compose environments yet`)
439
+ if (!env.containerId) throw new Error(`Environment "${env.name}" has no container to stop`)
440
+ if (typeof this._backend.stopEnvironment !== 'function') {
441
+ throw new Error(`Stop is not supported on this environment backend`)
442
+ }
443
+ if (env.status !== 'running') return env.status
444
+ log.info(`Stopping environment "${env.name}" (${envId})`)
445
+ await this._backend.stopEnvironment(env.containerId)
446
+ env.status = 'stopped'
447
+ this._persist()
448
+ this.emit('environment_stopped', { id: envId, name: env.name })
449
+ return env.status
450
+ } finally {
451
+ release()
452
+ }
453
+ }
454
+
455
+ /**
456
+ * #6134 — restart a standalone environment's container (works whether it is
457
+ * currently running or stopped; ends running). Returns the resulting status.
458
+ * Same compose / backend-support constraints as {@link stop}.
459
+ */
460
+ async restart(envId) {
461
+ const release = await this._acquireLock(envId)
462
+ try {
463
+ const env = this._getEnvironmentOrThrow(envId)
464
+ if (env.compose) throw new Error(`Restart is not supported for compose environments yet`)
465
+ if (!env.containerId) throw new Error(`Environment "${env.name}" has no container to restart`)
466
+ if (typeof this._backend.restartEnvironment !== 'function') {
467
+ throw new Error(`Restart is not supported on this environment backend`)
468
+ }
469
+ log.info(`Restarting environment "${env.name}" (${envId})`)
470
+ await this._backend.restartEnvironment(env.containerId)
471
+ env.status = 'running'
472
+ this._persist()
473
+ this.emit('environment_restarted', { id: envId, name: env.name })
474
+ return env.status
475
+ } finally {
476
+ release()
477
+ }
478
+ }
479
+
480
+ /**
481
+ * List all environments.
482
+ * @returns {Object[]} Array of environment objects
483
+ */
484
+ list() {
485
+ return Array.from(this._environments.values())
486
+ }
487
+
488
+ /**
489
+ * Get a single environment by ID.
490
+ * @param {string} envId
491
+ * @returns {Object|null}
492
+ */
493
+ get(envId) {
494
+ return this._environments.get(envId) || null
495
+ }
496
+
497
+ /**
498
+ * Get container details for session creation.
499
+ * @param {string} envId
500
+ * @returns {{ containerId: string, containerUser: string, containerCliPath: string }}
501
+ */
502
+ getContainerInfo(envId) {
503
+ const env = this._getEnvironmentOrThrow(envId)
504
+ if (env.status !== 'running') throw new Error(`Environment "${env.name}" is not running (status: ${env.status})`)
505
+ return {
506
+ containerId: env.containerId,
507
+ containerUser: env.containerUser,
508
+ containerCliPath: env.containerCliPath,
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Track a session connecting to an environment.
514
+ * @param {string} envId
515
+ * @param {string} sessionId
516
+ */
517
+ addSession(envId, sessionId) {
518
+ const env = this._environments.get(envId)
519
+ if (!env) return
520
+ if (!env.sessions.includes(sessionId)) {
521
+ env.sessions.push(sessionId)
522
+ this._persist()
523
+ }
524
+ }
525
+
526
+ /**
527
+ * Track a session disconnecting from an environment.
528
+ * @param {string} envId
529
+ * @param {string} sessionId
530
+ */
531
+ removeSession(envId, sessionId) {
532
+ const env = this._environments.get(envId)
533
+ if (!env) return
534
+ env.sessions = env.sessions.filter(s => s !== sessionId)
535
+ this._persist()
536
+ }
537
+
538
+ /**
539
+ * Reconnect to persisted environments on server restart.
540
+ * Inspects each saved container and updates its status.
541
+ *
542
+ * INVARIANT (#3492): every code path that flips `allHealthy = false` MUST
543
+ * also set `env.status` to a value in `UNREACHABLE_STATUSES` (currently
544
+ * `'error'` or `'stopped'`). The set is consumed by the boot-path
545
+ * aggregate-warn helper in
546
+ * `server-cli.js#logEnvironmentManagerReconnectResult`, which derives the
547
+ * unreachable count via
548
+ * `list().filter(e => UNREACHABLE_STATUSES.has(e.status)).length`. A future
549
+ * contributor adding a new `allHealthy = false` branch (quotas,
550
+ * partial-restore, metrics check, …) without a co-located unreachable
551
+ * status assignment would silently undercount and emit
552
+ * `0 environment(s) unreachable` at boot. If a new unreachable status is
553
+ * introduced (beyond `'error'`/`'stopped'`) it MUST be added to
554
+ * `UNREACHABLE_STATUSES` so the aggregate warn stays accurate. The
555
+ * invariant guard test in `tests/environment-manager.test.js` will fail CI
556
+ * if the count of `allHealthy = false` branches drifts from the count of
557
+ * unreachable status assignments.
558
+ *
559
+ * @returns {Promise<boolean>} `true` if every environment reconnected
560
+ * successfully; `false` if at least one environment was marked unreachable.
561
+ * An environment is considered unreachable when any of the following hold:
562
+ * - it has no `containerId` (status set to `'error'`)
563
+ * - `getEnvironmentStatus` reports the container is stopped (status set to `'stopped'`)
564
+ * - `getEnvironmentStatus` throws (status set to `'error'`)
565
+ * - `reconnectAgentToken` returns any non-`true` value, e.g. `false`
566
+ * (credential source GC'd) or `undefined` / `null` from a misbehaving
567
+ * backend (#3495) — status set to `'error'`
568
+ * - `reconnectAgentToken` throws (status set to `'error'`)
569
+ */
570
+ async reconnect() {
571
+ this._restore()
572
+ if (this._environments.size === 0) return true
573
+
574
+ log.info(`Reconnecting to ${this._environments.size} persisted environment(s)`)
575
+
576
+ let allHealthy = true
577
+
578
+ for (const env of this._environments.values()) {
579
+ // Clear stale session references unconditionally — in-memory session
580
+ // state never survives a server restart, regardless of whether the
581
+ // environment's container is reachable, stopped, or has no containerId
582
+ // at all. (#3494: this used to live at the bottom of the loop body and
583
+ // was skipped by the no-containerId `continue` below.)
584
+ env.sessions = []
585
+
586
+ if (!env.containerId) {
587
+ // Invariant: allHealthy=false co-located with unreachable status (#3492)
588
+ env.status = 'error'
589
+ allHealthy = false
590
+ continue
591
+ }
592
+ try {
593
+ const running = await this._backend.getEnvironmentStatus(env.containerId)
594
+ if (running) {
595
+ env.status = 'running'
596
+ log.info(`Environment "${env.name}" reconnected (container: ${env.containerId.slice(0, 12)})`)
597
+ } else {
598
+ // Invariant: allHealthy=false co-located with unreachable status (#3492).
599
+ // 'stopped' is in UNREACHABLE_STATUSES — see the boot-path aggregate
600
+ // warn in server-cli.js#logEnvironmentManagerReconnectResult.
601
+ env.status = 'stopped'
602
+ allHealthy = false
603
+ log.warn(`Environment "${env.name}" (id: ${env.id}) container is stopped`)
604
+ }
605
+ } catch (err) {
606
+ // Invariant: allHealthy=false co-located with unreachable status (#3492)
607
+ env.status = 'error'
608
+ allHealthy = false
609
+ log.warn(`Environment "${env.name}" (id: ${env.id}) container inspect failed: ${err.message}`)
610
+ }
611
+ // For backends that hold per-environment credentials in memory (e.g.
612
+ // K8sBackend._agentTokens), re-populate them from the canonical source
613
+ // so that streamCliInEnvironment() works after a server restart.
614
+ //
615
+ // Per the Backend JSDoc, reconnectAgentToken returns:
616
+ // true — credential found and cached; environment is usable
617
+ // false — credential source is gone (Pod/Secret GC'd); the environment
618
+ // is unreachable and must be marked accordingly so future
619
+ // streamCliInEnvironment calls don't fail without warning.
620
+ //
621
+ // A thrown error is treated as the same unreachable signal as returning
622
+ // false (#3478): the operator cannot rely on the credential, so the
623
+ // environment must be marked error and reconnect() must report failure.
624
+ //
625
+ // Defensive (#3495): treat any non-`true` return (including `undefined` /
626
+ // `null` from a misbehaving or future backend) as the same unreachable
627
+ // signal. The contract is "strict `=== true` for success" — a missing
628
+ // credential is just as unusable as `false`.
629
+ if (typeof this._backend.reconnectAgentToken === 'function') {
630
+ try {
631
+ const ok = await this._backend.reconnectAgentToken(env.containerId)
632
+ if (ok !== true) {
633
+ // Invariant: allHealthy=false co-located with unreachable status (#3492)
634
+ env.status = 'error'
635
+ allHealthy = false
636
+ log.warn(`Environment "${env.name}" (id: ${env.id}) credential source is gone — marking unreachable`)
637
+ }
638
+ } catch (err) {
639
+ // Invariant: allHealthy=false co-located with unreachable status (#3492)
640
+ env.status = 'error'
641
+ allHealthy = false
642
+ log.warn(`Environment "${env.name}" (id: ${env.id}) token refresh failed: ${err.message}`)
643
+ }
644
+ }
645
+ }
646
+
647
+ this._persist()
648
+ this.emit('environments_reconnected', this.list())
649
+ return allHealthy
650
+ }
651
+
652
+ /**
653
+ * Reconcile running containers against the registry.
654
+ * Enumerates all `chroxy-env-*` containers and stops any that are not
655
+ * tracked in the environment registry. Best-effort — failures are logged
656
+ * but do not throw.
657
+ */
658
+ async reconcile() {
659
+ let containerIds
660
+ try {
661
+ containerIds = await this._backend.listEnvironments()
662
+ } catch (err) {
663
+ log.warn(`Reconcile: failed to list containers: ${err.message}`)
664
+ return
665
+ }
666
+
667
+ const knownIds = new Set()
668
+ for (const env of this._environments.values()) {
669
+ if (env.containerId) knownIds.add(env.containerId)
670
+ }
671
+
672
+ const orphans = containerIds.filter(id => !knownIds.has(id))
673
+ if (orphans.length === 0) return
674
+
675
+ log.info(`Reconcile: found ${orphans.length} orphaned container(s), removing`)
676
+ for (const id of orphans) {
677
+ log.info(`Reconcile: removing orphaned container ${id.slice(0, 12)}`)
678
+ await this._backend.destroyEnvironment(id)
679
+ }
680
+ }
681
+
682
+ // ──────────────────────────────────────────────────────────────────────────
683
+ // Backward-compat delegation shim
684
+ //
685
+ // Tests that call manager._composeServices() directly (graceful degradation
686
+ // tests) continue to work via this thin delegation to the backend.
687
+ // No other Docker-specific private methods live here — they have all moved
688
+ // to DockerBackend in packages/server/src/environments/backends/docker.js.
689
+ // ──────────────────────────────────────────────────────────────────────────
690
+
691
+ /**
692
+ * @deprecated Call via this._backend instead. Kept for test backward-compat.
693
+ */
694
+ _composeServices(project) {
695
+ return this._backend._composeServices(project)
696
+ }
697
+
698
+ // ──────────────────────────────────────────────────────────────────────────
699
+ // DevContainer support
700
+ //
701
+ // Parsing and validation helpers live in `devcontainer-config.js` as pure
702
+ // functions so the persistent-environment `create()` path here and the
703
+ // per-session DockerByokSession path share one source of truth (#5077).
704
+ // Call sites: `parseDevContainer` / `validateMounts` / `sanitizeContainerEnv`
705
+ // are invoked from `create()` above.
706
+ // ──────────────────────────────────────────────────────────────────────────
707
+
708
+ // ──────────────────────────────────────────────────────────────────────────
709
+ // Persistence
710
+ // ──────────────────────────────────────────────────────────────────────────
711
+
712
+ _persist() {
713
+ try {
714
+ const dir = dirname(this._statePath)
715
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
716
+
717
+ const data = {
718
+ version: 1,
719
+ environments: Array.from(this._environments.values()),
720
+ }
721
+
722
+ // writeFileRestricted is atomic on both POSIX (#4850) and Windows
723
+ // (#4913) and cleans up its intermediate `.tmp` on rename failure
724
+ // (#4874) — no manual tmp+rename wrapper needed here. The
725
+ // pre-#4874 unlinkSync(EEXIST) workaround is no longer required
726
+ // since Node's renameSync uses MoveFileExW(REPLACE_EXISTING) on
727
+ // Windows.
728
+ writeFileRestricted(this._statePath, JSON.stringify(data, null, 2))
729
+ } catch (err) {
730
+ log.error(`Failed to persist environment state: ${err.message}`)
731
+ }
732
+ }
733
+
734
+ _restore() {
735
+ if (!existsSync(this._statePath)) return
736
+
737
+ try {
738
+ const data = JSON.parse(readFileSync(this._statePath, 'utf-8'))
739
+ if (data.version !== 1 || !Array.isArray(data.environments)) {
740
+ log.warn('Invalid environment state file, ignoring')
741
+ return
742
+ }
743
+ for (const env of data.environments) {
744
+ if (env.id) {
745
+ this._environments.set(env.id, env)
746
+ }
747
+ }
748
+ log.info(`Restored ${this._environments.size} environment(s) from disk`)
749
+ } catch (err) {
750
+ log.error(`Failed to restore environment state: ${err.message}`)
751
+ }
752
+ }
753
+ }