@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,3030 @@
1
+ import { createHash, randomBytes } from 'crypto'
2
+ import { EventEmitter } from 'events'
3
+ import { PassThrough } from 'stream'
4
+ import { KubeConfig, CoreV1Api, PortForward } from '@kubernetes/client-node'
5
+ import WebSocket from 'ws'
6
+ import { createLogger } from '../../logger.js'
7
+
8
+ const log = createLogger('k8s-backend')
9
+
10
+ const POLL_INTERVAL_MS = 1_000
11
+ const DESTROY_TIMEOUT_MS = 30_000
12
+
13
+ // Reconnect parameters for SidecarProcess WS blip recovery (#3321).
14
+ // These are the defaults; inject overrides via constructor opts for tests.
15
+ const DEFAULT_RECONNECT_DELAYS = [250, 500, 1_000, 2_000, 4_000, 8_000]
16
+ const DEFAULT_MAX_RETRIES = 5
17
+
18
+ /**
19
+ * Cap on bytes held in `_stdinBuffer` before the WS dial resolves (#3401).
20
+ * If the dial hangs (slow cluster, DNS failure) and the caller is piping
21
+ * large stdin payloads, an unbounded buffer would grow until the server
22
+ * OOMs. Writes that would push the buffer past the cap are dropped with
23
+ * a warning. 1 MiB is generous for a few large prompts but bounds the
24
+ * worst-case memory hold at one process-worth.
25
+ */
26
+ const DEFAULT_MAX_STDIN_BUFFER_BYTES = 1 * 1024 * 1024 // 1 MiB
27
+
28
+ /** Default sidecar image — overridden via constructor option */
29
+ const DEFAULT_SIDECAR_IMAGE = 'chroxy-pod-agent:latest'
30
+
31
+ /** Port the chroxy-pod-agent sidecar listens on inside the Pod */
32
+ const AGENT_PORT = 7681
33
+
34
+ /**
35
+ * Default resource requests/limits applied to the sidecar container when a
36
+ * createEnvironment call does not specify its own (#3195).
37
+ *
38
+ * Requests are what the scheduler reserves (and what the pod is guaranteed);
39
+ * limits are the hard ceiling the kernel/cgroup enforces. The defaults keep a
40
+ * single runaway session from starving the node while leaving generous
41
+ * headroom for a real Claude Code workload:
42
+ * - request 500m CPU / 512Mi memory — modest reservation so several
43
+ * environments can be packed onto one node.
44
+ * - limit 2 CPU / 4Gi memory — a session may burst well above its
45
+ * request but is capped before it can consume the whole node.
46
+ *
47
+ * Operators override any field per-call via `opts.resources` (or the legacy
48
+ * `opts.memoryLimit`/`opts.cpuLimit`); see createEnvironment's JSDoc.
49
+ */
50
+ export const DEFAULT_RESOURCES = Object.freeze({
51
+ cpu: '500m',
52
+ memory: '512Mi',
53
+ cpuLimit: '2',
54
+ memoryLimit: '4Gi',
55
+ })
56
+
57
+ /**
58
+ * Default container CLI path — used to remap the host's absolute cli.js path
59
+ * (passed by the SDK as args[0]) to a path that exists inside the Pod.
60
+ * Mirrors DEFAULT_CONTAINER_CLI_PATH in docker.js.
61
+ */
62
+ const DEFAULT_CONTAINER_CLI_PATH = '/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js'
63
+
64
+ // Per-method deferral tracking: each stub points to the issue/phase that owns it.
65
+ // Keep this in sync with the Backend interface (types.js) and the K8s phase plan in #3191.
66
+ // Note: renameEnvironment is intentionally absent — it is a documented no-op on K8s (see types.js).
67
+ const NOT_IMPLEMENTED_REASON = {
68
+ createComposeEnvironment: 'N/A for K8s — compose is a Docker-only concept',
69
+ destroyComposeEnvironment: 'N/A for K8s — compose is a Docker-only concept',
70
+ removeImage: 'N/A for K8s — image lifecycle is owned by the cluster registry/CRI',
71
+ commitEnvironment: 'deferred to Phase 2',
72
+ restoreEnvironment: 'deferred to Phase 2',
73
+ }
74
+
75
+ function notImplemented(method) {
76
+ const reason = NOT_IMPLEMENTED_REASON[method] || 'deferred to a later phase'
77
+ const err = new Error(`K8sBackend.${method} is not implemented in Phase 1 — ${reason}`)
78
+ err.name = 'NotImplementedError'
79
+ return err
80
+ }
81
+
82
+ /** Valid Kubernetes imagePullPolicy values */
83
+ const VALID_PULL_POLICIES = new Set(['Always', 'IfNotPresent', 'Never'])
84
+
85
+ /**
86
+ * Validates an imagePullPolicy value. Throws TypeError for unrecognised strings.
87
+ * Passes through null/undefined (meaning: omit the field, let K8s apply its default).
88
+ *
89
+ * @param {string|null|undefined} value
90
+ * @param {string} context - Describes where the value came from (for the error message)
91
+ */
92
+ function validateImagePullPolicy(value, context) {
93
+ if (value == null) return
94
+ if (!VALID_PULL_POLICIES.has(value)) {
95
+ throw new TypeError(
96
+ `K8sBackend: invalid imagePullPolicy "${value}" in ${context} — ` +
97
+ `must be one of: Always, IfNotPresent, Never`
98
+ )
99
+ }
100
+ }
101
+
102
+ /**
103
+ * RFC 1123 label regex: lowercase alphanumeric, '-' allowed in the middle,
104
+ * must start and end with an alphanumeric character.
105
+ * 1 char → [a-z0-9]
106
+ * ≥2 chars → [a-z0-9] + 0..n of ([a-z0-9-]) + [a-z0-9]
107
+ * Length is checked separately so the error message can distinguish
108
+ * "too long" from "bad characters".
109
+ */
110
+ const RFC_1123_LABEL = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/
111
+
112
+ /** RFC 1123 label maximum length (per the spec; K8s namespace == DNS label). */
113
+ const RFC_1123_MAX_LENGTH = 63
114
+
115
+ /**
116
+ * Validates a Kubernetes namespace string against the RFC 1123 DNS label rules
117
+ * the API server enforces. Layered on top of `_resolveNamespace()` so all five
118
+ * per-call resolution sites gain validation atomically (#3571).
119
+ *
120
+ * Rules enforced:
121
+ * - Must be a non-empty string
122
+ * - Length 1..63 characters
123
+ * - Lowercase alphanumeric and hyphens only
124
+ * - First and last character must be alphanumeric
125
+ *
126
+ * Throws Error with a `${context}:` prefix so the caller can identify which
127
+ * Backend method observed the invalid namespace (mirrors validateImagePullPolicy).
128
+ *
129
+ * @param {*} ns - Resolved namespace value
130
+ * @param {string} context - Method name / call site label for the error message
131
+ * @returns {string} The validated namespace (returned for convenient one-line use)
132
+ * @throws {Error} If `ns` is not a non-empty RFC 1123 label
133
+ */
134
+ function validateNamespace(ns, context) {
135
+ if (typeof ns !== 'string' || ns.length === 0) {
136
+ throw new Error(`${context}: namespace must be a non-empty string`)
137
+ }
138
+ if (ns.length > RFC_1123_MAX_LENGTH) {
139
+ throw new Error(
140
+ `${context}: namespace "${ns}" exceeds ${RFC_1123_MAX_LENGTH}-char RFC 1123 limit`
141
+ )
142
+ }
143
+ if (!RFC_1123_LABEL.test(ns)) {
144
+ throw new Error(
145
+ `${context}: namespace "${ns}" must match RFC 1123 label format ` +
146
+ '(lowercase alphanumeric and hyphens, start/end alphanumeric)'
147
+ )
148
+ }
149
+ return ns
150
+ }
151
+
152
+ /**
153
+ * Static prefix for per-user/per-project namespaces derived by the default
154
+ * mapping function (#3194). Kept short so the sanitized identity gets the
155
+ * lion's share of the 63-char RFC 1123 budget.
156
+ */
157
+ const DEFAULT_NAMESPACE_PREFIX = 'chroxy-user-'
158
+
159
+ /**
160
+ * Sanitize an arbitrary identity string (userId / projectId) into a fragment
161
+ * safe to splice into an RFC 1123 DNS label (#3194).
162
+ *
163
+ * Multi-tenant safety: the namespace is the tenant-isolation boundary, so the
164
+ * sanitizer must be *deterministic* (the same identity always maps to the same
165
+ * namespace) and *collision-resistant* (distinct identities should not silently
166
+ * collapse onto the same namespace and thereby share another tenant's Pods).
167
+ *
168
+ * Transform:
169
+ * - Lowercase (RFC 1123 labels are lowercase only).
170
+ * - Replace every run of disallowed characters with a single '-'.
171
+ * - Strip leading/trailing '-' so the fragment starts/ends alphanumeric.
172
+ *
173
+ * Collision handling: because the lossy character replacement above can map two
174
+ * different identities onto the same fragment (e.g. `a.b` and `a/b` → `a-b`), a
175
+ * short deterministic hash of the ORIGINAL identity is appended whenever the
176
+ * sanitized fragment differs from the input or has to be truncated. Two
177
+ * identities that sanitize identically will therefore still produce different
178
+ * namespaces (their hashes differ), preserving tenant isolation.
179
+ *
180
+ * Length: the returned fragment is capped at `maxLength` (default 50) leaving
181
+ * headroom for the caller's prefix; the hash suffix is included within the cap.
182
+ *
183
+ * @param {string} identity - Raw identity (userId or projectId)
184
+ * @param {Object} [opts]
185
+ * @param {number} [opts.maxLength=50] - Max length of the returned fragment
186
+ * @returns {string} An RFC 1123-label-safe fragment (non-empty)
187
+ * @throws {Error} If `identity` is not a non-empty string
188
+ */
189
+ export function sanitizeNamespaceLabel(identity, { maxLength = 50 } = {}) {
190
+ if (typeof identity !== 'string' || identity.length === 0) {
191
+ throw new Error('sanitizeNamespaceLabel: identity must be a non-empty string')
192
+ }
193
+
194
+ const lowered = identity.toLowerCase()
195
+ // Collapse every run of non-[a-z0-9] into a single '-', then trim '-' ends.
196
+ let fragment = lowered.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
197
+
198
+ // A short deterministic hash of the ORIGINAL identity disambiguates two
199
+ // identities that sanitize to the same fragment (lossy replacement) and two
200
+ // that share a truncated prefix. 8 hex chars (32 bits) is ample for the
201
+ // expected tenant cardinality and keeps the suffix compact.
202
+ const hash = createHash('sha256').update(identity).digest('hex').slice(0, 8)
203
+
204
+ // Decide whether disambiguation is needed: the sanitize step lost information
205
+ // (the result differs from the ORIGINAL identity — this also catches case
206
+ // folding, so `alice` and `Alice` map to different namespaces), the fragment
207
+ // is empty (all-symbol identity), or the raw fragment exceeds the budget.
208
+ const needsHash = fragment.length === 0 ||
209
+ fragment !== identity ||
210
+ fragment.length > maxLength
211
+
212
+ if (!needsHash) {
213
+ return fragment
214
+ }
215
+
216
+ // Reserve room for "-<hash>" within maxLength, then re-trim any '-' the
217
+ // truncation may have exposed at the boundary.
218
+ const suffix = `-${hash}`
219
+ // When maxLength is too small to hold even "<1char>-<hash>", drop the fragment
220
+ // entirely and return the hash truncated to maxLength. This keeps the
221
+ // documented length cap a hard guarantee (the `head + suffix` path below would
222
+ // otherwise overshoot for pathologically small maxLength values). The hash is
223
+ // [a-f0-9], so any prefix of it is still a valid RFC 1123 label.
224
+ if (maxLength <= suffix.length) {
225
+ return hash.slice(0, Math.max(1, maxLength))
226
+ }
227
+ const budget = maxLength - suffix.length
228
+ const head = fragment.slice(0, budget).replace(/-+$/g, '')
229
+ // `head` can be empty when the identity was all symbols; fall back to the
230
+ // hash alone (always [a-f0-9], a valid label).
231
+ return head.length > 0 ? `${head}${suffix}` : hash
232
+ }
233
+
234
+ /**
235
+ * Default namespace mapping function (#3194).
236
+ *
237
+ * Maps a per-call identity to a Kubernetes namespace name:
238
+ * - `userId` → `chroxy-user-<sanitized-userId>`
239
+ * - `projectId` (no userId) → `chroxy-user-<sanitized-projectId>`
240
+ * - neither → `null` (caller falls back to the static default namespace)
241
+ *
242
+ * The result is validated by `validateNamespace()` at the call site, so this
243
+ * function only needs to produce a candidate; the sanitizer guarantees a valid
244
+ * RFC 1123 label fragment and the short prefix keeps the total within 63 chars.
245
+ *
246
+ * @param {Object} identity
247
+ * @param {string} [identity.userId] - User identity
248
+ * @param {string} [identity.projectId] - Project identity (used when no userId)
249
+ * @returns {string|null} Namespace name, or null when no identity was supplied
250
+ */
251
+ function defaultNamespaceFor({ userId, projectId } = {}) {
252
+ const id = (typeof userId === 'string' && userId.length > 0)
253
+ ? userId
254
+ : (typeof projectId === 'string' && projectId.length > 0 ? projectId : null)
255
+ if (id == null) return null
256
+ // Reserve the prefix length out of the 63-char budget for the fragment.
257
+ const maxLength = RFC_1123_MAX_LENGTH - DEFAULT_NAMESPACE_PREFIX.length
258
+ return `${DEFAULT_NAMESPACE_PREFIX}${sanitizeNamespaceLabel(id, { maxLength })}`
259
+ }
260
+
261
+ /**
262
+ * Validate `opts.workspacePVC` for createEnvironment (#3385).
263
+ *
264
+ * Accepts:
265
+ * - `undefined` / `null` — no PVC workspace requested (caller will fall back
266
+ * to the hostPath strategy via opts.cwd, or no workspace at all).
267
+ * - `{ claimName: string, mountPath?: string, readOnly?: boolean }` — operator
268
+ * opts into the PVC strategy. `claimName` is required and must be a
269
+ * non-empty string.
270
+ *
271
+ * Also enforces the mutual exclusion with `opts.cwd` (hostPath strategy):
272
+ * passing both is an operator-intent ambiguity, not a fallback chain.
273
+ *
274
+ * @param {*} workspacePVC - Raw opts.workspacePVC value
275
+ * @param {*} cwd - opts.cwd value (for mutual-exclusion check)
276
+ * @throws {Error} If the value is malformed or both strategies are passed.
277
+ */
278
+ function validateWorkspacePVC(workspacePVC, cwd) {
279
+ if (workspacePVC == null) return
280
+ if (typeof workspacePVC !== 'object' || Array.isArray(workspacePVC)) {
281
+ throw new Error(
282
+ 'createEnvironment: opts.workspacePVC must be an object with a claimName property',
283
+ )
284
+ }
285
+ if (typeof workspacePVC.claimName !== 'string' || workspacePVC.claimName.length === 0) {
286
+ throw new Error(
287
+ 'createEnvironment: opts.workspacePVC.claimName must be a non-empty string',
288
+ )
289
+ }
290
+ if (cwd != null && cwd !== '') {
291
+ throw new Error(
292
+ 'createEnvironment: opts.cwd and opts.workspacePVC are mutually exclusive — ' +
293
+ 'choose either the hostPath strategy (opts.cwd, single-node clusters) ' +
294
+ 'or the PVC strategy (opts.workspacePVC, multi-node clusters), not both',
295
+ )
296
+ }
297
+ }
298
+
299
+ /** Default git image used by the clone init container — overridable via opts. */
300
+ const DEFAULT_GIT_IMAGE = 'alpine/git:latest'
301
+
302
+ /** Default mount path the workspace volume is exposed at inside the Pod. */
303
+ const DEFAULT_WORKSPACE_MOUNT_PATH = '/workspace'
304
+
305
+ /**
306
+ * Reject argv values that git would interpret as an option rather than a
307
+ * positional argument (argument-injection hardening, #3193).
308
+ *
309
+ * git-clone argv is NOT passed through a shell — the init container runs
310
+ * `command: ['git']` with an explicit `args` array — so classic shell
311
+ * metacharacter injection (`;`, `|`, `$()`, backticks) is structurally
312
+ * impossible. The residual risk is *argument* injection: a value beginning
313
+ * with `-` (e.g. `--upload-pack=…`, `--config=…`) would be parsed by git as a
314
+ * flag. We reject any value whose first character is `-`; the clone argv also
315
+ * uses `--` to terminate option parsing as belt-and-braces.
316
+ *
317
+ * @param {string} value
318
+ * @param {string} field - Field name for the error message
319
+ * @throws {Error} If the value starts with '-'
320
+ */
321
+ function rejectGitOptionLike(value, field) {
322
+ if (typeof value === 'string' && value.startsWith('-')) {
323
+ throw new Error(
324
+ `createEnvironment: opts.gitRepo.${field} must not start with "-" ` +
325
+ '(rejected to prevent git argument injection)',
326
+ )
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Validate + normalise `opts.gitRepo` for createEnvironment (#3193).
332
+ *
333
+ * The git-clone workspace strategy (Phase 1) provisions the Pod's workspace by
334
+ * cloning a repo into an `emptyDir` volume via an init container, instead of
335
+ * mounting a host path (`opts.cwd`) or referencing a pre-provisioned PVC
336
+ * (`opts.workspacePVC`). It is the K8s-native answer to "the pod is on a remote
337
+ * node and can't see the operator's filesystem" without requiring an
338
+ * out-of-band PVC seed step.
339
+ *
340
+ * Accepts:
341
+ * - `undefined` / `null` — git-clone strategy not requested.
342
+ * - A non-empty string — shorthand for `{ url: <string> }`.
343
+ * - `{ url, branch?, commit?, depth?, mountPath? }` — `url` is required and
344
+ * must be a non-empty string. `branch` / `commit` pin the checkout. `depth`
345
+ * (positive integer) requests a shallow clone. `mountPath` overrides the
346
+ * pod-side mount (default `/workspace`).
347
+ *
348
+ * Enforces mutual exclusion with the other two workspace strategies (`opts.cwd`
349
+ * and `opts.workspacePVC`): exactly one strategy may be chosen. The alternative
350
+ * — a silent precedence rule — would hide operator intent.
351
+ *
352
+ * branch + commit may both be supplied: git supports `clone --branch <branch>`
353
+ * followed by a `checkout <commit>`, so the clone fetches the branch tip and a
354
+ * second step pins the exact commit.
355
+ *
356
+ * @param {*} gitRepo - Raw opts.gitRepo value
357
+ * @param {*} cwd - opts.cwd value (mutual-exclusion check)
358
+ * @param {*} workspacePVC - opts.workspacePVC value (mutual-exclusion check)
359
+ * @returns {{ url: string, branch: string|null, commit: string|null, depth: number|null, mountPath: string }|null}
360
+ * Normalised descriptor, or null when no git-clone strategy was requested.
361
+ * @throws {Error} If the value is malformed or conflicts with another strategy.
362
+ */
363
+ function validateGitRepo(gitRepo, cwd, workspacePVC) {
364
+ if (gitRepo == null) return null
365
+
366
+ // Normalise the string shorthand to the object form.
367
+ const spec = typeof gitRepo === 'string' ? { url: gitRepo } : gitRepo
368
+
369
+ if (typeof spec !== 'object' || Array.isArray(spec)) {
370
+ throw new Error(
371
+ 'createEnvironment: opts.gitRepo must be a non-empty URL string or ' +
372
+ 'an object with a url property',
373
+ )
374
+ }
375
+ if (typeof spec.url !== 'string' || spec.url.length === 0) {
376
+ throw new Error(
377
+ 'createEnvironment: opts.gitRepo.url must be a non-empty string',
378
+ )
379
+ }
380
+ rejectGitOptionLike(spec.url, 'url')
381
+
382
+ if (spec.branch != null) {
383
+ if (typeof spec.branch !== 'string' || spec.branch.length === 0) {
384
+ throw new Error('createEnvironment: opts.gitRepo.branch must be a non-empty string')
385
+ }
386
+ rejectGitOptionLike(spec.branch, 'branch')
387
+ }
388
+
389
+ if (spec.commit != null) {
390
+ if (typeof spec.commit !== 'string' || spec.commit.length === 0) {
391
+ throw new Error('createEnvironment: opts.gitRepo.commit must be a non-empty string')
392
+ }
393
+ rejectGitOptionLike(spec.commit, 'commit')
394
+ }
395
+
396
+ let depth = null
397
+ if (spec.depth != null) {
398
+ if (!Number.isInteger(spec.depth) || spec.depth < 1) {
399
+ throw new Error('createEnvironment: opts.gitRepo.depth must be a positive integer')
400
+ }
401
+ depth = spec.depth
402
+ }
403
+
404
+ let mountPath = DEFAULT_WORKSPACE_MOUNT_PATH
405
+ if (spec.mountPath != null) {
406
+ if (typeof spec.mountPath !== 'string' || spec.mountPath.length === 0) {
407
+ throw new Error('createEnvironment: opts.gitRepo.mountPath must be a non-empty string')
408
+ }
409
+ // K8s requires volumeMount.mountPath to be absolute; a relative value would
410
+ // be rejected at Pod-create time with an opaque API error. Reject `.`/`..`
411
+ // segments too so the path can't escape the intended workspace root.
412
+ if (!spec.mountPath.startsWith('/')) {
413
+ throw new Error(
414
+ 'createEnvironment: opts.gitRepo.mountPath must be an absolute path (start with "/")',
415
+ )
416
+ }
417
+ if (spec.mountPath.split('/').some((seg) => seg === '.' || seg === '..')) {
418
+ throw new Error(
419
+ 'createEnvironment: opts.gitRepo.mountPath must not contain "." or ".." segments',
420
+ )
421
+ }
422
+ mountPath = spec.mountPath
423
+ }
424
+
425
+ // Mutual exclusion with the other two strategies.
426
+ if (cwd != null && cwd !== '') {
427
+ throw new Error(
428
+ 'createEnvironment: opts.cwd and opts.gitRepo are mutually exclusive — ' +
429
+ 'choose exactly one workspace strategy (hostPath, PVC, or git-clone)',
430
+ )
431
+ }
432
+ if (workspacePVC != null) {
433
+ throw new Error(
434
+ 'createEnvironment: opts.workspacePVC and opts.gitRepo are mutually exclusive — ' +
435
+ 'choose exactly one workspace strategy (hostPath, PVC, or git-clone)',
436
+ )
437
+ }
438
+
439
+ return { url: spec.url, branch: spec.branch ?? null, commit: spec.commit ?? null, depth, mountPath }
440
+ }
441
+
442
+ /**
443
+ * Build the git-clone init container spec(s) for the git-clone workspace
444
+ * strategy (#3193).
445
+ *
446
+ * Each container runs `git` with an explicit argv array (never a shell string),
447
+ * cloning `descriptor.url` into the shared `emptyDir` workspace volume mounted
448
+ * at `descriptor.mountPath`. Branch / commit pinning and shallow depth are
449
+ * honoured:
450
+ * - `--branch <branch>` checks out the named branch/tag at clone time.
451
+ * - `--depth <n>` requests a shallow clone.
452
+ * - `commit` pins the exact SHA via a SECOND init container running
453
+ * `git -C <dir> checkout --detach <commit>`. K8s runs init containers
454
+ * sequentially over the shared emptyDir, so the clone completes before the
455
+ * checkout starts. Splitting into two containers keeps every value in an
456
+ * argv slot — no shell is ever invoked, so neither the URL nor the SHA can
457
+ * be interpreted as a command.
458
+ *
459
+ * @param {{ url: string, branch: string|null, commit: string|null, depth: number|null, mountPath: string }} descriptor
460
+ * @param {string} gitImage - Image providing the `git` binary
461
+ * @returns {Array<object>} One or two init container specs (clone, optional checkout)
462
+ */
463
+ function buildGitCloneInitContainers(descriptor, gitImage) {
464
+ const { url, branch, commit, depth, mountPath } = descriptor
465
+
466
+ const cloneArgs = ['clone']
467
+ if (depth != null) {
468
+ cloneArgs.push('--depth', String(depth))
469
+ }
470
+ if (branch != null) {
471
+ cloneArgs.push('--branch', branch)
472
+ }
473
+ // `--` terminates option parsing so url/mountPath can never be read as flags.
474
+ cloneArgs.push('--', url, mountPath)
475
+
476
+ const volumeMount = { name: 'workspace', mountPath }
477
+
478
+ const containers = [{
479
+ name: 'git-clone',
480
+ image: gitImage,
481
+ command: ['git'],
482
+ args: cloneArgs,
483
+ volumeMounts: [volumeMount],
484
+ }]
485
+
486
+ if (commit != null) {
487
+ containers.push({
488
+ name: 'git-checkout',
489
+ image: gitImage,
490
+ command: ['git'],
491
+ // `-C <dir>` runs git in the cloned tree; `checkout --detach` pins the
492
+ // exact commit. `--` terminates option parsing before the SHA.
493
+ args: ['-C', mountPath, 'checkout', '--detach', '--', commit],
494
+ volumeMounts: [volumeMount],
495
+ })
496
+ }
497
+
498
+ return containers
499
+ }
500
+
501
+ /**
502
+ * K8sBackend implements the Backend interface (see types.js) using the
503
+ * Kubernetes API via @kubernetes/client-node.
504
+ *
505
+ * Phase 1 (#3191): createEnvironment (Pod create) + destroyEnvironment (Pod delete).
506
+ * Phase 2 (#3320): streamCliInEnvironment, execInEnvironment, getEnvironmentStatus.
507
+ * All other Backend interface methods throw NotImplementedError until later phases.
508
+ *
509
+ * This class owns NO environment state. Every method receives the identifier
510
+ * (Pod name) from the caller's in-memory record. The "handle" stored by
511
+ * EnvironmentManager for a K8s environment is the Pod name string.
512
+ *
513
+ * Namespace contract (#3571, #3194):
514
+ * - `_resolveNamespace(callNs, identity)` precedence: explicit `callNs`
515
+ * (`callNs != null`, so an empty string is preserved verbatim — #3493) >
516
+ * identity-derived namespace (`namespaceFor({ userId, projectId })`, #3194) >
517
+ * the static `this._namespace`.
518
+ * - `_validateNamespace(ns, context)` enforces the RFC 1123 DNS label rules
519
+ * the K8s API server applies: 1-63 chars, lowercase alphanumeric + hyphens,
520
+ * start/end alphanumeric. Throws with a `${context}:` prefix.
521
+ * - Per-call sites call `_namespaceForCall(opts, '<method>')` which resolves
522
+ * (explicit > identity > static) and validates in one step, so bad
523
+ * namespaces (empty, uppercase, too long, bad characters, leading/trailing
524
+ * dashes) are rejected client-side before any K8s API call is issued.
525
+ *
526
+ * Multi-tenant isolation (#3194):
527
+ * - The constructor `namespaceFor` mapping turns a per-call `userId`/`projectId`
528
+ * into a deterministic, sanitized, collision-resistant namespace name
529
+ * (default `chroxy-user-<sanitized-id>`).
530
+ * - `createEnvironment` calls `ensureNamespace(ns)` (idempotent read-or-create;
531
+ * 409 AlreadyExists swallowed) so each tenant's namespace exists on demand.
532
+ * - `listEnvironments` is scoped to exactly one namespace and label-filtered to
533
+ * `app.kubernetes.io/managed-by=chroxy`, so a tenant never sees another
534
+ * tenant's Pods. destroy/status/stream all target the resolved namespace.
535
+ *
536
+ * Connection modes for streamCliInEnvironment (constructor-gated):
537
+ * 'portforward' (default) — uses @kubernetes/client-node PortForward to tunnel
538
+ * TCP from a local port to the sidecar's AGENT_PORT.
539
+ * Safe from outside the cluster (dev / CI).
540
+ * 'clusterip' — dials the Pod IP directly. Requires chroxy to run
541
+ * inside the cluster where Pod IPs are routable.
542
+ */
543
+ export class K8sBackend {
544
+ /**
545
+ * @param {Object} [opts]
546
+ * @param {string} [opts.namespace='default'] - Static fallback namespace, used when a
547
+ * per-call invocation carries no identity (no userId/projectId) and no explicit `opts.namespace`.
548
+ * @param {Function} [opts.namespaceFor] - Namespace mapping function (#3194):
549
+ * `({ userId, projectId }) => string|null`. Called per createEnvironment/destroy/etc. to derive
550
+ * the tenant-isolated namespace from caller identity. Default maps `userId` (or `projectId`) to
551
+ * `chroxy-user-<sanitized-id>` and returns `null` when neither is present (→ static fallback).
552
+ * The returned name is validated against RFC 1123 before any K8s API call. Pass a custom function
553
+ * to project namespaces differently (e.g. `chroxy-proj-<projectId>`).
554
+ * @param {boolean} [opts.inCluster] - Force in-cluster auth (default: auto-detect via KUBERNETES_SERVICE_HOST)
555
+ * @param {string} [opts.kubeconfigPath] - Path to kubeconfig file (overrides default search)
556
+ * @param {string} [opts.sidecarImage] - Sidecar image to use in createEnvironment (default: chroxy-pod-agent:latest)
557
+ * @param {string} [opts.gitImage] - Image providing `git` for the git-clone workspace
558
+ * init container (default: alpine/git:latest). Used only when a createEnvironment call passes
559
+ * `opts.gitRepo` (#3193).
560
+ * @param {'Always'|'IfNotPresent'|'Never'} [opts.imagePullPolicy] - imagePullPolicy applied to all
561
+ * containers in the Pod spec. When unset the field is omitted and Kubernetes applies its own default
562
+ * ('Always' for :latest tags, 'IfNotPresent' otherwise). Set to 'IfNotPresent' for air-gapped
563
+ * clusters or local kind-based CI where images are loaded directly into the cluster.
564
+ * @param {Object|null} [opts.defaultResources] - Cluster-wide default resource requests/limits
565
+ * applied to the sidecar container when a createEnvironment call does not override them (#3195).
566
+ * Same shape as `createEnvironment`'s `opts.resources` (`{ cpu, memory, cpuLimit, memoryLimit }`).
567
+ * An object is merged over the built-in {@link DEFAULT_RESOURCES} (so partial overrides are fine)
568
+ * and validated at construction. Pass `null` to disable defaults entirely — then only explicit
569
+ * per-call resource values produce a `resources` block. Omit to use the built-in defaults.
570
+ * @param {Object|null} [opts.namespaceQuota] - Per-tenant aggregate ResourceQuota spec (#5142).
571
+ * When set, a namespace-scoped `ResourceQuota` capping the tenant's TOTAL CPU/memory (and
572
+ * optionally Pod count) across all their Pods is ensured (idempotent create) whenever a tenant
573
+ * namespace is ensured. Shape: `{ cpu, memory, cpuLimit, memoryLimit, pods }` — `cpu`/`memory`
574
+ * map to aggregate `requests.*`, `cpuLimit`/`memoryLimit` to aggregate `limits.*`, `pods` to the
575
+ * max object count. At least one field is required. Quantities are validated at construction.
576
+ * Distinct from per-pod `defaultResources` (#3195), which limits each individual Pod. Omit (or
577
+ * `null`) to skip — the namespace-ensure path is unchanged. Never applied to the static default
578
+ * namespace.
579
+ * @param {Object|null} [opts.namespaceLimitRange] - Per-tenant LimitRange defaults (#5142).
580
+ * When set, a namespace-scoped `LimitRange` is ensured so Pods created WITHOUT explicit
581
+ * requests/limits inherit namespace defaults at the cluster level (defence-in-depth on top of
582
+ * `defaultResources`). Same flat shape as `defaultResources`: `{ cpu, memory, cpuLimit,
583
+ * memoryLimit }` — `cpu`/`memory` become `defaultRequest.*`, `cpuLimit`/`memoryLimit` become
584
+ * `default.*`. At least one field required. Quantities validated at construction. Omit (or
585
+ * `null`) to skip. Never applied to the static default namespace.
586
+ * @param {'portforward'|'clusterip'} [opts.connectMode='portforward'] - How to reach the sidecar
587
+ * @param {object} [opts._coreV1Api] - Injected CoreV1Api for testing
588
+ * @param {object} [opts._portForward] - Injected PortForward for testing
589
+ * @param {Function} [opts._dialWs] - Injected WS dial factory for testing: (url, token) => WebSocket
590
+ * @param {number[]} [opts._reconnectDelays] - Override backoff delays in ms for testing
591
+ * @param {number} [opts._maxRetries] - Override max reconnect retries for testing
592
+ * @param {number} [opts._maxStdinBufferBytes] - Override SidecarProcess pre-dial stdin buffer cap (#3401)
593
+ * @param {Function} [opts._setTimeout] - Override setTimeout for deterministic testing
594
+ * @param {Function} [opts._clearTimeout] - Override clearTimeout for deterministic testing
595
+ */
596
+ constructor({ namespace, namespaceFor, inCluster, kubeconfigPath, sidecarImage, gitImage, imagePullPolicy,
597
+ defaultResources, namespaceQuota, namespaceLimitRange, connectMode, _coreV1Api, _portForward, _dialWs, _net,
598
+ _reconnectDelays, _maxRetries, _maxStdinBufferBytes,
599
+ _setTimeout: setTimeoutImpl, _clearTimeout: clearTimeoutImpl } = {}) {
600
+ validateImagePullPolicy(imagePullPolicy, 'constructor opts')
601
+ this._namespace = namespace ?? 'default'
602
+ // Namespace mapping function (#3194). A non-function override is rejected
603
+ // up-front rather than blowing up later inside _resolveNamespace.
604
+ if (namespaceFor != null && typeof namespaceFor !== 'function') {
605
+ throw new TypeError('K8sBackend: opts.namespaceFor must be a function')
606
+ }
607
+ this._namespaceFor = namespaceFor || defaultNamespaceFor
608
+ // Namespaces we have already ensured exist this process, so repeated
609
+ // createEnvironment calls for the same tenant skip the read/create roundtrip.
610
+ this._ensuredNamespaces = new Set()
611
+ this._sidecarImage = sidecarImage ?? DEFAULT_SIDECAR_IMAGE
612
+ this._gitImage = gitImage ?? DEFAULT_GIT_IMAGE
613
+ this._imagePullPolicy = imagePullPolicy ?? null
614
+ // Default resource requests/limits applied to the sidecar container (#3195).
615
+ // - undefined → use the module DEFAULT_RESOURCES
616
+ // - an object → merge over DEFAULT_RESOURCES (operator-set cluster-wide defaults)
617
+ // - null → disable defaults entirely (only explicit per-call values apply)
618
+ // Validate any object form up-front so a malformed quantity surfaces at
619
+ // construction rather than at the first createEnvironment call.
620
+ if (defaultResources === null) {
621
+ this._defaultResources = null
622
+ } else if (defaultResources === undefined) {
623
+ this._defaultResources = { ...DEFAULT_RESOURCES }
624
+ } else if (typeof defaultResources === 'object' && !Array.isArray(defaultResources)) {
625
+ const merged = { ...DEFAULT_RESOURCES, ...defaultResources }
626
+ // Reuse the per-call builder purely to validate the merged quantities
627
+ // (defaults disabled so only the merged object is validated). Re-scope
628
+ // any failure to opts.defaultResources — buildResourceBlock blames
629
+ // `resources.*`/`createEnvironment`, which points at the wrong call
630
+ // site for constructor config (#3195 review) — preserving the
631
+ // underlying error as `cause`.
632
+ try {
633
+ buildResourceBlock(merged, undefined, undefined, null)
634
+ } catch (err) {
635
+ throw new Error(`K8sBackend: opts.defaultResources is invalid — ${err.message}`, { cause: err })
636
+ }
637
+ this._defaultResources = merged
638
+ } else {
639
+ throw new TypeError('K8sBackend: opts.defaultResources must be an object or null')
640
+ }
641
+
642
+ // Namespace-level (per-tenant) ResourceQuota / LimitRange (#5142). These are
643
+ // OPT-IN: when unset the namespace-ensure path is unchanged. Build the canonical
644
+ // K8s spec up-front so a malformed quantity surfaces at construction rather than
645
+ // at the first createEnvironment call (mirrors defaultResources).
646
+ // - undefined/null → feature off (no quota / limitrange ensured)
647
+ // - object → validated + cached spec, ensured per tenant namespace
648
+ // Re-scope any builder failure to the constructor option (mirrors how
649
+ // defaultResources wraps buildResourceBlock above) — the builders blame
650
+ // `namespaceQuota.*` via _validateResourceQuantity's `createEnvironment:`
651
+ // prefix, which points at the wrong call site for constructor config. The
652
+ // original error is preserved as `cause`.
653
+ if (namespaceQuota == null) {
654
+ this._namespaceQuotaSpec = null
655
+ } else {
656
+ try {
657
+ this._namespaceQuotaSpec = buildResourceQuotaSpec(namespaceQuota)
658
+ } catch (err) {
659
+ throw new Error(`K8sBackend: opts.namespaceQuota is invalid — ${err.message}`, { cause: err })
660
+ }
661
+ }
662
+ if (namespaceLimitRange == null) {
663
+ this._namespaceLimitRangeSpec = null
664
+ } else {
665
+ try {
666
+ this._namespaceLimitRangeSpec = buildLimitRangeSpec(namespaceLimitRange)
667
+ } catch (err) {
668
+ throw new Error(`K8sBackend: opts.namespaceLimitRange is invalid — ${err.message}`, { cause: err })
669
+ }
670
+ }
671
+ // Namespaces whose ResourceQuota / LimitRange we have already ensured this
672
+ // process, so repeated createEnvironment calls for the same tenant skip the
673
+ // read/create roundtrip (mirrors _ensuredNamespaces).
674
+ this._ensuredQuotas = new Set()
675
+ this._ensuredLimitRanges = new Set()
676
+
677
+ this._connectMode = connectMode ?? 'portforward'
678
+
679
+ if (_coreV1Api) {
680
+ this._api = _coreV1Api
681
+ this._kc = null
682
+ } else {
683
+ const kc = new KubeConfig()
684
+ const useInCluster = inCluster ?? Boolean(process.env.KUBERNETES_SERVICE_HOST)
685
+ if (useInCluster) {
686
+ kc.loadFromCluster()
687
+ } else if (kubeconfigPath) {
688
+ kc.loadFromFile(kubeconfigPath)
689
+ } else {
690
+ kc.loadFromDefault()
691
+ }
692
+ this._kc = kc
693
+ this._api = kc.makeApiClient(CoreV1Api)
694
+ }
695
+
696
+ // Allow PortForward injection for unit tests
697
+ this._portForwardImpl = _portForward || null
698
+ // Allow `net` injection for unit tests of the portforward bridge
699
+ this._netImpl = _net || null
700
+ // Allow WS dial injection for unit tests.
701
+ // When _dialWs is injected, _dial() calls it directly (bypasses pod-IP
702
+ // lookup and port-forward machinery) — useful in unit tests where there is
703
+ // no real cluster.
704
+ if (_dialWs) {
705
+ this._dialWs = _dialWs
706
+ this._directDial = true
707
+ } else {
708
+ this._dialWs = _defaultDialWs
709
+ this._directDial = false
710
+ }
711
+
712
+ // Per-Pod agent tokens, keyed by pod name. Populated by createEnvironment()
713
+ // and consulted by streamCliInEnvironment() / execInEnvironment(). Removed
714
+ // by destroyEnvironment(). Storing it here keeps the Backend.streamCli...
715
+ // interface uniform across backends — callers do not need to thread a
716
+ // K8s-specific agentToken arg through the manager.
717
+ this._agentTokens = new Map()
718
+
719
+ // In-flight _readAgentToken promises, keyed by pod name. Coalesces
720
+ // concurrent callers so only one K8s API request is made per pod at a time
721
+ // (deduplicates the race where two streamCliInEnvironment calls arrive
722
+ // before either has populated _agentTokens).
723
+ this._pendingAgentTokens = new Map()
724
+
725
+ // Reconnect backoff config — injectable for deterministic unit tests.
726
+ // Validate the delay schedule defensively: an empty array (or non-finite
727
+ // entries) would make `delay` undefined and let `setTimeout` fire on the
728
+ // next tick, producing a tight reconnect loop.
729
+ const delays = _reconnectDelays || DEFAULT_RECONNECT_DELAYS
730
+ const validDelays = Array.isArray(delays) && delays.length > 0 &&
731
+ delays.every((d) => Number.isFinite(d) && d >= 0)
732
+ this._reconnectDelays = validDelays ? delays : DEFAULT_RECONNECT_DELAYS
733
+ this._maxRetries = Number.isFinite(_maxRetries) && _maxRetries >= 0
734
+ ? _maxRetries
735
+ : DEFAULT_MAX_RETRIES
736
+ // Pre-dial stdin buffer cap (#3401) — injectable for tests.
737
+ this._maxStdinBufferBytes = Number.isFinite(_maxStdinBufferBytes) && _maxStdinBufferBytes > 0
738
+ ? _maxStdinBufferBytes
739
+ : DEFAULT_MAX_STDIN_BUFFER_BYTES
740
+ // Timer seam: allow tests to substitute a fake clock and avoid real-time polling.
741
+ this._setTimeout = setTimeoutImpl || setTimeout
742
+ this._clearTimeout = clearTimeoutImpl || clearTimeout
743
+ }
744
+
745
+ /**
746
+ * Resolve the effective namespace for a per-call invocation.
747
+ *
748
+ * Precedence (highest first):
749
+ * 1. Explicit per-call `callNamespace` — including the empty string (#3493).
750
+ * `??` preserves `''` verbatim so it surfaces to the K8s API (and is
751
+ * rejected by `_validateNamespace`) rather than being silently rewritten.
752
+ * 2. Identity-derived namespace (#3194) — when `callNamespace` is
753
+ * null/undefined and `identity` carries a userId/projectId, the
754
+ * constructor-supplied `namespaceFor` mapping derives a tenant-isolated
755
+ * namespace. A `null` from the mapping means "no identity" → fall through.
756
+ * 3. The constructor-stored static `namespace` (default 'default').
757
+ *
758
+ * The mapping function runs only on the fall-through path so an explicit
759
+ * namespace always wins and an identity-less call keeps the legacy behaviour.
760
+ *
761
+ * @param {string|undefined|null} callNamespace - Per-call namespace override
762
+ * @param {Object} [identity] - Per-call tenant identity (#3194)
763
+ * @param {string} [identity.userId] - User identity for namespace mapping
764
+ * @param {string} [identity.projectId] - Project identity for namespace mapping
765
+ * @returns {string} Resolved namespace
766
+ */
767
+ _resolveNamespace(callNamespace, identity) {
768
+ if (callNamespace != null) return callNamespace
769
+ if (identity && (identity.userId != null || identity.projectId != null)) {
770
+ const mapped = this._namespaceFor(identity)
771
+ if (mapped != null) return mapped
772
+ }
773
+ return this._namespace
774
+ }
775
+
776
+ /**
777
+ * Idempotently ensure a namespace exists (#3194).
778
+ *
779
+ * Multi-tenant isolation requires the per-user/per-project namespace to be
780
+ * present before any Pod/Secret is created in it. This method is safe to call
781
+ * repeatedly and concurrently:
782
+ * - The first call reads the namespace; a 404 triggers a create.
783
+ * - A create that races another creator (409 AlreadyExists) is swallowed —
784
+ * the namespace exists, which is the post-condition we want.
785
+ * - Once ensured, the name is cached for the process so subsequent calls are
786
+ * a no-op (no API roundtrip).
787
+ *
788
+ * The static default namespace ('default', or any operator-supplied static
789
+ * `namespace`) is treated as pre-existing and never created — it is part of the
790
+ * cluster bootstrap, and a chroxy service account is unlikely to hold
791
+ * cluster-scoped namespace-create RBAC for it. Only namespaces *derived* from
792
+ * tenant identity are created on demand.
793
+ *
794
+ * @param {string} ns - A namespace name already validated as an RFC 1123 label
795
+ * @returns {Promise<void>}
796
+ */
797
+ async ensureNamespace(ns) {
798
+ if (this._ensuredNamespaces.has(ns)) return
799
+ // Never attempt to create the static fallback namespace — it is assumed to
800
+ // exist (cluster bootstrap) and chroxy may lack RBAC to create it.
801
+ if (ns === this._namespace) {
802
+ this._ensuredNamespaces.add(ns)
803
+ return
804
+ }
805
+
806
+ try {
807
+ await this._api.readNamespace({ name: ns })
808
+ this._ensuredNamespaces.add(ns)
809
+ return
810
+ } catch (err) {
811
+ if (!_isNotFound(err)) throw err
812
+ // 404 → fall through and create it.
813
+ }
814
+
815
+ const body = {
816
+ apiVersion: 'v1',
817
+ kind: 'Namespace',
818
+ metadata: {
819
+ name: ns,
820
+ labels: { 'app.kubernetes.io/managed-by': 'chroxy' },
821
+ },
822
+ }
823
+ try {
824
+ log.info(`Creating namespace ${ns}`)
825
+ await this._api.createNamespace({ body })
826
+ } catch (err) {
827
+ // Another creator won the race (or it already existed) — AlreadyExists is
828
+ // success for an idempotent ensure, not an error.
829
+ if (!_isAlreadyExists(err)) throw err
830
+ log.info(`Namespace ${ns} already exists (concurrent create)`)
831
+ }
832
+ this._ensuredNamespaces.add(ns)
833
+ }
834
+
835
+ /**
836
+ * Idempotently ensure a per-tenant `ResourceQuota` exists in `ns` (#5142).
837
+ *
838
+ * A namespace-scoped ResourceQuota caps the AGGREGATE CPU/memory (and
839
+ * optionally Pod count) a tenant may consume across ALL their Pods — distinct
840
+ * from the per-pod requests/limits #3195 sets on each container. It is the
841
+ * tenant-level guardrail that becomes meaningful now that #3194 gives every
842
+ * tenant their own namespace.
843
+ *
844
+ * Opt-in + safe by construction:
845
+ * - No-op when the backend was constructed without `namespaceQuota`.
846
+ * - No-op for the static default namespace (treated as cluster bootstrap,
847
+ * chroxy is unlikely to hold RBAC there) — mirrors ensureNamespace.
848
+ * - Read-or-create, idempotent, safe to call repeatedly/concurrently: a 404
849
+ * read triggers a create; a 409 AlreadyExists on create is swallowed.
850
+ * - Once ensured, the namespace is cached so subsequent calls are a no-op.
851
+ *
852
+ * @param {string} ns - A namespace name already validated as an RFC 1123 label
853
+ * @returns {Promise<void>}
854
+ */
855
+ async ensureResourceQuota(ns) {
856
+ if (this._namespaceQuotaSpec == null) return
857
+ if (this._ensuredQuotas.has(ns)) return
858
+ // Never touch the static default namespace — assumed pre-existing, and chroxy
859
+ // may lack RBAC to write ResourceQuota objects there.
860
+ if (ns === this._namespace) {
861
+ this._ensuredQuotas.add(ns)
862
+ return
863
+ }
864
+
865
+ const name = 'chroxy-quota'
866
+ try {
867
+ await this._api.readNamespacedResourceQuota({ name, namespace: ns })
868
+ this._ensuredQuotas.add(ns)
869
+ return
870
+ } catch (err) {
871
+ if (!_isNotFound(err)) throw err
872
+ // 404 → fall through and create it.
873
+ }
874
+
875
+ const body = {
876
+ apiVersion: 'v1',
877
+ kind: 'ResourceQuota',
878
+ metadata: {
879
+ name,
880
+ labels: { 'app.kubernetes.io/managed-by': 'chroxy' },
881
+ },
882
+ spec: { hard: this._namespaceQuotaSpec },
883
+ }
884
+ try {
885
+ log.info(`Creating ResourceQuota ${name} in namespace ${ns}`)
886
+ await this._api.createNamespacedResourceQuota({ namespace: ns, body })
887
+ } catch (err) {
888
+ // Another creator won the race (or it already existed) — AlreadyExists is
889
+ // success for an idempotent ensure, not an error.
890
+ if (!_isAlreadyExists(err)) throw err
891
+ log.info(`ResourceQuota ${name} already exists in ${ns} (concurrent create)`)
892
+ }
893
+ this._ensuredQuotas.add(ns)
894
+ }
895
+
896
+ /**
897
+ * Idempotently ensure a per-tenant `LimitRange` exists in `ns` (#5142).
898
+ *
899
+ * A namespace-scoped LimitRange supplies cluster-level DEFAULT requests/limits
900
+ * so Pods created WITHOUT explicit resources inherit sane values — a
901
+ * defence-in-depth layer on top of the backend's own DEFAULT_RESOURCES.
902
+ *
903
+ * Same opt-in + idempotency semantics as {@link ensureResourceQuota}:
904
+ * - No-op when constructed without `namespaceLimitRange`.
905
+ * - No-op for the static default namespace.
906
+ * - Read-or-create (404 → create, 409 → swallowed), cached per process.
907
+ *
908
+ * @param {string} ns - A namespace name already validated as an RFC 1123 label
909
+ * @returns {Promise<void>}
910
+ */
911
+ async ensureLimitRange(ns) {
912
+ if (this._namespaceLimitRangeSpec == null) return
913
+ if (this._ensuredLimitRanges.has(ns)) return
914
+ if (ns === this._namespace) {
915
+ this._ensuredLimitRanges.add(ns)
916
+ return
917
+ }
918
+
919
+ const name = 'chroxy-limits'
920
+ try {
921
+ await this._api.readNamespacedLimitRange({ name, namespace: ns })
922
+ this._ensuredLimitRanges.add(ns)
923
+ return
924
+ } catch (err) {
925
+ if (!_isNotFound(err)) throw err
926
+ // 404 → fall through and create it.
927
+ }
928
+
929
+ const body = {
930
+ apiVersion: 'v1',
931
+ kind: 'LimitRange',
932
+ metadata: {
933
+ name,
934
+ labels: { 'app.kubernetes.io/managed-by': 'chroxy' },
935
+ },
936
+ spec: { limits: [this._namespaceLimitRangeSpec] },
937
+ }
938
+ try {
939
+ log.info(`Creating LimitRange ${name} in namespace ${ns}`)
940
+ await this._api.createNamespacedLimitRange({ namespace: ns, body })
941
+ } catch (err) {
942
+ if (!_isAlreadyExists(err)) throw err
943
+ log.info(`LimitRange ${name} already exists in ${ns} (concurrent create)`)
944
+ }
945
+ this._ensuredLimitRanges.add(ns)
946
+ }
947
+
948
+ /**
949
+ * Validates a resolved namespace against RFC 1123 DNS label rules (#3571).
950
+ *
951
+ * Layered on top of `_resolveNamespace` so all five per-call resolution
952
+ * sites gain validation atomically. Delegates to the module-level
953
+ * `validateNamespace()` helper.
954
+ *
955
+ * @param {*} ns - Resolved namespace value (output of _resolveNamespace)
956
+ * @param {string} context - Method name / call site label for the error message
957
+ * @returns {string} The validated namespace
958
+ * @throws {Error} If `ns` is not a valid RFC 1123 DNS label
959
+ */
960
+ _validateNamespace(ns, context) {
961
+ return validateNamespace(ns, context)
962
+ }
963
+
964
+ /**
965
+ * Resolve + validate the namespace for a per-call invocation in one step
966
+ * (#3194). Reads `namespace`, `userId`, and `projectId` from the caller's
967
+ * opts, runs them through `_resolveNamespace` (explicit > identity > static),
968
+ * then validates the result against RFC 1123. Used by every per-call site so
969
+ * identity-based isolation and validation stay consistent.
970
+ *
971
+ * @param {Object} opts - The method's opts object
972
+ * @param {string} [opts.namespace] - Explicit namespace override
973
+ * @param {string} [opts.userId] - Tenant identity
974
+ * @param {string} [opts.projectId] - Project identity
975
+ * @param {string} context - Call-site label for the error message
976
+ * @returns {string} Validated namespace
977
+ */
978
+ _namespaceForCall(opts, context) {
979
+ const resolved = this._resolveNamespace(opts.namespace, {
980
+ userId: opts.userId,
981
+ projectId: opts.projectId,
982
+ })
983
+ return this._validateNamespace(resolved, context)
984
+ }
985
+
986
+ // ─────────────────────────────────────────────────────────────────────────
987
+ // createEnvironment — create a sidecar Pod + per-Pod Secret
988
+ // ─────────────────────────────────────────────────────────────────────────
989
+
990
+ /**
991
+ * Creates a per-Pod K8s Secret containing a random auth token, then creates
992
+ * a single-container Pod running the chroxy-pod-agent sidecar. The token is
993
+ * injected as CHROXY_AGENT_TOKEN via secretKeyRef.
994
+ *
995
+ * Returns as soon as `createNamespacedPod` resolves — the Pod has been accepted
996
+ * by the API server but may not yet be scheduled or Running.
997
+ *
998
+ * Workspace mount strategies (mutually exclusive — pick exactly one):
999
+ *
1000
+ * 1. hostPath (single-node clusters) — pass `opts.cwd`:
1001
+ * `opts.cwd` is mounted into the Pod as a `hostPath` volume at `/workspace`.
1002
+ * This is the simplest strategy for local clusters (kind, minikube, Docker
1003
+ * Desktop) where the Node running the Pod shares the host filesystem.
1004
+ * Cluster-side requirement: the K8s node the Pod schedules onto must be
1005
+ * able to read `opts.cwd` from its local filesystem.
1006
+ *
1007
+ * Failure mode on multi-node clusters: the Pod schedules onto a node that
1008
+ * does not have the path, which `hostPath` `DirectoryOrCreate` silently
1009
+ * papers over by creating an empty directory — the workload then sees an
1010
+ * empty workspace with no surface error.
1011
+ *
1012
+ * 2. PersistentVolumeClaim (multi-node clusters) — pass `opts.workspacePVC`:
1013
+ * `opts.workspacePVC = { claimName, mountPath?, readOnly? }` translates to
1014
+ * a `persistentVolumeClaim` volume + matching `volumeMount`. This is the
1015
+ * recommended strategy for production / multi-node clusters where the
1016
+ * workspace must follow the Pod across nodes. Operators are responsible
1017
+ * for provisioning the PVC and seeding its contents out-of-band; the
1018
+ * backend only references the claim by name. `mountPath` defaults to
1019
+ * `/workspace` to match the hostPath strategy.
1020
+ *
1021
+ * Migration from hostPath → PVC:
1022
+ * - Drop `opts.cwd` and pass `opts.workspacePVC.claimName` instead.
1023
+ * - Pre-populate the PVC with the workspace contents (e.g. an initContainer
1024
+ * that clones a repo, a Job that rsyncs from object storage, or a
1025
+ * manual `kubectl cp`) before relying on the workspace inside the Pod.
1026
+ * - `opts.cwd` and `opts.workspacePVC` are mutually exclusive — passing
1027
+ * both throws. Operators must explicitly choose one strategy.
1028
+ *
1029
+ * 3. git-clone (Phase 1, #3193) — pass `opts.gitRepo`:
1030
+ * `opts.gitRepo = { url, branch?, commit?, depth?, mountPath? }` (or a bare
1031
+ * URL string) provisions an ephemeral `emptyDir` workspace that a
1032
+ * `git clone` init container populates before the main container starts.
1033
+ * This is the K8s-native answer to "the Pod runs on a remote node that
1034
+ * can't see the operator's filesystem" without requiring an out-of-band
1035
+ * PVC seed step. Branch / commit pinning and shallow `depth` are honoured.
1036
+ * The git binary comes from the constructor `gitImage` (default
1037
+ * `alpine/git:latest`).
1038
+ *
1039
+ * Persistence caveat: `emptyDir` is tied to the Pod lifecycle — when the
1040
+ * Pod is deleted the cloned tree is gone. PVC-backed persistence for the
1041
+ * git-clone strategy is the explicit follow-up (#3385); until then a
1042
+ * git-clone workspace is for ephemeral, single-Pod sessions only.
1043
+ *
1044
+ * mountPath caveat (#3193 phase 1): the default `mountPath` of
1045
+ * `/workspace` aligns with `streamCliInEnvironment`'s host→Pod cwd
1046
+ * remap, so exec sessions land on the cloned tree automatically. A
1047
+ * NON-default `mountPath` is supported in the Pod manifest, but the cwd
1048
+ * remap still targets `/workspace` — callers that override `mountPath`
1049
+ * must pass the matching `cwd` to `streamCliInEnvironment` themselves.
1050
+ * Per-Pod workspace-root tracking is left as follow-up.
1051
+ *
1052
+ * **Security warning — hostPath privilege escalation:**
1053
+ * `hostPath` volumes (used for both `opts.cwd` and `opts.mounts`) give the
1054
+ * Pod direct access to the underlying node's filesystem. This is a
1055
+ * privilege-escalation vector on multi-tenant clusters: a malicious or
1056
+ * misconfigured workspace path could mount sensitive node paths such as
1057
+ * `/etc/kubernetes/pki`, `/var/run/docker.sock`, or `/var/lib/kubelet`,
1058
+ * allowing the workload to read cluster credentials or break out of the
1059
+ * container.
1060
+ *
1061
+ * Most production clusters block `hostPath` via PodSecurity admission —
1062
+ * PSA `restricted` and `baseline` policies both prohibit it, so Pod
1063
+ * creation will be rejected by the PSA admission controller (the API
1064
+ * server returns a 4xx at create time, before the Pod ever reaches the
1065
+ * scheduler). The PVC strategy above does NOT have this restriction and
1066
+ * is the safe default for shared / multi-tenant clusters.
1067
+ *
1068
+ * **This mode is not safe for shared / multi-tenant clusters.** Operators
1069
+ * running on shared infrastructure should use the PVC-based workspace
1070
+ * strategy (`opts.workspacePVC`) instead of relying on `hostPath`. Use
1071
+ * this backend only on single-tenant clusters where you control every
1072
+ * workload, or on a namespace where Pod Security Admission is enforced
1073
+ * at the `privileged` level (or with an equivalent policy exemption) so
1074
+ * that `hostPath` volumes are explicitly permitted.
1075
+ *
1076
+ * @param {Object} opts - See Backend interface in types.js
1077
+ * @param {string} opts.envId - Unique environment ID
1078
+ * @param {string} [opts.cwd] - Host path to mount as /workspace inside the Pod (hostPath strategy).
1079
+ * Mutually exclusive with `opts.workspacePVC` — passing both throws.
1080
+ * @param {Object} [opts.workspacePVC] - PVC-based workspace strategy for multi-node clusters.
1081
+ * @param {string} opts.workspacePVC.claimName - Name of a pre-provisioned PVC in the target namespace
1082
+ * @param {string} [opts.workspacePVC.mountPath] - Pod-side mount path (default: `/workspace`)
1083
+ * @param {boolean} [opts.workspacePVC.readOnly] - Mount the PVC read-only (default: false)
1084
+ * @param {string|Object} [opts.gitRepo] - git-clone workspace strategy (#3193). A bare URL string is
1085
+ * shorthand for `{ url }`. Provisions an `emptyDir` workspace populated by a `git clone` init container.
1086
+ * Mutually exclusive with `opts.cwd` and `opts.workspacePVC` — passing more than one throws.
1087
+ * @param {string} opts.gitRepo.url - Repo URL to clone (required; must not start with "-")
1088
+ * @param {string} [opts.gitRepo.branch] - Branch/tag to check out at clone time (`--branch`)
1089
+ * @param {string} [opts.gitRepo.commit] - Exact commit SHA to pin via a follow-up checkout init container
1090
+ * @param {number} [opts.gitRepo.depth] - Positive integer for a shallow clone (`--depth`)
1091
+ * @param {string} [opts.gitRepo.mountPath] - Pod-side workspace mount path (default: `/workspace`)
1092
+ * @param {string} [opts.image] - Overrides the constructor sidecarImage
1093
+ * @param {Object} [opts.resources] - Structured resource requests/limits (#3195).
1094
+ * All four fields are optional K8s quantity strings, validated before any API call:
1095
+ * - `resources.cpu` → `resources.requests.cpu` (e.g. "500m", "1")
1096
+ * - `resources.memory` → `resources.requests.memory` (e.g. "512Mi", "1Gi")
1097
+ * - `resources.cpuLimit` → `resources.limits.cpu` (e.g. "2")
1098
+ * - `resources.memoryLimit` → `resources.limits.memory` (e.g. "4Gi")
1099
+ * Unset fields fall back to the legacy flat opts (below), then to the
1100
+ * constructor `defaultResources` (default {@link DEFAULT_RESOURCES}). Pass the
1101
+ * constructor `defaultResources: null` to omit defaults entirely.
1102
+ * @param {string} [opts.memoryLimit] - Legacy flat K8s memory quantity string (e.g. "2Gi").
1103
+ * Applied to BOTH `resources.limits.memory` and `resources.requests.memory` for the
1104
+ * memory dimension (pre-#3195 behaviour). Superseded by `opts.resources.memory` /
1105
+ * `opts.resources.memoryLimit` when those are set.
1106
+ * Accepts Docker-style suffixes ("g"/"m") and standard K8s suffixes ("Gi"/"Mi").
1107
+ * @param {string} [opts.cpuLimit] - Legacy flat K8s CPU quantity string (e.g. "2" or "500m").
1108
+ * Applied to BOTH `resources.limits.cpu` and `resources.requests.cpu` for the CPU
1109
+ * dimension (pre-#3195 behaviour). Superseded by `opts.resources.cpu` /
1110
+ * `opts.resources.cpuLimit` when those are set.
1111
+ * A plain integer or float (e.g. "2", "0.5") is valid K8s CPU quantity syntax.
1112
+ * @param {number[]|string[]} [opts.forwardPorts] - Extra ports to expose from the container
1113
+ * (in addition to the built-in AGENT_PORT). Each value may be a bare port number
1114
+ * or a "hostPort:containerPort" string; only the containerPort is used in the Pod spec.
1115
+ * @param {string[]} [opts.mounts] - Additional volume mounts in Docker-style
1116
+ * "hostPath:containerPath[:ro]" format. Each entry is translated into a
1117
+ * `hostPath` volume + corresponding `volumeMount`. The volume name is derived
1118
+ * from the entry index ("extra-vol-0", "extra-vol-1", …).
1119
+ * @param {Object.<string,string>} [opts.containerEnv] - Extra environment variables
1120
+ * @param {string} [opts.namespace] - Explicit namespace; overrides both the identity mapping
1121
+ * and the constructor default.
1122
+ * @param {string} [opts.userId] - Tenant identity for namespace isolation (#3194). When set
1123
+ * (and no explicit `opts.namespace`), the Pod/Secret are created in the namespace produced by the
1124
+ * constructor `namespaceFor` mapping (default `chroxy-user-<userId>`). The namespace is created
1125
+ * on demand if it does not yet exist.
1126
+ * @param {string} [opts.projectId] - Project identity for namespace isolation (#3194), used by
1127
+ * the default mapping only when no `userId` is supplied.
1128
+ * @param {'Always'|'IfNotPresent'|'Never'} [opts.imagePullPolicy] - Per-call override for the
1129
+ * container imagePullPolicy. Falls back to the constructor-level option when unset.
1130
+ * @returns {Promise<{ containerId: string, containerCliPath: string, agentToken: string, secretName: string }>}
1131
+ * containerId — the Pod name (used as handle on subsequent calls)
1132
+ * containerCliPath — hardcoded default; sidecar-based discovery is future work
1133
+ * agentToken — token to authenticate WS connections (stored in memory by caller)
1134
+ * secretName — Secret name (stored by caller so destroyEnvironment can delete it)
1135
+ */
1136
+ async createEnvironment(opts) {
1137
+ const {
1138
+ envId, cwd, containerEnv, namespace, userId, projectId,
1139
+ memoryLimit, cpuLimit, resources: callResources, forwardPorts, mounts,
1140
+ imagePullPolicy: callImagePullPolicy,
1141
+ workspacePVC, gitRepo,
1142
+ } = opts
1143
+ validateImagePullPolicy(callImagePullPolicy, 'createEnvironment opts')
1144
+ // Workspace-strategy validation: three mutually-exclusive strategies decide
1145
+ // what backs /workspace:
1146
+ // - opts.cwd → hostPath volume (single-node clusters, #3316)
1147
+ // - opts.workspacePVC → persistentVolumeClaim (multi-node clusters, #3385)
1148
+ // - opts.gitRepo → git-clone init container into an emptyDir (#3193)
1149
+ // Accept exactly one — passing more than one throws. The alternative would
1150
+ // be a silent precedence rule that hides operator intent.
1151
+ validateWorkspacePVC(workspacePVC, cwd)
1152
+ const gitClone = validateGitRepo(gitRepo, cwd, workspacePVC)
1153
+ const ns = this._namespaceForCall({ namespace, userId, projectId }, 'createEnvironment')
1154
+ // Ensure the tenant namespace exists before provisioning any resource in it
1155
+ // (#3194). Idempotent + cached; a no-op for the static default namespace.
1156
+ await this.ensureNamespace(ns)
1157
+ // Ensure per-tenant namespace-level guardrails (#5142). Both are opt-in
1158
+ // (no-op unless the backend was constructed with namespaceQuota /
1159
+ // namespaceLimitRange) and idempotent + cached. Run after ensureNamespace so
1160
+ // the namespace is guaranteed to exist before the quota/limitrange is written.
1161
+ await this.ensureResourceQuota(ns)
1162
+ await this.ensureLimitRange(ns)
1163
+ const podName = `chroxy-env-${envId}`
1164
+ const secretName = `chroxy-token-${envId}`
1165
+ // K8sBackend ALWAYS runs the chroxy-pod-agent sidecar — the sidecar is
1166
+ // the env, and the user's workload runs inside it. EnvironmentManager
1167
+ // passes a workspace image (e.g. node:22-slim) which we deliberately
1168
+ // ignore here; only the constructor-configured sidecarImage is used.
1169
+ const sidecarImage = this._sidecarImage
1170
+
1171
+ // 0. Pre-flight: validate every mount string up-front. _parseMountString()
1172
+ // throws for Windows-style drive-letter paths (#3388); doing this BEFORE
1173
+ // the Secret/Pod create avoids leaking a half-provisioned Secret when a
1174
+ // caller passes a bad mount. Parse results are reused below.
1175
+ const parsedMounts = []
1176
+ if (mounts && mounts.length > 0) {
1177
+ for (let i = 0; i < mounts.length; i++) {
1178
+ parsedMounts.push(_parseMountString(mounts[i]))
1179
+ }
1180
+ }
1181
+
1182
+ // Build + validate the resources block up-front too (#3195). A malformed
1183
+ // quantity throws here, BEFORE the Secret/Pod create, so a bad value never
1184
+ // leaks a half-provisioned Secret. Defaults are applied unless the operator
1185
+ // disabled them (constructor `defaultResources: null`).
1186
+ const resources = buildResourceBlock(
1187
+ callResources, cpuLimit, memoryLimit, this._defaultResources,
1188
+ )
1189
+
1190
+ // 1. Generate per-Pod auth token
1191
+ const agentToken = randomBytes(32).toString('base64url')
1192
+
1193
+ // 2. Create K8s Secret containing the token
1194
+ const secret = {
1195
+ apiVersion: 'v1',
1196
+ kind: 'Secret',
1197
+ metadata: {
1198
+ name: secretName,
1199
+ labels: {
1200
+ 'app.kubernetes.io/managed-by': 'chroxy',
1201
+ 'chroxy-env-id': envId,
1202
+ },
1203
+ },
1204
+ stringData: {
1205
+ CHROXY_AGENT_TOKEN: agentToken,
1206
+ },
1207
+ }
1208
+
1209
+ log.info(`Creating Secret ${secretName} in namespace ${ns}`)
1210
+ await this._api.createNamespacedSecret({ namespace: ns, body: secret })
1211
+
1212
+ // 3. Build env array for the Pod, merging extra vars + secret ref
1213
+ const env = []
1214
+
1215
+ // Mount the token from the Secret
1216
+ env.push({
1217
+ name: 'CHROXY_AGENT_TOKEN',
1218
+ valueFrom: {
1219
+ secretKeyRef: {
1220
+ name: secretName,
1221
+ key: 'CHROXY_AGENT_TOKEN',
1222
+ },
1223
+ },
1224
+ })
1225
+
1226
+ // Extra env vars from caller
1227
+ if (containerEnv) {
1228
+ for (const [name, value] of Object.entries(containerEnv)) {
1229
+ env.push({ name, value: String(value) })
1230
+ }
1231
+ }
1232
+
1233
+ // 4. Resolve imagePullPolicy: per-call opt > constructor opt > omit (K8s default)
1234
+ const imagePullPolicy = callImagePullPolicy || this._imagePullPolicy
1235
+
1236
+ // 4. Build volumes + volumeMounts
1237
+ // 4a. Workspace volume — one of three mutually-exclusive strategies:
1238
+ // - `opts.cwd` → hostPath volume (single-node clusters, #3316)
1239
+ // - `opts.workspacePVC` → persistentVolumeClaim volume (multi-node clusters, #3385)
1240
+ // - `opts.gitRepo` → emptyDir populated by a git-clone init container (#3193)
1241
+ // See the createEnvironment JSDoc for the strategy comparison and migration
1242
+ // guidance. The validators above already rejected any both-set combination.
1243
+ const volumes = []
1244
+ const volumeMounts = []
1245
+ // Init containers populate the workspace before the main container starts
1246
+ // (git-clone strategy). Empty for the other strategies.
1247
+ const initContainers = []
1248
+
1249
+ if (gitClone) {
1250
+ // git-clone strategy: an emptyDir is shared between the clone init
1251
+ // container(s) and the main container. The init container clones the repo
1252
+ // into the emptyDir; the main container then sees the populated tree.
1253
+ // emptyDir is ephemeral — PVC-backed persistence is the explicit
1254
+ // follow-up (#3385); see the createEnvironment JSDoc.
1255
+ volumes.push({ name: 'workspace', emptyDir: {} })
1256
+ volumeMounts.push({ name: 'workspace', mountPath: gitClone.mountPath })
1257
+ const cloneContainers = buildGitCloneInitContainers(gitClone, this._gitImage)
1258
+ if (imagePullPolicy) {
1259
+ for (const c of cloneContainers) c.imagePullPolicy = imagePullPolicy
1260
+ }
1261
+ initContainers.push(...cloneContainers)
1262
+ } else if (workspacePVC) {
1263
+ const mountPath = workspacePVC.mountPath || '/workspace'
1264
+ volumes.push({
1265
+ name: 'workspace',
1266
+ persistentVolumeClaim: { claimName: workspacePVC.claimName },
1267
+ })
1268
+ const vm = { name: 'workspace', mountPath }
1269
+ if (workspacePVC.readOnly) vm.readOnly = true
1270
+ volumeMounts.push(vm)
1271
+ } else if (cwd) {
1272
+ volumes.push({
1273
+ name: 'workspace',
1274
+ hostPath: { path: cwd, type: 'DirectoryOrCreate' },
1275
+ })
1276
+ volumeMounts.push({
1277
+ name: 'workspace',
1278
+ mountPath: '/workspace',
1279
+ })
1280
+ }
1281
+
1282
+ // 4b. Additional mounts: Docker-style "hostPath:containerPath[:ro]" strings.
1283
+ // Parse results were validated up-front (step 0); a `null` entry means
1284
+ // the input did not match any supported format and is logged + skipped.
1285
+ if (parsedMounts.length > 0) {
1286
+ for (let i = 0; i < parsedMounts.length; i++) {
1287
+ const parsed = parsedMounts[i]
1288
+ if (!parsed) {
1289
+ log.warn(`createEnvironment: ignoring unparseable mount entry "${mounts[i]}"`)
1290
+ continue
1291
+ }
1292
+ const volName = `extra-vol-${i}`
1293
+ volumes.push({
1294
+ name: volName,
1295
+ hostPath: { path: parsed.hostPath, type: 'DirectoryOrCreate' },
1296
+ })
1297
+ const vm = { name: volName, mountPath: parsed.containerPath }
1298
+ if (parsed.readOnly) vm.readOnly = true
1299
+ volumeMounts.push(vm)
1300
+ }
1301
+ }
1302
+
1303
+ // 5. Build ports list: AGENT_PORT is always present; forwardPorts adds more.
1304
+ const ports = [{ containerPort: AGENT_PORT, name: 'agent' }]
1305
+ if (forwardPorts && forwardPorts.length > 0) {
1306
+ for (const entry of forwardPorts) {
1307
+ // Accept bare port number or "hostPort:containerPort" strings.
1308
+ const containerPort = _parseContainerPort(entry)
1309
+ if (containerPort === null) {
1310
+ log.warn(`createEnvironment: ignoring invalid forwardPorts entry "${entry}" (must be 1-65535)`)
1311
+ continue
1312
+ }
1313
+ if (containerPort !== AGENT_PORT) {
1314
+ ports.push({ containerPort })
1315
+ }
1316
+ }
1317
+ }
1318
+
1319
+ // 6. Resources block (requests/limits) was built + validated up-front in
1320
+ // step 0 (`resources`). See buildResourceBlock for the precedence rules
1321
+ // and DEFAULT_RESOURCES for the defaults (#3195).
1322
+
1323
+ // 7. Assemble container spec
1324
+ const containerSpec = {
1325
+ name: 'agent',
1326
+ image: sidecarImage,
1327
+ env,
1328
+ ports,
1329
+ livenessProbe: {
1330
+ httpGet: { path: '/healthz', port: AGENT_PORT },
1331
+ initialDelaySeconds: 5,
1332
+ periodSeconds: 10,
1333
+ },
1334
+ readinessProbe: {
1335
+ httpGet: { path: '/healthz', port: AGENT_PORT },
1336
+ initialDelaySeconds: 2,
1337
+ periodSeconds: 5,
1338
+ },
1339
+ }
1340
+
1341
+ if (imagePullPolicy) {
1342
+ containerSpec.imagePullPolicy = imagePullPolicy
1343
+ }
1344
+
1345
+ if (volumeMounts.length > 0) {
1346
+ containerSpec.volumeMounts = volumeMounts
1347
+ }
1348
+
1349
+ if (Object.keys(resources).length > 0) {
1350
+ containerSpec.resources = resources
1351
+ }
1352
+
1353
+ // 8. Assemble Pod spec
1354
+ const podSpec = {
1355
+ restartPolicy: 'Never',
1356
+ containers: [containerSpec],
1357
+ }
1358
+
1359
+ if (initContainers.length > 0) {
1360
+ podSpec.initContainers = initContainers
1361
+ }
1362
+
1363
+ if (volumes.length > 0) {
1364
+ podSpec.volumes = volumes
1365
+ }
1366
+
1367
+ const pod = {
1368
+ apiVersion: 'v1',
1369
+ kind: 'Pod',
1370
+ metadata: {
1371
+ name: podName,
1372
+ labels: {
1373
+ 'app.kubernetes.io/managed-by': 'chroxy',
1374
+ 'chroxy-env-id': envId,
1375
+ },
1376
+ },
1377
+ spec: podSpec,
1378
+ }
1379
+
1380
+ log.info(`Creating Pod ${podName} in namespace ${ns}`)
1381
+ try {
1382
+ await this._api.createNamespacedPod({ namespace: ns, body: pod })
1383
+ } catch (err) {
1384
+ // Pod creation failed — clean up the Secret we already created
1385
+ log.warn(`Pod creation failed, removing Secret ${secretName}: ${err.message}`)
1386
+ await this._deleteSecret(secretName, ns)
1387
+ throw err
1388
+ }
1389
+
1390
+ // Register the token internally so streamCliInEnvironment() can look it
1391
+ // up by Pod name without callers having to plumb it through.
1392
+ this._agentTokens.set(podName, agentToken)
1393
+
1394
+ return {
1395
+ containerId: podName,
1396
+ containerCliPath: DEFAULT_CONTAINER_CLI_PATH,
1397
+ agentToken,
1398
+ secretName,
1399
+ }
1400
+ }
1401
+
1402
+ // ─────────────────────────────────────────────────────────────────────────
1403
+ // destroyEnvironment — delete Pod + Secret and wait until Pod is gone (or 404)
1404
+ // ─────────────────────────────────────────────────────────────────────────
1405
+
1406
+ /**
1407
+ * Deletes the named Pod and polls until it no longer exists (404).
1408
+ * Also deletes the per-Pod Secret.
1409
+ *
1410
+ * `secretName` defaults to `chroxy-token-<envId>` derived from the canonical
1411
+ * `chroxy-env-<envId>` pod name. Callers that created the Pod via
1412
+ * createEnvironment() do not need to plumb the secret name through.
1413
+ *
1414
+ * Best-effort by design (mirrors `DockerBackend._removeContainer`):
1415
+ * - Idempotent: if the Pod is already gone (404 on delete), resolves immediately.
1416
+ * - If `deleteNamespacedPod` fails with a non-404 error, logs a warning and resolves
1417
+ * without throwing (the env record is removed regardless).
1418
+ * - The poll loop exits early on the first non-404 read error rather than retrying.
1419
+ * - Falls through to a timeout warning if the Pod never disappears within
1420
+ * {@link DESTROY_TIMEOUT_MS}.
1421
+ *
1422
+ * @param {string} podName - Pod name (the containerId handle stored by EnvironmentManager)
1423
+ * @param {Object} [opts]
1424
+ * @param {string} [opts.namespace] - Explicit namespace override
1425
+ * @param {string} [opts.userId] - Tenant identity for namespace isolation (#3194)
1426
+ * @param {string} [opts.projectId] - Project identity for namespace isolation (#3194)
1427
+ * @param {string} [opts.secretName] - Per-Pod Secret to delete (default: derived from podName)
1428
+ * @returns {Promise<void>}
1429
+ */
1430
+ async destroyEnvironment(podName, opts = {}) {
1431
+ const ns = this._namespaceForCall(opts, 'destroyEnvironment')
1432
+ const secretName = opts.secretName || _deriveSecretName(podName)
1433
+
1434
+ // Always drop the cached token first so a partial failure can't leave
1435
+ // a dangling token in memory.
1436
+ this._agentTokens.delete(podName)
1437
+
1438
+ log.info(`Deleting Pod ${podName} in namespace ${ns}`)
1439
+
1440
+ try {
1441
+ await this._api.deleteNamespacedPod({ name: podName, namespace: ns })
1442
+ } catch (err) {
1443
+ if (_isNotFound(err)) {
1444
+ log.info(`Pod ${podName} already gone`)
1445
+ // Still clean up the Secret
1446
+ await this._deleteSecret(secretName, ns)
1447
+ return
1448
+ }
1449
+ log.warn(`Failed to delete Pod ${podName}: ${err.message}`)
1450
+ await this._deleteSecret(secretName, ns)
1451
+ // Best-effort: do not rethrow — mirrors DockerBackend._removeContainer
1452
+ return
1453
+ }
1454
+
1455
+ // Poll until the Pod disappears from the API
1456
+ const deadline = Date.now() + DESTROY_TIMEOUT_MS
1457
+ while (Date.now() < deadline) {
1458
+ await _sleep(POLL_INTERVAL_MS)
1459
+ try {
1460
+ await this._api.readNamespacedPod({ name: podName, namespace: ns })
1461
+ // Pod still exists — keep polling
1462
+ } catch (err) {
1463
+ if (_isNotFound(err)) {
1464
+ log.info(`Pod ${podName} terminated`)
1465
+ await this._deleteSecret(secretName, ns)
1466
+ return
1467
+ }
1468
+ log.warn(`Error polling Pod ${podName}: ${err.message}`)
1469
+ await this._deleteSecret(secretName, ns)
1470
+ return
1471
+ }
1472
+ }
1473
+
1474
+ log.warn(`Timed out waiting for Pod ${podName} to terminate`)
1475
+ await this._deleteSecret(secretName, ns)
1476
+ }
1477
+
1478
+ // ─────────────────────────────────────────────────────────────────────────
1479
+ // getEnvironmentStatus — read Pod phase via readNamespacedPod
1480
+ // ─────────────────────────────────────────────────────────────────────────
1481
+
1482
+ /**
1483
+ * Returns true if the Pod exists and its phase is 'Running'.
1484
+ *
1485
+ * @param {string} podName
1486
+ * @param {Object} [opts]
1487
+ * @param {string} [opts.namespace] - Explicit namespace override
1488
+ * @param {string} [opts.userId] - Tenant identity for namespace isolation (#3194)
1489
+ * @param {string} [opts.projectId] - Project identity for namespace isolation (#3194)
1490
+ * @returns {Promise<boolean>}
1491
+ * @throws {Error} If the Pod does not exist
1492
+ */
1493
+ async getEnvironmentStatus(podName, opts = {}) {
1494
+ const ns = this._namespaceForCall(opts, 'getEnvironmentStatus')
1495
+ const result = await this._api.readNamespacedPod({ name: podName, namespace: ns })
1496
+ const phase = result?.status?.phase
1497
+ return phase === 'Running'
1498
+ }
1499
+
1500
+ // ─────────────────────────────────────────────────────────────────────────
1501
+ // execInEnvironment — one-shot command via streamCliInEnvironment wrapper
1502
+ // ─────────────────────────────────────────────────────────────────────────
1503
+
1504
+ /**
1505
+ * Run a command inside the Pod and return buffered stdout/stderr.
1506
+ * Thin wrapper over streamCliInEnvironment — captures output to strings,
1507
+ * resolves on exit code 0, rejects on non-zero exit.
1508
+ *
1509
+ * @param {string} podName
1510
+ * @param {Object} opts
1511
+ * @param {string} opts.cmd - Command to run
1512
+ * @param {string[]} [opts.args] - Arguments
1513
+ * @param {Object.<string,string>} [opts.env] - Extra env vars
1514
+ * @param {string} [opts.cwd] - Working directory
1515
+ * @param {number} [opts.timeout=30000] - Timeout in ms
1516
+ * @param {string} opts.agentToken - Auth token for the sidecar
1517
+ * @returns {Promise<{ stdout: string, stderr: string }>}
1518
+ */
1519
+ execInEnvironment(podName, opts = {}) {
1520
+ const { timeout = 30_000 } = opts
1521
+
1522
+ return new Promise((resolve, reject) => {
1523
+ let proc
1524
+ let settled = false
1525
+
1526
+ const settleReject = (err) => {
1527
+ if (settled) return
1528
+ settled = true
1529
+ if (timer) clearTimeout(timer)
1530
+ // Drain output streams so PassThroughs never accumulate buffered
1531
+ // data after the consumer has moved on (avoids slow-leak on a
1532
+ // long-running pod-side child after timeout).
1533
+ if (proc) {
1534
+ try { proc.stdout.resume() } catch (_) { /* ignore */ }
1535
+ try { proc.stderr.resume() } catch (_) { /* ignore */ }
1536
+ }
1537
+ reject(err)
1538
+ }
1539
+
1540
+ const settleResolve = (value) => {
1541
+ if (settled) return
1542
+ settled = true
1543
+ if (timer) clearTimeout(timer)
1544
+ resolve(value)
1545
+ }
1546
+
1547
+ const timer = timeout > 0
1548
+ ? setTimeout(() => {
1549
+ // Kill the underlying process so the WS closes and the agent
1550
+ // SIGTERMs the in-pod child (PROTOCOL.md "Lifecycle and Orphan
1551
+ // Prevention"). Otherwise the WS + child + buffered streams
1552
+ // leak past the caller's await point.
1553
+ if (proc && typeof proc.kill === 'function') {
1554
+ try { proc.kill('SIGTERM') } catch (_) { /* ignore */ }
1555
+ }
1556
+ settleReject(new Error(`execInEnvironment timed out after ${timeout}ms`))
1557
+ }, timeout)
1558
+ : null
1559
+
1560
+ try {
1561
+ proc = this.streamCliInEnvironment(podName, opts)
1562
+ } catch (err) {
1563
+ settleReject(err)
1564
+ return
1565
+ }
1566
+
1567
+ let stdout = ''
1568
+ let stderr = ''
1569
+
1570
+ proc.stdout.on('data', (chunk) => { stdout += chunk.toString() })
1571
+ proc.stderr.on('data', (chunk) => { stderr += chunk.toString() })
1572
+
1573
+ proc.on('exit', (code) => {
1574
+ if (code === 0 || code === null) {
1575
+ settleResolve({ stdout, stderr })
1576
+ } else {
1577
+ settleReject(new Error(stderr.trim() || `Command exited with code ${code}`))
1578
+ }
1579
+ })
1580
+
1581
+ proc.on('error', (err) => {
1582
+ settleReject(err)
1583
+ })
1584
+ })
1585
+ }
1586
+
1587
+ // ─────────────────────────────────────────────────────────────────────────
1588
+ // streamCliInEnvironment — open WS to sidecar, send spawn frame, bridge I/O
1589
+ // ─────────────────────────────────────────────────────────────────────────
1590
+
1591
+ /**
1592
+ * Opens a WebSocket connection to the chroxy-pod-agent sidecar running inside
1593
+ * the Pod, sends a `spawn` frame per the sidecar protocol (PROTOCOL.md), and
1594
+ * returns a ChildProcess-shaped EventEmitter that bridges the WS events to the
1595
+ * SpawnedProcess interface consumed by the Agent SDK.
1596
+ *
1597
+ * Connection is established asynchronously (the WS dial happens in the
1598
+ * background; the spawn frame is sent on `open`). The returned handle
1599
+ * immediately exposes `stdout`, `stderr`, and `stdin` streams so the caller
1600
+ * can attach listeners before the connection completes.
1601
+ *
1602
+ * The bearer token used to authenticate with the sidecar is read from the
1603
+ * backend's per-Pod registry (populated by `createEnvironment`). Callers do
1604
+ * not need to thread `agentToken` through opts; for tests / external pods
1605
+ * the token may be passed explicitly via `opts.agentToken`.
1606
+ *
1607
+ * Like DockerBackend.streamCliInEnvironment, this method also remaps the
1608
+ * SDK's host-absolute `cli.js` path (passed as args[0]) to the container's
1609
+ * installed CLI path so the Pod can actually exec it.
1610
+ *
1611
+ * @param {string} podName
1612
+ * @param {Object} opts
1613
+ * @param {string} opts.cmd - Binary to execute inside the Pod
1614
+ * @param {string[]} [opts.args] - Argument list
1615
+ * @param {Object.<string,string>} [opts.env] - Extra env vars for the child
1616
+ * @param {string} [opts.cwd] - Working directory for the child
1617
+ * @param {AbortSignal} [opts.signal] - Abort → SIGTERM the child (WS close)
1618
+ * @param {string} [opts.agentToken] - Override the registered bearer token (test seam)
1619
+ * @param {string} [opts.containerCliPath] - Pod-side cli.js path (default fallback)
1620
+ * @param {string} [opts.hostCwd] - Host CWD mount root for path remapping
1621
+ * @param {string} [opts.namespace] - Explicit namespace override
1622
+ * @param {string} [opts.userId] - Tenant identity for namespace isolation (#3194)
1623
+ * @param {string} [opts.projectId] - Project identity for namespace isolation (#3194)
1624
+ * @returns {SidecarProcess} ChildProcess-shaped handle
1625
+ */
1626
+ streamCliInEnvironment(podName, opts = {}) {
1627
+ const {
1628
+ cmd, args = [], env, cwd, signal,
1629
+ containerCliPath = DEFAULT_CONTAINER_CLI_PATH,
1630
+ hostCwd,
1631
+ } = opts
1632
+ const ns = this._namespaceForCall(opts, 'streamCliInEnvironment')
1633
+
1634
+ // Prefer explicit token (test seam), fall back to the in-memory cache, and
1635
+ // lazily fetch from the K8s Secret when neither is available (e.g. after a
1636
+ // server restart that cleared _agentTokens). The lazy path is async, so we
1637
+ // wrap the entire dial in a Promise and let it proceed in the background.
1638
+ const tokenOrPromise = opts.agentToken
1639
+ || this._agentTokens.get(podName)
1640
+ || this._readAgentToken(podName, ns)
1641
+
1642
+ // Remap host cli.js path to container path, mirroring DockerBackend.
1643
+ const containerArgs = [...args]
1644
+ if (containerArgs.length > 0 &&
1645
+ typeof containerArgs[0] === 'string' &&
1646
+ containerArgs[0].includes('@anthropic-ai/claude-code/cli.js')) {
1647
+ log.info(`Remapped CLI path: ${containerArgs[0]} -> ${containerCliPath}`)
1648
+ containerArgs[0] = containerCliPath
1649
+ }
1650
+
1651
+ // Remap host cwd to /workspace inside the Pod when provided.
1652
+ let containerCwd = cwd
1653
+ if (cwd && hostCwd) {
1654
+ containerCwd = cwd.startsWith(hostCwd)
1655
+ ? '/workspace' + cwd.slice(hostCwd.length)
1656
+ : '/workspace'
1657
+ }
1658
+
1659
+ const {
1660
+ _reconnectDelays: reconnectDelays,
1661
+ _maxRetries: maxRetries,
1662
+ _maxStdinBufferBytes: maxStdinBufferBytes,
1663
+ _setTimeout: setTimeoutImpl,
1664
+ _clearTimeout: clearTimeoutImpl,
1665
+ } = this
1666
+ const proc = new SidecarProcess({
1667
+ reconnectDelays, maxRetries, maxStdinBufferBytes, setTimeoutImpl, clearTimeoutImpl,
1668
+ })
1669
+
1670
+ // Resolve the token (synchronous fast path or async Secret fetch), then dial.
1671
+ Promise.resolve(tokenOrPromise).then((agentToken) => {
1672
+ if (!agentToken) {
1673
+ // Phrasing kept compatible with the existing /agentToken is required/
1674
+ // assertion. The token is normally registered by createEnvironment() or
1675
+ // repopulated by reconnect(); tests can still pass opts.agentToken directly.
1676
+ throw new Error(
1677
+ `K8sBackend.streamCliInEnvironment: agentToken is required for Pod "${podName}" ` +
1678
+ '(register via createEnvironment(), reconnect(), or pass opts.agentToken)'
1679
+ )
1680
+ }
1681
+
1682
+ // Bind a redial function so the reconnect loop inside _wireWsToProc can
1683
+ // re-dial the same pod without holding a reference to this K8sBackend.
1684
+ proc._redial = () => this._dial(podName, ns, agentToken)
1685
+
1686
+ // Dial asynchronously; the returned handle is usable immediately. We
1687
+ // capture portforward cleanup callbacks so kill() / exit can tear down
1688
+ // the local TCP listener even if dial completes after kill is called.
1689
+ return this._dial(podName, ns, agentToken)
1690
+ }).then((dialResult) => {
1691
+ // dialResult is either { ws, cleanup? } (portforward bridge) or a bare
1692
+ // ws (clusterip / direct dial). Normalize.
1693
+ const ws = dialResult && dialResult.ws ? dialResult.ws : dialResult
1694
+ const cleanup = dialResult && typeof dialResult.cleanup === 'function'
1695
+ ? dialResult.cleanup : null
1696
+
1697
+ // Race: kill() / abort may have fired before dial resolved. In that
1698
+ // case `proc.killed` is set but `_ws` is null, so the synchronous
1699
+ // kill() call did nothing. Detect that here and tear down cleanly.
1700
+ if (proc.killed || (signal && signal.aborted)) {
1701
+ try { ws.close() } catch (_) { /* ignore */ }
1702
+ if (cleanup) { try { cleanup() } catch (_) { /* ignore */ } }
1703
+ if (!proc._exited) {
1704
+ proc._exited = true
1705
+ proc.stdout.push(null)
1706
+ proc.stderr.push(null)
1707
+ proc.emit('exit', -1)
1708
+ }
1709
+ return
1710
+ }
1711
+
1712
+ _wireWsToProc(ws, proc, {
1713
+ cmd, args: containerArgs, env, cwd: containerCwd, signal, cleanup,
1714
+ })
1715
+ }).catch((err) => {
1716
+ log.warn(`streamCliInEnvironment dial failed for ${podName}: ${err.message}`)
1717
+ if (!proc._exited) {
1718
+ proc._exited = true
1719
+ proc.stdout.push(null)
1720
+ proc.stderr.push(null)
1721
+ proc.emit('exit', -1)
1722
+ }
1723
+ })
1724
+
1725
+ return proc
1726
+ }
1727
+
1728
+ // ─────────────────────────────────────────────────────────────────────────
1729
+ // reconnectAgentToken — repopulate _agentTokens from the K8s Secret
1730
+ // ─────────────────────────────────────────────────────────────────────────
1731
+
1732
+ /**
1733
+ * Reads the per-Pod Secret and registers the agent token in the in-memory
1734
+ * cache. Called by EnvironmentManager.reconnect() for K8s-backed
1735
+ * environments so that streamCliInEnvironment() works after a server restart.
1736
+ *
1737
+ * Returns `true` when the token was successfully fetched and cached; `false`
1738
+ * when the Secret no longer exists (Pod was externally garbage-collected).
1739
+ *
1740
+ * @param {string} podName - Pod name (the containerId handle)
1741
+ * @param {Object} [opts]
1742
+ * @param {string} [opts.namespace] - Explicit namespace override
1743
+ * @param {string} [opts.userId] - Tenant identity for namespace isolation (#3194)
1744
+ * @param {string} [opts.projectId] - Project identity for namespace isolation (#3194)
1745
+ * @returns {Promise<boolean>}
1746
+ */
1747
+ async reconnectAgentToken(podName, opts = {}) {
1748
+ const ns = this._namespaceForCall(opts, 'reconnectAgentToken')
1749
+ const token = await this._readAgentToken(podName, ns)
1750
+ return token !== null
1751
+ }
1752
+
1753
+ // ─────────────────────────────────────────────────────────────────────────
1754
+ // Phase-1 stubs — not yet implemented
1755
+ // ─────────────────────────────────────────────────────────────────────────
1756
+
1757
+ createComposeEnvironment(_opts) {
1758
+ return Promise.reject(notImplemented('createComposeEnvironment'))
1759
+ }
1760
+
1761
+ destroyComposeEnvironment(_opts) {
1762
+ return Promise.reject(notImplemented('destroyComposeEnvironment'))
1763
+ }
1764
+
1765
+ removeImage(_imageTag) {
1766
+ return Promise.reject(notImplemented('removeImage'))
1767
+ }
1768
+
1769
+ // ─────────────────────────────────────────────────────────────────────────
1770
+ // listEnvironments — list chroxy-managed Pods, scoped to one namespace (#3194)
1771
+ // ─────────────────────────────────────────────────────────────────────────
1772
+
1773
+ /**
1774
+ * List the names of chroxy-managed Pods in a single namespace (#3194).
1775
+ *
1776
+ * Multi-tenant isolation: the list is scoped to exactly one namespace — the
1777
+ * one resolved from the caller's identity (or the explicit/static namespace) —
1778
+ * and filtered by the `app.kubernetes.io/managed-by=chroxy` label so it never
1779
+ * returns Pods belonging to other tenants or unrelated workloads in the same
1780
+ * namespace. There is intentionally no cluster-wide list: a tenant must only
1781
+ * ever see its own environments.
1782
+ *
1783
+ * A brand-new tenant whose namespace has not been created yet has, by
1784
+ * definition, no environments. The K8s API returns 404 ("namespace not
1785
+ * found") for `listNamespacedPod` in that case, which we translate to an empty
1786
+ * list rather than surfacing as an error.
1787
+ *
1788
+ * @param {Object} [opts]
1789
+ * @param {string} [opts.namespace] - Explicit namespace to list
1790
+ * @param {string} [opts.userId] - Tenant identity for namespace resolution
1791
+ * @param {string} [opts.projectId] - Project identity for namespace resolution
1792
+ * @returns {Promise<string[]>} Pod names (the containerId handles) in the namespace
1793
+ */
1794
+ async listEnvironments(opts = {}) {
1795
+ const ns = this._namespaceForCall(opts, 'listEnvironments')
1796
+ let result
1797
+ try {
1798
+ result = await this._api.listNamespacedPod({
1799
+ namespace: ns,
1800
+ labelSelector: 'app.kubernetes.io/managed-by=chroxy',
1801
+ })
1802
+ } catch (err) {
1803
+ // The tenant namespace does not exist yet → no environments.
1804
+ if (_isNotFound(err)) return []
1805
+ throw err
1806
+ }
1807
+ const items = result?.items || []
1808
+ return items
1809
+ .map((pod) => pod?.metadata?.name)
1810
+ .filter((name) => typeof name === 'string' && name.length > 0)
1811
+ }
1812
+
1813
+ commitEnvironment(_containerId, _imageTag) {
1814
+ return Promise.reject(notImplemented('commitEnvironment'))
1815
+ }
1816
+
1817
+ // K8s pods have unique names by design — there is no mutable canonical name
1818
+ // slot to free. The restore flow tolerates a no-op here because the old pod
1819
+ // is destroyed after the new one passes its health check. See types.js.
1820
+ renameEnvironment(_containerId, _newName) {
1821
+ return Promise.resolve()
1822
+ }
1823
+
1824
+ restoreEnvironment(_opts) {
1825
+ return Promise.reject(notImplemented('restoreEnvironment'))
1826
+ }
1827
+
1828
+ // ─────────────────────────────────────────────────────────────────────────
1829
+ // Private helpers
1830
+ // ─────────────────────────────────────────────────────────────────────────
1831
+
1832
+ /**
1833
+ * Resolve the WebSocket URL for the sidecar and open a connection.
1834
+ * Mode 'clusterip': dial pod-ip:AGENT_PORT directly.
1835
+ * Mode 'portforward': open a local TCP listener and bridge each connection
1836
+ * through @kubernetes/client-node `PortForward` to the Pod's AGENT_PORT,
1837
+ * then dial localhost:<listenerPort>.
1838
+ *
1839
+ * When `_dialWs` was injected at construction time (test mode) the lookup
1840
+ * and port-forward machinery is skipped and `_dialWs` is called directly
1841
+ * with a synthetic URL so unit tests never need a real cluster.
1842
+ *
1843
+ * @param {string} podName
1844
+ * @param {string} ns
1845
+ * @param {string} token
1846
+ * @returns {Promise<WebSocket | { ws: WebSocket, cleanup: Function }>}
1847
+ * Returns either a bare WebSocket (clusterip / direct dial) or a dial
1848
+ * result object that includes a `cleanup` callback for tearing down the
1849
+ * local TCP listener (portforward mode). The caller is expected to invoke
1850
+ * `cleanup` on exit/error so listeners do not leak.
1851
+ */
1852
+ async _dial(podName, ns, token) {
1853
+ if (this._directDial) {
1854
+ return this._dialWs(`ws://test/${podName}`, token)
1855
+ }
1856
+
1857
+ if (this._connectMode === 'clusterip') {
1858
+ const podIp = await this._getPodIp(podName, ns)
1859
+ const url = `ws://${podIp}:${AGENT_PORT}`
1860
+ log.info(`Dialing sidecar ${podName} via ClusterIP: ${url}`)
1861
+ return this._dialWs(url, token)
1862
+ }
1863
+
1864
+ // portforward mode
1865
+ return this._dialViaPortForward(podName, ns, token)
1866
+ }
1867
+
1868
+ /**
1869
+ * Look up the Pod's IP address from the API.
1870
+ *
1871
+ * @param {string} podName
1872
+ * @param {string} ns
1873
+ * @returns {Promise<string>}
1874
+ */
1875
+ async _getPodIp(podName, ns) {
1876
+ const result = await this._api.readNamespacedPod({ name: podName, namespace: ns })
1877
+ const ip = result?.status?.podIP
1878
+ if (!ip) throw new Error(`Pod ${podName} has no podIP yet — is it Running?`)
1879
+ return ip
1880
+ }
1881
+
1882
+ /**
1883
+ * Set up a localhost TCP listener that bridges each incoming connection
1884
+ * through `PortForward.portForward` to the Pod's AGENT_PORT, then dial
1885
+ * `ws://127.0.0.1:<listenerPort>` and return both the WS and a cleanup
1886
+ * callback that closes the listener.
1887
+ *
1888
+ * The `@kubernetes/client-node` `PortForward` API is per-connection: it
1889
+ * does NOT bind a local TCP listener — the caller does. Each call to
1890
+ * `pf.portForward(ns, pod, [TARGET_POD_PORT], stream, errStream, input,
1891
+ * [TARGET_POD_PORT])` proxies a single duplex stream pair to the pod's
1892
+ * `TARGET_POD_PORT`. We wire the local TCP socket as that stream pair so
1893
+ * an HTTP/WS client connecting to the listener appears at the pod's port
1894
+ * 7681 (AGENT_PORT) end-to-end.
1895
+ *
1896
+ * @param {string} podName
1897
+ * @param {string} ns
1898
+ * @param {string} token
1899
+ * @returns {Promise<{ ws: WebSocket, cleanup: Function }>}
1900
+ */
1901
+ async _dialViaPortForward(podName, ns, token) {
1902
+ const net = this._netImpl || (await import('net'))
1903
+ const pf = this._portForwardImpl || (this._kc ? new PortForward(this._kc) : null)
1904
+ if (!pf) {
1905
+ throw new Error('PortForward not available — no KubeConfig (was _coreV1Api injected in tests?)')
1906
+ }
1907
+
1908
+ return new Promise((resolve, reject) => {
1909
+ // Bridge each accepted local TCP connection through the K8s
1910
+ // portforward subresource to the Pod's fixed AGENT_PORT.
1911
+ const server = net.createServer((socket) => {
1912
+ try {
1913
+ // Per @kubernetes/client-node API:
1914
+ // portForward(ns, podName, targetPorts, output, error, input, [outputPorts])
1915
+ // The target/output port array contains the POD-side port, not the
1916
+ // local listener port.
1917
+ pf.portForward(ns, podName, [AGENT_PORT], socket, socket, socket, [AGENT_PORT])
1918
+ } catch (err) {
1919
+ log.warn(`portForward bridge error for ${podName}: ${err.message}`)
1920
+ try { socket.destroy() } catch (_) { /* ignore */ }
1921
+ }
1922
+ })
1923
+
1924
+ server.on('error', (err) => {
1925
+ log.warn(`portforward listener error for ${podName}: ${err.message}`)
1926
+ })
1927
+
1928
+ server.listen(0, '127.0.0.1', async () => {
1929
+ const localPort = server.address().port
1930
+ const url = `ws://127.0.0.1:${localPort}`
1931
+ log.info(`Dialing sidecar ${podName} via port-forward listener on port ${localPort}`)
1932
+
1933
+ const cleanup = () => {
1934
+ try { server.close() } catch (_) { /* ignore */ }
1935
+ }
1936
+
1937
+ try {
1938
+ const ws = await this._dialWs(url, token)
1939
+ resolve({ ws, cleanup })
1940
+ } catch (err) {
1941
+ cleanup()
1942
+ reject(err)
1943
+ }
1944
+ })
1945
+ })
1946
+ }
1947
+
1948
+ /**
1949
+ * Read the per-Pod Secret and return the agent token, caching it in
1950
+ * `_agentTokens` for subsequent calls. Returns `null` when the Secret
1951
+ * does not exist (404) so callers can distinguish "gone" from errors.
1952
+ *
1953
+ * This is the recovery path for server restart: the Secret is the canonical
1954
+ * source of truth for the token; the in-memory map is just a cache.
1955
+ *
1956
+ * Concurrent callers for the same pod are coalesced: only one K8s API
1957
+ * request is issued at a time. The in-flight promise is stored in
1958
+ * `_pendingAgentTokens` and cleared once it settles, so a subsequent call
1959
+ * after resolution starts a fresh fetch (needed for the reconnect path where
1960
+ * the Secret may have been rotated).
1961
+ *
1962
+ * @param {string} podName
1963
+ * @param {string} ns
1964
+ * @returns {Promise<string|null>}
1965
+ */
1966
+ _readAgentToken(podName, ns) {
1967
+ // Return the in-flight promise if one already exists for this pod.
1968
+ if (this._pendingAgentTokens.has(podName)) {
1969
+ return this._pendingAgentTokens.get(podName)
1970
+ }
1971
+
1972
+ const secretName = _deriveSecretName(podName)
1973
+ const pending = (async () => {
1974
+ try {
1975
+ const secret = await this._api.readNamespacedSecret({ name: secretName, namespace: ns })
1976
+ // The K8s API decodes base64 stringData into `.data` as base64-encoded
1977
+ // strings, but when we store via `stringData` the API may return the
1978
+ // value under either field depending on the client version. Prefer
1979
+ // `data` (always present on read responses), fall back to `stringData`.
1980
+ const raw = secret?.data?.CHROXY_AGENT_TOKEN
1981
+ || secret?.stringData?.CHROXY_AGENT_TOKEN
1982
+ if (!raw) {
1983
+ log.warn(`Secret ${secretName} exists but has no CHROXY_AGENT_TOKEN — treating as missing`)
1984
+ return null
1985
+ }
1986
+ // K8s stores Secret `.data` values as base64; decode unconditionally.
1987
+ // If the value came via `stringData` it is already plaintext, but a
1988
+ // base64-decode of a base64url-encoded token (no padding) is idempotent
1989
+ // only when the token length is a multiple of 4. Instead, detect the
1990
+ // encoding: `data` values are padded base64; `stringData` values are not.
1991
+ const token = secret?.data?.CHROXY_AGENT_TOKEN
1992
+ ? Buffer.from(raw, 'base64').toString('utf8')
1993
+ : raw
1994
+ // Cache for subsequent calls so we only hit the API once per pod per process.
1995
+ this._agentTokens.set(podName, token)
1996
+ log.info(`Loaded agentToken for Pod ${podName} from Secret ${secretName}`)
1997
+ return token
1998
+ } catch (err) {
1999
+ if (_isNotFound(err)) {
2000
+ log.warn(`Secret ${secretName} not found — pod may have been externally deleted`)
2001
+ return null
2002
+ }
2003
+ throw err
2004
+ } finally {
2005
+ // Always clear the in-flight entry so the next caller starts a fresh
2006
+ // fetch (important for the reconnect path where the Secret may rotate).
2007
+ this._pendingAgentTokens.delete(podName)
2008
+ }
2009
+ })()
2010
+
2011
+ this._pendingAgentTokens.set(podName, pending)
2012
+ return pending
2013
+ }
2014
+
2015
+ /**
2016
+ * Delete a K8s Secret, swallowing 404s and errors (best-effort).
2017
+ *
2018
+ * @param {string} secretName
2019
+ * @param {string} ns
2020
+ */
2021
+ async _deleteSecret(secretName, ns) {
2022
+ try {
2023
+ await this._api.deleteNamespacedSecret({ name: secretName, namespace: ns })
2024
+ log.info(`Deleted Secret ${secretName}`)
2025
+ } catch (err) {
2026
+ if (!_isNotFound(err)) {
2027
+ log.warn(`Failed to delete Secret ${secretName}: ${err.message}`)
2028
+ }
2029
+ }
2030
+ }
2031
+ }
2032
+
2033
+ // ─── SidecarProcess ──────────────────────────────────────────────────────────
2034
+
2035
+ /**
2036
+ * ChildProcess-shaped EventEmitter that bridges the sidecar WebSocket protocol
2037
+ * to the SpawnedProcess interface expected by the Agent SDK.
2038
+ *
2039
+ * Exposes:
2040
+ * - `stdout` {PassThrough} — receives data pushed via `event` WS frames
2041
+ * - `stderr` {PassThrough} — receives data pushed via `stderr` WS frames
2042
+ * - `stdin` {PassThrough} — writes here are forwarded to the sidecar as
2043
+ * `stdin` / `stdin_end` WS frames (#3336)
2044
+ * - `'exit'` event (code) — emitted when the `exit` WS frame arrives or on error
2045
+ *
2046
+ * On unexpected WS disconnect the process attempts to reconnect with exponential
2047
+ * backoff (#3321). The redial function is injected via `proc._redial` after
2048
+ * construction by `K8sBackend.streamCliInEnvironment`.
2049
+ *
2050
+ * ### stdin forwarding and reconnect semantics
2051
+ *
2052
+ * `stdin` frames are NOT buffered by the agent's ring buffer and are NOT
2053
+ * replayed on resume. A reconnect (`resume` frame) picks up output from where
2054
+ * the client left off — it does NOT re-send stdin. Callers must NOT replay
2055
+ * stdin data after a reconnect; doing so would cause the in-pod child to
2056
+ * receive duplicate input.
2057
+ *
2058
+ * ### stdin write before WS is open
2059
+ *
2060
+ * Writes that arrive before the WS dial resolves are held in `_stdinBuffer`
2061
+ * (an array of Buffer chunks) and flushed as `stdin` frames when `_wireStdin`
2062
+ * is called by `_wireWsToProc` after the connection opens. If the process is
2063
+ * killed or exits before the dial resolves, the buffer is discarded silently.
2064
+ *
2065
+ * The pre-dial buffer is capped at `maxStdinBufferBytes` (default 1 MiB,
2066
+ * #3401). Writes that would push the buffer past the cap are dropped with
2067
+ * a `log.warn`; this prevents unbounded memory growth when the WS dial
2068
+ * hangs and a fast producer keeps writing. `kill()` clears the buffer
2069
+ * immediately so the bytes are not held until GC.
2070
+ *
2071
+ * Each over-cap drop also emits a `'stdin_dropped'` event on the proc with
2072
+ * `{ bytes, reason: 'pre-dial-cap' }` so consumers (`SdkSession`) get a
2073
+ * runtime signal instead of silent loss (#3474). The event fires once per
2074
+ * dropped chunk; the log.warn spam guard only suppresses repeat log lines,
2075
+ * not the event itself.
2076
+ *
2077
+ * ### stdin disabled signal (#3402)
2078
+ *
2079
+ * On WS reconnect (`resume` frame) stdin forwarding is intentionally NOT
2080
+ * re-wired — see resume semantics above. To prevent silent data loss when a
2081
+ * consumer keeps writing after reconnect, the proc emits a one-shot
2082
+ * `'stdin_disabled'` event the moment forwarding becomes unrecoverable
2083
+ * (reconnect dial succeeds, or WS closes mid-write before reconnect). After
2084
+ * that point further writes are dropped and the consumer can use
2085
+ * `isStdinForwardingEnabled()` to poll the current state.
2086
+ */
2087
+ class SidecarProcess extends EventEmitter {
2088
+ /**
2089
+ * @param {Object} [opts]
2090
+ * @param {number[]} [opts.reconnectDelays] - Backoff delay schedule in ms
2091
+ * @param {number} [opts.maxRetries] - Max reconnect attempts before giving up
2092
+ * @param {number} [opts.maxStdinBufferBytes] - Pre-dial stdin buffer cap in bytes (#3401)
2093
+ * @param {Function} [opts.setTimeoutImpl] - setTimeout override for deterministic testing
2094
+ * @param {Function} [opts.clearTimeoutImpl] - clearTimeout override for deterministic testing
2095
+ */
2096
+ constructor({
2097
+ reconnectDelays = DEFAULT_RECONNECT_DELAYS,
2098
+ maxRetries = DEFAULT_MAX_RETRIES,
2099
+ maxStdinBufferBytes = DEFAULT_MAX_STDIN_BUFFER_BYTES,
2100
+ setTimeoutImpl,
2101
+ clearTimeoutImpl,
2102
+ } = {}) {
2103
+ super()
2104
+ this.stdout = new PassThrough()
2105
+ this.stderr = new PassThrough()
2106
+ this.stdin = new PassThrough()
2107
+ this.killed = false
2108
+ this._exited = false
2109
+ this._ws = null
2110
+ this._cleanup = null
2111
+
2112
+ // Reconnect state (#3321)
2113
+ this._reconnectDelays = reconnectDelays
2114
+ this._maxRetries = maxRetries
2115
+ this._retryAttempt = 0 // current reconnect attempt count
2116
+ this._retryTimer = null // pending setTimeout handle for next reconnect
2117
+ this._sessionId = null // set by _wireWsToProc when session_started arrives
2118
+ this._lastSeq = 0 // last seq number seen from the sidecar
2119
+ this._redial = null // injected by K8sBackend.streamCliInEnvironment
2120
+
2121
+ // Timer seam: defaults to globals; override in tests for deterministic scheduling.
2122
+ this._setTimeout = setTimeoutImpl || setTimeout
2123
+ this._clearTimeout = clearTimeoutImpl || clearTimeout
2124
+ // stdin forwarding (#3336): buffer writes that arrive before the WS opens.
2125
+ // Once _wireStdin() is called the buffer is flushed and subsequent writes
2126
+ // go directly to the live WS.
2127
+ this._stdinBuffer = [] // Array<Buffer> — pre-dial write buffer
2128
+ this._stdinBufferBytes = 0 // running total of bytes held in _stdinBuffer
2129
+ this._stdinBufferDropped = false // true once a write has been dropped due to cap
2130
+ this._maxStdinBufferBytes = maxStdinBufferBytes
2131
+ this._stdinWired = false // true once _wireStdin() has been called
2132
+ this._stdinEnded = false // true once stdin 'end' has fired
2133
+
2134
+ // stdin disabled signal (#3402): set true once forwarding is permanently
2135
+ // off (reconnect happened, or live WS dropped mid-write). The first
2136
+ // transition emits a one-shot 'stdin_disabled' event so consumers can
2137
+ // surface the failure to the user instead of silently losing turns.
2138
+ this._stdinForwardingDisabled = false
2139
+ this._stdinDisabledSignaled = false
2140
+
2141
+ // Accumulate stdin data until the WS is ready.
2142
+ this.stdin.on('data', (chunk) => {
2143
+ if (this._stdinWired) {
2144
+ // _wireStdin() already flushed and replaced this handler — should not
2145
+ // reach here, but guard defensively.
2146
+ return
2147
+ }
2148
+ if (this._stdinForwardingDisabled) {
2149
+ // Reconnect happened before _wireStdin ran on this WS — surface the
2150
+ // disabled state to the consumer rather than buffering forever.
2151
+ this._signalStdinDisabled()
2152
+ return
2153
+ }
2154
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
2155
+ // Cap the pre-dial buffer (#3401). Without a cap a slow WS dial plus a
2156
+ // fast producer would grow this array without bound and OOM the server.
2157
+ // Drop the over-cap chunk entirely (rather than truncating) so we don't
2158
+ // split frames mid-line — the consumer's NDJSON stream would become
2159
+ // invalid otherwise.
2160
+ if (this._stdinBufferBytes + buf.length > this._maxStdinBufferBytes) {
2161
+ if (!this._stdinBufferDropped) {
2162
+ // Log only the first drop to avoid log spam from a fast producer;
2163
+ // smaller writes that still fit may continue to be buffered.
2164
+ log.warn(
2165
+ `SidecarProcess: pre-dial stdin buffer exceeded cap (` +
2166
+ `${this._maxStdinBufferBytes} bytes) — dropping ${buf.length}-byte chunk; ` +
2167
+ `further drops will be silent`
2168
+ )
2169
+ this._stdinBufferDropped = true
2170
+ }
2171
+ // Emit 'stdin_dropped' for every over-cap chunk (#3474). The log.warn
2172
+ // above is one-shot to avoid spam, but the event must fire each time
2173
+ // so structured consumers (e.g. SdkSession) can sum lost bytes,
2174
+ // surface the failure to the user, or fall back to a different
2175
+ // delivery path. Payload mirrors the 'stdin_disabled' shape: a small
2176
+ // object with the dropped byte count and a reason tag callers can
2177
+ // switch on if more drop reasons are added later.
2178
+ this.emit('stdin_dropped', { bytes: buf.length, reason: 'pre-dial-cap' })
2179
+ return
2180
+ }
2181
+ this._stdinBuffer.push(buf)
2182
+ this._stdinBufferBytes += buf.length
2183
+ })
2184
+
2185
+ this.stdin.on('end', () => {
2186
+ this._stdinEnded = true
2187
+ if (this._stdinWired) {
2188
+ // WS is live — send stdin_end frame if WS is still open.
2189
+ _sendStdinEnd(this._ws)
2190
+ }
2191
+ // If not yet wired, _wireStdin() will send stdin_end after flushing.
2192
+ })
2193
+ }
2194
+
2195
+ /**
2196
+ * Whether writes to `proc.stdin` are currently being forwarded to the
2197
+ * sidecar (#3402). Returns `false` once a reconnect has occurred or the
2198
+ * live WS dropped mid-write — at that point further writes are dropped
2199
+ * silently, and the consumer should fall back to a different mechanism
2200
+ * (or surface an error to the user).
2201
+ *
2202
+ * @returns {boolean}
2203
+ */
2204
+ isStdinForwardingEnabled() {
2205
+ return !this._stdinForwardingDisabled
2206
+ }
2207
+
2208
+ /**
2209
+ * Mark stdin forwarding as disabled and emit `'stdin_disabled'` exactly
2210
+ * once (#3402). Idempotent — repeated calls are no-ops after the first
2211
+ * emission. Called by the reconnect path in `_wireWsToProc` and by the
2212
+ * live-forwarding listener in `_wireStdin` when WS closes mid-write.
2213
+ *
2214
+ * On the first transition we also drop any pre-wire buffered chunks in
2215
+ * `_stdinBuffer`: once forwarding is permanently off the buffer can never
2216
+ * be flushed (no live WS will ever take it), so retaining it would leak
2217
+ * memory. Anything that was already buffered is unrecoverable from the
2218
+ * sidecar's perspective; the consumer was just told via `'stdin_disabled'`
2219
+ * and should fall back to a different mechanism. The number of dropped
2220
+ * chunks is logged so operators have a paper trail for lost input.
2221
+ *
2222
+ * @private
2223
+ */
2224
+ _signalStdinDisabled() {
2225
+ this._stdinForwardingDisabled = true
2226
+ if (this._stdinDisabledSignaled) return
2227
+ this._stdinDisabledSignaled = true
2228
+ if (this._stdinBuffer.length > 0) {
2229
+ log.warn(
2230
+ `SidecarProcess: dropping ${this._stdinBuffer.length} pre-wire stdin ` +
2231
+ `chunk(s) (${this._stdinBufferBytes} bytes) — forwarding disabled ` +
2232
+ 'before flush could complete',
2233
+ )
2234
+ this._stdinBuffer = []
2235
+ this._stdinBufferBytes = 0
2236
+ }
2237
+ this.emit('stdin_disabled')
2238
+ }
2239
+
2240
+ kill(signal = 'SIGTERM') {
2241
+ if (this.killed) return
2242
+ this.killed = true
2243
+ log.info(`SidecarProcess.kill(${signal}) — closing WS`)
2244
+ // Cancel any pending reconnect timer so we don't re-dial after kill.
2245
+ if (this._retryTimer) {
2246
+ this._clearTimeout(this._retryTimer)
2247
+ this._retryTimer = null
2248
+ }
2249
+ if (this._ws) {
2250
+ try {
2251
+ this._ws.close()
2252
+ } catch (_) {
2253
+ // ignore
2254
+ }
2255
+ }
2256
+ if (this._cleanup) {
2257
+ try { this._cleanup() } catch (_) { /* ignore */ }
2258
+ this._cleanup = null
2259
+ }
2260
+ // Release the pre-dial stdin buffer immediately (#3401). If kill() fires
2261
+ // before the dial resolves, _wireStdin() will never run and the buffered
2262
+ // bytes would otherwise be held until the proc is GC'd.
2263
+ this._stdinBuffer = []
2264
+ this._stdinBufferBytes = 0
2265
+ // If the WS was never wired (kill called before dial resolved), there
2266
+ // will be no `close` event to drive the exit. The post-dial wiring path
2267
+ // checks `proc.killed` and synthesizes exit(-1) in that case.
2268
+ }
2269
+ }
2270
+
2271
+ // ─── WS wiring ───────────────────────────────────────────────────────────────
2272
+
2273
+ /**
2274
+ * Wire a live WebSocket to a SidecarProcess once the connection is open.
2275
+ * Sends the `spawn` frame (new session) or `resume` frame (reconnect) and
2276
+ * routes incoming frames to the proc's streams.
2277
+ *
2278
+ * On an unexpected WS close or error the function schedules a reconnect with
2279
+ * exponential backoff if the session has been established (session_started
2280
+ * received). On reconnect, a `resume` frame is sent so the agent can replay
2281
+ * any buffered output the client missed.
2282
+ *
2283
+ * Unrecoverable situations (max retries exceeded, session_lost from agent)
2284
+ * emit exit(-2) so upstream consumers can distinguish session loss from a
2285
+ * clean pre-session failure (exit(-1)).
2286
+ *
2287
+ * @param {WebSocket} ws
2288
+ * @param {SidecarProcess} proc
2289
+ * @param {Object} spawnOpts
2290
+ * @param {string} spawnOpts.cmd
2291
+ * @param {string[]} [spawnOpts.args]
2292
+ * @param {Object} [spawnOpts.env]
2293
+ * @param {string} [spawnOpts.cwd]
2294
+ * @param {AbortSignal} [spawnOpts.signal]
2295
+ * @param {Function} [spawnOpts.cleanup] - Optional teardown for portforward bridge
2296
+ */
2297
+ function _wireWsToProc(ws, proc, { cmd, args = [], env, cwd, signal, cleanup } = {}) {
2298
+ // Distinguish initial wiring (spawn) from a reconnect (resume).
2299
+ const isReconnect = Boolean(proc._sessionId)
2300
+
2301
+ // Attach the WS + cleanup to the proc so kill() can close them
2302
+ proc._ws = ws
2303
+ if (cleanup) proc._cleanup = cleanup
2304
+
2305
+ // Tracks whether the agent has produced any output yet. An `error` frame
2306
+ // that arrives BEFORE any event/stderr means the spawn was rejected — per
2307
+ // PROTOCOL.md the WS stays open in that case, but the consumer's `exit`
2308
+ // listener must still fire or `execInEnvironment` will hang until timeout.
2309
+ let firstFrameSeen = false
2310
+
2311
+ const finishWithExit = (code) => {
2312
+ if (proc._exited) return
2313
+ proc._exited = true
2314
+ if (proc._retryTimer) {
2315
+ proc._clearTimeout(proc._retryTimer)
2316
+ proc._retryTimer = null
2317
+ }
2318
+ proc.stdout.push(null)
2319
+ proc.stderr.push(null)
2320
+ proc.emit('exit', code)
2321
+ try { ws.close() } catch (_) { /* ignore */ }
2322
+ if (proc._cleanup) {
2323
+ try { proc._cleanup() } catch (_) { /* ignore */ }
2324
+ proc._cleanup = null
2325
+ }
2326
+ }
2327
+
2328
+ /**
2329
+ * Schedule a reconnect attempt with exponential backoff.
2330
+ * If no session has been established yet (pre-session failure) emit exit(-1).
2331
+ * If max retries are exceeded emit exit(-2) (session unrecoverable).
2332
+ *
2333
+ * Idempotent: WS 'error' and 'close' handlers can both fire for the same
2334
+ * underlying drop; without de-dup we would create two pending timers and
2335
+ * double-step the retry counter. Returning early when a timer is already
2336
+ * pending guarantees one reconnect attempt per drop.
2337
+ */
2338
+ const scheduleReconnect = () => {
2339
+ if (proc._exited || proc.killed) return
2340
+ if (proc._retryTimer) return // already scheduled — drop duplicate trigger
2341
+ if (!proc._sessionId) {
2342
+ // Failed before the session was acknowledged — treat as connection failure.
2343
+ finishWithExit(-1)
2344
+ return
2345
+ }
2346
+ if (proc._retryAttempt >= proc._maxRetries) {
2347
+ log.warn(`SidecarProcess: max retries (${proc._maxRetries}) exceeded — giving up`)
2348
+ finishWithExit(-2)
2349
+ return
2350
+ }
2351
+ const delay = proc._reconnectDelays[
2352
+ Math.min(proc._retryAttempt, proc._reconnectDelays.length - 1)
2353
+ ]
2354
+ proc._retryAttempt += 1
2355
+ log.info(`SidecarProcess: scheduling reconnect attempt ${proc._retryAttempt} in ${delay}ms`)
2356
+ proc._retryTimer = proc._setTimeout(() => {
2357
+ proc._retryTimer = null
2358
+ if (proc._exited || proc.killed) return
2359
+ proc._redial().then((dialResult) => {
2360
+ if (proc._exited || proc.killed) {
2361
+ // kill() fired during dial — tear down cleanly.
2362
+ const rws = dialResult && dialResult.ws ? dialResult.ws : dialResult
2363
+ try { rws.close() } catch (_) { /* ignore */ }
2364
+ const rCleanup = dialResult && typeof dialResult.cleanup === 'function'
2365
+ ? dialResult.cleanup : null
2366
+ if (rCleanup) { try { rCleanup() } catch (_) { /* ignore */ } }
2367
+ // Caller-initiated cancellation → exit(-1) (matches the synchronous
2368
+ // kill() before-dial path). exit(-2) is reserved for unrecoverable
2369
+ // session loss the consumer cannot mitigate.
2370
+ if (!proc._exited) finishWithExit(-1)
2371
+ return
2372
+ }
2373
+ const rws = dialResult && dialResult.ws ? dialResult.ws : dialResult
2374
+ const rCleanup = dialResult && typeof dialResult.cleanup === 'function'
2375
+ ? dialResult.cleanup : null
2376
+ _wireWsToProc(rws, proc, { cmd, args, env, cwd, signal, cleanup: rCleanup })
2377
+ }).catch((err) => {
2378
+ log.warn(`SidecarProcess: reconnect dial failed: ${err.message}`)
2379
+ scheduleReconnect()
2380
+ })
2381
+ }, delay)
2382
+ }
2383
+
2384
+ const sendFirst = () => {
2385
+ let frame
2386
+ if (isReconnect) {
2387
+ frame = { type: 'resume', sessionId: proc._sessionId, lastSeq: proc._lastSeq }
2388
+ log.info(`Sent resume frame: sessionId=${proc._sessionId} lastSeq=${proc._lastSeq}`)
2389
+ } else {
2390
+ frame = { type: 'spawn', cmd, args, stdin: 'ignore' }
2391
+ // Always request a piped stdin channel so the consumer can write user
2392
+ // turns as NDJSON (--input-format stream-json workflow). Matches the
2393
+ // sidecar protocol default introduced by #3329.
2394
+ frame = { type: 'spawn', cmd, args, stdin: 'pipe' }
2395
+ if (env && Object.keys(env).length > 0) frame.env = env
2396
+ if (cwd) frame.cwd = cwd
2397
+ log.info(`Sent spawn frame: ${cmd} ${args.slice(0, 2).join(' ')}`)
2398
+ }
2399
+ ws.send(JSON.stringify(frame))
2400
+ // Wire proc.stdin → WS after the first frame is sent so the agent has
2401
+ // already opened a piped stdin channel before we forward any data.
2402
+ // On reconnect we do NOT re-wire — stdin forwarding is not resumed
2403
+ // (see class-level JSDoc on resume semantics). Surface the disabled
2404
+ // state to the consumer so they can stop writing or surface an error
2405
+ // (#3402).
2406
+ if (!isReconnect) {
2407
+ _wireStdin(ws, proc)
2408
+ } else {
2409
+ proc._signalStdinDisabled()
2410
+ }
2411
+ }
2412
+
2413
+ if (ws.readyState === WebSocket.OPEN) {
2414
+ sendFirst()
2415
+ } else {
2416
+ ws.once('open', sendFirst)
2417
+ }
2418
+
2419
+ ws.on('message', (raw) => {
2420
+ let frame
2421
+ try {
2422
+ frame = JSON.parse(raw.toString())
2423
+ } catch {
2424
+ log.warn('Received non-JSON frame from sidecar — ignoring')
2425
+ return
2426
+ }
2427
+
2428
+ // Track the highest seq seen for resume replay (#3321).
2429
+ if (typeof frame.seq === 'number' && frame.seq > proc._lastSeq) {
2430
+ proc._lastSeq = frame.seq
2431
+ }
2432
+
2433
+ switch (frame.type) {
2434
+ case 'session_started':
2435
+ // Agent acknowledged the spawn and assigned a sessionId.
2436
+ proc._sessionId = frame.sessionId
2437
+ proc._retryAttempt = 0 // reset retry counter on fresh session
2438
+ log.info(`Sidecar session started: ${frame.sessionId}`)
2439
+ break
2440
+ case 'resumed':
2441
+ // Agent acknowledged a successful resume after replay (#3348). Reset
2442
+ // the retry counter so `maxRetries` is a per-blip budget, not a
2443
+ // session-lifetime budget. PROTOCOL.md documents this frame.
2444
+ proc._retryAttempt = 0
2445
+ log.info(`Sidecar session resumed: ${frame.sessionId} (replayed=${frame.replayedCount ?? 0})`)
2446
+ break
2447
+ case 'session_lost':
2448
+ // Agent does not recognise our sessionId or cannot replay the gap
2449
+ // (buffer overflow). Either way unrecoverable — exit(-2) signals
2450
+ // session loss to the caller.
2451
+ log.warn(`Sidecar session lost: ${frame.sessionId} (reason=${frame.reason || 'unknown'})`)
2452
+ finishWithExit(-2)
2453
+ break
2454
+ case 'event': {
2455
+ firstFrameSeen = true
2456
+ // Each `event` frame carries one parsed stdout NDJSON object (or raw string).
2457
+ // Re-serialize to NDJSON so the SDK's readline reader sees complete lines.
2458
+ const line = typeof frame.payload === 'string'
2459
+ ? frame.payload
2460
+ : JSON.stringify(frame.payload)
2461
+ proc.stdout.push(line + '\n')
2462
+ break
2463
+ }
2464
+ case 'stderr':
2465
+ firstFrameSeen = true
2466
+ proc.stderr.push(frame.data)
2467
+ break
2468
+ case 'exit':
2469
+ finishWithExit(frame.code ?? 0)
2470
+ break
2471
+ case 'error':
2472
+ log.warn(`Sidecar error frame: ${frame.message}`)
2473
+ proc.stderr.push(`sidecar error: ${frame.message}\n`)
2474
+ // Per PROTOCOL.md the agent leaves the connection open after most
2475
+ // error frames. But spawn-rejection errors arrive BEFORE any
2476
+ // event/stderr (because the child never started) and the agent
2477
+ // will not emit a follow-up `exit`. Without a synthetic exit the
2478
+ // consumer hangs until its timeout. Treat any error-before-first-
2479
+ // frame as fatal and synthesize exit(-1) to terminate the wait.
2480
+ if (!firstFrameSeen) {
2481
+ finishWithExit(-1)
2482
+ }
2483
+ break
2484
+ case 'pong':
2485
+ // no-op
2486
+ break
2487
+ default:
2488
+ log.warn(`Unknown sidecar frame type: ${frame.type}`)
2489
+ }
2490
+ })
2491
+
2492
+ ws.on('error', (err) => {
2493
+ if (proc._exited) return
2494
+ log.warn(`Sidecar WS error for process: ${err.message}`)
2495
+ // Caller asked to stop. Real-world WS errors (TCP reset, DNS, etc.) do
2496
+ // NOT guarantee a follow-up close with code 1000 — emit exit(-1) here
2497
+ // so the consumer's `on('exit')` listener fires regardless of which
2498
+ // event the underlying ws emits. Without this, kill() before a 1006-
2499
+ // shaped drop leaves _exited=false forever (#3346).
2500
+ if (proc.killed || (signal && signal.aborted)) {
2501
+ finishWithExit(-1)
2502
+ return
2503
+ }
2504
+ scheduleReconnect()
2505
+ })
2506
+
2507
+ ws.on('close', (code) => {
2508
+ if (proc._exited) return
2509
+ // Caller asked to stop — synthesize exit(-1) immediately, regardless of
2510
+ // the close code. Real WS implementations emit 1006 when the TCP socket
2511
+ // is dropped abruptly (the common case after kill()), and the original
2512
+ // code path fell through to scheduleReconnect() which then bailed on
2513
+ // proc.killed without ever emitting exit (#3346).
2514
+ if (proc.killed || (signal && signal.aborted)) {
2515
+ log.info(`Sidecar WS closed after kill (code=${code})`)
2516
+ finishWithExit(-1)
2517
+ return
2518
+ }
2519
+ // Normal close codes (1000 = normal, 1001 = going away) indicate a
2520
+ // clean shutdown — treat as pre-session failure or natural exit.
2521
+ if (code === 1000 || code === 1001) {
2522
+ log.info(`Sidecar WS closed normally (code=${code})`)
2523
+ finishWithExit(-1)
2524
+ return
2525
+ }
2526
+ log.warn(`Sidecar WS closed unexpectedly (code=${code}) — scheduling reconnect`)
2527
+ scheduleReconnect()
2528
+ })
2529
+
2530
+ // Abort signal support
2531
+ if (signal) {
2532
+ const onAbort = () => {
2533
+ if (!proc.killed) proc.kill('SIGTERM')
2534
+ }
2535
+ if (signal.aborted) {
2536
+ onAbort()
2537
+ } else {
2538
+ signal.addEventListener('abort', onAbort, { once: true })
2539
+ }
2540
+ }
2541
+ }
2542
+
2543
+ // ─── stdin forwarding helpers (#3336) ────────────────────────────────────────
2544
+
2545
+ /**
2546
+ * Flush the pre-dial stdin buffer and wire future writes to the live WS.
2547
+ *
2548
+ * Called once by `_wireWsToProc` immediately after the spawn frame is sent.
2549
+ * Removes the accumulator `data` listener from `proc.stdin`, replaces it with
2550
+ * a live-forwarding listener, flushes any buffered chunks, and sends
2551
+ * `stdin_end` if the stream already ended while we were dialling.
2552
+ *
2553
+ * This function is intentionally NOT called on reconnect because stdin frames
2554
+ * are not replayed by the agent's ring buffer. The consumer must not send
2555
+ * the same stdin bytes twice.
2556
+ *
2557
+ * @param {WebSocket} ws
2558
+ * @param {SidecarProcess} proc
2559
+ */
2560
+ function _wireStdin(ws, proc) {
2561
+ // Mark as wired first to suppress the accumulator listener's fallthrough.
2562
+ proc._stdinWired = true
2563
+
2564
+ // Replace the accumulator with a live-forwarding listener.
2565
+ // Remove all 'data' listeners that the constructor added (there should be
2566
+ // only the one accumulator, but removeAllListeners scopes to this event).
2567
+ proc.stdin.removeAllListeners('data')
2568
+ proc.stdin.on('data', (chunk) => {
2569
+ if (ws.readyState !== WebSocket.OPEN) {
2570
+ // WS closed mid-stream. Surface the disabled state via the dedicated
2571
+ // #3402 'stdin_disabled' signal first — that event is one-shot and
2572
+ // explicit, and unlike 'error' it never throws when no listener is
2573
+ // attached.
2574
+ proc._signalStdinDisabled()
2575
+ // Only emit 'error' if a consumer is actually listening — Node throws
2576
+ // an unhandled 'error' otherwise, which would crash the process and
2577
+ // defeat the point of the 'stdin_disabled' signal. Consumers that
2578
+ // care about errors should subscribe; consumers that only need the
2579
+ // disabled signal listen on 'stdin_disabled' instead.
2580
+ if (proc.listenerCount('error') > 0) {
2581
+ proc.emit('error', new Error('SidecarProcess: WS closed while writing stdin'))
2582
+ } else {
2583
+ log.warn('SidecarProcess: WS closed while writing stdin — dropping further writes (no error listener)')
2584
+ }
2585
+ // Stop forwarding — remove this listener so further writes are silent.
2586
+ proc.stdin.removeAllListeners('data')
2587
+ return
2588
+ }
2589
+ try {
2590
+ const data = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk)
2591
+ ws.send(JSON.stringify({ type: 'stdin', data }))
2592
+ } catch (err) {
2593
+ log.warn(`SidecarProcess: failed to send stdin frame: ${err.message}`)
2594
+ }
2595
+ })
2596
+
2597
+ // Flush buffered chunks accumulated before the WS opened.
2598
+ for (const chunk of proc._stdinBuffer) {
2599
+ if (ws.readyState !== WebSocket.OPEN) break
2600
+ try {
2601
+ ws.send(JSON.stringify({ type: 'stdin', data: chunk.toString('utf8') }))
2602
+ } catch (err) {
2603
+ log.warn(`SidecarProcess: failed to flush buffered stdin frame: ${err.message}`)
2604
+ }
2605
+ }
2606
+ proc._stdinBuffer = [] // release memory
2607
+ proc._stdinBufferBytes = 0
2608
+
2609
+ // stdin may have already ended while we were buffering.
2610
+ if (proc._stdinEnded) {
2611
+ _sendStdinEnd(ws)
2612
+ }
2613
+ }
2614
+
2615
+ /**
2616
+ * Send a `stdin_end` frame over the WS if the connection is still open.
2617
+ *
2618
+ * @param {WebSocket|null} ws
2619
+ */
2620
+ function _sendStdinEnd(ws) {
2621
+ if (!ws || ws.readyState !== WebSocket.OPEN) return
2622
+ try {
2623
+ ws.send(JSON.stringify({ type: 'stdin_end' }))
2624
+ } catch (err) {
2625
+ log.warn(`SidecarProcess: failed to send stdin_end frame: ${err.message}`)
2626
+ }
2627
+ }
2628
+
2629
+ // ─── Default WS dial factory ─────────────────────────────────────────────────
2630
+
2631
+ /**
2632
+ * Open a WebSocket to `url` with bearer token auth.
2633
+ * Resolves once the WS `open` event fires.
2634
+ *
2635
+ * @param {string} url
2636
+ * @param {string} token
2637
+ * @returns {Promise<WebSocket>}
2638
+ */
2639
+ function _defaultDialWs(url, token) {
2640
+ return new Promise((resolve, reject) => {
2641
+ const ws = new WebSocket(url, {
2642
+ headers: { Authorization: `Bearer ${token}` },
2643
+ })
2644
+ ws.once('open', () => resolve(ws))
2645
+ ws.once('error', reject)
2646
+ })
2647
+ }
2648
+
2649
+ // ─── Helpers ────────────────────────────────────────────────────────────────
2650
+
2651
+ // Detects a Kubernetes 404 across the shapes the JS clients have used over time.
2652
+ // `@kubernetes/client-node` v1.x throws `ApiException` with the HTTP status on
2653
+ // `err.code` — that's the canonical real-world shape. The other branches cover
2654
+ // older clients and adapter wrappers, so we keep them as a safety net.
2655
+ function _isNotFound(err) {
2656
+ return err?.code === 404 ||
2657
+ err?.statusCode === 404 ||
2658
+ err?.response?.statusCode === 404 ||
2659
+ err?.body?.code === 404
2660
+ }
2661
+
2662
+ // Detects a Kubernetes 409 Conflict (AlreadyExists) across the client shapes,
2663
+ // mirroring _isNotFound. Used to make namespace create idempotent: a 409 from
2664
+ // createNamespace means another creator won the race (#3194).
2665
+ function _isAlreadyExists(err) {
2666
+ return err?.code === 409 ||
2667
+ err?.statusCode === 409 ||
2668
+ err?.response?.statusCode === 409 ||
2669
+ err?.body?.code === 409
2670
+ }
2671
+
2672
+ function _sleep(ms) {
2673
+ return new Promise(resolve => setTimeout(resolve, ms))
2674
+ }
2675
+
2676
+ /**
2677
+ * Derive a per-Pod Secret name from the canonical Pod name.
2678
+ * createEnvironment() names pods `chroxy-env-<envId>` and secrets
2679
+ * `chroxy-token-<envId>`; given the former, return the latter.
2680
+ */
2681
+ function _deriveSecretName(podName) {
2682
+ if (typeof podName === 'string' && podName.startsWith('chroxy-env-')) {
2683
+ return 'chroxy-token-' + podName.slice('chroxy-env-'.length)
2684
+ }
2685
+ // Fallback: best-effort token cleanup name based on the pod name itself.
2686
+ return `chroxy-token-${podName}`
2687
+ }
2688
+
2689
+ /**
2690
+ * Parse a Docker-style volume mount string into its components.
2691
+ *
2692
+ * Supported formats:
2693
+ * "/host/path:/container/path"
2694
+ * "/host/path:/container/path:ro"
2695
+ *
2696
+ * Returns null for unrecognised *formats* (so the caller can log and skip), but
2697
+ * throws for inputs that are recognised as invalid — currently Windows-style
2698
+ * drive-letter prefixes (see below). Callers must therefore tolerate both a
2699
+ * `null` return and a thrown Error.
2700
+ *
2701
+ * Windows-style paths with a drive letter (e.g. `C:\Users\foo:/workspace` or
2702
+ * the relative form `C:foo:/container`) are rejected with an explicit Error:
2703
+ * splitting on `:` would silently truncate the host path to the drive letter
2704
+ * (`"C"`) and treat the rest of the Windows path as the container path,
2705
+ * producing a misconfigured mount that fails later at Pod scheduling. K8s
2706
+ * nodes are Linux-only, so Windows host paths are not supportable in any
2707
+ * case — fail loudly at parse time. Two guards run: (1) a regex that catches
2708
+ * absolute drive-letter prefixes (`C:\…`/`C:/…`), and (2) a post-split check
2709
+ * for any 1-char single-letter hostPath that catches relative drive paths.
2710
+ *
2711
+ * @param {string} mountStr Docker-style mount string in `<host>:<container>[:ro]` form.
2712
+ * @returns {{ hostPath: string, containerPath: string, readOnly: boolean } | null}
2713
+ * @throws {Error} when `mountStr` is recognised as a Windows drive-letter path.
2714
+ */
2715
+ // Build the Windows-path Error thrown by both _parseMountString guards.
2716
+ // Centralised so the message can't drift between the absolute-form regex check
2717
+ // and the relative-form post-split check below.
2718
+ function _windowsMountPathError(mountStr) {
2719
+ return new Error(
2720
+ `K8s mount string '${mountStr}' looks like a Windows path; K8s nodes only accept POSIX paths (expected '<host>:<container>[:ro]' with a POSIX host path)`
2721
+ )
2722
+ }
2723
+
2724
+ function _parseMountString(mountStr) {
2725
+ if (typeof mountStr !== 'string') return null
2726
+ // Reject Windows drive-letter paths up-front: `C:\…` or `C:/…` would split on
2727
+ // `:` into a 1-char hostPath and a corrupted containerPath. K8s nodes only
2728
+ // accept POSIX paths, so this can never produce a valid mount.
2729
+ if (/^[A-Za-z]:[\\/]/.test(mountStr)) {
2730
+ throw _windowsMountPathError(mountStr)
2731
+ }
2732
+ const parts = mountStr.split(':')
2733
+ if (parts.length < 2) return null
2734
+ const hostPath = parts[0]
2735
+ const containerPath = parts[1]
2736
+ if (!hostPath || !containerPath) return null
2737
+ // Defensive second check: a single-character hostPath that is a letter is a
2738
+ // Windows *relative* drive path (e.g. `C:foo:/container` → hostPath="C") that
2739
+ // the drive-letter prefix regex above can't catch (it requires `\` or `/`
2740
+ // after the colon). No legitimate POSIX mount ever produces a 1-char
2741
+ // hostPath ('/' alone splits to '' and is already rejected by the !hostPath
2742
+ // check), so fail loud with the same Error shape.
2743
+ if (hostPath.length === 1 && /^[A-Za-z]$/.test(hostPath)) {
2744
+ throw _windowsMountPathError(mountStr)
2745
+ }
2746
+ const readOnly = parts[2] === 'ro'
2747
+ return { hostPath, containerPath, readOnly }
2748
+ }
2749
+
2750
+ /**
2751
+ * Extract the container port from a forwardPorts entry.
2752
+ *
2753
+ * Accepts:
2754
+ * - A bare number or numeric string: "8080" → 8080
2755
+ * - A "hostPort:containerPort" string: "9000:8080" → 8080
2756
+ *
2757
+ * Returns null for non-numeric, zero, or out-of-range (> 65535) values.
2758
+ *
2759
+ * @param {string|number} entry
2760
+ * @returns {number | null}
2761
+ */
2762
+ function _parseContainerPort(entry) {
2763
+ const str = String(entry)
2764
+ const colonIdx = str.indexOf(':')
2765
+ const portStr = colonIdx >= 0 ? str.slice(colonIdx + 1) : str
2766
+ const port = parseInt(portStr, 10)
2767
+ if (!Number.isFinite(port) || port < 1 || port > 65535) return null
2768
+ return port
2769
+ }
2770
+
2771
+ /**
2772
+ * Normalise a memory quantity string to a valid Kubernetes quantity.
2773
+ *
2774
+ * Docker accepts lowercase suffixes ("g", "m", "k") while Kubernetes expects
2775
+ * binary SI suffixes ("Gi", "Mi", "Ki"). This function converts Docker-style
2776
+ * single-letter suffixes to their K8s equivalents. Values that already use
2777
+ * K8s suffixes (e.g. "2Gi", "512Mi") or plain integers (bytes) are returned
2778
+ * unchanged.
2779
+ *
2780
+ * Mapping:
2781
+ * "2g" → "2Gi"
2782
+ * "512m" → "512Mi"
2783
+ * "1024k"→ "1024Ki"
2784
+ * "2Gi" → "2Gi" (already valid)
2785
+ * "1024" → "1024" (plain bytes, valid K8s quantity)
2786
+ *
2787
+ * **SI vs binary-SI approximation:** Docker's single-letter suffixes use SI
2788
+ * (decimal) units — "g" = 10^9 bytes, "m" = 10^6 bytes, "k" = 10^3 bytes —
2789
+ * while Kubernetes binary suffixes ("Gi", "Mi", "Ki") use powers of two.
2790
+ * The mapping is therefore not lossless:
2791
+ *
2792
+ * "2g" → "2Gi" (~7.4 % over: 2 GiB = 2,147,483,648 B vs 2,000,000,000 B)
2793
+ * "512m" → "512Mi" (~4.9 % over: 512 MiB = 536,870,912 B vs 512,000,000 B)
2794
+ *
2795
+ * The conversion always **errs generous** — the container receives slightly
2796
+ * more memory than the Docker value would imply. This is intentional and
2797
+ * safe for the typical use case. Operators who need exact semantics should
2798
+ * supply a K8s-native quantity string (e.g. "2Gi", "2000000000") which is
2799
+ * passed through unchanged.
2800
+ *
2801
+ * @param {string} value
2802
+ * @returns {string}
2803
+ */
2804
+ function _normaliseMemoryQuantity(value) {
2805
+ const str = String(value)
2806
+ // Replace trailing lone-letter suffix (g/m/k, case-insensitive) with the
2807
+ // K8s binary equivalent. A trailing 'i' (already K8s-style) is left alone.
2808
+ return str.replace(/^(\d+(?:\.\d+)?)\s*([gGmMkK])$/, (_, num, unit) => {
2809
+ const map = { g: 'Gi', G: 'Gi', m: 'Mi', M: 'Mi', k: 'Ki', K: 'Ki' }
2810
+ return num + (map[unit] || unit)
2811
+ })
2812
+ }
2813
+
2814
+ // Valid Kubernetes CPU quantity: a plain decimal number ("2", "0.5", "1.5")
2815
+ // or a milli-cpu value with the `m` suffix ("500m", "1500m"). Exponent /
2816
+ // binary-SI suffixes are not meaningful for CPU and are rejected.
2817
+ const _CPU_QUANTITY_RE = /^(?:\d+(?:\.\d+)?|\.\d+|\d+m)$/
2818
+
2819
+ // Valid Kubernetes memory quantity AFTER normalisation: a number with an
2820
+ // optional binary-SI ("Ki"/"Mi"/"Gi"/"Ti"/"Pi"/"Ei"), decimal-SI
2821
+ // ("k"/"M"/"G"/"T"/"P"/"E"), or exponent ("e6") suffix, or a bare byte count.
2822
+ // We normalise Docker-style lone-letter suffixes first, then validate.
2823
+ const _MEMORY_QUANTITY_RE =
2824
+ /^(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+|Ki|Mi|Gi|Ti|Pi|Ei|[kKMGTPE])?$/
2825
+
2826
+ /**
2827
+ * Validate + normalise a single resource quantity string (#3195).
2828
+ *
2829
+ * @param {string} value - The caller-supplied quantity (e.g. "500m", "2Gi")
2830
+ * @param {'cpu'|'memory'} kind - Which quantity grammar to enforce
2831
+ * @param {string} field - Field label for the error message (e.g. "resources.cpu")
2832
+ * @returns {string} The validated (and, for memory, normalised) quantity string
2833
+ * @throws {Error} If `value` is not a string or is not a valid K8s quantity
2834
+ */
2835
+ function _validateResourceQuantity(value, kind, field) {
2836
+ if (typeof value !== 'string' || value.trim() === '') {
2837
+ throw new Error(
2838
+ `createEnvironment: ${field} must be a non-empty K8s quantity string`,
2839
+ )
2840
+ }
2841
+ const trimmed = value.trim()
2842
+ if (kind === 'cpu') {
2843
+ if (!_CPU_QUANTITY_RE.test(trimmed)) {
2844
+ throw new Error(
2845
+ `createEnvironment: ${field} "${value}" is not a valid K8s CPU quantity ` +
2846
+ '(expected e.g. "500m", "1", "0.5")',
2847
+ )
2848
+ }
2849
+ return trimmed
2850
+ }
2851
+ // memory
2852
+ const normalised = _normaliseMemoryQuantity(trimmed)
2853
+ if (!_MEMORY_QUANTITY_RE.test(normalised)) {
2854
+ throw new Error(
2855
+ `createEnvironment: ${field} "${value}" is not a valid K8s memory quantity ` +
2856
+ '(expected e.g. "512Mi", "2Gi", "1G")',
2857
+ )
2858
+ }
2859
+ return normalised
2860
+ }
2861
+
2862
+ /**
2863
+ * Build a Pod container `resources` block from caller opts + defaults (#3195).
2864
+ *
2865
+ * Resolution precedence per field (highest first):
2866
+ * 1. The structured `opts.resources` object: `{ cpu, memory, cpuLimit, memoryLimit }`
2867
+ * where `cpu`/`memory` map to `requests` and `cpuLimit`/`memoryLimit` to `limits`.
2868
+ * 2. The legacy flat opts `opts.cpuLimit` / `opts.memoryLimit` (applied to BOTH
2869
+ * the request and the limit for that dimension — the pre-#3195 behaviour).
2870
+ * 3. The supplied `defaults` object (constructor `defaultResources`, itself
2871
+ * seeded from the module-level {@link DEFAULT_RESOURCES}). Pass `null` to
2872
+ * disable defaults so only explicit per-call values produce a block.
2873
+ *
2874
+ * Every resolved quantity is validated against the K8s quantity grammar; an
2875
+ * invalid string throws before the Pod/Secret are created — `createEnvironment`
2876
+ * awaits `ensureNamespace()` first, so the tenant namespace may already exist,
2877
+ * but no workload is provisioned with a bad value.
2878
+ *
2879
+ * @param {Object} [resources] - opts.resources (structured form)
2880
+ * @param {string} [legacyCpuLimit] - opts.cpuLimit (flat form)
2881
+ * @param {string} [legacyMemoryLimit] - opts.memoryLimit (flat form)
2882
+ * @param {Object|null} [defaults=DEFAULT_RESOURCES] - Per-field defaults, or null to disable
2883
+ * @returns {{ requests?: Object, limits?: Object }} A resources block (possibly empty)
2884
+ */
2885
+ function _resolveResourceField(structured, structuredLabel, legacy, legacyLabel, dflt, defaultLabel) {
2886
+ if (structured != null) return { value: structured, field: structuredLabel }
2887
+ if (legacy != null) return { value: legacy, field: legacyLabel }
2888
+ if (dflt != null) return { value: dflt, field: defaultLabel }
2889
+ return { value: null, field: null }
2890
+ }
2891
+
2892
+ export function buildResourceBlock(resources, legacyCpuLimit, legacyMemoryLimit, defaults = DEFAULT_RESOURCES) {
2893
+ if (resources != null && (typeof resources !== 'object' || Array.isArray(resources))) {
2894
+ throw new Error('createEnvironment: opts.resources must be an object')
2895
+ }
2896
+ const r = resources || {}
2897
+ const d = defaults || {}
2898
+
2899
+ // Resolve each of the four dimensions through the precedence chain,
2900
+ // tracking which source actually supplied the value so a validation
2901
+ // failure names the option the operator set (#3195 review) — the legacy
2902
+ // flat opt or a constructor default — instead of always blaming
2903
+ // `resources.*`.
2904
+ const cpuRequest = _resolveResourceField(r.cpu, 'resources.cpu', legacyCpuLimit, 'cpuLimit', d.cpu, 'defaultResources.cpu')
2905
+ const memRequest = _resolveResourceField(r.memory, 'resources.memory', legacyMemoryLimit, 'memoryLimit', d.memory, 'defaultResources.memory')
2906
+ const cpuLimit = _resolveResourceField(r.cpuLimit, 'resources.cpuLimit', legacyCpuLimit, 'cpuLimit', d.cpuLimit, 'defaultResources.cpuLimit')
2907
+ const memLimit = _resolveResourceField(r.memoryLimit, 'resources.memoryLimit', legacyMemoryLimit, 'memoryLimit', d.memoryLimit, 'defaultResources.memoryLimit')
2908
+
2909
+ const requests = {}
2910
+ const limits = {}
2911
+ if (cpuRequest.value != null) requests.cpu = _validateResourceQuantity(cpuRequest.value, 'cpu', cpuRequest.field)
2912
+ if (memRequest.value != null) requests.memory = _validateResourceQuantity(memRequest.value, 'memory', memRequest.field)
2913
+ if (cpuLimit.value != null) limits.cpu = _validateResourceQuantity(cpuLimit.value, 'cpu', cpuLimit.field)
2914
+ if (memLimit.value != null) limits.memory = _validateResourceQuantity(memLimit.value, 'memory', memLimit.field)
2915
+
2916
+ const block = {}
2917
+ if (Object.keys(requests).length > 0) block.requests = requests
2918
+ if (Object.keys(limits).length > 0) block.limits = limits
2919
+ return block
2920
+ }
2921
+
2922
+ /**
2923
+ * Map a tenant-friendly quota spec to the K8s `ResourceQuota.spec.hard` keys
2924
+ * (#5142).
2925
+ *
2926
+ * The operator supplies a small, intention-revealing object; this builder
2927
+ * translates it into the canonical `hard` map the API server understands and
2928
+ * validates every quantity through the same grammar the per-pod path uses
2929
+ * (`_validateResourceQuantity`). CPU/memory values become the standard
2930
+ * `requests.*` / `limits.*` aggregate keys, and the pod count maps to the
2931
+ * `pods` object-count quota.
2932
+ *
2933
+ * { cpu, memory } → requests.cpu / requests.memory
2934
+ * { cpuLimit, memoryLimit } → limits.cpu / limits.memory
2935
+ * { pods } → pods (max object count, integer)
2936
+ *
2937
+ * @param {Object} spec
2938
+ * @param {string} [spec.cpu] - Aggregate CPU request cap (e.g. "8")
2939
+ * @param {string} [spec.memory] - Aggregate memory request cap (e.g. "16Gi")
2940
+ * @param {string} [spec.cpuLimit] - Aggregate CPU limit cap (e.g. "16")
2941
+ * @param {string} [spec.memoryLimit] - Aggregate memory limit cap (e.g. "32Gi")
2942
+ * @param {number} [spec.pods] - Max number of Pods in the namespace
2943
+ * @returns {Object} A `ResourceQuota.spec.hard` map (at least one entry)
2944
+ * @throws {Error} If the spec is malformed or yields no caps
2945
+ */
2946
+ export function buildResourceQuotaSpec(spec) {
2947
+ if (spec == null || typeof spec !== 'object' || Array.isArray(spec)) {
2948
+ throw new Error('K8sBackend: namespaceQuota must be an object')
2949
+ }
2950
+ const hard = {}
2951
+ if (spec.cpu != null) {
2952
+ hard['requests.cpu'] = _validateResourceQuantity(spec.cpu, 'cpu', 'namespaceQuota.cpu')
2953
+ }
2954
+ if (spec.memory != null) {
2955
+ hard['requests.memory'] = _validateResourceQuantity(spec.memory, 'memory', 'namespaceQuota.memory')
2956
+ }
2957
+ if (spec.cpuLimit != null) {
2958
+ hard['limits.cpu'] = _validateResourceQuantity(spec.cpuLimit, 'cpu', 'namespaceQuota.cpuLimit')
2959
+ }
2960
+ if (spec.memoryLimit != null) {
2961
+ hard['limits.memory'] = _validateResourceQuantity(spec.memoryLimit, 'memory', 'namespaceQuota.memoryLimit')
2962
+ }
2963
+ if (spec.pods != null) {
2964
+ if (!Number.isInteger(spec.pods) || spec.pods < 1) {
2965
+ throw new Error('K8sBackend: namespaceQuota.pods must be a positive integer')
2966
+ }
2967
+ // ResourceQuota `hard` values are all quantity strings, including counts.
2968
+ hard.pods = String(spec.pods)
2969
+ }
2970
+ if (Object.keys(hard).length === 0) {
2971
+ throw new Error(
2972
+ 'K8sBackend: namespaceQuota must set at least one of ' +
2973
+ 'cpu, memory, cpuLimit, memoryLimit, pods',
2974
+ )
2975
+ }
2976
+ return hard
2977
+ }
2978
+
2979
+ /**
2980
+ * Map a tenant-friendly LimitRange spec to a single container-scoped
2981
+ * `LimitRange.spec.limits[]` entry (#5142).
2982
+ *
2983
+ * A LimitRange supplies *namespace-level* defaults so Pods created WITHOUT
2984
+ * explicit requests/limits inherit sane values at the cluster level — a
2985
+ * defence-in-depth layer on top of the backend's own DEFAULT_RESOURCES. The
2986
+ * operator supplies the same flat shape as `defaultResources`; this builder
2987
+ * splits it into the `default` (limits) and `defaultRequest` (requests) maps a
2988
+ * container-type LimitRange item expects, validating every quantity.
2989
+ *
2990
+ * { cpu, memory } → defaultRequest.cpu / defaultRequest.memory
2991
+ * { cpuLimit, memoryLimit } → default.cpu / default.memory
2992
+ *
2993
+ * @param {Object} spec
2994
+ * @param {string} [spec.cpu] - Default CPU request (e.g. "250m")
2995
+ * @param {string} [spec.memory] - Default memory request (e.g. "256Mi")
2996
+ * @param {string} [spec.cpuLimit] - Default CPU limit (e.g. "1")
2997
+ * @param {string} [spec.memoryLimit] - Default memory limit (e.g. "1Gi")
2998
+ * @returns {{ type: 'Container', default?: Object, defaultRequest?: Object }}
2999
+ * A single LimitRange item (at least one of default/defaultRequest set)
3000
+ * @throws {Error} If the spec is malformed or yields no defaults
3001
+ */
3002
+ export function buildLimitRangeSpec(spec) {
3003
+ if (spec == null || typeof spec !== 'object' || Array.isArray(spec)) {
3004
+ throw new Error('K8sBackend: namespaceLimitRange must be an object')
3005
+ }
3006
+ const defaultRequest = {}
3007
+ const defaultLimit = {}
3008
+ if (spec.cpu != null) {
3009
+ defaultRequest.cpu = _validateResourceQuantity(spec.cpu, 'cpu', 'namespaceLimitRange.cpu')
3010
+ }
3011
+ if (spec.memory != null) {
3012
+ defaultRequest.memory = _validateResourceQuantity(spec.memory, 'memory', 'namespaceLimitRange.memory')
3013
+ }
3014
+ if (spec.cpuLimit != null) {
3015
+ defaultLimit.cpu = _validateResourceQuantity(spec.cpuLimit, 'cpu', 'namespaceLimitRange.cpuLimit')
3016
+ }
3017
+ if (spec.memoryLimit != null) {
3018
+ defaultLimit.memory = _validateResourceQuantity(spec.memoryLimit, 'memory', 'namespaceLimitRange.memoryLimit')
3019
+ }
3020
+ const item = { type: 'Container' }
3021
+ if (Object.keys(defaultLimit).length > 0) item.default = defaultLimit
3022
+ if (Object.keys(defaultRequest).length > 0) item.defaultRequest = defaultRequest
3023
+ if (item.default == null && item.defaultRequest == null) {
3024
+ throw new Error(
3025
+ 'K8sBackend: namespaceLimitRange must set at least one of ' +
3026
+ 'cpu, memory, cpuLimit, memoryLimit',
3027
+ )
3028
+ }
3029
+ return item
3030
+ }