@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
package/src/config.js CHANGED
@@ -8,9 +8,9 @@
8
8
  * 4. Defaults
9
9
  */
10
10
 
11
- import { readFileSync, existsSync, mkdirSync } from 'fs'
12
- import { join, dirname } from 'path'
13
- import { homedir } from 'os'
11
+ import { readFileSync, existsSync, mkdirSync, copyFileSync, constants as fsConstants } from 'fs'
12
+ import { createHash } from 'crypto'
13
+ import { dirname } from 'path'
14
14
  import { writeFileRestricted } from './platform.js'
15
15
  import { parseDuration } from './duration.js'
16
16
  import { createLogger } from './logger.js'
@@ -18,6 +18,19 @@ import { createLogger } from './logger.js'
18
18
  // deliberately a dependency-free module so importing it here never pulls
19
19
  // the BYOK/SDK machinery into the config-load path.
20
20
  import { validateProvidersConfigBlock } from './anthropic-compatible-config.js'
21
+ // #7319: pure validation helpers for `providers.acp` — same dependency-free
22
+ // rationale (no spawn/ACP-SDK machinery in the config-load path). Called
23
+ // directly here (not from validateProvidersConfigBlock) to avoid a circular
24
+ // import — acp-config.js already imports RESERVED_PROVIDER_IDS from
25
+ // anthropic-compatible-config.js.
26
+ import { validateAcpProviders } from './acp-config.js'
27
+ // #6764: default cheap model + timeout for the one-shot semantic-title call.
28
+ // Imported from the pure title module (no provider/SDK deps) so config load stays
29
+ // lightweight.
30
+ import { DEFAULT_SEMANTIC_TITLE_MODEL, DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS } from './session-title.js'
31
+ import { configPath } from './config-dir.js'
32
+ import { SESSION_ARCHIVE_MAX_ENTRIES } from './session-archive-limits.js'
33
+ import { validateAgentConnections } from './agent-connections.js'
21
34
 
22
35
  const log = createLogger('config')
23
36
 
