@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/service.js ADDED
@@ -0,0 +1,835 @@
1
+ import { homedir, platform } from 'os'
2
+ import { join, dirname } from 'path'
3
+ import { existsSync, readFileSync, mkdirSync, unlinkSync, readdirSync, writeFileSync, chmodSync } from 'fs'
4
+ import { writeFileRestricted } from './platform.js'
5
+ import { execFileSync } from 'child_process'
6
+ import { fileURLToPath } from 'url'
7
+
8
+ const SERVICE_LABEL = 'com.chroxy.server'
9
+ const DEFAULT_CONFIG_DIR = join(homedir(), '.chroxy')
10
+ const WRAPPER_NAME = 'service-wrapper.sh'
11
+
12
+ // Keychain coordinates for secrets resolved by the service wrapper at spawn
13
+ // time. The api-token pair mirrors keychain.js (service 'chroxy', account
14
+ // 'api-token'); the webhook pair mirrors the deployed workaround for #5490
15
+ // (service 'chroxy-discord-webhook', account 'webhook-url').
16
+ const KEYCHAIN_API_TOKEN = { service: 'chroxy', account: 'api-token', env: 'API_TOKEN' }
17
+ const KEYCHAIN_DISCORD_WEBHOOK = {
18
+ service: 'chroxy-discord-webhook',
19
+ account: 'webhook-url',
20
+ env: 'CHROXY_DISCORD_WEBHOOK_URL',
21
+ }
22
+
23
+ /**
24
+ * Escape XML special characters in a string.
25
+ */
26
+ function escapeXml(str) {
27
+ return str
28
+ .replace(/&/g, '&')
29
+ .replace(/</g, '&lt;')
30
+ .replace(/>/g, '&gt;')
31
+ .replace(/"/g, '&quot;')
32
+ .replace(/'/g, '&apos;')
33
+ }
34
+
35
+ /**
36
+ * Returns platform-specific service file paths.
37
+ * @param {string} [plat] - Override platform (defaults to process.platform)
38
+ */
39
+ export function getServicePaths(plat = platform()) {
40
+ const logDir = join(homedir(), '.chroxy', 'logs')
41
+
42
+ if (plat === 'darwin') {
43
+ return {
44
+ type: 'launchd',
45
+ plistPath: join(homedir(), 'Library', 'LaunchAgents', `${SERVICE_LABEL}.plist`),
46
+ logDir,
47
+ }
48
+ }
49
+
50
+ if (plat === 'linux') {
51
+ return {
52
+ type: 'systemd',
53
+ unitPath: join(homedir(), '.config', 'systemd', 'user', 'chroxy.service'),
54
+ logDir,
55
+ }
56
+ }
57
+
58
+ if (plat === 'win32') {
59
+ return {
60
+ type: 'windows',
61
+ logDir,
62
+ }
63
+ }
64
+
65
+ throw new Error(`Platform "${plat}" is not supported. Only macOS (launchd), Linux (systemd), and Windows are supported.`)
66
+ }
67
+
68
+ /**
69
+ * Generate a macOS launchd plist XML string.
70
+ */
71
+ export function generateLaunchdPlist(config) {
72
+ const {
73
+ nodePath,
74
+ chroxyBin,
75
+ claudeBin,
76
+ wrapperPath,
77
+ cwd = homedir(),
78
+ startAtLogin = false,
79
+ logDir = join(homedir(), '.chroxy', 'logs'),
80
+ } = config
81
+
82
+ // Bake a PATH that includes the node and claude bin dirs so the daemon's
83
+ // preflight finds both under launchd's bare default PATH (#5491).
84
+ const pathValue = buildServicePath({ nodePath, claudeBin })
85
+
86
+ // When a wrapper is provided, exec it so keychain secrets reach the daemon
87
+ // (#5491). Otherwise exec node+chroxy directly (legacy / no-wrapper path).
88
+ const programArgs = wrapperPath
89
+ ? ` <string>${escapeXml(wrapperPath)}</string>`
90
+ : ` <string>${escapeXml(nodePath)}</string>
91
+ <string>${escapeXml(chroxyBin)}</string>
92
+ <string>start</string>`
93
+
94
+ return `<?xml version="1.0" encoding="UTF-8"?>
95
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
96
+ <plist version="1.0">
97
+ <dict>
98
+ <key>Label</key>
99
+ <string>${SERVICE_LABEL}</string>
100
+ <key>ProgramArguments</key>
101
+ <array>
102
+ ${programArgs}
103
+ </array>
104
+ <key>RunAtLoad</key>
105
+ ${startAtLogin ? '<true/>' : '<false/>'}
106
+ <key>KeepAlive</key>
107
+ <true/>
108
+ <key>WorkingDirectory</key>
109
+ <string>${escapeXml(cwd)}</string>
110
+ <key>StandardOutPath</key>
111
+ <string>${escapeXml(join(logDir, 'chroxy-stdout.log'))}</string>
112
+ <key>StandardErrorPath</key>
113
+ <string>${escapeXml(join(logDir, 'chroxy-stderr.log'))}</string>
114
+ <key>EnvironmentVariables</key>
115
+ <dict>
116
+ <key>PATH</key>
117
+ <string>${escapeXml(pathValue)}</string>
118
+ <key>CHROXY_DAEMON</key>
119
+ <string>1</string>
120
+ </dict>
121
+ </dict>
122
+ </plist>
123
+ `
124
+ }
125
+
126
+ /**
127
+ * Generate a Linux systemd user unit file string.
128
+ */
129
+ export function generateSystemdUnit(config) {
130
+ const {
131
+ nodePath,
132
+ chroxyBin,
133
+ claudeBin,
134
+ wrapperPath,
135
+ cwd = homedir(),
136
+ logDir = join(homedir(), '.chroxy', 'logs'),
137
+ } = config
138
+
139
+ // Bake a PATH that includes the node and claude bin dirs for parity with the
140
+ // launchd plist (#5491).
141
+ const pathValue = buildServicePath({ nodePath, claudeBin })
142
+
143
+ // Prefer the wrapper (resolves keychain secrets) when provided.
144
+ const execStart = wrapperPath
145
+ ? `ExecStart=${wrapperPath}`
146
+ : `ExecStart="${nodePath}" "${chroxyBin}" start`
147
+
148
+ return `[Unit]
149
+ Description=Chroxy remote terminal daemon
150
+ After=network.target
151
+
152
+ [Service]
153
+ Type=simple
154
+ ${execStart}
155
+ WorkingDirectory=${cwd}
156
+ Restart=on-failure
157
+ RestartSec=5
158
+ Environment=PATH=${pathValue}
159
+ Environment=CHROXY_DAEMON=1
160
+ StandardOutput=file:${join(logDir, 'chroxy-stdout.log')}
161
+ StandardError=file:${join(logDir, 'chroxy-stderr.log')}
162
+
163
+ [Install]
164
+ WantedBy=default.target
165
+ `
166
+ }
167
+
168
+ /**
169
+ * Returns alternative methods for running Chroxy as a service on Windows.
170
+ * Since Windows doesn't have a native equivalent to launchd/systemd user agents,
171
+ * we provide guidance on third-party tools and built-in alternatives.
172
+ */
173
+ export function getWindowsAlternatives() {
174
+ return [
175
+ {
176
+ name: 'Task Scheduler',
177
+ description: 'Built-in Windows tool. Create a task that runs at logon with "Run whether user is logged on or not".',
178
+ command: 'schtasks /create /tn "Chroxy" /tr "node <chroxy-path> start" /sc onlogon /rl highest',
179
+ },
180
+ {
181
+ name: 'NSSM (Non-Sucking Service Manager)',
182
+ description: 'Lightweight tool that wraps any executable as a Windows service. Install from nssm.cc.',
183
+ command: 'nssm install Chroxy node <chroxy-path> start',
184
+ },
185
+ {
186
+ name: 'PM2',
187
+ description: 'Node.js process manager with Windows service support via pm2-windows-service.',
188
+ command: 'pm2 start <chroxy-path> -- start && pm2 save && pm2-service-install',
189
+ },
190
+ ]
191
+ }
192
+
193
+ /**
194
+ * Search common locations for Node 22, verify the version, and return the path.
195
+ * Throws with a helpful message if not found.
196
+ */
197
+ export function resolveNode22Path() {
198
+ const candidates = []
199
+
200
+ // Homebrew (Apple Silicon)
201
+ candidates.push('/opt/homebrew/opt/node@22/bin/node')
202
+ // Homebrew (Intel)
203
+ candidates.push('/usr/local/opt/node@22/bin/node')
204
+
205
+ // nvm — glob for latest v22.*
206
+ const nvmDir = join(homedir(), '.nvm', 'versions', 'node')
207
+ if (existsSync(nvmDir)) {
208
+ try {
209
+ const dirs = readdirSync(nvmDir)
210
+ .filter(d => d.startsWith('v22.'))
211
+ .sort()
212
+ .reverse()
213
+ for (const d of dirs) {
214
+ candidates.push(join(nvmDir, d, 'bin', 'node'))
215
+ }
216
+ } catch {
217
+ // ignore read errors
218
+ }
219
+ }
220
+
221
+ // Check each candidate
222
+ for (const candidate of candidates) {
223
+ if (existsSync(candidate)) {
224
+ try {
225
+ const version = execFileSync(candidate, ['--version'], { encoding: 'utf-8' }).trim()
226
+ if (version.startsWith('v22')) {
227
+ return candidate
228
+ }
229
+ } catch {
230
+ // candidate didn't work, try next
231
+ }
232
+ }
233
+ }
234
+
235
+ // Fall back to `which node` and check version
236
+ try {
237
+ const whichNode = execFileSync('which', ['node'], { encoding: 'utf-8' }).trim()
238
+ if (whichNode && existsSync(whichNode)) {
239
+ const version = execFileSync(whichNode, ['--version'], { encoding: 'utf-8' }).trim()
240
+ if (version.startsWith('v22')) {
241
+ return whichNode
242
+ }
243
+ }
244
+ } catch {
245
+ // not found via which
246
+ }
247
+
248
+ throw new Error(
249
+ 'Could not find Node.js 22. Install it via:\n' +
250
+ ' brew install node@22\n' +
251
+ ' or use nvm: nvm install 22\n' +
252
+ 'Node 22 is the minimum supported version.'
253
+ )
254
+ }
255
+
256
+ /**
257
+ * Find the chroxy CLI entry point.
258
+ * First checks if we're running from the monorepo source, then falls back to `which chroxy`.
259
+ */
260
+ export function resolveChroxyBin() {
261
+ // Check monorepo location relative to this file
262
+ const thisDir = dirname(fileURLToPath(import.meta.url))
263
+ const monorepoCliPath = join(thisDir, 'cli.js')
264
+ if (existsSync(monorepoCliPath)) {
265
+ return monorepoCliPath
266
+ }
267
+
268
+ // Fall back to globally installed chroxy
269
+ try {
270
+ const whichChroxy = execFileSync('which', ['chroxy'], { encoding: 'utf-8' }).trim()
271
+ if (whichChroxy && existsSync(whichChroxy)) {
272
+ return whichChroxy
273
+ }
274
+ } catch {
275
+ // not found
276
+ }
277
+
278
+ throw new Error(
279
+ 'Could not find chroxy CLI. Make sure you are running from the chroxy project directory\n' +
280
+ 'or install globally: npm install -g chroxy'
281
+ )
282
+ }
283
+
284
+ /**
285
+ * Resolve the `claude` CLI binary from the installer's environment.
286
+ *
287
+ * The Agent SDK requires the Claude Code CLI on PATH. launchd/systemd run the
288
+ * daemon with a bare PATH (`/usr/bin:/bin:...`), so `claude` (commonly under
289
+ * `~/.local/bin`) is invisible and preflight fails (#5491). We capture the
290
+ * resolved location at install time via `which` so it can be baked into the
291
+ * service's PATH.
292
+ *
293
+ * Throws with an actionable message if `claude` cannot be resolved — install
294
+ * MUST fail loudly rather than register a job that crash-loops on preflight.
295
+ *
296
+ * @param {object} [options]
297
+ * @param {(cmd: string, args: string[], opts: object) => string} [options._which]
298
+ * Injectable exec for testing (defaults to execFileSync).
299
+ * @returns {string} Absolute path to the `claude` binary.
300
+ */
301
+ export function resolveClaudeBin(options = {}) {
302
+ const which = options._which || execFileSync
303
+ try {
304
+ const resolved = which('which', ['claude'], { encoding: 'utf-8' }).trim()
305
+ if (resolved && existsSync(resolved)) {
306
+ return resolved
307
+ }
308
+ } catch {
309
+ // fall through to the actionable error below
310
+ }
311
+
312
+ throw new Error(
313
+ "Could not find the 'claude' CLI (required by the Agent SDK).\n" +
314
+ 'Install Claude Code (https://claude.ai/code) and ensure `claude` is on your PATH,\n' +
315
+ 'then re-run `chroxy service install`. The resolved location is baked into the\n' +
316
+ 'service so the daemon can find it under launchd/systemd.'
317
+ )
318
+ }
319
+
320
+ /**
321
+ * Build the PATH value baked into the service definition.
322
+ *
323
+ * Includes the directories holding the resolved `node` and `claude` binaries
324
+ * (deduplicated, in that priority order) ahead of the standard system dirs,
325
+ * so the daemon's preflight finds both even under a bare launchd/systemd PATH.
326
+ *
327
+ * @param {object} args
328
+ * @param {string} args.nodePath - Resolved node binary path.
329
+ * @param {string} [args.claudeBin] - Resolved claude binary path.
330
+ * @returns {string} Colon-separated PATH.
331
+ */
332
+ export function buildServicePath({ nodePath, claudeBin }) {
333
+ const dirs = []
334
+ const push = (p) => {
335
+ if (!p) return
336
+ const d = dirname(p)
337
+ if (!dirs.includes(d)) dirs.push(d)
338
+ }
339
+ push(nodePath)
340
+ push(claudeBin)
341
+ for (const sys of ['/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin']) {
342
+ if (!dirs.includes(sys)) dirs.push(sys)
343
+ }
344
+ return dirs.join(':')
345
+ }
346
+
347
+ /**
348
+ * Generate the service wrapper script the service definition execs.
349
+ *
350
+ * launchd resolves keychain items in a context where the daemon's own
351
+ * `getToken()` fails even though `security find-generic-password` succeeds in a
352
+ * shell spawned by the same job (#5491). This wrapper resolves the secrets via
353
+ * `/usr/bin/security` at spawn time, exports them, and execs the server.
354
+ *
355
+ * Secret resolution is graceful: a failed/empty keychain read leaves the env
356
+ * var unset so config-file / `--no-auth` setups still work. The token itself is
357
+ * NEVER written into the plist — only this 0700 wrapper reads it.
358
+ *
359
+ * @param {object} config
360
+ * @param {string} config.nodePath - Resolved node binary path.
361
+ * @param {string} config.chroxyBin - Resolved chroxy CLI entry point.
362
+ * @param {string} config.pathValue - PATH to export (from buildServicePath).
363
+ * @param {string} [config.cwd] - Working directory (informational; the service
364
+ * definition sets the actual cwd).
365
+ * @returns {string} POSIX sh script.
366
+ */
367
+ export function generateServiceWrapper(config) {
368
+ const { nodePath, chroxyBin, pathValue } = config
369
+
370
+ const sh = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`
371
+ const keychainBlock = ({ service, account, env }) => `
372
+ # ${env} — resolve from the keychain at spawn time (graceful: skip on failure)
373
+ if _val="$(/usr/bin/security find-generic-password -s ${sh(service)} -a ${sh(account)} -w 2>/dev/null)"; then
374
+ if [ -n "$_val" ]; then
375
+ export ${env}="$_val"
376
+ fi
377
+ fi`
378
+
379
+ return `#!/bin/sh
380
+ # Chroxy service wrapper — generated by \`chroxy service install\` (#5491).
381
+ # Resolves keychain secrets unavailable to the launchd/systemd daemon context
382
+ # and execs the server. Regenerated on every \`service install\`; edits are lost.
383
+ set -e
384
+
385
+ export PATH=${sh(pathValue)}
386
+ export CHROXY_DAEMON=1
387
+ ${keychainBlock(KEYCHAIN_API_TOKEN)}
388
+ ${keychainBlock(KEYCHAIN_DISCORD_WEBHOOK)}
389
+
390
+ exec ${sh(nodePath)} ${sh(chroxyBin)} start
391
+ `
392
+ }
393
+
394
+ /**
395
+ * Load service state from the config directory.
396
+ * @param {string} [configDir] - Override config directory (for testing)
397
+ * @returns {object|null}
398
+ */
399
+ export function loadServiceState(configDir = DEFAULT_CONFIG_DIR) {
400
+ const statePath = join(configDir, 'service.json')
401
+ if (!existsSync(statePath)) {
402
+ return null
403
+ }
404
+ try {
405
+ return JSON.parse(readFileSync(statePath, 'utf-8'))
406
+ } catch {
407
+ return null
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Save service state to the config directory.
413
+ * @param {object} state
414
+ * @param {string} [configDir] - Override config directory (for testing)
415
+ */
416
+ export function saveServiceState(state, configDir = DEFAULT_CONFIG_DIR) {
417
+ if (!existsSync(configDir)) {
418
+ mkdirSync(configDir, { recursive: true })
419
+ }
420
+ const statePath = join(configDir, 'service.json')
421
+ writeFileRestricted(statePath, JSON.stringify(state, null, 2))
422
+ }
423
+
424
+ /**
425
+ * Write the service wrapper script to disk with 0700 perms (owner rwx only).
426
+ *
427
+ * The wrapper resolves keychain secrets at spawn time (#5491); it is owner-only
428
+ * executable because it is what the service execs and it reads secrets.
429
+ *
430
+ * @param {string} wrapperPath - Absolute path to write the wrapper to.
431
+ * @param {string} content - Wrapper script body (from generateServiceWrapper).
432
+ * @returns {string} The wrapper path written.
433
+ */
434
+ export function writeServiceWrapper(wrapperPath, content) {
435
+ const dir = dirname(wrapperPath)
436
+ if (!existsSync(dir)) {
437
+ mkdirSync(dir, { recursive: true })
438
+ }
439
+ // 0600 first (no world/group bits during the write window), then 0700 so the
440
+ // service can exec it. The script holds no secret itself — only the security
441
+ // invocations that read them — but owner-only is defense in depth.
442
+ writeFileSync(wrapperPath, content, { mode: 0o600 })
443
+ chmodSync(wrapperPath, 0o700)
444
+ return wrapperPath
445
+ }
446
+
447
+ /**
448
+ * Install Chroxy as a system daemon.
449
+ * Generates the appropriate service file, writes it, and optionally registers it.
450
+ *
451
+ * @param {object} config
452
+ * @param {string} config.nodePath - Path to Node 22 binary
453
+ * @param {string} config.chroxyBin - Path to chroxy CLI entry point
454
+ * @param {string} [config.claudeBin] - Path to the claude CLI (baked into PATH)
455
+ * @param {string} [config.cwd] - Working directory for sessions
456
+ * @param {boolean} [config.startAtLogin] - Start on login
457
+ * @param {string} [config._servicePath] - Override service file path (testing)
458
+ * @param {string} [config._logDir] - Override log directory (testing)
459
+ * @param {string} [config._stateDir] - Override state directory (testing)
460
+ * @param {string} [config._wrapperPath] - Override wrapper script path (testing)
461
+ * @param {boolean} [config._skipRegister] - Skip launchctl/systemctl registration (testing)
462
+ * @param {string} [config._platform] - Override platform (testing)
463
+ */
464
+ export function installService(config) {
465
+ const plat = config._platform || platform()
466
+ const paths = getServicePaths(plat)
467
+
468
+ if (plat === 'win32') {
469
+ const alternatives = getWindowsAlternatives()
470
+ return {
471
+ installed: false,
472
+ message: 'Windows does not support native service installation via chroxy. Use one of the alternatives below to run Chroxy at startup.',
473
+ alternatives,
474
+ }
475
+ }
476
+
477
+ const servicePath = config._servicePath || (plat === 'darwin' ? paths.plistPath : paths.unitPath)
478
+ const logDir = config._logDir || paths.logDir
479
+ const stateDir = config._stateDir || DEFAULT_CONFIG_DIR
480
+ const wrapperPath = config._wrapperPath || join(stateDir, WRAPPER_NAME)
481
+
482
+ // Bake the resolved binary locations into the service PATH so the daemon's
483
+ // preflight finds node + claude under the bare launchd/systemd PATH (#5491).
484
+ const pathValue = buildServicePath({
485
+ nodePath: config.nodePath,
486
+ claudeBin: config.claudeBin,
487
+ })
488
+
489
+ // Write the wrapper that resolves keychain secrets at spawn time (#5491).
490
+ const wrapperContent = generateServiceWrapper({
491
+ nodePath: config.nodePath,
492
+ chroxyBin: config.chroxyBin,
493
+ pathValue,
494
+ cwd: config.cwd || homedir(),
495
+ })
496
+ writeServiceWrapper(wrapperPath, wrapperContent)
497
+
498
+ // Generate service file content
499
+ const genConfig = {
500
+ nodePath: config.nodePath,
501
+ chroxyBin: config.chroxyBin,
502
+ claudeBin: config.claudeBin,
503
+ wrapperPath,
504
+ cwd: config.cwd || homedir(),
505
+ startAtLogin: config.startAtLogin || false,
506
+ logDir,
507
+ }
508
+
509
+ let content
510
+ if (plat === 'darwin') {
511
+ content = generateLaunchdPlist(genConfig)
512
+ } else {
513
+ content = generateSystemdUnit(genConfig)
514
+ }
515
+
516
+ // Create log directory
517
+ if (!existsSync(logDir)) {
518
+ mkdirSync(logDir, { recursive: true })
519
+ }
520
+
521
+ // Create service file parent directory
522
+ const serviceDir = dirname(servicePath)
523
+ if (!existsSync(serviceDir)) {
524
+ mkdirSync(serviceDir, { recursive: true })
525
+ }
526
+
527
+ // Write service file
528
+ writeFileRestricted(servicePath, content)
529
+
530
+ // Register with system (unless testing)
531
+ if (!config._skipRegister) {
532
+ if (plat === 'darwin') {
533
+ execFileSync('launchctl', ['bootstrap', `gui/${process.getuid()}`, servicePath])
534
+ } else {
535
+ execFileSync('systemctl', ['--user', 'enable', '--now', 'chroxy.service'])
536
+ }
537
+ }
538
+
539
+ // Save state
540
+ saveServiceState({
541
+ installedAt: new Date().toISOString(),
542
+ platform: plat,
543
+ servicePath,
544
+ nodePath: config.nodePath,
545
+ chroxyBin: config.chroxyBin,
546
+ claudeBin: config.claudeBin,
547
+ wrapperPath,
548
+ cwd: genConfig.cwd,
549
+ startAtLogin: genConfig.startAtLogin,
550
+ }, stateDir)
551
+ }
552
+
553
+ /**
554
+ * Uninstall the Chroxy system daemon.
555
+ * Stops the service if running, removes the service file and state.
556
+ *
557
+ * @param {object} [options]
558
+ * @param {string} [options._stateDir] - Override state directory (testing)
559
+ * @param {boolean} [options._skipUnregister] - Skip launchctl/systemctl unregistration (testing)
560
+ */
561
+ export function uninstallService(options = {}) {
562
+ const stateDir = options._stateDir || DEFAULT_CONFIG_DIR
563
+ const state = loadServiceState(stateDir)
564
+
565
+ if (!state) {
566
+ throw new Error('Chroxy service is not installed. Nothing to uninstall.')
567
+ }
568
+
569
+ // Unregister from system (unless testing)
570
+ if (!options._skipUnregister) {
571
+ try {
572
+ if (state.platform === 'darwin') {
573
+ execFileSync('launchctl', ['bootout', `gui/${process.getuid()}/${SERVICE_LABEL}`], { stdio: 'ignore' })
574
+ } else {
575
+ execFileSync('systemctl', ['--user', 'disable', '--now', 'chroxy.service'], { stdio: 'ignore' })
576
+ }
577
+ } catch {
578
+ // Service may already be stopped/unloaded — continue cleanup
579
+ }
580
+ }
581
+
582
+ // Remove service file
583
+ if (existsSync(state.servicePath)) {
584
+ unlinkSync(state.servicePath)
585
+ }
586
+
587
+ // Remove the generated wrapper script (#5491)
588
+ const wrapperPath = state.wrapperPath || join(stateDir, WRAPPER_NAME)
589
+ if (existsSync(wrapperPath)) {
590
+ unlinkSync(wrapperPath)
591
+ }
592
+
593
+ // Remove state file
594
+ const statePath = join(stateDir, 'service.json')
595
+ if (existsSync(statePath)) {
596
+ unlinkSync(statePath)
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Start the system service.
602
+ * @param {object} [options] - Options
603
+ * @param {string} [options._platform] - Override platform for testing
604
+ * @param {string} [options._stateDir] - Override state directory (for testing)
605
+ * @param {boolean} [options._skipExec] - Skip actual launchctl/systemctl calls (for testing)
606
+ * @param {(cmd: string, args: string[], opts: object) => void} [options._exec]
607
+ * Injectable exec for testing (defaults to execFileSync).
608
+ * @returns {{ started: boolean, message: string }}
609
+ */
610
+ export function startService(options = {}) {
611
+ const plat = options._platform || platform()
612
+ const paths = getServicePaths(plat)
613
+ const stateDir = options._stateDir || DEFAULT_CONFIG_DIR
614
+ const exec = options._exec || execFileSync
615
+
616
+ if (plat === 'win32') {
617
+ return {
618
+ started: false,
619
+ message: 'Windows does not support native service management via chroxy. Use Task Scheduler, NSSM, or PM2 to manage the Chroxy process.',
620
+ alternatives: getWindowsAlternatives(),
621
+ }
622
+ }
623
+
624
+ if (!options._skipExec) {
625
+ if (paths.type === 'launchd') {
626
+ const state = loadServiceState(stateDir)
627
+ let plistPath
628
+ if (state?.servicePath) {
629
+ if (!existsSync(state.servicePath)) {
630
+ throw new Error(
631
+ `Service file not found at ${state.servicePath}. ` +
632
+ "The service state is stale. Run 'chroxy service install' to reinstall."
633
+ )
634
+ }
635
+ plistPath = state.servicePath
636
+ } else if (existsSync(paths.plistPath)) {
637
+ // Service file exists but state is missing/stale — use the default path
638
+ plistPath = paths.plistPath
639
+ } else {
640
+ throw new Error(
641
+ "Service not installed. Run 'chroxy service install' first."
642
+ )
643
+ }
644
+ bootstrapLaunchd(plistPath, exec)
645
+ } else {
646
+ exec('systemctl', ['--user', 'start', 'chroxy.service'], { stdio: 'pipe' })
647
+ }
648
+ }
649
+
650
+ return { started: true, message: 'Service started' }
651
+ }
652
+
653
+ /**
654
+ * Idempotently (re)start a launchd job: bootout any existing instance of the
655
+ * label first, then bootstrap (#5491).
656
+ *
657
+ * launchd refuses to bootstrap a label that is already registered. A stale
658
+ * label left from a prior run makes the first `service start` fail with the
659
+ * opaque `Bootstrap failed: 5: Input/output error`. Booting out first makes
660
+ * start idempotent; if bootstrap still fails with EIO we translate it into an
661
+ * actionable hint instead of surfacing the raw launchd error.
662
+ *
663
+ * @param {string} plistPath - Path to the plist to bootstrap.
664
+ * @param {(cmd: string, args: string[], opts: object) => void} exec - exec impl.
665
+ */
666
+ function bootstrapLaunchd(plistPath, exec) {
667
+ const domain = `gui/${process.getuid()}`
668
+
669
+ // Bootout a stale label first — failure is fine (label may not be loaded).
670
+ try {
671
+ exec('launchctl', ['bootout', `${domain}/${SERVICE_LABEL}`], { stdio: 'pipe' })
672
+ } catch {
673
+ // Not currently loaded — nothing to bootout.
674
+ }
675
+
676
+ try {
677
+ exec('launchctl', ['bootstrap', domain, plistPath], { stdio: 'pipe' })
678
+ } catch (err) {
679
+ const detail = String(err?.stderr || err?.message || '')
680
+ // `Bootstrap failed: 5: Input/output error` — usually a stale/duplicate
681
+ // label or a job still shutting down. Surface an actionable hint (#5491).
682
+ if (/Input\/output error|: 5:/.test(detail)) {
683
+ throw new Error(
684
+ 'launchd could not bootstrap the Chroxy service (Bootstrap failed: 5: Input/output error).\n' +
685
+ 'This usually means a previous instance is still registered or shutting down. Try:\n' +
686
+ ` launchctl bootout ${domain}/${SERVICE_LABEL}\n` +
687
+ ' chroxy service start\n' +
688
+ "If it persists, reinstall with 'chroxy service uninstall && chroxy service install'."
689
+ )
690
+ }
691
+ throw err
692
+ }
693
+ }
694
+
695
+ /**
696
+ * Stop the system service.
697
+ * @param {object} [options] - Options
698
+ * @param {string} [options._platform] - Override platform for testing
699
+ * @param {boolean} [options._skipExec] - Skip actual launchctl/systemctl calls (for testing)
700
+ * @returns {{ stopped: boolean, message: string }}
701
+ */
702
+ export function stopService(options = {}) {
703
+ const plat = options._platform || platform()
704
+ const paths = getServicePaths(plat)
705
+
706
+ if (plat === 'win32') {
707
+ return {
708
+ stopped: false,
709
+ message: 'Windows does not support native service management via chroxy. Stop the Chroxy process through Task Scheduler, NSSM, or your process manager.',
710
+ }
711
+ }
712
+
713
+ if (!options._skipExec) {
714
+ if (paths.type === 'launchd') {
715
+ execFileSync('launchctl', ['bootout', `gui/${process.getuid()}/${SERVICE_LABEL}`], { stdio: 'pipe' })
716
+ } else {
717
+ execFileSync('systemctl', ['--user', 'stop', 'chroxy.service'], { stdio: 'pipe' })
718
+ }
719
+ }
720
+
721
+ return { stopped: true, message: 'Service stopped' }
722
+ }
723
+
724
+ /**
725
+ * Check if the service is currently running by checking PID file.
726
+ * @param {object} [options]
727
+ * @param {string} [options.configDir] - Override config dir for testing
728
+ * @returns {{ installed: boolean, running: boolean, pid: number|null, stale: boolean }}
729
+ */
730
+ export function getServiceStatus(options = {}) {
731
+ const configDir = options.configDir || DEFAULT_CONFIG_DIR
732
+ const state = loadServiceState(configDir)
733
+
734
+ if (!state) {
735
+ return { installed: false, running: false, pid: null, stale: false }
736
+ }
737
+
738
+ const pidFile = join(configDir, 'supervisor.pid')
739
+ if (!existsSync(pidFile)) {
740
+ return { installed: true, running: false, pid: null, stale: false }
741
+ }
742
+
743
+ let pid
744
+ try {
745
+ pid = parseInt(readFileSync(pidFile, 'utf-8').trim(), 10)
746
+ } catch {
747
+ return { installed: true, running: false, pid: null, stale: false }
748
+ }
749
+
750
+ if (isNaN(pid)) {
751
+ return { installed: true, running: false, pid: null, stale: false }
752
+ }
753
+
754
+ // Check if process is alive (signal 0 = check existence only)
755
+ // EPERM means the process exists but we lack permission — still alive
756
+ // ESRCH means the process does not exist
757
+ let alive = false
758
+ try {
759
+ process.kill(pid, 0)
760
+ alive = true
761
+ } catch (err) {
762
+ alive = err.code === 'EPERM'
763
+ }
764
+
765
+ return {
766
+ installed: true,
767
+ running: alive,
768
+ pid: alive ? pid : null,
769
+ stale: !alive,
770
+ }
771
+ }
772
+
773
+ /**
774
+ * Get comprehensive service info for the status command.
775
+ * Includes health endpoint check, connection info, and recent logs.
776
+ * @param {object} [options]
777
+ * @param {string} [options.configDir] - Override config dir for testing
778
+ * @returns {Promise<object>} Full status including health, connection info, etc.
779
+ */
780
+ export async function getFullServiceStatus(options = {}) {
781
+ const configDir = options.configDir || DEFAULT_CONFIG_DIR
782
+ const status = getServiceStatus({ configDir })
783
+ const result = { ...status }
784
+
785
+ // Try to read connection info
786
+ const connFile = join(configDir, 'connection.json')
787
+ if (existsSync(connFile)) {
788
+ try {
789
+ result.connection = JSON.parse(readFileSync(connFile, 'utf-8'))
790
+ } catch {
791
+ // Ignore malformed connection.json
792
+ }
793
+ }
794
+
795
+ // If running, try health endpoint
796
+ if (status.running) {
797
+ try {
798
+ // Parse port: prefer config.json, then connection.json URL, then default (#745)
799
+ let port = 8765
800
+ const configFile = join(configDir, 'config.json')
801
+ if (existsSync(configFile)) {
802
+ try {
803
+ const cfg = JSON.parse(readFileSync(configFile, 'utf-8'))
804
+ if (cfg.port && typeof cfg.port === 'number') port = cfg.port
805
+ } catch {
806
+ // Ignore malformed config.json
807
+ }
808
+ }
809
+ if (port === 8765 && result.connection?.wsUrl) {
810
+ const urlPort = result.connection.wsUrl.match(/:(\d+)/)?.[1]
811
+ if (urlPort) port = parseInt(urlPort, 10)
812
+ }
813
+ const response = await fetch(`http://127.0.0.1:${port}/`, {
814
+ signal: AbortSignal.timeout(3000),
815
+ })
816
+ result.health = await response.json()
817
+ } catch {
818
+ result.health = null
819
+ }
820
+ }
821
+
822
+ // Read recent log lines
823
+ const logFile = join(configDir, 'logs', 'chroxy-stdout.log')
824
+ if (existsSync(logFile)) {
825
+ try {
826
+ const content = readFileSync(logFile, 'utf-8')
827
+ const lines = content.trim().split('\n')
828
+ result.recentLogs = lines.slice(-5)
829
+ } catch {
830
+ // Ignore read errors
831
+ }
832
+ }
833
+
834
+ return result
835
+ }