@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,130 @@
1
+ /**
2
+ * chroxy shell — host-local approval for user-shell spawns (#6277).
3
+ *
4
+ * chroxy shell list → list shells pending host approval
5
+ * chroxy shell approve <id> → approve a held shell (it spawns)
6
+ * chroxy shell deny <id> → decline a held shell
7
+ *
8
+ * These talk to the daemon's SEPARATE host-local approval listener — bound to
9
+ * 127.0.0.1 on an ephemeral port the Cloudflare tunnel never forwards (see
10
+ * shell-approval-info.js) — using the primary token from connection.json. So
11
+ * approval can only ever originate from the host machine, never over the tunnel.
12
+ */
13
+
14
+ async function approvalRequest(method, path, deps = {}) {
15
+ const readConnectionInfo =
16
+ deps.readConnectionInfo || (await import('../connection-info.js')).readConnectionInfo
17
+ const readShellApprovalInfo =
18
+ deps.readShellApprovalInfo || (await import('../shell-approval-info.js')).readShellApprovalInfo
19
+ const fetchFn = deps.fetchFn || globalThis.fetch
20
+
21
+ const conn = readConnectionInfo()
22
+ if (!conn) return { ok: false, reason: 'not_running' }
23
+ if (!conn.apiToken) return { ok: false, reason: 'no_token' }
24
+ const approval = readShellApprovalInfo()
25
+ if (!approval || !Number.isInteger(approval.port)) return { ok: false, reason: 'approval_disabled' }
26
+
27
+ const headers = { Authorization: `Bearer ${conn.apiToken}`, Accept: 'application/json' }
28
+ try {
29
+ const res = await fetchFn(`http://127.0.0.1:${approval.port}${path}`, {
30
+ method,
31
+ headers,
32
+ signal: AbortSignal.timeout(10_000),
33
+ })
34
+ let json = null
35
+ try { json = await res.json() } catch { /* non-JSON body */ }
36
+ if (!res.ok) {
37
+ return { ok: false, reason: 'http_error', status: res.status, message: json?.error || `HTTP ${res.status}` }
38
+ }
39
+ return { ok: true, json }
40
+ } catch (err) {
41
+ return { ok: false, reason: 'unavailable', message: err?.message || 'request failed' }
42
+ }
43
+ }
44
+
45
+ function reportFailure(result, writeErr) {
46
+ switch (result.reason) {
47
+ case 'not_running':
48
+ writeErr('Chroxy server is not running. Start it with `chroxy start`.')
49
+ break
50
+ case 'no_token':
51
+ writeErr('Server is running without an auth token — shell approval is unavailable.')
52
+ break
53
+ case 'approval_disabled':
54
+ writeErr('User-shell approval is not enabled. Set userShell.requireApproval and restart the daemon.')
55
+ break
56
+ case 'http_error':
57
+ if (result.status === 404) writeErr('No pending approval with that id (it may have expired or already been used).')
58
+ else if (result.status === 403) writeErr(result.message === 'expired' ? 'That approval has expired.' : 'Not authorized — the primary token is required.')
59
+ else writeErr(`Request failed: ${result.message || result.status}`)
60
+ break
61
+ default:
62
+ writeErr(`Request failed: ${result.message || result.reason}`)
63
+ }
64
+ }
65
+
66
+ export async function runShellListCmd(options = {}, deps = {}) {
67
+ const out = deps.out || ((s) => process.stdout.write(s + '\n'))
68
+ const err = deps.err || ((s) => process.stderr.write(s + '\n'))
69
+ const result = await approvalRequest('GET', '/api/shell/pending', deps)
70
+ if (!result.ok) { reportFailure(result, err); return result }
71
+ const pending = result.json?.pending || []
72
+ if (options.json) { out(JSON.stringify(pending, null, 2)); return result }
73
+ if (pending.length === 0) { out('No shells pending approval.'); return result }
74
+ out(`${pending.length} shell(s) pending host approval:`)
75
+ for (const p of pending) {
76
+ out(` ${p.approvalId} cwd=${p.cwd || '(default)'} device=${p.deviceName || '(unknown)'}`)
77
+ }
78
+ return result
79
+ }
80
+
81
+ async function runShellDecisionCmd(decision, id, options = {}, deps = {}) {
82
+ const out = deps.out || ((s) => process.stdout.write(s + '\n'))
83
+ const err = deps.err || ((s) => process.stderr.write(s + '\n'))
84
+ if (typeof id !== 'string' || id.length === 0) {
85
+ err('An approval id is required.')
86
+ return { ok: false, reason: 'bad_args' }
87
+ }
88
+ const result = await approvalRequest('POST', `/api/shell/${decision}?id=${encodeURIComponent(id)}`, deps)
89
+ if (!result.ok) { reportFailure(result, err); return result }
90
+ if (options.json) { out(JSON.stringify(result.json || { ok: true }, null, 2)); return result }
91
+ if (decision === 'approve') out(`Approved — shell spawned (session ${result.json?.sessionId || '?'}).`)
92
+ else out('Declined.')
93
+ return result
94
+ }
95
+
96
+ export async function runShellApproveCmd(id, options = {}, deps = {}) {
97
+ return runShellDecisionCmd('approve', id, options, deps)
98
+ }
99
+
100
+ export async function runShellDenyCmd(id, options = {}, deps = {}) {
101
+ return runShellDecisionCmd('deny', id, options, deps)
102
+ }
103
+
104
+ export function registerShellApprovalCommand(program) {
105
+ const shell = program.command('shell').description('Approve or deny host-local user-shell spawns (#6277)')
106
+ shell
107
+ .command('list')
108
+ .description('List shells pending host approval')
109
+ .option('--json', 'Output machine-readable JSON')
110
+ .action(async (options) => {
111
+ const r = await runShellListCmd(options)
112
+ if (!r.ok) process.exitCode = 1
113
+ })
114
+ shell
115
+ .command('approve <id>')
116
+ .description('Approve a held shell — it spawns on the host')
117
+ .option('--json', 'Output machine-readable JSON')
118
+ .action(async (id, options) => {
119
+ const r = await runShellApproveCmd(id, options)
120
+ if (!r.ok) process.exitCode = 1
121
+ })
122
+ shell
123
+ .command('deny <id>')
124
+ .description('Decline a held shell')
125
+ .option('--json', 'Output machine-readable JSON')
126
+ .action(async (id, options) => {
127
+ const r = await runShellDenyCmd(id, options)
128
+ if (!r.ok) process.exitCode = 1
129
+ })
130
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * chroxy status — Show whether the Chroxy server is running,
3
+ * tunnel URL/mode, uptime, version, and active session count.
4
+ *
5
+ * Detection uses connection.json (written by server-cli/supervisor) which
6
+ * is stale-checked via PID, then pings the local HTTP health endpoint.
7
+ */
8
+ import { createRequire } from 'module'
9
+
10
+ const require = createRequire(import.meta.url)
11
+ const { version: CLI_VERSION } = require('../../package.json')
12
+
13
+ function formatUptime(seconds) {
14
+ if (!Number.isFinite(seconds) || seconds < 0) return 'unknown'
15
+ const s = Math.floor(seconds)
16
+ const d = Math.floor(s / 86400)
17
+ const h = Math.floor((s % 86400) / 3600)
18
+ const m = Math.floor((s % 3600) / 60)
19
+ const rem = s % 60
20
+ if (d > 0) return `${d}d ${h}h ${m}m`
21
+ if (h > 0) return `${h}h ${m}m`
22
+ if (m > 0) return `${m}m ${rem}s`
23
+ return `${rem}s`
24
+ }
25
+
26
+ function classifyTunnel(mode, wsUrl) {
27
+ if (mode) return mode
28
+ if (typeof wsUrl === 'string') {
29
+ if (wsUrl.includes('trycloudflare.com')) return 'quick'
30
+ if (wsUrl.startsWith('wss://')) return 'named'
31
+ if (wsUrl.startsWith('ws://')) return 'local'
32
+ }
33
+ return 'unknown'
34
+ }
35
+
36
+ function portFromUrl(url) {
37
+ if (typeof url !== 'string') return null
38
+ const m = url.match(/:(\d+)(?:\/|$)/)
39
+ return m ? parseInt(m[1], 10) : null
40
+ }
41
+
42
+ /**
43
+ * Collect status information. Exposed for testing.
44
+ * @param {object} [deps]
45
+ * @param {function} [deps.readConnectionInfo]
46
+ * @param {function} [deps.fetchFn]
47
+ * @param {number} [deps.defaultPort]
48
+ */
49
+ export async function collectStatus(deps = {}) {
50
+ const readConnectionInfo =
51
+ deps.readConnectionInfo ||
52
+ (await import('../connection-info.js')).readConnectionInfo
53
+ const fetchFn = deps.fetchFn || globalThis.fetch
54
+ const defaultPort = deps.defaultPort || 8765
55
+
56
+ const out = {
57
+ version: CLI_VERSION,
58
+ running: false,
59
+ pid: null,
60
+ port: null,
61
+ tunnel: null,
62
+ uptimeSeconds: null,
63
+ sessions: null,
64
+ mode: null,
65
+ counters: null, // populated by --verbose via /metrics
66
+ }
67
+
68
+ const info = readConnectionInfo()
69
+ if (info) {
70
+ out.pid = info.pid ?? null
71
+ out.port =
72
+ portFromUrl(info.httpUrl) || portFromUrl(info.wsUrl) || defaultPort
73
+ out.tunnel = {
74
+ url: info.httpUrl || info.wsUrl || null,
75
+ type: classifyTunnel(info.tunnelMode, info.wsUrl),
76
+ }
77
+ if (info.startedAt) {
78
+ const started = Date.parse(info.startedAt)
79
+ if (!Number.isNaN(started)) {
80
+ out.uptimeSeconds = Math.round((Date.now() - started) / 1000)
81
+ }
82
+ }
83
+ }
84
+
85
+ // Ping local health endpoint regardless — this is the definitive
86
+ // "is something listening" check.
87
+ const pingPort = out.port || defaultPort
88
+ try {
89
+ const res = await fetchFn(`http://127.0.0.1:${pingPort}/`, {
90
+ signal: AbortSignal.timeout(2000),
91
+ headers: { Accept: 'application/json' },
92
+ })
93
+ if (res && res.ok) {
94
+ out.running = true
95
+ try {
96
+ const body = await res.json()
97
+ if (body && typeof body === 'object') {
98
+ if (body.version) out.version = body.version
99
+ if (body.mode) out.mode = body.mode
100
+ }
101
+ } catch {
102
+ // non-JSON response — still counts as running
103
+ }
104
+ }
105
+ } catch {
106
+ // fetch failed — server not reachable on this port
107
+ }
108
+
109
+ // Active session count — try authenticated /metrics if we have a token.
110
+ if (out.running && info?.apiToken) {
111
+ try {
112
+ const res = await fetchFn(`http://127.0.0.1:${pingPort}/metrics`, {
113
+ signal: AbortSignal.timeout(2000),
114
+ headers: { Authorization: `Bearer ${info.apiToken}` },
115
+ })
116
+ if (res && res.ok) {
117
+ const body = await res.json()
118
+ if (body?.sessions?.active != null) {
119
+ out.sessions = body.sessions.active
120
+ }
121
+ if (body?.uptime != null && out.uptimeSeconds == null) {
122
+ out.uptimeSeconds = body.uptime
123
+ }
124
+ if (body?.counters && typeof body.counters === 'object') {
125
+ out.counters = body.counters
126
+ }
127
+ }
128
+ } catch {
129
+ // Ignore — sessions remains null
130
+ }
131
+ }
132
+
133
+ if (!out.running) {
134
+ // If we can't reach the endpoint, consider it not running even if a
135
+ // stale connection.json existed. Clear volatile fields.
136
+ out.pid = null
137
+ }
138
+
139
+ return out
140
+ }
141
+
142
+ function printHuman(status) {
143
+ const lines = []
144
+ lines.push('')
145
+ lines.push(`Chroxy v${status.version}`)
146
+ lines.push('')
147
+ if (!status.running) {
148
+ lines.push('Status: Not running')
149
+ lines.push('')
150
+ return lines.join('\n')
151
+ }
152
+ lines.push(
153
+ `Status: Running${status.pid ? ` (pid ${status.pid})` : ''}`
154
+ )
155
+ if (status.port != null) lines.push(`Port: ${status.port}`)
156
+ if (status.tunnel?.url) {
157
+ lines.push(`Tunnel: ${status.tunnel.url} (${status.tunnel.type})`)
158
+ } else {
159
+ lines.push('Tunnel: (none)')
160
+ }
161
+ if (status.uptimeSeconds != null) {
162
+ lines.push(`Uptime: ${formatUptime(status.uptimeSeconds)}`)
163
+ }
164
+ if (status.sessions != null) {
165
+ lines.push(`Sessions: ${status.sessions} active`)
166
+ }
167
+ if (status.counters && typeof status.counters === 'object') {
168
+ const c = status.counters
169
+ // Only show non-zero counters — keeps default output clean
170
+ const entries = Object.entries(c).filter(([k, v]) => k !== '_uptimeSeconds' && v > 0)
171
+ if (entries.length > 0) {
172
+ lines.push('')
173
+ lines.push('Counters (this lifetime):')
174
+ for (const [k, v] of entries.sort(([a], [b]) => a.localeCompare(b))) {
175
+ lines.push(` ${k}: ${v}`)
176
+ }
177
+ }
178
+ }
179
+ lines.push('')
180
+ return lines.join('\n')
181
+ }
182
+
183
+ export async function runStatusCmd(options = {}, deps = {}) {
184
+ const status = await collectStatus(deps)
185
+ if (options.json) {
186
+ const out = (deps.write || console.log)
187
+ out(JSON.stringify(status, null, 2))
188
+ } else {
189
+ const out = (deps.write || console.log)
190
+ out(printHuman(status))
191
+ }
192
+ return status
193
+ }
194
+
195
+ export function registerStatusCommand(program) {
196
+ program
197
+ .command('status')
198
+ .description('Show whether the Chroxy server is running and its current state')
199
+ .option('--json', 'Output machine-readable JSON')
200
+ .action(async (options) => {
201
+ const status = await runStatusCmd(options)
202
+ if (!status.running) process.exitCode = 1
203
+ })
204
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * chroxy tunnel — Tunnel management commands
3
+ */
4
+ import { existsSync, mkdirSync, readFileSync } from 'fs'
5
+ import { CloudflareTunnelAdapter } from '../tunnel/index.js'
6
+ import { writeFileRestricted } from '../platform.js'
7
+ import { CONFIG_DIR, CONFIG_FILE, prompt } from './shared.js'
8
+
9
+ export function registerTunnelCommand(program) {
10
+ const tunnelCmd = program
11
+ .command('tunnel')
12
+ .description('Manage tunnel configuration')
13
+
14
+ tunnelCmd
15
+ .command('setup')
16
+ .description('Interactive Cloudflare Named Tunnel setup')
17
+ .action(async () => {
18
+ const binary = CloudflareTunnelAdapter.checkBinary()
19
+ if (!binary.available) {
20
+ console.error(`❌ cloudflared not found.${binary.hint ? ' ' + binary.hint : ''}`)
21
+ process.exit(1)
22
+ }
23
+
24
+ await setupCloudflare()
25
+ })
26
+ }
27
+
28
+ async function setupCloudflare() {
29
+ const { execFileSync } = await import('child_process')
30
+
31
+ console.log('\n🔧 Named Tunnel Setup\n')
32
+ console.log('A Named Tunnel gives you a stable URL that never changes.')
33
+ console.log('You need: a Cloudflare account + a domain on Cloudflare DNS.\n')
34
+
35
+ console.log('Step 1: Authenticate with Cloudflare\n')
36
+ console.log('This will open a browser window to log in to Cloudflare.')
37
+ const loginAnswer = await prompt('Ready to login? (Y/n): ')
38
+ if (loginAnswer.toLowerCase() === 'n') {
39
+ console.log('\nRun \'cloudflared tunnel login\' manually when ready.')
40
+ process.exit(0)
41
+ }
42
+
43
+ try {
44
+ execFileSync('cloudflared', ['tunnel', 'login'], { stdio: 'inherit' })
45
+ } catch (_err) {
46
+ console.error('\n❌ Login failed. Run \'cloudflared tunnel login\' manually.')
47
+ process.exit(1)
48
+ }
49
+
50
+ console.log('\n✅ Authenticated with Cloudflare\n')
51
+
52
+ console.log('Step 2: Create a tunnel\n')
53
+ const tunnelName = (await prompt('Tunnel name (default \'chroxy\'): ')) || 'chroxy'
54
+
55
+ try {
56
+ execFileSync('cloudflared', ['tunnel', 'create', tunnelName], { stdio: 'inherit' })
57
+ } catch {
58
+ console.log(`\nTunnel '${tunnelName}' may already exist. Continuing...\n`)
59
+ }
60
+
61
+ console.log('\nStep 3: Set up DNS route\n')
62
+ console.log('Enter the hostname you want to use (e.g., chroxy.example.com).')
63
+ console.log('The domain must be on Cloudflare DNS.\n')
64
+ const hostname = await prompt('Hostname: ')
65
+ if (!hostname) {
66
+ console.error('❌ Hostname is required.')
67
+ process.exit(1)
68
+ }
69
+
70
+ try {
71
+ execFileSync('cloudflared', ['tunnel', 'route', 'dns', tunnelName, hostname], { stdio: 'inherit' })
72
+ } catch {
73
+ console.log('\nDNS route may already exist. Continuing...\n')
74
+ }
75
+
76
+ console.log('\nStep 4: Saving configuration\n')
77
+
78
+ if (!existsSync(CONFIG_DIR)) {
79
+ mkdirSync(CONFIG_DIR, { recursive: true })
80
+ }
81
+
82
+ let config = {}
83
+ if (existsSync(CONFIG_FILE)) {
84
+ config = JSON.parse(readFileSync(CONFIG_FILE, 'utf-8'))
85
+ }
86
+
87
+ config.tunnel = 'named'
88
+ config.tunnelName = tunnelName
89
+ config.tunnelHostname = hostname
90
+
91
+ writeFileRestricted(CONFIG_FILE, JSON.stringify(config, null, 2))
92
+
93
+ console.log('✅ Configuration saved to:', CONFIG_FILE)
94
+ console.log('')
95
+ console.log('Your stable URLs:')
96
+ console.log(` HTTP: https://${hostname}`)
97
+ console.log(` WebSocket: wss://${hostname}`)
98
+ console.log('')
99
+ console.log('Run \'npx chroxy start\' to launch with your Named Tunnel.')
100
+ console.log('The QR code will always be the same — scan it once, connect forever.\n')
101
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * chroxy update — Check for available updates
3
+ */
4
+ import { createRequire } from 'module'
5
+ import { isNewer } from '../semver.js'
6
+
7
+ const require = createRequire(import.meta.url)
8
+ const { version } = require('../../package.json')
9
+
10
+ export function registerUpdateCommand(program) {
11
+ program
12
+ .command('update')
13
+ .description('Check for available updates')
14
+ .action(async () => {
15
+ try {
16
+ const res = await fetch('https://api.github.com/repos/blamechris/chroxy/releases/latest', {
17
+ headers: { 'User-Agent': 'chroxy-cli' },
18
+ })
19
+ if (!res.ok) {
20
+ console.error('Failed to check for updates:', res.statusText)
21
+ process.exit(1)
22
+ }
23
+ const release = await res.json()
24
+ const latest = release.tag_name.replace(/^v/, '')
25
+ const current = version
26
+
27
+ if (!isNewer(latest, current)) {
28
+ console.log(`\nChroxy v${current} is up to date.\n`)
29
+ } else {
30
+ console.log(`\nUpdate available: v${current} → v${latest}`)
31
+ console.log(`\nRelease: ${release.html_url}`)
32
+ console.log('\nTo update (git clone):')
33
+ console.log(' git pull && npm ci\n')
34
+
35
+ const dmg = release.assets?.find(a => a.name.endsWith('.dmg'))
36
+ if (dmg) {
37
+ console.log(`Desktop app: ${dmg.browser_download_url}\n`)
38
+ }
39
+ }
40
+ } catch (err) {
41
+ console.error('Failed to check for updates:', err.message)
42
+ process.exit(1)
43
+ }
44
+ })
45
+ }
@@ -0,0 +1,195 @@
1
+ // `chroxy worktree gc` — reclaim orphaned, dead-pid-locked agent worktrees (#5158).
2
+ //
3
+ // Dry-run by DEFAULT: it reports what it would reclaim and changes nothing.
4
+ // Pass --apply to actually unlock + remove (clean trees only, never --force).
5
+ //
6
+ // Scans the resolved repo set (config.repos ∪ auto-discover under the
7
+ // configured root, default ~/Projects) — or a single repo via --repo — and,
8
+ // per the safety contract in worktree-gc.js, only reclaims worktrees that are
9
+ // locked by a verified-dead pid AND clean, plus stale dir-gone admin refs.
10
+
11
+ import { existsSync, readFileSync } from 'node:fs'
12
+ import { execFileSync } from 'node:child_process'
13
+ import { resolve, basename } from 'node:path'
14
+ import { CONFIG_FILE } from './shared.js'
15
+ import { resolveRepoSet } from '../control-room/repo-set.js'
16
+ import { planRepoGc, applyPlan } from '../worktree-gc.js'
17
+
18
+ /** Read config.json best-effort for repos + discovery root (never throws/exits). */
19
+ function readConfigSoft(configPath, deps = {}) {
20
+ const { exists = existsSync, read = readFileSync } = deps
21
+ try {
22
+ if (!exists(configPath)) return {}
23
+ return JSON.parse(read(configPath, 'utf-8')) || {}
24
+ } catch {
25
+ return {}
26
+ }
27
+ }
28
+
29
+ /** Best-effort directory size in KiB via `du -sk`; null when unavailable. */
30
+ function dirSizeKib(path, deps = {}) {
31
+ const { exec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8' }) } = deps
32
+ try {
33
+ const out = exec('du', ['-sk', path])
34
+ const kib = parseInt(String(out).split(/\s+/)[0], 10)
35
+ return Number.isFinite(kib) ? kib : null
36
+ } catch {
37
+ return null
38
+ }
39
+ }
40
+
41
+ function humanSize(kib) {
42
+ if (kib == null) return ''
43
+ if (kib < 1024) return `${kib} KiB`
44
+ const mib = kib / 1024
45
+ if (mib < 1024) return `${mib.toFixed(1)} MiB`
46
+ return `${(mib / 1024).toFixed(2)} GiB`
47
+ }
48
+
49
+ /**
50
+ * Build the GC report across all target repos. Returns a structured object
51
+ * (also what --json prints). Pure aside from injected seams.
52
+ */
53
+ export function collectWorktreeGc(options = {}, deps = {}) {
54
+ const {
55
+ configPath = CONFIG_FILE,
56
+ plan = planRepoGc,
57
+ sizeOf = (p) => dirSizeKib(p, deps),
58
+ withSizes = true,
59
+ } = deps
60
+
61
+ // #5706: read config up front so manual `chroxy worktree gc` honors the same
62
+ // age-fallback setting as the auto-reaper (otherwise an operator who set
63
+ // maxLockAgeMs would find the CLI ignored it). Soft-read → {} when absent.
64
+ const cfg = readConfigSoft(configPath, deps)
65
+ const cliMaxAge = cfg.worktreeGc?.maxLockAgeMs
66
+ const planDeps = {
67
+ ...(Number.isFinite(cliMaxAge) && cliMaxAge >= 0 ? { maxLockAgeMs: cliMaxAge } : {}),
68
+ ...(deps.planDeps || {}),
69
+ }
70
+
71
+ let repos
72
+ if (options.repo) {
73
+ const p = resolve(options.repo)
74
+ repos = [{ name: basename(p), path: p }]
75
+ } else {
76
+ repos = resolveRepoSet({
77
+ repos: cfg.repos,
78
+ root: cfg.controlRoomRoot,
79
+ ...(deps.repoSetSeams || {}),
80
+ })
81
+ }
82
+
83
+ const reposOut = []
84
+ let reclaimableCount = 0
85
+ let reclaimableKib = 0
86
+ let skippedCount = 0
87
+
88
+ for (const r of repos) {
89
+ const p = plan(r.path, planDeps)
90
+ const reclaimable = p.items.filter((it) => it.action === 'remove' || it.action === 'prune')
91
+ const skipped = p.items.filter((it) => it.action === 'skip')
92
+ if (withSizes) {
93
+ for (const it of reclaimable) {
94
+ if (it.action === 'remove') {
95
+ it.sizeKib = sizeOf(it.path)
96
+ if (it.sizeKib != null) reclaimableKib += it.sizeKib
97
+ }
98
+ }
99
+ }
100
+ reclaimableCount += reclaimable.length
101
+ skippedCount += skipped.length
102
+ reposOut.push({ name: r.name, path: r.path, error: p.error, reclaimable, skipped })
103
+ }
104
+
105
+ return {
106
+ apply: !!options.apply,
107
+ repoCount: repos.length,
108
+ reclaimableCount,
109
+ reclaimableKib,
110
+ skippedCount,
111
+ repos: reposOut,
112
+ }
113
+ }
114
+
115
+ function printHuman(report, applied) {
116
+ const lines = []
117
+ const mode = report.apply ? 'apply' : 'dry-run'
118
+ lines.push(`Worktree GC (${mode}) — scanned ${report.repoCount} repo${report.repoCount === 1 ? '' : 's'}`)
119
+ lines.push('')
120
+
121
+ let any = false
122
+ for (const repo of report.repos) {
123
+ const reclaimable = repo.reclaimable
124
+ if (repo.error) {
125
+ lines.push(` ${repo.name} — error: ${repo.error}`)
126
+ any = true
127
+ continue
128
+ }
129
+ if (reclaimable.length === 0) continue
130
+ any = true
131
+ lines.push(` ${repo.name} (${repo.path})`)
132
+ for (const it of reclaimable) {
133
+ const size = it.sizeKib != null ? ` [${humanSize(it.sizeKib)}]` : ''
134
+ const verb = it.action === 'prune' ? 'prune' : 'remove'
135
+ const why = it.reason ? ` — ${it.reason}` : ''
136
+ let status = ''
137
+ if (applied) {
138
+ const res = applied.find((a) => a.path === it.path)
139
+ status = res ? (res.ok ? ' ✓ done' : ` ✗ failed: ${res.error}`) : ''
140
+ }
141
+ lines.push(` ${verb} ${it.path}${size}${why}${status}`)
142
+ }
143
+ lines.push('')
144
+ }
145
+
146
+ if (!any) {
147
+ lines.push(' Nothing to reclaim — no dead-pid-locked or stale worktrees found.')
148
+ lines.push('')
149
+ }
150
+
151
+ const sz = report.reclaimableKib ? ` (~${humanSize(report.reclaimableKib)})` : ''
152
+ lines.push(`Summary: ${report.reclaimableCount} reclaimable${sz}, ${report.skippedCount} skipped (live/dirty/unknown — preserved).`)
153
+ if (!report.apply && report.reclaimableCount > 0) {
154
+ lines.push('Re-run with --apply to reclaim them (clean trees only; never --force).')
155
+ }
156
+ return lines.join('\n')
157
+ }
158
+
159
+ export async function runWorktreeGc(options = {}, deps = {}) {
160
+ const out = deps.write || console.log
161
+ const report = collectWorktreeGc(options, deps)
162
+
163
+ let applied = null
164
+ if (options.apply) {
165
+ applied = []
166
+ for (const repo of report.repos) {
167
+ if (repo.error || repo.reclaimable.length === 0) continue
168
+ const res = applyPlan(repo.path, { items: repo.reclaimable }, deps.planDeps || {})
169
+ applied.push(...res)
170
+ }
171
+ }
172
+
173
+ if (options.json) {
174
+ out(JSON.stringify({ ...report, applied }, null, 2))
175
+ } else {
176
+ out(printHuman(report, applied))
177
+ }
178
+ return { report, applied }
179
+ }
180
+
181
+ export function registerWorktreeCommand(program) {
182
+ const wt = program
183
+ .command('worktree')
184
+ .description('Manage chroxy/agent git worktrees')
185
+
186
+ wt
187
+ .command('gc')
188
+ .description('Reclaim orphaned worktrees locked by dead agent processes (dry-run by default)')
189
+ .option('--repo <path>', 'Scan a single repo instead of the configured/discovered set')
190
+ .option('--apply', 'Actually unlock + remove reclaimable worktrees (default: dry-run report only)')
191
+ .option('--json', 'Output machine-readable JSON')
192
+ .action(async (options) => {
193
+ await runWorktreeGc(options)
194
+ })
195
+ }