@chroxy/server 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
package/src/doctor.js ADDED
@@ -0,0 +1,667 @@
1
+ import { execFileSync } from 'child_process'
2
+ import { existsSync, readFileSync } from 'fs'
3
+ import { dirname, isAbsolute, join, resolve } from 'path'
4
+ import { fileURLToPath } from 'url'
5
+ import { homedir, platform } from 'os'
6
+ import { createServer } from 'net'
7
+ import { validateConfig } from './config.js'
8
+ import { resolveBinary } from './utils/resolve-binary.js'
9
+ import { prepareSpawn } from './utils/win-spawn.js'
10
+ import { getProvider, DEFAULT_PROVIDER } from './providers.js'
11
+ import { registerAnthropicCompatibleProviders } from './anthropic-compatible-session.js'
12
+ import { registerOpenAiCompatibleProviders } from './openai-compatible-session.js'
13
+ import { parseTunnelArg } from './tunnel/index.js'
14
+ import { TESTED_CLAUDE_TUI_CLI_VERSION } from './claude-tui/tested-cli-version.js'
15
+ import { detectSilentMeteredDefault } from './doctor-billing.js'
16
+ import { keychainHealth } from './keychain.js'
17
+ import {
18
+ billingClassForProvider,
19
+ billingDetailForClass,
20
+ isProgrammaticCreditEra,
21
+ PROGRAMMATIC_CREDIT_ERA_START,
22
+ } from './billing-class.js'
23
+ import { checkDependencies } from './utils/check-dependencies.js'
24
+
25
+ // Resolve the server package root (the directory containing package.json
26
+ // and node_modules) so dependency checks work regardless of where the
27
+ // server process was launched. `import.meta.url` points to this file at
28
+ // src/doctor.js — two `dirname` calls walk from the file up through
29
+ // src/ to the package root.
30
+ const __filename = fileURLToPath(import.meta.url)
31
+ const SERVER_PKG_DIR = dirname(dirname(__filename))
32
+
33
+ // Honor CHROXY_CONFIG_DIR (the repo-wide convention — connection-info.js,
34
+ // models.js, etc.) so the config read resolves to the same dir as every other
35
+ // reader. Without this, doctor read the REAL ~/.chroxy in tests despite
36
+ // tests/_setup.mjs redirecting CHROXY_CONFIG_DIR to a tmp dir — which would let
37
+ // the named-tunnel routability probe (#5328) fire a live network request from
38
+ // a maintainer's real config during the suite.
39
+ const CONFIG_FILE = join(process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy'), 'config.json')
40
+
41
+ /**
42
+ * Parse the leading `major.minor.patch` semver out of an arbitrary version
43
+ * string (e.g. "2.1.163 (Claude Code)" → [2, 1, 163]). Returns null when no
44
+ * leading semver is present so callers can degrade gracefully rather than
45
+ * hard-fail on an unexpected version format. Pre-release / build suffixes
46
+ * are ignored — only the numeric core is compared. (#3953)
47
+ *
48
+ * @param {string} str
49
+ * @returns {[number, number, number] | null}
50
+ */
51
+ export function parseLeadingSemver(str) {
52
+ if (typeof str !== 'string') return null
53
+ const m = str.trim().match(/^v?(\d+)\.(\d+)\.(\d+)/)
54
+ if (!m) return null
55
+ return [Number(m[1]), Number(m[2]), Number(m[3])]
56
+ }
57
+
58
+ /**
59
+ * Compare two semver values. `found` may be a string or a parsed
60
+ * `[major, minor, patch]` tuple; `required` is a semver string. Returns a
61
+ * negative number when `found` < `required`, 0 when equal (on the numeric
62
+ * core), positive when greater.
63
+ *
64
+ * Both sides fail CLOSED: an unparseable `found` OR an unparseable
65
+ * `required` sorts as less-than (returns negative) so the floor is treated
66
+ * as NOT satisfied. This matters for `required` too — a provider that
67
+ * accidentally supplies a non-`major.minor.patch` floor (e.g. ">=2.1.80"
68
+ * or "2.1.80-beta") must not silently disable minVersion enforcement
69
+ * (Copilot review on #3953). (#3953)
70
+ *
71
+ * @param {string | [number, number, number]} found
72
+ * @param {string} required
73
+ * @returns {number}
74
+ */
75
+ export function compareSemver(found, required) {
76
+ const a = Array.isArray(found) ? found : parseLeadingSemver(found)
77
+ const b = parseLeadingSemver(required)
78
+ // Fail closed on either side: a malformed floor (b) or version (a) is
79
+ // treated as "not satisfied" so an enforcement gate can never pass by
80
+ // accident. Returns negative (found < required) in every invalid case.
81
+ if (!a || !b) return -1
82
+ for (let i = 0; i < 3; i++) {
83
+ if (a[i] !== b[i]) return a[i] - b[i]
84
+ }
85
+ return 0
86
+ }
87
+
88
+ /**
89
+ * Detect whether the server is running inside a bundled .app (Tauri) or
90
+ * under the supervisor process. In either case, the end user cannot fix
91
+ * a missing dependency / broken install themselves by running `npm install`
92
+ * — they need a reinstall or rebuild. Checks affected by this distinction
93
+ * (Dependencies, and likely cloudflared / Node version / port soon)
94
+ * downgrade `fail` → `warn` and surface a context-appropriate hint.
95
+ *
96
+ * Centralised here so:
97
+ * - The detection lives in one place as more checks adopt it
98
+ * - Tests can stub `process.env` once (or import this helper directly)
99
+ * instead of duplicating the env-var pattern at every call site
100
+ *
101
+ * Exported for tests; production callers should prefer using the helper
102
+ * from within `runDoctorChecks`.
103
+ *
104
+ * @returns {boolean} true when CHROXY_BUNDLED=1 OR CHROXY_SUPERVISED=1
105
+ */
106
+ export function isBundledOrSupervisedContext() {
107
+ return process.env.CHROXY_BUNDLED === '1' || process.env.CHROXY_SUPERVISED === '1'
108
+ }
109
+
110
+ /**
111
+ * Resolve the list of providers to preflight check.
112
+ *
113
+ * Precedence:
114
+ * 1. Explicit `providers` option (array of provider names)
115
+ * 2. `provider` field from loaded config file
116
+ * 3. DEFAULT_PROVIDER (see providers.js)
117
+ *
118
+ * Returns an array of provider name strings.
119
+ */
120
+ function resolveProviders({ providers, configProvider }) {
121
+ if (Array.isArray(providers) && providers.length > 0) return providers
122
+ if (typeof configProvider === 'string' && configProvider.length > 0) return [configProvider]
123
+ return [DEFAULT_PROVIDER]
124
+ }
125
+
126
+ /**
127
+ * The claude-tui provider's preflight binary candidate paths (homebrew, ~/.local,
128
+ * npm-global, etc.), so the version-pin check resolves `claude` the same way the
129
+ * provider preflight does. Best-effort: returns [] if the spec isn't shaped as
130
+ * expected (the check then falls back to PATH resolution). (#5871)
131
+ */
132
+ function claudeTuiBinaryCandidates() {
133
+ try {
134
+ const Provider = getProvider('claude-tui')
135
+ const candidates = Provider?.preflight?.binary?.candidates
136
+ return Array.isArray(candidates) ? candidates : []
137
+ } catch {
138
+ return []
139
+ }
140
+ }
141
+
142
+ /**
143
+ * audit P1-3 / #5821: compare the installed claude CLI version against the
144
+ * version chroxy's claude-tui form-driving was validated against
145
+ * (TESTED_CLAUDE_TUI_CLI_VERSION). A major.minor drift is a `warn` — the
146
+ * keystroke driving may mis-resolve forms after a CLI UI change; an exact or
147
+ * patch-only difference is a `pass`. Returns null when claude can't be run (the
148
+ * provider binary check already reports a missing claude). Dependency-injected
149
+ * for tests.
150
+ *
151
+ * @param {object} [deps]
152
+ * @param {(bin: string, args: string[]) => string} [deps.exec]
153
+ * @param {string} [deps.tested]
154
+ * @param {string[]} [deps.candidates] - fallback absolute paths for resolveBinary
155
+ * @returns {{ name: string, status: 'pass'|'warn', message: string } | null}
156
+ */
157
+ export function checkClaudeTuiCliVersion(deps = {}) {
158
+ const {
159
+ // #6484 — route through prepareSpawn so a `.cmd` shim (npm-only Windows host)
160
+ // is run via cmd.exe instead of hitting Node 24's `.cmd` EINVAL. No-op for
161
+ // `.exe`/POSIX. Most tests inject their own `exec`, bypassing this; the
162
+ // win32-routing test exercises this default path directly.
163
+ exec = (bin, args) => {
164
+ const s = prepareSpawn(bin, args)
165
+ return execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], ...s.options })
166
+ },
167
+ tested = TESTED_CLAUDE_TUI_CLI_VERSION,
168
+ // #5871: resolve against the SAME candidate paths the claude-tui provider
169
+ // preflight uses, so this drift backstop isn't silently skipped in a
170
+ // minimal-PATH (Tauri/launchd) install where the provider check still finds
171
+ // claude via its candidate list — exactly the bundled context where a
172
+ // silent mis-drive would otherwise go unnoticed.
173
+ candidates = claudeTuiBinaryCandidates(),
174
+ } = deps
175
+ let output
176
+ try {
177
+ output = exec(resolveBinary('claude', candidates), ['--version'])
178
+ } catch {
179
+ return null // claude missing/hung — the provider binary check surfaces that
180
+ }
181
+ const NAME = 'claude-tui driving'
182
+ const found = parseLeadingSemver(output)
183
+ const testedSemver = parseLeadingSemver(tested)
184
+ if (found === null) {
185
+ return { name: NAME, status: 'warn', message: `Could not parse 'claude --version'; TUI form-driving is validated against ${tested}` }
186
+ }
187
+ const foundStr = `${found[0]}.${found[1]}.${found[2]}`
188
+ if (testedSemver && found[0] === testedSemver[0] && found[1] === testedSemver[1]) {
189
+ return { name: NAME, status: 'pass', message: `claude ${foundStr} matches the tested TUI-driving baseline (${tested})` }
190
+ }
191
+ return {
192
+ name: NAME,
193
+ status: 'warn',
194
+ message: `claude ${foundStr} differs from the tested TUI-driving baseline (${tested}) — chroxy drives the TUI by screen-scraping pinned keystrokes, so a CLI UI change can mis-drive AskUserQuestion forms silently. If question prompts misbehave, report it; re-validation will bump the baseline.`,
195
+ }
196
+ }
197
+
198
+ /**
199
+ * #5328 (WP-5.6) — default end-to-end routability probe for a named tunnel:
200
+ * a HEAD request to the tunnel hostname with a hard timeout. ANY HTTP response
201
+ * (even 4xx/5xx/426-upgrade, and whether it comes from the chroxy origin or a
202
+ * Cloudflare edge error page) means the hostname resolves and the edge answered
203
+ * — i.e. the route is live enough to reach. Only a network/DNS error or a
204
+ * timeout (caught here, returned as `{ ok: false }`) means the path is broken.
205
+ * Uses the Node 22 global `fetch` + `AbortController`; no new dependency.
206
+ */
207
+ async function defaultHttpsProbe(url, timeoutMs) {
208
+ const controller = new AbortController()
209
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
210
+ try {
211
+ const res = await fetch(url, { method: 'HEAD', signal: controller.signal, redirect: 'manual' })
212
+ return { ok: true, status: res.status }
213
+ } catch (err) {
214
+ const error = err?.name === 'AbortError' ? `timed out after ${timeoutMs}ms` : (err?.message || String(err))
215
+ return { ok: false, error }
216
+ } finally {
217
+ clearTimeout(timer)
218
+ }
219
+ }
220
+
221
+ /**
222
+ * #5328 (WP-5.6) — probe whether a configured NAMED tunnel's hostname is
223
+ * actually routable end-to-end, so `chroxy doctor` distinguishes "cloudflared
224
+ * is installed" (the binary check) from "the edge → origin path resolves".
225
+ *
226
+ * Skipped (returns null) unless a named tunnel with a hostname is configured —
227
+ * a quick tunnel's URL is random and runtime-only, so doctor can't know it
228
+ * ahead of time. A reachable hostname is a `pass`; an unreachable one is a
229
+ * `warn` (a diagnostic, not a hard failure: the daemon still runs on localhost).
230
+ *
231
+ * @param {object} [deps]
232
+ * @param {string|null} [deps.hostname] - the configured named-tunnel hostname
233
+ * @param {string|null} [deps.mode] - the configured tunnel mode ('named'|'quick'|'none')
234
+ * @param {(url: string, timeoutMs: number) => Promise<{ ok: boolean, status?: number, error?: string }>} [deps.probe]
235
+ * @param {number} [deps.timeoutMs]
236
+ * @returns {Promise<{ name: string, status: 'pass'|'warn', message: string } | null>}
237
+ */
238
+ export async function checkTunnelRoutability(deps = {}) {
239
+ const { hostname = null, mode = null, timeoutMs = 5000, probe = defaultHttpsProbe } = deps
240
+ if (mode !== 'named' || typeof hostname !== 'string') return null
241
+ const NAME = 'Tunnel routability'
242
+ // Trim and reject anything that isn't a bare host — a stray scheme, path,
243
+ // userinfo (`@`), or whitespace in the configured `tunnelHostname` would make
244
+ // `https://${hostname}/` probe a DIFFERENT host than intended (or build an
245
+ // invalid URL). Surface it as a warn rather than silently probing the wrong
246
+ // place. A bare `host` or `host:port` is fine.
247
+ const host = hostname.trim()
248
+ if (host.length === 0) return null
249
+ if (/[\s/@]/.test(host) || host.includes('://')) {
250
+ return {
251
+ name: NAME,
252
+ status: 'warn',
253
+ message: `Configured tunnelHostname '${hostname}' is not a bare host — expected e.g. 'tunnel.example.com', not a URL. Run 'chroxy tunnel setup' to (re)configure.`,
254
+ }
255
+ }
256
+ let result
257
+ try {
258
+ result = await probe(`https://${host}/`, timeoutMs)
259
+ } catch (err) {
260
+ // A probe should resolve { ok: false }, never throw — but never let a
261
+ // diagnostic crash the whole doctor run.
262
+ result = { ok: false, error: err?.message || String(err) }
263
+ }
264
+ if (result && result.ok) {
265
+ const code = typeof result.status === 'number' ? ` (HTTP ${result.status})` : ''
266
+ return { name: NAME, status: 'pass', message: `${host} is reachable${code}` }
267
+ }
268
+ return {
269
+ name: NAME,
270
+ status: 'warn',
271
+ message: `${host} did not respond${result?.error ? ` (${result.error})` : ''} — the DNS route may be missing or the named tunnel is down. Run 'chroxy tunnel setup' to (re)configure.`,
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Run all preflight dependency checks and return results.
277
+ *
278
+ * Provider-aware: only runs the binary/credential checks for the
279
+ * provider(s) configured for this install. A Gemini-only user won't
280
+ * fail because `claude` is missing, and a Claude-only user won't be
281
+ * warned about missing `codex` or `OPENAI_API_KEY` (issue #2951).
282
+ *
283
+ * @param {Object} [options]
284
+ * @param {number} [options.port] - Port to test availability for
285
+ * @param {string[]} [options.providers] - Override configured providers (mainly for tests)
286
+ * @param {boolean} [options.verbose]
287
+ * @param {string} [options.pkgDir] - Override directory used to locate node_modules for the
288
+ * Dependencies check. Defaults to the server package root. Relative paths are resolved to
289
+ * absolute at call time so the check is fully decoupled from process.cwd(). Exposed so
290
+ * tests can point the check at a temp directory without mutating process.cwd().
291
+ * @returns {{ checks: Array<{ name: string, status: 'pass'|'warn'|'fail', message: string, provider?: string }>, passed: boolean, providers: string[] }}
292
+ */
293
+ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgDir = SERVER_PKG_DIR, now = Date.now(), tunnelProbe } = {}) {
294
+ const checks = []
295
+ const isMac = platform() === 'darwin'
296
+ const isLinux = platform() === 'linux'
297
+
298
+ // 1. Node.js version
299
+ const nodeVersion = process.versions.node
300
+ const major = parseInt(nodeVersion.split('.')[0], 10)
301
+ if (major === 22) {
302
+ checks.push({ name: 'Node.js', status: 'pass', message: `v${nodeVersion}` })
303
+ } else if (major > 22) {
304
+ checks.push({ name: 'Node.js', status: 'warn', message: `v${nodeVersion} — Node 22 is recommended` })
305
+ } else {
306
+ checks.push({ name: 'Node.js', status: 'fail', message: `v${nodeVersion} — Node 22 required` })
307
+ }
308
+
309
+ // 2. cloudflared
310
+ checks.push(checkBinary('cloudflared', ['--version'], {
311
+ parseVersion: (out) => out.trim().split('\n')[0],
312
+ required: true,
313
+ candidates: [
314
+ '/opt/homebrew/bin/cloudflared',
315
+ '/usr/local/bin/cloudflared',
316
+ join(homedir(), '.local/bin/cloudflared'),
317
+ ],
318
+ installHint: isMac ? 'brew install cloudflared'
319
+ : isLinux ? 'see https://pkg.cloudflare.com/ for installation'
320
+ : 'see https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/',
321
+ }))
322
+
323
+ // 3. Load config (once) — used for both the Config check and provider resolution.
324
+ let configProvider = null
325
+ let configCheck = null
326
+ // #5328 (WP-5.6): named-tunnel coordinates for the routability probe (step 5.6).
327
+ let tunnelMode = null
328
+ let tunnelHostname = null
329
+ if (existsSync(CONFIG_FILE)) {
330
+ try {
331
+ const config = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'))
332
+ if (typeof config.provider === 'string') configProvider = config.provider
333
+ // Normalize the tunnel mode through parseTunnelArg so aliases resolve —
334
+ // e.g. `cloudflare:named` (a documented --tunnel form persisted verbatim)
335
+ // maps to mode 'named' and isn't silently skipped by the routability
336
+ // probe. parseTunnelArg throws on an unknown value; validateConfig already
337
+ // surfaces that, so treat it as "no probe" here rather than crashing doctor.
338
+ if (typeof config.tunnel === 'string') {
339
+ try {
340
+ tunnelMode = parseTunnelArg(config.tunnel)?.mode ?? null
341
+ } catch {
342
+ tunnelMode = null
343
+ }
344
+ }
345
+ if (typeof config.tunnelHostname === 'string') tunnelHostname = config.tunnelHostname
346
+ // #5419: register config-driven Anthropic-compatible endpoints before
347
+ // provider resolution so a config.provider pointing at one preflights
348
+ // its credential spec instead of failing as "Unknown provider".
349
+ // Invalid entries are warned about (and surface again through
350
+ // validateConfig below) and skipped.
351
+ registerAnthropicCompatibleProviders(config)
352
+ // #5420: register config-driven OpenAI-compatible endpoints too, same
353
+ // rationale as above — a config.provider pointing at one preflights its
354
+ // credential spec instead of failing as "Unknown provider".
355
+ registerOpenAiCompatibleProviders(config)
356
+ const { valid, warnings } = validateConfig(config)
357
+ if (valid) {
358
+ configCheck = { name: 'Config', status: 'pass', message: CONFIG_FILE }
359
+ } else {
360
+ configCheck = { name: 'Config', status: 'warn', message: `${CONFIG_FILE} — ${warnings.join('; ')}` }
361
+ }
362
+ } catch (err) {
363
+ if (err instanceof SyntaxError) {
364
+ configCheck = { name: 'Config', status: 'fail', message: `${CONFIG_FILE} — invalid JSON: ${err.message}` }
365
+ } else {
366
+ configCheck = { name: 'Config', status: 'fail', message: `${CONFIG_FILE} — ${err.message}` }
367
+ }
368
+ }
369
+ } else {
370
+ configCheck = { name: 'Config', status: 'warn', message: `Not found — run 'npx chroxy init' to create` }
371
+ }
372
+
373
+ // 4. Provider-specific checks. Each configured provider contributes its
374
+ // own binary and credential checks. Providers not in the user's config
375
+ // are skipped entirely — a Gemini-only install does NOT fail because
376
+ // `claude` is missing (#2951).
377
+ const resolvedProviders = resolveProviders({ providers, configProvider })
378
+ for (const providerName of resolvedProviders) {
379
+ const providerChecks = checkProvider(providerName)
380
+ for (const c of providerChecks) checks.push(c)
381
+ }
382
+
383
+ // 5. Config check — appended after provider checks so per-provider
384
+ // sections group together in the output report.
385
+ checks.push(configCheck)
386
+
387
+ // Credential storage (#6236). Surface WHERE the API token + credentials
388
+ // actually live and whether the OS keychain is healthy — the #6235 fallback to
389
+ // the 0600 file on a broken/missing login keychain is otherwise silent. A
390
+ // broken keychain is a WARN (secrets work but aren't in the keychain + the
391
+ // operator gets a repair hint); disabled/unsupported/usable are informational
392
+ // PASS. keychainHealth() is non-prompting, so this never pops the macOS modal.
393
+ const kh = keychainHealth()
394
+ checks.push({
395
+ name: 'Credential storage',
396
+ status: kh.status === 'broken' ? 'warn' : 'pass',
397
+ message:
398
+ kh.status === 'usable'
399
+ ? 'OS keychain'
400
+ : kh.repairHint
401
+ ? `file fallback — ${kh.detail} — fix: ${kh.repairHint}`
402
+ : `file fallback — ${kh.detail}`,
403
+ })
404
+
405
+ // 5.6 Tunnel routability (#5328 WP-5.6). For a configured NAMED tunnel, probe
406
+ // the hostname end-to-end so a broken DNS route / down tunnel is visible here
407
+ // rather than only as a failed remote connection later. Skipped for quick /
408
+ // no tunnel (no stable hostname to probe). `tunnelProbe` is injectable so the
409
+ // check is testable without a real network round-trip.
410
+ const tunnelCheck = await checkTunnelRoutability({
411
+ hostname: tunnelHostname,
412
+ mode: tunnelMode,
413
+ ...(tunnelProbe ? { probe: tunnelProbe } : {}),
414
+ })
415
+ if (tunnelCheck) checks.push(tunnelCheck)
416
+
417
+ // 5.5 Billing canary (#5821, audit rec #4). Standalone-feasible half of the
418
+ // canary: the silent-metered-default check needs only the resolved default
419
+ // provider + the clock. (The reclassification + datacenter-egress checks in
420
+ // doctor-billing.js need live daemon state / a network lookup, so they're
421
+ // consumed by the daemon/dashboard, not this preflight.) Use the same
422
+ // resolution as the provider checks above — explicit `providers` override
423
+ // wins (for tests), else config.provider, else DEFAULT_PROVIDER — so the
424
+ // billing line tracks whichever provider a zero-config session would use.
425
+ const effectiveDefault = resolvedProviders[0] || DEFAULT_PROVIDER
426
+ // billing-class refinement: claude-sdk authed with an explicit ANTHROPIC_API_KEY
427
+ // bills the raw API account (api-key), not the metered credit pool — so a BYOK
428
+ // default must not trip a false silent-metered warning. claude-cli strips the key
429
+ // before spawn, so the env var doesn't change its class; only claude-sdk honours
430
+ // it here, matching sdk-session's auth resolution.
431
+ const apiKeyAuth = effectiveDefault === 'claude-sdk' && Boolean(process.env.ANTHROPIC_API_KEY)
432
+ const meteredWarnings = detectSilentMeteredDefault(effectiveDefault, now, { apiKeyAuth })
433
+ if (meteredWarnings.length > 0) {
434
+ checks.push({ name: 'Billing', status: 'warn', message: meteredWarnings[0].message })
435
+ } else {
436
+ const billingClass = billingClassForProvider(effectiveDefault, now, { apiKeyAuth })
437
+ const detail = billingDetailForClass(billingClass)
438
+ if (isProgrammaticCreditEra(now)) {
439
+ checks.push({
440
+ name: 'Billing',
441
+ status: 'pass',
442
+ message: `Default provider '${effectiveDefault}' — ${detail}`,
443
+ })
444
+ } else {
445
+ // Pre-cutover: nothing meters yet, but surface the upcoming boundary and
446
+ // what the default will bill once it lands.
447
+ const cutover = new Date(PROGRAMMATIC_CREDIT_ERA_START).toISOString().slice(0, 10)
448
+ checks.push({
449
+ name: 'Billing',
450
+ status: 'pass',
451
+ message: `Default provider '${effectiveDefault}' — ${detail}. Programmatic-credit cutover: ${cutover}.`,
452
+ })
453
+ }
454
+ }
455
+
456
+ // 5.6 claude-tui CLI version pin (audit P1-3, #5821 backstop). The claude-tui
457
+ // provider drives the real `claude` TUI by screen-scraping pinned keystrokes
458
+ // (no structured answer channel), so a CLI UI change can mis-drive
459
+ // AskUserQuestion forms SILENTLY. Surface a major.minor drift from the tested
460
+ // version as a measured warning instead. Only meaningful when the default
461
+ // provider actually drives the TUI.
462
+ if (effectiveDefault === 'claude-tui') {
463
+ const tuiCheck = checkClaudeTuiCliVersion()
464
+ if (tuiCheck) checks.push(tuiCheck)
465
+ }
466
+
467
+ // 6. Dependencies
468
+ // Resolve deps relative to the server package, not process.cwd() — Tauri
469
+ // launches the server with cwd='/' under launchd, which would always
470
+ // fail a `${process.cwd()}/node_modules` check. Tests may override
471
+ // `pkgDir` to point at a temp directory. Normalize to an absolute
472
+ // path so a relative `pkgDir` can't reintroduce cwd coupling.
473
+ //
474
+ // Also handles npm workspace hoisting: deps may live in a parent
475
+ // node_modules/ when installed via `npm ci --workspace=@chroxy/server`.
476
+ // The helper walks up the tree and uses createRequire as a reliable
477
+ // proxy for whether deps are installed.
478
+ //
479
+ // Context-aware severity: when running inside a bundled .app (Tauri) or
480
+ // under the supervisor, a missing node_modules is unactionable for the
481
+ // end user — they can't run `npm install` to fix it, they need a new
482
+ // build or reinstall. In that context we downgrade to `warn` and provide
483
+ // an appropriate message. In a dev environment the original `fail` +
484
+ // "run npm install" message is preserved.
485
+ if (typeof pkgDir !== 'string' || pkgDir.length === 0) {
486
+ throw new TypeError(`pkgDir must be a non-empty string, got ${typeof pkgDir}`)
487
+ }
488
+ const absPkgDir = isAbsolute(pkgDir) ? pkgDir : resolve(pkgDir)
489
+ const deps = checkDependencies({
490
+ startDir: absPkgDir,
491
+ probes: ['commander', 'ws', '@anthropic-ai/claude-agent-sdk'],
492
+ })
493
+ if (deps.ok) {
494
+ checks.push({ name: 'Dependencies', status: 'pass', message: `resolved via ${deps.foundAt}` })
495
+ } else {
496
+ if (isBundledOrSupervisedContext()) {
497
+ checks.push({
498
+ name: 'Dependencies',
499
+ status: 'warn',
500
+ message: `${deps.message || 'dependencies not found'} — reinstall Chroxy or rebuild the app`,
501
+ })
502
+ } else {
503
+ checks.push({
504
+ name: 'Dependencies',
505
+ status: 'fail',
506
+ message: `${deps.message || 'dependencies not found'} — run npm install`,
507
+ })
508
+ }
509
+ }
510
+
511
+ // 7. Port availability
512
+ const checkPort = port || 8765
513
+ try {
514
+ await checkPortAvailable(checkPort)
515
+ checks.push({ name: 'Port', status: 'pass', message: `${checkPort} is available` })
516
+ } catch {
517
+ checks.push({ name: 'Port', status: 'warn', message: `${checkPort} is in use (server may already be running)` })
518
+ }
519
+
520
+ const passed = checks.every(c => c.status !== 'fail')
521
+ return { checks, passed, providers: resolvedProviders }
522
+ }
523
+
524
+ /**
525
+ * Run the binary + credential preflight for a single registered provider.
526
+ *
527
+ * Reads `ProviderClass.preflight` to learn what binary and env vars the
528
+ * provider needs. Unknown providers contribute a single `fail` check so
529
+ * bad config is reported rather than silently ignored.
530
+ *
531
+ * @param {string} providerName
532
+ * @returns {Array<{ name: string, status: 'pass'|'warn'|'fail', message: string, provider: string }>}
533
+ */
534
+ function checkProvider(providerName) {
535
+ let ProviderClass
536
+ try {
537
+ ProviderClass = getProvider(providerName)
538
+ } catch (err) {
539
+ return [{
540
+ name: `Provider: ${providerName}`,
541
+ status: 'fail',
542
+ message: err.message,
543
+ provider: providerName,
544
+ }]
545
+ }
546
+
547
+ const spec = ProviderClass.preflight
548
+ if (!spec) {
549
+ // Provider doesn't declare preflight requirements — nothing to check.
550
+ // Not a failure; e.g. docker-cli/docker-sdk reuse upstream provider
551
+ // binaries and can opt out.
552
+ return []
553
+ }
554
+
555
+ const out = []
556
+ if (spec.binary) {
557
+ const bin = checkBinary(spec.binary.name, spec.binary.args || ['--version'], {
558
+ parseVersion: spec.binary.parseVersion || ((out) => out.trim().split('\n')[0]),
559
+ required: true,
560
+ candidates: spec.binary.candidates || [],
561
+ installHint: spec.binary.installHint || `install ${spec.binary.name}`,
562
+ // #3953: providers may declare a minimum binary version (e.g.
563
+ // claude-channel needs `claude` ≥ 2.1.80 for the --channels MCP
564
+ // transport). checkBinary parses the leading semver out of the
565
+ // version output and fails when it's below the floor.
566
+ minVersion: spec.binary.minVersion || null,
567
+ })
568
+ bin.provider = providerName
569
+ out.push(bin)
570
+ }
571
+
572
+ if (spec.credentials && Array.isArray(spec.credentials.envVars) && spec.credentials.envVars.length > 0) {
573
+ const matched = spec.credentials.envVars.find(v => process.env[v])
574
+ const credName = `${spec.label || providerName} credentials`
575
+ if (matched) {
576
+ out.push({ name: credName, status: 'pass', message: `${matched} is set`, provider: providerName })
577
+ } else {
578
+ const joined = spec.credentials.envVars.join(' or ')
579
+ const hint = spec.credentials.hint || `set ${joined}`
580
+ // Optional credentials (e.g. Claude — login subscription also works)
581
+ // downgrade to `warn` so absent env vars don't block server startup.
582
+ const status = spec.credentials.optional ? 'warn' : 'fail'
583
+ out.push({
584
+ name: credName,
585
+ status,
586
+ message: `${joined} not set — ${hint}`,
587
+ provider: providerName,
588
+ })
589
+ }
590
+ }
591
+
592
+ return out
593
+ }
594
+
595
+ /**
596
+ * Check if a binary is available and return its version.
597
+ * Differentiates between not-found and timeout errors.
598
+ *
599
+ * `candidates` gives fallback absolute paths to try when the binary is not
600
+ * on PATH — important for GUI-launched processes (e.g. Tauri) whose
601
+ * inherited PATH excludes user-local install dirs.
602
+ *
603
+ * Exported for tests — callers in production should use `runDoctorChecks`.
604
+ */
605
+ export function checkBinary(name, args, { parseVersion, required, installHint, candidates = [], minVersion = null }) {
606
+ const resolved = resolveBinary(name, candidates)
607
+ try {
608
+ // #6484 — a resolved `.cmd` shim (npm-only Windows host) can't be spawned
609
+ // directly on Node 24; route it through cmd.exe via prepareSpawn. No-op for
610
+ // a `.exe` and on POSIX, so non-Windows binary checks are unchanged.
611
+ const spawnSpec = prepareSpawn(resolved, args)
612
+ const output = execFileSync(spawnSpec.command, spawnSpec.args, {
613
+ encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], ...spawnSpec.options,
614
+ })
615
+ const message = parseVersion(output)
616
+ // #3953: when the provider declares a minimum version, parse the
617
+ // leading semver out of the (already pretty-printed) version message
618
+ // and fail the check below the floor. If the version can't be parsed
619
+ // we don't block the user — we surface a warn so a format change in
620
+ // the upstream CLI doesn't hard-fail an otherwise-working install.
621
+ if (minVersion) {
622
+ const found = parseLeadingSemver(message)
623
+ if (found === null) {
624
+ return {
625
+ name,
626
+ status: 'warn',
627
+ message: `${message} — could not parse version to verify ≥ ${minVersion}`,
628
+ }
629
+ }
630
+ if (compareSemver(found, minVersion) < 0) {
631
+ return {
632
+ name,
633
+ status: required ? 'fail' : 'warn',
634
+ message: `${message} — requires ${name} ≥ ${minVersion}; ${installHint}`,
635
+ }
636
+ }
637
+ }
638
+ return { name, status: 'pass', message }
639
+ } catch (err) {
640
+ if (err.killed || err.signal === 'SIGTERM') {
641
+ // Timeout — binary exists but hung
642
+ return {
643
+ name,
644
+ status: required ? 'fail' : 'warn',
645
+ message: `Timed out — ${name} may be hanging or misconfigured`,
646
+ }
647
+ }
648
+ return {
649
+ name,
650
+ status: required ? 'fail' : 'warn',
651
+ message: `Not found — ${installHint}`,
652
+ }
653
+ }
654
+ }
655
+
656
+ function checkPortAvailable(port) {
657
+ return new Promise((resolve, reject) => {
658
+ const server = createServer()
659
+ server.once('error', (err) => {
660
+ reject(err)
661
+ })
662
+ server.once('listening', () => {
663
+ server.close(() => resolve())
664
+ })
665
+ server.listen(port, '127.0.0.1')
666
+ })
667
+ }