@chroxy/server 0.10.0 → 0.11.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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
package/src/config.js CHANGED
@@ -8,7 +8,8 @@
8
8
  * 4. Defaults
9
9
  */
10
10
 
11
- import { readFileSync, existsSync, mkdirSync } from 'fs'
11
+ import { readFileSync, existsSync, mkdirSync, copyFileSync, constants as fsConstants } from 'fs'
12
+ import { createHash } from 'crypto'
12
13
  import { join, dirname } from 'path'
13
14
  import { homedir } from 'os'
14
15
  import { writeFileRestricted } from './platform.js'
@@ -18,6 +19,10 @@ import { createLogger } from './logger.js'
18
19
  // deliberately a dependency-free module so importing it here never pulls
19
20
  // the BYOK/SDK machinery into the config-load path.
20
21
  import { validateProvidersConfigBlock } from './anthropic-compatible-config.js'
22
+ // #6764: default cheap model + timeout for the one-shot semantic-title call.
23
+ // Imported from the pure title module (no provider/SDK deps) so config load stays
24
+ // lightweight.
25
+ import { DEFAULT_SEMANTIC_TITLE_MODEL, DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS } from './session-title.js'
21
26
 
22
27
  const log = createLogger('config')
23
28
 
@@ -110,6 +115,13 @@ const CONFIG_SCHEMA = {
110
115
  // CHROXY_ENABLE_IDE=1 env override) reveals the IDE navigation/editing features;
111
116
  // off by default so it never risks the core offering. See isIdeFeatureEnabled().
112
117
  features: 'object',
118
+ // #6691 (E-4): the orchestration engine's config block ({ roles, bash, diff,
119
+ // maxParallelWorkers, ... } — consumed by OrchestrationManager via
120
+ // buildOrchestrationManager). Declared here so a configured block doesn't
121
+ // trip the misleading "Unknown config key ... (will be ignored)" warning —
122
+ // mergeConfig passes unknown file keys through regardless, but the warning
123
+ // suggested otherwise.
124
+ orchestration: 'object',
113
125
  externalUrl: 'string',
114
126
  repos: 'array',
115
127
  // #5172 (Control Room v2): filesystem root the Host Status survey scans
@@ -238,6 +250,18 @@ const CONFIG_SCHEMA = {
238
250
  // implicit.
239
251
  // Documented in CONFIG.md.
240
252
  trustMismatchMode: 'string',
253
+ // #6858: opt-in provenance verification for spawned provider binaries.
254
+ // Nested object:
255
+ // binaryProvenance.mode 'off' (default) | 'warn' | 'block' —
256
+ // SHA-256 pin ledger. Pins each provider binary on first sight; a changed
257
+ // hash re-gates (warn surfaces + allows, block refuses the spawn).
258
+ // binaryProvenance.signatureGate boolean (default false) — macOS `spctl`
259
+ // signature/notarization gate; hard-blocks un-notarized builds when on.
260
+ // Both OFF by default so P1 (#6708) behaviour is unchanged. Env overrides:
261
+ // CHROXY_BINARY_PROVENANCE (off|warn|block), CHROXY_BINARY_SIGNATURE_GATE (1|0).
262
+ // See resolveBinaryProvenanceMode() / isBinarySignatureGateEnabled() and
263
+ // docs/security/spawned-binary-provenance.md.
264
+ binaryProvenance: 'object',
241
265
  // #3749 / #3884 / #3899: SOFT-warning inactivity timeout (ms). When no
242
266
  // SDK / CLI event fires within this window, the server emits an
243
267
  // `inactivity_warning` event (and push notification) — the session
@@ -289,6 +313,132 @@ const CONFIG_SCHEMA = {
289
313
  mcpToolCallTimeoutMs: 'number',
290
314
  }
291
315
 
316
+ /**
317
+ * #7083 — config options whose value is a millisecond duration, and which therefore
318
+ * must never be fractional: they feed `setTimeout` AND the wire, where the protocol
319
+ * schemas require `.int()`.
320
+ *
321
+ * An EXPLICIT allowlist rather than `key.endsWith('Ms')`, even though the suffix
322
+ * happens to select exactly these six today. The `'number'` branch of `parseEnvValue`
323
+ * is shared with `costBudget`, which is USD and legitimately fractional — so a
324
+ * convention-driven predicate would be correct by accident and give a future reviewer
325
+ * nothing to check against. `tests/config-duration-coercion.test.js` asserts this list
326
+ * equals every `*Ms: 'number'` key in CONFIG_SCHEMA, so adding a duration option
327
+ * without listing it here fails CI rather than silently opting out.
328
+ *
329
+ * Deliberately NOT covered: nested ms options under `'object'`-typed keys
330
+ * (`worktreeGc.*`, `notifications.discord.*`, `orchestration.turnTimeoutMs`,
331
+ * `summarize.titleTimeoutMs`). Those do not reach the wire, and covering them needs
332
+ * per-block handling — a recursive walk of the merged object would destroy
333
+ * `providers.*.pricing.input` and `billing.monthlyCreditBudgetUsd`, which are
334
+ * legitimately fractional.
335
+ *
336
+ * `providerStreamStallTimeoutMs` IS covered (see DURATION_MS_MAP_CONFIG_KEYS below) —
337
+ * an earlier revision of this comment wrongly lumped it in with the exclusions.
338
+ */
339
+ export const DURATION_MS_CONFIG_KEYS = Object.freeze([
340
+ 'terminalDownGraceMs',
341
+ 'resultTimeoutMs',
342
+ 'hardTimeoutMs',
343
+ 'streamStallTimeoutMs',
344
+ 'backgroundShellHardQuiesceMs',
345
+ 'mcpToolCallTimeoutMs',
346
+ ])
347
+ const DURATION_MS_KEY_SET = new Set(DURATION_MS_CONFIG_KEYS)
348
+
349
+ /**
350
+ * #7083 — config options whose value is a MAP of `<id> -> duration-ms`.
351
+ *
352
+ * `providerStreamStallTimeoutMs.<id>` is not a cosmetic omission: it OUTRANKS the
353
+ * coerced global (session-manager.js `_sanitizeProviderTimeoutMap` keeps it verbatim
354
+ * because `isOperatorTimeoutInRange` checks finite/positive/<=24h but never
355
+ * integrality), flows into `base-session.js`, and is emitted as `result.duration` by
356
+ * `sdk-session.js`. Measured: a fractional per-provider entry survives `mergeConfig`
357
+ * and draws ZERO validateConfig warnings.
358
+ *
359
+ * That is the exact field `stream.ts` records as blocked on THIS issue before `.int()`
360
+ * can be added (#7095). Coercing only the flat keys would have left the per-provider
361
+ * override fractional, so #7095 would then make a config that is legal today emit a
362
+ * wire-illegal frame.
363
+ *
364
+ * An explicit list of MAP-shaped keys, not a recursive walk — the walk is what would
365
+ * destroy `providers.*.pricing.input` and `billing.monthlyCreditBudgetUsd`.
366
+ */
367
+ export const DURATION_MS_MAP_CONFIG_KEYS = Object.freeze(['providerStreamStallTimeoutMs'])
368
+ const DURATION_MS_MAP_KEY_SET = new Set(DURATION_MS_MAP_CONFIG_KEYS)
369
+
370
+ /**
371
+ * #7083 — coerce a duration-ms config value to a whole number of milliseconds.
372
+ *
373
+ * Applied at the single merge site so it covers BOTH input paths: an env var (parsed
374
+ * with `parseFloat`) and a `~/.chroxy/config.json` value, which is JSON and arrives as
375
+ * a fractional number with no parse step to hook. Fixing only the env parser would
376
+ * leave the config-file case — the one named in #7083 — fully broken.
377
+ *
378
+ * `Math.trunc` — truncate toward zero. Chosen for two reasons, not for convention:
379
+ * it cannot round an out-of-range value UP into legality (`Math.round(29999.5)` would
380
+ * become 30000 and silently suppress a below-minimum warning), and because every
381
+ * documented minimum is itself an integer, truncation can never push a legal value
382
+ * below its minimum. It also matches the truncating `parseInt` used for integer CLI
383
+ * flags in `cli/shared.js` — note this module's own env parser uses `parseFloat`, which
384
+ * is precisely why the fractional value reaches here in the first place.
385
+ *
386
+ * The zero guard is load-bearing. `0` is the documented "disabled" sentinel for
387
+ * `streamStallTimeoutMs` and `backgroundShellHardQuiesceMs`, so a naive
388
+ * `Math.trunc(0.4) === 0` would silently switch stall detection OFF — turning an
389
+ * illegal value that warns today into a feature that is quietly disabled. Sub-1
390
+ * magnitudes go to ±1 instead, which is never the sentinel.
391
+ *
392
+ * Precise about what ±1 then means: for the five range-checked keys it is still below
393
+ * the documented minimum, so validateConfig still warns and nothing is silently
394
+ * accepted. `terminalDownGraceMs` is the exception — it has NO range validation at all,
395
+ * so `0.4` becomes a legal, unwarned `1`. That is an invented value, and it is
396
+ * tolerable only because that key never reaches the wire; it is not a general property
397
+ * of the guard, so do not extend the guard to a wire-bound key on that basis.
398
+ *
399
+ * Non-numbers pass through untouched so `parseEnvValue`'s NaN-means-keep-the-string
400
+ * contract survives, and non-finite values pass through so the existing Infinity
401
+ * semantics in the range checks are unchanged.
402
+ *
403
+ * @param {string} key
404
+ * @param {unknown} value
405
+ * @returns {unknown} the coerced value, or `value` unchanged
406
+ */
407
+ export function coerceDurationConfigValue(key, value) {
408
+ if (DURATION_MS_MAP_KEY_SET.has(key)) return coerceDurationMap(key, value)
409
+ if (!DURATION_MS_KEY_SET.has(key)) return value
410
+ return coerceOneDuration(key, value)
411
+ }
412
+
413
+ /** @private — coerce a single duration-ms value. */
414
+ function coerceOneDuration(label, value) {
415
+ if (typeof value !== 'number' || !Number.isFinite(value)) return value
416
+ if (Number.isInteger(value)) return value
417
+ const truncated = Math.trunc(value)
418
+ const coerced = truncated === 0 ? Math.sign(value) : truncated
419
+ log.warn(`Config '${label}' must be a whole number of milliseconds — coercing ${value} to ${coerced}`)
420
+ return coerced
421
+ }
422
+
423
+ /**
424
+ * @private — coerce each value of an `<id> -> ms` map, ONE level deep.
425
+ *
426
+ * Deliberately not recursive: depth is what turns this from a targeted fix into the
427
+ * change that truncates `providers.*.pricing.input`. Non-object inputs pass through so
428
+ * the existing "wrong type" validateConfig warning still fires on the raw value.
429
+ */
430
+ function coerceDurationMap(key, value) {
431
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value
432
+ let changed = false
433
+ const out = {}
434
+ for (const [id, entry] of Object.entries(value)) {
435
+ const coerced = coerceOneDuration(`${key}.${id}`, entry)
436
+ if (coerced !== entry) changed = true
437
+ out[id] = coerced
438
+ }
439
+ return changed ? out : value
440
+ }
441
+
292
442
  /**
293
443
  * Config keys that should be masked in verbose output and sanitized logs.
294
444
  * `pushToken` was a dead entry — it is never a CONFIG_SCHEMA key; push tokens
@@ -673,6 +823,113 @@ export function isIdeFeatureEnabled(config) {
673
823
  return config?.features?.ide === true
674
824
  }
675
825
 
826
+ // #6691 — the opt-in orchestration/delegation harness ("committee"). Fail-closed
827
+ // like isIdeFeatureEnabled: only an explicit env=1 or `features.orchestration
828
+ // === true` enables it. Gates the WS handler surface AND the `orchestration`
829
+ // capability advertised in auth_ok, so a client only reveals the Runs surface
830
+ // when the operator has opted in.
831
+ export function isOrchestrationEnabled(config) {
832
+ if (process.env.CHROXY_ENABLE_ORCHESTRATION === '1') return true
833
+ return config?.features?.orchestration === true
834
+ }
835
+
836
+ // #6865 — the opt-in HEADLESS SCHEDULER: fires persisted scheduled tasks (#6862)
837
+ // into a real agent session at their due time with NO client connected. Because
838
+ // that runs a session with nobody watching, it is off unless explicitly enabled.
839
+ // Fail-closed exactly like isIdeFeatureEnabled/isOrchestrationEnabled: only an
840
+ // explicit env=1 or `features.scheduler === true` arms the engine; anything else
841
+ // (absent, false, 'yes', 0) leaves the daemon byte-identical to pre-#6865 — no
842
+ // timers armed, no sessions spawned. Exported standalone so the CLI (#6868) and
843
+ // dashboard (#6871) can report the gate state without constructing an engine.
844
+ export function isSchedulerEnabled(config) {
845
+ if (process.env.CHROXY_ENABLE_SCHEDULER === '1') return true
846
+ return config?.features?.scheduler === true
847
+ }
848
+
849
+ // #6858 — resolve the opt-in provider-binary provenance PIN-LEDGER mode. One of
850
+ // 'off' | 'warn' | 'block'. Fail-closed to 'off' (behaviour identical to the
851
+ // pre-#6858 spawn path) for anything but an explicit 'warn' / 'block'. Precedence:
852
+ // CHROXY_BINARY_PROVENANCE env > config.binaryProvenance.mode > 'off'.
853
+ // 'warn' pins on first sight and surfaces a later hash change while still
854
+ // spawning; 'block' refuses the spawn on a hash change until re-approved.
855
+ export function resolveBinaryProvenanceMode(config) {
856
+ const env = typeof process.env.CHROXY_BINARY_PROVENANCE === 'string'
857
+ ? process.env.CHROXY_BINARY_PROVENANCE.trim().toLowerCase()
858
+ : ''
859
+ if (env === 'warn' || env === 'block') return env
860
+ if (env === 'off') return 'off'
861
+ const cfg = config?.binaryProvenance && typeof config.binaryProvenance === 'object'
862
+ ? config.binaryProvenance.mode
863
+ : undefined
864
+ return (cfg === 'warn' || cfg === 'block') ? cfg : 'off'
865
+ }
866
+
867
+ // #6858 — is the opt-in macOS signature/notarization gate (`spctl --assess`)
868
+ // enabled? Fail-closed to false (chroxy's own bundled providers are ad-hoc
869
+ // signed and would be rejected, so this can only ever be opt-in). Precedence:
870
+ // CHROXY_BINARY_SIGNATURE_GATE env (1/0) > config.binaryProvenance.signatureGate > false.
871
+ export function isBinarySignatureGateEnabled(config) {
872
+ const env = process.env.CHROXY_BINARY_SIGNATURE_GATE
873
+ if (env === '1') return true
874
+ if (env === '0') return false
875
+ return config?.binaryProvenance?.signatureGate === true
876
+ }
877
+
878
+ // #6764 — opt-in semantic session titles. When on, the first user turn's sidebar
879
+ // label is upgraded from a raw truncation of the message to a short model-
880
+ // generated summary via a cheap one-shot (Haiku) call. Off by default; the
881
+ // truncation fallback is used when off, when the call fails, or when no model
882
+ // access is available. Enabled by `features.semanticTitles === true` OR the
883
+ // `CHROXY_SEMANTIC_TITLES=1` env override; `CHROXY_SEMANTIC_TITLES=0` force-
884
+ // disables (handy for tests / A-B without editing config).
885
+ export function isSemanticTitlesEnabled(config) {
886
+ const env = process.env.CHROXY_SEMANTIC_TITLES
887
+ if (env === '1') return true
888
+ if (env === '0') return false
889
+ return config?.features?.semanticTitles === true
890
+ }
891
+
892
+ // #6764 — resolve the model for the one-shot title call. Precedence:
893
+ // CHROXY_SEMANTIC_TITLES_MODEL env > config.summarize.model > Haiku default.
894
+ // The `summarize.{model}` cheap-model override is reused (per #6764) so an
895
+ // operator who already tuned the summarizer's model gets the same for titles;
896
+ // the default stays a cheap Haiku alias so titles never burn a premium model.
897
+ export function resolveSemanticTitleModel(config) {
898
+ const envModel = typeof process.env.CHROXY_SEMANTIC_TITLES_MODEL === 'string'
899
+ && process.env.CHROXY_SEMANTIC_TITLES_MODEL.trim()
900
+ ? process.env.CHROXY_SEMANTIC_TITLES_MODEL.trim()
901
+ : null
902
+ if (envModel) return envModel
903
+ const summarizeModel = config?.summarize && typeof config.summarize === 'object'
904
+ && typeof config.summarize.model === 'string' && config.summarize.model.trim()
905
+ ? config.summarize.model.trim()
906
+ : null
907
+ return summarizeModel || DEFAULT_SEMANTIC_TITLE_MODEL
908
+ }
909
+
910
+ // #6764 — resolve the timeout (ms) for the one-shot title call. Precedence:
911
+ // CHROXY_SEMANTIC_TITLES_TIMEOUT_MS env > config.summarize.titleTimeoutMs > default.
912
+ // The title call is fire-and-forget, so without a timeout a stalled provider
913
+ // connection leaves its promise pending forever (retaining the SessionManager +
914
+ // first message → an unbounded per-session leak) and never tears the one-shot
915
+ // subprocess down. The resolved value is passed to SessionManager, which turns it
916
+ // into an `AbortSignal.timeout(...)` so the call aborts and falls open to the
917
+ // truncation label. Invalid / non-positive values fall back to the default.
918
+ export function resolveSemanticTitleTimeoutMs(config) {
919
+ const env = typeof process.env.CHROXY_SEMANTIC_TITLES_TIMEOUT_MS === 'string'
920
+ ? process.env.CHROXY_SEMANTIC_TITLES_TIMEOUT_MS.trim()
921
+ : ''
922
+ if (env) {
923
+ const n = Number(env)
924
+ if (Number.isFinite(n) && n > 0) return n
925
+ }
926
+ const cfg = config?.summarize && typeof config.summarize === 'object'
927
+ ? config.summarize.titleTimeoutMs
928
+ : undefined
929
+ if (typeof cfg === 'number' && Number.isFinite(cfg) && cfg > 0) return cfg
930
+ return DEFAULT_SEMANTIC_TITLE_TIMEOUT_MS
931
+ }
932
+
676
933
  // #6277: single source of truth for "does a user-shell spawn need host-local
677
934
  // approval first?". Fail-closed — only an explicit `userShell.requireApproval
678
935
  // === true` enables the gate. Independent of `enabled`: the gate only bites when
@@ -847,6 +1104,28 @@ export function isFatalConfigWarning(warning) {
847
1104
  return typeof warning === 'string' && warning.startsWith(FATAL_CONFIG_WARNING_PREFIX)
848
1105
  }
849
1106
 
1107
+ /**
1108
+ * Effective default for `maxPayload` — the WebSocket max message size applied
1109
+ * when nothing sets it (config file, `CHROXY_MAX_PAYLOAD`, or `--max-payload`).
1110
+ * 10 MB, wide enough for image / document attachments.
1111
+ *
1112
+ * #7011: it lives here, in the module that already owns maxPayload's numeric
1113
+ * contract (see NUMERIC_RANGE_CHECKS below), because FOUR surfaces must agree on
1114
+ * it — the WsServer fallback, the `--max-payload` help text, CONFIG.md, and
1115
+ * `.env.example` (the `CHROXY_MAX_PAYLOAD` spelling). It used to be a bare
1116
+ * literal in ws-server.js while the help string hand-copied a stale 1 MB value,
1117
+ * and the two drifted 10x apart. config.js is the only shared dependency of the
1118
+ * two code sites that is cheap to import: cli/shared.js loads on EVERY `chroxy`
1119
+ * invocation, whereas ws-server.js sits behind a deliberately lazy
1120
+ * `await import('../server-cli.js')` in cli/server-cmd.js — so the constant must
1121
+ * not live on the ws-server side of that boundary.
1122
+ *
1123
+ * The two static surfaces (CONFIG.md, `.env.example`) cannot import it, so they
1124
+ * are pinned to this value by tests/cli-max-payload-help-default.test.js instead.
1125
+ * If you change this number, those tests tell you every file that must move.
1126
+ */
1127
+ export const DEFAULT_MAX_PAYLOAD_BYTES = 10 * 1024 * 1024
1128
+
850
1129
  /**
851
1130
  * Declarative range checks for the simple numeric config fields (audit P2-6).
852
1131
  * Each entry replaces a hand-rolled `if (Number.isFinite(value) ...)` block that
@@ -1249,7 +1528,10 @@ export function mergeConfig({ fileConfig = {}, cliOverrides = {}, defaults = {},
1249
1528
 
1250
1529
  // Helper to set value and track source
1251
1530
  const setValue = (key, value, source) => {
1252
- merged[key] = value
1531
+ // #7083: the single choke point for every precedence branch (CLI, env, file,
1532
+ // defaults), so one coercion covers all of them — including the config-FILE path,
1533
+ // which has no parse step of its own.
1534
+ merged[key] = coerceDurationConfigValue(key, value)
1253
1535
  sources[key] = source
1254
1536
  }
1255
1537
 
@@ -1371,6 +1653,10 @@ function envKeyForConfig(key) {
1371
1653
  // warning). Operators should migrate to
1372
1654
  // `CHROXY_DANGEROUSLY_SKIP_PERMISSIONS`.
1373
1655
  skipPermissions: 'CHROXY_SKIP_PERMISSIONS',
1656
+ // #6691 (E-4): explicit mapping so the fallback doesn't become the very
1657
+ // generic `ORCHESTRATION` (key.toUpperCase()), which an unrelated
1658
+ // environment could plausibly set and have silently honored as config.
1659
+ orchestration: 'CHROXY_ORCHESTRATION',
1374
1660
  }
1375
1661
  return envMap[key] || key.toUpperCase()
1376
1662
  }
@@ -1652,20 +1938,130 @@ export function readReposFromConfig(configPath = DEFAULT_CONFIG_PATH) {
1652
1938
  }
1653
1939
  }
1654
1940
 
1941
+ /**
1942
+ * Copy an unparseable config aside before refusing to write over it, so the
1943
+ * operator can recover their settings by hand (#7027).
1944
+ *
1945
+ * Best effort by design: the REFUSAL is what protects the file, the backup is a
1946
+ * courtesy. `COPYFILE_EXCL` means an existing backup is never clobbered — that
1947
+ * would be this very bug in miniature.
1948
+ *
1949
+ * The name is derived from the CONTENT, not the wall clock, because the refusal
1950
+ * is per-attempt and every caller is a button the operator can press again:
1951
+ * - identical content collapses onto one file, so a repeatedly-retried toggle
1952
+ * cannot pile up an unbounded set of full copies of config.json (API token
1953
+ * included) in ~/.chroxy. A duplicate of content already saved carries no
1954
+ * extra recovery value.
1955
+ * - genuinely different damage still gets its own file, which a timestamp
1956
+ * could NOT guarantee: two different corrupt versions refused inside the
1957
+ * same millisecond collided, and the reported path then named a backup
1958
+ * holding somebody else's content.
1959
+ * The file's mtime still carries the "when".
1960
+ *
1961
+ * @param {string} configPath
1962
+ * @param {Buffer} bytes - The raw bytes read back, used to key the backup.
1963
+ * @returns {string|null} the backup path, or null if none could be made.
1964
+ */
1965
+ function backUpMalformedConfig(configPath, bytes) {
1966
+ const digest = createHash('sha256').update(bytes).digest('hex').slice(0, 16)
1967
+ const backup = `${configPath}.corrupt-${digest}`
1968
+ try {
1969
+ copyFileSync(configPath, backup, fsConstants.COPYFILE_EXCL)
1970
+ return backup
1971
+ } catch (err) {
1972
+ // EEXIST means this exact content was already saved aside by an earlier
1973
+ // attempt — that file IS the recovery pointer, so keep naming it.
1974
+ return err?.code === 'EEXIST' ? backup : null
1975
+ }
1976
+ }
1977
+
1978
+ /**
1979
+ * Read an existing config.json for a read-modify-write, refusing to continue on
1980
+ * anything that would silently destroy it (#7027).
1981
+ *
1982
+ * Every `write*ToConfig` helper below is a read-modify-write over the operator's
1983
+ * ENTIRE config, and its next act is
1984
+ * `writeFileRestricted(configPath, JSON.stringify(existing))`. These all used to
1985
+ * open with `try { ... } catch { /* start fresh *\/ }`, so a config.json with a
1986
+ * hand-edited trailing comma, one truncated by an earlier crash, or one hit by a
1987
+ * transient read error turned an unrelated Control Room toggle into a WHOLESALE
1988
+ * overwrite: tunnel config, providers, features and permission rules replaced by
1989
+ * a single-key object, with no warning to the operator.
1990
+ *
1991
+ * So only ONE case starts fresh — the file genuinely not existing, which is the
1992
+ * legitimate first-run path. Every other outcome throws, and all three callers
1993
+ * already have an honest failure path for it (repo-handlers' `Failed to
1994
+ * add/remove repo`, the preset drawer's write-failure error, and the scheduler
1995
+ * handler's `SCHEDULER_GATE_FAILED`).
1996
+ *
1997
+ * A file that PARSES but is not a plain object (`null`, an array, a bare string)
1998
+ * is refused the same way: coercing it to `{}` and writing is the same wholesale
1999
+ * replacement wearing a different hat.
2000
+ *
2001
+ * @param {string} configPath - Path to config.json.
2002
+ * @returns {object} The parsed config object, or `{}` when the file is absent.
2003
+ * @throws {Error} When the file exists but cannot be read or parsed into an object.
2004
+ */
2005
+ export function readConfigForMerge(configPath) {
2006
+ // Read as BYTES and decode separately: the backup is keyed off the raw bytes,
2007
+ // and a crash-truncated config can be cut mid multi-byte character, so two
2008
+ // byte-different files can decode to the same U+FFFD-bearing string. Keying
2009
+ // off the decoded text would collapse those onto one backup and then name it
2010
+ // in the refusal for the version it does NOT hold.
2011
+ let bytes
2012
+ try {
2013
+ bytes = readFileSync(configPath)
2014
+ } catch (err) {
2015
+ // Absent → legitimately start fresh. Anything else (EACCES, EISDIR, EIO) is
2016
+ // a read we cannot trust, and overwriting on the back of it loses the file.
2017
+ if (err?.code === 'ENOENT') return {}
2018
+ throw new Error(
2019
+ `Refusing to write ${configPath}: the existing config could not be read (${err.message}). ` +
2020
+ 'Overwriting it would discard every other setting.',
2021
+ )
2022
+ }
2023
+
2024
+ let parsed
2025
+ try {
2026
+ parsed = JSON.parse(bytes.toString('utf-8'))
2027
+ } catch (err) {
2028
+ throw refuseMalformedConfig(configPath, `it is not valid JSON (${err.message})`, bytes)
2029
+ }
2030
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
2031
+ const found = parsed === null ? 'null' : (Array.isArray(parsed) ? 'an array' : `a ${typeof parsed}`)
2032
+ throw refuseMalformedConfig(configPath, `it does not contain a JSON object (found ${found})`, bytes)
2033
+ }
2034
+ return parsed
2035
+ }
2036
+
2037
+ /**
2038
+ * Build the refusal for a config.json that exists but cannot be merged into,
2039
+ * backing the bad file up first (#7027).
2040
+ * @param {string} configPath
2041
+ * @param {string} reason - Why it could not be merged, in sentence-fragment form.
2042
+ * @param {Buffer} bytes - The raw bytes read back, used to key the backup.
2043
+ * @returns {Error}
2044
+ */
2045
+ function refuseMalformedConfig(configPath, reason, bytes) {
2046
+ const backup = backUpMalformedConfig(configPath, bytes)
2047
+ return new Error(
2048
+ `Refusing to overwrite ${configPath}: ${reason}. ` +
2049
+ (backup ? `A copy was saved to ${backup}. ` : '') +
2050
+ 'Repair or move the file and retry — writing would have replaced every other setting.',
2051
+ )
2052
+ }
2053
+
1655
2054
  /**
1656
2055
  * Write the repos array to a config file, preserving other fields.
2056
+ *
2057
+ * Throws rather than starting fresh when an existing config.json is unreadable
2058
+ * or malformed (#7027) — see readConfigForMerge.
2059
+ *
1657
2060
  * @param {Array<{ path: string, name?: string }>} repos - Repos array to write.
1658
2061
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1659
2062
  */
1660
2063
  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
- }
2064
+ const existing = readConfigForMerge(configPath)
1669
2065
  existing.repos = repos
