@chroxy/server 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,1223 @@
1
+ import { SessionManager } from './session-manager.js'
2
+ import { DEFAULT_RESULT_TIMEOUT_MS, DEFAULT_HARD_TIMEOUT_MS, DEFAULT_STREAM_STALL_TIMEOUT_MS } from './base-session.js'
3
+ import { DEFAULT_TOOL_CALL_TIMEOUT_MS } from './byok-mcp-client.js'
4
+ import { formatIdleDuration } from './session-timeout-manager.js'
5
+ import { isOperatorTimeoutInRange } from './duration.js'
6
+ import { WsServer } from './ws-server.js'
7
+ import { BillingCanaryMonitor } from './billing-canary-monitor.js'
8
+ import { resolvePublicIp } from './get-public-ip.js'
9
+ import { createTunnel, parseTunnelArg } from './tunnel/index.js'
10
+ // #5368 slice (c): QUICK_TUNNEL_DNS_SETTLE_MS + TUNNEL_STATUS_MIN_PROTOCOL_VERSION
11
+ // moved to tunnel-lifecycle-handler.js with the tunnel block; createTunnel +
12
+ // waitForTunnel are still passed into the handler.
13
+ import { waitForTunnel } from './tunnel-check.js'
14
+ import { PushManager, settlePush } from './push.js'
15
+ import { ensureIngestSecret } from './event-ingest.js'
16
+ import { PushNotificationHandler } from './server-cli/push-notification-handler.js'
17
+ import { StartupDisplay } from './server-cli/startup-display.js'
18
+ import { TunnelLifecycleHandler } from './server-cli/tunnel-lifecycle-handler.js'
19
+ import { ServerOrchestrator } from './server-cli/server-orchestrator.js'
20
+ import { hostname, homedir } from 'os'
21
+ import { readFileSync, existsSync } from 'fs'
22
+ import { fileURLToPath } from 'url'
23
+ import { dirname, join, relative, sep } from 'path'
24
+ import { createLogger, setJsonMode, initFileLogging } from './logger.js'
25
+
26
+ const log = createLogger('cli')
27
+ // #5368 slice (b): QRCode + writeConnectionInfo moved to startup-display.js with
28
+ // displayQr; only removeConnectionInfo (shutdown) is still used here.
29
+ import { removeConnectionInfo } from './connection-info.js'
30
+ import { TokenManager } from './token-manager.js'
31
+ import { PairingManager } from './pairing.js'
32
+ import { getOrCreateServerIdentity, IdentityUnavailableError, resolveServerRotationCert } from './server-identity.js'
33
+ import { getLanIp } from './lan-ip.js'
34
+ import { resolveBindHost, isLoopbackHost, formatHostForUrl, maybeWarnNonLoopbackBind } from './bind-host.js'
35
+ import { writeFileRestricted } from './platform.js'
36
+ import { getToken, setToken, migrateToken, isKeychainAvailable } from './keychain.js'
37
+ import { maybeEncryptCredentialsAtRest } from './credential-store.js'
38
+ import { registerDockerProvider, resolveProviderLabel, DEFAULT_PROVIDER } from './providers.js'
39
+ import { registerAnthropicCompatibleProviders } from './anthropic-compatible-session.js'
40
+ import { registerOpenAiCompatibleProviders } from './openai-compatible-session.js'
41
+ import { getSharedPool, isPoolEnabled } from './docker-byok-pool.js'
42
+ import { getSharedPoolStats } from './docker-byok-pool-stats.js'
43
+ import { getRegistryForProvider, watchModelsOverlay } from './models.js'
44
+ // Imported from a dedicated constants module rather than environment-manager.js
45
+ // so we don't eagerly pull in DockerBackend when environments are disabled —
46
+ // environment-manager.js itself remains behind the dynamic import below
47
+ // (`if (config?.environments?.enabled)`).
48
+ import { UNREACHABLE_STATUSES } from './environment-statuses.js'
49
+ import { resolveSkipPermissions, buildEnvironmentBackend, isUserShellEnabled, getAllowAnyModelProviders } from './config.js'
50
+ import { parseDuration } from './duration.js'
51
+ import { createSessionTokenStore } from './session-token-store.js'
52
+
53
+ const __filename = fileURLToPath(import.meta.url)
54
+ const __dirname = dirname(__filename)
55
+ const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
56
+ const SERVER_VERSION = packageJson.version
57
+
58
+ // Tools that indicate a "writing" activity state for push notifications (#2085)
59
+
60
+ /**
61
+ * Build a `server_status` broadcast payload for the tunnel_warming phase.
62
+ *
63
+ * Factored out of the broadcast site so tests can import and assert the
64
+ * exact object shape that ships to clients — previously tests duplicated
65
+ * the construction and silently drifted if the production code changed.
66
+ *
67
+ * Pass `attempt`/`maxAttempts` for per-attempt progress updates; omit
68
+ * them for the initial pre-poll broadcast ("Tunnel warming up…" with no
69
+ * counter).
70
+ *
71
+ * @param {{ tunnelMode: string, tunnelUrl: string, attempt?: number, maxAttempts?: number }} args
72
+ * @returns {object} WS message envelope
73
+ */
74
+ export function buildTunnelWarmingStatus({ tunnelMode, tunnelUrl, attempt, maxAttempts }) {
75
+ const base = {
76
+ type: 'server_status',
77
+ phase: 'tunnel_warming',
78
+ tunnelMode,
79
+ tunnelUrl,
80
+ }
81
+ if (typeof attempt === 'number' && typeof maxAttempts === 'number') {
82
+ return {
83
+ ...base,
84
+ attempt,
85
+ maxAttempts,
86
+ message: `Tunnel warming up… (${attempt}/${maxAttempts})`,
87
+ }
88
+ }
89
+ return { ...base, message: 'Tunnel warming up…' }
90
+ }
91
+
92
+ /**
93
+ * Build a `server_status` broadcast for the terminal `ready` phase —
94
+ * signals the dashboard banner to disappear and the tunnel URL to be
95
+ * considered routable.
96
+ *
97
+ * `tunnelMode` (#5356) lets clients that connected before the tunnel came up
98
+ * (whose auth_ok exposure snapshot predates it) learn that a public quick
99
+ * tunnel is now live. Optional so older callers/tests stay valid.
100
+ *
101
+ * @param {{ tunnelUrl: string, tunnelMode?: string }} args
102
+ * @returns {object} WS message envelope
103
+ */
104
+ export function buildTunnelReadyStatus({ tunnelUrl, tunnelMode }) {
105
+ return {
106
+ type: 'server_status',
107
+ phase: 'ready',
108
+ tunnelUrl,
109
+ ...(tunnelMode ? { tunnelMode } : {}),
110
+ message: 'Tunnel is ready',
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Build the single-line startup banner string (#2953).
116
+ *
117
+ * Renders as `Chroxy Server vX.Y.Z (<provider label>)`. The provider label is
118
+ * resolved via `resolveProviderLabel()` so each provider contributes its own
119
+ * `static get displayLabel()`, replacing the previous hardcoded
120
+ * `PROVIDER_LABELS` map that had to be updated manually every time a new
121
+ * provider landed (Gemini/Codex had been falling through to the raw id).
122
+ *
123
+ * Exported so tests can assert the exact banner text without executing
124
+ * `startCliServer()` end-to-end.
125
+ *
126
+ * @param {{ version: string, provider?: string }} args
127
+ * @returns {string} Banner line (no outer box, no padding)
128
+ */
129
+ export function buildServerBanner({ version, provider }) {
130
+ const providerType = provider || DEFAULT_PROVIDER
131
+ const modeStr = resolveProviderLabel(providerType)
132
+ return `Chroxy Server v${version} (${modeStr})`
133
+ }
134
+
135
+ /**
136
+ * Run `environmentManager.reconnect()` and log a startup summary (#3464).
137
+ *
138
+ * Always emits the existing `info` summary so the healthy-startup line stays
139
+ * unchanged. When `reconnect()` resolves `false` (one or more environments
140
+ * unreachable per PR #3462's contract), additionally emits a single aggregate
141
+ * `warn` summarising the unreachable count derived from
142
+ * `environmentManager.list()` — without this, the only signal was a buried
143
+ * per-env `warn`, which is invisible in startup logs and tray-app dashboards.
144
+ *
145
+ * The unreachable count uses `UNREACHABLE_STATUSES` (currently `'error'` and
146
+ * `'stopped'`) and stays accurate only while every code path in
147
+ * `EnvironmentManager.reconnect()` that flips `allHealthy = false` also sets
148
+ * `env.status` to one of those values. See the INVARIANT block on
149
+ * `EnvironmentManager.reconnect()` JSDoc for details (#3492).
150
+ *
151
+ * Exported so tests can assert log behaviour without executing
152
+ * `startCliServer()` end-to-end.
153
+ *
154
+ * @param {{ reconnect: () => Promise<boolean>, list: () => Array<{status: string}> }} environmentManager
155
+ * @param {{ info: (msg: string) => void, warn: (msg: string) => void }} logger
156
+ * @returns {Promise<boolean>} The boolean returned by `reconnect()`.
157
+ */
158
+ export async function logEnvironmentManagerReconnectResult(environmentManager, logger) {
159
+ const allHealthy = await environmentManager.reconnect()
160
+ const environments = environmentManager.list()
161
+ logger.info(`EnvironmentManager ready (${environments.length} environment(s))`)
162
+ if (!allHealthy) {
163
+ // Invariant (#3492): every reconnect() branch that flips allHealthy=false
164
+ // also sets env.status to a value in UNREACHABLE_STATUSES. If a future
165
+ // contributor adds a new branch without that co-located status assignment,
166
+ // this count will silently undercount — keep them in sync.
167
+ const unreachable = environments.filter(e => UNREACHABLE_STATUSES.has(e.status)).length
168
+ logger.warn(`EnvironmentManager reconnect: ${unreachable} environment(s) unreachable — see per-environment logs above for details`)
169
+ }
170
+ return allHealthy
171
+ }
172
+
173
+ function checkNoAuthWarnings({ authRequired, tunnel }) {
174
+ if (authRequired) return
175
+ log.warn('--no-auth disables all authentication. Only safe on isolated networks!')
176
+ if (tunnel && tunnel !== 'none') {
177
+ log.error('--no-auth with tunnel exposes your server to the internet without authentication!')
178
+ }
179
+ }
180
+
181
+ // #5368 slice (b): maskToken moved to server-cli/startup-display.js (its only
182
+ // caller was displayQr). Still also inlined in supervisor.js + mask-token.test.js.
183
+
184
+ function wireTunnelEvents(tunnel, wsServer) {
185
+ tunnel.on('tunnel_lost', ({ code, signal }) => {
186
+ const exitReason = signal ? `signal ${signal}` : `code ${code}`
187
+ log.warn(`Tunnel lost (${exitReason})`)
188
+ wsServer.broadcastError('tunnel', `Tunnel connection lost (${exitReason}). Recovering...`, true)
189
+ })
190
+
191
+ tunnel.on('tunnel_recovering', ({ attempt, delayMs }) => {
192
+ log.info(`Attempting tunnel recovery (attempt ${attempt}, waiting ${delayMs}ms)...`)
193
+ wsServer.broadcastStatus('Tunnel recovering...')
194
+ })
195
+
196
+ tunnel.on('tunnel_failed', ({ message, lastExitCode, lastSignal, recoveryOngoing }) => {
197
+ log.warn(message)
198
+ log.warn(`Last exit: code=${lastExitCode} signal=${lastSignal}`)
199
+ if (recoveryOngoing) {
200
+ // 2026-04-11 audit (Skeptic Task #2): the tunnel adapter now
201
+ // retries indefinitely with capped exponential backoff, so this
202
+ // event means "fast round exhausted, still retrying" rather than
203
+ // "gave up permanently". Surface a recoverable warning to connected
204
+ // clients so they know something's wrong without panicking.
205
+ log.warn('Tunnel is still retrying with long-tail backoff. Remote connections may be temporarily unavailable.')
206
+ wsServer.broadcastError(
207
+ 'tunnel',
208
+ 'Tunnel connection unstable — retrying. Remote connections may be temporarily unavailable.',
209
+ true,
210
+ )
211
+ } else {
212
+ log.error('Server will continue on localhost only. Remote connections will not work.')
213
+ wsServer.broadcastError('tunnel', 'Tunnel recovery failed. Remote connections will not work.', false)
214
+ }
215
+ })
216
+
217
+ tunnel.on('tunnel_recovery_exhausted_round', ({ attempts, nextBackoffMs }) => {
218
+ log.warn(`Tunnel recovery round exhausted after ${attempts} fast attempts; next retry in ${nextBackoffMs}ms`)
219
+ // The tunnel_failed event above already surfaces a user-facing error.
220
+ // This is operator-facing diagnostic only.
221
+ })
222
+ }
223
+
224
+ function isWithinHome(dir) {
225
+ const rel = relative(homedir(), dir)
226
+ return !rel.startsWith('..') && !rel.startsWith(sep)
227
+ }
228
+
229
+ /**
230
+ * Start the Chroxy server in CLI headless mode.
231
+ */
232
+ /**
233
+ * Persist server logs to disk so timeouts and crashes leave a forensic trail (#3731).
234
+ *
235
+ * Pre-fix the server only wrote to stdout/stderr — the Tauri parent buffered
236
+ * ~100 lines in memory and the rest was dropped. Default destination is
237
+ * `~/.chroxy/logs/chroxy.log` with 5MB rotation × 3 files; the caller can
238
+ * override via `config.logLevel` / `config.logDir` or the `CHROXY_LOG_LEVEL` /
239
+ * `CHROXY_LOG_DIR` env vars, and opt out entirely with
240
+ * `CHROXY_NO_FILE_LOGGING=1` (used when a parent process owns log capture).
241
+ *
242
+ * Failures are swallowed: the boot path must not abort over a logging-only
243
+ * problem (e.g. a read-only home directory). The error is reported to stderr
244
+ * and the server continues with stdout-only logging.
245
+ *
246
+ * Exported for testing.
247
+ *
248
+ * @param {{ logLevel?: string, logDir?: string }} config
249
+ * @returns {{ enabled: boolean, level: string, logDir: string|null, error?: string }}
250
+ */
251
+ /**
252
+ * #4509: resolve the three operator-facing inactivity timeouts
253
+ * (resultTimeoutMs / hardTimeoutMs / streamStallTimeoutMs) from a startup
254
+ * config object into BOTH shapes `startCliServer` needs:
255
+ *
256
+ * - SessionManager constructor args (`*TimeoutMs`): null = let BaseSession
257
+ * apply its default. The provider opts forwarding path treats null as
258
+ * "omit", which is exactly the behaviour we want for fallback.
259
+ * - Startup log line (`effective*TimeoutMs`): the resolved DEFAULT_*
260
+ * constant so operators see the actual wall-clock value that will fire
261
+ * instead of a misleading `null`.
262
+ *
263
+ * Previously these two sites hand-rolled the same
264
+ * `Number.isFinite(x) && x [>|>=] 0` check independently, with no
265
+ * MAX_SANE_DURATION_MS ceiling. Consolidating into one helper closes the
266
+ * #4509 gap and makes the two sites impossible to drift apart.
267
+ *
268
+ * @param {object} config - The merged startup config (from `~/.chroxy/config.json`
269
+ * + CLI flags + env vars).
270
+ * @param {{ warn: Function }} log - Logger to emit the over-ceiling
271
+ * warning through. Defaults to a no-op so callers can omit it in tests.
272
+ * @returns {{
273
+ * resultTimeoutMs: number|null,
274
+ * hardTimeoutMs: number|null,
275
+ * streamStallTimeoutMs: number|null,
276
+ * mcpToolCallTimeoutMs: number|null,
277
+ * effectiveResultTimeoutMs: number,
278
+ * effectiveHardTimeoutMs: number,
279
+ * effectiveStreamStallTimeoutMs: number,
280
+ * effectiveMcpToolCallTimeoutMs: number,
281
+ * }}
282
+ */
283
+ export function resolveStartupTimeouts(config = {}, log = { warn: () => {} }) {
284
+ const resultOk = isOperatorTimeoutInRange(config.resultTimeoutMs, { name: 'resultTimeoutMs', log })
285
+ const hardOk = isOperatorTimeoutInRange(config.hardTimeoutMs, { name: 'hardTimeoutMs', log })
286
+ const stallOk = isOperatorTimeoutInRange(config.streamStallTimeoutMs, { allowZero: true, name: 'streamStallTimeoutMs', log })
287
+ // #4517: mcpToolCallTimeoutMs joined the ceiling-clamped family. Same
288
+ // `> 0` gate as the soft/hard timeouts (0 fires the callTool deadline
289
+ // immediately and would make every MCP tool look broken); same fall-back-
290
+ // to-null contract so byok-mcp-client's DEFAULT_TOOL_CALL_TIMEOUT_MS (30s)
291
+ // applies. The config.js validator already gates file-loaded values to
292
+ // 1s-10min — this guardrail catches programmatic instantiation and acts
293
+ // as defense-in-depth for any future config path that bypasses validation.
294
+ const mcpOk = isOperatorTimeoutInRange(config.mcpToolCallTimeoutMs, { name: 'mcpToolCallTimeoutMs', log })
295
+
296
+ return {
297
+ resultTimeoutMs: resultOk ? config.resultTimeoutMs : null,
298
+ hardTimeoutMs: hardOk ? config.hardTimeoutMs : null,
299
+ streamStallTimeoutMs: stallOk ? config.streamStallTimeoutMs : null,
300
+ mcpToolCallTimeoutMs: mcpOk ? config.mcpToolCallTimeoutMs : null,
301
+ effectiveResultTimeoutMs: resultOk ? config.resultTimeoutMs : DEFAULT_RESULT_TIMEOUT_MS,
302
+ effectiveHardTimeoutMs: hardOk ? config.hardTimeoutMs : DEFAULT_HARD_TIMEOUT_MS,
303
+ effectiveStreamStallTimeoutMs: stallOk ? config.streamStallTimeoutMs : DEFAULT_STREAM_STALL_TIMEOUT_MS,
304
+ effectiveMcpToolCallTimeoutMs: mcpOk ? config.mcpToolCallTimeoutMs : DEFAULT_TOOL_CALL_TIMEOUT_MS,
305
+ }
306
+ }
307
+
308
+ export function initFileLoggingFromConfig(config = {}) {
309
+ if (process.env.CHROXY_NO_FILE_LOGGING === '1') {
310
+ return { enabled: false, level: 'info', logDir: null }
311
+ }
312
+ const level = config.logLevel || process.env.CHROXY_LOG_LEVEL || 'info'
313
+ const logDir = config.logDir || process.env.CHROXY_LOG_DIR || null
314
+ try {
315
+ initFileLogging({ level, ...(logDir ? { logDir } : {}) })
316
+ return { enabled: true, level, logDir }
317
+ } catch (err) {
318
+ const message = err?.message || String(err)
319
+ // Use console.error rather than the chroxy logger because the logger
320
+ // itself may have just failed to initialize — a recursive log call
321
+ // here would either silently swallow the message or crash on the
322
+ // unset log path.
323
+ console.error(`[logger] file logging init failed: ${message}`)
324
+ return { enabled: false, level, logDir, error: message }
325
+ }
326
+ }
327
+
328
+ /**
329
+ * Decide whether to advertise the server over mDNS/Bonjour and, if so, publish
330
+ * the `_chroxy._tcp` service. Extracted from startCliServer so the loopback
331
+ * gating wiring is testable without booting the full CLI (#5280) — the pure
332
+ * resolver (bind-host.js) was already covered, but the decision to suppress the
333
+ * advertisement on a loopback bind was not.
334
+ *
335
+ * Returns `{ mdnsService, bonjourInstance }` (both null when not advertising) so
336
+ * the caller can stop/destroy them on shutdown.
337
+ *
338
+ * @param {object} opts
339
+ * @param {boolean} opts.noAuth — auth disabled; never advertise.
340
+ * @param {string|undefined} opts.bindHost — the resolved bind host.
341
+ * @param {number} opts.port
342
+ * @param {string} opts.version
343
+ * @param {boolean} opts.hasToken — surfaced in the TXT record's `auth` field.
344
+ * @param {object} [opts.log] — logger (defaults to console).
345
+ * @param {() => (object|Promise<object>)} [opts.bonjourFactory] — injectable
346
+ * Bonjour instance factory for tests; defaults to dynamically importing
347
+ * `bonjour-service`.
348
+ */
349
+ export async function maybeAdvertiseMdns({
350
+ noAuth,
351
+ bindHost,
352
+ port,
353
+ version,
354
+ hasToken,
355
+ log = console,
356
+ bonjourFactory,
357
+ } = {}) {
358
+ const none = { mdnsService: null, bonjourInstance: null }
359
+ // Auth-off skips discovery entirely (matches the pre-#5280 guards).
360
+ if (noAuth) return none
361
+ // Loopback bind — nothing on the LAN can reach it, so an _chroxy._tcp
362
+ // advertisement would be misleading.
363
+ if (isLoopbackHost(bindHost)) {
364
+ log.info?.('Loopback bind — skipping mDNS advertisement (server not LAN-reachable)')
365
+ return none
366
+ }
367
+ try {
368
+ const bonjourInstance = bonjourFactory
369
+ ? await bonjourFactory()
370
+ : await (async () => {
371
+ const { Bonjour } = await import('bonjour-service')
372
+ return new Bonjour()
373
+ })()
374
+ const mdnsService = bonjourInstance.publish({
375
+ name: `Chroxy (${hostname()})`,
376
+ type: 'chroxy',
377
+ port,
378
+ txt: { version, auth: hasToken ? 'token' : 'none' },
379
+ })
380
+ log.info?.(`Advertising _chroxy._tcp on port ${port} via mDNS`)
381
+ return { mdnsService, bonjourInstance }
382
+ } catch (err) {
383
+ // Normalize the error the way the rest of this file does — a Bonjour
384
+ // factory (or the dynamic import) that throws a non-Error / null must not
385
+ // turn the graceful no-advertisement fallback into a crash.
386
+ log.debug?.(`mDNS advertisement unavailable: ${err?.message || String(err)}`)
387
+ return none
388
+ }
389
+ }
390
+
391
+ /**
392
+ * #5369: best-effort teardown for STARTUP-ERROR paths (tunnel.start failure,
393
+ * waitForTunnel failure). Async — awaits tunnel.stop() because at startup there
394
+ * is no exit-deadline risk and we want a clean stop. Each step is try/catch-
395
+ * isolated so one failure can't strand the rest. Exported (no process.exit) so
396
+ * it can be unit-tested with fakes — mirrors flushAndDestroy in
397
+ * server-cli-child.js. Order is tunnel → ws → mdns → bonjour → token → pairing
398
+ * → sessionManager (the deliberate startup-error order; pool is NOT torn down
399
+ * at these sites today and must not be added).
400
+ */
401
+ export async function emergencyCleanup({
402
+ tunnel, wsServer, mdnsService, bonjourInstance,
403
+ tokenManager, pairingManager, sessionManager, logger = log,
404
+ }) {
405
+ // String(err?.message || err) so a non-Error throw (e.g. a Symbol) can't make
406
+ // the log-formatting itself throw and break this best-effort teardown chain.
407
+ 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)}`) }
409
+ try { mdnsService?.stop?.() } catch {}
410
+ try { bonjourInstance?.destroy?.() } catch {}
411
+ try { tokenManager?.destroy() } catch {}
412
+ try { pairingManager?.destroy() } catch {}
413
+ try { sessionManager?.destroyAll() } catch (err) { logger?.warn?.(`emergencyCleanup: destroyAll failed: ${String(err?.message || err)}`) }
414
+ }
415
+
416
+ /**
417
+ * #5369: unified SYNCHRONOUS crash teardown for uncaughtException /
418
+ * unhandledRejection. `kind` is the log label. Deliberately NOT async and does
419
+ * NOT await tunnel.stop() — the sigterm-not-sigkill invariant: a hung stop must
420
+ * never block the setTimeout-driven process.exit in the caller (otherwise an
421
+ * installed crash handler suppresses Node's default crash-exit and could leave
422
+ * the process alive forever). Order: broadcast → serialize → destroyAll → ws
423
+ * close → tunnel.stop (fire-and-forget) → removeConnectionInfo. destroyAll runs
424
+ * before wsServer.close so SDK sessions auto-deny pending permissions first.
425
+ */
426
+ export function emergencyCleanupSync({ kind, tunnel, wsServer, sessionManager, logger = log }) {
427
+ try { wsServer?.broadcastShutdown('crash', 0) } catch {}
428
+ // Persist sessions before destroying — losing the user's restored state on
429
+ // crash is worse UX than the small risk of writing partial state. The
430
+ // try/catch isolates serialization failures so destroyAll() still runs.
431
+ // logger?.warn?.() + String(...) so a minimal/nullish logger or a non-Error
432
+ // throw can't itself throw and abort the remaining crash teardown.
433
+ try { sessionManager?.serializeState() } catch (serializeErr) {
434
+ logger?.warn?.(`Failed to serialize state during ${kind}: ${String(serializeErr?.stack || serializeErr)}`)
435
+ }
436
+ try { sessionManager?.destroyAll() } catch {}
437
+ try { wsServer?.close() } catch {}
438
+ // NO await — see the invariant above.
439
+ try { if (tunnel) tunnel.stop() } catch {}
440
+ try { removeConnectionInfo() } catch {}
441
+ }
442
+
443
+ export async function startCliServer(config) {
444
+ // Enable JSON log format if configured
445
+ if (config.logFormat === 'json') {
446
+ setJsonMode(true)
447
+ }
448
+
449
+ initFileLoggingFromConfig(config)
450
+
451
+ const PORT = config.port || parseInt(process.env.PORT || '8765', 10)
452
+ const NO_AUTH = !!config.noAuth
453
+
454
+ // Token precedence: config (may be from keychain migration) > keychain > env var
455
+ let API_TOKEN = NO_AUTH ? null : (config.apiToken || getToken() || process.env.API_TOKEN)
456
+
457
+ // Migrate plaintext token to keychain and remove from config file
458
+ if (!NO_AUTH && config.apiToken && isKeychainAvailable()) {
459
+ const configFile = join(homedir(), '.chroxy', 'config.json')
460
+ const { migrated } = migrateToken(config)
461
+ // Remove plaintext token from config file (whether newly migrated or already in keychain)
462
+ const keychainToken = getToken()
463
+ if (keychainToken && (migrated || keychainToken === config.apiToken)) {
464
+ try {
465
+ const raw = existsSync(configFile) ? readFileSync(configFile, 'utf-8') : '{}'
466
+ const cfg = JSON.parse(raw)
467
+ if (cfg.apiToken) {
468
+ delete cfg.apiToken
469
+ writeFileRestricted(configFile, JSON.stringify(cfg, null, 2))
470
+ if (migrated) log.info('API token migrated to OS keychain')
471
+ else log.info('Removed redundant plaintext token from config')
472
+ }
473
+ } catch (err) {
474
+ log.warn(`Keychain migration warning: ${err.message}`)
475
+ }
476
+ // Use keychain token as authoritative source
477
+ API_TOKEN = keychainToken
478
+ }
479
+ }
480
+
481
+ if (!NO_AUTH && !API_TOKEN) {
482
+ console.error('[!] No API token configured. Run \'npx chroxy init\' first.') // intentional user-facing output
483
+ process.exit(1)
484
+ }
485
+
486
+ // #5154 — encrypt a legacy plaintext credentials.json at rest once an OS
487
+ // keychain is available (mirrors the primary-token migration above).
488
+ // Best-effort: never blocks boot.
489
+ try {
490
+ maybeEncryptCredentialsAtRest({ log })
491
+ } catch (err) {
492
+ log.warn(`Credentials at-rest encryption check failed: ${err.message}`)
493
+ }
494
+
495
+ const banner = buildServerBanner({ version: SERVER_VERSION, provider: config.provider })
496
+ const pad = Math.max(0, 38 - banner.length)
497
+ const left = Math.floor(pad / 2)
498
+ const right = pad - left
499
+ console.log('')
500
+ console.log('╔════════════════════════════════════════╗')
501
+ console.log(`║${' '.repeat(left + 1)}${banner}${' '.repeat(right + 1)}║`)
502
+ console.log('╚════════════════════════════════════════╝')
503
+ console.log('')
504
+
505
+ if (NO_AUTH) {
506
+ const tunnelMode = config.tunnel || 'none'
507
+ checkNoAuthWarnings({ authRequired: false, tunnel: tunnelMode })
508
+ console.log('')
509
+ }
510
+
511
+ // Prevent unencrypted traffic over public tunnels
512
+ if (config.noEncrypt && config.tunnel && config.tunnel !== 'none') {
513
+ console.error('[!] Cannot use --no-encrypt with a tunnel. Unencrypted WebSocket') // intentional user-facing output
514
+ console.error(' traffic over a public tunnel exposes all session data in transit.')
515
+ console.error(' Remove --no-encrypt or disable the tunnel (--tunnel none).')
516
+ process.exit(1)
517
+ }
518
+
519
+ // Register optional providers (e.g. docker) based on config
520
+ await registerDockerProvider(config)
521
+
522
+ // #5419: register config-driven Anthropic-compatible endpoints from
523
+ // `providers.anthropicCompatible` (Z.ai GLM, Moonshot Kimi, MiniMax,
524
+ // LM Studio, llama.cpp, vLLM, OpenRouter, custom). Registered before
525
+ // the default-provider resolution below so `--provider <id>` /
526
+ // `config.provider` can select one. Invalid entries are warned about
527
+ // and skipped; valid siblings still register.
528
+ registerAnthropicCompatibleProviders(config)
529
+ // #5420: register config-driven OpenAI-compatible endpoints from
530
+ // `providers.openaiCompatible` (OpenAI, OpenRouter, LM Studio, vLLM,
531
+ // llama.cpp, Together, Groq, custom). Same entry shape, but the session
532
+ // talks chat-completions via the Anthropic↔OpenAI shim. Registered right
533
+ // after the Anthropic-compatible block (collision-checked against it).
534
+ registerOpenAiCompatibleProviders(config)
535
+
536
+ const providerType = config.provider || DEFAULT_PROVIDER
537
+
538
+ // Warm the models registry from disk cache so the picker is populated before
539
+ // any SDK session fires supportedModels(). Routed through the ACTIVE provider's
540
+ // registry (#6368) so a non-Claude DEFAULT_PROVIDER warms its OWN cache
541
+ // (~/.chroxy/models-cache.<provider>.json) instead of the Claude default. For
542
+ // Claude providers getRegistryForProvider returns the shared default registry,
543
+ // so behaviour is byte-identical to the prior module-level loadModelsCache().
544
+ // Placed after the provider-registration block above so getRegistryForProvider
545
+ // can resolve docker/config-driven/non-Claude providers. Silent miss on first boot.
546
+ const bootRegistry = getRegistryForProvider(providerType)
547
+ if (bootRegistry.loadCache()) {
548
+ log.info(`Warmed models from cache: ${bootRegistry.getModels().map(m => m.id).join(', ')}`)
549
+ }
550
+
551
+ // #4209 / #4246: resolve the effective skip-permissions setting from the
552
+ // merged config (CLI flag > canonical `dangerouslySkipPermissions` >
553
+ // legacy `skipPermissions` alias). When enabled, log a loud security
554
+ // banner identifying which key/source surfaced it — operators scanning
555
+ // their config.json shouldn't have to wonder why their TUI sessions
556
+ // started spawning with --dangerously-skip-permissions. When the legacy
557
+ // alias is used, also surface the deprecation warning so they're
558
+ // nudged to rename the key.
559
+ const skipPerms = resolveSkipPermissions(config)
560
+ if (skipPerms.deprecationWarning) {
561
+ log.warn(`[security] ${skipPerms.deprecationWarning}`)
562
+ }
563
+ if (skipPerms.enabled) {
564
+ log.warn(`[security] dangerouslySkipPermissions=true (source: config.${skipPerms.source}) — claude-tui sessions will spawn with --dangerously-skip-permissions and chroxy's permission gate is BYPASSED for those sessions`)
565
+ }
566
+
567
+ // Create environment manager for persistent container environments (optional)
568
+ let environmentManager = null
569
+ if (config?.environments?.enabled) {
570
+ const { EnvironmentManager } = await import('./environment-manager.js')
571
+ // #4556: forward the operator-configured K8s workspace PVC default so
572
+ // every environment created on a K8s backend picks up the strategy
573
+ // without per-call plumbing. Shape was validated at config-load time
574
+ // (`validateConfig` in config.js); the manager re-passes it verbatim to
575
+ // the backend, which is the single enforcement point for runtime checks
576
+ // (K8sBackend.validateWorkspacePVC). Docker / other backends ignore the
577
+ // field, so this is safe to pass regardless of the active backend.
578
+ const workspacePVCDefault = config?.environments?.k8s?.workspace || null
579
+ if (workspacePVCDefault) {
580
+ const mountPath = workspacePVCDefault.mountPath || '/workspace'
581
+ const readOnlyTag = workspacePVCDefault.readOnly ? ' (readOnly)' : ''
582
+ // Make the K8s-only scope explicit so an operator who set this block
583
+ // against a Docker deployment doesn't assume the PVC is being mounted —
584
+ // Docker / other backends silently ignore the field at runtime.
585
+ log.info(`EnvironmentManager: K8s workspace PVC configured (claim: ${workspacePVCDefault.claimName}, mount: ${mountPath})${readOnlyTag} — active only on K8sBackend; ignored by Docker and other backends`)
586
+ }
587
+ // #5144: config-driven backend selection. `environments.backend` picks
588
+ // docker (default) | k8s | rancher; the selected backend's options come
589
+ // from `environments.k8s` / `environments.rancher` (Rancher token resolved
590
+ // from a secret-friendly source and never logged). The factory imports the
591
+ // backend module lazily so a Docker deployment never pulls in the kube SDK,
592
+ // and throws on a malformed k8s/rancher block — surfaced here as a fatal
593
+ // startup error rather than a silent fall-through to Docker.
594
+ let backend
595
+ try {
596
+ const built = await buildEnvironmentBackend(config)
597
+ backend = built.backend
598
+ if (built.type !== 'docker') {
599
+ log.info(`EnvironmentManager: using '${built.type}' backend (from environments.backend)`)
600
+ }
601
+ } catch (err) {
602
+ log.error(`EnvironmentManager: failed to construct '${config?.environments?.backend || 'docker'}' backend — ${err.message}`)
603
+ throw err
604
+ }
605
+ environmentManager = new EnvironmentManager({ backend, workspacePVCDefault })
606
+ await logEnvironmentManagerReconnectResult(environmentManager, log)
607
+ }
608
+
609
+ // #5081: boot-time garbage collection of leaked docker-byok compose stacks.
610
+ // A daemon crash / SIGKILL between `docker compose up` and `docker compose
611
+ // down` leaves the stack running with only an on-disk record (written by
612
+ // DockerByokSession on start). Sweep those orphans now — before any new
613
+ // session launches — so a crash can't leak stacks indefinitely. Entirely
614
+ // best-effort: a failure here (docker down, partial teardown) is logged and
615
+ // the offending entry stays on disk to be retried on the next boot.
616
+ try {
617
+ const { getSharedComposeStateStore } = await import('./byok-compose-state-shared.js')
618
+ const { sweepOrphanedComposeStacks } = await import('./byok-compose-state.js')
619
+ const store = getSharedComposeStateStore()
620
+ if (store.list().length > 0) {
621
+ const { DockerBackend } = await import('./environments/backends/docker.js')
622
+ const result = await sweepOrphanedComposeStacks({ store, backend: new DockerBackend() })
623
+ log.info(`docker-byok compose sweep: ${result.swept} orphaned stack(s) torn down, ${result.failed} deferred to next boot`)
624
+ }
625
+ } catch (err) {
626
+ log.warn(`docker-byok compose sweep failed: ${err.message}`)
627
+ }
628
+
629
+ // #4509: resolve once so the SessionManager arg side and the startup log
630
+ // line below can't drift apart, and any over-ceiling operator value emits
631
+ // a single warning here at boot (not three on each tunable).
632
+ const startupTimeouts = resolveStartupTimeouts(config, log)
633
+
634
+ // 1. Create session manager
635
+ const sessionManager = new SessionManager({
636
+ maxSessions: config.maxSessions || 5,
637
+ port: PORT,
638
+ apiToken: API_TOKEN,
639
+ defaultCwd: config.cwd || (isWithinHome(process.cwd()) ? process.cwd() : homedir()),
640
+ defaultModel: config.model || null,
641
+ defaultPermissionMode: 'approve',
642
+ // #5859 (audit P1-7): reclaim orphaned chroxy session worktrees at boot when
643
+ // the operator opted into worktree auto-reaping. Clean-tree-guarded.
644
+ sweepOrphanWorktrees: config.worktreeGc?.autoReap === true,
645
+ // #4209 / #4246: seed the auto-created Default session + any
646
+ // subsequent createSession() that omits the field. Only honoured by
647
+ // the claude-tui provider; other providers ignore it harmlessly.
648
+ // Resolved via `resolveSkipPermissions()` so both the canonical
649
+ // `dangerouslySkipPermissions` key and the legacy `skipPermissions`
650
+ // alias are honoured (with a deprecation warning for the latter —
651
+ // see the [security] log lines above).
652
+ defaultSkipPermissions: skipPerms.enabled,
653
+ // #5985 (epic #5982): gate the embedded user-shell terminal. Off unless the
654
+ // operator set userShell.enabled:true in the config file. Enforced in
655
+ // SessionManager.createSession so it covers every spawn path.
656
+ userShellEnabled: isUserShellEnabled(config),
657
+ // #6378: providers opted into unrestricted model validation (serve any
658
+ // API-valid model id without a release). Empty Set unless the operator set
659
+ // config.providers.allowAnyModel.
660
+ allowAnyModelProviders: getAllowAnyModelProviders(config),
661
+ providerType,
662
+ maxToolInput: config.maxToolInput || null,
663
+ transforms: config.transforms || [],
664
+ sessionTimeout: config.sessionTimeout || null,
665
+ sandbox: config.sandbox || null,
666
+ costBudget: config.costBudget || null,
667
+ // #5665: monthly programmatic-credit budget meter config.
668
+ billing: config.billing || null,
669
+ maxMessages: config.maxMessages || config.maxHistory || null,
670
+ // #3749 / #3884 / #3899: SOFT-warning inactivity timeout (ms). null = BaseSession default (30 min).
671
+ // #3899: HARD-cap inactivity timeout (ms). null = BaseSession default (2h).
672
+ // #4467: stream-stall recovery (ms). null = BaseSession default (5min).
673
+ // 0 explicitly disables (operators with workloads that have legitimate
674
+ // long event gaps can opt out).
675
+ // #4509: ceiling-clamped via `resolveStartupTimeouts()` above; an
676
+ // over-24h operator value falls back to null here so BaseSession applies
677
+ // its default (and the operator gets a warn log identifying the bad key).
678
+ resultTimeoutMs: startupTimeouts.resultTimeoutMs,
679
+ hardTimeoutMs: startupTimeouts.hardTimeoutMs,
680
+ streamStallTimeoutMs: startupTimeouts.streamStallTimeoutMs,
681
+ // #5288: background-shell hard-quiesce window (ms). null = BaseSession
682
+ // default (4h); 0 disables hard-reaping. SessionManager applies the same
683
+ // isOperatorTimeoutInRange ceiling guard (allowZero) as the timeouts.
684
+ backgroundShellHardQuiesceMs: config.backgroundShellHardQuiesceMs ?? null,
685
+ // #4601: per-provider streamStallTimeoutMs override map. SessionManager
686
+ // sanitises each entry against the same range gate as the global value
687
+ // (`allowZero: true`, 5s-24h ceiling) — bogus entries are dropped (with
688
+ // a warn) and the affected session falls through to the global value.
689
+ // The unsanitised object is forwarded as-is so SessionManager owns the
690
+ // single source of truth for validation.
691
+ providerStreamStallTimeoutMs: config.providerStreamStallTimeoutMs || null,
692
+ // #4482: per-MCP-call timeout (ms). null = byok-mcp-client default (30s).
693
+ // Unlike streamStallTimeoutMs, 0 is not a meaningful disable — every
694
+ // MCP tool would look broken — so non-positive falls back to null.
695
+ // #4517: ceiling-clamped via `resolveStartupTimeouts()` above; an
696
+ // over-24h operator value falls back to null here so byok-mcp-client
697
+ // applies its default (and the operator gets a warn log).
698
+ 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
+ })
703
+
704
+ // #3749 / #3899: surface the effective inactivity timeouts at startup so
705
+ // operators can verify their config overrides took effect.
706
+ // #4509: re-use the already-clamped values from `resolveStartupTimeouts()`
707
+ // so the log line can't drift away from the SessionManager constructor
708
+ // args (e.g. log "12h hard-cap" while passing `null` because only one of
709
+ // the two sites caught a typo).
710
+ const { effectiveResultTimeoutMs, effectiveHardTimeoutMs, effectiveStreamStallTimeoutMs } = startupTimeouts
711
+ const stallLabel = effectiveStreamStallTimeoutMs === 0
712
+ ? 'disabled'
713
+ : `${formatIdleDuration(effectiveStreamStallTimeoutMs)} (${effectiveStreamStallTimeoutMs}ms)`
714
+ log.info(`Inactivity soft-warning: ${formatIdleDuration(effectiveResultTimeoutMs)} (${effectiveResultTimeoutMs}ms); hard-cap: ${formatIdleDuration(effectiveHardTimeoutMs)} (${effectiveHardTimeoutMs}ms); stream-stall: ${stallLabel}`)
715
+
716
+ // 2. Try restoring session state from a previous instance
717
+ let defaultSessionId
718
+ defaultSessionId = sessionManager.restoreState()
719
+ if (defaultSessionId) {
720
+ log.info('Restored sessions from previous server instance')
721
+ }
722
+
723
+ // 3. Create default session if no restore
724
+ if (!defaultSessionId) {
725
+ defaultSessionId = sessionManager.createSession({ name: 'Default' })
726
+ }
727
+
728
+ let wsServer
729
+
730
+ // #5368 slice (a): the `session_event` → push-notification path (incl. the
731
+ // #3866 idle-push dedupe and the #3870/#3871/#3872 races) lives in
732
+ // PushNotificationHandler, constructed + started after pushManager exists and
733
+ // before wsServer (so the #3871 wsServer-undefined branch still covers an
734
+ // early restoreState event). See below, right after `new PushManager(...)`.
735
+
736
+ // Log events for debugging
737
+ sessionManager.on('session_created', ({ sessionId, name, cwd }) => {
738
+ log.info(`Session created: ${sessionId} (${name}) in ${cwd}`)
739
+ })
740
+
741
+ sessionManager.on('session_destroyed', ({ sessionId }) => {
742
+ log.info(`Session destroyed: ${sessionId}`)
743
+ // #5368: the idle-push dedupe clear-on-destroy now lives in
744
+ // PushNotificationHandler (its own session_destroyed listener).
745
+ })
746
+
747
+ sessionManager.on('session_warning', ({ sessionId, name, reason, message, remainingMs }) => {
748
+ log.warn(`Session warning: ${message}`)
749
+ if (wsServer) {
750
+ wsServer.broadcast({ type: 'session_warning', sessionId, name, reason, message, remainingMs })
751
+ }
752
+ })
753
+
754
+ sessionManager.on('session_timeout', ({ sessionId, name, idleMs }) => {
755
+ log.info(`Session ${sessionId} (${name}) timed out after ${Math.round(idleMs / 1000)}s idle`)
756
+ if (wsServer) {
757
+ wsServer.broadcast({ type: 'session_timeout', sessionId, name, idleMs })
758
+ }
759
+ })
760
+
761
+ // 3. Create push notification manager, token manager, and WebSocket server
762
+ const pushManager = new PushManager({
763
+ storagePath: join(homedir(), '.chroxy', 'push-tokens.json'),
764
+ // #4541: notification preferences persistence. Co-located in
765
+ // ~/.chroxy alongside push-tokens.json so cleanup is one step.
766
+ prefsPath: join(homedir(), '.chroxy', 'notification-prefs.json'),
767
+ // #5413 Phase 2: Discord status-embed sink. Off by default — only
768
+ // active when a webhook URL resolves from CHROXY_DISCORD_WEBHOOK_URL
769
+ // or ~/.chroxy/credentials.json (0600). Non-secret knobs (bot name,
770
+ // per-project embed colors, throttle/heartbeat intervals) come from
771
+ // the `notifications.discord` config block; the status-message state
772
+ // (message ids, current state) persists alongside the other
773
+ // notification state in ~/.chroxy.
774
+ discord: {
775
+ statePath: join(homedir(), '.chroxy', 'discord-webhook-state.json'),
776
+ // #5828: the billing-alert sink keeps its own state file, separate from
777
+ // the per-project status store above.
778
+ billingStatePath: join(homedir(), '.chroxy', 'discord-billing-state.json'),
779
+ ...(config.notifications?.discord || {}),
780
+ },
781
+ })
782
+
783
+ // #5413 Phase 3: provision the daemon-level ingest secret for
784
+ // POST /api/events BEFORE any external hook needs to read it (emitters
785
+ // authenticate with the file's content, so it must exist up front).
786
+ // Fail-soft: on failure the route fails closed (rejects everything) and
787
+ // the warn log tells the operator why. Never logs the secret.
788
+ ensureIngestSecret()
789
+
790
+ // #5368 slice (a): wire the session_event → push path now that pushManager
791
+ // exists. `getWsServer` is lazy because the handler is started before wsServer
792
+ // is constructed (below) — an early restoreState `result` event must still
793
+ // route here and hit the wsServer-undefined branch (#3871).
794
+ const pushNotificationHandler = new PushNotificationHandler({
795
+ sessionManager,
796
+ pushManager,
797
+ getWsServer: () => wsServer,
798
+ logger: log,
799
+ })
800
+ pushNotificationHandler.start()
801
+
802
+ const configFile = join(homedir(), '.chroxy', 'config.json')
803
+ const tokenManager = NO_AUTH ? null : new TokenManager({
804
+ token: API_TOKEN,
805
+ 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
+ },
828
+ })
829
+ if (tokenManager) tokenManager.start()
830
+
831
+ // #5536 — long-lived server identity for E2E key pinning. Minted once and
832
+ // persisted across restarts (keychain, or a 0600 file fallback). Its public
833
+ // half rides the pairing payload (pinned by clients); its secret half signs
834
+ // each connection's ephemeral exchange key so a pinned client can verify the
835
+ // exchange key really came from this daemon. Only relevant when encryption is
836
+ // on and auth is required — skip the keypair work for --no-auth / --no-encrypt
837
+ // so those modes carry no pinning surface (and old TOFU behaviour is unchanged).
838
+ let serverIdentity = null
839
+ if (!NO_AUTH && !config.noEncrypt) {
840
+ try {
841
+ serverIdentity = getOrCreateServerIdentity()
842
+ } catch (err) {
843
+ if (err instanceof IdentityUnavailableError) {
844
+ // #5615 case (b): the keychain is PRESENT but the identity read FAILED
845
+ // (locked / interaction-not-allowed). We deliberately did NOT mint a
846
+ // replacement — doing so would silently rotate the daemon's identity and
847
+ // brick every already-pinned client with a false "network impersonation"
848
+ // alert. A transient lock must not look like an active MITM.
849
+ //
850
+ // Fail loudly by default: refuse to start so the operator unlocks the
851
+ // keychain (or grants access) and the SAME pinned identity loads. The
852
+ // CHROXY_ALLOW_UNPINNED_BOOT escape hatch lets an operator who knows no
853
+ // clients are pinned boot anyway with pinning DISABLED this boot — the
854
+ // server then signs nothing. Clients that NEVER pinned this daemon see an
855
+ // old-daemon shape (TOFU). Clients that ALREADY pinned it will REFUSE the
856
+ // unsigned handshake (pinned-but-unsigned) — which is the safe outcome and
857
+ // still better than a false "impersonation" alert from a rotated identity.
858
+ // (err.message already begins with "server identity keychain read
859
+ // failed (…)", so log it directly — no redundant prefix.)
860
+ if (process.env.CHROXY_ALLOW_UNPINNED_BOOT === '1') {
861
+ log.warn(
862
+ `${err.message}. ` +
863
+ 'CHROXY_ALLOW_UNPINNED_BOOT=1 set — starting WITH KEY PINNING DISABLED this boot ' +
864
+ '(server signs no exchange keys). Clients that never pinned this daemon get TOFU; ' +
865
+ 'clients that ALREADY pinned it will refuse until you restore the identity. ' +
866
+ 'Unlock the keychain and restart to restore pinning.',
867
+ )
868
+ serverIdentity = null
869
+ } else {
870
+ log.error(
871
+ `${err.message}. ` +
872
+ 'Refusing to start: minting a replacement would rotate this daemon\'s identity and ' +
873
+ 'falsely alarm every paired client as a network-impersonation attempt. ' +
874
+ 'Unlock your OS keychain (or grant chroxy access) and start again. ' +
875
+ 'If you are certain NO clients have pinned this daemon, set CHROXY_ALLOW_UNPINNED_BOOT=1 ' +
876
+ 'to start once with key pinning disabled.',
877
+ )
878
+ process.exit(1)
879
+ }
880
+ } else {
881
+ // Any other failure (e.g. no keychain + unwritable fallback file) keeps
882
+ // the original behaviour: disable pinning, stay TOFU. This is NOT the
883
+ // silent-rotation hazard — there was no prior identity to contradict.
884
+ log.warn(`Could not establish server identity key (${err.message}); E2E key pinning disabled — connections stay TOFU`)
885
+ serverIdentity = null
886
+ }
887
+ }
888
+ }
889
+
890
+ // #5616/#5976 — if the identity was rotated (admin ran `chroxy identity
891
+ // rotate`), attach the single-hop continuity cert so the handshake can offer
892
+ // it. The staleness guard inside resolveServerRotationCert ignores a sidecar
893
+ // that names a different identity than the one we just loaded (e.g. left over
894
+ // from before a clean re-mint). Best-effort: a missing/unreadable sidecar
895
+ // simply leaves pinning behaviour unchanged (rotated clients re-pair).
896
+ if (serverIdentity) {
897
+ try {
898
+ const cert = resolveServerRotationCert(serverIdentity.publicKey)
899
+ if (cert) {
900
+ serverIdentity = { ...serverIdentity, rotationCert: cert.rotationCert, previousPublicKey: cert.previousPublicKey }
901
+ log.info('Identity-rotation continuity cert loaded — pinned clients can chain forward without re-pairing')
902
+ }
903
+ } catch (err) {
904
+ log.warn(`Could not load identity-rotation cert (${err.message}); rotated clients will need to re-pair`)
905
+ }
906
+ }
907
+
908
+ // Create pairing manager for ephemeral QR-based pairing (replaces permanent token in QR)
909
+ // #6598 — how long a paired device's token survives without reconnecting
910
+ // (sliding). Operator-configurable via `sessionTokenTtl` / CHROXY_SESSION_TOKEN_TTL;
911
+ // default 30d, floored at 5min so a typo can't cause re-pair spam.
912
+ const SESSION_TOKEN_TTL_DEFAULT_MS = 30 * 24 * 60 * 60_000
913
+ const SESSION_TOKEN_TTL_FLOOR_MS = 5 * 60_000
914
+ const parsedSessionTtl = config.sessionTokenTtl ? parseDuration(config.sessionTokenTtl) : null
915
+ const sessionTokenTtlMs = Math.max(
916
+ parsedSessionTtl && parsedSessionTtl > 0 ? parsedSessionTtl : SESSION_TOKEN_TTL_DEFAULT_MS,
917
+ SESSION_TOKEN_TTL_FLOOR_MS,
918
+ )
919
+ // #6598 — persist paired tokens across restarts (encrypted at rest). Honour a
920
+ // CHROXY_CONFIG_DIR override so it sits next to config.json / credentials.json.
921
+ const chroxyDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
922
+ const pairingManager = NO_AUTH ? null : new PairingManager({
923
+ ttlMs: 60_000,
924
+ autoRefresh: true,
925
+ identityPublicKey: serverIdentity?.publicKey || null,
926
+ sessionTokenTtlMs,
927
+ sessionTokenStore: createSessionTokenStore({ dir: chroxyDir }),
928
+ })
929
+
930
+ wsServer = new WsServer({
931
+ port: PORT,
932
+ apiToken: API_TOKEN,
933
+ sessionManager,
934
+ defaultSessionId,
935
+ authRequired: !NO_AUTH,
936
+ pushManager,
937
+ maxPayload: config.maxPayload,
938
+ noEncrypt: config.noEncrypt,
939
+ // #6564 — `encryptLocalhost` (CHROXY_ENCRYPT_LOCALHOST) forces E2E encryption
940
+ // on loopback too by disabling the plaintext bypass unconditionally. Default
941
+ // off; the bypass is separately auto-disabled while a tunnel is active.
942
+ localhostBypass: !config.encryptLocalhost,
943
+ tokenManager,
944
+ pairingManager,
945
+ // #5536 — the identity keypair the WsServer uses to sign each connection's
946
+ // ephemeral exchange public key (both eager and discrete paths). Null when
947
+ // pinning is unavailable (no-auth / no-encrypt / keychain failure).
948
+ serverIdentity,
949
+ environmentManager,
950
+ // Full runtime config so handlers can consult settings at message
951
+ // time — e.g. validateCwdAllowed consults config.workspaceRoots to
952
+ // enforce the 2026-04-11 audit blocker 1 workspace allowlist.
953
+ config,
954
+ })
955
+ // Resolve the bind address. --no-auth forces loopback; otherwise an explicit
956
+ // config.host (e.g. --host 127.0.0.1) binds that interface with auth still
957
+ // on, and the default (undefined) binds 0.0.0.0 as before.
958
+ const bindHost = resolveBindHost({ noAuth: NO_AUTH, host: config.host })
959
+ // #5356 (visibility layer): one warning when binding non-loopback (the
960
+ // default 0.0.0.0 included) — LAN peers can reach the unauthenticated
961
+ // surface (/health fingerprint, dashboard assets, rate-limited auth and
962
+ // pairing attempts). No default change; points at --host 127.0.0.1.
963
+ maybeWarnNonLoopbackBind({ bindHost, log })
964
+ wsServer.start(bindHost)
965
+
966
+ // #5932: hot-reload the ~/.chroxy/models.json overlay on edit — surfacing a
967
+ // new model id (or a label/contextWindow/pricing override) is "a config entry,
968
+ // 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).
971
+ 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
+ },
976
+ })
977
+
978
+ // #5821 (live wiring): the billing canary. Recomputes the daemon's billing
979
+ // early-warnings (silent metered default; the dormant claude-tui
980
+ // reclassification tripwire) and broadcasts a `billing_canary` message when
981
+ // they change, so the dashboard can surface a banner during the 2026-06-15
982
+ // programmatic-credit window. Created after wsServer (it broadcasts through
983
+ // it); the provider is wired back into wsServer so the snapshot also seeds
984
+ // auth_ok for late joiners.
985
+ //
986
+ // #5828: datacenter-egress detection is OPT-IN via `config.billing.egressCheck`
987
+ // — only then do we pass `resolveEgressIp`, the one place the daemon makes an
988
+ // outbound IP lookup (consent-gated). `getDatacenterPrefixes` lets an operator
989
+ // add their cloud's ranges without a code change. `notify` fans a warning set
990
+ // out as a `billing_warning` push so an away operator hears about a metered
991
+ // default or a datacenter-egress flag without watching the dashboard.
992
+ const egressCheckEnabled = config.billing?.egressCheck === true
993
+ const billingCanaryMonitor = new BillingCanaryMonitor({
994
+ getSessions: () => sessionManager.listSessions(),
995
+ getDefaultProvider: () => config.provider || DEFAULT_PROVIDER,
996
+ getApiKeyAuth: () => (config.provider || DEFAULT_PROVIDER) === 'claude-sdk' && Boolean(process.env.ANTHROPIC_API_KEY),
997
+ broadcast: (msg) => { try { wsServer?.broadcast(msg) } catch { /* best-effort */ } },
998
+ logger: log,
999
+ resolveEgressIp: egressCheckEnabled ? () => resolvePublicIp() : undefined,
1000
+ getDatacenterPrefixes: () => config.billing?.datacenterPrefixes || [],
1001
+ notify: (warnings) => {
1002
+ // #5828: the monitor fires this once per distinct warning SET, plus once
1003
+ // on the non-empty→empty (all-clear) transition with an empty array. An
1004
+ // empty set is the all-clear: send a `resolved` push so the Discord
1005
+ // billing sink repaints its message green (and mobile gets a cleared
1006
+ // note). settlePush (#5702) logs both a thrown error AND a `false`
1007
+ // not-delivered return that a bare `.catch()` would drop.
1008
+ if (warnings.length === 0) {
1009
+ settlePush(
1010
+ pushManager.send('billing_warning', 'Billing alert cleared', 'All billing warnings have cleared.', { resolved: true }),
1011
+ 'billing-canary-clear',
1012
+ log,
1013
+ )
1014
+ return
1015
+ }
1016
+ // One aggregate push per distinct warning set — billing_warning has no
1017
+ // rate limit (RATE_LIMITS), so the monitor's own change-detection is the
1018
+ // throttle. Codes ride in `data` for clients that key off them.
1019
+ const count = warnings.length
1020
+ const title = count > 1 ? `Billing alert (${count})` : 'Billing alert'
1021
+ const body = warnings.map((w) => w.message).join('\n\n')
1022
+ const codes = warnings.map((w) => w.code)
1023
+ settlePush(pushManager.send('billing_warning', title, body, { codes }), 'billing-canary', log)
1024
+ },
1025
+ })
1026
+ wsServer.setBillingCanaryProvider(() => billingCanaryMonitor.current())
1027
+ // Recompute on session lifecycle (changes the session set the canary reads);
1028
+ // the periodic interval covers cost drift. These are additional listeners —
1029
+ // they don't replace the logging ones above.
1030
+ sessionManager.on('session_created', () => billingCanaryMonitor.refresh())
1031
+ sessionManager.on('session_destroyed', () => billingCanaryMonitor.refresh())
1032
+ billingCanaryMonitor.start()
1033
+
1034
+ // #5053: wire the pool stats aggregator to the shared pool so the
1035
+ // dashboard's GET /api/pool/stats has rolling counters (hit rate,
1036
+ // eviction-by-reason, recent evictions) to read. Default-OFF — only the
1037
+ // shared pool exists when CHROXY_DOCKER_BYOK_POOL is enabled, so this is a
1038
+ // no-op otherwise. attach() is idempotent (won't double-subscribe).
1039
+ if (isPoolEnabled(process.env)) {
1040
+ const statsPool = getSharedPool(process.env)
1041
+ if (statsPool) getSharedPoolStats().attach(statsPool)
1042
+ }
1043
+
1044
+ // Wire session timeout to WsServer viewer checks
1045
+ sessionManager.setActiveViewersFn((sid) => wsServer.hasActiveViewersForSession(sid))
1046
+ sessionManager.startSessionTimeouts()
1047
+
1048
+ // Advertise via mDNS/Bonjour for local network discovery. Suppressed on a
1049
+ // loopback bind and when auth is off — see maybeAdvertiseMdns (#5280).
1050
+ const { mdnsService, bonjourInstance } = await maybeAdvertiseMdns({
1051
+ noAuth: NO_AUTH,
1052
+ bindHost,
1053
+ port: PORT,
1054
+ version: SERVER_VERSION,
1055
+ hasToken: !!API_TOKEN,
1056
+ log,
1057
+ })
1058
+
1059
+ // Track the live tunnel handle across modes (consumed by shutdown below).
1060
+ let tunnel = null
1061
+
1062
+ // #5368 slice (b): the connection display — QR render + manual-connect block +
1063
+ // the connection-info side-car (displayQr), the ephemeral pairing-URL builder
1064
+ // (buildPairingUrl), the current-URL/mode display state shared across modes,
1065
+ // and the QR re-render listeners — lives in StartupDisplay. The mode branches
1066
+ // below set `startupDisplay.currentWsUrl` / `currentTunnelMode` and call
1067
+ // `startupDisplay.displayQr(...)`. The tunnel path sets currentWsUrl EARLY
1068
+ // (before the first displayQr) so a mid-startup tunnel_recovered has a value to
1069
+ // diff against — so displayQr deliberately does not mutate that state.
1070
+ const startupDisplay = new StartupDisplay({
1071
+ pairingManager,
1072
+ tokenManager,
1073
+ apiToken: API_TOKEN,
1074
+ showToken: !!config.showToken || process.env.CHROXY_SHOW_TOKEN === '1',
1075
+ logger: log,
1076
+ })
1077
+
1078
+ // External URL mode: reverse proxy / custom domain (skip tunnel entirely)
1079
+ const externalUrl = config.externalUrl || null
1080
+ if (externalUrl) {
1081
+ const wsUrl = externalUrl.replace(/^https?:\/\//, 'wss://')
1082
+ startupDisplay.currentWsUrl = wsUrl
1083
+ startupDisplay.currentTunnelMode = 'external'
1084
+ const httpUrl = externalUrl.replace(/^wss?:\/\//, 'https://')
1085
+ await startupDisplay.displayQr(wsUrl, httpUrl, 'external')
1086
+ }
1087
+
1088
+ // Determine tunnel mode
1089
+ const tunnelArg = parseTunnelArg(config.tunnel || 'quick')
1090
+ const SKIP_TUNNEL = NO_AUTH || !tunnelArg || !!externalUrl
1091
+
1092
+ if (!SKIP_TUNNEL) {
1093
+ // #5356 (visibility layer): record quick-tunnel exposure before startup so
1094
+ // the auth_ok exposure snapshot covers clients that connect mid-warming.
1095
+ wsServer.setQuickTunnelActive(tunnelArg.mode === 'quick')
1096
+ // #5368 slice (c): the tunnel lifecycle (create + start + emergency-cleanup
1097
+ // on a start throw, wireTunnelEvents, tunnel_recovered re-verify + QR
1098
+ // re-render, waitForTunnel with warming/ready broadcasts + emergency-cleanup
1099
+ // on failure, success QR + pairing-id extension) lives in
1100
+ // TunnelLifecycleHandler. The function deps are passed in (createTunnel /
1101
+ // waitForTunnel as test seams; emergencyCleanup / wireTunnelEvents /
1102
+ // buildTunnel*Status are server-cli-defined, so injecting avoids a circular
1103
+ // import). On startup failure it returns ok:false after the full cleanup —
1104
+ // preserving startCliServer's original `process.exitCode = 1; return`.
1105
+ const tunnelHandler = new TunnelLifecycleHandler({
1106
+ createTunnel,
1107
+ emergencyCleanup,
1108
+ wireTunnelEvents,
1109
+ waitForTunnel,
1110
+ buildTunnelWarmingStatus,
1111
+ buildTunnelReadyStatus,
1112
+ config: {
1113
+ port: PORT,
1114
+ tunnelArg,
1115
+ tunnelConfig: config.tunnelConfig,
1116
+ tunnelName: config.tunnelName || null,
1117
+ tunnelHostname: config.tunnelHostname || null,
1118
+ },
1119
+ wsServer,
1120
+ startupDisplay,
1121
+ pairingManager,
1122
+ cleanupRefs: { mdnsService, bonjourInstance, tokenManager, sessionManager },
1123
+ logger: log,
1124
+ })
1125
+ const result = await tunnelHandler.createAndStart()
1126
+ tunnel = result.tunnel || tunnel
1127
+ if (!result.ok) {
1128
+ process.exitCode = 1
1129
+ return
1130
+ }
1131
+
1132
+ } else if (externalUrl) {
1133
+ // Ready message already printed above
1134
+ } else if (!tunnelArg && !NO_AUTH) {
1135
+ // When bound to loopback the LAN IP is not reachable — advertise localhost.
1136
+ // When bound to a specific non-loopback interface, advertise that exact
1137
+ // address (getLanIp() returns the first NIC, which may not be the bound
1138
+ // one). Otherwise (default 0.0.0.0 bind) fall back to the discovered LAN IP.
1139
+ const host = isLoopbackHost(bindHost)
1140
+ ? 'localhost'
1141
+ : (bindHost && bindHost !== '0.0.0.0' ? bindHost : (getLanIp() || 'localhost'))
1142
+ // Bracket IPv6 literals so the URL authority is well-formed.
1143
+ const authority = `${formatHostForUrl(host)}:${PORT}`
1144
+ startupDisplay.currentWsUrl = `ws://${authority}`
1145
+ await startupDisplay.displayQr(`ws://${authority}`, `http://${authority}`, 'none')
1146
+ } else if (!NO_AUTH) {
1147
+ // tunnelArg is set but SKIP_TUNNEL is true due to externalUrl — already handled above
1148
+ } else {
1149
+ console.log(`[✓] Server ready! (CLI headless mode, no auth)\n`)
1150
+ console.log(` Connect: ws://localhost:${PORT}`)
1151
+ console.log(` Dashboard: http://localhost:${PORT}/dashboard`)
1152
+ }
1153
+
1154
+ // #5368 slice (b): QR re-render on pairing auto-refresh + token rotation now
1155
+ // lives in StartupDisplay (it owns displayQr + the current-URL state the
1156
+ // listeners read). Wired here, after the mode branches set the initial URL.
1157
+ startupDisplay.wireReRenderListeners()
1158
+
1159
+ // #5158: opt-in worktree auto-reaper. When enabled, reclaim orphaned
1160
+ // dead-pid-locked agent worktrees (clean trees only, never --force). Lazily
1161
+ // imported so a default (disabled) boot pays nothing and a failure here never
1162
+ // affects startup; the reaper itself yields between repos so the sweep
1163
+ // doesn't starve the loop.
1164
+ //
1165
+ // #5326 (WP-5.4): sweep once at boot AND on a recurring unref'd interval, so
1166
+ // a long-running daemon reclaims worktrees created mid-run without a restart.
1167
+ // The timer handle is assigned inside the async import .then(); if shutdown
1168
+ // races ahead of the import resolving, the clearInterval below is skipped —
1169
+ // tolerated because the interval is unref'd and process.exit reaps it anyway.
1170
+ let worktreeReapTimer = null
1171
+ if (config.worktreeGc?.autoReap === true) {
1172
+ import('./worktree-reaper.js')
1173
+ .then(({ startPeriodicAutoReap }) => { worktreeReapTimer = startPeriodicAutoReap(config, log) })
1174
+ .catch((err) => log.warn(`worktree auto-reaper failed: ${(err && err.message) || err}`))
1175
+ }
1176
+
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}`))
1185
+
1186
+ console.log('\nPress Ctrl+C to stop.\n')
1187
+
1188
+ // Graceful shutdown.
1189
+ // Idempotent: a second SIGINT/SIGTERM (or a crash arriving mid-shutdown)
1190
+ // returns immediately. Without this, the second call ran serializeState()
1191
+ // against an already-empty `_sessions` Map and wrote 0 sessions to disk,
1192
+ // erasing the user's restored state across upgrade/quit cycles (#3697).
1193
+ // #5368 slice (d): the process lifecycle — the shuttingDown latch, the
1194
+ // graceful shutdown() teardown sequence, and the SIGINT/SIGTERM/SIGHUP/
1195
+ // uncaughtException/unhandledRejection registrations (#5369 onFatal +
1196
+ // emergencyCleanupSync) — lives in ServerOrchestrator. `worktreeReapTimer` is
1197
+ // passed as a GETTER because it's assigned inside an async import().then() and
1198
+ // may still be null now — the original shutdown closure read it lazily at
1199
+ // shutdown time, so the getter reproduces that. emergencyCleanupSync is
1200
+ // injected (server-cli-defined → avoids a circular import).
1201
+ const orchestrator = new ServerOrchestrator({
1202
+ wsServer,
1203
+ sessionManager,
1204
+ tunnel,
1205
+ mdnsService,
1206
+ bonjourInstance,
1207
+ tokenManager,
1208
+ pairingManager,
1209
+ pushManager,
1210
+ billingCanaryMonitor,
1211
+ modelsOverlayWatcher,
1212
+ getWorktreeReapTimer: () => worktreeReapTimer,
1213
+ emergencyCleanupSync,
1214
+ removeConnectionInfo,
1215
+ isPoolEnabled,
1216
+ getSharedPool,
1217
+ logger: log,
1218
+ })
1219
+ orchestrator.install()
1220
+
1221
+ // Return references for supervised child drain protocol
1222
+ return { sessionManager, wsServer }
1223
+ }