@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,34 @@
1
+ /**
2
+ * chroxy config — Show current configuration
3
+ */
4
+ import { existsSync, readFileSync } from 'fs'
5
+ import { CONFIG_FILE } from './shared.js'
6
+
7
+ export function registerConfigCommand(program) {
8
+ program
9
+ .command('config')
10
+ .description('Show current configuration')
11
+ .action(() => {
12
+ if (!existsSync(CONFIG_FILE)) {
13
+ console.log('No config found. Run \'npx chroxy init\' first.')
14
+ process.exit(1)
15
+ }
16
+
17
+ const config = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'))
18
+
19
+ console.log('\nšŸ“‹ Current Configuration\n')
20
+ console.log(` Config file: ${CONFIG_FILE}`)
21
+ console.log(` Port: ${config.port}`)
22
+ const tunnelMode = config.tunnel || 'quick'
23
+ if (tunnelMode === 'named') {
24
+ console.log(` Tunnel: Named (${config.tunnelName || '?'} -> ${config.tunnelHostname || '?'})`)
25
+ } else if (tunnelMode === 'none') {
26
+ console.log(` Tunnel: None (local only)`)
27
+ } else {
28
+ console.log(` Tunnel: Quick (random URL)`)
29
+ }
30
+ console.log(` API token: ${config.apiToken}`)
31
+ console.log('\nNote: CLI flags and environment variables can override these values.')
32
+ console.log('Run \'npx chroxy start --verbose\' to see full config resolution.\n')
33
+ })
34
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * `chroxy credentials` CLI subcommands.
3
+ *
4
+ * `rekey` (#5229) rotates the at-rest credential data key: it mints a fresh
5
+ * OS-keychain data key, re-encrypts ~/.chroxy/credentials.json under it
6
+ * atomically (temp → chmod 0600 → rename), and replaces the old keychain entry
7
+ * in place. Use it after a suspected keychain compromise, or to periodically
8
+ * rotate the key, WITHOUT re-entering any provider credentials.
9
+ */
10
+ import { rekeyCredentialStore } from '../credential-store.js'
11
+ import { createLogger } from '../logger.js'
12
+
13
+ const REKEY_MESSAGES = {
14
+ rekeyed: 'Rotated the credential data key and re-encrypted credentials.json.',
15
+ 'no-keychain': 'No OS keychain available to hold a data key — nothing to rotate.',
16
+ 'no-file': 'No credentials.json found — nothing to rotate.',
17
+ empty: 'credentials.json holds no credentials — nothing to rotate.',
18
+ 'read-error': 'Could not read credentials.json safely — aborted without changing anything.',
19
+ 'write-error': 'Re-encryption failed — the keychain key was rolled back; the existing store is unchanged.',
20
+ }
21
+
22
+ /**
23
+ * Run `chroxy credentials rekey`. Returns the {@link rekeyCredentialStore}
24
+ * result. `deps` is a test seam (`write`, `log`, `rekey`).
25
+ */
26
+ export async function runCredentialsRekey(options = {}, deps = {}) {
27
+ const out = deps.write || console.log
28
+ const log = deps.log || createLogger('credentials')
29
+ const rekey = deps.rekey || rekeyCredentialStore
30
+ const result = rekey({ log })
31
+
32
+ if (options.json) {
33
+ out(JSON.stringify(result, null, 2))
34
+ } else {
35
+ const msg = REKEY_MESSAGES[result.reason] || result.reason
36
+ out(`${result.rekeyed ? 'āœ“' : '•'} ${msg}`)
37
+ }
38
+ return result
39
+ }
40
+
41
+ export function registerCredentialsCommand(program) {
42
+ const creds = program
43
+ .command('credentials')
44
+ .description('Manage stored provider credentials')
45
+
46
+ creds
47
+ .command('rekey')
48
+ .description('Rotate the at-rest credential data key and re-encrypt credentials.json')
49
+ .option('--json', 'Output machine-readable JSON')
50
+ .action(async (options) => {
51
+ const result = await runCredentialsRekey(options)
52
+ // Signal failure to scripts/CI only when we INTENDED to rotate but
53
+ // couldn't (the store was readable yet the swap failed). Benign no-ops
54
+ // (no-file, empty, no-keychain) exit 0.
55
+ if (!result.rekeyed && (result.reason === 'read-error' || result.reason === 'write-error')) {
56
+ process.exitCode = 1
57
+ }
58
+ })
59
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * chroxy deploy — Validate and restart the running server
3
+ */
4
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync } from 'fs'
5
+ import { join } from 'path'
6
+ import { CONFIG_DIR } from './shared.js'
7
+ import { isWindows } from '../platform.js'
8
+
9
+ export function registerDeployCommand(program) {
10
+ program
11
+ .command('deploy')
12
+ .description('Validate and restart the running Chroxy server')
13
+ .option('--dry-run', 'Validate only, do not restart')
14
+ .option('--skip-tests', 'Skip running server tests')
15
+ .action(async (options) => {
16
+ const { execFileSync } = await import('child_process')
17
+
18
+ const PID_FILE = join(CONFIG_DIR, 'supervisor.pid')
19
+ const LOCK_FILE = join(CONFIG_DIR, 'update.lock')
20
+ const KNOWN_GOOD_FILE = join(CONFIG_DIR, 'known-good-ref')
21
+
22
+ let lockAcquired = false
23
+ try {
24
+ // 1. Pre-checks
25
+ console.log('\n[deploy] Pre-checks...')
26
+
27
+ const gitStatus = execFileSync('git', ['status', '--porcelain'], { encoding: 'utf-8' }).trim()
28
+ if (gitStatus) {
29
+ console.error('[deploy] Working tree is not clean. Commit or stash changes first.')
30
+ console.error(gitStatus)
31
+ process.exitCode = 1
32
+ return
33
+ }
34
+
35
+ if (existsSync(LOCK_FILE)) {
36
+ const lockPid = readFileSync(LOCK_FILE, 'utf-8').trim()
37
+ try {
38
+ process.kill(parseInt(lockPid, 10), 0)
39
+ console.error(`[deploy] Another deploy is in progress (pid: ${lockPid})`)
40
+ process.exitCode = 1
41
+ return
42
+ } catch {
43
+ unlinkSync(LOCK_FILE)
44
+ }
45
+ }
46
+
47
+ if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true })
48
+ writeFileSync(LOCK_FILE, String(process.pid))
49
+ lockAcquired = true
50
+
51
+ // 2. Validate JS files
52
+ console.log('[deploy] Validating JavaScript files...')
53
+ const knownGoodRef = existsSync(KNOWN_GOOD_FILE)
54
+ ? readFileSync(KNOWN_GOOD_FILE, 'utf-8').trim()
55
+ : null
56
+
57
+ const jsFiles = knownGoodRef
58
+ ? execFileSync('git', ['diff', '--name-only', knownGoodRef, '--', 'packages/server/src/'], { encoding: 'utf-8' })
59
+ .trim().split('\n').filter((f) => f.endsWith('.js'))
60
+ : execFileSync('git', ['ls-files', '--', 'packages/server/src/'], { encoding: 'utf-8' })
61
+ .trim().split('\n').filter((f) => f.endsWith('.js'))
62
+
63
+ let validationErrors = 0
64
+ for (const file of jsFiles) {
65
+ if (!file) continue
66
+ const fullPath = join(process.cwd(), file)
67
+ if (!existsSync(fullPath)) continue
68
+ try {
69
+ execFileSync('node', ['--check', fullPath], { stdio: 'pipe' })
70
+ } catch (err) {
71
+ console.error(`[deploy] Syntax error in ${file}:`)
72
+ console.error(err.stderr?.toString() || err.message)
73
+ validationErrors++
74
+ }
75
+ }
76
+
77
+ if (validationErrors > 0) {
78
+ console.error(`[deploy] ${validationErrors} file(s) failed validation`)
79
+ process.exitCode = 1
80
+ return
81
+ }
82
+ console.log(`[deploy] ${jsFiles.filter(Boolean).length || 0} file(s) validated`)
83
+
84
+ // 3. Run tests
85
+ if (!options.skipTests) {
86
+ const testDir = join(process.cwd(), 'packages', 'server', 'tests')
87
+ if (existsSync(testDir)) {
88
+ console.log('[deploy] Running server tests...')
89
+ try {
90
+ execFileSync('node', ['--test', testDir], {
91
+ stdio: 'inherit',
92
+ timeout: 120000,
93
+ })
94
+ console.log('[deploy] Tests passed')
95
+ } catch {
96
+ console.error('[deploy] Tests failed')
97
+ process.exitCode = 1
98
+ return
99
+ }
100
+ }
101
+ } else {
102
+ console.log('[deploy] Skipping tests (--skip-tests)')
103
+ }
104
+
105
+ if (options.dryRun) {
106
+ console.log('[deploy] Dry run complete. No restart performed.')
107
+ return
108
+ }
109
+
110
+ // 4. Tag known-good commit
111
+ const headHash = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf-8' }).trim()
112
+ const tagName = `known-good-${Date.now()}`
113
+ execFileSync('git', ['tag', tagName])
114
+ writeFileSync(KNOWN_GOOD_FILE, headHash)
115
+ console.log(`[deploy] Tagged ${headHash.slice(0, 8)} as ${tagName}`)
116
+
117
+ try {
118
+ const allTags = execFileSync('git', ['tag', '--list', 'known-good-*', '--sort=-creatordate'], { encoding: 'utf-8' }).trim().split('\n').filter(Boolean)
119
+ const stale = allTags.slice(5)
120
+ for (const old of stale) {
121
+ execFileSync('git', ['tag', '-d', old], { stdio: 'pipe' })
122
+ }
123
+ if (stale.length > 0) console.log(`[deploy] Pruned ${stale.length} old known-good tag(s)`)
124
+ } catch (err) {
125
+ console.warn(`[deploy] Warning: failed to prune old tags: ${err.message}`)
126
+ }
127
+
128
+ // 5. Signal supervisor
129
+ if (!existsSync(PID_FILE)) {
130
+ console.error('[deploy] Supervisor PID file not found. Is chroxy running with supervisor mode?')
131
+ process.exitCode = 1
132
+ return
133
+ }
134
+
135
+ const supervisorPid = parseInt(readFileSync(PID_FILE, 'utf-8').trim(), 10)
136
+ if (isNaN(supervisorPid)) {
137
+ console.error('[deploy] Invalid supervisor PID')
138
+ process.exitCode = 1
139
+ return
140
+ }
141
+
142
+ try {
143
+ process.kill(supervisorPid, 0)
144
+ } catch {
145
+ console.error(`[deploy] Supervisor (pid ${supervisorPid}) is not running`)
146
+ process.exitCode = 1
147
+ return
148
+ }
149
+
150
+ if (isWindows) {
151
+ console.error('[deploy] Deploy restart via SIGUSR2 is not supported on Windows.')
152
+ console.error(' Restart the server manually: npx chroxy start')
153
+ process.exitCode = 1
154
+ return
155
+ }
156
+
157
+ console.log(`[deploy] Signaling supervisor (pid ${supervisorPid}) to restart...`)
158
+ process.kill(supervisorPid, 'SIGUSR2')
159
+ console.log('[deploy] Deploy signal sent. Server will restart momentarily.\n')
160
+
161
+ } finally {
162
+ if (lockAcquired) {
163
+ try { unlinkSync(LOCK_FILE) } catch {}
164
+ }
165
+ }
166
+ })
167
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * chroxy doctor — Check dependencies and environment
3
+ */
4
+ export function registerDoctorCommand(program) {
5
+ program
6
+ .command('doctor')
7
+ .description('Check that all dependencies are installed and configured correctly')
8
+ .option('-p, --port <port>', 'Port to check availability (default: 8765)')
9
+ .option('--provider <name>', 'Override provider(s) to preflight (comma-separated)')
10
+ .action(async (options) => {
11
+ const { runDoctorChecks } = await import('../doctor.js')
12
+
13
+ const port = options.port ? parseInt(options.port, 10) : undefined
14
+ const providers = options.provider
15
+ ? options.provider.split(',').map(s => s.trim()).filter(Boolean)
16
+ : undefined
17
+ const result = await runDoctorChecks({ port, providers })
18
+ const { checks, passed } = result
19
+
20
+ console.log('\nChroxy Doctor\n')
21
+
22
+ const STATUS_ICONS = { pass: '\x1b[32m OK \x1b[0m', warn: '\x1b[33mWARN\x1b[0m', fail: '\x1b[31mFAIL\x1b[0m' }
23
+
24
+ // Group checks into sections: general checks (no provider), then per-provider.
25
+ const general = checks.filter(c => !c.provider)
26
+ const byProvider = new Map()
27
+ for (const c of checks) {
28
+ if (!c.provider) continue
29
+ if (!byProvider.has(c.provider)) byProvider.set(c.provider, [])
30
+ byProvider.get(c.provider).push(c)
31
+ }
32
+
33
+ for (const check of general) {
34
+ console.log(` [${STATUS_ICONS[check.status]}] ${check.name.padEnd(18)} ${check.message}`)
35
+ }
36
+
37
+ for (const [providerName, providerChecks] of byProvider) {
38
+ console.log(`\n Provider: ${providerName}`)
39
+ for (const check of providerChecks) {
40
+ console.log(` [${STATUS_ICONS[check.status]}] ${check.name.padEnd(18)} ${check.message}`)
41
+ }
42
+ }
43
+
44
+ console.log('')
45
+ if (passed) {
46
+ console.log('All checks passed. Ready to start.\n')
47
+ } else {
48
+ console.log('Some checks failed. Fix the issues above and try again.\n')
49
+ process.exitCode = 1
50
+ }
51
+ })
52
+ }
@@ -0,0 +1,82 @@
1
+ // `chroxy identity rotate` — rotate the daemon's long-lived signing identity
2
+ // while minting a single-hop continuity cert (#5616/#5976).
3
+ //
4
+ // The daemon's identity key is what clients PIN at pairing time. Rotating it
5
+ // (reinstall, machine migration, key hygiene) would normally force every paired
6
+ // client to manually re-pair — and look indistinguishable from a MITM. This
7
+ // command instead signs the NEW identity with the OLD secret ("old signs new"),
8
+ // so a previously-pinned client that reconnects chains its pin forward
9
+ // automatically. Single-hop: only the most-recent rotation is bridged; a client
10
+ // that is ≄2 rotations behind still re-pairs.
11
+ //
12
+ // Admin-initiated and CONSEQUENTIAL, so it requires an explicit `--yes`. Without
13
+ // it, the command explains what will happen and changes nothing.
14
+
15
+ import { rotateServerIdentity } from '../server-identity.js'
16
+
17
+ /**
18
+ * Run the rotation. Pure aside from the injected `rotate` seam + writer, so a
19
+ * test can assert the output + that the rotation ran without touching real
20
+ * keychain/disk.
21
+ *
22
+ * @param {{ yes?: boolean }} options
23
+ * @param {object} [deps]
24
+ * @returns {{ rotated: boolean, result: object|null }}
25
+ */
26
+ export function runIdentityRotate(options = {}, deps = {}) {
27
+ const out = deps.write || console.log
28
+ const rotate = deps.rotate || rotateServerIdentity
29
+
30
+ if (!options.yes) {
31
+ out(
32
+ [
33
+ 'chroxy identity rotate — mint a NEW daemon identity (continuity cert preserved).',
34
+ '',
35
+ 'What happens:',
36
+ ' • A fresh identity keypair is minted and stored in place of the current one.',
37
+ ' • The OLD identity signs the NEW one (a single-hop continuity cert), so a',
38
+ ' client that pinned the current identity reconnects WITHOUT re-pairing.',
39
+ ' • A client that is ≄2 rotations behind, or that never pinned this daemon,',
40
+ ' will re-pair as usual.',
41
+ ' • Restart the daemon afterwards to serve the new identity.',
42
+ '',
43
+ 'This is consequential — re-run with --yes to proceed:',
44
+ ' chroxy identity rotate --yes',
45
+ ].join('\n'),
46
+ )
47
+ return { rotated: false, result: null }
48
+ }
49
+
50
+ const result = rotate(deps.rotateOpts || {})
51
+ out(
52
+ [
53
+ 'Rotated server identity.',
54
+ ` previous: ${result.previousPublicKey}`,
55
+ ` new: ${result.newPublicKey}`,
56
+ ` backend: ${result.backend}`,
57
+ '',
58
+ 'A single-hop continuity cert was written — previously-pinned clients chain',
59
+ 'forward without re-pairing. Restart the daemon to serve the new identity.',
60
+ ].join('\n'),
61
+ )
62
+ return { rotated: true, result }
63
+ }
64
+
65
+ export function registerIdentityCommand(program) {
66
+ const identity = program
67
+ .command('identity')
68
+ .description('Manage the daemon\'s long-lived signing identity (E2E key pinning)')
69
+
70
+ identity
71
+ .command('rotate')
72
+ .description('Rotate the identity key, preserving a single-hop continuity cert so pinned clients don\'t re-pair')
73
+ .option('--yes', 'Confirm the rotation (without this, the command only explains what it would do)')
74
+ .action((options) => {
75
+ try {
76
+ runIdentityRotate(options)
77
+ } catch (err) {
78
+ console.error(`identity rotate failed: ${err.message}`)
79
+ process.exitCode = 1
80
+ }
81
+ })
82
+ }
@@ -0,0 +1,209 @@
1
+ /**
2
+ * chroxy init — Set up configuration
3
+ */
4
+ import { existsSync, mkdirSync } from 'fs'
5
+ import { randomBytes } from 'crypto'
6
+ import { CONFIG_DIR, CONFIG_FILE, prompt } from './shared.js'
7
+ import { writeFileRestricted } from '../platform.js'
8
+ import { setToken, isKeychainAvailable } from '../keychain.js'
9
+
10
+ /**
11
+ * Catalog of user-selectable providers shown in the `chroxy init` picker.
12
+ *
13
+ * Each entry is the on-disk provider id (written to config.providers), a
14
+ * short display label for the UI, and a "next-step hint" explaining what
15
+ * the user still needs to do to make that provider usable — e.g. export
16
+ * an API key or log in via another CLI. The hint is printed only when the
17
+ * user selects the provider so we don't spam instructions for things
18
+ * they never asked for.
19
+ *
20
+ * Keep this list in sync with the built-in providers registered in
21
+ * `src/providers.js` — if a new first-class provider is added there, add
22
+ * it here too and bump the numbering in tests/prompts accordingly.
23
+ */
24
+ export const PROVIDER_CHOICES = [
25
+ {
26
+ // #5819 — default. Bills against the flat Claude subscription allowance
27
+ // today (best-effort, not guaranteed), keeping a zero-config setup off the
28
+ // metered programmatic-credit pool that claude-sdk/-cli draw from on/after
29
+ // 2026-06-15. See providers.js DEFAULT_PROVIDER.
30
+ id: 'claude-tui',
31
+ label: 'Claude (TUI Ā· subscription)',
32
+ hint: 'Drives the interactive CLI; bills against your Claude subscription today. Run \'claude login\' first.',
33
+ },
34
+ {
35
+ id: 'claude-sdk',
36
+ label: 'Claude (Agent SDK)',
37
+ hint: 'On/after 2026-06-15 draws metered programmatic credits unless ANTHROPIC_API_KEY is set. Run \'claude login\' (or set the key) if not already authenticated.',
38
+ },
39
+ {
40
+ id: 'codex',
41
+ label: 'Codex (OpenAI)',
42
+ hint: 'Set OPENAI_API_KEY in your environment before starting the server.',
43
+ },
44
+ {
45
+ id: 'gemini',
46
+ label: 'Gemini (Google)',
47
+ hint: 'Set GEMINI_API_KEY in your environment before starting the server.',
48
+ },
49
+ ]
50
+
51
+ /**
52
+ * Parse a comma-separated provider selection answer from the init prompt.
53
+ *
54
+ * Accepted forms:
55
+ * - empty / whitespace → default (claude-tui)
56
+ * - "all" → every known provider
57
+ * - "1", "2", "1,3", "1, 3" → numeric indices (1-based) into PROVIDER_CHOICES
58
+ *
59
+ * Invalid tokens (non-numeric, out-of-range) are silently dropped. If the
60
+ * result is empty we fall back to the default so the user always ends up
61
+ * with at least one working provider.
62
+ *
63
+ * @param {string} input
64
+ * @param {Array<{id: string}>} [choices]
65
+ * @returns {string[]} provider ids, order-preserving and de-duplicated
66
+ */
67
+ export function parseProviderSelection(input, choices = PROVIDER_CHOICES) {
68
+ const raw = (input || '').trim().toLowerCase()
69
+ if (raw === '') return [choices[0].id]
70
+ if (raw === 'all') return choices.map((c) => c.id)
71
+
72
+ const ids = []
73
+ for (const token of raw.split(',')) {
74
+ const trimmed = token.trim()
75
+ // Require the entire token to be digits — `parseInt('2abc', 10)`
76
+ // would otherwise silently accept `2`, which contradicts the
77
+ // "invalid tokens are dropped" contract documented above.
78
+ if (!/^\d+$/.test(trimmed)) continue
79
+ const n = parseInt(trimmed, 10)
80
+ const idx = n - 1
81
+ if (idx < 0 || idx >= choices.length) continue
82
+ const id = choices[idx].id
83
+ if (!ids.includes(id)) ids.push(id)
84
+ }
85
+
86
+ if (ids.length === 0) return [choices[0].id]
87
+ return ids
88
+ }
89
+
90
+ /**
91
+ * Run the `chroxy init` flow. Exposed as a pure(-ish) function so tests
92
+ * can inject prompt/log/fs/keychain stubs instead of touching stdin,
93
+ * stdout, or the user's real ~/.chroxy directory.
94
+ *
95
+ * @param {object} [deps]
96
+ * @param {boolean} [deps.force] - Overwrite existing config without asking
97
+ * @param {(q: string) => Promise<string>} [deps.promptFn] - Reads one line from the user
98
+ * @param {(msg: string) => void} [deps.logFn] - Prints user-visible output
99
+ * @param {(path: string, contents: string) => void} [deps.writeFileFn] - Persists the config
100
+ * @param {(path: string) => boolean} [deps.existsFn] - fs existsSync stub
101
+ * @param {(path: string) => void} [deps.ensureDirFn] - mkdir -p equivalent
102
+ * @param {() => boolean} [deps.isKeychainAvailableFn] - OS keychain probe
103
+ * @param {(token: string) => void} [deps.setTokenFn] - Store token in keychain
104
+ * @param {string} [deps.configFilePath] - Config file location
105
+ * @param {string} [deps.configDirPath] - Config directory location
106
+ * @param {() => string} [deps.generateTokenFn] - Token generator (for deterministic tests)
107
+ * @returns {Promise<{written: boolean, config: object, apiToken: string|null}>}
108
+ */
109
+ export async function runInitCmd(deps = {}) {
110
+ const promptFn = deps.promptFn || prompt
111
+ const logFn = deps.logFn || console.log
112
+ const writeFileFn = deps.writeFileFn || writeFileRestricted
113
+ const existsFn = deps.existsFn || existsSync
114
+ const ensureDirFn = deps.ensureDirFn || ((p) => mkdirSync(p, { recursive: true }))
115
+ const isKeychainAvailableFn = deps.isKeychainAvailableFn || isKeychainAvailable
116
+ const setTokenFn = deps.setTokenFn || setToken
117
+ const configFilePath = deps.configFilePath || CONFIG_FILE
118
+ const configDirPath = deps.configDirPath || CONFIG_DIR
119
+ const generateTokenFn =
120
+ deps.generateTokenFn || (() => randomBytes(32).toString('base64url'))
121
+
122
+ logFn('\nšŸ”§ Chroxy Setup\n')
123
+
124
+ if (existsFn(configFilePath) && !deps.force) {
125
+ logFn(`Config already exists at ${configFilePath}`)
126
+ const overwrite = await promptFn('Overwrite? (y/N): ')
127
+ if (overwrite.toLowerCase() !== 'y') {
128
+ logFn('Keeping existing config. Use --force to overwrite.')
129
+ return { written: false, config: null, apiToken: null }
130
+ }
131
+ }
132
+
133
+ if (!existsFn(configDirPath)) {
134
+ ensureDirFn(configDirPath)
135
+ }
136
+
137
+ logFn('We need a few things to get started:\n')
138
+
139
+ const apiToken = generateTokenFn()
140
+
141
+ logFn('1. Local WebSocket port')
142
+ const portInput = await promptFn(' Port (default 8765): ')
143
+ const port = parseInt(portInput, 10) || 8765
144
+
145
+ // Provider picker — see PROVIDER_CHOICES for the menu. Default is
146
+ // Claude-only, so existing users who just hit enter end up with the
147
+ // same behaviour they had before this prompt was added.
148
+ logFn('\n2. Which providers do you want to use?')
149
+ for (let i = 0; i < PROVIDER_CHOICES.length; i++) {
150
+ logFn(` ${i + 1}. ${PROVIDER_CHOICES[i].label}`)
151
+ }
152
+ logFn(' (comma-separated numbers, or "all". Default: 1 — Claude only)')
153
+ const providersInput = await promptFn(' Providers: ')
154
+ const providers = parseProviderSelection(providersInput)
155
+
156
+ // #6565: the daemon's provider SELECTOR reads the singular `provider` key
157
+ // (server-cli.js `config.provider || DEFAULT_PROVIDER`), NOT this `providers[]`
158
+ // list — that array is informational only (providers-cmd.js). Write the primary
159
+ // choice (providers[0]) as `provider` so the picker actually takes effect;
160
+ // otherwise a non-default selection is silently ignored and the daemon falls
161
+ // back to DEFAULT_PROVIDER (claude-tui). PROVIDER_CHOICES ids are already valid
162
+ // selector ids ('claude-tui', 'codex', …), so no mapping is needed.
163
+ const config = {
164
+ port,
165
+ ...(providers.length > 0 ? { provider: providers[0] } : {}),
166
+ providers,
167
+ }
168
+
169
+ // Store token in OS keychain if available, otherwise in config file
170
+ if (isKeychainAvailableFn()) {
171
+ setTokenFn(apiToken)
172
+ logFn('\nšŸ” API token stored in OS keychain')
173
+ } else {
174
+ config.apiToken = apiToken
175
+ logFn('\n⚠ OS keychain unavailable — token stored in config file (chmod 600)')
176
+ }
177
+
178
+ writeFileFn(configFilePath, JSON.stringify(config, null, 2))
179
+
180
+ logFn(`āœ… Configuration saved to: ${configFilePath}`)
181
+
182
+ // Per-provider next-step hints — only show instructions for providers
183
+ // the user actually selected to avoid noise.
184
+ const selectedChoices = PROVIDER_CHOICES.filter((c) => providers.includes(c.id))
185
+ if (selectedChoices.length > 0) {
186
+ logFn('\nšŸ“¦ Next steps for your selected providers:')
187
+ for (const choice of selectedChoices) {
188
+ logFn(` • ${choice.label}: ${choice.hint}`)
189
+ }
190
+ }
191
+
192
+ logFn('\nšŸ“± Your API token (keep this secret):')
193
+ logFn(` ${apiToken}`)
194
+ logFn('\nšŸš€ Run \'npx chroxy start\' to launch the server')
195
+ logFn('')
196
+
197
+ return { written: true, config, apiToken }
198
+ }
199
+
200
+ export function registerInitCommand(program) {
201
+ program
202
+ .command('init')
203
+ .description('Initialize Chroxy configuration')
204
+ .option('-f, --force', 'Overwrite existing configuration')
205
+ .action(async (options) => {
206
+ const result = await runInitCmd({ force: options.force })
207
+ if (!result.written) process.exit(0)
208
+ })
209
+ }