1670
2066
  const dir = dirname(configPath)
1671
2067
  mkdirSync(dir, { recursive: true })
@@ -1680,20 +2076,15 @@ export function writeReposToConfig(repos, configPath = DEFAULT_CONFIG_PATH) {
1680
2076
  * the operator can configure an override for a repo that isn't otherwise
1681
2077
  * registered. Other config fields and repo entries are preserved.
1682
2078
  *
2079
+ * Throws rather than starting fresh when an existing config.json is unreadable
2080
+ * or malformed (#7027) — see readConfigForMerge.
2081
+ *
1683
2082
  * @param {string} repoPath - The repo path to key the override by.
1684
2083
  * @param {object|null} preset - The preset object ({ preamble?, seed?, enabled? }) or null to clear.
1685
2084
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1686
2085
  */
1687
2086
  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 = {}
2087
+ const existing = readConfigForMerge(configPath)
1697
2088
  if (!Array.isArray(existing.repos)) existing.repos = []
1698
2089
 
1699
2090
  const idx = existing.repos.findIndex(
@@ -1719,6 +2110,44 @@ export function writeSessionPresetOverrideToConfig(repoPath, preset, configPath
1719
2110
  writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
1720
2111
  }
1721
2112
 
2113
+ /**
2114
+ * Persist the global scheduled-execution enable gate (`features.scheduler`) to a
2115
+ * config file, preserving every other field (#6871). Mirrors
2116
+ * writeControlRoomRootToConfig's read-modify-write.
2117
+ *
2118
+ * This ONLY writes the persisted flag. It does NOT arm or disarm a running
2119
+ * daemon: the scheduler engine is built once at boot (buildSchedulerEngine
2120
+ * returns null when the gate is closed) and its destroy() is terminal, so a
2121
+ * running daemon must be restarted for a change here to affect what actually
2122
+ * fires. Callers are responsible for telling the operator that — see
2123
+ * handlers/scheduler-handlers.js, which reports `restartRequired` on every
2124
+ * snapshot rather than implying the toggle took effect.
2125
+ *
2126
+ * Note `CHROXY_ENABLE_SCHEDULER=1` OVERRIDES this flag (isSchedulerEnabled
2127
+ * checks the env first), so writing `false` while that env var is set leaves the
2128
+ * gate open; the handler refuses that combination instead of writing a lie.
2129
+ *
2130
+ * Throws rather than starting fresh when an existing config.json is unreadable
2131
+ * or malformed (#7027) — see readConfigForMerge. The handler already reports
2132
+ * that as SCHEDULER_GATE_FAILED.
2133
+ *
2134
+ * @param {boolean} enabled - the new gate value.
2135
+ * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
2136
+ */
2137
+ export function writeSchedulerEnabledToConfig(enabled, configPath = DEFAULT_CONFIG_PATH) {
2138
+ const existing = readConfigForMerge(configPath)
2139
+ // A non-object `features` is a single stray FIELD, not the whole config, so it
2140
+ // is repaired in place rather than refused — the operator's other settings
2141
+ // still survive the write.
2142
+ if (!existing.features || typeof existing.features !== 'object' || Array.isArray(existing.features)) {
2143
+ existing.features = {}
2144
+ }
2145
+ existing.features.scheduler = enabled === true
2146
+ const dir = dirname(configPath)
2147
+ mkdirSync(dir, { recursive: true })
2148
+ writeFileRestricted(configPath, JSON.stringify(existing, null, 2))
2149
+ }
2150
+
1722
2151
  /**
1723
2152
  * Read the Control Room discovery root from a config file (#5172).
1724
2153
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
@@ -1737,18 +2166,15 @@ export function readControlRoomRootFromConfig(configPath = DEFAULT_CONFIG_PATH)
1737
2166
  /**
1738
2167
  * Write the Control Room discovery root to a config file, preserving other
1739
2168
  * fields (#5172).
2169
+ *
2170
+ * Throws rather than starting fresh when an existing config.json is unreadable
2171
+ * or malformed (#7027) — see readConfigForMerge.
2172
+ *
1740
2173
  * @param {string} root - Absolute path to the discovery root.
1741
2174
  * @param {string} [configPath] - Path to config.json. Defaults to ~/.chroxy/config.json.
1742
2175
  */
1743
2176
  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
- }
2177
+ const existing = readConfigForMerge(configPath)
1752
2178
  existing.controlRoomRoot = root
1753
2179
  const dir = dirname(configPath)
1754
2180
  mkdirSync(dir, { recursive: true })
@@ -54,6 +54,7 @@ import { readFile, stat } from 'fs/promises'
54
54
  import { join } from 'path'
55
55
  import { parseGithubOwnerRepo } from './survey.js'
56
56
  import { DEFAULT_CONCURRENCY, EXEC_TIMEOUT_MS } from './constants.js'
57
+ import { isoFromEpochMs } from '../utils/iso-datetime.js'
57
58
 
58
59
  const execFileAsync = promisify(execFile)
59
60
 
@@ -127,16 +128,16 @@ export function parseRepoMemoryConfig(text) {
127
128
  */
128
129
  function deriveLastActivity(parsed) {
129
130
  const raw = parsed.lastEventAt ?? parsed.lastActivityAt ?? parsed.lastActivity
130
- if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
131
- try {
132
- return new Date(raw).toISOString()
133
- } catch {
134
- return null
135
- }
136
- }
131
+ // #7081: both branches go through isoFromEpochMs. The destination is
132
+ // `z.string().datetime()`, and this input is repo-memory's own report JSON —
133
+ // arbitrary third-party output, so weaker protection than the mtime site below.
134
+ if (typeof raw === 'number') return isoFromEpochMs(raw)
137
135
  if (typeof raw === 'string' && raw.length > 0) {
136
+ // Date.parse ROUND-TRIPS the expanded-year form, so parsing a
137
+ // '+058851-…' string and re-emitting it reproduces the same wire-illegal
138
+ // value. The string branch needs the range check just as much as the number one.
138
139
  const ms = Date.parse(raw)
139
- if (!Number.isNaN(ms)) return new Date(ms).toISOString()
140
+ if (!Number.isNaN(ms)) return isoFromEpochMs(ms)
140
141
  }
141
142
  return null
142
143
  }
@@ -247,7 +248,11 @@ async function surveyCache(statFn, repoPath) {
247
248
  }
248
249
  const sizeBytes = Math.max(0, Math.trunc(nonNegNumber(db?.size, 0) + nonNegNumber(wal?.size, 0)))
249
250
  const mtimes = [db?.mtimeMs, wal?.mtimeMs].filter(m => typeof m === 'number' && Number.isFinite(m) && m > 0)
250
- const lastModified = mtimes.length > 0 ? new Date(Math.max(...mtimes)).toISOString() : null
251
+ // #7081: same unbounded epoch->ISO shape as skills `lastUsed`. Unreachable on
252
+ // APFS/ext4 (neither can store a year > 9999) but a network/FUSE mount or a
253
+ // deliberately-set mtime can, and the adjacent sizeBytes above is already
254
+ // bounded — so the rule gets applied here rather than relying on the filesystem.
255
+ const lastModified = mtimes.length > 0 ? isoFromEpochMs(Math.max(...mtimes)) : null
251
256
  return { present: true, sizeBytes, lastModified }
252
257
  }
253
258
 
@@ -524,7 +529,8 @@ export function parseRelayRuns(json) {
524
529
  status: str(r.status),
525
530
  conclusion: str(r.conclusion),
526
531
  event: str(r.event),
527
- createdAt: Number.isNaN(createdMs) ? null : new Date(createdMs).toISOString(),
532
+ // #7081: same bound — gh run JSON is third-party input.
533
+ createdAt: Number.isNaN(createdMs) ? null : isoFromEpochMs(createdMs),
528
534
  })
