@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,237 @@
1
+ /**
2
+ * chroxy service — Manage Chroxy as a system daemon
3
+ */
4
+ import { existsSync } from 'fs'
5
+ import { homedir } from 'os'
6
+ import { isWindows } from '../platform.js'
7
+
8
+ export function registerServiceCommand(program) {
9
+ const serviceCmd = program
10
+ .command('service')
11
+ .description('Manage Chroxy as a system daemon')
12
+
13
+ serviceCmd
14
+ .command('install')
15
+ .description('Register Chroxy as a system daemon (launchd/systemd)')
16
+ .option('--cwd <path>', 'Working directory for Claude sessions')
17
+ .option('--start-at-login', 'Start automatically on login')
18
+ .action(async (options) => {
19
+ const {
20
+ getServicePaths,
21
+ resolveNode22Path,
22
+ resolveChroxyBin,
23
+ resolveClaudeBin,
24
+ loadServiceState,
25
+ installService,
26
+ } = await import('../service.js')
27
+
28
+ if (isWindows) {
29
+ console.error('Error: Service install is not supported on Windows.')
30
+ console.error('Only macOS (launchd) and Linux (systemd) are supported.')
31
+ process.exit(1)
32
+ }
33
+
34
+ const existing = loadServiceState()
35
+ if (existing) {
36
+ console.error('Chroxy service is already installed.')
37
+ console.error(` Service file: ${existing.servicePath}`)
38
+ console.error(' Run "chroxy service uninstall" first to remove it.')
39
+ process.exit(1)
40
+ }
41
+
42
+ let nodePath
43
+ try {
44
+ nodePath = resolveNode22Path()
45
+ } catch (err) {
46
+ console.error(`Error: ${err.message}`)
47
+ process.exit(1)
48
+ }
49
+
50
+ let chroxyBin
51
+ try {
52
+ chroxyBin = resolveChroxyBin()
53
+ } catch (err) {
54
+ console.error(`Error: ${err.message}`)
55
+ process.exit(1)
56
+ }
57
+
58
+ // Resolve the claude CLI from the installer's PATH and bake it into the
59
+ // service PATH (#5491). Install MUST fail here rather than register a job
60
+ // that crash-loops on preflight when claude isn't on launchd's PATH.
61
+ let claudeBin
62
+ try {
63
+ claudeBin = resolveClaudeBin()
64
+ } catch (err) {
65
+ console.error(`Error: ${err.message}`)
66
+ process.exit(1)
67
+ }
68
+
69
+ const cwd = options.cwd || homedir()
70
+
71
+ if (options.cwd && !existsSync(options.cwd)) {
72
+ console.error(`Error: Working directory "${options.cwd}" does not exist.`)
73
+ process.exit(1)
74
+ }
75
+
76
+ const startAtLogin = options.startAtLogin || false
77
+
78
+ try {
79
+ installService({
80
+ nodePath,
81
+ chroxyBin,
82
+ claudeBin,
83
+ cwd,
84
+ startAtLogin,
85
+ })
86
+
87
+ const paths = getServicePaths()
88
+ const servicePath = paths.type === 'launchd' ? paths.plistPath : paths.unitPath
89
+
90
+ console.log('\n\u2705 Chroxy service installed successfully!\n')
91
+ console.log(` Node: ${nodePath}`)
92
+ console.log(` Chroxy CLI: ${chroxyBin}`)
93
+ console.log(` Claude CLI: ${claudeBin}`)
94
+ console.log(` Service file: ${servicePath}`)
95
+ console.log(` Log dir: ${paths.logDir}`)
96
+ console.log(` Working dir: ${cwd}`)
97
+ console.log(` Start on login: ${startAtLogin}`)
98
+ if (paths.type === 'launchd') {
99
+ console.log('\nThe service is installed but not running. To start it now:')
100
+ console.log(' launchctl start com.chroxy.server')
101
+ } else {
102
+ console.log('\nThe service is enabled and running. To restart it:')
103
+ console.log(' systemctl --user restart chroxy.service')
104
+ }
105
+ } catch (err) {
106
+ console.error(`Error installing service: ${err.message}`)
107
+ process.exit(1)
108
+ }
109
+ })
110
+
111
+ serviceCmd
112
+ .command('uninstall')
113
+ .description('Remove the Chroxy system daemon')
114
+ .action(async () => {
115
+ const { uninstallService, loadServiceState } = await import('../service.js')
116
+
117
+ const state = loadServiceState()
118
+ if (!state) {
119
+ console.error('Chroxy service is not installed. Nothing to uninstall.')
120
+ process.exit(1)
121
+ }
122
+
123
+ try {
124
+ uninstallService()
125
+ console.log('\n\u2705 Chroxy service uninstalled successfully.\n')
126
+ console.log(' Service file and state have been removed.')
127
+ if (state.platform === 'darwin') {
128
+ console.log(' The launchd job has been unloaded.')
129
+ } else {
130
+ console.log(' The systemd unit has been disabled and stopped.')
131
+ }
132
+ } catch (err) {
133
+ console.error(`Error uninstalling service: ${err.message}`)
134
+ process.exit(1)
135
+ }
136
+ })
137
+
138
+ serviceCmd
139
+ .command('start')
140
+ .description('Start the Chroxy daemon')
141
+ .action(async () => {
142
+ const { getServiceStatus, startService } = await import('../service.js')
143
+ const status = getServiceStatus()
144
+
145
+ if (!status.installed) {
146
+ console.error('Chroxy service is not installed. Run: chroxy service install')
147
+ process.exit(1)
148
+ }
149
+ if (status.running) {
150
+ console.error('Chroxy service is already running (PID ' + status.pid + ')')
151
+ process.exit(1)
152
+ }
153
+
154
+ try {
155
+ startService()
156
+ console.log('Chroxy service started')
157
+ console.log('Check status: chroxy service status')
158
+ } catch (err) {
159
+ console.error('Failed to start service:', err.message)
160
+ process.exit(1)
161
+ }
162
+ })
163
+
164
+ serviceCmd
165
+ .command('stop')
166
+ .description('Stop the Chroxy daemon')
167
+ .action(async () => {
168
+ const { getServiceStatus, stopService } = await import('../service.js')
169
+ const status = getServiceStatus()
170
+
171
+ if (!status.installed) {
172
+ console.error('Chroxy service is not installed.')
173
+ process.exit(1)
174
+ }
175
+ if (!status.running) {
176
+ console.error('Chroxy service is not running.')
177
+ process.exit(1)
178
+ }
179
+
180
+ try {
181
+ stopService()
182
+ console.log('Chroxy service stopped')
183
+ } catch (err) {
184
+ console.error('Failed to stop service:', err.message)
185
+ process.exit(1)
186
+ }
187
+ })
188
+
189
+ serviceCmd
190
+ .command('status')
191
+ .description('Show daemon status')
192
+ .action(async () => {
193
+ const { getFullServiceStatus } = await import('../service.js')
194
+ const status = await getFullServiceStatus()
195
+
196
+ console.log('\nChroxy Service Status\n')
197
+
198
+ if (!status.installed) {
199
+ console.log(' Installed: No')
200
+ console.log(' Run: chroxy service install\n')
201
+ return
202
+ }
203
+
204
+ console.log(' Installed: Yes')
205
+
206
+ if (!status.running) {
207
+ if (status.stale) {
208
+ console.log(' Running: No (stale PID file)')
209
+ } else {
210
+ console.log(' Running: No')
211
+ }
212
+ console.log(' Run: chroxy service start\n')
213
+ return
214
+ }
215
+
216
+ console.log(' Running: Yes (PID ' + status.pid + ')')
217
+
218
+ if (status.health) {
219
+ console.log(' Status: ' + status.health.status)
220
+ }
221
+
222
+ if (status.connection) {
223
+ console.log(' URL: ' + status.connection.wsUrl)
224
+ const token = status.connection.apiToken
225
+ if (token) console.log(' Token: ' + token)
226
+ }
227
+
228
+ if (status.recentLogs && status.recentLogs.length > 0) {
229
+ console.log('\n Recent logs:')
230
+ for (const line of status.recentLogs) {
231
+ console.log(' ' + line)
232
+ }
233
+ }
234
+
235
+ console.log('')
236
+ })
237
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * chroxy sessions / chroxy resume — Session management commands
3
+ */
4
+ import { existsSync, readFileSync } from 'fs'
5
+ import { join } from 'path'
6
+ import { CONFIG_DIR } from './shared.js'
7
+
8
+ export function registerSessionCommands(program) {
9
+ program
10
+ .command('sessions')
11
+ .description('List saved sessions with conversation IDs for terminal handoff')
12
+ .action(() => {
13
+ const stateFile = join(CONFIG_DIR, 'session-state.json')
14
+
15
+ if (!existsSync(stateFile)) {
16
+ console.log('\nNo saved sessions found.')
17
+ console.log('Sessions are saved when the server runs.\n')
18
+ process.exit(0)
19
+ }
20
+
21
+ let state
22
+ try {
23
+ state = JSON.parse(readFileSync(stateFile, 'utf-8'))
24
+ } catch (err) {
25
+ console.error(`Failed to read session state: ${err.message}`)
26
+ process.exit(1)
27
+ }
28
+
29
+ if (!Array.isArray(state.sessions) || state.sessions.length === 0) {
30
+ console.log('\nNo saved sessions.\n')
31
+ process.exit(0)
32
+ }
33
+
34
+ console.log(`\nSaved Sessions (${state.sessions.length})\n`)
35
+
36
+ for (const session of state.sessions) {
37
+ const convId = session.conversationId || session.sdkSessionId || null
38
+ console.log(` ${session.name}`)
39
+ console.log(` cwd: ${session.cwd}`)
40
+ if (convId) {
41
+ console.log(` conversation: ${convId}`)
42
+ console.log(` resume: claude --resume ${convId}`)
43
+ } else {
44
+ console.log(` conversation: (none — no messages sent yet)`)
45
+ }
46
+ console.log('')
47
+ }
48
+
49
+ if (state.timestamp) {
50
+ const age = Math.round((Date.now() - state.timestamp) / 60000)
51
+ console.log(` Last saved: ${age} minute(s) ago\n`)
52
+ }
53
+ })
54
+
55
+ program
56
+ .command('resume')
57
+ .description('Resume a Chroxy session in your terminal')
58
+ .argument('[session]', 'Session name or number (default: most recent)')
59
+ .option('--dangerously-skip-permissions', 'Pass --dangerously-skip-permissions to claude')
60
+ .action(async (sessionArg, options) => {
61
+ const { execFileSync } = await import('child_process')
62
+ const stateFile = join(CONFIG_DIR, 'session-state.json')
63
+
64
+ if (!existsSync(stateFile)) {
65
+ console.error('No saved sessions found. Start the server first.')
66
+ process.exit(1)
67
+ }
68
+
69
+ let state
70
+ try {
71
+ state = JSON.parse(readFileSync(stateFile, 'utf-8'))
72
+ } catch (err) {
73
+ console.error(`Failed to read session state: ${err.message}`)
74
+ process.exit(1)
75
+ }
76
+
77
+ if (!Array.isArray(state.sessions) || state.sessions.length === 0) {
78
+ console.error('No saved sessions.')
79
+ process.exit(1)
80
+ }
81
+
82
+ const resumable = state.sessions
83
+ .map((s, i) => ({ ...s, index: i, convId: s.conversationId || s.sdkSessionId }))
84
+ .filter(s => s.convId)
85
+
86
+ if (resumable.length === 0) {
87
+ console.error('No sessions have conversation IDs yet. Send a message first.')
88
+ process.exit(1)
89
+ }
90
+
91
+ let target
92
+ if (sessionArg) {
93
+ const num = parseInt(sessionArg, 10)
94
+ if (!isNaN(num) && num >= 1 && num <= resumable.length) {
95
+ target = resumable[num - 1]
96
+ } else {
97
+ target = resumable.find(s => s.name.toLowerCase() === sessionArg.toLowerCase())
98
+ }
99
+ if (!target) {
100
+ console.error(`Session "${sessionArg}" not found. Available:`)
101
+ resumable.forEach((s, i) => console.error(` ${i + 1}. ${s.name}`))
102
+ process.exit(1)
103
+ }
104
+ } else if (resumable.length === 1) {
105
+ target = resumable[0]
106
+ } else {
107
+ const readline = await import('readline')
108
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
109
+ console.log('\nAvailable sessions:\n')
110
+ resumable.forEach((s, i) => {
111
+ console.log(` ${i + 1}. ${s.name} (${s.cwd})`)
112
+ })
113
+ const answer = await new Promise(resolve => {
114
+ rl.question(`\nPick session [1]: `, resolve)
115
+ })
116
+ rl.close()
117
+ const pick = parseInt(answer, 10) || 1
118
+ if (pick < 1 || pick > resumable.length) {
119
+ console.error('Invalid selection.')
120
+ process.exit(1)
121
+ }
122
+ target = resumable[pick - 1]
123
+ }
124
+
125
+ console.log(`\nResuming "${target.name}" in ${target.cwd}`)
126
+ console.log(`Conversation: ${target.convId}\n`)
127
+
128
+ const args = ['--resume', target.convId]
129
+ if (options.dangerouslySkipPermissions) {
130
+ args.push('--dangerously-skip-permissions')
131
+ }
132
+
133
+ try {
134
+ execFileSync('claude', args, {
135
+ stdio: 'inherit',
136
+ cwd: target.cwd,
137
+ })
138
+ } catch (err) {
139
+ if (err.status != null) process.exit(err.status)
140
+ throw err
141
+ }
142
+ })
143
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Shared CLI utilities and option definitions.
3
+ *
4
+ * Dependency root for all CLI command modules — provides shared options,
5
+ * config loading, and helper functions.
6
+ */
7
+ import { existsSync, readFileSync } from 'fs'
8
+ import { join } from 'path'
9
+ import { homedir } from 'os'
10
+ import readline from 'readline'
11
+ import { validateConfig, mergeConfig, isFatalConfigWarning } from '../config.js'
12
+
13
+ export const CONFIG_DIR = join(homedir(), '.chroxy')
14
+ export const CONFIG_FILE = join(CONFIG_DIR, 'config.json')
15
+
16
+ /**
17
+ * Interactive prompt helper
18
+ */
19
+ export function prompt(question) {
20
+ const rl = readline.createInterface({
21
+ input: process.stdin,
22
+ output: process.stdout,
23
+ })
24
+ return new Promise((resolve) => {
25
+ rl.question(question, (answer) => {
26
+ rl.close()
27
+ resolve(answer.trim())
28
+ })
29
+ })
30
+ }
31
+
32
+ /**
33
+ * Add shared server options to a Commander command.
34
+ * Used by both `start` and `dev` commands.
35
+ */
36
+ export function addServerOptions(cmd) {
37
+ return cmd
38
+ .option('-c, --config <path>', 'Path to config file', CONFIG_FILE)
39
+ .option('--host <address>', 'Bind address (default: 0.0.0.0; use 127.0.0.1 for loopback-only). Auth stays enabled.')
40
+ .option('--cwd <path>', 'Working directory for Claude')
41
+ .option('--model <model>', 'Model to use')
42
+ .option('--allowed-tools <tools>', 'Comma-separated tools to auto-approve')
43
+ .option('--max-restarts <count>', 'Max supervisor restart attempts before exit (default: 10)')
44
+ .option('--tunnel <mode>', 'Tunnel: quick (default), named, none, or provider:mode (e.g., cloudflare:named)')
45
+ .option('--tunnel-name <name>', 'Named tunnel name (requires cloudflared login)')
46
+ .option('--tunnel-hostname <host>', 'Named tunnel hostname (e.g., chroxy.example.com)')
47
+ .option('--legacy-cli', 'Use legacy CLI process mode instead of Agent SDK')
48
+ .option('--provider <name>', 'Session provider to use (e.g. claude-sdk, claude-cli)')
49
+ .option('--max-messages <count>', 'Max messages retained per session (FIFO eviction, default: 1000)')
50
+ .option('--max-payload <bytes>', 'WebSocket max message size in bytes (default: 1048576)')
51
+ .option('--max-tool-input <bytes>', 'Maximum tool input size in bytes (default: 262144)')
52
+ .option('--session-timeout <duration>', 'Idle session timeout (e.g. 2h, 30m). Disabled by default')
53
+ .option('--cost-budget <dollars>', 'Per-session cost budget in dollars (e.g., 5.00)')
54
+ .option('--log-format <format>', 'Log output format: text (default) or json')
55
+ .option('--dangerously-skip-permissions', 'TUI provider only: spawn claude with --dangerously-skip-permissions and disable chroxy permission gating (mirrors `chroxy resume` flag)')
56
+ .option('-v, --verbose', 'Show detailed config sources and validation info')
57
+ .option('--environments', 'Enable environment isolation providers (e.g. docker)')
58
+ .option('--environment-backend <backend>', 'Environment backend: docker (default), k8s, or rancher')
59
+ }
60
+
61
+ /**
62
+ * Parse extra overrides from common CLI option values.
63
+ */
64
+ export function parseExtraOverrides(options) {
65
+ const extra = {}
66
+ if (options.maxMessages !== undefined) {
67
+ const parsed = parseInt(options.maxMessages, 10)
68
+ extra.maxMessages = Number.isNaN(parsed) ? options.maxMessages : parsed
69
+ }
70
+ if (options.maxPayload !== undefined) {
71
+ const parsed = parseInt(options.maxPayload, 10)
72
+ extra.maxPayload = Number.isNaN(parsed) ? options.maxPayload : parsed
73
+ }
74
+ if (options.maxToolInput !== undefined) {
75
+ const parsed = parseInt(options.maxToolInput, 10)
76
+ extra.maxToolInput = Number.isNaN(parsed) ? options.maxToolInput : parsed
77
+ }
78
+ if (options.costBudget !== undefined) {
79
+ const parsed = parseFloat(options.costBudget)
80
+ extra.costBudget = Number.isNaN(parsed) ? options.costBudget : parsed
81
+ }
82
+ if (options.sessionTimeout !== undefined) extra.sessionTimeout = options.sessionTimeout
83
+ return extra
84
+ }
85
+
86
+ /**
87
+ * Load config file, build CLI overrides, merge, validate, and set env vars.
88
+ *
89
+ * @param {object} options - Commander options object
90
+ * @param {object} [extraOverrides] - Additional CLI overrides
91
+ * @returns {object} Merged and validated config
92
+ */
93
+ export function loadAndMergeConfig(options, extraOverrides = {}) {
94
+ let fileConfig = {}
95
+ if (existsSync(options.config)) {
96
+ try {
97
+ fileConfig = JSON.parse(readFileSync(options.config, 'utf-8'))
98
+ } catch (err) {
99
+ if (err instanceof SyntaxError) {
100
+ console.error(`❌ Config file contains invalid JSON: ${options.config}`)
101
+ console.error(` ${err.message}`)
102
+ console.error(` Fix the file or delete it and run 'npx chroxy init' to recreate.`)
103
+ process.exit(1)
104
+ }
105
+ throw err
106
+ }
107
+ } else if (options.config !== CONFIG_FILE) {
108
+ console.error(`❌ Config file not found: ${options.config}`)
109
+ process.exit(1)
110
+ } else {
111
+ console.error('❌ No config found. Run \'npx chroxy init\' first.')
112
+ process.exit(1)
113
+ }
114
+
115
+ validateConfig(fileConfig, options.verbose)
116
+
117
+ const cliOverrides = { ...extraOverrides }
118
+ if (options.host !== undefined) cliOverrides.host = options.host
119
+ if (options.cwd !== undefined) cliOverrides.cwd = options.cwd
120
+ if (options.model !== undefined) cliOverrides.model = options.model
121
+ if (options.allowedTools !== undefined) {
122
+ cliOverrides.allowedTools = options.allowedTools.split(',').map((t) => t.trim())
123
+ }
124
+ if (options.maxRestarts !== undefined) {
125
+ cliOverrides.maxRestarts = parseInt(options.maxRestarts, 10)
126
+ }
127
+ if (options.tunnel !== undefined) cliOverrides.tunnel = options.tunnel
128
+ if (options.tunnelName !== undefined) cliOverrides.tunnelName = options.tunnelName
129
+ if (options.tunnelHostname !== undefined) cliOverrides.tunnelHostname = options.tunnelHostname
130
+ if (options.legacyCli) cliOverrides.legacyCli = true
131
+ if (options.provider !== undefined) cliOverrides.provider = options.provider
132
+ if (options.logFormat !== undefined) cliOverrides.logFormat = options.logFormat
133
+ // #5144: the `environments` key is an object whose sub-blocks (k8s, rancher,
134
+ // workspace) normally live in the config file. mergeConfig replaces a whole
135
+ // top-level key on CLI override, so a naive `cliOverrides.environments =
136
+ // { enabled: true }` would WIPE a file-configured k8s/rancher block. Layer
137
+ // the CLI-supplied environment sub-fields over a shallow copy of the file's
138
+ // block instead, so `--environments` / `--environment-backend` compose with
139
+ // file config rather than clobbering it.
140
+ const fileEnv = (fileConfig.environments && typeof fileConfig.environments === 'object' && !Array.isArray(fileConfig.environments))
141
+ ? fileConfig.environments
142
+ : {}
143
+ let envOverride = null
144
+ if (options.environments) {
145
+ envOverride = { ...fileEnv, enabled: true }
146
+ }
147
+ if (options.environmentBackend !== undefined) {
148
+ envOverride = { ...(envOverride || fileEnv), backend: options.environmentBackend }
149
+ }
150
+ if (envOverride) cliOverrides.environments = envOverride
151
+ // #4209 / #4246: only forward when the flag was explicitly passed.
152
+ // Commander sets the property to `true` when present and leaves it
153
+ // `undefined` when absent, so we never write a coerced `false` that
154
+ // would mask a pre-existing `dangerouslySkipPermissions: true` (or
155
+ // legacy `skipPermissions: true`) in the on-disk config file.
156
+ //
157
+ // #4246 — forward as the canonical `dangerouslySkipPermissions`
158
+ // key. The legacy `skipPermissions` key is still read by
159
+ // `resolveSkipPermissions()` for backwards compatibility with
160
+ // existing config.json files.
161
+ if (options.dangerouslySkipPermissions) cliOverrides.dangerouslySkipPermissions = true
162
+
163
+ const defaults = {
164
+ port: 8765,
165
+ noAuth: false,
166
+ }
167
+
168
+ const config = mergeConfig({
169
+ fileConfig,
170
+ cliOverrides,
171
+ defaults,
172
+ verbose: options.verbose,
173
+ })
174
+
175
+ const validation = validateConfig(config, options.verbose)
176
+ if (!validation.valid) {
177
+ // Fatality comes from the single policy in config.js (isFatalConfigWarning),
178
+ // not an inlined string match here — see audit P1-9.
179
+ const typeErrors = validation.warnings.filter(isFatalConfigWarning)
180
+ if (typeErrors.length > 0) {
181
+ console.error('❌ Configuration has type errors:')
182
+ for (const err of typeErrors) {
183
+ console.error(` ${err}`)
184
+ }
185
+ console.error(' Fix your config file or CLI flags and try again.')
186
+ process.exit(1)
187
+ }
188
+ }
189
+
190
+ if (config.apiToken) process.env.API_TOKEN = config.apiToken
191
+ if (config.port) process.env.PORT = String(config.port)
192
+
193
+ return config
194
+ }