@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
package/src/config.js ADDED
@@ -0,0 +1,1757 @@
1
+ /**
2
+ * Configuration schema validation and merging utilities.
3
+ *
4
+ * Config precedence (highest to lowest):
5
+ * 1. CLI flags
6
+ * 2. Environment variables
7
+ * 3. Config file (~/.chroxy/config.json)
8
+ * 4. Defaults
9
+ */
10
+
11
+ import { readFileSync, existsSync, mkdirSync } from 'fs'
12
+ import { join, dirname } from 'path'
13
+ import { homedir } from 'os'
14
+ import { writeFileRestricted } from './platform.js'
15
+ import { parseDuration } from './duration.js'
16
+ import { createLogger } from './logger.js'
17
+ // #5419: pure validation helpers for `providers.anthropicCompatible` —
18
+ // deliberately a dependency-free module so importing it here never pulls
19
+ // the BYOK/SDK machinery into the config-load path.
20
+ import { validateProvidersConfigBlock } from './anthropic-compatible-config.js'
21
+
22
+ const log = createLogger('config')
23
+
24
+ /**
25
+ * Known configuration keys and their expected types.
26
+ */
27
+ const CONFIG_SCHEMA = {
28
+ apiToken: 'string',
29
+ port: 'number',
30
+ // Bind address for the server socket. Default (unset) binds 0.0.0.0 so the
31
+ // mobile app / LAN clients can reach it. Set to '127.0.0.1' for a
32
+ // loopback-only bind that keeps auth enabled — opt-in defence-in-depth for
33
+ // single-device setups. `--no-auth` always forces loopback regardless.
34
+ host: 'string',
35
+ cwd: 'string',
36
+ model: 'string',
37
+ allowedTools: 'array',
38
+ noAuth: 'boolean',
39
+ maxRestarts: 'number',
40
+ // #6022: ms the supervisor serves a terminal `status:'down'` health response
41
+ // (reason `supervisor_gave_up`) after exhausting its restart budget, before
42
+ // exiting — long enough for a polling client to latch the terminal state.
43
+ // 0 preserves the prior exit-immediately behaviour. Default 15000.
44
+ terminalDownGraceMs: 'number',
45
+ tunnel: 'string',
46
+ tunnelName: 'string',
47
+ tunnelHostname: 'string',
48
+ tunnelConfig: 'object',
49
+ legacyCli: 'boolean',
50
+ // #4209 / #4246: server-wide default for the per-session
51
+ // `skipPermissions` option. Honoured only by the claude-tui provider
52
+ // (spawns claude with `--dangerously-skip-permissions` + elides
53
+ // chroxy's permission hook). Wired from
54
+ // `chroxy start --dangerously-skip-permissions`; can also be pinned
55
+ // in config.json for headless deploys.
56
+ //
57
+ // #4246 — the canonical config-file key is now
58
+ // `dangerouslySkipPermissions` (mirrors the CLI flag). The legacy
59
+ // `skipPermissions` key is still honoured for backwards compatibility
60
+ // but `resolveSkipPermissions()` emits a deprecation warning when only
61
+ // the legacy key is set. Operators should rename the key in their
62
+ // config.json — both keys remain in the schema so a config.json with
63
+ // either key passes validation cleanly.
64
+ dangerouslySkipPermissions: 'boolean',
65
+ skipPermissions: 'boolean',
66
+ provider: 'string',
67
+ // Two accepted forms (#2950 / #5419):
68
+ // - array (legacy, written by `chroxy init`): provider ids the user
69
+ // opted into. Informational today — `provider` remains the
70
+ // authoritative runtime selector.
71
+ // - object: `providers.anthropicCompatible` is an array of
72
+ // config-driven Anthropic-compatible endpoint entries (Z.ai GLM,
73
+ // Moonshot Kimi, MiniMax, LM Studio, llama.cpp, vLLM, OpenRouter,
74
+ // custom proxies). Each entry registers a first-class provider at
75
+ // startup — see anthropic-compatible-config.js for the entry shape
76
+ // and validation rules. API keys are NEVER inlined here: entries
77
+ // name an env var (`apiKeyEnv`) or a ~/.chroxy/credentials.json
78
+ // field (`credentialsKey`).
79
+ providers: 'array|object',
80
+ // #5547: optional override for the one-shot session summarizer (the sidebar
81
+ // "Summarize & start new session" action). `{ provider?: string, model?:
82
+ // string }` — when set, the summarizer uses this (typically cheaper) model
83
+ // instead of the target session's own model. `provider` is accepted for
84
+ // forward-compat; the one-shot path currently runs through the SDK provider
85
+ // and only threads the model id. Unset → summarize with the session's model.
86
+ summarize: 'object',
87
+ maxPayload: 'number',
88
+ maxToolInput: 'number',
89
+ noEncrypt: 'boolean',
90
+ // #6564 — force E2E encryption on loopback connections too (disable the
91
+ // localhost plaintext bypass unconditionally). Default off: the bypass is
92
+ // already auto-disabled while a tunnel is active (see ws-history.js).
93
+ encryptLocalhost: 'boolean',
94
+ transforms: 'array',
95
+ tokenExpiry: 'string',
96
+ // #6598 — how long a paired device's session token stays valid without
97
+ // reconnecting (sliding: each connect refreshes it). Duration string like
98
+ // '30d' / '15d' / '12h'. Persisted across restarts. Default 30d + the 5min
99
+ // floor are applied in server-cli when computing sessionTokenTtlMs; a malformed
100
+ // or sub-floor value is warned about by validateConfig.
101
+ sessionTokenTtl: 'string',
102
+ sessionTimeout: 'string',
103
+ costBudget: 'number',
104
+ // #5665: monthly programmatic-credit budget meter config. Nested object:
105
+ // billing.creditTier pro | max5x | max20x
106
+ // billing.monthlyCreditBudgetUsd raw USD cap (wins over the tier preset)
107
+ // billing.budgetWarningPercent warn threshold 1-100 (default 80)
108
+ billing: 'object',
109
+ // #6481 (epic #6469): opt-in IDE feature surface. `features.ide: true` (or the
110
+ // CHROXY_ENABLE_IDE=1 env override) reveals the IDE navigation/editing features;
111
+ // off by default so it never risks the core offering. See isIdeFeatureEnabled().
112
+ features: 'object',
113
+ externalUrl: 'string',
114
+ repos: 'array',
115
+ // #5172 (Control Room v2): filesystem root the Host Status survey scans
116
+ // for auto-discovered git repos. resolveRepoSet (control-room/repo-set.js)
117
+ // unions any explicit `repos[]` entries with the immediate subdirectories
118
+ // of this root that contain a `.git` entry. Defaults to ~/Projects when
119
+ // unset. Mirrored by the CHROXY_CONTROL_ROOM_ROOT env var.
120
+ controlRoomRoot: 'string',
121
+ // #5253 (Control Room): filesystem root the self-hosted runner survey
122
+ // (control-room/runners.js) scans for GitHub Actions runner installs (dirs
123
+ // containing a `.runner` config). Defaults to ~/github-runners when unset.
124
+ // Mirrored by the CHROXY_RUNNER_ROOT env var.
125
+ controlRoomRunnerRoot: 'string',
126
+ // #5260 (Control Room): whether the self-hosted runner survey enriches each
127
+ // runner with GitHub's view via `gh api` (online/busy/labels). Defaults to
128
+ // true. Set false for a faster local-only survey, or on hosts where `gh`
129
+ // isn't authenticated. Mirrored by the CHROXY_RUNNER_INCLUDE_GITHUB env var.
130
+ controlRoomRunnerIncludeGithub: 'boolean',
131
+ // #6133 (Control Room): set false to skip the `docker stats` enrichment in the
132
+ // containers survey (inventory-only, for a slow/socketless docker). Default true.
133
+ controlRoomContainersIncludeStats: 'boolean',
134
+ // #5499 (Control Room): explicit path to the `repo-memory` binary the
135
+ // Integrations survey (control-room/integrations.js) shells out to for the
136
+ // per-repo telemetry report. When unset, the survey probes the PATH with
137
+ // `which repo-memory` once per snapshot — set this on hosts where the daemon
138
+ // runs with a GUI/launchd PATH that misses npm globals. Mirrored by the
139
+ // CHROXY_REPO_MEMORY_BIN env var.
140
+ controlRoomRepoMemoryBin: 'string',
141
+ maxSessions: 'number',
142
+ maxHistory: 'number',
143
+ maxMessages: 'number',
144
+ showToken: 'boolean',
145
+ logFormat: 'string',
146
+ environments: 'object',
147
+ // #5413: notification-sink settings. Currently one sub-block,
148
+ // `notifications.discord`, carrying the Discord status-embed sink's
149
+ // non-secret knobs: `botName` (string), `colors` (project → decimal
150
+ // 24-bit RGB map for the embed sidebar), `defaultColor` /
151
+ // `permissionColor` / `errorColor` (decimal RGB), `updateThrottleMs`
152
+ // (min interval between same-state routine embed updates),
153
+ // `heartbeatIntervalMs` (elapsed-time refresh; 0 disables) and
154
+ // `pruneAfterMs` (state-store entry retention, #5429/#5434; 0 disables
155
+ // pruning). The webhook
156
+ // URL itself is a SECRET and deliberately NOT a config key — it lives in
157
+ // CHROXY_DISCORD_WEBHOOK_URL or ~/.chroxy/credentials.json (0600); see
158
+ // discord-credentials.js. Documented in CONFIG.md +
159
+ // docs/guides/discord-notifications.md.
160
+ notifications: 'object',
161
+ // #5158: worktree garbage-collection. `{ autoReap: boolean }` — when true,
162
+ // the server reclaims orphaned, dead-pid-locked agent worktrees on startup
163
+ // (clean trees only, never --force). Defaults to off; the `chroxy worktree
164
+ // gc` CLI is always available for manual/dry-run use.
165
+ worktreeGc: 'object',
166
+ sandbox: 'object',
167
+ // Optional allowlist of absolute directory paths that sessions may use
168
+ // as their working directory. When set (non-empty array), session
169
+ // cwds MUST be within one of these realpath-resolved roots;
170
+ // otherwise creation is rejected. When unset/empty, falls back to the
171
+ // legacy "must be inside $HOME" check. Defense-in-depth (credential
172
+ // directory deny-list) is active in BOTH modes — see validateCwdAllowed
173
+ // in handler-utils.js. Added in the 2026-04-11 audit blocker 1 fix.
174
+ workspaceRoots: 'array',
175
+ // Gates the auto permission mode (bypass all permission checks). When
176
+ // not explicitly set to true, clients that attempt to flip to auto
177
+ // mode are rejected with AUTO_MODE_DISABLED_BY_CONFIG. Defaults to
178
+ // undefined/false so fresh installs are secure-by-default. Operators
179
+ // who want to run Claude unattended can opt in by editing their
180
+ // config file on the dev machine (physical-access proxy for real
181
+ // user confirmation). Added in the 2026-04-11 audit Adversary A5 fix.
182
+ allowAutoPermissionMode: 'boolean',
183
+ // #5985 (epic #5982): gate for the embedded user-shell terminal — a
184
+ // `user-shell` session spawns the operator's `$SHELL` (arbitrary code
185
+ // execution on the dev machine, reachable through the tunnel). Nested object
186
+ // `{ enabled: boolean }`. Defaults to undefined/false so fresh installs are
187
+ // secure-by-default: creating a `user-shell` session is rejected with
188
+ // USER_SHELL_DISABLED unless `userShell.enabled === true`. Enabling is a
189
+ // deliberate edit on the dev machine (physical-access proxy for confirmation),
190
+ // matching `allowAutoPermissionMode`. The gate is enforced in
191
+ // SessionManager.createSession so it covers every spawn path (WS create,
192
+ // restore, internal callers) — see the swarm-audit C3 finding.
193
+ userShell: 'object',
194
+ // Allowlist of Docker image patterns that create_environment may use.
195
+ // Each entry is either an exact image name or a prefix pattern like
196
+ // `mcr.microsoft.com/devcontainers/*`. When set, client-supplied
197
+ // images must match at least one entry; otherwise the request is
198
+ // rejected with DOCKER_IMAGE_NOT_ALLOWED. When unset, falls back to
199
+ // a built-in DEFAULT_ALLOWED_DOCKER_IMAGES list (see
200
+ // docker-image-allowlist.js) covering common base images. Added in
201
+ // the 2026-04-11 audit Adversary A7 fix to close the "register any
202
+ // attacker-controlled image and run it" attack path.
203
+ allowedDockerImages: 'array',
204
+ // Per-session regex source string used by `shouldSkipEvaluator` to extend
205
+ // the default continuation-pattern skip list. Wrapped in try/catch when
206
+ // compiled — malformed sources are logged and ignored, the default
207
+ // pattern still applies. Documented in CONFIG.md. Added in #3187.
208
+ promptEvaluatorSkipPattern: 'string',
209
+ // Per-skill byte cap and global skills-context budget (#3202). Skills
210
+ // exceeding the per-skill cap are rejected; a merged set exceeding the
211
+ // global cap is pruned by ascending priority then alphabetical name.
212
+ // Defaults: 32768 (32KB) per skill, 262144 (256KB) total. Setting either
213
+ // to 0 disables that cap. Documented in CONFIG.md.
214
+ maxSkillBytes: 'number',
215
+ maxTotalSkillBytes: 'number',
216
+ // Per-provider skill allowlist (#3207). An object keyed by provider id
217
+ // (e.g. `codex`, `gemini`) whose value is an array of skill names that
218
+ // are permitted to load for that provider. When this map is omitted
219
+ // entirely, the loader keeps the v1 permissive behaviour (every loaded
220
+ // skill is eligible for every provider). When the map is present:
221
+ // - Claude-family providers (`claude-sdk`, `claude-cli`, `docker-*`)
222
+ // stay permissive — Claude has built-in tool gating so skills there
223
+ // are lower risk.
224
+ // - For non-Claude providers (`codex`, `gemini`, …) only the skills
225
+ // listed in the allowlist for that provider load. A missing key
226
+ // OR an empty array filters out ALL skills for that provider —
227
+ // fail-secure.
228
+ // Documented in CONFIG.md.
229
+ providerSkillAllowlist: 'object',
230
+ // Skill content-hash mismatch mode (#3204). One of:
231
+ // - 'warn': a hash mismatch logs a sanitised warn and emits a
232
+ // `skill_changed` WS event but the skill still loads.
233
+ // - 'block': same warn + event, but the skill is filtered out of
234
+ // the active set until the operator explicitly re-trusts it.
235
+ // Invalid values disable trust checking — the operator must
236
+ // explicitly opt into 'warn' or 'block' to enable it. This was an
237
+ // intentional design choice so the trust ledger is opt-in, not
238
+ // implicit.
239
+ // Documented in CONFIG.md.
240
+ trustMismatchMode: 'string',
241
+ // #3749 / #3884 / #3899: SOFT-warning inactivity timeout (ms). When no
242
+ // SDK / CLI event fires within this window, the server emits an
243
+ // `inactivity_warning` event (and push notification) — the session
244
+ // stays alive. Defaults to 1800000 (30 min). Was a hardcoded 5 min
245
+ // before — too aggressive for legitimate slow tools (large fetches,
246
+ // long Bash, extended thinking). Range: 30s minimum, 24h maximum —
247
+ // validateConfig logs a warning for out-of-range values (warn-only,
248
+ // not clamped); the runtime still applies whatever was set.
249
+ // Operators should fix the warning rather than rely on silent
250
+ // normalisation.
251
+ resultTimeoutMs: 'number',
252
+ // #3899: HARD-cap inactivity timeout (ms). When silence continues
253
+ // for this long with no user check-in, the session is force-cleared
254
+ // (the pre-#3899 kill path). Defaults to 7200000 (2h). Same range
255
+ // semantics as resultTimeoutMs — operators can set this shorter if
256
+ // they want tighter runaway-session protection, but it should always
257
+ // be >= resultTimeoutMs (the soft warning fires first).
258
+ hardTimeoutMs: 'number',
259
+ // #4467: stream-stall recovery (ms). Resets on any stream activity from
260
+ // the child; when silence reaches this window while busy, the session
261
+ // emits a recoverable error (code: stream_stall), clears busy state,
262
+ // and the dashboard can offer a retry. Default 300000 (5 min). Set to
263
+ // 0 to disable (operators with legitimately long event gaps).
264
+ streamStallTimeoutMs: 'number',
265
+ // #5288: background-shell HARD-quiesce window (ms). A finished-but-never-
266
+ // polled background shell is reaped after this much continuous output
267
+ // silence so it stops pinning the session "running". Default 14400000 (4h);
268
+ // set 0 to disable hard-reaping (advisory-only, #5247). The tradeoff: a
269
+ // genuinely-silent-for-hours background compute could have its tracking
270
+ // reaped — operators running such workloads should raise this (6-8h) or
271
+ // disable it. Range: 60s minimum, 24h maximum (0 to disable).
272
+ backgroundShellHardQuiesceMs: 'number',
273
+ // #4601: per-provider override map for streamStallTimeoutMs. An object
274
+ // keyed by provider id (e.g. 'codex', 'gemini', 'claude-sdk') whose
275
+ // value is a stall window in ms. Same 5s-24h-or-0 validation as
276
+ // `streamStallTimeoutMs` applies to each entry. When a session is
277
+ // created for a provider that has an entry here, that entry wins over
278
+ // the global `streamStallTimeoutMs`; otherwise the global value (or
279
+ // BaseSession default) applies. Default behaviour is unchanged when
280
+ // omitted — Codex/Gemini/long-running upstream APIs were the original
281
+ // motivation but operators can override any provider id.
282
+ providerStreamStallTimeoutMs: 'object',
283
+ // #4482: per-call MCP tools/call timeout (ms). Forwarded to
284
+ // byok-mcp-client.callTool's setTimeout via byok-session →
285
+ // MCPFleet.callTool → MCPClient.callTool. Default 30000 (30s) at the
286
+ // client layer matches DEFAULT_TOOL_CALL_TIMEOUT_MS. Range 1s-10min —
287
+ // below 1s every realistic MCP server times out, above 10min the
288
+ // model conversation is already lost.
289
+ mcpToolCallTimeoutMs: 'number',
290
+ }
291
+
292
+ /**
293
+ * Config keys that should be masked in verbose output and sanitized logs.
294
+ * `pushToken` was a dead entry — it is never a CONFIG_SCHEMA key; push tokens
295
+ * are runtime device registrations (`prefs.devices`), masked elsewhere. The
296
+ * only real config secret is `apiToken`. (audit P2-12)
297
+ */
298
+ const SENSITIVE_KEYS = ['apiToken']
299
+
300
+ /**
301
+ * #5144: recognised values for `environments.backend`. 'docker' is the default
302
+ * when the key is absent so existing single-node setups are unchanged.
303
+ */
304
+ const ENVIRONMENT_BACKENDS = new Set(['docker', 'k8s', 'rancher'])
305
+
306
+ /** #5144: valid Kubernetes imagePullPolicy values (mirrors k8s.js). */
307
+ const VALID_K8S_PULL_POLICIES = new Set(['Always', 'IfNotPresent', 'Never'])
308
+
309
+ /** #5144: valid K8sBackend connectMode values (mirrors k8s.js). */
310
+ const VALID_K8S_CONNECT_MODES = new Set(['portforward', 'clusterip'])
311
+
312
+ /**
313
+ * #5144: Rancher cluster-/project-ID formats. Kept in sync with the canonical
314
+ * regexes in rancher.js (RANCHER_CLUSTER_ID / RANCHER_PROJECT_ID). Duplicated
315
+ * here rather than imported to keep config.js free of any cluster-client
316
+ * dependency (rancher.js eagerly imports @kubernetes/client-node), so loading
317
+ * config never pulls in the kube SDK.
318
+ */
319
+ const RANCHER_CLUSTER_ID_RE = /^c-[a-z0-9-]+$/
320
+ const RANCHER_PROJECT_ID_RE = /^p-[a-z0-9-]+$/
321
+
322
+ /**
323
+ * #5878 (audit P2-6 part 2): warn on unrecognised keys in a config sub-block so
324
+ * a typo (`billing.creditTeir`, `worktreeGc.autoRepa`, `k8s.imagePulPolicy`)
325
+ * surfaces a non-fatal warning instead of being silently dropped. Factored from
326
+ * the existing `notifications.discord` unknown-key loop (#5453).
327
+ *
328
+ * Iterates own enumerable keys; a key absent from `knownSet` pushes an
329
+ * "Invalid value … unknown key" warning (the NON-fatal wording — the CLI layer
330
+ * escalates only "Invalid type" prefixes, so a cosmetic typo can never fail
331
+ * startup). The "supported:" hint lists `supportedKeys` (defaults to `knownSet`)
332
+ * so a block whose known set includes allowed-but-not-advertised keys (e.g.
333
+ * discord's secret keys, which get their own pointed warning) doesn't surface
334
+ * them as suggestions.
335
+ *
336
+ * @param {object} obj - the sub-block (already known to be a plain object)
337
+ * @param {Set<string>} knownSet - recognised keys (no warning)
338
+ * @param {string} prefix - dotted path for the message (e.g. 'environments.k8s')
339
+ * @param {string[]} warnings - accumulator
340
+ * @param {Set<string>|string[]} [supportedKeys] - keys to list in the hint
341
+ */
342
+ function warnUnknownKeys(obj, knownSet, prefix, warnings, supportedKeys = knownSet) {
343
+ const hint = [...supportedKeys].join(', ')
344
+ for (const key of Object.keys(obj)) {
345
+ if (knownSet.has(key)) continue
346
+ warnings.push(`Invalid value for '${prefix}.${key}': unknown key (supported: ${hint})`)
347
+ }
348
+ }
349
+
350
+ // #5878: recognised keys per advanced/enterprise config sub-block. Each set is
351
+ // the UNION of what the validator checks AND what the wiring layer
352
+ // (createEnvironmentBackend / server-cli / the reaper) forwards to the consumer
353
+ // — a key the consumer reads but the validator omits would otherwise false-warn.
354
+ // Verified against the consumers: the K8sBackend wiring in
355
+ // createEnvironmentBackend (the `new K8sBackend({...})` field list) + the
356
+ // `workspace` sub-block (#4556); billing-budget.js + billing-canary (egressCheck
357
+ // / datacenterPrefixes via server-cli); worktree-reaper.js; rancher.js (the
358
+ // RancherBackend ctor) + resolveRancherToken (tokenEnv / tokenFile).
359
+ const K8S_SUPPORTED_KEYS = new Set([
360
+ 'namespace', 'inCluster', 'kubeconfigPath', 'sidecarImage', 'imagePullPolicy',
361
+ 'connectMode', 'namespaceQuota', 'namespaceLimitRange', 'workspace',
362
+ ])
363
+ const BILLING_SUPPORTED_KEYS = new Set([
364
+ 'creditTier', 'monthlyCreditBudgetUsd', 'budgetWarningPercent', 'egressCheck', 'datacenterPrefixes',
365
+ ])
366
+ const WORKTREE_GC_SUPPORTED_KEYS = new Set([
367
+ 'autoReap', 'reapIntervalMs', 'maxLockAgeMs',
368
+ ])
369
+ const RANCHER_SUPPORTED_KEYS = new Set([
370
+ 'rancherUrl', 'clusterId', 'token', 'tokenEnv', 'tokenFile', 'caData', 'skipTLSVerify', 'defaultProjectId',
371
+ ])
372
+
373
+ /**
374
+ * #5144: validate the `environments.k8s` connection sub-block at config-load
375
+ * time. The `workspace` sub-block has its own validation (#4556); this covers
376
+ * the remaining fields the wiring layer forwards to `K8sBackend`. Every field
377
+ * is optional — only the fields actually present are checked — so a partial
378
+ * block (or one carrying only `workspace`) passes cleanly.
379
+ *
380
+ * Pushes human-readable warnings onto `warnings`; never throws.
381
+ *
382
+ * @param {object} k8s - The `environments.k8s` object (already known to be a plain object)
383
+ * @param {string[]} warnings - Accumulator the caller logs/returns
384
+ */
385
+ function validateK8sBlock(k8s, warnings) {
386
+ const stringFields = ['namespace', 'kubeconfigPath', 'sidecarImage']
387
+ for (const field of stringFields) {
388
+ if (Object.prototype.hasOwnProperty.call(k8s, field) && typeof k8s[field] !== 'string') {
389
+ warnings.push(
390
+ `Invalid type for 'environments.k8s.${field}': expected string, got ${Array.isArray(k8s[field]) ? 'array' : typeof k8s[field]}`,
391
+ )
392
+ }
393
+ }
394
+ if (Object.prototype.hasOwnProperty.call(k8s, 'inCluster') && typeof k8s.inCluster !== 'boolean') {
395
+ warnings.push(
396
+ `Invalid type for 'environments.k8s.inCluster': expected boolean, got ${typeof k8s.inCluster}`,
397
+ )
398
+ }
399
+ if (Object.prototype.hasOwnProperty.call(k8s, 'imagePullPolicy')) {
400
+ const v = k8s.imagePullPolicy
401
+ if (typeof v !== 'string' || !VALID_K8S_PULL_POLICIES.has(v)) {
402
+ warnings.push(
403
+ `Invalid value for 'environments.k8s.imagePullPolicy': '${v}' (must be one of: ${[...VALID_K8S_PULL_POLICIES].join(', ')})`,
404
+ )
405
+ }
406
+ }
407
+ if (Object.prototype.hasOwnProperty.call(k8s, 'connectMode')) {
408
+ const v = k8s.connectMode
409
+ if (typeof v !== 'string' || !VALID_K8S_CONNECT_MODES.has(v)) {
410
+ warnings.push(
411
+ `Invalid value for 'environments.k8s.connectMode': '${v}' (must be one of: ${[...VALID_K8S_CONNECT_MODES].join(', ')})`,
412
+ )
413
+ }
414
+ }
415
+ // #5878: typo-catch. `workspace` IS recognised (validated separately at the
416
+ // call site, #4556), so it's in the known set — only genuine unknowns warn.
417
+ warnUnknownKeys(k8s, K8S_SUPPORTED_KEYS, 'environments.k8s', warnings)
418
+ }
419
+
420
+ /**
421
+ * #5144: validate the `environments.rancher` connection block at config-load
422
+ * time. Mirrors `validateRancherOptions` in rancher.js (URL shape, cluster-ID
423
+ * format, presence of a bearer token) so the operator sees the same error at
424
+ * startup that RancherBackend's constructor would throw — without ever logging
425
+ * the token value itself.
426
+ *
427
+ * Gated on `isRancherConfigured` semantics: a block missing any of rancherUrl /
428
+ * clusterId / token is treated as "Rancher not yet configured" and only its
429
+ * top-level shape (must be a plain object) is checked. This keeps a
430
+ * half-filled-in block from spamming warnings during setup while still
431
+ * catching a genuinely malformed complete config.
432
+ *
433
+ * Pushes human-readable warnings onto `warnings`; never throws. The token value
434
+ * is never echoed into a warning.
435
+ *
436
+ * @param {*} rancher - The `environments.rancher` value (any type)
437
+ * @param {string[]} warnings - Accumulator the caller logs/returns
438
+ */
439
+ function validateRancherBlock(rancher, warnings) {
440
+ if (typeof rancher !== 'object' || rancher === null || Array.isArray(rancher)) {
441
+ warnings.push(
442
+ `Invalid type for 'environments.rancher': expected object, got ${Array.isArray(rancher) ? 'array' : typeof rancher}`,
443
+ )
444
+ return
445
+ }
446
+
447
+ // #5878: typo-catch — runs BEFORE the "configured" gate below so an unknown
448
+ // key warns even in a half-filled-in block.
449
+ warnUnknownKeys(rancher, RANCHER_SUPPORTED_KEYS, 'environments.rancher', warnings)
450
+
451
+ const { rancherUrl, clusterId, token, tokenEnv, tokenFile, caData, skipTLSVerify, defaultProjectId } = rancher
452
+
453
+ // A token can come from any of three secret-friendly sources (resolved by
454
+ // `resolveRancherToken` at construct time). Presence of ANY source counts
455
+ // toward "configured" so a block using `tokenEnv` / `tokenFile` is still
456
+ // validated here (Copilot review #5148) — not just inline `token`.
457
+ const hasTokenSource = Boolean(token || tokenEnv || tokenFile)
458
+
459
+ // Presence gate (mirrors isRancherConfigured): unless rancherUrl + clusterId
460
+ // are present AND a token source is configured, treat the block as "not
461
+ // configured yet" — only the top-level shape was checked above. This keeps a
462
+ // half-filled-in block from spamming warnings during setup.
463
+ const configured = Boolean(rancherUrl && clusterId && hasTokenSource)
464
+ if (!configured) return
465
+
466
+ if (typeof rancherUrl !== 'string' || rancherUrl.length === 0) {
467
+ warnings.push(`Invalid value for 'environments.rancher.rancherUrl': must be a non-empty string`)
468
+ } else {
469
+ let parsed
470
+ try {
471
+ parsed = new URL(rancherUrl)
472
+ } catch {
473
+ parsed = null
474
+ warnings.push(`Invalid URL format for 'environments.rancher.rancherUrl': ${rancherUrl}`)
475
+ }
476
+ if (parsed && parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
477
+ warnings.push(
478
+ `Invalid value for 'environments.rancher.rancherUrl': must use http:// or https://, got '${parsed.protocol}'`,
479
+ )
480
+ }
481
+ }
482
+
483
+ if (typeof clusterId !== 'string' || !RANCHER_CLUSTER_ID_RE.test(clusterId)) {
484
+ warnings.push(
485
+ `Invalid value for 'environments.rancher.clusterId': must match the Rancher cluster-ID format (c-...), got '${clusterId}'`,
486
+ )
487
+ }
488
+
489
+ // Token sources. Validate the SHAPE of each provided source (never the value
490
+ // — the token is never echoed). Only warn "missing token" when NO source is
491
+ // present; an inline `token` is no longer required when `tokenEnv` /
492
+ // `tokenFile` is set (Copilot review #5148).
493
+ if (token != null && (typeof token !== 'string' || token.length === 0)) {
494
+ warnings.push(`Invalid value for 'environments.rancher.token': when provided, must be a non-empty bearer token string`)
495
+ }
496
+ if (tokenEnv != null && (typeof tokenEnv !== 'string' || tokenEnv.length === 0)) {
497
+ warnings.push(`Invalid value for 'environments.rancher.tokenEnv': when provided, must be a non-empty env-var name`)
498
+ }
499
+ if (tokenFile != null && (typeof tokenFile !== 'string' || tokenFile.length === 0)) {
500
+ warnings.push(`Invalid value for 'environments.rancher.tokenFile': when provided, must be a non-empty file path`)
501
+ }
502
+ // NB: a "missing token" warning is unreachable here — the `configured` gate
503
+ // above already requires at least one token source, so a block with no token
504
+ // source short-circuits as "not configured yet" without warning (the intended
505
+ // setup-friendly behaviour). The shape checks above only fire on a block that
506
+ // is otherwise complete.
507
+
508
+ if (caData != null && (typeof caData !== 'string' || caData.length === 0)) {
509
+ warnings.push(
510
+ `Invalid value for 'environments.rancher.caData': when provided, must be a non-empty base64-encoded PEM string`,
511
+ )
512
+ }
513
+
514
+ if (skipTLSVerify != null && typeof skipTLSVerify !== 'boolean') {
515
+ warnings.push(
516
+ `Invalid type for 'environments.rancher.skipTLSVerify': expected boolean, got ${typeof skipTLSVerify}`,
517
+ )
518
+ }
519
+
520
+ if (defaultProjectId != null && (typeof defaultProjectId !== 'string' || !RANCHER_PROJECT_ID_RE.test(defaultProjectId))) {
521
+ warnings.push(
522
+ `Invalid value for 'environments.rancher.defaultProjectId': must match the Rancher project-ID format (p-...), got '${defaultProjectId}'`,
523
+ )
524
+ }
525
+ }
526
+
527
+ /** #5413: decimal 24-bit RGB range for Discord embed sidebar colors. */
528
+ const MAX_DISCORD_COLOR = 16777215
529
+
530
+ // #5453: the recognised `notifications.discord` config knobs. The unknown-key
531
+ // check warns on anything outside this set so a typo (e.g. `botname`) or a
532
+ // test-injection seam (`resolveWebhookUrl`/`sleepImpl`/`now`, reachable via the
533
+ // `{ ...config.notifications.discord }` spread into the sink) surfaces instead of
534
+ // silently no-op'ing / failing the sink closed. Keep in sync with the per-key
535
+ // validation below. The webhook URL is a SECRET (its own warning) — not a knob.
536
+ const DISCORD_SUPPORTED_KEYS = new Set([
537
+ 'botName', 'billingAlerts', 'defaultColor', 'permissionColor', 'errorColor',
538
+ 'colors', 'updateThrottleMs', 'heartbeatIntervalMs', 'pruneAfterMs',
539
+ // #5676 status-watchdog tunables — the sink reads these from the config spread
540
+ // (discord-webhook-sink.js: staleAfterMs/offlineAfterMs, default 10m/30m), so
541
+ // they are real config knobs, not test seams (PR #5845 review).
542
+ 'staleAfterMs', 'offlineAfterMs',
543
+ // State-store paths: the caller (server-cli.js / supervisor.js) defaults these
544
+ // then lets the config spread override them, and push.js honors them
545
+ // (statePath → DiscordWebhookSink, billingStatePath → DiscordBillingSink). They
546
+ // are string value knobs (override → works), unlike the function test seams, so
547
+ // an operator relocating them must not warn as unknown (PR #5845 review).
548
+ 'statePath', 'billingStatePath',
549
+ ])
550
+ const DISCORD_SECRET_KEYS = ['webhookUrl', 'webhook', 'url']
551
+
552
+ /**
553
+ * #5413: validate the `notifications.discord` block (the Discord
554
+ * status-embed sink's non-secret knobs). Every field is optional; only
555
+ * fields actually present are checked. The webhook URL is a secret and
556
+ * does NOT belong here — a `webhookUrl` key in this block gets a pointed
557
+ * warning steering the operator to the credential paths.
558
+ *
559
+ * All warnings use the "Invalid value" wording so a cosmetic typo never
560
+ * escalates to a fatal startup error (the CLI layer treats "Invalid type"
561
+ * prefixes as fatal); the sink clamps bad values to defaults at runtime.
562
+ *
563
+ * @param {*} discord - The `notifications.discord` value
564
+ * @param {string[]} warnings - Accumulator the caller logs/returns
565
+ */
566
+ /**
567
+ * #5665: validate the `billing` block (monthly programmatic-credit budget
568
+ * meter). Per-FIELD problems (bad creditTier, out-of-range numbers) are
569
+ * "Invalid value" warnings — non-fatal, the meter clamps/ignores at runtime.
570
+ * A gross top-level non-object value additionally trips the generic
571
+ * `billing: 'object'` schema check ("Invalid type", fatal), matching the
572
+ * `notifications` / `environments` object blocks — a billing block that isn't
573
+ * even an object is a real misconfiguration worth failing fast on.
574
+ */
575
+ function validateBillingBlock(billing, warnings) {
576
+ if (typeof billing !== 'object' || billing === null || Array.isArray(billing)) {
577
+ warnings.push(`Invalid value for 'billing': expected object, got ${Array.isArray(billing) ? 'array' : typeof billing}`)
578
+ return
579
+ }
580
+ const VALID_TIERS = ['pro', 'max5x', 'max20x']
581
+ if (Object.prototype.hasOwnProperty.call(billing, 'creditTier')) {
582
+ if (typeof billing.creditTier !== 'string' || !VALID_TIERS.includes(billing.creditTier)) {
583
+ warnings.push(`Invalid value for 'billing.creditTier': expected one of ${VALID_TIERS.join(' | ')}, got ${JSON.stringify(billing.creditTier)}`)
584
+ }
585
+ }
586
+ if (Object.prototype.hasOwnProperty.call(billing, 'monthlyCreditBudgetUsd')) {
587
+ const v = billing.monthlyCreditBudgetUsd
588
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
589
+ warnings.push(`Invalid value for 'billing.monthlyCreditBudgetUsd': expected a number >= 0, got ${JSON.stringify(v)}`)
590
+ }
591
+ }
592
+ if (Object.prototype.hasOwnProperty.call(billing, 'budgetWarningPercent')) {
593
+ const v = billing.budgetWarningPercent
594
+ if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0 || v > 100) {
595
+ warnings.push(`Invalid value for 'billing.budgetWarningPercent': expected a number 1-100, got ${JSON.stringify(v)}`)
596
+ }
597
+ }
598
+ // #5828: opt-in datacenter-egress check for the billing canary. Default OFF
599
+ // (no field) — when enabled, the daemon makes a best-effort public-IP lookup
600
+ // so it can warn when a subscription-billed provider runs from a cloud host
601
+ // (a documented ban signal). Off by default because it's an outbound network
602
+ // call the operator should consent to.
603
+ if (Object.prototype.hasOwnProperty.call(billing, 'egressCheck')) {
604
+ if (typeof billing.egressCheck !== 'boolean') {
605
+ warnings.push(`Invalid value for 'billing.egressCheck': expected a boolean, got ${JSON.stringify(billing.egressCheck)}`)
606
+ }
607
+ }
608
+ // #5828: operator-supplied extra IPv4 prefixes for the datacenter classifier
609
+ // (merged with the conservative built-in list). Lets a user on a known cloud
610
+ // add their provider's ranges without a code change.
611
+ if (Object.prototype.hasOwnProperty.call(billing, 'datacenterPrefixes')) {
612
+ const v = billing.datacenterPrefixes
613
+ if (!Array.isArray(v) || !v.every((p) => typeof p === 'string' && p.length > 0)) {
614
+ warnings.push(`Invalid value for 'billing.datacenterPrefixes': expected an array of non-empty strings, got ${JSON.stringify(v)}`)
615
+ }
616
+ }
617
+ // #5878: typo-catch for the billing knobs.
618
+ warnUnknownKeys(billing, BILLING_SUPPORTED_KEYS, 'billing', warnings)
619
+ }
620
+
621
+ const USER_SHELL_SUPPORTED_KEYS = new Set(['enabled', 'requireApproval'])
622
+
623
+ // #5985 (epic #5982): validate the `userShell` block. Only `enabled` (boolean)
624
+ // today; the security primitives (primary-token gate, audit, isolation) land in
625
+ // the #5985b slice. SUB-key checks here are warn-only "Invalid value" (never
626
+ // "Invalid type") so a mis-typed knob doesn't abort startup via
627
+ // loadAndMergeConfig's fatal-prefix — and isUserShellEnabled stays fail-closed
628
+ // for a bad `enabled` value. NOTE: the TOP-LEVEL shape (userShell must be an
629
+ // object) is enforced separately by the shared schema type-gate in
630
+ // validateConfig, which IS fatal for a non-object — same as billing /
631
+ // notifications / environments. That's the fail-safe choice for a security gate:
632
+ // a malformed block stops boot rather than silently disabling.
633
+ function validateUserShellBlock(userShell, warnings) {
634
+ if (typeof userShell !== 'object' || userShell === null || Array.isArray(userShell)) {
635
+ warnings.push(`Invalid value for 'userShell': expected object, got ${Array.isArray(userShell) ? 'array' : typeof userShell}`)
636
+ return
637
+ }
638
+ if (Object.prototype.hasOwnProperty.call(userShell, 'enabled')) {
639
+ if (typeof userShell.enabled !== 'boolean') {
640
+ warnings.push(`Invalid value for 'userShell.enabled': expected a boolean, got ${JSON.stringify(userShell.enabled)}`)
641
+ }
642
+ }
643
+ // #6277 — host-local per-spawn shell approval. Warn-only (never fatal) like
644
+ // `enabled`; isUserShellApprovalRequired stays fail-closed for a bad value.
645
+ if (Object.prototype.hasOwnProperty.call(userShell, 'requireApproval')) {
646
+ if (typeof userShell.requireApproval !== 'boolean') {
647
+ warnings.push(`Invalid value for 'userShell.requireApproval': expected a boolean, got ${JSON.stringify(userShell.requireApproval)}`)
648
+ }
649
+ }
650
+ warnUnknownKeys(userShell, USER_SHELL_SUPPORTED_KEYS, 'userShell', warnings)
651
+ }
652
+
653
+ // #5985: single source of truth for "may a user-shell session be created?".
654
+ // Fail-closed — anything other than an explicit `userShell.enabled === true` is
655
+ // disabled. Used by SessionManager.createSession (the authoritative gate).
656
+ export function isUserShellEnabled(config) {
657
+ return config?.userShell?.enabled === true
658
+ }
659
+
660
+ // #6481 (epic #6469): single source of truth for the OPT-IN IDE feature surface
661
+ // (file navigator, symbol navigation, go-to-definition, find-references,
662
+ // edit-in-place). Off by default so it never risks the core remote-cockpit
663
+ // offering. Enabled by an explicit `features.ide === true` in config OR the
664
+ // `CHROXY_ENABLE_IDE=1` env override (quick opt-in / dev). When on, the server
665
+ // registers the IDE WS handlers and advertises the `ide` capability so clients
666
+ // reveal the IDE UI; off ⇒ the IDE handlers are fail-closed no-ops (registered
667
+ // but gated per-call via isIdeFeatureEnabled, so a runtime flag flip needs no
668
+ // re-registration) and no `ide` capability is advertised — no reachable IDE
669
+ // surface, no IDE UI, core byte-identical.
670
+ // Fail-closed: anything but an explicit boolean true / the env "1" is off.
671
+ export function isIdeFeatureEnabled(config) {
672
+ if (process.env.CHROXY_ENABLE_IDE === '1') return true
673
+ return config?.features?.ide === true
674
+ }
675
+
676
+ // #6277: single source of truth for "does a user-shell spawn need host-local
677
+ // approval first?". Fail-closed — only an explicit `userShell.requireApproval
678
+ // === true` enables the gate. Independent of `enabled`: the gate only bites when
679
+ // shells are enabled (a disabled shell is already rejected upstream), so an
680
+ // operator opts into BOTH `enabled: true` and `requireApproval: true`.
681
+ export function isUserShellApprovalRequired(config) {
682
+ return config?.userShell?.requireApproval === true
683
+ }
684
+
685
+ // #6378: which providers may serve a model id that is NOT in their static
686
+ // allowlist. The static-allowlist subprocess providers (gemini/codex/deepseek)
687
+ // otherwise hard-reject an unlisted-but-API-valid model, forcing a code release
688
+ // just to add one the upstream API already exposes. Opting a provider in here
689
+ // makes it behave like ollama (#5418 PROVIDER_MODELS_UNRESTRICTED): the id
690
+ // passes through verbatim and the upstream API becomes the validator. Returns a
691
+ // Set of provider-name strings; a missing/non-array value → empty Set (the
692
+ // default — OFF, so the misconfig-catching strictness is preserved unless an
693
+ // operator explicitly opts in). Only well-formed string entries are kept.
694
+ export function getAllowAnyModelProviders(config) {
695
+ const raw = config?.providers?.allowAnyModel
696
+ if (!Array.isArray(raw)) return new Set()
697
+ return new Set(raw.filter((name) => typeof name === 'string' && name.length > 0))
698
+ }
699
+
700
+ // #6378: does `providerName` opt out of static model-allowlist validation?
701
+ // Fail-closed: anything other than an explicit entry in
702
+ // `config.providers.allowAnyModel` returns false.
703
+ export function isProviderModelUnrestricted(config, providerName) {
704
+ if (!providerName) return false
705
+ return getAllowAnyModelProviders(config).has(providerName)
706
+ }
707
+
708
+ function validateDiscordNotificationsBlock(discord, warnings) {
709
+ if (typeof discord !== 'object' || discord === null || Array.isArray(discord)) {
710
+ warnings.push(`Invalid value for 'notifications.discord': expected object, got ${Array.isArray(discord) ? 'array' : typeof discord}`)
711
+ return
712
+ }
713
+
714
+ // Secrets do not belong in config.json (not permission-restricted, echoed
715
+ // in verbose output). Warn loudly and point at the right place.
716
+ for (const key of DISCORD_SECRET_KEYS) {
717
+ if (Object.prototype.hasOwnProperty.call(discord, key)) {
718
+ warnings.push(
719
+ `'notifications.discord.${key}' is not supported: the webhook URL is a secret — set CHROXY_DISCORD_WEBHOOK_URL or add "discordWebhookUrl" to ~/.chroxy/credentials.json (mode 0600) instead`,
720
+ )
721
+ }
722
+ }
723
+
724
+ if (Object.prototype.hasOwnProperty.call(discord, 'botName') && (typeof discord.botName !== 'string' || discord.botName.length === 0)) {
725
+ warnings.push(`Invalid value for 'notifications.discord.botName': expected a non-empty string`)
726
+ }
727
+
728
+ // #5828: kill-switch for the Discord billing-alert sink. Default ON when a
729
+ // webhook resolves; set false to keep billing alerts off Discord while the
730
+ // status embed stays on.
731
+ if (Object.prototype.hasOwnProperty.call(discord, 'billingAlerts') && typeof discord.billingAlerts !== 'boolean') {
732
+ warnings.push(`Invalid value for 'notifications.discord.billingAlerts': expected a boolean, got ${JSON.stringify(discord.billingAlerts)}`)
733
+ }
734
+
735
+ const isValidColor = (v) => Number.isInteger(v) && v >= 0 && v <= MAX_DISCORD_COLOR
736
+ for (const key of ['defaultColor', 'permissionColor', 'errorColor']) {
737
+ if (Object.prototype.hasOwnProperty.call(discord, key) && !isValidColor(discord[key])) {
738
+ warnings.push(`Invalid value for 'notifications.discord.${key}': expected an integer 0-${MAX_DISCORD_COLOR} (decimal 24-bit RGB), got ${JSON.stringify(discord[key])}`)
739
+ }
740
+ }
741
+
742
+ if (Object.prototype.hasOwnProperty.call(discord, 'colors')) {
743
+ const colors = discord.colors
744
+ if (typeof colors !== 'object' || colors === null || Array.isArray(colors)) {
745
+ warnings.push(`Invalid value for 'notifications.discord.colors': expected an object mapping project name → decimal color`)
746
+ } else {
747
+ for (const [project, value] of Object.entries(colors)) {
748
+ if (!isValidColor(value)) {
749
+ warnings.push(`Invalid value for 'notifications.discord.colors.${project}': expected an integer 0-${MAX_DISCORD_COLOR} (decimal 24-bit RGB), got ${JSON.stringify(value)}`)
750
+ }
751
+ }
752
+ }
753
+ }
754
+
755
+ if (Object.prototype.hasOwnProperty.call(discord, 'updateThrottleMs')) {
756
+ const v = discord.updateThrottleMs
757
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
758
+ warnings.push(`Invalid value for 'notifications.discord.updateThrottleMs': expected a number >= 0, got ${JSON.stringify(v)}`)
759
+ }
760
+ }
761
+
762
+ if (Object.prototype.hasOwnProperty.call(discord, 'heartbeatIntervalMs')) {
763
+ const v = discord.heartbeatIntervalMs
764
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
765
+ warnings.push(`Invalid value for 'notifications.discord.heartbeatIntervalMs': expected a number >= 0 (0 disables), got ${JSON.stringify(v)}`)
766
+ } else if (v !== 0 && v < 10_000) {
767
+ warnings.push(`Invalid value for 'notifications.discord.heartbeatIntervalMs': ${v} (minimum 10000 / 10s; set 0 to disable — the sink falls back to its default)`)
768
+ }
769
+ }
770
+
771
+ // #5429/#5434: state-store entry retention. 0 disables pruning; the sink
772
+ // falls back to its 24h default on invalid values. #5457: values below 60s
773
+ // get the same treatment — a retention shorter than the gap between events
774
+ // prunes the messageId in between and turns the single status embed into
775
+ // message-per-event spam (parity with the heartbeatIntervalMs floor).
776
+ if (Object.prototype.hasOwnProperty.call(discord, 'pruneAfterMs')) {
777
+ const v = discord.pruneAfterMs
778
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
779
+ warnings.push(`Invalid value for 'notifications.discord.pruneAfterMs': expected a number >= 0 (0 disables pruning), got ${JSON.stringify(v)}`)
780
+ } else if (v !== 0 && v < 60_000) {
781
+ warnings.push(`Invalid value for 'notifications.discord.pruneAfterMs': ${v} (minimum 60000 / 60s; set 0 to disable pruning — the sink falls back to its default)`)
782
+ }
783
+ }
784
+
785
+ // #5676 status-watchdog tunables: the sink honors any finite >= 0 value, else
786
+ // falls back to its default (10m stale / 30m offline). Validate to keep
787
+ // DISCORD_SUPPORTED_KEYS in sync with the per-key checks (PR #5845 review).
788
+ for (const key of ['staleAfterMs', 'offlineAfterMs']) {
789
+ if (Object.prototype.hasOwnProperty.call(discord, key)) {
790
+ const v = discord[key]
791
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
792
+ warnings.push(`Invalid value for 'notifications.discord.${key}': expected a number >= 0 (the sink falls back to its default), got ${JSON.stringify(v)}`)
793
+ }
794
+ }
795
+ }
796
+
797
+ // #5453: warn on any unrecognised key. A typo'd knob is silently ignored
798
+ // (operator gets default behavior with no hint), and a test-seam key spread
799
+ // into the sink constructor fails it closed — both silent foot-guns. The
800
+ // secret keys are KNOWN (no unknown-key warning — they already got their
801
+ // specific "it's a secret" warning above) but are NOT advertised in the
802
+ // "supported:" hint, so warnUnknownKeys takes the union as the known set and
803
+ // DISCORD_SUPPORTED_KEYS as the hint. #5878: factored onto the shared helper.
804
+ warnUnknownKeys(
805
+ discord,
806
+ new Set([...DISCORD_SUPPORTED_KEYS, ...DISCORD_SECRET_KEYS]),
807
+ 'notifications.discord',
808
+ warnings,
809
+ DISCORD_SUPPORTED_KEYS,
810
+ )
811
+ }
812
+
813
+ /**
814
+ * Return a copy of config with sensitive fields replaced by '***'.
815
+ * Use this whenever the config object is serialized to logs or debug output.
816
+ *
817
+ * @param {object} config - Config object to sanitize
818
+ * @returns {object} Shallow copy with sensitive fields masked
819
+ */
820
+ export function sanitizeConfig(config) {
821
+ const safe = { ...config }
822
+ for (const key of SENSITIVE_KEYS) {
823
+ if (safe[key]) safe[key] = '***'
824
+ }
825
+ return safe
826
+ }
827
+
828
+ /**
829
+ * The SINGLE source of the fatal-vs-warn config policy (audit P1-9). A config
830
+ * problem is FATAL (the CLI exits 1) iff its warning is a schema TYPE mismatch
831
+ * — wording prefix "Invalid type ..." — because a wrong-typed field is a real
832
+ * misconfiguration the operator must fix. Everything else ("Invalid value ...",
833
+ * "Unknown config key ...", range/format warnings) is non-fatal: the runtime
834
+ * clamps/ignores it, so a cosmetic typo never blocks startup.
835
+ *
836
+ * This used to be inlined as `w.startsWith('Invalid type')` in cli/shared.js,
837
+ * divorced from where the warnings are produced — so a new fatal/non-fatal
838
+ * decision had no single home and a mis-prefixed message could silently flip
839
+ * a field's severity. Centralizing it here (with the invariant test in
840
+ * config.test.js asserting no "Invalid value" warning is ever fatal) keeps the
841
+ * policy and the wording convention in lockstep.
842
+ */
843
+ export const FATAL_CONFIG_WARNING_PREFIX = 'Invalid type'
844
+
845
+ /** True iff this validateConfig warning should abort startup. See FATAL_CONFIG_WARNING_PREFIX. */
846
+ export function isFatalConfigWarning(warning) {
847
+ return typeof warning === 'string' && warning.startsWith(FATAL_CONFIG_WARNING_PREFIX)
848
+ }
849
+
850
+ /**
851
+ * Declarative range checks for the simple numeric config fields (audit P2-6).
852
+ * Each entry replaces a hand-rolled `if (Number.isFinite(value) ...)` block that
853
+ * was copy-pasted ~6 times — a shape where a forgotten `Number.isFinite` guard,
854
+ * a missed `allowZero`, or an inverted comparison silently flips validation.
855
+ *
856
+ * `belowMessage`/`aboveMessage` are the EXACT operator-facing suffixes (appended
857
+ * after `${value} `); wording is per-field by design (different unit labels).
858
+ * Only the `Invalid value` PREFIX is load-bearing — it must never become
859
+ * `Invalid type`, which the CLI treats as fatal (see FATAL_CONFIG_WARNING_PREFIX).
860
+ *
861
+ * Fields with extra logic stay bespoke in validateConfig: `sessionTimeout`
862
+ * (duration-string parse), `hardTimeoutMs` (cross-field vs resultTimeoutMs), and
863
+ * `providerStreamStallTimeoutMs` (per-entry map iteration).
864
+ */
865
+ const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000
866
+ const NUMERIC_RANGE_CHECKS = [
867
+ { key: 'port', min: 1, max: 65535, belowMessage: '(must be 1-65535)', aboveMessage: '(must be 1-65535)' },
868
+ { key: 'maxSessions', min: 1, belowMessage: '(must be >= 1)' },
869
+ { key: 'maxPayload', min: 1024, max: 100 * 1024 * 1024, belowMessage: '(minimum 1KB / 1024 bytes)', aboveMessage: '(maximum 100MB)' },
870
+ { key: 'resultTimeoutMs', min: 30_000, max: TWENTY_FOUR_HOURS_MS, finiteOnly: true, belowMessage: '(minimum 30000 / 30s)', aboveMessage: '(maximum 86400000 / 24h)' },
871
+ { key: 'streamStallTimeoutMs', min: 5_000, max: TWENTY_FOUR_HOURS_MS, allowZero: true, finiteOnly: true, belowMessage: '(minimum 5000 / 5s; set 0 to disable)', aboveMessage: '(maximum 86400000 / 24h)' },
872
+ { key: 'backgroundShellHardQuiesceMs', min: 60_000, max: TWENTY_FOUR_HOURS_MS, allowZero: true, finiteOnly: true, belowMessage: '(minimum 60000 / 60s; set 0 to disable)', aboveMessage: '(maximum 86400000 / 24h)' },
873
+ ]
874
+
875
+ /**
876
+ * Push an `Invalid value` warning when numeric `value` falls outside [min, max].
877
+ * Skips non-number / NaN (the type-check loop already warned). `allowZero` skips
878
+ * an explicit 0 (the "disable" sentinel). `min`/`max` are each optional
879
+ * (maxSessions has only a lower bound).
880
+ *
881
+ * `finiteOnly` selects the original per-field guard exactly: port/maxSessions/
882
+ * maxPayload historically used `typeof === 'number'`, so a parseFloat'd env like
883
+ * `PORT=Infinity` reaches the comparison and trips the bound — keep that. The
884
+ * timeout fields used `Number.isFinite`, which skips Infinity entirely — keep
885
+ * that too (finiteOnly: true).
886
+ */
887
+ function validateRange(warnings, key, value, { min, max, allowZero = false, finiteOnly = false, belowMessage, aboveMessage }) {
888
+ if (typeof value !== 'number' || Number.isNaN(value)) return
889
+ if (finiteOnly && !Number.isFinite(value)) return
890
+ if (allowZero && value === 0) return
891
+ if (min != null && value < min) {
892
+ warnings.push(`Invalid value for '${key}': ${value} ${belowMessage}`)
893
+ } else if (max != null && value > max) {
894
+ warnings.push(`Invalid value for '${key}': ${value} ${aboveMessage}`)
895
+ }
896
+ }
897
+
898
+ /**
899
+ * Validate config object against schema.
900
+ * Logs warnings for unknown keys and type mismatches.
901
+ *
902
+ * @param {object} config - Config object to validate
903
+ * @param {boolean} verbose - If true, log detailed validation info
904
+ * @returns {object} Validation result { valid: boolean, warnings: string[] }
905
+ */
906
+ export function validateConfig(config, verbose = false) {
907
+ const warnings = []
908
+
909
+ // Check for unknown keys
910
+ for (const key of Object.keys(config)) {
911
+ if (!(key in CONFIG_SCHEMA)) {
912
+ warnings.push(`Unknown config key: '${key}' (will be ignored)`)
913
+ }
914
+ }
915
+
916
+ // Check types for known keys. A schema entry may be a union of types
917
+ // separated by '|' (#5419 — `providers` accepts the legacy array OR the
918
+ // object form); single-type entries keep the exact legacy wording.
919
+ for (const [key, expectedType] of Object.entries(CONFIG_SCHEMA)) {
920
+ if (key in config) {
921
+ const value = config[key]
922
+ const actualType = Array.isArray(value) ? 'array' : typeof value
923
+ const expectedTypes = expectedType.split('|')
924
+
925
+ if (!expectedTypes.includes(actualType)) {
926
+ warnings.push(`Invalid type for '${key}': expected ${expectedTypes.join(' or ')}, got ${actualType}`)
927
+ }
928
+ }
929
+ }
930
+
931
+ // Range validation for the simple numeric fields (audit P2-6) — declarative
932
+ // table + shared validateRange; the Number.isFinite guard skips fields whose
933
+ // type the loop above already flagged. Duration/cross-field/map cases below
934
+ // stay bespoke.
935
+ for (const check of NUMERIC_RANGE_CHECKS) {
936
+ validateRange(warnings, check.key, config[check.key], check)
937
+ }
938
+
939
+ if (typeof config.sessionTimeout === 'string' && config.sessionTimeout.length > 0) {
940
+ const ms = parseDuration(config.sessionTimeout)
941
+ if (ms == null) {
942
+ warnings.push(`Invalid duration format for 'sessionTimeout': '${config.sessionTimeout}'`)
943
+ } else if (ms < 30_000) {
944
+ warnings.push(`Value for 'sessionTimeout' is too low: '${config.sessionTimeout}' (minimum 30s)`)
945
+ }
946
+ }
947
+
948
+ // #6598: paired-session-token lifetime. Warn on a typo (which would silently
949
+ // fall back to the 30d default) or a sub-floor value (floored to 5min at wiring).
950
+ if (typeof config.sessionTokenTtl === 'string' && config.sessionTokenTtl.length > 0) {
951
+ const ms = parseDuration(config.sessionTokenTtl)
952
+ if (ms == null) {
953
+ warnings.push(`Invalid duration format for 'sessionTokenTtl': '${config.sessionTokenTtl}'`)
954
+ } else if (ms < 5 * 60_000) {
955
+ warnings.push(`Value for 'sessionTokenTtl' is too low: '${config.sessionTokenTtl}' (minimum 5m)`)
956
+ }
957
+ }
958
+
959
+ // #3899: hard-cap range. Same 30s / 24h bounds as resultTimeoutMs.
960
+ // Additionally: warn if hardTimeoutMs < resultTimeoutMs — the soft
961
+ // warning is supposed to fire first; an inverted config would fire
962
+ // the kill before the warning ever surfaces. Warn-only (not clamped)
963
+ // so operators can deliberately set them equal for tight kill
964
+ // semantics if they really want.
965
+ if (Number.isFinite(config.hardTimeoutMs)) {
966
+ if (config.hardTimeoutMs < 30_000) {
967
+ warnings.push(`Invalid value for 'hardTimeoutMs': ${config.hardTimeoutMs} (minimum 30000 / 30s)`)
968
+ } else if (config.hardTimeoutMs > 24 * 60 * 60 * 1000) {
969
+ warnings.push(`Invalid value for 'hardTimeoutMs': ${config.hardTimeoutMs} (maximum 86400000 / 24h)`)
970
+ } else if (Number.isFinite(config.resultTimeoutMs) && config.hardTimeoutMs < config.resultTimeoutMs) {
971
+ warnings.push(`'hardTimeoutMs' (${config.hardTimeoutMs}) is less than 'resultTimeoutMs' (${config.resultTimeoutMs}) — the soft warning will never fire before the hard kill`)
972
+ }
973
+ }
974
+
975
+ // #4601: per-provider override map. Each entry follows the same
976
+ // 5s-24h-or-0 range as the global `streamStallTimeoutMs`. Values that
977
+ // pass type-of-map but fail per-entry validation produce a single warn
978
+ // per offending entry; the runtime ignores those entries and falls
979
+ // back to the global / default value (see SessionManager). The
980
+ // top-level type check above (object) already rejects arrays via the
981
+ // `actualType === 'array'` branch, so this block only runs on real
982
+ // plain objects.
983
+ if (
984
+ config.providerStreamStallTimeoutMs &&
985
+ typeof config.providerStreamStallTimeoutMs === 'object' &&
986
+ !Array.isArray(config.providerStreamStallTimeoutMs)
987
+ ) {
988
+ for (const [providerId, value] of Object.entries(config.providerStreamStallTimeoutMs)) {
989
+ const path = `providerStreamStallTimeoutMs.${providerId}`
990
+ // NB: a bad per-entry value is an "Invalid value" warning (NOT
991
+ // "Invalid type") even when the JS-level type mismatches the
992
+ // expected number. The CLI layer (`cli/shared.js:loadAndMergeConfig`)
993
+ // treats any warning whose prefix is "Invalid type" as a fatal
994
+ // startup error — using that wording for a single mis-typed map
995
+ // entry would prevent the whole server from booting, contradicting
996
+ // the documented "drop bad entries, fall through to global" contract
997
+ // (see PR #4745 Copilot review feedback).
998
+ if (typeof value !== 'number') {
999
+ warnings.push(`Invalid value for '${path}': expected number, got ${Array.isArray(value) ? 'array' : typeof value}`)
1000
+ continue
1001
+ }
1002
+ if (!Number.isFinite(value) || value < 0) {
1003
+ warnings.push(`Invalid value for '${path}': ${value} (must be 0 or a positive number)`)
1004
+ continue
1005
+ }
1006
+ if (value === 0) continue
1007
+ if (value < 5_000) {
1008
+ warnings.push(`Invalid value for '${path}': ${value} (minimum 5000 / 5s; set 0 to disable)`)
1009
+ } else if (value > 24 * 60 * 60 * 1000) {
1010
+ warnings.push(`Invalid value for '${path}': ${value} (maximum 86400000 / 24h)`)
1011
+ }
1012
+ }
1013
+ }
1014
+
1015
+ // #4482: per-MCP-call timeout. 1s-10min. Unlike streamStallTimeoutMs,
1016
+ // 0 isn't meaningful here — a 0-ms callTool timeout fires immediately
1017
+ // and makes every MCP tool look broken — so any non-finite / non-
1018
+ // positive value gets a warning and the runtime falls back to the
1019
+ // client default (30s) instead of accepting it.
1020
+ if (Number.isFinite(config.mcpToolCallTimeoutMs)) {
1021
+ if (config.mcpToolCallTimeoutMs < 1_000) {
1022
+ warnings.push(`Invalid value for 'mcpToolCallTimeoutMs': ${config.mcpToolCallTimeoutMs} (minimum 1000 / 1s)`)
1023
+ } else if (config.mcpToolCallTimeoutMs > 10 * 60 * 1000) {
1024
+ warnings.push(`Invalid value for 'mcpToolCallTimeoutMs': ${config.mcpToolCallTimeoutMs} (maximum 600000 / 10min)`)
1025
+ }
1026
+ }
1027
+
1028
+ // #4556: validate the optional environments.k8s.workspace block (operator
1029
+ // surface for the K8sBackend PVC strategy added in #4547 / #4548). Done at
1030
+ // config-load time so a typo (missing claimName, wrong type) surfaces at
1031
+ // startup rather than on the first environment-creation call. Shape mirrors
1032
+ // `K8sBackend.validateWorkspacePVC()` so an operator never sees a different
1033
+ // message at load-time vs runtime for the same malformed value.
1034
+ //
1035
+ // Only fires when the sub-block is present — the common case (Docker
1036
+ // operators without any k8s key, or with other k8s settings but no
1037
+ // workspace block) passes through untouched.
1038
+ if (config.environments && typeof config.environments === 'object' && !Array.isArray(config.environments)) {
1039
+ // #5144: backend selector. One of 'docker' (default) | 'k8s' | 'rancher'.
1040
+ // When absent the wiring layer falls back to Docker, so the common
1041
+ // single-node setup is unchanged. A bad value is warn-only (not fatal):
1042
+ // the wiring layer treats an unrecognised selector as Docker, mirroring
1043
+ // the "drop bad value, keep the safe default" contract used elsewhere.
1044
+ if (Object.prototype.hasOwnProperty.call(config.environments, 'backend')) {
1045
+ const backend = config.environments.backend
1046
+ if (typeof backend !== 'string') {
1047
+ // Deliberately an "Invalid value" (not "Invalid type") warning: the
1048
+ // wiring layer (`resolveEnvironmentBackend`) treats anything
1049
+ // unrecognised as Docker, so a typo must NOT be fatal.
1050
+ // `loadAndMergeConfig` escalates only "Invalid type" warnings to a hard
1051
+ // exit, which would contradict the documented "malformed → docker"
1052
+ // fallback (Copilot review #5148).
1053
+ warnings.push(
1054
+ `Invalid value for 'environments.backend': expected one of ${[...ENVIRONMENT_BACKENDS].join(', ')}, got ${Array.isArray(backend) ? 'array' : typeof backend}`,
1055
+ )
1056
+ } else if (!ENVIRONMENT_BACKENDS.has(backend)) {
1057
+ warnings.push(
1058
+ `Invalid value for 'environments.backend': '${backend}' (must be one of: ${[...ENVIRONMENT_BACKENDS].join(', ')})`,
1059
+ )
1060
+ }
1061
+ }
1062
+
1063
+ const k8sBlock = config.environments.k8s
1064
+ if (k8sBlock && typeof k8sBlock === 'object' && !Array.isArray(k8sBlock)) {
1065
+ // #5144: validate the K8s connection sub-block (the `workspace` block
1066
+ // below already had its own validation from #4556). Only fields the
1067
+ // wiring layer actually forwards to K8sBackend are checked; each is
1068
+ // optional so a partial block (or just the workspace sub-block) passes.
1069
+ validateK8sBlock(k8sBlock, warnings)
1070
+ if (Object.prototype.hasOwnProperty.call(k8sBlock, 'workspace')) {
1071
+ const ws = k8sBlock.workspace
1072
+ if (typeof ws !== 'object' || ws === null || Array.isArray(ws)) {
1073
+ warnings.push(
1074
+ `Invalid 'environments.k8s.workspace': must be an object with a claimName property`,
1075
+ )
1076
+ } else {
1077
+ if (!Object.prototype.hasOwnProperty.call(ws, 'claimName')) {
1078
+ warnings.push(
1079
+ `Missing 'environments.k8s.workspace.claimName': required, non-empty string`,
1080
+ )
1081
+ } else if (typeof ws.claimName !== 'string') {
1082
+ warnings.push(
1083
+ `Invalid type for 'environments.k8s.workspace.claimName': expected string, got ${typeof ws.claimName}`,
1084
+ )
1085
+ } else if (ws.claimName.length === 0) {
1086
+ warnings.push(
1087
+ `Invalid value for 'environments.k8s.workspace.claimName': must be a non-empty string`,
1088
+ )
1089
+ }
1090
+ if (Object.prototype.hasOwnProperty.call(ws, 'mountPath') && typeof ws.mountPath !== 'string') {
1091
+ warnings.push(
1092
+ `Invalid type for 'environments.k8s.workspace.mountPath': expected string, got ${typeof ws.mountPath}`,
1093
+ )
1094
+ }
1095
+ if (Object.prototype.hasOwnProperty.call(ws, 'readOnly') && typeof ws.readOnly !== 'boolean') {
1096
+ warnings.push(
1097
+ `Invalid type for 'environments.k8s.workspace.readOnly': expected boolean, got ${typeof ws.readOnly}`,
1098
+ )
1099
+ }
1100
+ }
1101
+ }
1102
+ }
1103
+
1104
+ // #5144: validate the Rancher connection block. Mirrors
1105
+ // `validateRancherOptions` in rancher.js so an operator never sees one
1106
+ // message at config-load time and a different one when RancherBackend is
1107
+ // constructed. Gated on `isRancherConfigured` (presence of rancherUrl +
1108
+ // clusterId + token): a block that does not yet carry a complete Rancher
1109
+ // config is treated as "Rancher not configured" and only its shape (object,
1110
+ // not array) is checked — partial blocks during setup don't spam warnings.
1111
+ const rancherBlock = config.environments.rancher
1112
+ if (rancherBlock !== undefined) {
1113
+ validateRancherBlock(rancherBlock, warnings)
1114
+ }
1115
+ }
1116
+
1117
+ // #5158: worktree GC block. Only the shape (object, not array), the
1118
+ // `autoReap` boolean, and the `reapIntervalMs` positive number (#5326) are
1119
+ // checked; an unset block means "auto-reaper off".
1120
+ if (config.worktreeGc !== undefined) {
1121
+ if (typeof config.worktreeGc !== 'object' || config.worktreeGc === null || Array.isArray(config.worktreeGc)) {
1122
+ warnings.push(`Invalid type for 'worktreeGc': expected object, got ${Array.isArray(config.worktreeGc) ? 'array' : typeof config.worktreeGc}`)
1123
+ } else {
1124
+ if (
1125
+ Object.prototype.hasOwnProperty.call(config.worktreeGc, 'autoReap') &&
1126
+ typeof config.worktreeGc.autoReap !== 'boolean'
1127
+ ) {
1128
+ warnings.push(`Invalid type for 'worktreeGc.autoReap': expected boolean, got ${typeof config.worktreeGc.autoReap}`)
1129
+ }
1130
+ // #5326 (WP-5.4): periodic-reaper interval. Optional; when omitted the
1131
+ // reaper uses its built-in default. Must be a positive finite number.
1132
+ if (Object.prototype.hasOwnProperty.call(config.worktreeGc, 'reapIntervalMs')) {
1133
+ const v = config.worktreeGc.reapIntervalMs
1134
+ if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) {
1135
+ warnings.push(`Invalid value for 'worktreeGc.reapIntervalMs': expected a positive number, got ${typeof v === 'number' ? v : typeof v}`)
1136
+ }
1137
+ }
1138
+ // #5706: absolute-age fallback for the PID-liveness check. A non-negative
1139
+ // number of ms; 0 (the default) disables the fallback (pure PID liveness).
1140
+ // Negative / non-finite values WARN; they're not hard-rejected, but they
1141
+ // fail safe — planRepoGc treats any non-positive/NaN value as disabled, so
1142
+ // a typo can only ever turn the fallback OFF, never silently widen it.
1143
+ if (Object.prototype.hasOwnProperty.call(config.worktreeGc, 'maxLockAgeMs')) {
1144
+ const v = config.worktreeGc.maxLockAgeMs
1145
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
1146
+ warnings.push(`Invalid value for 'worktreeGc.maxLockAgeMs': expected a non-negative number (0 disables), got ${typeof v === 'number' ? v : typeof v}`)
1147
+ }
1148
+ }
1149
+ // #5878: typo-catch for the worktree-GC knobs.
1150
+ warnUnknownKeys(config.worktreeGc, WORKTREE_GC_SUPPORTED_KEYS, 'worktreeGc', warnings)
1151
+ }
1152
+ }
1153
+
1154
+ // #5413: notifications block. Only `notifications.discord` is recognised
1155
+ // today. All warnings here are "Invalid value" (not "Invalid type") so a
1156
+ // typo in a cosmetic color can never become a fatal startup error via the
1157
+ // loadAndMergeConfig "Invalid type" escalation — the sink clamps bad
1158
+ // values to its defaults at runtime.
1159
+ // #5665: validate the `billing` block (monthly programmatic-credit meter).
1160
+ // Per-field typos are warn-only "Invalid value"; see validateBillingBlock.
1161
+ if (config.billing !== undefined) {
1162
+ validateBillingBlock(config.billing, warnings)
1163
+ }
1164
+
1165
+ // #5985 (epic #5982): validate the user-shell gate block.
1166
+ if (config.userShell !== undefined) {
1167
+ validateUserShellBlock(config.userShell, warnings)
1168
+ }
1169
+
1170
+ if (config.notifications !== undefined) {
1171
+ if (typeof config.notifications !== 'object' || config.notifications === null || Array.isArray(config.notifications)) {
1172
+ // "Invalid value", NOT "Invalid type" — loadAndMergeConfig escalates
1173
+ // the "Invalid type" prefix to a fatal startup error, and this block
1174
+ // is deliberately warn-only (a cosmetic-notifications typo must never
1175
+ // stop the daemon from booting).
1176
+ warnings.push(`Invalid value for 'notifications': expected an object, got ${Array.isArray(config.notifications) ? 'array' : typeof config.notifications}`)
1177
+ } else if (config.notifications.discord !== undefined) {
1178
+ validateDiscordNotificationsBlock(config.notifications.discord, warnings)
1179
+ }
1180
+ }
1181
+
1182
+ // #5419: providers block. The legacy array form (chroxy init's
1183
+ // informational provider-id list) passes through unvalidated, as
1184
+ // before; the object form carries `providers.anthropicCompatible` —
1185
+ // config-driven Anthropic-compatible endpoint entries. All entry-level
1186
+ // warnings use "Invalid value" wording (never the "Invalid type"
1187
+ // prefix) so a malformed entry can't become a fatal startup error via
1188
+ // the loadAndMergeConfig escalation — bad entries are dropped at
1189
+ // registration (anthropic-compatible-session.js) and valid siblings
1190
+ // still register.
1191
+ if (
1192
+ config.providers !== undefined &&
1193
+ typeof config.providers === 'object' &&
1194
+ config.providers !== null &&
1195
+ !Array.isArray(config.providers)
1196
+ ) {
1197
+ validateProvidersConfigBlock(config.providers, warnings)
1198
+ }
1199
+
1200
+ // Validate externalUrl format if provided
1201
+ if (config.externalUrl && typeof config.externalUrl === 'string') {
1202
+ try {
1203
+ const parsed = new URL(config.externalUrl)
1204
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
1205
+ warnings.push(`externalUrl should use http:// or https:// protocol, got '${parsed.protocol}'`)
1206
+ }
1207
+ } catch {
1208
+ warnings.push(`Invalid URL format for 'externalUrl': ${config.externalUrl}`)
1209
+ }
1210
+ }
1211
+
1212
+ // Log warnings
1213
+ if (warnings.length > 0) {
1214
+ log.warn('Configuration warnings:')
1215
+ for (const warning of warnings) {
1216
+ log.warn(` - ${warning}`)
1217
+ }
1218
+ }
1219
+
1220
+ if (verbose && warnings.length === 0) {
1221
+ log.info('Configuration validated successfully')
1222
+ }
1223
+
1224
+ return {
1225
+ valid: warnings.length === 0,
1226
+ warnings,
1227
+ }
1228
+ }
1229
+
1230
+ /**
1231
+ * Merge configuration from multiple sources with proper precedence.
1232
+ *
1233
+ * Precedence order (highest to lowest):
1234
+ * 1. CLI options (provided via cli.js commands)
1235
+ * 2. Environment variables
1236
+ * 3. Config file
1237
+ * 4. Defaults
1238
+ *
1239
+ * @param {object} options - Options object from CLI
1240
+ * @param {object} options.fileConfig - Config loaded from file
1241
+ * @param {object} options.cliOverrides - CLI flag overrides
1242
+ * @param {object} options.defaults - Default values
1243
+ * @param {boolean} options.verbose - Log source of each config value
1244
+ * @returns {object} Merged config object
1245
+ */
1246
+ export function mergeConfig({ fileConfig = {}, cliOverrides = {}, defaults = {}, verbose = false }) {
1247
+ const merged = {}
1248
+ const sources = {}
1249
+
1250
+ // Helper to set value and track source
1251
+ const setValue = (key, value, source) => {
1252
+ merged[key] = value
1253
+ sources[key] = source
1254
+ }
1255
+
1256
+ // Get all possible keys from defaults, fileConfig, cliOverrides, AND known schema keys with env vars
1257
+ const allKeys = new Set([
1258
+ ...Object.keys(defaults),
1259
+ ...Object.keys(fileConfig),
1260
+ ...Object.keys(cliOverrides),
1261
+ ...Object.keys(CONFIG_SCHEMA),
1262
+ ])
1263
+
1264
+ // Apply precedence for each key
1265
+ for (const key of allKeys) {
1266
+ if (cliOverrides[key] !== undefined) {
1267
+ setValue(key, cliOverrides[key], 'CLI')
1268
+ } else {
1269
+ const envKey = envKeyForConfig(key)
1270
+ if (process.env[envKey] !== undefined) {
1271
+ const envValue = parseEnvValue(key, process.env[envKey])
1272
+ setValue(key, envValue, 'ENV')
1273
+ } else if (fileConfig[key] !== undefined) {
1274
+ setValue(key, fileConfig[key], 'config file')
1275
+ } else if (defaults[key] !== undefined) {
1276
+ setValue(key, defaults[key], 'default')
1277
+ }
1278
+ }
1279
+ }
1280
+
1281
+ // Map legacy legacyCli flag to provider if no explicit provider set
1282
+ if (merged.legacyCli && !merged.provider) {
1283
+ merged.provider = 'claude-cli'
1284
+ sources.provider = 'legacyCli mapping'
1285
+ }
1286
+
1287
+ // Log sources in verbose mode (after mapping so provider is included)
1288
+ if (verbose) {
1289
+ const safe = sanitizeConfig(merged)
1290
+ log.info('Configuration sources:')
1291
+ for (const [key, source] of Object.entries(sources)) {
1292
+ log.info(` ${key.padEnd(16)} = ${JSON.stringify(safe[key]).padEnd(24)} (${source})`)
1293
+ }
1294
+ }
1295
+
1296
+ return merged
1297
+ }
1298
+
1299
+ /**
1300
+ * Convert config key to corresponding environment variable name.
1301
+ * @param {string} key - Config key
1302
+ * @returns {string} Environment variable name
1303
+ */
1304
+ function envKeyForConfig(key) {
1305
+ const envMap = {
1306
+ apiToken: 'API_TOKEN',
1307
+ port: 'PORT',
1308
+ host: 'CHROXY_HOST',
1309
+ cwd: 'CHROXY_CWD',
1310
+ model: 'CHROXY_MODEL',
1311
+ allowedTools: 'CHROXY_ALLOWED_TOOLS',
1312
+ noAuth: 'CHROXY_NO_AUTH',
1313
+ maxRestarts: 'CHROXY_MAX_RESTARTS',
1314
+ terminalDownGraceMs: 'CHROXY_TERMINAL_DOWN_GRACE_MS',
1315
+ tunnel: 'CHROXY_TUNNEL',
1316
+ tunnelName: 'CHROXY_TUNNEL_NAME',
1317
+ tunnelHostname: 'CHROXY_TUNNEL_HOSTNAME',
1318
+ tunnelConfig: 'CHROXY_TUNNEL_CONFIG',
1319
+ legacyCli: 'CHROXY_LEGACY_CLI',
1320
+ provider: 'CHROXY_PROVIDER',
1321
+ providers: 'CHROXY_PROVIDERS',
1322
+ maxPayload: 'CHROXY_MAX_PAYLOAD',
1323
+ maxToolInput: 'CHROXY_MAX_TOOL_INPUT',
1324
+ noEncrypt: 'CHROXY_NO_ENCRYPT',
1325
+ encryptLocalhost: 'CHROXY_ENCRYPT_LOCALHOST',
1326
+ transforms: 'CHROXY_TRANSFORMS',
1327
+ tokenExpiry: 'CHROXY_TOKEN_EXPIRY',
1328
+ sessionTokenTtl: 'CHROXY_SESSION_TOKEN_TTL',
1329
+ sessionTimeout: 'CHROXY_SESSION_TIMEOUT',
1330
+ costBudget: 'CHROXY_COST_BUDGET',
1331
+ externalUrl: 'CHROXY_EXTERNAL_URL',
1332
+ maxSessions: 'CHROXY_MAX_SESSIONS',
1333
+ maxHistory: 'CHROXY_MAX_HISTORY',
1334
+ maxMessages: 'CHROXY_MAX_MESSAGES',
1335
+ showToken: 'CHROXY_SHOW_TOKEN',
1336
+ repos: 'CHROXY_REPOS',
1337
+ // #5172: discovery root for the Control Room Host Status repo survey.
1338
+ controlRoomRoot: 'CHROXY_CONTROL_ROOM_ROOT',
1339
+ // #5253: discovery root for the Control Room self-hosted runner survey.
1340
+ controlRoomRunnerRoot: 'CHROXY_RUNNER_ROOT',
1341
+ // #5260: toggle gh enrichment of the runner survey.
1342
+ controlRoomRunnerIncludeGithub: 'CHROXY_RUNNER_INCLUDE_GITHUB',
1343
+ controlRoomContainersIncludeStats: 'CHROXY_CONTAINERS_INCLUDE_STATS',
1344
+ // #5499: explicit repo-memory binary path for the Integrations survey.
1345
+ controlRoomRepoMemoryBin: 'CHROXY_REPO_MEMORY_BIN',
1346
+ logFormat: 'CHROXY_LOG_FORMAT',
1347
+ sandbox: 'CHROXY_SANDBOX',
1348
+ resultTimeoutMs: 'CHROXY_RESULT_TIMEOUT_MS',
1349
+ hardTimeoutMs: 'CHROXY_HARD_TIMEOUT_MS',
1350
+ streamStallTimeoutMs: 'CHROXY_STREAM_STALL_TIMEOUT_MS',
1351
+ backgroundShellHardQuiesceMs: 'CHROXY_BACKGROUND_SHELL_HARD_QUIESCE_MS',
1352
+ // #4601: JSON-encoded provider→ms map (e.g.
1353
+ // `CHROXY_PROVIDER_STREAM_STALL_TIMEOUT_MS='{"codex":900000}'`).
1354
+ // parseEnvValue dispatches on CONFIG_SCHEMA's `'object'` type and
1355
+ // runs JSON.parse, falling back to the raw string on parse error so
1356
+ // validateConfig can surface the eventual type mismatch.
1357
+ providerStreamStallTimeoutMs: 'CHROXY_PROVIDER_STREAM_STALL_TIMEOUT_MS',
1358
+ mcpToolCallTimeoutMs: 'CHROXY_MCP_TOOL_CALL_TIMEOUT_MS',
1359
+ // #4384 — canonical env var for the #4246 rename. Without this entry
1360
+ // the fallback was `key.toUpperCase()` (DANGEROUSLYSKIPPERMISSIONS,
1361
+ // no underscores) which is not what we document or what operators
1362
+ // would guess. `resolveSkipPermissions()` is still the single read
1363
+ // site that decides effective behaviour and surfaces the deprecation
1364
+ // warning for the legacy alias below.
1365
+ dangerouslySkipPermissions: 'CHROXY_DANGEROUSLY_SKIP_PERMISSIONS',
1366
+ // #4384 — legacy env-var alias mirroring the legacy config-file
1367
+ // key. mergeConfig is the dumb plumbing layer: it just lands the
1368
+ // value under the legacy `skipPermissions` config key so
1369
+ // resolveSkipPermissions sees it on the same code path as a
1370
+ // file-side legacy key (and therefore emits the same deprecation
1371
+ // warning). Operators should migrate to
1372
+ // `CHROXY_DANGEROUSLY_SKIP_PERMISSIONS`.
1373
+ skipPermissions: 'CHROXY_SKIP_PERMISSIONS',
1374
+ }
1375
+ return envMap[key] || key.toUpperCase()
1376
+ }
1377
+
1378
+ /**
1379
+ * Parse environment variable value to appropriate type.
1380
+ * @param {string} key - Config key
1381
+ * @param {string} value - Raw env var value
1382
+ * @returns {*} Parsed value
1383
+ */
1384
+ function parseEnvValue(key, value) {
1385
+ const expectedType = CONFIG_SCHEMA[key]
1386
+
1387
+ // #5419: union-typed keys (currently only `providers`: 'array|object').
1388
+ // JSON-looking values parse as JSON (the object form); anything else
1389
+ // keeps the legacy comma-split array semantics of CHROXY_PROVIDERS.
1390
+ if (expectedType === 'array|object') {
1391
+ const trimmed = value.trim()
1392
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
1393
+ try {
1394
+ return JSON.parse(trimmed)
1395
+ } catch {
1396
+ // A JSON-looking value with a typo must not silently degrade into
1397
+ // the comma-split legacy array — that would discard an intended
1398
+ // `providers.anthropicCompatible` block without a trace. Warn
1399
+ // loudly and still fall through so startup proceeds on the legacy
1400
+ // semantics. Deliberately no err.message / value echo: Node's
1401
+ // SyntaxError messages quote a snippet of the source, and a
1402
+ // pasted env value could carry a secret.
1403
+ log.warn(
1404
+ `${envKeyForConfig(key)} looks like JSON but failed to parse — falling back to the legacy comma-split list; fix the JSON if you meant the object form`,
1405
+ )
1406
+ }
1407
+ }
1408
+ return value.split(',').map(s => s.trim())
1409
+ }
1410
+
1411
+ if (expectedType === 'number') {
1412
+ const num = parseFloat(value)
1413
+ return isNaN(num) ? value : num
1414
+ }
1415
+
1416
+ if (expectedType === 'boolean') {
1417
+ return value === 'true' || value === '1'
1418
+ }
1419
+
1420
+ if (expectedType === 'array') {
1421
+ return value.split(',').map(s => s.trim())
1422
+ }
1423
+
1424
+ if (expectedType === 'object') {
1425
+ try {
1426
+ return JSON.parse(value)
1427
+ } catch {
1428
+ return value
1429
+ }
1430
+ }
1431
+
1432
+ return value
1433
+ }
1434
+
1435
+ /**
1436
+ * Resolve the effective `dangerouslySkipPermissions` value from a merged
1437
+ * config object (#4246).
1438
+ *
1439
+ * Precedence:
1440
+ * 1. `dangerouslySkipPermissions` (canonical, mirrors the CLI flag name)
1441
+ * 2. `skipPermissions` (legacy alias from #4209 — kept for one
1442
+ * deprecation window; emits a warning that the resolver returns so
1443
+ * the caller can surface it once at boot).
1444
+ *
1445
+ * The resolver does NOT log directly — it returns a `deprecationWarning`
1446
+ * string so the caller decides when/where to surface it (server-cli logs
1447
+ * it once at startup; tests assert on the value). When the canonical key
1448
+ * is set the legacy key is ignored as a value-source but its mere
1449
+ * presence still triggers the warning (to nudge cleanup of stale
1450
+ * duplicates).
1451
+ *
1452
+ * @param {object | null | undefined} config
1453
+ * @returns {{
1454
+ * enabled: boolean,
1455
+ * source: 'dangerouslySkipPermissions' | 'skipPermissions' | null,
1456
+ * deprecationWarning: string | null,
1457
+ * }}
1458
+ */
1459
+ export function resolveSkipPermissions(config) {
1460
+ const c = config || {}
1461
+ const canonical = c.dangerouslySkipPermissions
1462
+ const legacy = c.skipPermissions
1463
+ const legacyPresent = Object.prototype.hasOwnProperty.call(c, 'skipPermissions')
1464
+
1465
+ const deprecationWarning = legacyPresent
1466
+ ? "config key 'skipPermissions' is deprecated — rename it to 'dangerouslySkipPermissions' to match the CLI flag name. Both keys are honoured for now; the legacy key will be removed in a future release."
1467
+ : null
1468
+
1469
+ if (typeof canonical === 'boolean') {
1470
+ return {
1471
+ enabled: canonical,
1472
+ source: 'dangerouslySkipPermissions',
1473
+ // Even when the canonical key wins, surface the warning if the
1474
+ // legacy key is also set — operators should clean up the duplicate.
1475
+ deprecationWarning,
1476
+ }
1477
+ }
1478
+
1479
+ if (typeof legacy === 'boolean') {
1480
+ return {
1481
+ enabled: legacy,
1482
+ source: 'skipPermissions',
1483
+ deprecationWarning,
1484
+ }
1485
+ }
1486
+
1487
+ return {
1488
+ enabled: false,
1489
+ source: null,
1490
+ deprecationWarning: null,
1491
+ }
1492
+ }
1493
+
1494
+ /**
1495
+ * #5144: resolve the selected environment backend from a merged config object.
1496
+ *
1497
+ * Returns 'docker' for an absent, malformed, or unrecognised
1498
+ * `environments.backend` (validateConfig already surfaces the warning), so the
1499
+ * wiring layer never crashes on a typo and the default single-node path is
1500
+ * preserved. Pure — no side effects, no logging.
1501
+ *
1502
+ * @param {object|null|undefined} config - Merged config
1503
+ * @returns {'docker'|'k8s'|'rancher'}
1504
+ */
1505
+ export function resolveEnvironmentBackend(config) {
1506
+ const selected = config?.environments?.backend
1507
+ if (typeof selected === 'string' && ENVIRONMENT_BACKENDS.has(selected)) {
1508
+ return selected
1509
+ }
1510
+ return 'docker'
1511
+ }
1512
+
1513
+ /**
1514
+ * #5144: resolve a Rancher bearer token from a secret-friendly source.
1515
+ *
1516
+ * Precedence (highest first):
1517
+ * 1. `tokenEnv` — name of an env var holding the token (e.g. RANCHER_TOKEN).
1518
+ * Keeps the secret out of the on-disk config file.
1519
+ * 2. `tokenFile` — path to a file whose trimmed contents are the token
1520
+ * (e.g. a mounted secret).
1521
+ * 3. `token` — inline token (discouraged but supported for parity with
1522
+ * validateRancherOptions).
1523
+ *
1524
+ * The resolved value is never logged. Returns `undefined` when none resolve so
1525
+ * the caller / RancherBackend constructor produces the canonical "token must be
1526
+ * a non-empty bearer token string" error.
1527
+ *
1528
+ * @param {object} rancher - The `environments.rancher` block
1529
+ * @returns {string|undefined}
1530
+ */
1531
+ export function resolveRancherToken(rancher = {}) {
1532
+ if (typeof rancher.tokenEnv === 'string' && rancher.tokenEnv.length > 0) {
1533
+ const fromEnv = process.env[rancher.tokenEnv]
1534
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv
1535
+ }
1536
+ if (typeof rancher.tokenFile === 'string' && rancher.tokenFile.length > 0) {
1537
+ try {
1538
+ const fromFile = readFileSync(rancher.tokenFile, 'utf-8').trim()
1539
+ if (fromFile.length > 0) return fromFile
1540
+ } catch {
1541
+ // Fall through to inline token / undefined. Do not log the path's
1542
+ // contents; the eventual "token required" error is enough signal.
1543
+ }
1544
+ }
1545
+ if (typeof rancher.token === 'string' && rancher.token.length > 0) return rancher.token
1546
+ return undefined
1547
+ }
1548
+
1549
+ /**
1550
+ * #5144: construct the environment backend selected by config.
1551
+ *
1552
+ * - 'docker' (default): `new DockerBackend({ _execFile })` — unchanged behaviour.
1553
+ * - 'k8s' : `new K8sBackend({ ...environments.k8s })`.
1554
+ * - 'rancher' : `new RancherBackend({ ...environments.k8s, ...rancher })`
1555
+ * with the token resolved from a secret-friendly source.
1556
+ *
1557
+ * Backend modules are imported lazily so loading config never eagerly pulls in
1558
+ * `@kubernetes/client-node` (only the K8s/Rancher paths need it). The selected
1559
+ * backend's construction validates its own options and throws on a malformed
1560
+ * block — the caller (server-cli) surfaces that as a fatal startup error.
1561
+ *
1562
+ * @param {object} config - Merged config
1563
+ * @param {object} [deps] - Injection seam for testing
1564
+ * @param {Function} [deps._execFile] - Forwarded to DockerBackend
1565
+ * @param {Function} [deps._loadBackends] - Override the lazy module loader
1566
+ * (returns `{ DockerBackend, K8sBackend, RancherBackend }`). Lets unit tests
1567
+ * assert which class is instantiated with which options without importing the
1568
+ * kube SDK.
1569
+ * @returns {Promise<{ backend: object, type: 'docker'|'k8s'|'rancher' }>}
1570
+ */
1571
+ export async function buildEnvironmentBackend(config, { _execFile, _loadBackends } = {}) {
1572
+ const type = resolveEnvironmentBackend(config)
1573
+ const envs = config?.environments || {}
1574
+
1575
+ const loadBackends = _loadBackends || (async () => {
1576
+ if (type === 'docker') {
1577
+ const { DockerBackend } = await import('./environments/backends/docker.js')
1578
+ return { DockerBackend }
1579
+ }
1580
+ if (type === 'k8s') {
1581
+ const { K8sBackend } = await import('./environments/backends/k8s.js')
1582
+ return { K8sBackend }
1583
+ }
1584
+ const { RancherBackend } = await import('./environments/backends/rancher.js')
1585
+ return { RancherBackend }
1586
+ })
1587
+
1588
+ const mods = await loadBackends()
1589
+
1590
+ if (type === 'k8s') {
1591
+ const k8s = (envs.k8s && typeof envs.k8s === 'object' && !Array.isArray(envs.k8s)) ? envs.k8s : {}
1592
+ const backend = new mods.K8sBackend({
1593
+ namespace: k8s.namespace,
1594
+ inCluster: k8s.inCluster,
1595
+ kubeconfigPath: k8s.kubeconfigPath,
1596
+ sidecarImage: k8s.sidecarImage,
1597
+ imagePullPolicy: k8s.imagePullPolicy,
1598
+ connectMode: k8s.connectMode,
1599
+ // Per-tenant namespace-level guardrails (#5142). Both opt-in; the backend
1600
+ // validates the quantity strings and throws on a malformed block.
1601
+ namespaceQuota: k8s.namespaceQuota,
1602
+ namespaceLimitRange: k8s.namespaceLimitRange,
1603
+ })
1604
+ return { backend, type }
1605
+ }
1606
+
1607
+ if (type === 'rancher') {
1608
+ const k8s = (envs.k8s && typeof envs.k8s === 'object' && !Array.isArray(envs.k8s)) ? envs.k8s : {}
1609
+ const rancher = (envs.rancher && typeof envs.rancher === 'object' && !Array.isArray(envs.rancher)) ? envs.rancher : {}
1610
+ const token = resolveRancherToken(rancher)
1611
+ const backend = new mods.RancherBackend({
1612
+ // K8s connection/runtime knobs shared with the plain K8s path.
1613
+ namespace: k8s.namespace,
1614
+ inCluster: k8s.inCluster,
1615
+ kubeconfigPath: k8s.kubeconfigPath,
1616
+ sidecarImage: k8s.sidecarImage,
1617
+ imagePullPolicy: k8s.imagePullPolicy,
1618
+ connectMode: k8s.connectMode,
1619
+ // Per-tenant namespace-level guardrails (#5142), shared with the plain K8s path.
1620
+ namespaceQuota: k8s.namespaceQuota,
1621
+ namespaceLimitRange: k8s.namespaceLimitRange,
1622
+ // Rancher connection block. Token is resolved from a secret-friendly
1623
+ // source and never logged.
1624
+ rancherUrl: rancher.rancherUrl,
1625
+ clusterId: rancher.clusterId,
1626
+ token,
1627
+ caData: rancher.caData,
1628
+ skipTLSVerify: rancher.skipTLSVerify,
1629
+ defaultProjectId: rancher.defaultProjectId,
1630
+ })
1631
+ return { backend, type }
1632
+ }
1633
+
1634
+ const backend = new mods.DockerBackend({ _execFile })
1635
+ return { backend, type }
1636
+ }
1637
+
1638
+ const DEFAULT_CONFIG_PATH = join(homedir(), '.chroxy', 'config.json')
1639
+
1640
+ /**
1641
+ * Read the repos array from a config file.
1642
+ * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1643
+ * @returns {Array<{ path: string, name?: string }>} Repos array, or [] if missing/invalid.
1644
+ */
1645
+ export function readReposFromConfig(configPath = DEFAULT_CONFIG_PATH) {
1646
+ try {
1647
+ if (!existsSync(configPath)) return []
1648
+ const raw = JSON.parse(readFileSync(configPath, 'utf-8'))
1649
+ return Array.isArray(raw.repos) ? raw.repos : []
1650
+ } catch {
1651
+ return []
1652
+ }
1653
+ }
1654
+
1655
+ /**
1656
+ * Write the repos array to a config file, preserving other fields.
1657
+ * @param {Array<{ path: string, name?: string }>} repos - Repos array to write.
1658
+ * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1659
+ */
1660
+ export function writeReposToConfig(repos, configPath = DEFAULT_CONFIG_PATH) {
1661
+ let existing = {}
1662
+ try {
1663
+ if (existsSync(configPath)) {
1664
+ existing = JSON.parse(readFileSync(configPath, 'utf-8'))
1665
+ }
1666
+ } catch {
1667
+ // Start fresh if parse fails
1668
+ }
1669
+ existing.repos = repos
1670
+ const dir = dirname(configPath)
1671
+ mkdirSync(dir, { recursive: true })
1672
+ writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
1673
+ }
1674
+
1675
+ /**
1676
+ * Write (or clear) the daemon-side session-preset override for a repo path
1677
+ * (#5553). The override lives on the matching `repos[]` entry's `sessionPreset`
1678
+ * key. When `preset` is null the key is removed (revert to repo-local file /
1679
+ * no preset). When the repo path has no `repos[]` entry yet, one is created so
1680
+ * the operator can configure an override for a repo that isn't otherwise
1681
+ * registered. Other config fields and repo entries are preserved.
1682
+ *
1683
+ * @param {string} repoPath - The repo path to key the override by.
1684
+ * @param {object|null} preset - The preset object ({ preamble?, seed?, enabled? }) or null to clear.
1685
+ * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1686
+ */
1687
+ export function writeSessionPresetOverrideToConfig(repoPath, preset, configPath = DEFAULT_CONFIG_PATH) {
1688
+ let existing = {}
1689
+ try {
1690
+ if (existsSync(configPath)) {
1691
+ existing = JSON.parse(readFileSync(configPath, 'utf-8'))
1692
+ }
1693
+ } catch {
1694
+ // Start fresh if parse fails
1695
+ }
1696
+ if (!existing || typeof existing !== 'object') existing = {}
1697
+ if (!Array.isArray(existing.repos)) existing.repos = []
1698
+
1699
+ const idx = existing.repos.findIndex(
1700
+ r => r && typeof r === 'object' && typeof r.path === 'string' && r.path === repoPath,
1701
+ )
1702
+ if (idx === -1) {
1703
+ if (preset === null) {
1704
+ // Nothing to clear and no entry exists — no-op write avoided.
1705
+ return
1706
+ }
1707
+ existing.repos.push({ path: repoPath, sessionPreset: preset })
1708
+ } else {
1709
+ const entry = existing.repos[idx]
1710
+ if (preset === null) {
1711
+ delete entry.sessionPreset
1712
+ } else {
1713
+ entry.sessionPreset = preset
1714
+ }
1715
+ }
1716
+
1717
+ const dir = dirname(configPath)
1718
+ mkdirSync(dir, { recursive: true })
1719
+ writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
1720
+ }
1721
+
1722
+ /**
1723
+ * Read the Control Room discovery root from a config file (#5172).
1724
+ * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1725
+ * @returns {string|undefined} The configured root, or undefined if missing/invalid.
1726
+ */
1727
+ export function readControlRoomRootFromConfig(configPath = DEFAULT_CONFIG_PATH) {
1728
+ try {
1729
+ if (!existsSync(configPath)) return undefined
1730
+ const raw = JSON.parse(readFileSync(configPath, 'utf-8'))
1731
+ return typeof raw.controlRoomRoot === 'string' ? raw.controlRoomRoot : undefined
1732
+ } catch {
1733
+ return undefined
1734
+ }
1735
+ }
1736
+
1737
+ /**
1738
+ * Write the Control Room discovery root to a config file, preserving other
1739
+ * fields (#5172).
1740
+ * @param {string} root - Absolute path to the discovery root.
1741
+ * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1742
+ */
1743
+ export function writeControlRoomRootToConfig(root, configPath = DEFAULT_CONFIG_PATH) {
1744
+ let existing = {}
1745
+ try {
1746
+ if (existsSync(configPath)) {
1747
+ existing = JSON.parse(readFileSync(configPath, 'utf-8'))
1748
+ }
1749
+ } catch {
1750
+ // Start fresh if parse fails
1751
+ }
1752
+ existing.controlRoomRoot = root
1753
+ const dir = dirname(configPath)
1754
+ mkdirSync(dir, { recursive: true })
1755
+ writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
1756
+ }
1757
+