529
535
  }
530
536
  return runs
@@ -47,6 +47,7 @@ import { readFileSync } from 'fs'
47
47
  import { join, dirname } from 'path'
48
48
  import { loadActiveSkills, findRepoSkillsDir, DEFAULT_SKILLS_DIR } from '../skills-loader.js'
49
49
  import { DEFAULT_CONCURRENCY } from './constants.js'
50
+ import { isoFromEpochMs } from '../utils/iso-datetime.js'
50
51
 
51
52
  /**
52
53
  * Parse a `skills.lock` file into a name → { hash, installed } map. The lock
@@ -163,7 +164,11 @@ export function toInventoryEntry(skill, lock, usage, globalNames) {
163
164
  hash: lockRec ? lockRec.hash : null,
164
165
  installed: lockRec ? lockRec.installed : null,
165
166
  // Usage rollup (#5554 Phase 2). Null when never recorded.
166
- lastUsed: usageRec && typeof usageRec.lastUsed === 'number' ? new Date(usageRec.lastUsed).toISOString() : null,
167
+ // #7081: via the shared helper, which returns null for anything that would
168
+ // render as an expanded-year (>year 9999) string the wire cannot carry.
169
+ // skills-usage.js already bounds what it PERSISTS; this covers any other path
170
+ // that reaches here with an unbounded number.
171
+ lastUsed: isoFromEpochMs(usageRec?.lastUsed),
167
172
  useCount: usageRec ? usageRec.count : 0,
168
173
  usedRepos: usageRec && Array.isArray(usageRec.repos) ? usageRec.repos.slice() : [],
169
174
  }