@@ -77,6 +90,10 @@ const CONFIG_SCHEMA = {
77
90
  // name an env var (`apiKeyEnv`) or a ~/.chroxy/credentials.json
78
91
  // field (`credentialsKey`).
79
92
  providers: 'array|object',
93
+ // Explicit host-scoped agent access routes. Entries contain only stable
94
+ // identifiers and credential references; raw credentials are rejected by
95
+ // the connection validator and remain in env/native/vendor stores.
96
+ agentConnections: 'array',
80
97
  // #5547: optional override for the one-shot session summarizer (the sidebar
81
98
  // "Summarize & start new session" action). `{ provider?: string, model?:
82
99
  // string }` — when set, the summarizer uses this (typically cheaper) model
@@ -110,6 +127,13 @@ const CONFIG_SCHEMA = {
110
127
  // CHROXY_ENABLE_IDE=1 env override) reveals the IDE navigation/editing features;
111
128
  // off by default so it never risks the core offering. See isIdeFeatureEnabled().
112
129
  features: 'object',
130
+ // #6691 (E-4): the orchestration engine's config block ({ roles, bash, diff,
131
+ // maxParallelWorkers, ... } — consumed by OrchestrationManager via
132
+ // buildOrchestrationManager). Declared here so a configured block doesn't
133
+ // trip the misleading "Unknown config key ... (will be ignored)" warning —
134
+ // mergeConfig passes unknown file keys through regardless, but the warning
135
+ // suggested otherwise.
136
+ orchestration: 'object',
113
137
  externalUrl: 'string',
114
138
  repos: 'array',
115
139
  // #5172 (Control Room v2): filesystem root the Host Status survey scans
@@ -138,6 +162,10 @@ const CONFIG_SCHEMA = {
138
162
  // runs with a GUI/launchd PATH that misses npm globals. Mirrored by the
139
163
  // CHROXY_REPO_MEMORY_BIN env var.
140
164
  controlRoomRepoMemoryBin: 'string',
165
+ // #8609: explicit path of the codex client the codex provider launches
166
+ // (instead of the first `codex` on PATH). Mirrored by CHROXY_CODEX_BIN, which
167
+ // is what CodexSession.resolvedBinary reads — see applyCodexBinaryConfig.
168
+ codexBinary: 'string',
141
169
  maxSessions: 'number',
142
170
  maxHistory: 'number',
143
171
  maxMessages: 'number',
@@ -158,11 +186,39 @@ const CONFIG_SCHEMA = {
158
186
  // discord-credentials.js. Documented in CONFIG.md +
159
187
  // docs/guides/discord-notifications.md.
160
188
  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.
189
+ // #5158: worktree garbage-collection. `{ autoReap?: boolean, reapIntervalMs?:
190
+ // number, maxLockAgeMs?: number }` — when `autoReap` is true, the server
191
+ // reclaims orphaned, dead-pid-locked agent worktrees on startup and then
192
+ // every `reapIntervalMs` (clean trees only, never --force); `maxLockAgeMs` is
193
+ // the absolute-age fallback for the PID-liveness check (0 disables it).
194
+ // Defaults to off; the `chroxy worktree gc` CLI is always available for
195
+ // manual/dry-run use.
165
196
  worktreeGc: 'object',
197
+ // #7606: orphaned-child reaper. `{ enabled?: boolean, sweepIntervalMs?:
198
+ // number, minAgeMs?: number }` — the daemon periodically SIGKILLs processes
199
+ // that are reparented to pid 1, owned by this uid, older than `minAgeMs`
200
+ // (default 10 min) and whose cwd is inside chroxy's own session-worktree
201
+ // root — work a dead session left behind. `enabled` defaults ON; sweeps
202
+ // every `sweepIntervalMs` (default 5 min). POSIX only.
203
+ orphanReap: 'object',
204
+ // Session archive: the chroxy-held history of a session that leaves the live
205
+ // set (closed, idle-timed-out, stale at boot, dismissed/expired failed
206
+ // restore) is kept as a compressed, read-only record so a Codex / Gemini /
207
+ // BYOK session's content is not lost. `{ enabled?: boolean, maxEntries?:
208
+ // number, maxAgeDays?: number, maxMegabytes?: number }` — defaults ON, 100
209
+ // entries, 30 days, 256 MiB; the oldest records are deleted first.
210
+ sessionArchive: 'object',
211
+ // #7424: the session CI-completion watcher. `{ watch?: boolean, wakeAgent?:
212
+ // boolean, intervalMs?: number, discoveryIntervalMs?: number,
213
+ // maxSurveysPerTick?: number }` (#7436 added the per-tick cap). `watch`
214
+ // defaults ON — the daemon periodically surveys each session's PR through the
215
+ // user's own `gh` and, when a run settles, notifies (`ci_complete`) and wakes
216
+ // the agent with one daemon-authored line: typed into a claude-tui prompt, or
217
+ // delivered as a user turn (queued when busy) to a provider that declares
218
+ // `capabilities.daemonTurnInput` — claude-sdk included (#8301). Set
219
+ // `watch: false` on a host that should make no background GitHub calls;
220
+ // `wakeAgent: false` keeps the notification but never wakes a session.
221
+ sessionCi: 'object',
166
222
  sandbox: 'object',
167
223
  // Optional allowlist of absolute directory paths that sessions may use
168
224
  // as their working directory. When set (non-empty array), session
@@ -183,7 +239,8 @@ const CONFIG_SCHEMA = {
183
239
  // #5985 (epic #5982): gate for the embedded user-shell terminal — a
184
240
  // `user-shell` session spawns the operator's `$SHELL` (arbitrary code
185
241
  // execution on the dev machine, reachable through the tunnel). Nested object
186
- // `{ enabled: boolean }`. Defaults to undefined/false so fresh installs are
242
+ // `{ enabled?: boolean, requireApproval?: boolean }` (#6277 added the
243
+ // host-local approval gate). Defaults to undefined/false so fresh installs are
187
244
  // secure-by-default: creating a `user-shell` session is rejected with
188
245
  // USER_SHELL_DISABLED unless `userShell.enabled === true`. Enabling is a
189
246
  // deliberate edit on the dev machine (physical-access proxy for confirmation),
@@ -201,7 +258,7 @@ const CONFIG_SCHEMA = {
201
258
  // the 2026-04-11 audit Adversary A7 fix to close the "register any
202
259
  // attacker-controlled image and run it" attack path.
203
260
  allowedDockerImages: 'array',
204
- // Per-session regex source string used by `shouldSkipEvaluator` to extend
261
+ // Per-session regex source string used by `shouldSkipEvaluatorAsync` to extend
205
262
  // the default continuation-pattern skip list. Wrapped in try/catch when
206
263
  // compiled — malformed sources are logged and ignored, the default
207
264
  // pattern still applies. Documented in CONFIG.md. Added in #3187.
@@ -238,6 +295,18 @@ const CONFIG_SCHEMA = {
238
295
  // implicit.
239
296
  // Documented in CONFIG.md.
240
297
  trustMismatchMode: 'string',
298
+ // #6858: opt-in provenance verification for spawned provider binaries.
299
+ // Nested object:
300
+ // binaryProvenance.mode 'off' (default) | 'warn' | 'block' —
301
+ // SHA-256 pin ledger. Pins each provider binary on first sight; a changed
302
+ // hash re-gates (warn surfaces + allows, block refuses the spawn).
303
+ // binaryProvenance.signatureGate boolean (default false) — macOS `spctl`
304
+ // signature/notarization gate; hard-blocks un-notarized builds when on.
305
+ // Both OFF by default so P1 (#6708) behaviour is unchanged. Env overrides:
306
+ // CHROXY_BINARY_PROVENANCE (off|warn|block), CHROXY_BINARY_SIGNATURE_GATE (1|0).
307
+ // See resolveBinaryProvenanceMode() / isBinarySignatureGateEnabled() and
308
+ // docs/security/spawned-binary-provenance.md.
309
+ binaryProvenance: 'object',
241
310
  // #3749 / #3884 / #3899: SOFT-warning inactivity timeout (ms). When no
242
311
  // SDK / CLI event fires within this window, the server emits an
243
312
  // `inactivity_warning` event (and push notification) — the session
@@ -289,6 +358,132 @@ const CONFIG_SCHEMA = {
289
358
  mcpToolCallTimeoutMs: 'number',
290
359
  }
291
360
 
361
+ /**
362
+ * #7083 — config options whose value is a millisecond duration, and which therefore
363
+ * must never be fractional: they feed `setTimeout` AND the wire, where the protocol
364
+ * schemas require `.int()`.
365
+ *
366
+ * An EXPLICIT allowlist rather than `key.endsWith('Ms')`, even though the suffix
367
+ * happens to select exactly these six today. The `'number'` branch of `parseEnvValue`
368
+ * is shared with `costBudget`, which is USD and legitimately fractional — so a
369
+ * convention-driven predicate would be correct by accident and give a future reviewer
370
+ * nothing to check against. `tests/config-duration-coercion.test.js` asserts this list
371
+ * equals every `*Ms: 'number'` key in CONFIG_SCHEMA, so adding a duration option
372
+ * without listing it here fails CI rather than silently opting out.
373
+ *
374
+ * Deliberately NOT covered: nested ms options under `'object'`-typed keys
375
+ * (`worktreeGc.*`, `notifications.discord.*`, `orchestration.turnTimeoutMs`,
376
+ * `summarize.titleTimeoutMs`). Those do not reach the wire, and covering them needs
377
+ * per-block handling — a recursive walk of the merged object would destroy
378
+ * `providers.*.pricing.input` and `billing.monthlyCreditBudgetUsd`, which are
379
+ * legitimately fractional.
380
+ *
381
+ * `providerStreamStallTimeoutMs` IS covered (see DURATION_MS_MAP_CONFIG_KEYS below) —
382
+ * an earlier revision of this comment wrongly lumped it in with the exclusions.
383
+ */
384
+ export const DURATION_MS_CONFIG_KEYS = Object.freeze([
385
+ 'terminalDownGraceMs',
386
+ 'resultTimeoutMs',
387
+ 'hardTimeoutMs',
388
+ 'streamStallTimeoutMs',
389
+ 'backgroundShellHardQuiesceMs',
390
+ 'mcpToolCallTimeoutMs',
391
+ ])
392
+ const DURATION_MS_KEY_SET = new Set(DURATION_MS_CONFIG_KEYS)
393
+
394
+ /**
395
+ * #7083 — config options whose value is a MAP of `<id> -> duration-ms`.
396
+ *
397
+ * `providerStreamStallTimeoutMs.<id>` is not a cosmetic omission: it OUTRANKS the
398
+ * coerced global (session-manager.js `_sanitizeProviderTimeoutMap` keeps it verbatim
399
+ * because `isOperatorTimeoutInRange` checks finite/positive/<=24h but never
400
+ * integrality), flows into `base-session.js`, and is emitted as `result.duration` by
401
+ * `sdk-session.js`. Measured: a fractional per-provider entry survives `mergeConfig`
402
+ * and draws ZERO validateConfig warnings.
403
+ *
404
+ * That is the exact field `stream.ts` records as blocked on THIS issue before `.int()`
405
+ * can be added (#7095). Coercing only the flat keys would have left the per-provider
406
+ * override fractional, so #7095 would then make a config that is legal today emit a
407
+ * wire-illegal frame.
408
+ *
409
+ * An explicit list of MAP-shaped keys, not a recursive walk — the walk is what would
410
+ * destroy `providers.*.pricing.input` and `billing.monthlyCreditBudgetUsd`.
411
+ */
412
+ export const DURATION_MS_MAP_CONFIG_KEYS = Object.freeze(['providerStreamStallTimeoutMs'])
413
+ const DURATION_MS_MAP_KEY_SET = new Set(DURATION_MS_MAP_CONFIG_KEYS)
414
+
415
+ /**
416
+ * #7083 — coerce a duration-ms config value to a whole number of milliseconds.
417
+ *
418
+ * Applied at the single merge site so it covers BOTH input paths: an env var (parsed
419
+ * with `parseFloat`) and a `~/.chroxy/config.json` value, which is JSON and arrives as
420
+ * a fractional number with no parse step to hook. Fixing only the env parser would
421
+ * leave the config-file case — the one named in #7083 — fully broken.
422
+ *
423
+ * `Math.trunc` — truncate toward zero. Chosen for two reasons, not for convention:
424
+ * it cannot round an out-of-range value UP into legality (`Math.round(29999.5)` would
425
+ * become 30000 and silently suppress a below-minimum warning), and because every
426
+ * documented minimum is itself an integer, truncation can never push a legal value
427
+ * below its minimum. It also matches the truncating `parseInt` used for integer CLI
428
+ * flags in `cli/shared.js` — note this module's own env parser uses `parseFloat`, which
429
+ * is precisely why the fractional value reaches here in the first place.
430
+ *
431
+ * The zero guard is load-bearing. `0` is the documented "disabled" sentinel for
432
+ * `streamStallTimeoutMs` and `backgroundShellHardQuiesceMs`, so a naive
433
+ * `Math.trunc(0.4) === 0` would silently switch stall detection OFF — turning an
434
+ * illegal value that warns today into a feature that is quietly disabled. Sub-1
435
+ * magnitudes go to ±1 instead, which is never the sentinel.
436
+ *
437
+ * Precise about what ±1 then means: for the five range-checked keys it is still below
438
+ * the documented minimum, so validateConfig still warns and nothing is silently
439
+ * accepted. `terminalDownGraceMs` is the exception — it has NO range validation at all,
440
+ * so `0.4` becomes a legal, unwarned `1`. That is an invented value, and it is
441
+ * tolerable only because that key never reaches the wire; it is not a general property
442
+ * of the guard, so do not extend the guard to a wire-bound key on that basis.
443
+ *
444
+ * Non-numbers pass through untouched so `parseEnvValue`'s NaN-means-keep-the-string
445
+ * contract survives, and non-finite values pass through so the existing Infinity
446
+ * semantics in the range checks are unchanged.
447
+ *
448
+ * @param {string} key
449
+ * @param {unknown} value
450
+ * @returns {unknown} the coerced value, or `value` unchanged
451
+ */
452
+ export function coerceDurationConfigValue(key, value) {
453
+ if (DURATION_MS_MAP_KEY_SET.has(key)) return coerceDurationMap(key, value)
454
+ if (!DURATION_MS_KEY_SET.has(key)) return value
455
+ return coerceOneDuration(key, value)
456
+ }
457
+
458
+ /** @private — coerce a single duration-ms value. */
459
+ function coerceOneDuration(label, value) {
460
+ if (typeof value !== 'number' || !Number.isFinite(value)) return value
461
+ if (Number.isInteger(value)) return value
462
+ const truncated = Math.trunc(value)
463
+ const coerced = truncated === 0 ? Math.sign(value) : truncated
464
+ log.warn(`Config '${label}' must be a whole number of milliseconds — coercing ${value} to ${coerced}`)
465
+ return coerced
466
+ }
467
+
468
+ /**
469
+ * @private — coerce each value of an `<id> -> ms` map, ONE level deep.
470
+ *
471
+ * Deliberately not recursive: depth is what turns this from a targeted fix into the
472
+ * change that truncates `providers.*.pricing.input`. Non-object inputs pass through so
473
+ * the existing "wrong type" validateConfig warning still fires on the raw value.
474
+ */
475
+ function coerceDurationMap(key, value) {
476
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value
477
+ let changed = false
478
+ const out = {}
479
+ for (const [id, entry] of Object.entries(value)) {
480
+ const coerced = coerceOneDuration(`${key}.${id}`, entry)
481
+ if (coerced !== entry) changed = true
482
+ out[id] = coerced
483
+ }
484
+ return changed ? out : value
485
+ }
486
+
292
487
  /**
293
488
  * Config keys that should be masked in verbose output and sanitized logs.
294
489
  * `pushToken` was a dead entry — it is never a CONFIG_SCHEMA key; push tokens
@@ -356,17 +551,33 @@ function warnUnknownKeys(obj, knownSet, prefix, warnings, supportedKeys = knownS
356
551
  // `workspace` sub-block (#4556); billing-budget.js + billing-canary (egressCheck
357
552
  // / datacenterPrefixes via server-cli); worktree-reaper.js; rancher.js (the
358
553
  // RancherBackend ctor) + resolveRancherToken (tokenEnv / tokenFile).
359
- const K8S_SUPPORTED_KEYS = new Set([
554
+ //
555
+ // #7449: these are EXPORTED solely so the doc gate
556
+ // (tests/config-supported-keys-docs.test.js) can compare CONFIG.md's rosters
557
+ // against the producer itself rather than a hand-copied expectation. Nothing
558
+ // in src/ imports them across module boundaries — but a re-parse of this file
559
+ // as text would be a second implementation of the roster, and that copy is
560
+ // what drifts.
561
+ export const K8S_SUPPORTED_KEYS = new Set([
360
562
  'namespace', 'inCluster', 'kubeconfigPath', 'sidecarImage', 'imagePullPolicy',
361
563
  'connectMode', 'namespaceQuota', 'namespaceLimitRange', 'workspace',
362
564
  ])
363
- const BILLING_SUPPORTED_KEYS = new Set([
565
+ export const BILLING_SUPPORTED_KEYS = new Set([
364
566
  'creditTier', 'monthlyCreditBudgetUsd', 'budgetWarningPercent', 'egressCheck', 'datacenterPrefixes',
365
567
  ])
366
- const WORKTREE_GC_SUPPORTED_KEYS = new Set([
568
+ export const WORKTREE_GC_SUPPORTED_KEYS = new Set([
367
569
  'autoReap', 'reapIntervalMs', 'maxLockAgeMs',
368
570
  ])
369
- const RANCHER_SUPPORTED_KEYS = new Set([
571
+ export const ORPHAN_REAP_SUPPORTED_KEYS = new Set([
572
+ 'enabled', 'sweepIntervalMs', 'minAgeMs',
573
+ ])
574
+ export const SESSION_ARCHIVE_SUPPORTED_KEYS = new Set([
575
+ 'enabled', 'maxEntries', 'maxAgeDays', 'maxMegabytes',
576
+ ])
577
+ export const SESSION_CI_SUPPORTED_KEYS = new Set([
578
+ 'watch', 'wakeAgent', 'intervalMs', 'discoveryIntervalMs', 'maxSurveysPerTick',
579
+ ])
580
+ export const RANCHER_SUPPORTED_KEYS = new Set([
370
581
  'rancherUrl', 'clusterId', 'token', 'tokenEnv', 'tokenFile', 'caData', 'skipTLSVerify', 'defaultProjectId',
371
582
  ])
372
583
 
@@ -533,8 +744,8 @@ const MAX_DISCORD_COLOR = 16777215
533
744
  // `{ ...config.notifications.discord }` spread into the sink) surfaces instead of
534
745
  // silently no-op'ing / failing the sink closed. Keep in sync with the per-key
535
746
  // 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',
747
+ export const DISCORD_SUPPORTED_KEYS = new Set([
748
+ 'botName', 'billingAlerts', 'ciAlerts', 'defaultColor', 'permissionColor', 'errorColor',
538
749
  'colors', 'updateThrottleMs', 'heartbeatIntervalMs', 'pruneAfterMs',
539
750
  // #5676 status-watchdog tunables — the sink reads these from the config spread
540
751
  // (discord-webhook-sink.js: staleAfterMs/offlineAfterMs, default 10m/30m), so
@@ -618,7 +829,7 @@ function validateBillingBlock(billing, warnings) {
618
829
  warnUnknownKeys(billing, BILLING_SUPPORTED_KEYS, 'billing', warnings)
619
830
  }
620
831
 
621
- const USER_SHELL_SUPPORTED_KEYS = new Set(['enabled', 'requireApproval'])
832
+ export const USER_SHELL_SUPPORTED_KEYS = new Set(['enabled', 'requireApproval'])
622
833
 
623
834
  // #5985 (epic #5982): validate the `userShell` block. Only `enabled` (boolean)
624
835
  // today; the security primitives (primary-token gate, audit, isolation) land in
@@ -650,6 +861,20 @@ function validateUserShellBlock(userShell, warnings) {
650
861
  warnUnknownKeys(userShell, USER_SHELL_SUPPORTED_KEYS, 'userShell', warnings)
651
862
  }
652
863
 
864
+ /**
865
+ * #8609: CodexSession.resolvedBinary is a static getter with no config handle,
866
+ * so the config-file `codexBinary` is published to CHROXY_CODEX_BIN once at
867
+ * startup. An env var already set wins (it is the same key merged by
868
+ * mergeConfig, so a file value only matters when the env is unset).
869
+ */
870
+ // Needed beyond the env→config merge: that merge only reads the env, but the static
871
+ // resolvedBinary getter has no config handle, so a file value must be pushed to the env.
872
+ export function applyCodexBinaryConfig(config, env = process.env) {
873
+ const configured = typeof config?.codexBinary === 'string' ? config.codexBinary.trim() : ''
874
+ const current = typeof env.CHROXY_CODEX_BIN === 'string' ? env.CHROXY_CODEX_BIN.trim() : ''
875
+ if (configured && !current) env.CHROXY_CODEX_BIN = configured
876
+ }
877
+
653
878
  // #5985: single source of truth for "may a user-shell session be created?".
654
879
  // Fail-closed — anything other than an explicit `userShell.enabled === true` is
655
880
  // disabled. Used by SessionManager.createSession (the authoritative gate).
@@ -673,6 +898,113 @@ export function isIdeFeatureEnabled(config) {
673
898
  return config?.features?.ide === true
674
899
  }
675
900
 
901
+ // #6691 — the opt-in orchestration/delegation harness ("committee"). Fail-closed
902
+ // like isIdeFeatureEnabled: only an explicit env=1 or `features.orchestration
903
+ // === true` enables it. Gates the WS handler surface AND the `orchestration`
904
+ // capability advertised in auth_ok, so a client only reveals the Runs surface
905
+ // when the operator has opted in.
906
+ export function isOrchestrationEnabled(config) {
907
+ if (process.env.CHROXY_ENABLE_ORCHESTRATION === '1') return true
908
+ return config?.features?.orchestration === true
909
+ }
910
+
911
+ // #6865 — the opt-in HEADLESS SCHEDULER: fires persisted scheduled tasks (#6862)
912
+ // into a real agent session at their due time with NO client connected. Because
913
+ // that runs a session with nobody watching, it is off unless explicitly enabled.
914
+ // Fail-closed exactly like isIdeFeatureEnabled/isOrchestrationEnabled: only an
915
+ // explicit env=1 or `features.scheduler === true` arms the engine; anything else
916
+ // (absent, false, 'yes', 0) leaves the daemon byte-identical to pre-#6865 — no
917
+ // timers armed, no sessions spawned. Exported standalone so the CLI (#6868) and
918
+ // dashboard (#6871) can report the gate state without constructing an engine.
919
+ export function isSchedulerEnabled(config) {
920
+ if (process.env.CHROXY_ENABLE_SCHEDULER === '1') return true
921
+ return config?.features?.scheduler === true
922
+ }
923
+
924
+ // #6858 — resolve the opt-in provider-binary provenance PIN-LEDGER mode. One of
925
+ // 'off' | 'warn' | 'block'. Fail-closed to 'off' (behaviour identical to the
926
+ // pre-#6858 spawn path) for anything but an explicit 'warn' / 'block'. Precedence:
927
+ // CHROXY_BINARY_PROVENANCE env > config.binaryProvenance.mode > 'off'.
928
+ // 'warn' pins on first sight and surfaces a later hash change while still
929
+ // spawning; 'block' refuses the spawn on a hash change until re-approved.
930
+ export function resolveBinaryProvenanceMode(config) {
931
+ const env = typeof process.env.CHROXY_BINARY_PROVENANCE === 'string'
932
+ ? process.env.CHROXY_BINARY_PROVENANCE.trim().toLowerCase()
933
+ : ''
934
+ if (env === 'warn' || env === 'block') return env
935
+ if (env === 'off') return 'off'
936
+ const cfg = config?.binaryProvenance && typeof config.binaryProvenance === 'object'
937
+ ? config.binaryProvenance.mode
938
+ : undefined
939
+ return (cfg === 'warn' || cfg === 'block') ? cfg : 'off'
940
+ }
941
+
942
+ // #6858 — is the opt-in macOS signature/notarization gate (`spctl --assess`)
943
+ // enabled? Fail-closed to false (chroxy's own bundled providers are ad-hoc
944
+ // signed and would be rejected, so this can only ever be opt-in). Precedence:
945
+ // CHROXY_BINARY_SIGNATURE_GATE env (1/0) > config.binaryProvenance.signatureGate > false.
946
+ export function isBinarySignatureGateEnabled(config) {
947
+ const env = process.env.CHROXY_BINARY_SIGNATURE_GATE
948
+ if (env === '1') return true
949
+ if (env === '0') return false
950
+ return config?.binaryProvenance?.signatureGate === true
951
+ }
952
+
953
+ // #6764 — opt-in semantic session titles. When on, the first user turn's sidebar
954
+ // label is upgraded from a raw truncation of the message to a short model-
955
+ // generated summary via a cheap one-shot (Haiku) call. Off by default; the
956
+ // truncation fallback is used when off, when the call fails, or when no model
957
+ // access is available. Enabled by `features.semanticTitles === true` OR the
958
+ // `CHROXY_SEMANTIC_TITLES=1` env override; `CHROXY_SEMANTIC_TITLES=0` force-
959
+ // disables (handy for tests / A-B without editing config).
960
+ export function isSemanticTitlesEnabled(config) {
961
+ const env = process.env.CHROXY_SEMANTIC_TITLES
962
+ if (env === '1') return true
963
+ if (env === '0') return false
964
+ return config?.features?.semanticTitles === true
965
+ }
966
+
967
+ // #6764 — resolve the model for the one-shot title call. Precedence:
968
+ // CHROXY_SEMANTIC_TITLES_MODEL env > config.summarize.model > Haiku default.
969
+ // The `summarize.{model}` cheap-model override is reused (per #6764) so an
970
+ // operator who already tuned the summarizer's model gets the same for titles;
971
+ // the default stays a cheap Haiku alias so titles never burn a premium model.
972
+ export function resolveSemanticTitleModel(config) {
973
+ const envModel = typeof process.env.CHROXY_SEMANTIC_TITLES_MODEL === 'string'
974
+ && process.env.CHROXY_SEMANTIC_TITLES_MODEL.trim()
975
+ ? process.env.CHROXY_SEMANTIC_TITLES_MODEL.trim()
976
+ : null
977
+ if (envModel) return envModel
978
+ const summarizeModel = config?.summarize && typeof config.summarize === 'object'
979
+ && typeof config.summarize.model === 'string' && config.summarize.model.trim()
980
+ ? config.summarize.model.trim()
981
+ : null
982
+ return summarizeModel || DEFAULT_SEMANTIC_TITLE_MODEL
983
+ }
984
+
985
+ // #6764 — resolve the timeout (ms) for the one-shot title call. Precedence:
986
+ // CHROXY_SEMANTIC_TITLES_TIMEOUT_MS env > config.summarize.titleTimeoutMs > default.
987
+ // The title call is fire-and-forget, so without a timeout a stalled provider
988
+ // connection leaves its promise pending forever (retaining the SessionManager +
989
+ // first message → an unbounded per-session leak) and never tears the one-shot
990
+ // subprocess down. The resolved value is passed to SessionManager, which turns it
991
+ // into an `AbortSignal.timeout(...)` so the call aborts and falls open to the
992
+ // truncation label. Invalid / non-positive values fall back to the default.
993
+ export function resolveSemanticTitleTimeoutMs(config) {
994
+ const env = typeof process.env.CHROXY_SEMANTIC_TITLES_TIMEOUT_MS === 'string'
995
+ ? process.env.CHROXY_SEMANTIC_TITLES_TIMEOUT_MS.trim()
996
+ : ''
997
+ if (env) {
998
+ const n = Number(env)
999
+ if (Number.isFinite(n) && n > 0) return n
1000
+ }
1001
+ const cfg = config?.summarize && typeof config.summarize === 'object'
1002
+ ? config.summarize.titleTimeoutMs
1003
+ : undefined
1004
+ if (typeof cfg === 'number' && Number.isFinite(cfg) && cfg > 0) return cfg
1005
+ return DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS
1006
+ }
1007
+
676
1008
  // #6277: single source of truth for "does a user-shell spawn need host-local
677
1009
  // approval first?". Fail-closed — only an explicit `userShell.requireApproval
678
1010
  // === true` enables the gate. Independent of `enabled`: the gate only bites when
@@ -683,9 +1015,14 @@ export function isUserShellApprovalRequired(config) {
683
1015
  }
684
1016
 
685
1017
  // #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
1018
+ // allowlist. A static-allowlist subprocess provider (currently gemini and
1019
+ // deepseek — NOT codex since #7727, whose allowlist is the installed binary's
1020
+ // own model/list answer) otherwise hard-rejects an unlisted-but-API-valid
1021
+ // model, forcing a code release just to add one the upstream API already
1022
+ // exposes. This flag is keyed on the provider NAME and checked before any class
1023
+ // lookup, so it stays generic: the set of providers it matters for grows with
1024
+ // every provider that ships a compiled-in list, and the parenthetical above is
1025
+ // an inventory of today, not a closed roster. Opting a provider in here
689
1026
  // makes it behave like ollama (#5418 PROVIDER_MODELS_UNRESTRICTED): the id
690
1027
  // passes through verbatim and the upstream API becomes the validator. Returns a
691
1028
  // Set of provider-name strings; a missing/non-array value → empty Set (the
@@ -732,6 +1069,13 @@ function validateDiscordNotificationsBlock(discord, warnings) {
732
1069
  warnings.push(`Invalid value for 'notifications.discord.billingAlerts': expected a boolean, got ${JSON.stringify(discord.billingAlerts)}`)
733
1070
  }
734
1071
 
1072
+ // #7428: kill-switch for the Discord CI-completion sink. Default ON when a
1073
+ // webhook resolves; set false to keep ci_complete notices off Discord while
1074
+ // the status embed / billing alerts stay on.
1075
+ if (Object.prototype.hasOwnProperty.call(discord, 'ciAlerts') && typeof discord.ciAlerts !== 'boolean') {
1076
+ warnings.push(`Invalid value for 'notifications.discord.ciAlerts': expected a boolean, got ${JSON.stringify(discord.ciAlerts)}`)
1077
+ }
1078
+
735
1079
  const isValidColor = (v) => Number.isInteger(v) && v >= 0 && v <= MAX_DISCORD_COLOR
736
1080
  for (const key of ['defaultColor', 'permissionColor', 'errorColor']) {
737
1081
  if (Object.prototype.hasOwnProperty.call(discord, key) && !isValidColor(discord[key])) {
@@ -847,6 +1191,28 @@ export function isFatalConfigWarning(warning) {
847
1191
  return typeof warning === 'string' && warning.startsWith(FATAL_CONFIG_WARNING_PREFIX)
848
1192
  }
849
1193
 
1194
+ /**
1195
+ * Effective default for `maxPayload` — the WebSocket max message size applied
1196
+ * when nothing sets it (config file, `CHROXY_MAX_PAYLOAD`, or `--max-payload`).
1197
+ * 10 MB, wide enough for image / document attachments.
1198
+ *
1199
+ * #7011: it lives here, in the module that already owns maxPayload's numeric
1200
+ * contract (see NUMERIC_RANGE_CHECKS below), because FOUR surfaces must agree on
1201
+ * it — the WsServer fallback, the `--max-payload` help text, CONFIG.md, and
1202
+ * `.env.example` (the `CHROXY_MAX_PAYLOAD` spelling). It used to be a bare
1203
+ * literal in ws-server.js while the help string hand-copied a stale 1 MB value,
1204
+ * and the two drifted 10x apart. config.js is the only shared dependency of the
1205
+ * two code sites that is cheap to import: cli/shared.js loads on EVERY `chroxy`
1206
+ * invocation, whereas ws-server.js sits behind a deliberately lazy
1207
+ * `await import('../server-cli.js')` in cli/server-cmd.js — so the constant must
1208
+ * not live on the ws-server side of that boundary.
1209
+ *
1210
+ * The two static surfaces (CONFIG.md, `.env.example`) cannot import it, so they
1211
+ * are pinned to this value by tests/cli-max-payload-help-default.test.js instead.
1212
+ * If you change this number, those tests tell you every file that must move.
1213
+ */
1214
+ export const DEFAULT_MAX_PAYLOAD_BYTES = 10 * 1024 * 1024
1215
+
850
1216
  /**
851
1217
  * Declarative range checks for the simple numeric config fields (audit P2-6).
852
1218
  * Each entry replaces a hand-rolled `if (Number.isFinite(value) ...)` block that
@@ -1012,6 +1378,10 @@ export function validateConfig(config, verbose = false) {
1012
1378
  }
1013
1379
  }
1014
1380
 
1381
+ if (config.agentConnections !== undefined) {
1382
+ validateAgentConnections(config.agentConnections, warnings)
1383
+ }
1384
+
1015
1385
  // #4482: per-MCP-call timeout. 1s-10min. Unlike streamStallTimeoutMs,
1016
1386
  // 0 isn't meaningful here — a 0-ms callTool timeout fires immediately
1017
1387
  // and makes every MCP tool look broken — so any non-finite / non-
@@ -1151,6 +1521,85 @@ export function validateConfig(config, verbose = false) {
1151
1521
  }
1152
1522
  }
1153
1523
 
1524
+ // #7606: orphaned-child reaper block. `enabled` boolean; `sweepIntervalMs`
1525
+ // positive; `minAgeMs` non-negative. A bad value warns and the reaper falls
1526
+ // back to its built-in default for that knob (fail-safe: a typo can only
1527
+ // ever leave the defaults in place, never widen the predicate).
1528
+ if (config.orphanReap !== undefined) {
1529
+ if (typeof config.orphanReap !== 'object' || config.orphanReap === null || Array.isArray(config.orphanReap)) {
1530
+ warnings.push(`Invalid type for 'orphanReap': expected object, got ${Array.isArray(config.orphanReap) ? 'array' : typeof config.orphanReap}`)
1531
+ } else {
1532
+ if (
1533
+ Object.prototype.hasOwnProperty.call(config.orphanReap, 'enabled') &&
1534
+ typeof config.orphanReap.enabled !== 'boolean'
1535
+ ) {
1536
+ warnings.push(`Invalid type for 'orphanReap.enabled': expected boolean, got ${typeof config.orphanReap.enabled}`)
1537
+ }
1538
+ if (Object.prototype.hasOwnProperty.call(config.orphanReap, 'sweepIntervalMs')) {
1539
+ const v = config.orphanReap.sweepIntervalMs
1540
+ if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) {
1541
+ warnings.push(`Invalid value for 'orphanReap.sweepIntervalMs': expected a positive number, got ${typeof v === 'number' ? v : typeof v}`)
1542
+ }
1543
+ }
1544
+ if (Object.prototype.hasOwnProperty.call(config.orphanReap, 'minAgeMs')) {
1545
+ const v = config.orphanReap.minAgeMs
1546
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
1547
+ warnings.push(`Invalid value for 'orphanReap.minAgeMs': expected a non-negative number, got ${typeof v === 'number' ? v : typeof v}`)
1548
+ }
1549
+ }
1550
+ warnUnknownKeys(config.orphanReap, ORPHAN_REAP_SUPPORTED_KEYS, 'orphanReap', warnings)
1551
+ }
1552
+ }
1553
+
1554
+ // Session archive block. `enabled` boolean; `maxEntries` a positive integer;
1555
+ // `maxAgeDays` / `maxMegabytes` positive numbers. A bad value warns and the
1556
+ // archive falls back to its built-in default for that knob (SessionArchive
1557
+ // re-validates, so a typo can never widen retention past the defaults).
1558
+ if (config.sessionArchive !== undefined) {
1559
+ if (typeof config.sessionArchive !== 'object' || config.sessionArchive === null || Array.isArray(config.sessionArchive)) {
1560
+ warnings.push(`Invalid type for 'sessionArchive': expected object, got ${Array.isArray(config.sessionArchive) ? 'array' : typeof config.sessionArchive}`)
1561
+ } else {
1562
+ for (const key of SESSION_ARCHIVE_POLICY_KEYS) {
1563
+ if (!Object.prototype.hasOwnProperty.call(config.sessionArchive, key)) continue
1564
+ const problem = sessionArchiveFieldProblem(key, config.sessionArchive[key])
1565
+ if (!problem) continue
1566
+ if (problem.kind === 'type') {
1567
+ warnings.push(`Invalid type for 'sessionArchive.${key}': ${problem.detail}`)
1568
+ } else if (problem.kind === 'above_max') {
1569
+ warnings.push(`Invalid value for 'sessionArchive.${key}': ${config.sessionArchive[key]} is above the maximum of ${SESSION_ARCHIVE_MAX_ENTRIES} and is clamped to it`)
1570
+ } else {
1571
+ warnings.push(`Invalid value for 'sessionArchive.${key}': ${problem.detail}`)
1572
+ }
1573
+ }
1574
+ warnUnknownKeys(config.sessionArchive, SESSION_ARCHIVE_SUPPORTED_KEYS, 'sessionArchive', warnings)
1575
+ }
1576
+ }
1577
+
1578
+ // #7424: session CI-completion watcher. Every key is optional; an unset block
1579
+ // means "watch on, wake on, built-in intervals". The two intervals must be
1580
+ // positive finite numbers — a zero or negative sweep interval would spin the
1581
+ // event loop spawning `gh`, so a typo warns and the wiring layer falls back to
1582
+ // the module default rather than honouring it.
1583
+ if (config.sessionCi !== undefined) {
1584
+ if (typeof config.sessionCi !== 'object' || config.sessionCi === null || Array.isArray(config.sessionCi)) {
1585
+ warnings.push(`Invalid type for 'sessionCi': expected object, got ${Array.isArray(config.sessionCi) ? 'array' : typeof config.sessionCi}`)
1586
+ } else {
1587
+ for (const key of ['watch', 'wakeAgent']) {
1588
+ if (Object.prototype.hasOwnProperty.call(config.sessionCi, key) && typeof config.sessionCi[key] !== 'boolean') {
1589
+ warnings.push(`Invalid type for 'sessionCi.${key}': expected boolean, got ${typeof config.sessionCi[key]}`)
1590
+ }
1591
+ }
1592
+ for (const key of ['intervalMs', 'discoveryIntervalMs', 'maxSurveysPerTick']) {
1593
+ if (!Object.prototype.hasOwnProperty.call(config.sessionCi, key)) continue
1594
+ const v = config.sessionCi[key]
1595
+ if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) {
1596
+ warnings.push(`Invalid value for 'sessionCi.${key}': expected a positive number, got ${typeof v === 'number' ? v : typeof v}`)
1597
+ }
1598
+ }
1599
+ warnUnknownKeys(config.sessionCi, SESSION_CI_SUPPORTED_KEYS, 'sessionCi', warnings)
1600
+ }
1601
+ }
1602
+
1154
1603
  // #5413: notifications block. Only `notifications.discord` is recognised
1155
1604
  // today. All warnings here are "Invalid value" (not "Invalid type") so a
1156
1605
  // typo in a cosmetic color can never become a fatal startup error via the
@@ -1195,6 +1644,16 @@ export function validateConfig(config, verbose = false) {
1195
1644
  !Array.isArray(config.providers)
1196
1645
  ) {
1197
1646
  validateProvidersConfigBlock(config.providers, warnings)
1647
+ // #7319 — `providers.acp` (config-driven ACP agents). Validated here
1648
+ // rather than inside validateProvidersConfigBlock to avoid a circular
1649
+ // import (see the import comment above); entry-level warnings use the
1650
+ // same "Invalid value" wording so a malformed entry can't escalate into
1651
+ // a fatal startup error — bad entries are dropped at registration
1652
+ // (acp-session.js) and valid siblings still register.
1653
+ if (Object.prototype.hasOwnProperty.call(config.providers, 'acp')) {
1654
+ const { warnings: acpWarnings } = validateAcpProviders(config.providers.acp)
1655
+ warnings.push(...acpWarnings)
1656
+ }
1198
1657
  }
1199
1658
 
1200
1659
  // Validate externalUrl format if provided
@@ -1249,7 +1708,10 @@ export function mergeConfig({ fileConfig = {}, cliOverrides = {}, defaults = {},
1249
1708
 
1250
1709
  // Helper to set value and track source
1251
1710
  const setValue = (key, value, source) => {
1252
- merged[key] = value
1711
+ // #7083: the single choke point for every precedence branch (CLI, env, file,
1712
+ // defaults), so one coercion covers all of them — including the config-FILE path,
1713
+ // which has no parse step of its own.
1714
+ merged[key] = coerceDurationConfigValue(key, value)
1253
1715
  sources[key] = source
1254
1716
  }
1255
1717
 
@@ -1298,6 +1760,19 @@ export function mergeConfig({ fileConfig = {}, cliOverrides = {}, defaults = {},
1298
1760
 
1299
1761
  /**
1300
1762
  * Convert config key to corresponding environment variable name.
1763
+ *
1764
+ * #8151 round-2 review (nit) — was exported (S6) for doctor.js's
1765
+ * `resolveProviders` to read the same env-var name this file uses for a
1766
+ * given config key, rather than a second hand-typed copy. Round-2 Critical
1767
+ * 2 removed that direct read entirely — `resolveProviders` now goes
1768
+ * through `mergeConfig`/`resolveDaemonDefaultProvider` instead, the actual
1769
+ * fix for the regression that export-for-direct-reads turned out to be
1770
+ * (CHROXY_PROVIDERS is `config.providers`'s env var, not a provider-name
1771
+ * list, and a direct per-key env read couldn't tell the difference). No
1772
+ * remaining caller outside this file reads `envKeyForConfig` itself
1773
+ * (confirmed: `grep -rl` finds none), so this reverts to module-private
1774
+ * rather than carry a stale-justification export.
1775
+ *
1301
1776
  * @param {string} key - Config key
1302
1777
  * @returns {string} Environment variable name
1303
1778
  */
@@ -1343,6 +1818,8 @@ function envKeyForConfig(key) {
1343
1818
  controlRoomContainersIncludeStats: 'CHROXY_CONTAINERS_INCLUDE_STATS',
1344
1819
  // #5499: explicit repo-memory binary path for the Integrations survey.
1345
1820
  controlRoomRepoMemoryBin: 'CHROXY_REPO_MEMORY_BIN',
1821
+ // #8609: codex client to launch (read by CodexSession.resolvedBinary).
1822
+ codexBinary: 'CHROXY_CODEX_BIN',
1346
1823
  logFormat: 'CHROXY_LOG_FORMAT',
1347
1824
  sandbox: 'CHROXY_SANDBOX',
1348
1825
  resultTimeoutMs: 'CHROXY_RESULT_TIMEOUT_MS',
@@ -1371,6 +1848,10 @@ function envKeyForConfig(key) {
1371
1848
  // warning). Operators should migrate to
1372
1849
  // `CHROXY_DANGEROUSLY_SKIP_PERMISSIONS`.
1373
1850
  skipPermissions: 'CHROXY_SKIP_PERMISSIONS',
1851
+ // #6691 (E-4): explicit mapping so the fallback doesn't become the very
1852
+ // generic `ORCHESTRATION` (key.toUpperCase()), which an unrelated
1853
+ // environment could plausibly set and have silently honored as config.
1854
+ orchestration: 'CHROXY_ORCHESTRATION',
1374
1855
  }
1375
1856
  return envMap[key] || key.toUpperCase()
1376
1857
  }
@@ -1635,14 +2116,80 @@ export async function buildEnvironmentBackend(config, { _execFile, _loadBackends
1635
2116
  return { backend, type }
1636
2117
  }
1637
2118
 
1638
- const DEFAULT_CONFIG_PATH = join(homedir(), '.chroxy', 'config.json')
2119
+ /** The four `sessionArchive` retention knobs, in display order. */
2120
+ export const SESSION_ARCHIVE_POLICY_KEYS = ['enabled', 'maxEntries', 'maxAgeDays', 'maxMegabytes']
2121
+
2122
+ /**
2123
+ * The ONE rule for a single `sessionArchive` retention value, shared by the
2124
+ * config validator (which warns) and the dashboard setter (which rejects).
2125
+ * `enabled` is a boolean; `maxEntries` a positive integer no larger than
2126
+ * SESSION_ARCHIVE_MAX_ENTRIES; `maxAgeDays` / `maxMegabytes` positive finite
2127
+ * numbers.
2128
+ * @returns {null | { kind: 'type'|'value'|'above_max', detail: string }}
2129
+ */
2130
+ export function sessionArchiveFieldProblem(key, v) {
2131
+ const got = typeof v === 'number' ? String(v) : typeof v
2132
+ if (key === 'enabled') {
2133
+ return typeof v === 'boolean' ? null : { kind: 'type', detail: `expected boolean, got ${typeof v}` }
2134
+ }
2135
+ if (key === 'maxEntries') {
2136
+ if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) {
2137
+ return { kind: 'value', detail: `expected a positive integer, got ${got}` }
2138
+ }
2139
+ if (v > SESSION_ARCHIVE_MAX_ENTRIES) {
2140
+ return { kind: 'above_max', detail: `${v} is above the maximum of ${SESSION_ARCHIVE_MAX_ENTRIES}` }
2141
+ }
2142
+ return null
2143
+ }
2144
+ if (key === 'maxAgeDays' || key === 'maxMegabytes') {
2145
+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? null : { kind: 'value', detail: `expected a positive number, got ${got}` }
2146
+ }
2147
+ return { kind: 'value', detail: 'unknown key' }
2148
+ }
2149
+
2150
+ /**
2151
+ * Validate a whole retention policy (all four fields required, exactly as the
2152
+ * dashboard setter sends them). Unlike config loading, an over-max
2153
+ * `maxEntries` is REJECTED, not clamped.
2154
+ * @returns {{ field: string, message: string } | null} the first problem, or null
2155
+ */
2156
+ export function validateSessionArchivePolicy(policy) {
2157
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) {
2158
+ return { field: 'policy', message: 'expected a retention policy object' }
2159
+ }
2160
+ for (const key of SESSION_ARCHIVE_POLICY_KEYS) {
2161
+ const problem = sessionArchiveFieldProblem(key, policy[key])
2162
+ if (problem) return { field: key, message: `sessionArchive.${key}: ${problem.detail}` }
2163
+ }
2164
+ return null
2165
+ }
2166
+
2167
+ /**
2168
+ * Persist the four session-archive retention knobs to a config file,
2169
+ * preserving every other field (including unknown keys inside `sessionArchive`).
2170
+ * Throws on an unreadable/malformed existing config (readConfigForMerge).
2171
+ * Does NOT validate; callers run validateSessionArchivePolicy first.
2172
+ */
2173
+ export function writeSessionArchiveToConfig(policy, configPath = defaultConfigPath()) {
2174
+ const existing = readConfigForMerge(configPath)
2175
+ if (!existing.sessionArchive || typeof existing.sessionArchive !== 'object' || Array.isArray(existing.sessionArchive)) {
2176
+ existing.sessionArchive = {}
2177
+ }
2178
+ for (const key of SESSION_ARCHIVE_POLICY_KEYS) existing.sessionArchive[key] = policy[key]
2179
+ mkdirSync(dirname(configPath), { recursive: true })
2180
+ writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
2181
+ }
2182
+
2183
+ function defaultConfigPath() {
2184
+ return configPath('config.json')
2185
+ }
1639
2186
 
1640
2187
  /**
1641
2188
  * Read the repos array from a config file.
1642
2189
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1643
2190
  * @returns {Array<{ path: string, name?: string }>} Repos array, or [] if missing/invalid.
1644
2191
  */
1645
- export function readReposFromConfig(configPath = DEFAULT_CONFIG_PATH) {
2192
+ export function readReposFromConfig(configPath = defaultConfigPath()) {
1646
2193
  try {
1647
2194
  if (!existsSync(configPath)) return []
1648
2195
  const raw = JSON.parse(readFileSync(configPath, 'utf-8'))
@@ -1652,20 +2199,130 @@ export function readReposFromConfig(configPath = DEFAULT_CONFIG_PATH) {
1652
2199
  }
1653
2200
  }
1654
2201
 
2202
+ /**
2203
+ * Copy an unparseable config aside before refusing to write over it, so the
2204
+ * operator can recover their settings by hand (#7027).
2205
+ *
2206
+ * Best effort by design: the REFUSAL is what protects the file, the backup is a
2207
+ * courtesy. `COPYFILE_EXCL` means an existing backup is never clobbered — that
2208
+ * would be this very bug in miniature.
2209
+ *
2210
+ * The name is derived from the CONTENT, not the wall clock, because the refusal
2211
+ * is per-attempt and every caller is a button the operator can press again:
2212
+ * - identical content collapses onto one file, so a repeatedly-retried toggle
2213
+ * cannot pile up an unbounded set of full copies of config.json (API token
2214
+ * included) in ~/.chroxy. A duplicate of content already saved carries no
2215
+ * extra recovery value.
2216
+ * - genuinely different damage still gets its own file, which a timestamp
2217
+ * could NOT guarantee: two different corrupt versions refused inside the
2218
+ * same millisecond collided, and the reported path then named a backup
2219
+ * holding somebody else's content.
2220
+ * The file's mtime still carries the "when".
2221
+ *
2222
+ * @param {string} configPath
2223
+ * @param {Buffer} bytes - The raw bytes read back, used to key the backup.
2224
+ * @returns {string|null} the backup path, or null if none could be made.
2225
+ */
2226
+ function backUpMalformedConfig(configPath, bytes) {
2227
+ const digest = createHash('sha256').update(bytes).digest('hex').slice(0, 16)
2228
+ const backup = `${configPath}.corrupt-${digest}`
2229
+ try {
2230
+ copyFileSync(configPath, backup, fsConstants.COPYFILE_EXCL)
2231
+ return backup
2232
+ } catch (err) {
2233
+ // EEXIST means this exact content was already saved aside by an earlier
2234
+ // attempt — that file IS the recovery pointer, so keep naming it.
2235
+ return err?.code === 'EEXIST' ? backup : null
2236
+ }
2237
+ }
2238
+
2239
+ /**
2240
+ * Read an existing config.json for a read-modify-write, refusing to continue on
2241
+ * anything that would silently destroy it (#7027).
2242
+ *
2243
+ * Every `write*ToConfig` helper below is a read-modify-write over the operator's
2244
+ * ENTIRE config, and its next act is
2245
+ * `writeFileRestricted(configPath, JSON.stringify(existing))`. These all used to
2246
+ * open with `try { ... } catch { /* start fresh *\/ }`, so a config.json with a
2247
+ * hand-edited trailing comma, one truncated by an earlier crash, or one hit by a
2248
+ * transient read error turned an unrelated Control Room toggle into a WHOLESALE
2249
+ * overwrite: tunnel config, providers, features and permission rules replaced by
2250
+ * a single-key object, with no warning to the operator.
2251
+ *
2252
+ * So only ONE case starts fresh — the file genuinely not existing, which is the
2253
+ * legitimate first-run path. Every other outcome throws, and all three callers
2254
+ * already have an honest failure path for it (repo-handlers' `Failed to
2255
+ * add/remove repo`, the preset drawer's write-failure error, and the scheduler
2256
+ * handler's `SCHEDULER_GATE_FAILED`).
2257
+ *
2258
+ * A file that PARSES but is not a plain object (`null`, an array, a bare string)
2259
+ * is refused the same way: coercing it to `{}` and writing is the same wholesale
2260
+ * replacement wearing a different hat.
2261
+ *
2262
+ * @param {string} configPath - Path to config.json.
2263
+ * @returns {object} The parsed config object, or `{}` when the file is absent.
2264
+ * @throws {Error} When the file exists but cannot be read or parsed into an object.
2265
+ */
2266
+ export function readConfigForMerge(configPath) {
2267
+ // Read as BYTES and decode separately: the backup is keyed off the raw bytes,
2268
+ // and a crash-truncated config can be cut mid multi-byte character, so two
2269
+ // byte-different files can decode to the same U+FFFD-bearing string. Keying
2270
+ // off the decoded text would collapse those onto one backup and then name it
2271
+ // in the refusal for the version it does NOT hold.
2272
+ let bytes
2273
+ try {
2274
+ bytes = readFileSync(configPath)
2275
+ } catch (err) {
2276
+ // Absent → legitimately start fresh. Anything else (EACCES, EISDIR, EIO) is
2277
+ // a read we cannot trust, and overwriting on the back of it loses the file.
2278
+ if (err?.code === 'ENOENT') return {}
2279
+ throw new Error(
2280
+ `Refusing to write ${configPath}: the existing config could not be read (${err.message}). ` +
2281
+ 'Overwriting it would discard every other setting.',
2282
+ )
2283
+ }
2284
+
2285
+ let parsed
2286
+ try {
2287
+ parsed = JSON.parse(bytes.toString('utf-8'))
2288
+ } catch (err) {
2289
+ throw refuseMalformedConfig(configPath, `it is not valid JSON (${err.message})`, bytes)
2290
+ }
2291
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
2292
+ const found = parsed === null ? 'null' : (Array.isArray(parsed) ? 'an array' : `a ${typeof parsed}`)
2293
+ throw refuseMalformedConfig(configPath, `it does not contain a JSON object (found ${found})`, bytes)
2294
+ }
2295
+ return parsed
2296
+ }
2297
+
2298
+ /**
2299
+ * Build the refusal for a config.json that exists but cannot be merged into,
2300
+ * backing the bad file up first (#7027).
2301
+ * @param {string} configPath
2302
+ * @param {string} reason - Why it could not be merged, in sentence-fragment form.
2303
+ * @param {Buffer} bytes - The raw bytes read back, used to key the backup.
2304
+ * @returns {Error}
2305
+ */
2306
+ function refuseMalformedConfig(configPath, reason, bytes) {
2307
+ const backup = backUpMalformedConfig(configPath, bytes)
2308
+ return new Error(
2309
+ `Refusing to overwrite ${configPath}: ${reason}. ` +
2310
+ (backup ? `A copy was saved to ${backup}. ` : '') +
2311
+ 'Repair or move the file and retry — writing would have replaced every other setting.',
2312
+ )
2313
+ }
2314
+
1655
2315
  /**
1656
2316
  * Write the repos array to a config file, preserving other fields.
2317
+ *
2318
+ * Throws rather than starting fresh when an existing config.json is unreadable
2319
+ * or malformed (#7027) — see readConfigForMerge.
2320
+ *
1657
2321
  * @param {Array<{ path: string, name?: string }>} repos - Repos array to write.
1658
2322
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1659
2323
  */
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
- }
2324
+ export function writeReposToConfig(repos, configPath = defaultConfigPath()) {
2325
+ const existing = readConfigForMerge(configPath)
1669
2326
  existing.repos = repos
1670
2327
  const dir = dirname(configPath)
1671
2328
  mkdirSync(dir, { recursive: true })
@@ -1680,20 +2337,15 @@ export function writeReposToConfig(repos, configPath = DEFAULT_CONFIG_PATH) {
1680
2337
  * the operator can configure an override for a repo that isn't otherwise
1681
2338
  * registered. Other config fields and repo entries are preserved.
1682
2339
  *
2340
+ * Throws rather than starting fresh when an existing config.json is unreadable
2341
+ * or malformed (#7027) — see readConfigForMerge.
2342
+ *
1683
2343
  * @param {string} repoPath - The repo path to key the override by.
1684
2344
  * @param {object|null} preset - The preset object ({ preamble?, seed?, enabled? }) or null to clear.
1685
2345
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1686
2346
  */
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 = {}
2347
+ export function writeSessionPresetOverrideToConfig(repoPath, preset, configPath = defaultConfigPath()) {
2348
+ const existing = readConfigForMerge(configPath)
1697
2349
  if (!Array.isArray(existing.repos)) existing.repos = []
1698
2350
 
1699
2351
  const idx = existing.repos.findIndex(
@@ -1719,12 +2371,50 @@ export function writeSessionPresetOverrideToConfig(repoPath, preset, configPath
1719
2371
  writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
1720
2372
  }
1721
2373
 
2374
+ /**
2375
+ * Persist the global scheduled-execution enable gate (`features.scheduler`) to a
2376
+ * config file, preserving every other field (#6871). Mirrors
2377
+ * writeControlRoomRootToConfig's read-modify-write.
2378
+ *
2379
+ * This ONLY writes the persisted flag. It does NOT arm or disarm a running
2380
+ * daemon: the scheduler engine is built once at boot (buildSchedulerEngine
2381
+ * returns null when the gate is closed) and its destroy() is terminal, so a
2382
+ * running daemon must be restarted for a change here to affect what actually
2383
+ * fires. Callers are responsible for telling the operator that — see
2384
+ * handlers/scheduler-handlers.js, which reports `restartRequired` on every
2385
+ * snapshot rather than implying the toggle took effect.
2386
+ *
2387
+ * Note `CHROXY_ENABLE_SCHEDULER=1` OVERRIDES this flag (isSchedulerEnabled
2388
+ * checks the env first), so writing `false` while that env var is set leaves the
2389
+ * gate open; the handler refuses that combination instead of writing a lie.
2390
+ *
2391
+ * Throws rather than starting fresh when an existing config.json is unreadable
2392
+ * or malformed (#7027) — see readConfigForMerge. The handler already reports
2393
+ * that as SCHEDULER_GATE_FAILED.
2394
+ *
2395
+ * @param {boolean} enabled - the new gate value.
2396
+ * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
2397
+ */
2398
+ export function writeSchedulerEnabledToConfig(enabled, configPath = defaultConfigPath()) {
2399
+ const existing = readConfigForMerge(configPath)
2400
+ // A non-object `features` is a single stray FIELD, not the whole config, so it
2401
+ // is repaired in place rather than refused — the operator's other settings
2402
+ // still survive the write.
2403
+ if (!existing.features || typeof existing.features !== 'object' || Array.isArray(existing.features)) {
2404
+ existing.features = {}
2405
+ }
2406
+ existing.features.scheduler = enabled === true
2407
+ const dir = dirname(configPath)
2408
+ mkdirSync(dir, { recursive: true })
2409
+ writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
2410
+ }
2411
+
1722
2412
  /**
1723
2413
  * Read the Control Room discovery root from a config file (#5172).
1724
2414
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1725
2415
  * @returns {string|undefined} The configured root, or undefined if missing/invalid.
1726
2416
  */
1727
- export function readControlRoomRootFromConfig(configPath = DEFAULT_CONFIG_PATH) {
2417
+ export function readControlRoomRootFromConfig(configPath = defaultConfigPath()) {
1728
2418
  try {
1729
2419
  if (!existsSync(configPath)) return undefined
1730
2420
  const raw = JSON.parse(readFileSync(configPath, 'utf-8'))
@@ -1737,21 +2427,17 @@ export function readControlRoomRootFromConfig(configPath = DEFAULT_CONFIG_PATH)
1737
2427
  /**
1738
2428
  * Write the Control Room discovery root to a config file, preserving other
1739
2429
  * fields (#5172).
2430
+ *
2431
+ * Throws rather than starting fresh when an existing config.json is unreadable
2432
+ * or malformed (#7027) — see readConfigForMerge.
2433
+ *
1740
2434
  * @param {string} root - Absolute path to the discovery root.
1741
2435
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1742
2436
  */
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
- }
2437
+ export function writeControlRoomRootToConfig(root, configPath = defaultConfigPath()) {
2438
+ const existing = readConfigForMerge(configPath)
1752
2439
  existing.controlRoomRoot = root
1753
2440
  const dir = dirname(configPath)
1754
2441
  mkdirSync(dir, { recursive: true })
1755
2442
  writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
1756
2443
  }
1757
-