@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/server-cli.js CHANGED
@@ -1,10 +1,21 @@
1
- import { SessionManager } from './session-manager.js'
1
+ import {
2
+ SessionManager,
3
+ ProviderBinaryNotFoundError,
4
+ ProviderBinaryQuarantinedError,
5
+ ProviderBinaryProvenanceError,
6
+ ProviderBinaryUnsupportedError,
7
+ ProviderBinaryVersionError,
8
+ ProviderCredentialMissingError,
9
+ } from './session-manager.js'
2
10
  import { DEFAULT_RESULT_TIMEOUT_MS, DEFAULT_HARD_TIMEOUT_MS, DEFAULT_STREAM_STALL_TIMEOUT_MS } from './base-session.js'
3
11
  import { DEFAULT_TOOL_CALL_TIMEOUT_MS } from './byok-mcp-client.js'
4
12
  import { formatIdleDuration } from './session-timeout-manager.js'
5
13
  import { isOperatorTimeoutInRange } from './duration.js'
6
14
  import { WsServer } from './ws-server.js'
7
15
  import { BillingCanaryMonitor } from './billing-canary-monitor.js'
16
+ import { buildSessionCiWatcher } from './session-ci-watcher.js'
17
+ import { DaemonUpdateStatus } from './daemon-update-status.js'
18
+ import { computeDaemonIdleState } from './daemon-idle-state.js'
8
19
  import { resolvePublicIp } from './get-public-ip.js'
9
20
  import { createTunnel, parseTunnelArg } from './tunnel/index.js'
10
21
  // #5368 slice (c): QUICK_TUNNEL_DNS_SETTLE_MS + TUNNEL_STATUS_MIN_PROTOCOL_VERSION
@@ -13,6 +24,9 @@ import { createTunnel, parseTunnelArg } from './tunnel/index.js'
13
24
  import { waitForTunnel } from './tunnel-check.js'
14
25
  import { PushManager, settlePush } from './push.js'
15
26
  import { ensureIngestSecret } from './event-ingest.js'
27
+ import { getChroxyHostEnv } from './chroxy-host-metadata.js'
28
+ import { boundedRegex } from './utils/bounded-regex.js'
29
+ import { probeNodePtyAvailable } from './utils/node-pty-probe.js'
16
30
  import { PushNotificationHandler } from './server-cli/push-notification-handler.js'
17
31
  import { StartupDisplay } from './server-cli/startup-display.js'
18
32
  import { TunnelLifecycleHandler } from './server-cli/tunnel-lifecycle-handler.js'
@@ -21,7 +35,10 @@ import { hostname, homedir } from 'os'
21
35
  import { readFileSync, existsSync } from 'fs'
22
36
  import { fileURLToPath } from 'url'
23
37
  import { dirname, join, relative, sep } from 'path'
24
- import { createLogger, setJsonMode, initFileLogging } from './logger.js'
38
+ import { createLogger, setJsonMode, initFileLogging, setConsoleQuiet } from './logger.js'
39
+ import { configDir, configPath } from './config-dir.js'
40
+ import { defaultCwdAdvisory } from './handler-utils.js'
41
+ import { detectStrandedState, missingTokenAdvice, startupStrandedWarning } from './config-dir-migration.js'
25
42
 
26
43
  const log = createLogger('cli')
27
44
  // #5368 slice (b): QRCode + writeConnectionInfo moved to startup-display.js with
@@ -35,20 +52,27 @@ import { resolveBindHost, isLoopbackHost, formatHostForUrl, maybeWarnNonLoopback
35
52
  import { writeFileRestricted } from './platform.js'
36
53
  import { getToken, setToken, migrateToken, isKeychainAvailable } from './keychain.js'
37
54
  import { maybeEncryptCredentialsAtRest } from './credential-store.js'
38
- import { registerDockerProvider, resolveProviderLabel, DEFAULT_PROVIDER } from './providers.js'
55
+ import { registerDockerProvider, resolveProviderLabel, DEFAULT_PROVIDER, resolveDaemonDefaultProvider } from './providers.js'
39
56
  import { registerAnthropicCompatibleProviders } from './anthropic-compatible-session.js'
40
57
  import { registerOpenAiCompatibleProviders } from './openai-compatible-session.js'
58
+ import { registerAcpProviders } from './acp-session.js'
41
59
  import { getSharedPool, isPoolEnabled } from './docker-byok-pool.js'
42
60
  import { getSharedPoolStats } from './docker-byok-pool-stats.js'
43
- import { getRegistryForProvider, watchModelsOverlay } from './models.js'
61
+ import { getRegistryForProvider, watchModelsOverlay, setInUseModelsProvider } from './models.js'
62
+ import { clientActiveProvider, overlayBroadcastReachesProvider, broadcastRosterPerRecipient } from './roster-broadcast.js'
44
63
  // Imported from a dedicated constants module rather than environment-manager.js
45
64
  // so we don't eagerly pull in DockerBackend when environments are disabled —
46
65
  // environment-manager.js itself remains behind the dynamic import below
47
66
  // (`if (config?.environments?.enabled)`).
48
67
  import { UNREACHABLE_STATUSES } from './environment-statuses.js'
49
- import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders } from './config.js'
68
+ import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders, isSemanticTitlesEnabled, resolveSemanticTitleModel, resolveSemanticTitleTimeoutMs, resolveBinaryProvenanceMode, isBinarySignatureGateEnabled, applyCodexBinaryConfig } from './config.js'
69
+ import { sweepStaleProviderDirs } from './sweep-stale-provider-dirs.js'
70
+ import { buildOrchestrationManager } from './orchestration/build-manager.js'
71
+ import { buildSchedulerEngine } from './scheduler.js'
50
72
  import { parseDuration } from './duration.js'
51
73
  import { createSessionTokenStore } from './session-token-store.js'
74
+ import { StatusLineManager } from './statusline.js'
75
+ import { warnIfClaudeConfigDirUnusable } from './utils/claude-config-dir.js'
52
76
 
53
77
  const __filename = fileURLToPath(import.meta.url)
54
78
  const __dirname = dirname(__filename)
@@ -71,6 +95,103 @@ const SERVER_VERSION = packageJson.version
71
95
  * @param {{ tunnelMode: string, tunnelUrl: string, attempt?: number, maxAttempts?: number }} args
72
96
  * @returns {object} WS message envelope
73
97
  */
98
+ /**
99
+ * #6927/#7067 — write the (possibly rotated) primary token into config.json.
100
+ *
101
+ * Exported and `_write`-injectable so the DURABILITY limb is testable: #7067
102
+ * made `writeFileRestricted` REPORT a post-rename directory-fsync failure rather
103
+ * than throw, which is right for callers where a landed write must not be
104
+ * reported as failed. This caller is the deliberate exception — #6965 built an
105
+ * operator-visible `REVOKE_NOT_DURABLE` frame for exactly this outcome and the
106
+ * revoke ack is gated on this callback, so swallowing the caveat would trade the
107
+ * old false-FAILURE for a false SUCCESS on the panic button. Re-raise it and let
108
+ * #6965's existing path surface it.
109
+ *
110
+ * @param {string} configFile
111
+ * @param {string} newToken
112
+ * @param {{ durable?: boolean, _write?: Function }} [opts]
113
+ */
114
+ export function persistTokenToConfigFile(configFile, newToken, { durable = false, _write = writeFileRestricted } = {}) {
115
+ const raw = existsSync(configFile) ? readFileSync(configFile, 'utf-8') : '{}'
116
+ const cfg = JSON.parse(raw)
117
+ cfg.apiToken = newToken
118
+ const outcome = _write(configFile, JSON.stringify(cfg, null, 2), { durable })
119
+ if (durable && outcome?.durabilityUnconfirmed) {
120
+ throw new Error(
121
+ `token written but its directory entry could not be fsynced (${outcome.durabilityUnconfirmed})`,
122
+ )
123
+ }
124
+ }
125
+
126
+ /**
127
+ * #7055 — build the `TokenManager({ onPersist })` callback.
128
+ *
129
+ * Extracted from `startServer`'s inline closure so BOTH limbs are drivable by a
130
+ * test. It is load-bearing for a security guarantee (#6965 gates the revoke ack
131
+ * on it settling; #7045 made it rethrow so a failed write cannot masquerade as a
132
+ * durable revoke) yet nothing executed it: the gate tests supply a synthetic
133
+ * `onPersist`, and every local/CI run disables the keychain.
134
+ *
135
+ * The keychain seam matters more than it looks. `setToken()` re-checks
136
+ * availability itself and RETURNS SILENTLY when the keychain is unavailable — no
137
+ * throw, no boolean. The outer `_isKeychainAvailable()` guard is the only thing
138
+ * stopping that from becoming a persist that writes nothing anywhere and still
139
+ * reports success, i.e. a revoke acked for a write that never happened.
140
+ *
141
+ * @param {object} opts
142
+ * @param {string} opts.configFile - path to `~/.chroxy/config.json`
143
+ * @param {{ error: Function }} [opts.logger]
144
+ * @param {Function} [opts._isKeychainAvailable] - test seam
145
+ * @param {Function} [opts._setToken] - test seam
146
+ * @param {Function} [opts._write] - test seam, forwarded to persistTokenToConfigFile
147
+ * @returns {(newToken: string, ctx?: { reason?: string }) => void}
148
+ */
149
+ export function buildTokenPersistCallback({
150
+ configFile,
151
+ logger = log,
152
+ _isKeychainAvailable = isKeychainAvailable,
153
+ _setToken = setToken,
154
+ _write = writeFileRestricted,
155
+ } = {}) {
156
+ return (newToken, { reason } = {}) => {
157
+ // #6927 — a 'revoke' is the operator panic button (a compromised primary
158
+ // token killed NOW). Persist it DURABLY so a power loss within the OS
159
+ // writeback window can't roll config.json back to the compromised token and
160
+ // resurrect it on the next daemon start. A routine 'scheduled' rotation is
161
+ // fail-safe (the old token keeps working through its grace window), so it
162
+ // stays non-durable. Only the file fallback is fsync-controllable here; the
163
+ // keychain path's durability is the OS keychain's responsibility.
164
+ const durable = reason === 'revoke'
165
+ const persistToFile = () => persistTokenToConfigFile(configFile, newToken, { durable, _write })
166
+ try {
167
+ if (_isKeychainAvailable()) {
168
+ try {
169
+ _setToken(newToken)
170
+ } catch {
171
+ // Keychain write failed — fall back to config file
172
+ persistToFile()
173
+ }
174
+ } else {
175
+ persistToFile()
176
+ }
177
+ } catch (err) {
178
+ // `err?.message || String(err)` (the platform.js idiom), not `err.message`:
179
+ // a thrown `null`/`undefined` would make the LOG LINE throw a TypeError,
180
+ // which then replaces the original failure on its way to the ack gate —
181
+ // the operator would be told the persist failed for the wrong reason and
182
+ // never see a `Failed to persist token` line at all.
183
+ logger.error(`Failed to persist token: ${err?.message || String(err)}`)
184
+ // #6965 — RETHROW. The revoke ack is now gated on this callback resolving,
185
+ // so swallowing the error here would report a durable revoke that never
186
+ // reached the disk (the exact false-safety this closes). TokenManager logs
187
+ // the rejection too, and for a revoke WsServer sends an explicit
188
+ // REVOKE_NOT_DURABLE error FIRST and then the token-less revoke transition
189
+ // anyway — the client must still re-authenticate.
190
+ throw err
191
+ }
192
+ }
193
+ }
194
+
74
195
  export function buildTunnelWarmingStatus({ tunnelMode, tunnelUrl, attempt, maxAttempts }) {
75
196
  const base = {
76
197
  type: 'server_status',
@@ -132,6 +253,155 @@ export function buildServerBanner({ version, provider }) {
132
253
  return `Chroxy Server v${version} (${modeStr})`
133
254
  }
134
255
 
256
+ /**
257
+ * #7722 — build the `available_models` broadcasts for one models-overlay
258
+ * hot-reload (`watchModelsOverlay`'s `onReload`).
259
+ *
260
+ * The reload re-folds the default (Claude) registry AND every per-provider
261
+ * registry the overlay touches (#6377), so it produces ONE roster per affected
262
+ * registry — not one. Broadcasting only the Claude roster (and labelling it
263
+ * `claude-sdk`, as this did before) had two failures on a live codex session: a
264
+ * `provider: "codex"` overlay row never reached the codex client at all, and —
265
+ * on the pre-#7728 clients this was written against — the claude-sdk tag flipped
266
+ * the dashboard's `modelsMatchProvider` false, which HID the model picker until
267
+ * the client reconnected. That second failure is gone: `modelsMatchProvider` was
268
+ * deleted with the single `availableModels` slot, and a client now keys each
269
+ * roster by its sender. The FIRST one is still live and is what this function
270
+ * exists for — a roster that is never sent cannot be read from any slot.
271
+ *
272
+ * The wire shape is unchanged — each entry is the same provider-tagged
273
+ * `available_models` message every other sender emits.
274
+ *
275
+ * This builds the SET; it does not decide recipients.
276
+ * `overlayBroadcastReachesProvider` below is the recipient rule, and
277
+ * `createOverlayReloadBroadcaster` is what applies it. Until #7728 that routing
278
+ * was load-bearing for CORRECTNESS: every client kept ONE `availableModels`
279
+ * slot, replaced unconditionally on every message, so sending the whole set to
280
+ * everyone was last-write-wins and a Claude client on a daemon that also has a
281
+ * codex row ended up tagged `codex` and lost the very picker this issue is
282
+ * about. Clients now key each roster by the provider that sent it
283
+ * (`mergeModelsByProvider`, store-core/src/models-by-provider.ts), so the
284
+ * routing is defence in depth and bandwidth rather than the only thing standing
285
+ * between a codex session and a Claude roster.
286
+ *
287
+ * Exported so tests can assert the broadcast set without executing
288
+ * `startCliServer()` end-to-end.
289
+ *
290
+ * @param {{ models?: object[], defaultModelId?: string|null, providers?: {provider: string, models: object[], defaultModelId: string|null}[] }} reload
291
+ * @returns {{ type: 'available_models', models: object[], defaultModel: string|null, provider: string }[]}
292
+ */
293
+ export function buildOverlayReloadBroadcasts({ models, defaultModelId, providers } = {}) {
294
+ const out = [{
295
+ type: 'available_models',
296
+ models: models || [],
297
+ defaultModel: defaultModelId ?? null,
298
+ provider: 'claude-sdk',
299
+ }]
300
+ for (const entry of providers || []) {
301
+ if (!entry || typeof entry.provider !== 'string' || entry.provider.length === 0) continue
302
+ out.push({
303
+ type: 'available_models',
304
+ models: entry.models || [],
305
+ defaultModel: entry.defaultModelId ?? null,
306
+ provider: entry.provider,
307
+ })
308
+ }
309
+ return out
310
+ }
311
+
312
+ // #7895 — `overlayBroadcastReachesProvider` and `clientActiveProvider` moved to
313
+ // `./roster-broadcast.js` so `ws-forwarding.js`'s two `available_models` send
314
+ // sites can share them (and the per-recipient tagging loop below) instead of a
315
+ // third hand-rolled copy. Re-exported here so every existing importer of this
316
+ // module — notably `models-overlay-reload-broadcast.test.js` — is unaffected.
317
+ export { overlayBroadcastReachesProvider, clientActiveProvider }
318
+
319
+ /**
320
+ * #7722 — build the `watchModelsOverlay({ onReload })` callback: turn one reload
321
+ * into its broadcast set and send each entry ONLY to the clients that registry
322
+ * is the roster for (`overlayBroadcastReachesProvider`).
323
+ *
324
+ * #7756 — the DEFAULT (Claude) entry additionally gets RE-TAGGED per recipient
325
+ * instead of sent verbatim. `claude-sdk`, `claude-cli` and `claude-tui` share
326
+ * this one registry, so `overlayBroadcastReachesProvider` correctly decides all
327
+ * three should receive it — but since #7728 the client keys each roster by the
328
+ * EXACT tag it arrived under (`modelsByProvider`,
329
+ * store-core/src/models-by-provider.ts), so a single `claude-sdk` literal
330
+ * never refreshes a `claude-cli`/`claude-tui` client's OWN bucket even though
331
+ * routing already decided it should. Each recipient is instead served the same roster
332
+ * tagged with the name `resolveRosterProvider` would give IT on a fresh
333
+ * connect (`ws-history.js`'s own resolution), so a reload and a reconnect agree
334
+ * on what a session's roster is called — no reconnect-vs-reload skew.
335
+ *
336
+ * The concrete tag set is derived from the provider REGISTRY
337
+ * (`getRegisteredProviderNames` + `isClaudeProvider`, #5858's single source of
338
+ * truth), never a hand-maintained name literal — the exact defect class #5855
339
+ * fixed for `isClaudeProvider` itself. That includes `claude-byok`
340
+ * (`static claudeFamily = true`, byok-session.js) — see the paragraph below
341
+ * for why an earlier revision of this fix excluded it and why that was wrong.
342
+ *
343
+ * A residual broadcast (still tagged with the reload's own literal) covers
344
+ * whatever does not resolve to a known tag — an unregistered/custom provider
345
+ * name, or one whose own registry build throws — preserving the pre-#7756
346
+ * fail-open delivery for that edge case (`overlayBroadcastReachesProvider`'s
347
+ * own try/catch) rather than silently dropping it. That roster was already
348
+ * "delivered and discarded" for such a client before this fix (its own bucket
349
+ * key never matched `claude-sdk` either), so nothing regresses; #7756 is about
350
+ * the KNOWN Claude-family names landing in the wrong bucket, not this edge
351
+ * case.
352
+ *
353
+ * `claude-byok` MUST be in `knownTags`, not the residual: `ws-history.js`'s
354
+ * post-auth connect path (`resolveRosterProvider(entry.provider, ...)` at
355
+ * `ws-history.js:928`) tags a byok client's roster `'claude-byok'` exactly,
356
+ * same registry as claude-sdk/cli/tui. A prior revision of this fix instead
357
+ * excluded `claude-byok` from `knownTags` and explicitly skipped it in the
358
+ * residual, reasoning that connect never refreshed a byok client's own
359
+ * bucket either — but that reasoning rested on a stale reading of #7756
360
+ * (`static claudeFamily = false`) that does not match this class. Excluding
361
+ * it here reproduces the EXACT #7756 bug for a fourth provider: the roster is
362
+ * delivered (via the residual, tagged with the reload's own literal) and
363
+ * discarded, because a byok client's bucket key is `'claude-byok'`, not
364
+ * whatever the residual's literal happens to be. Folding it into the same
365
+ * per-tag treatment as claude-cli/claude-tui is what keeps a reload and a
366
+ * reconnect agreeing on a byok session's roster tag, exactly as they do for
367
+ * the other three.
368
+ *
369
+ * A factory rather than an inline closure so the wiring is a single named
370
+ * reference at the call site AND the behaviour is directly executable in a test
371
+ * — the previous inline closure lived inside `startCliServer()`, which no test
372
+ * can run, so the only available check was a source grep over its body.
373
+ *
374
+ * #7895 — the per-message tagging loop itself (the `tagIsDefault` branch, the
375
+ * known-tags set, the residual fallback) now lives in
376
+ * `broadcastRosterPerRecipient` (`./roster-broadcast.js`), shared with
377
+ * `ws-forwarding.js`'s two `available_models` send sites. This function keeps
378
+ * only what's specific to the overlay-reload wiring: the per-message reload
379
+ * log line and adapting `wsServer._broadcast` to the shared `(msg, filter)`
380
+ * broadcast shape.
381
+ *
382
+ * @param {{ wsServer: { _broadcast: Function }, sessionManager: object, logger?: object, defaultProvider?: string|null }} deps
383
+ * `defaultProvider` is this daemon's resolved default (`config.provider ||
384
+ * DEFAULT_PROVIDER`) — the same value `ws-history.js` feeds
385
+ * `resolveRosterProvider` from `billingCanary.defaultProvider`. Omitted (as
386
+ * every existing caller/test does), `resolveRosterProvider` falls back to
387
+ * `DEFAULT_PROVIDER` itself, which is a true statement only when the daemon
388
+ * was not started with an explicit `--provider` override.
389
+ * @returns {(reload: object) => void}
390
+ */
391
+ export function createOverlayReloadBroadcaster({ wsServer, sessionManager, logger = log, defaultProvider = null }) {
392
+ return (reload) => {
393
+ for (const message of buildOverlayReloadBroadcasts(reload)) {
394
+ logger.info(`Models overlay reloaded (${message.provider}): ${message.models.map((m) => m.id).join(', ')}`)
395
+ broadcastRosterPerRecipient({
396
+ broadcast: (msg, filter) => wsServer._broadcast(msg, filter),
397
+ sessionManager,
398
+ defaultProvider,
399
+ message,
400
+ })
401
+ }
402
+ }
403
+ }
404
+
135
405
  /**
136
406
  * Run `environmentManager.reconnect()` and log a startup summary (#3464).
137
407
  *
@@ -305,6 +575,99 @@ export function resolveStartupTimeouts(config = {}, log = { warn: () => {} }) {
305
575
  }
306
576
  }
307
577
 
578
+ /**
579
+ * Resolve runtime-skill policy once for both SessionManager construction and
580
+ * startup diagnostics (#7834). Keeping the effective values beside their
581
+ * diagnostic source prevents startup from reporting a policy that was not
582
+ * actually forwarded to provider sessions.
583
+ *
584
+ * Omitted values preserve the documented permissive/no-trust defaults.
585
+ * An explicitly malformed allowlist throws before SessionManager construction:
586
+ * `null` is the loader's permissive sentinel, so falling back to it would fail
587
+ * open on the supervised child's independent config re-read. Unknown trust
588
+ * modes remain disabled and are called out as rejected in diagnostics.
589
+ *
590
+ * @param {object} config merged daemon config
591
+ * @returns {{
592
+ * sessionManagerOptions: {
593
+ * maxSkillBytes: number|null,
594
+ * maxTotalSkillBytes: number|null,
595
+ * providerSkillAllowlist: object|null,
596
+ * trustMismatchMode: 'warn'|'block'|null,
597
+ * },
598
+ * diagnostics: {
599
+ * allowlist: { effective: 'configured'|'disabled', source: 'config'|'default'|'rejected config', providerCount: number },
600
+ * trust: { effective: 'warn'|'block'|'disabled', source: 'config'|'default'|'rejected config' },
601
+ * },
602
+ * }}
603
+ */
604
+ export function resolveStartupSkillPolicy(config = {}) {
605
+ const hasAllowlist = Object.prototype.hasOwnProperty.call(config, 'providerSkillAllowlist')
606
+ const allowlist = config.providerSkillAllowlist
607
+ const allowlistIsValid = allowlist !== null
608
+ && typeof allowlist === 'object'
609
+ && !Array.isArray(allowlist)
610
+ if (hasAllowlist && !allowlistIsValid) {
611
+ const error = new TypeError('Runtime skills: allowlist=rejected (source: config; expected object)')
612
+ error.code = 'INVALID_PROVIDER_SKILL_ALLOWLIST'
613
+ throw error
614
+ }
615
+
616
+ const hasTrustMode = Object.prototype.hasOwnProperty.call(config, 'trustMismatchMode')
617
+ const trustMode = config.trustMismatchMode
618
+ const trustModeIsValid = trustMode === 'warn' || trustMode === 'block'
619
+
620
+ return {
621
+ sessionManagerOptions: {
622
+ // Keep byte budgets in this builder too: all runtime-skill startup
623
+ // options now cross the daemon boundary through one production seam.
624
+ maxSkillBytes: Number.isFinite(config.maxSkillBytes) ? config.maxSkillBytes : null,
625
+ maxTotalSkillBytes: Number.isFinite(config.maxTotalSkillBytes) ? config.maxTotalSkillBytes : null,
626
+ providerSkillAllowlist: allowlistIsValid ? allowlist : null,
627
+ trustMismatchMode: trustModeIsValid ? trustMode : null,
628
+ },
629
+ diagnostics: {
630
+ allowlist: {
631
+ effective: allowlistIsValid ? 'configured' : 'disabled',
632
+ source: allowlistIsValid ? 'config' : 'default',
633
+ providerCount: allowlistIsValid ? Object.keys(allowlist).length : 0,
634
+ },
635
+ trust: {
636
+ effective: trustModeIsValid ? trustMode : 'disabled',
637
+ source: trustModeIsValid ? 'config' : (hasTrustMode ? 'rejected config' : 'default'),
638
+ },
639
+ },
640
+ }
641
+ }
642
+
643
+ /** Format the content-free operator diagnostic for resolved skill policy. */
644
+ export function formatStartupSkillPolicyDiagnostic(diagnostics) {
645
+ const allowlist = diagnostics?.allowlist || { effective: 'disabled', source: 'default', providerCount: 0 }
646
+ const trust = diagnostics?.trust || { effective: 'disabled', source: 'default' }
647
+ const providers = allowlist.effective === 'configured'
648
+ ? `, providers: ${allowlist.providerCount}`
649
+ : ''
650
+ return `Runtime skills: allowlist=${allowlist.effective} (source: ${allowlist.source}${providers}); trust=${trust.effective} (source: ${trust.source})`
651
+ }
652
+
653
+ /**
654
+ * Construct the daemon SessionManager with its resolved runtime-skill policy.
655
+ * Tests use this same production factory so removing the final constructor
656
+ * forwarding cannot leave a resolver-only test green (#7834).
657
+ *
658
+ * @param {object} config merged daemon config
659
+ * @param {object} sessionManagerOptions remaining daemon constructor options
660
+ * @returns {{ sessionManager: SessionManager, startupSkillPolicy: object }}
661
+ */
662
+ export function createDaemonSessionManager(config, sessionManagerOptions) {
663
+ const startupSkillPolicy = resolveStartupSkillPolicy(config)
664
+ const sessionManager = new SessionManager({
665
+ ...sessionManagerOptions,
666
+ ...startupSkillPolicy.sessionManagerOptions,
667
+ })
668
+ return { sessionManager, startupSkillPolicy }
669
+ }
670
+
308
671
  export function initFileLoggingFromConfig(config = {}) {
309
672
  if (process.env.CHROXY_NO_FILE_LOGGING === '1') {
310
673
  return { enabled: false, level: 'info', logDir: null }
@@ -405,11 +768,12 @@ export async function emergencyCleanup({
405
768
  // String(err?.message || err) so a non-Error throw (e.g. a Symbol) can't make
406
769
  // the log-formatting itself throw and break this best-effort teardown chain.
407
770
  try { if (tunnel) await tunnel.stop() } catch (err) { logger?.warn?.(`emergencyCleanup: tunnel.stop failed: ${String(err?.message || err)}`) }
408
- try { wsServer?.close() } catch (err) { logger?.warn?.(`emergencyCleanup: wsServer.close failed: ${String(err?.message || err)}`) }
771
+ try { await wsServer?.close() } catch (err) { logger?.warn?.(`emergencyCleanup: wsServer.close failed: ${String(err?.message || err)}`) }
409
772
  try { mdnsService?.stop?.() } catch {}
410
773
  try { bonjourInstance?.destroy?.() } catch {}
411
774
  try { tokenManager?.destroy() } catch {}
412
775
  try { pairingManager?.destroy() } catch {}
776
+ try { boundedRegex.close() } catch {}
413
777
  try { sessionManager?.destroyAll() } catch (err) { logger?.warn?.(`emergencyCleanup: destroyAll failed: ${String(err?.message || err)}`) }
414
778
  }
415
779
 
@@ -433,6 +797,7 @@ export function emergencyCleanupSync({ kind, tunnel, wsServer, sessionManager, l
433
797
  try { sessionManager?.serializeState() } catch (serializeErr) {
434
798
  logger?.warn?.(`Failed to serialize state during ${kind}: ${String(serializeErr?.stack || serializeErr)}`)
435
799
  }
800
+ try { boundedRegex.close() } catch {}
436
801
  try { sessionManager?.destroyAll() } catch {}
437
802
  try { wsServer?.close() } catch {}
438
803
  // NO await — see the invariant above.
@@ -440,13 +805,139 @@ export function emergencyCleanupSync({ kind, tunnel, wsServer, sessionManager, l
440
805
  try { removeConnectionInfo() } catch {}
441
806
  }
442
807
 
808
+ // #8029: the set of typed errors `runProviderPreflight` (via
809
+ // SessionManager#createSession) throws for a provider that isn't usable —
810
+ // binary missing/quarantined/unsupported/wrong-provenance/wrong-version, or
811
+ // missing credentials. Kept as an explicit instanceof list (not a
812
+ // duck-typed `err.code` check) and exposed through `isProviderPreflightError`
813
+ // below, so a test can prove the startup
814
+ // default-session guard below only swallows THIS class of failure and lets
815
+ // anything else — a bug, an out-of-memory error, a corrupted state file —
816
+ // still crash loudly instead of being silently absorbed by a broadened net.
817
+ const PROVIDER_PREFLIGHT_ERROR_CLASSES = [
818
+ ProviderBinaryNotFoundError,
819
+ ProviderBinaryQuarantinedError,
820
+ ProviderBinaryProvenanceError,
821
+ ProviderBinaryUnsupportedError,
822
+ ProviderBinaryVersionError,
823
+ ProviderCredentialMissingError,
824
+ ]
825
+
826
+ export function isProviderPreflightError(err) {
827
+ return PROVIDER_PREFLIGHT_ERROR_CLASSES.some((ErrorClass) => err instanceof ErrorClass)
828
+ }
829
+
830
+ /**
831
+ * Create the startup default session, or return the already-restored one.
832
+ * Extracted (like `createDaemonSessionManager` above) so the #8029 preflight
833
+ * guard is unit-testable without driving the rest of `startCliServer`'s
834
+ * WS-server/tunnel/push-manager setup.
835
+ *
836
+ * `createSession` runs `runProviderPreflight` for the configured default
837
+ * provider, which throws a typed error (binary missing/quarantined/
838
+ * unsupported/wrong-provenance/wrong-version, or missing credentials) when
839
+ * the provider isn't usable. Without `--skip-checks`, `chroxy start`'s
840
+ * doctor pass (server-cmd.js) catches the same class of failure first and
841
+ * refuses with a readable one-line message before any server state exists.
842
+ * `--skip-checks` reaches this point instead. `restoreState()` (called just
843
+ * before this) already keeps the daemon running when a RESTORED session fails
844
+ * to come back (it catches any restore failure, broader than this guard), so
845
+ * one broken provider does not take the whole process down. This does the
846
+ * same, more narrowly, for the startup default session: log the same readable message and
847
+ * keep starting with no default session, rather than letting an uncaught
848
+ * exception kill a daemon that (a) may serve other, working providers per
849
+ * session and (b) is often the only way to reach this machine remotely to
850
+ * fix the credential/binary problem in the first place.
851
+ *
852
+ * The returned `defaultSessionId` may be `null` — `ws-server.js` already
853
+ * coalesces that (`this.defaultSessionId = defaultSessionId || null`) and
854
+ * every client (dashboard's WelcomeScreen, the app's "No active sessions"
855
+ * states) already renders a clean zero-session state.
856
+ *
857
+ * Anything NOT one of the typed preflight errors is an unexpected failure
858
+ * and must still surface (uncaught), same as before this guard existed.
859
+ *
860
+ * @param {{ sessionManager: SessionManager, defaultSessionId: string|null, logger?: { warn: Function } }} args
861
+ * @returns {string|null}
862
+ */
863
+ export function createDefaultSessionIfNeeded({ sessionManager, defaultSessionId, logger = log }) {
864
+ if (defaultSessionId) return defaultSessionId
865
+ try {
866
+ return sessionManager.createSession({ name: 'Default' })
867
+ } catch (err) {
868
+ if (!isProviderPreflightError(err)) throw err
869
+ logger.warn(`✗ default session [${err.code}]: ${err.message}`)
870
+ logger.warn('Starting with no default session — fix the provider (see the message above) and create a session from the app or dashboard, or restart once resolved.')
871
+ return null
872
+ }
873
+ }
874
+
443
875
  export async function startCliServer(config) {
876
+ applyCodexBinaryConfig(config)
444
877
  // Enable JSON log format if configured
445
878
  if (config.logFormat === 'json') {
446
879
  setJsonMode(true)
447
880
  }
448
881
 
449
- initFileLoggingFromConfig(config)
882
+ const fileLogging = initFileLoggingFromConfig(config)
883
+
884
+ // #8270: say so once at startup when the claude data-dir override is unusable.
885
+ warnIfClaudeConfigDirUnusable()
886
+
887
+ // #7162: under a service manager (CHROXY_DAEMON=1) the console streams are
888
+ // captured to files nothing rotates (launchd StandardOutPath et al); the
889
+ // logger's console mirror is how the stdout capture reached 32MB in a
890
+ // month. With the file log live it is authoritative, so quiet the
891
+ // info/debug/audit mirror — warn/error keep flowing to chroxy-stderr.log,
892
+ // and write() falls back to the console for any line whose file append
893
+ // fails. Only when file logging actually initialized: with no file log,
894
+ // the capture is the only record and must stay verbose. Capture BOUNDING
895
+ // deliberately does NOT happen here — startCliServer re-runs in every
896
+ // supervised child restart, and the cap is safe exactly once per service
897
+ // boot (see the `start` action in cli/server-cmd.js).
898
+ if (process.env.CHROXY_DAEMON === '1' && fileLogging.enabled) {
899
+ setConsoleQuiet(true)
900
+ }
901
+
902
+ // #6633: publish Chroxy's host identity into this process's environment so the
903
+ // in-process SDK provider's Bash tools inherit it (subprocess providers get it
904
+ // via buildSpawnEnv). Computed + authoritative — a session can read
905
+ // $CHROXY_HOST_VERSION / _GIT_SHA / _CHANNEL to confirm the exact running build.
906
+ Object.assign(process.env, getChroxyHostEnv())
907
+
908
+ // #8151 (C3) — probe once, before the WS server can accept any real
909
+ // connection, so the very first `list_providers` / `auth_bootstrap` a
910
+ // client sees already reflects reality (claude-tui greyed out when
911
+ // node-pty can't load here, e.g. the official Docker image). Cheap either
912
+ // way (a failed resolution is a fast ENOENT-class failure) and cached for
913
+ // the rest of the process by node-pty-probe.js.
914
+ await probeNodePtyAvailable()
915
+
916
+ // #7240 — state stranded at ~/.chroxy by a CHROXY_CONFIG_DIR relocation.
917
+ //
918
+ // This runs HERE, near the top of startCliServer, and the placement is the
919
+ // point. #7052 logs the resolved root, but that line sits ~500 lines further
920
+ // down — past the `No API token configured` exit below. In the sharpest
921
+ // failure (stranded config.json on a keychain-less host) the daemon exits
922
+ // before it ever says which root it opened, so the operator sees a token
923
+ // error with no hint that a relocation caused it. Warning first is what makes
924
+ // the diagnosis reachable.
925
+ //
926
+ // Detection only — the copy is opt-in via `chroxy config-dir migrate`.
927
+ // Best-effort, like maybeEncryptCredentialsAtRest: never blocks boot.
928
+ //
929
+ // #7244 — an operator running a deliberate second root can acknowledge the
930
+ // CURRENT set with `chroxy config-dir ack`. Only the warning is filtered:
931
+ // `strandedState` stays the raw detection, so the missing-token exit below
932
+ // still names an unmoved config.json even when it was acknowledged. An entry
933
+ // that appears after the acknowledgement is not in the snapshot and warns.
934
+ let strandedState = null
935
+ try {
936
+ strandedState = detectStrandedState()
937
+ for (const line of startupStrandedWarning(strandedState)) log.warn(line)
938
+ } catch (err) {
939
+ log.warn(`Stranded config-dir state check failed: ${err.message}`)
940
+ }
450
941
 
451
942
  const PORT = config.port || parseInt(process.env.PORT || '8765', 10)
452
943
  const NO_AUTH = !!config.noAuth
@@ -456,7 +947,7 @@ export async function startCliServer(config) {
456
947
 
457
948
  // Migrate plaintext token to keychain and remove from config file
458
949
  if (!NO_AUTH && config.apiToken && isKeychainAvailable()) {
459
- const configFile = join(homedir(), '.chroxy', 'config.json')
950
+ const configFile = configPath('config.json')
460
951
  const { migrated } = migrateToken(config)
461
952
  // Remove plaintext token from config file (whether newly migrated or already in keychain)
462
953
  const keychainToken = getToken()
@@ -479,7 +970,12 @@ export async function startCliServer(config) {
479
970
  }
480
971
 
481
972
  if (!NO_AUTH && !API_TOKEN) {
482
- console.error('[!] No API token configured. Run \'npx chroxy init\' first.') // intentional user-facing output
973
+ // #7240 — when config.json is sitting at ~/.chroxy and the daemon is reading
974
+ // a relocated root, `chroxy init` is the WRONG advice: it mints a brand new
975
+ // token and forces every paired device to re-pair. Name the real cause.
976
+ // The wording lives in missingTokenAdvice so a test can pin it; an
977
+ // acknowledgement (#7244) does not change it.
978
+ for (const line of missingTokenAdvice(strandedState)) console.error(line) // intentional user-facing output
483
979
  process.exit(1)
484
980
  }
485
981
 
@@ -492,7 +988,12 @@ export async function startCliServer(config) {
492
988
  log.warn(`Credentials at-rest encryption check failed: ${err.message}`)
493
989
  }
494
990
 
495
- const banner = buildServerBanner({ version: SERVER_VERSION, provider: config.provider })
991
+ // #8189: pass the daemon's actually-resolved default through the shared
992
+ // helper rather than the raw `config.provider` field — `buildServerBanner`
993
+ // itself still floors to DEFAULT_PROVIDER internally (its own unit tests
994
+ // call it directly with no provider at all), so this is belt-and-suspenders
995
+ // against the two ever drifting apart, not a behavior change today.
996
+ const banner = buildServerBanner({ version: SERVER_VERSION, provider: resolveDaemonDefaultProvider(config) })
496
997
  const pad = Math.max(0, 38 - banner.length)
497
998
  const left = Math.floor(pad / 2)
498
999
  const right = pad - left
@@ -532,8 +1033,13 @@ export async function startCliServer(config) {
532
1033
  // talks chat-completions via the Anthropic↔OpenAI shim. Registered right
533
1034
  // after the Anthropic-compatible block (collision-checked against it).
534
1035
  registerOpenAiCompatibleProviders(config)
1036
+ // #7319: register config-driven ACP (Agent Client Protocol) agents from
1037
+ // `providers.acp` — one registered provider per configured agent, spawned
1038
+ // over stdio. Permissions ship denied-by-default (#7320 wires the real
1039
+ // bridge). Collision-checked against every provider registered above.
1040
+ registerAcpProviders(config)
535
1041
 
536
- const providerType = config.provider || DEFAULT_PROVIDER
1042
+ const providerType = resolveDaemonDefaultProvider(config)
537
1043
 
538
1044
  // Warm the models registry from disk cache so the picker is populated before
539
1045
  // any SDK session fires supportedModels(). Routed through the ACTIVE provider's
@@ -631,14 +1137,40 @@ export async function startCliServer(config) {
631
1137
  // a single warning here at boot (not three on each tunable).
632
1138
  const startupTimeouts = resolveStartupTimeouts(config, log)
633
1139
 
1140
+ // #7601: wire the proactive container-liveness poll's inspect seam. A dedicated
1141
+ // DockerBackend (a stateless docker-CLI wrapper — same shape server-cli already
1142
+ // constructs for the compose sweep above) inspects each live containerized
1143
+ // session's container; `inspectContainerLiveness` classifies a rejection so a
1144
+ // Docker-daemon outage can't false-surface a vanish across every session at
1145
+ // once. Safe to wire unconditionally: the poll is a no-op when no containerized
1146
+ // session exists, and docker-cli/docker-sdk sessions can be created even with
1147
+ // the container-environments feature off.
1148
+ const { DockerBackend: LivenessDockerBackend } = await import('./environments/backends/docker.js')
1149
+ const { inspectContainerLiveness } = await import('./docker-session.js')
1150
+ const livenessBackend = new LivenessDockerBackend()
1151
+ const containerInspect = (containerId) =>
1152
+ inspectContainerLiveness((cid) => livenessBackend.getEnvironmentStatus(cid), containerId)
1153
+
634
1154
  // 1. Create session manager
635
- const sessionManager = new SessionManager({
1155
+ // (#8967 — registered right after construction below, so a live Claude model
1156
+ // refresh keeps a row a running session is still on instead of dropping it.)
1157
+ const { sessionManager, startupSkillPolicy } = createDaemonSessionManager(config, {
636
1158
  maxSessions: config.maxSessions || 5,
637
1159
  port: PORT,
638
1160
  apiToken: API_TOKEN,
639
1161
  defaultCwd: config.cwd || (isWithinHome(process.cwd()) ? process.cwd() : homedir()),
640
1162
  defaultModel: config.model || null,
641
1163
  defaultPermissionMode: 'approve',
1164
+ // #7552: so a session created with an `environmentId` is TAGGED onto that
1165
+ // environment for its lifetime (and untagged on teardown). Null when
1166
+ // container environments are off — the block above only constructs one when
1167
+ // the feature is enabled — and every use inside SessionManager is
1168
+ // optional-chained. Ordering matters and already holds: the manager is
1169
+ // constructed AND `reconnect()`ed (which clears every stale session tag from
1170
+ // the previous process) above, before this line runs.
1171
+ environmentManager,
1172
+ // #7601: the proactive container-liveness poll inspect seam (see above).
1173
+ containerInspect,
642
1174
  // #5859 (audit P1-7): reclaim orphaned chroxy session worktrees at boot when
643
1175
  // the operator opted into worktree auto-reaping. Clean-tree-guarded.
644
1176
  sweepOrphanWorktrees: config.worktreeGc?.autoReap === true,
@@ -658,7 +1190,14 @@ export async function startCliServer(config) {
658
1190
  // API-valid model id without a release). Empty Set unless the operator set
659
1191
  // config.providers.allowAnyModel.
660
1192
  allowAnyModelProviders: getAllowAnyModelProviders(config),
1193
+ // #6858: opt-in provenance verification for spawned provider binaries. Both
1194
+ // OFF by default (behaviour identical to #6708). `mode` drives the SHA-256
1195
+ // pin ledger (warn surfaces a swap + allows; block refuses the spawn);
1196
+ // `signatureGate` toggles the macOS `spctl` notarization gate.
1197
+ binaryProvenanceMode: resolveBinaryProvenanceMode(config),
1198
+ binarySignatureGate: isBinarySignatureGateEnabled(config),
661
1199
  providerType,
1200
+ agentConnections: config.agentConnections || [],
662
1201
  maxToolInput: config.maxToolInput || null,
663
1202
  transforms: config.transforms || [],
664
1203
  sessionTimeout: config.sessionTimeout || null,
@@ -666,7 +1205,22 @@ export async function startCliServer(config) {
666
1205
  costBudget: config.costBudget || null,
667
1206
  // #5665: monthly programmatic-credit budget meter config.
668
1207
  billing: config.billing || null,
1208
+ // Session archive retention (`sessionArchive` config block); the archive
1209
+ // directory itself sits next to the session-state file.
1210
+ sessionArchive: config.sessionArchive || null,
669
1211
  maxMessages: config.maxMessages || config.maxHistory || null,
1212
+ // #6764: opt-in semantic session titles. Off unless the operator set
1213
+ // features.semanticTitles:true (or CHROXY_SEMANTIC_TITLES=1). The title model
1214
+ // defaults to a cheap Haiku alias; summarize.model / CHROXY_SEMANTIC_TITLES_MODEL
1215
+ // override it (resolveSemanticTitleModel). When off, the historical truncation
1216
+ // label is used unchanged.
1217
+ semanticTitlesEnabled: isSemanticTitlesEnabled(config),
1218
+ semanticTitleModel: resolveSemanticTitleModel(config),
1219
+ // #6764: hard timeout (ms) for the fire-and-forget one-shot title call so a
1220
+ // stalled provider aborts the subprocess and falls open to the truncation
1221
+ // label instead of leaking a never-settling promise. Env / summarize.titleTimeoutMs
1222
+ // override; default ~15s (resolveSemanticTitleTimeoutMs).
1223
+ semanticTitleTimeoutMs: resolveSemanticTitleTimeoutMs(config),
670
1224
  // #3749 / #3884 / #3899: SOFT-warning inactivity timeout (ms). null = BaseSession default (30 min).
671
1225
  // #3899: HARD-cap inactivity timeout (ms). null = BaseSession default (2h).
672
1226
  // #4467: stream-stall recovery (ms). null = BaseSession default (5min).
@@ -696,10 +1250,10 @@ export async function startCliServer(config) {
696
1250
  // over-24h operator value falls back to null here so byok-mcp-client
697
1251
  // applies its default (and the operator gets a warn log).
698
1252
  mcpToolCallTimeoutMs: startupTimeouts.mcpToolCallTimeoutMs,
699
- // Skills size budgets (#3202). null = use loader defaults (32KB / 256KB).
700
- maxSkillBytes: Number.isFinite(config.maxSkillBytes) ? config.maxSkillBytes : null,
701
- maxTotalSkillBytes: Number.isFinite(config.maxTotalSkillBytes) ? config.maxTotalSkillBytes : null,
702
1253
  })
1254
+ // #8303: a blank New Session cwd inherits this without the explicit-cwd check.
1255
+ const defaultCwdWarning = defaultCwdAdvisory(sessionManager.defaultCwd, config)
1256
+ if (defaultCwdWarning) log.warn(defaultCwdWarning)
703
1257
 
704
1258
  // #3749 / #3899: surface the effective inactivity timeouts at startup so
705
1259
  // operators can verify their config overrides took effect.
@@ -712,6 +1266,9 @@ export async function startCliServer(config) {
712
1266
  ? 'disabled'
713
1267
  : `${formatIdleDuration(effectiveStreamStallTimeoutMs)} (${effectiveStreamStallTimeoutMs}ms)`
714
1268
  log.info(`Inactivity soft-warning: ${formatIdleDuration(effectiveResultTimeoutMs)} (${effectiveResultTimeoutMs}ms); hard-cap: ${formatIdleDuration(effectiveHardTimeoutMs)} (${effectiveHardTimeoutMs}ms); stream-stall: ${stallLabel}`)
1269
+ log.info(formatStartupSkillPolicyDiagnostic(startupSkillPolicy.diagnostics))
1270
+
1271
+ setInUseModelsProvider(() => sessionManager.listSessions().map((s) => s.model).filter(Boolean))
715
1272
 
716
1273
  // 2. Try restoring session state from a previous instance
717
1274
  let defaultSessionId
@@ -721,9 +1278,7 @@ export async function startCliServer(config) {
721
1278
  }
722
1279
 
723
1280
  // 3. Create default session if no restore
724
- if (!defaultSessionId) {
725
- defaultSessionId = sessionManager.createSession({ name: 'Default' })
726
- }
1281
+ defaultSessionId = createDefaultSessionIfNeeded({ sessionManager, defaultSessionId, logger: log })
727
1282
 
728
1283
  let wsServer
729
1284
 
@@ -758,12 +1313,63 @@ export async function startCliServer(config) {
758
1313
  }
759
1314
  })
760
1315
 
1316
+ // #6791: read + execute the user's OWN Claude Code statusLine script and
1317
+ // surface its stdout. The command is ONLY ever the one in the user's own
1318
+ // settings.json (~/.claude / the project's .claude) — never client-supplied —
1319
+ // and every execution is bounded by a timeout + stdout cap + secret-stripped
1320
+ // env (see statusline.js). Inactive (silent no-op) when no statusLine is
1321
+ // configured. Session-scoped broadcast so one session's status never fans out
1322
+ // to clients viewing another.
1323
+ const statusLineManager = new StatusLineManager()
1324
+ const buildStatuslineContext = (sessionId) => {
1325
+ const entry = sessionManager.getSession(sessionId)
1326
+ if (!entry) return null
1327
+ const usage = entry.cumulativeUsage || {}
1328
+ const cost = {}
1329
+ if (Number.isFinite(usage.costUsd)) cost.totalCostUsd = usage.costUsd
1330
+ return {
1331
+ sessionId,
1332
+ sessionName: entry.name || null,
1333
+ cwd: entry.cwd,
1334
+ projectDir: entry.worktreeRepoDir || entry.cwd,
1335
+ model: { id: entry.session?.model || entry.session?.bootedModel || null },
1336
+ cost,
1337
+ }
1338
+ }
1339
+ statusLineManager.on('output', ({ sessionId, text, active, truncated }) => {
1340
+ // wsServer is assigned further down; a periodic tick can fire first.
1341
+ if (!wsServer) return
1342
+ wsServer._broadcastToSession(sessionId, { type: 'statusline_output', text, active, truncated })
1343
+ })
1344
+ sessionManager.on('session_created', ({ sessionId }) => {
1345
+ statusLineManager.startSession(sessionId, () => buildStatuslineContext(sessionId))
1346
+ })
1347
+ sessionManager.on('session_destroyed', ({ sessionId }) => {
1348
+ // Clears the session's periodic timer. On graceful shutdown, destroyAll()
1349
+ // cascades a session_destroyed per session, so every timer is cleared here
1350
+ // (and all timers are .unref()'d, so they never block process exit anyway).
1351
+ statusLineManager.stopSession(sessionId)
1352
+ })
1353
+ // Turn-boundary refresh for immediacy (mirrors Claude Code's "new assistant
1354
+ // message" trigger); the periodic loop in StatusLineManager covers the rest.
1355
+ sessionManager.on('session_event', ({ sessionId, event }) => {
1356
+ if (event !== 'result') return
1357
+ const ctx = buildStatuslineContext(sessionId)
1358
+ if (ctx) statusLineManager.refresh(sessionId, ctx)
1359
+ })
1360
+ // NOTE: session_created above fires only for FUTURE sessions; the default
1361
+ // session (and any restored ones) were created before these listeners
1362
+ // registered, so their loops are started AFTER wsServer is constructed (see
1363
+ // below) — starting them here would let the first tick's `output` fire while
1364
+ // `wsServer` is still null, and the manager's dedupe would then swallow the
1365
+ // (dropped) broadcast until the script's text next changed.
1366
+
761
1367
  // 3. Create push notification manager, token manager, and WebSocket server
762
1368
  const pushManager = new PushManager({
763
- storagePath: join(homedir(), '.chroxy', 'push-tokens.json'),
1369
+ storagePath: configPath('push-tokens.json'),
764
1370
  // #4541: notification preferences persistence. Co-located in
765
1371
  // ~/.chroxy alongside push-tokens.json so cleanup is one step.
766
- prefsPath: join(homedir(), '.chroxy', 'notification-prefs.json'),
1372
+ prefsPath: configPath('notification-prefs.json'),
767
1373
  // #5413 Phase 2: Discord status-embed sink. Off by default — only
768
1374
  // active when a webhook URL resolves from CHROXY_DISCORD_WEBHOOK_URL
769
1375
  // or ~/.chroxy/credentials.json (0600). Non-secret knobs (bot name,
@@ -772,10 +1378,10 @@ export async function startCliServer(config) {
772
1378
  // (message ids, current state) persists alongside the other
773
1379
  // notification state in ~/.chroxy.
774
1380
  discord: {
775
- statePath: join(homedir(), '.chroxy', 'discord-webhook-state.json'),
1381
+ statePath: configPath('discord-webhook-state.json'),
776
1382
  // #5828: the billing-alert sink keeps its own state file, separate from
777
1383
  // the per-project status store above.
778
- billingStatePath: join(homedir(), '.chroxy', 'discord-billing-state.json'),
1384
+ billingStatePath: configPath('discord-billing-state.json'),
779
1385
  ...(config.notifications?.discord || {}),
780
1386
  },
781
1387
  })
@@ -799,32 +1405,13 @@ export async function startCliServer(config) {
799
1405
  })
800
1406
  pushNotificationHandler.start()
801
1407
 
802
- const configFile = join(homedir(), '.chroxy', 'config.json')
1408
+ const configFile = configPath('config.json')
803
1409
  const tokenManager = NO_AUTH ? null : new TokenManager({
804
1410
  token: API_TOKEN,
805
1411
  tokenExpiry: config.tokenExpiry || null,
806
- onPersist: (newToken) => {
807
- const persistToFile = () => {
808
- const raw = existsSync(configFile) ? readFileSync(configFile, 'utf-8') : '{}'
809
- const cfg = JSON.parse(raw)
810
- cfg.apiToken = newToken
811
- writeFileRestricted(configFile, JSON.stringify(cfg, null, 2))
812
- }
813
- try {
814
- if (isKeychainAvailable()) {
815
- try {
816
- setToken(newToken)
817
- } catch {
818
- // Keychain write failed — fall back to config file
819
- persistToFile()
820
- }
821
- } else {
822
- persistToFile()
823
- }
824
- } catch (err) {
825
- log.error(`Failed to persist token: ${err.message}`)
826
- }
827
- },
1412
+ // #7055 — the callback body lives in `buildTokenPersistCallback` (above) so
1413
+ // both its limbs are testable; as an inline closure nothing could drive it.
1414
+ onPersist: buildTokenPersistCallback({ configFile }),
828
1415
  })
829
1416
  if (tokenManager) tokenManager.start()
830
1417
 
@@ -918,7 +1505,13 @@ export async function startCliServer(config) {
918
1505
  )
919
1506
  // #6598 — persist paired tokens across restarts (encrypted at rest). Honour a
920
1507
  // CHROXY_CONFIG_DIR override so it sits next to config.json / credentials.json.
921
- const chroxyDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
1508
+ const chroxyDir = configDir()
1509
+ // #7052 — state the resolved root once at startup. Every persistent path the
1510
+ // daemon touches now hangs off it, so when an operator relocates the dir and
1511
+ // finds empty trust stores or a missing token, this line is the one thing
1512
+ // that tells them WHICH root the daemon actually opened. Logged
1513
+ // unconditionally: knowing it is `~/.chroxy` is exactly as useful.
1514
+ log.info(`Config/state root: ${chroxyDir}${process.env.CHROXY_CONFIG_DIR ? ' (from CHROXY_CONFIG_DIR)' : ''}`)
922
1515
  const pairingManager = NO_AUTH ? null : new PairingManager({
923
1516
  ttlMs: 60_000,
924
1517
  autoRefresh: true,
@@ -927,10 +1520,61 @@ export async function startCliServer(config) {
927
1520
  sessionTokenStore: createSessionTokenStore({ dir: chroxyDir }),
928
1521
  })
929
1522
 
1523
+ // #6691 (E-4): the orchestration engine (null when the feature is off or if
1524
+ // construction fails — never a throw, so it can't break daemon boot).
1525
+ const orchestrationManager = buildOrchestrationManager({ sessionManager, config, chroxyDir, log })
1526
+
1527
+ // #6865: the headless scheduler engine — fires due scheduled tasks (#6862)
1528
+ // into a session with no client connected. null unless the operator opted in
1529
+ // (`features.scheduler` / CHROXY_ENABLE_SCHEDULER=1), so a default daemon arms
1530
+ // no timers and spawns nothing.
1531
+ const schedulerEngine = buildSchedulerEngine({ sessionManager, config, logger: log })
1532
+
1533
+ // #7424 (step 3 of #7344): watch the PR each session opened and announce a CI
1534
+ // run the moment it SETTLES, to both audiences — a `ci_complete` push for the
1535
+ // user's phone, and one typed line into the session's own prompt so the agent
1536
+ // learns it without spending a turn (and a full cached-context re-read)
1537
+ // polling `gh pr checks`.
1538
+ //
1539
+ // ON by default; `sessionCi.watch: false` returns null here. Everything
1540
+ // decidable lives in buildSessionCiWatcher so it is unit-tested rather than
1541
+ // source-grepped.
1542
+ //
1543
+ // Built BEFORE the WsServer (#7427) because the ws handler ctx carries it: the
1544
+ // dashboard's on-demand `session_pr_status_request` survey hands its snapshot
1545
+ // to `observe()`, which ARMS the watch without waiting on the sweep's
1546
+ // five-minute discovery pass.
1547
+ const sessionCiWatcher = buildSessionCiWatcher({ config, sessionManager, pushManager, logger: log })
1548
+ sessionCiWatcher?.start()
1549
+
1550
+ // #8331: the daily-daemon "update ready" banner. Watches the files the idle-only
1551
+ // auto-deploy script leaves in the config dir and answers the dashboard's
1552
+ // Restart now / Postpone. The idle verdict is the SAME function
1553
+ // GET /api/daemon/idle answers from, so the confirm dialog and the script's own
1554
+ // gate cannot disagree. Harmless on a daemon with no deploy script: with no
1555
+ // files there is nothing to report and nothing to act on.
1556
+ const daemonUpdate = new DaemonUpdateStatus({
1557
+ dir: chroxyDir,
1558
+ getIdleState: () => computeDaemonIdleState({
1559
+ sessionManager,
1560
+ getHookPendingPermissionCount: () => wsServer.getHookPendingPermissionCount(),
1561
+ }),
1562
+ })
1563
+ daemonUpdate.start()
1564
+
930
1565
  wsServer = new WsServer({
931
1566
  port: PORT,
932
1567
  apiToken: API_TOKEN,
933
1568
  sessionManager,
1569
+ orchestrationManager,
1570
+ // #6871: nullable — null whenever the scheduled-execution gate is closed (the
1571
+ // default). The scheduled-tasks handlers report that as "not armed".
1572
+ schedulerEngine,
1573
+ // #7427: nullable — null when `sessionCi.watch` is off. Handed to handlers
1574
+ // only; server-cli owns its start() above and ServerOrchestrator its stop().
1575
+ sessionCiWatcher,
1576
+ // #8331: closed by wsServer.close().
1577
+ daemonUpdate,
934
1578
  defaultSessionId,
935
1579
  authRequired: !NO_AUTH,
936
1580
  pushManager,
@@ -952,9 +1596,24 @@ export async function startCliServer(config) {
952
1596
  // enforce the 2026-04-11 audit blocker 1 workspace allowlist.
953
1597
  config,
954
1598
  })
1599
+ // #6791: now that wsServer exists, start statusLine loops for the sessions
1600
+ // that already existed at boot (the default + any restored). session_created
1601
+ // covers every FUTURE session; startSession is idempotent so no double-start.
1602
+ for (const s of sessionManager.listSessions()) {
1603
+ if (s?.sessionId) statusLineManager.startSession(s.sessionId, () => buildStatuslineContext(s.sessionId))
1604
+ }
955
1605
  // Resolve the bind address. --no-auth forces loopback; otherwise an explicit
956
1606
  // config.host (e.g. --host 127.0.0.1) binds that interface with auth still
957
1607
  // on, and the default (undefined) binds 0.0.0.0 as before.
1608
+ // #6691 (E-4): forward engine run deltas to host-level (unbound) dashboard
1609
+ // clients. The manager already projects each delta to the wire shape; the
1610
+ // WsServer only routes it. Guarded so a broadcast error never bubbles.
1611
+ if (orchestrationManager) {
1612
+ orchestrationManager.on('run_delta', (delta) => {
1613
+ try { wsServer._broadcastOrchestrationDelta(delta) } catch (err) { log.warn(`orchestration delta broadcast failed: ${err?.message || err}`) }
1614
+ })
1615
+ }
1616
+
958
1617
  const bindHost = resolveBindHost({ noAuth: NO_AUTH, host: config.host })
959
1618
  // #5356 (visibility layer): one warning when binding non-loopback (the
960
1619
  // default 0.0.0.0 included) — LAN peers can reach the unauthenticated
@@ -966,13 +1625,24 @@ export async function startCliServer(config) {
966
1625
  // #5932: hot-reload the ~/.chroxy/models.json overlay on edit — surfacing a
967
1626
  // new model id (or a label/contextWindow/pricing override) is "a config entry,
968
1627
  // not a code change", so it must not require a daemon restart. On a successful
969
- // reload, re-broadcast `available_models` for the default (Claude) registry so
970
- // connected pickers refresh live. A malformed save is ignored (last-good kept).
1628
+ // reload, re-broadcast `available_models` for every registry the overlay
1629
+ // CHANGED — the default (Claude) one plus each provider-tagged slice (#7722)
1630
+ // — routed so each client only ever receives the roster for the provider its
1631
+ // active session runs on, RE-TAGGED per recipient for the default registry
1632
+ // (#7756) so a claude-cli/claude-tui/claude-byok client's own bucket
1633
+ // refreshes too. A malformed save is ignored (last-good kept).
1634
+ //
1635
+ // #7756: `defaultProvider` mirrors `billingCanaryMonitor`'s own
1636
+ // `getDefaultProvider` below (`resolveDaemonDefaultProvider(config)`) — the
1637
+ // same resolution `ws-history.js` feeds `resolveRosterProvider` via
1638
+ // `billingCanary.defaultProvider` — so a no-session client's roster is
1639
+ // tagged identically whether it arrives on connect or on a reload.
971
1640
  const modelsOverlayWatcher = watchModelsOverlay({
972
- onReload: ({ models, defaultModelId }) => {
973
- log.info(`Models overlay reloaded: ${models.map((m) => m.id).join(', ')}`)
974
- wsServer.broadcast({ type: 'available_models', models, defaultModel: defaultModelId, provider: 'claude-sdk' })
975
- },
1641
+ onReload: createOverlayReloadBroadcaster({
1642
+ wsServer,
1643
+ sessionManager,
1644
+ defaultProvider: resolveDaemonDefaultProvider(config),
1645
+ }),
976
1646
  })
977
1647
 
978
1648
  // #5821 (live wiring): the billing canary. Recomputes the daemon's billing
@@ -992,8 +1662,8 @@ export async function startCliServer(config) {
992
1662
  const egressCheckEnabled = config.billing?.egressCheck === true
993
1663
  const billingCanaryMonitor = new BillingCanaryMonitor({
994
1664
  getSessions: () => sessionManager.listSessions(),
995
- getDefaultProvider: () => config.provider || DEFAULT_PROVIDER,
996
- getApiKeyAuth: () => (config.provider || DEFAULT_PROVIDER) === 'claude-sdk' && Boolean(process.env.ANTHROPIC_API_KEY),
1665
+ getDefaultProvider: () => resolveDaemonDefaultProvider(config),
1666
+ getApiKeyAuth: () => resolveDaemonDefaultProvider(config) === 'claude-sdk' && Boolean(process.env.ANTHROPIC_API_KEY),
997
1667
  broadcast: (msg) => { try { wsServer?.broadcast(msg) } catch { /* best-effort */ } },
998
1668
  logger: log,
999
1669
  resolveEgressIp: egressCheckEnabled ? () => resolvePublicIp() : undefined,
@@ -1044,6 +1714,10 @@ export async function startCliServer(config) {
1044
1714
  // Wire session timeout to WsServer viewer checks
1045
1715
  sessionManager.setActiveViewersFn((sid) => wsServer.hasActiveViewersForSession(sid))
1046
1716
  sessionManager.startSessionTimeouts()
1717
+ // #7601: begin the proactive container-liveness poll (no-op when no
1718
+ // containerInspect seam was wired). Surfaces CONTAINER_VANISHED on an idle
1719
+ // containerized session whose container was stopped/removed externally.
1720
+ sessionManager.startContainerLiveness()
1047
1721
 
1048
1722
  // Advertise via mDNS/Bonjour for local network discovery. Suppressed on a
1049
1723
  // loopback bind and when auth is off — see maybeAdvertiseMdns (#5280).
@@ -1115,6 +1789,15 @@ export async function startCliServer(config) {
1115
1789
  tunnelConfig: config.tunnelConfig,
1116
1790
  tunnelName: config.tunnelName || null,
1117
1791
  tunnelHostname: config.tunnelHostname || null,
1792
+ // #6858: fold cloudflared into the SAME opt-in provenance gate + pin
1793
+ // ledger as the provider binaries. Reuse the SessionManager's ledger
1794
+ // instance so pins are unified across every spawned binary. Off by
1795
+ // default (mode 'off' + gate false) ⇒ the tunnel gate is a no-op.
1796
+ binaryProvenance: {
1797
+ mode: resolveBinaryProvenanceMode(config),
1798
+ signatureGate: isBinarySignatureGateEnabled(config),
1799
+ ledger: sessionManager.binaryProvenanceLedger,
1800
+ },
1118
1801
  },
1119
1802
  wsServer,
1120
1803
  startupDisplay,
@@ -1174,14 +1857,25 @@ export async function startCliServer(config) {
1174
1857
  .catch((err) => log.warn(`worktree auto-reaper failed: ${(err && err.message) || err}`))
1175
1858
  }
1176
1859
 
1177
- // #5323 (WP-5.1) — sweep claude-tui hook-sink dirs left in /tmp by prior
1178
- // crashed processes (a leak on every crash). Safe + unconditional: only dirs
1179
- // whose owner pid is dead are removed, so a live daemon's dirs — including
1180
- // ours — are kept. Fire-and-forget + lazily imported so a non-tui boot pays
1181
- // nothing and a failure never affects startup.
1182
- import('./claude-tui-session.js')
1183
- .then(({ ClaudeTuiSession }) => ClaudeTuiSession.sweepStaleSinkDirs(log))
1184
- .catch((err) => log.warn(`claude-tui sink-dir sweep failed: ${(err && err.message) || err}`))
1860
+ // #7606: orphaned-child reaper — sends SIGKILL to processes a dead session
1861
+ // left behind, reparented to pid 1 inside chroxy's own worktree root (ppid 1
1862
+ // + this uid + cwd under the root + older than minAgeMs). Default ON; the
1863
+ // sweep is a no-op on Windows. Same lazy-import / getter-at-shutdown shape
1864
+ // as the worktree reaper above.
1865
+ let orphanReapTimer = null
1866
+ if (config.orphanReap?.enabled !== false) {
1867
+ import('./orphan-reaper.js')
1868
+ .then(({ startPeriodicOrphanReap }) => { orphanReapTimer = startPeriodicOrphanReap(config, log) })
1869
+ .catch((err) => log.warn(`orphan-reaper failed: ${(err && err.message) || err}`))
1870
+ }
1871
+
1872
+ // #7374 — every provider's stale per-session dirs (claude-tui, claude-cli,
1873
+ // codex app-server, docker-byok — #8047). The body lives in its own module
1874
+ // so the sweep is covered by tests that RUN it; this block used to be
1875
+ // inline and was pinned only by a source grep, which stayed green with the
1876
+ // whole thing behind a false condition. Fire-and-forget: the function never
1877
+ // rejects, and a sweep must never affect startup.
1878
+ sweepStaleProviderDirs(log)
1185
1879
 
1186
1880
  console.log('\nPress Ctrl+C to stop.\n')
1187
1881
 
@@ -1208,8 +1902,12 @@ export async function startCliServer(config) {
1208
1902
  pairingManager,
1209
1903
  pushManager,
1210
1904
  billingCanaryMonitor,
1905
+ sessionCiWatcher,
1906
+ orchestrationManager,
1907
+ schedulerEngine,
1211
1908
  modelsOverlayWatcher,
1212
1909
  getWorktreeReapTimer: () => worktreeReapTimer,
1910
+ getOrphanReapTimer: () => orphanReapTimer,
1213
1911
  emergencyCleanupSync,
1214
1912
  removeConnectionInfo,
1215
1913
  isPoolEnabled,