@chroxy/server 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @chroxy/server
2
+
3
+ Node.js daemon that bridges your phone to Claude Code via WebSocket over Cloudflare tunnel.
4
+
5
+ The server runs in **CLI headless mode**: it executes the Claude Agent SDK in-process by default, or shells out to `claude -p`, `gemini -p`, or `codex exec` for the other providers, and streams parsed events to clients. No tmux, no PTY.
6
+
7
+ ## Quick Start
8
+
9
+ ```bash
10
+ # Initialize configuration
11
+ PATH="/opt/homebrew/opt/node@22/bin:$PATH" npx chroxy init
12
+
13
+ # Start the server
14
+ PATH="/opt/homebrew/opt/node@22/bin:$PATH" npx chroxy start
15
+ ```
16
+
17
+ The server will print a QR code. Scan it with the Chroxy app.
18
+
19
+ ## CLI Commands
20
+
21
+ | Command | Description |
22
+ |---------|-------------|
23
+ | `chroxy init` | Interactive setup — generates API token and config file |
24
+ | `chroxy start` | Start server (default: Quick Tunnel) |
25
+ | `chroxy start --tunnel named` | Use a named tunnel for stable URLs (requires Cloudflare account) |
26
+ | `chroxy start --tunnel cloudflare:named` | Explicit provider:mode syntax |
27
+ | `chroxy start --tunnel none` | Disable tunnel (local only) |
28
+ | `chroxy start --no-auth` | Start without authentication (localhost only) |
29
+ | `chroxy start --no-supervisor` | Disable supervisor auto-restart (named tunnel mode) |
30
+ | `chroxy start --config /path` | Use a specific config file |
31
+ | `chroxy start --cwd /path` | Set working directory |
32
+ | `chroxy start --model opus` | Use a specific Claude model |
33
+ | `chroxy start --allowed-tools tool1,tool2` | Restrict exposed tools |
34
+ | `chroxy start --provider name` | Use a specific session provider (default: `claude-tui`) |
35
+ | `chroxy start --no-encrypt` | Disable end-to-end encryption |
36
+ | `chroxy dev` | Development mode (supervisor + auto-restart) |
37
+ | `chroxy deploy` | Validate and restart the running server |
38
+ | `chroxy config` | Show current configuration |
39
+ | `chroxy doctor` | Check dependencies and environment |
40
+ | `chroxy sessions` | List saved sessions with conversation IDs |
41
+ | `chroxy resume [session]` | Resume a Chroxy session in your terminal |
42
+ | `chroxy tunnel setup` | Interactive named tunnel setup (default: Cloudflare) |
43
+ | `chroxy tunnel setup --provider <name>` | Setup a specific tunnel provider |
44
+
45
+ ## Architecture
46
+
47
+ ```
48
+ ┌─────────────────────────────────────────────────────┐
49
+ │ cli.js │
50
+ │ (entry point — Commander, src/cli/*) │
51
+ └─────────────────────┬───────────────────────────────┘
52
+ │
53
+ ┌─────────────┼─────────────┐
54
+ ▼ ▼ ▼
55
+ ┌───────────────┐ ┌───────────┐ ┌───────────────┐
56
+ │ server-cli.js │ │ ws-server │ │ tunnel/ │
57
+ │ │ │ │ │ │
58
+ │ Orchestrates │ │ WebSocket │ │ cloudflared │
59
+ │ sessions via │ │ + auth │ │ management │
60
+ │ providers.js │ └───────────┘ └───────────────┘
61
+ └───────┬───────┘
62
+ │
63
+ ▼
64
+ ┌───────────────┐
65
+ │sdk-session.js │ (default — Claude Agent SDK)
66
+ │cli-session.js │ (legacy claude -p)
67
+ │gemini-session │ (Google Gemini)
68
+ │codex-session │ (OpenAI Codex)
69
+ │docker-session │ (containerized — opt-in)
70
+ └───────────────┘
71
+ ```
72
+
73
+ ## Key Components
74
+
75
+ | Component | File | Purpose |
76
+ |-----------|------|---------|
77
+ | ProviderRegistry | `providers.js` | Provider adapter interface + built-in registrations |
78
+ | SdkSession | `sdk-session.js` | Claude Agent SDK executor (default provider) |
79
+ | CliSession | `cli-session.js` | Legacy headless executor via `claude -p` |
80
+ | GeminiSession | `gemini-session.js` | Google Gemini CLI executor |
81
+ | CodexSession | `codex-session.js` | OpenAI Codex CLI executor |
82
+ | SessionManager | `session-manager.js` | Multi-session lifecycle management |
83
+ | WsServer | `ws-server.js` | WebSocket protocol with auth + encryption |
84
+ | Tunnel wiring | `tunnel/index.js` | `parseTunnelArg` + Cloudflare adapter selection |
85
+ | BaseTunnelAdapter | `tunnel/base.js` | Base class with shared recovery logic |
86
+ | CloudflareTunnelAdapter | `tunnel/cloudflare.js` | Cloudflare adapter (quick/named modes) |
87
+ | Supervisor | `supervisor.js` | Tunnel owner + child auto-restart (named tunnel) |
88
+ | PushManager | `push.js` | Push notifications via Expo Push API |
89
+
90
+ ## Development
91
+
92
+ ```bash
93
+ # Run with auto-reload
94
+ PATH="/opt/homebrew/opt/node@22/bin:$PATH" npm run dev
95
+
96
+ # Run tests (700+ tests)
97
+ PATH="/opt/homebrew/opt/node@22/bin:$PATH" npm test
98
+
99
+ # Test with the CLI client
100
+ node src/test-client.js wss://your-cloudflare-url
101
+ ```
102
+
103
+ ## WebSocket Protocol
104
+
105
+ See the main [README](../../README.md) for protocol details, or the header comment in `src/ws-server.js` for the full message type reference.
@@ -0,0 +1,285 @@
1
+ #!/bin/bash
2
+ # Chroxy permission hook — bridges Claude Code permission requests to the mobile app.
3
+ #
4
+ # Claude Code calls this via its hooks system (PreToolUse event). The script:
5
+ # 1. Checks if this is a Chroxy-spawned session (CHROXY_PORT env var present)
6
+ # 2. Reads the hook input JSON from stdin (contains tool_name, tool_input, etc.)
7
+ # 3. POSTs it to the Chroxy HTTP server with per-session hook secret auth
8
+ # (long-poll, blocks until user responds). CHROXY_HOOK_SECRET is a short-lived
9
+ # random secret specific to this session — never the primary API token.
10
+ # 4. Translates the response into Claude Code's hookSpecificOutput format
11
+ #
12
+ # Non-Chroxy Claude sessions don't have CHROXY_PORT set, so the hook immediately
13
+ # falls through to Claude's normal permission prompt.
14
+ #
15
+ # SECURITY: All tool parameters arrive via stdin as JSON (never as shell arguments).
16
+ # Claude Code's hooks mechanism always passes hook data through stdin, not positional
17
+ # args. Do NOT use $1/$2/etc for tool parameters — they are untrusted and could
18
+ # contain shell metacharacters that execute arbitrary commands.
19
+
20
+ # If CHROXY_PORT is not set, this isn't a Chroxy session — exit silently
21
+ # so Claude Code uses its normal permission flow without showing a hook prompt.
22
+ if [ -z "$CHROXY_PORT" ]; then
23
+ exit 0
24
+ fi
25
+
26
+ PORT="$CHROXY_PORT"
27
+ TOKEN="$CHROXY_HOOK_SECRET"
28
+ # Permission mode resolution order:
29
+ # 1. CHROXY_PERMISSION_MODE_FILE — if set AND readable AND non-empty.
30
+ # ClaudeTuiSession writes this sidecar file when setPermissionMode()
31
+ # is called mid-session, since env vars on a running PTY can't be
32
+ # mutated from outside (#4013).
33
+ # 2. CHROXY_PERMISSION_MODE env var — the value at session-spawn time.
34
+ # Used by CliSession (which restarts on mode change) and as the
35
+ # initial value for TUI sessions.
36
+ # 3. "approve" — default if nothing else is set.
37
+ PERM_MODE=""
38
+ if [ -n "$CHROXY_PERMISSION_MODE_FILE" ] && [ -r "$CHROXY_PERMISSION_MODE_FILE" ]; then
39
+ PERM_MODE=$(tr -d '[:space:]' < "$CHROXY_PERMISSION_MODE_FILE" 2>/dev/null)
40
+ fi
41
+ if [ -z "$PERM_MODE" ]; then
42
+ PERM_MODE="${CHROXY_PERMISSION_MODE:-approve}"
43
+ fi
44
+
45
+ # Sanitize: PORT must be numeric
46
+ case "$PORT" in
47
+ ''|*[!0-9]*) exit 0 ;;
48
+ esac
49
+
50
+ # Sanitize: PERM_MODE must be a known value
51
+ case "$PERM_MODE" in
52
+ approve|auto|acceptEdits|plan) ;;
53
+ *) PERM_MODE="approve" ;;
54
+ esac
55
+
56
+ # #4648 (v0.9.24): refuse multi-question AskUserQuestion forms before any
57
+ # mode-specific routing. Chroxy's PTY-keystroke driver for multi-question
58
+ # forms has a 0% production success rate (per chroxy.log forensic, 2026-05-31
59
+ # /swarm-audit consensus). Denying here forces the model to re-emit as N
60
+ # sequential single-question calls, each driven by the empirically-validated
61
+ # single-question happy path that has worked since v0.9.4. Defense in depth:
62
+ # the v0.9.23 _onAskUserQuestionStall teardown still catches anything that
63
+ # slips through. See docs/audit-results/tui-form-delivery-rethink/ for the
64
+ # full audit (6 agents, unanimous on this path).
65
+ #
66
+ # Reads stdin once at the top because the deny check must apply regardless
67
+ # of permission mode — auto/plan modes previously exited early without
68
+ # touching the payload. Modes below that need the payload reuse $REQUEST.
69
+ REQUEST=$(cat -)
70
+ TOOL_NAME=$(echo "$REQUEST" | grep -o '"tool_name":"[^"]*"' | head -1 | cut -d'"' -f4)
71
+ if [ "$TOOL_NAME" = "AskUserQuestion" ]; then
72
+ # Parse `questions[]` length AND whether any question is multiSelect via
73
+ # python3 (stock macOS has it at /usr/bin/python3 3.9.6; Homebrew at
74
+ # /opt/homebrew/bin). On parse failure or python3 absence we get empty
75
+ # output → fall through to normal handling rather than crash/deny-everything.
76
+ # Worst case: same as today (the v0.9.23 watchdog + the form-driver multiSelect
77
+ # guard catch the wedge), so this defaults safe.
78
+ #
79
+ # #5771: deny single-question multiSelect too. claude TUI is keyboard-only and
80
+ # has no reliable multi-toggle+submit keystroke sequence (0/7 production
81
+ # success — swarm audit 2026-06-13). Single-select single-questions stay on the
82
+ # empirically-validated happy path; everything multiSelect is refused here so
83
+ # the model decomposes into single-select asks. Output is "<count> <hasMulti>".
84
+ PARSED=$(printf '%s' "$REQUEST" | python3 -c '
85
+ import sys, json
86
+ try:
87
+ d = json.load(sys.stdin)
88
+ q = d.get("tool_input", {}).get("questions", [])
89
+ if not isinstance(q, list):
90
+ q = []
91
+ has_multi = 1 if any(isinstance(x, dict) and x.get("multiSelect") is True for x in q) else 0
92
+ print(f"{len(q)} {has_multi}")
93
+ except Exception:
94
+ pass
95
+ ' 2>/dev/null)
96
+ QUESTION_COUNT=$(printf '%s' "$PARSED" | cut -d' ' -f1)
97
+ HAS_MULTISELECT=$(printf '%s' "$PARSED" | cut -d' ' -f2)
98
+ if [ -n "$QUESTION_COUNT" ] && [ "$QUESTION_COUNT" -gt 1 ]; then
99
+ cat <<'EOF'
100
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Chroxy currently delivers AskUserQuestion forms one question at a time. Please re-issue this call as separate AskUserQuestion tool calls, ONE AT A TIME — issue the next one only after the previous one's tool_result has been returned. Do NOT issue multiple AskUserQuestion tool_use blocks in parallel within the same assistant turn."}}
101
+ EOF
102
+ exit 0
103
+ fi
104
+ if [ "$QUESTION_COUNT" = "1" ] && [ "$HAS_MULTISELECT" = "1" ]; then
105
+ # #5776 (Phase 0) — when the multi-select reinject spike is enabled, the
106
+ # Chroxy client renders the multi-select form itself and delivers the user's
107
+ # selection as a follow-up message. Steer the model to STOP and wait for that
108
+ # message rather than decompose into single-select asks. Still a deny (that is
109
+ # what suppresses claude TUI's own un-drivable form); only the reason differs.
110
+ if [ "$CHROXY_TUI_MULTISELECT_REINJECT" = "1" ]; then
111
+ cat <<'EOF'
112
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"The Chroxy client is collecting this multi-select choice from the user directly. Do NOT re-ask, do NOT decompose into single-select questions, and do NOT call any further tools. Stop here — the user's selection will arrive as your next user message; continue from it then."}}
113
+ EOF
114
+ exit 0
115
+ fi
116
+ cat <<'EOF'
117
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Chroxy's TUI provider does not support multi-select questions (multiSelect:true). Re-issue this as a single-select question (multiSelect:false), or — if the user genuinely needs to choose several items — ask one single-select AskUserQuestion per item (e.g. an include/skip choice for each), ONE AT A TIME, issuing the next only after the previous tool_result returns."}}
118
+ EOF
119
+ exit 0
120
+ fi
121
+
122
+ # #4668 (short-term): deny when another AskUserQuestion is already pending
123
+ # in this session. The model interprets #4648's "separate AskUserQuestion
124
+ # tool calls" as "parallel within the same turn" — empirically, claude TUI
125
+ # was emitting 4 parallel AskUserQuestion tool_use blocks in one turn,
126
+ # which overwrote chroxy's single `_pendingUserAnswer` field and routed all
127
+ # user answers to the wrong question (chroxy.log forensic 2026-05-31 on
128
+ # v0.9.26 session 9ea82aed). Forcing true serialization at the hook layer
129
+ # restores the single-pending invariant that the existing keystroke driver
130
+ # was built around. The PostToolUse hook in writeHookSettings()
131
+ # (claude-tui-session.js) clears this lock when the active AskUserQuestion
132
+ # completes, so sequential AskUserQuestions are unaffected.
133
+ #
134
+ # mkdir IS the atomic claim — not a follow-up to a separate existence
135
+ # check. POSIX guarantees mkdir is atomic across concurrent processes: at
136
+ # most one caller per parent directory wins; the rest see EEXIST. Pre-v1
137
+ # of this fix used `if [ -d "$LOCK" ]; then deny; else mkdir; fi` which
138
+ # is TOCTOU-broken: parallel hooks (chroxy's exact case — 4 AskUserQuestion
139
+ # hooks firing within milliseconds) can all observe "not exists" before
140
+ # any of them mkdir. The mkdir-first structure here eliminates that
141
+ # window: the race-winner gets through, every other caller sees the dir
142
+ # already there and falls into the stale-check / deny branch.
143
+ if [ -n "$CHROXY_SINK_DIR" ] && [ -d "$CHROXY_SINK_DIR" ]; then
144
+ SIBLING_LOCK="${CHROXY_SINK_DIR}/askuserquestion-active"
145
+ if ! mkdir "$SIBLING_LOCK" 2>/dev/null; then
146
+ # mkdir failed because the dir already exists (EEXIST — the only
147
+ # plausible cause once CHROXY_SINK_DIR is verified writable above).
148
+ # Inspect the existing lock's age to decide: fresh sibling (deny) or
149
+ # stale leftover (reclaim).
150
+ #
151
+ # stat flag portability: macOS uses BSD stat (-f %m, mtime as epoch
152
+ # seconds); Linux uses GNU stat (-c %Y). The platform branch keeps
153
+ # the wrong invocation from succeeding accidentally — GNU stat -f
154
+ # silently switches to filesystem-info mode and returns a mount-point
155
+ # string, which then breaks the arithmetic below (assigns LOCK_AGE
156
+ # to empty → the [ -lt 60 ] check evaluates falsy → would skip the
157
+ # deny path and bypass the fix entirely on Linux CI).
158
+ case "$(uname -s)" in
159
+ Darwin) LOCK_MTIME=$(stat -f %m "$SIBLING_LOCK" 2>/dev/null) ;;
160
+ *) LOCK_MTIME=$(stat -c %Y "$SIBLING_LOCK" 2>/dev/null) ;;
161
+ esac
162
+ LOCK_AGE=$(($(date +%s) - ${LOCK_MTIME:-0}))
163
+ if [ "$LOCK_AGE" -ge 0 ] && [ "$LOCK_AGE" -lt 60 ]; then
164
+ cat <<'EOF'
165
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Another AskUserQuestion is already pending in this session. Wait for the user's answer (tool_result) before issuing the next AskUserQuestion. Do NOT issue multiple AskUserQuestion tool_use blocks in parallel within the same assistant turn — chroxy delivers them serially."}}
166
+ EOF
167
+ exit 0
168
+ fi
169
+ # Stale lock (>60s old OR mtime unreadable — LOCK_MTIME defaulted to
170
+ # 0 so LOCK_AGE ≈ epoch seconds, well past 60 → treated as stale and
171
+ # reclaimed; explicit "fall back to reclaim" semantics for the
172
+ # belt-and-suspenders case where stat fails for an unexpected reason).
173
+ # Reclaim by removing + recreating so mtime resets and our new claim
174
+ # is the active sibling. If a concurrent hook also detected staleness
175
+ # and reclaimed first, our mkdir fails — deny ourselves so we don't
176
+ # bypass the single-pending invariant the recovery is trying to
177
+ # preserve.
178
+ rm -rf "$SIBLING_LOCK" 2>/dev/null
179
+ if ! mkdir "$SIBLING_LOCK" 2>/dev/null; then
180
+ cat <<'EOF'
181
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Another AskUserQuestion is already pending in this session. Wait for the user's answer (tool_result) before issuing the next AskUserQuestion. Do NOT issue multiple AskUserQuestion tool_use blocks in parallel within the same assistant turn — chroxy delivers them serially."}}
182
+ EOF
183
+ exit 0
184
+ fi
185
+ fi
186
+ fi
187
+ fi
188
+
189
+ # #5330: fallback decision when chroxy cannot obtain an explicit user decision
190
+ # (the daemon is unreachable, or the response is unparseable). The OLD behavior
191
+ # emitted permissionDecision:"ask", which makes claude prompt at the PTY — but
192
+ # in chroxy's model the user is on their phone, not at the keyboard, so "ask"
193
+ # wedges the session on a dialog no one can answer. Default to "deny" (fail
194
+ # closed): the tool is blocked with a reason claude can report/recover from,
195
+ # instead of an indefinite hang. Set CHROXY_HOOK_UNREACHABLE_DECISION=ask to
196
+ # restore the old behavior for a local-at-the-PTY setup.
197
+ FALLBACK_DECISION="${CHROXY_HOOK_UNREACHABLE_DECISION:-deny}"
198
+ case "$FALLBACK_DECISION" in
199
+ ask|deny) ;;
200
+ *) FALLBACK_DECISION="deny" ;;
201
+ esac
202
+
203
+ # Emit the fail-closed fallback ($1 = static reason string, no quotes/backslashes
204
+ # so it stays valid JSON) and exit.
205
+ emit_unreachable_fallback() {
206
+ if [ "$FALLBACK_DECISION" = "ask" ]; then
207
+ printf '%s\n' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask"}}'
208
+ else
209
+ printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"%s"}}\n' "$1"
210
+ fi
211
+ exit 0
212
+ }
213
+
214
+ # ---- Shared: route a permission request to the phone via HTTP ----
215
+ # Expects $REQUEST to contain the JSON body to POST.
216
+ # Outputs the appropriate hookSpecificOutput JSON and exits.
217
+ route_to_phone() {
218
+ CURL_ARGS=(-s -X POST "http://localhost:${PORT}/permission" -H "Content-Type: application/json" -d "$REQUEST" --max-time 300)
219
+ if [ -n "$TOKEN" ]; then
220
+ CURL_ARGS+=(-H "Authorization: Bearer ${TOKEN}")
221
+ fi
222
+
223
+ RESPONSE=$(curl "${CURL_ARGS[@]}")
224
+ EXIT_CODE=$?
225
+
226
+ if [ $EXIT_CODE -ne 0 ]; then
227
+ # Daemon unreachable / curl timeout — the request never reached the phone.
228
+ emit_unreachable_fallback "Chroxy could not reach the daemon to request your approval; the request never reached your phone. Failing closed (denied). Retry once Chroxy is reachable."
229
+ fi
230
+
231
+ DECISION=$(echo "$RESPONSE" | grep -o '"decision":"[^"]*"' | head -1 | cut -d'"' -f4)
232
+
233
+ case "$DECISION" in
234
+ allow|allowAlways)
235
+ cat <<EOF
236
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}
237
+ EOF
238
+ ;;
239
+ deny)
240
+ cat <<EOF
241
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Denied by user via Chroxy mobile app"}}
242
+ EOF
243
+ ;;
244
+ *)
245
+ # Reached the daemon but got no recognizable decision — also unanswerable
246
+ # at the PTY, so fail closed rather than wedge on "ask".
247
+ emit_unreachable_fallback "Chroxy received an unrecognized permission response from the daemon. Failing closed (denied)."
248
+ ;;
249
+ esac
250
+ exit 0
251
+ }
252
+
253
+ # Auto mode — allow everything without routing to the phone
254
+ if [ "$PERM_MODE" = "auto" ]; then
255
+ cat <<'EOF'
256
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}
257
+ EOF
258
+ exit 0
259
+ fi
260
+
261
+ # Accept Edits mode — auto-approve file operations, route everything else to phone
262
+ if [ "$PERM_MODE" = "acceptEdits" ]; then
263
+ # $REQUEST and $TOOL_NAME already populated at top of script (#4648).
264
+ case "$TOOL_NAME" in
265
+ Read|Write|Edit|NotebookEdit|Glob|Grep)
266
+ cat <<'EOF'
267
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}
268
+ EOF
269
+ exit 0 ;;
270
+ esac
271
+ # Non-file tool — route to phone
272
+ route_to_phone
273
+ fi
274
+
275
+ # Plan mode — let Claude handle permission (read-only self-restriction)
276
+ if [ "$PERM_MODE" = "plan" ]; then
277
+ cat <<'EOF'
278
+ {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask"}}
279
+ EOF
280
+ exit 0
281
+ fi
282
+
283
+ # Approve mode (default) — route to phone via HTTP
284
+ # $REQUEST already populated at top of script (#4648).
285
+ route_to_phone
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@chroxy/server",
3
+ "version": "0.10.0",
4
+ "description": "Chroxy server daemon and CLI",
5
+ "type": "module",
6
+ "main": "src/cli.js",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "!src/dashboard-next/node_modules",
13
+ "hooks",
14
+ "sidecar",
15
+ "!sidecar/node_modules",
16
+ "scripts/fix-node-pty-helper.js",
17
+ "CONFIG.md",
18
+ "README.md"
19
+ ],
20
+ "bin": {
21
+ "chroxy": "src/cli.js"
22
+ },
23
+ "scripts": {
24
+ "start": "node src/cli.js start",
25
+ "dev": "node --watch src/cli.js start",
26
+ "test": "node ./scripts/assert-test-count.mjs c8 node --import ./tests/_setup.mjs --experimental-test-module-mocks --test './tests/**/*.test.js'",
27
+ "test:raw": "c8 node --import ./tests/_setup.mjs --experimental-test-module-mocks --test './tests/**/*.test.js'",
28
+ "test:coverage": "c8 --reporter=text --reporter=html node --import ./tests/_setup.mjs --experimental-test-module-mocks --test './tests/**/*.test.js'",
29
+ "test:integration": "node --import ./tests/_setup.mjs --test ./tests/*.integration.test.js",
30
+ "test:integration:k8s": "RUN_K8S_INTEGRATION=1 node --import ./tests/_setup.mjs --test ./tests/integration/k8s-sidecar-roundtrip.test.js",
31
+ "lint": "eslint src/",
32
+ "prepack": "node scripts/copy-dashboard-dist.mjs",
33
+ "postinstall": "node scripts/fix-node-pty-helper.js"
34
+ },
35
+ "dependencies": {
36
+ "@anthropic-ai/claude-agent-sdk": "^0.2.0",
37
+ "@anthropic-ai/sdk": "^0.81.0",
38
+ "@chroxy/protocol": "0.10.0",
39
+ "@chroxy/store-core": "0.10.0",
40
+ "@kubernetes/client-node": "^1.4.0",
41
+ "@modelcontextprotocol/sdk": "^1.29.0",
42
+ "@xterm/addon-fit": "^0.10.0",
43
+ "@xterm/xterm": "^5.5.0",
44
+ "bonjour-service": "^1.3.0",
45
+ "commander": "^12.0.0",
46
+ "dotenv": "^16.3.0",
47
+ "node-pty": "^1.1.0",
48
+ "openai": "^6.0.0",
49
+ "qrcode": "^1.5.3",
50
+ "tweetnacl": "^1.0.3",
51
+ "tweetnacl-util": "^0.15.1",
52
+ "ws": "^8.16.0",
53
+ "zod": "^4.3.6"
54
+ },
55
+ "engines": {
56
+ "node": ">=22"
57
+ },
58
+ "repository": {
59
+ "type": "git",
60
+ "url": "git+https://github.com/blamechris/chroxy.git",
61
+ "directory": "packages/server"
62
+ },
63
+ "license": "MIT",
64
+ "devDependencies": {
65
+ "c8": "^11.0.0",
66
+ "eslint": "^9.39.3",
67
+ "playwright": "^1.58.2"
68
+ }
69
+ }
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ // node-pty 1.1.0 ships `prebuilds/<platform>/spawn-helper` without the
3
+ // executable bit. `pty.fork()` fails with "posix_spawnp failed." Apply +x
4
+ // at postinstall so the server can spawn child processes under a PTY.
5
+ //
6
+ // Idempotent: re-running just re-applies the bit. Safe to invoke from
7
+ // non-npm contexts.
8
+
9
+ import { existsSync, chmodSync, statSync } from 'fs'
10
+ import { dirname, join, resolve } from 'path'
11
+ import { fileURLToPath } from 'url'
12
+
13
+ const __dirname = dirname(fileURLToPath(import.meta.url))
14
+
15
+ // node-pty may be hoisted to the workspace root by npm. Walk up looking for it.
16
+ function findPrebuildsDir(start) {
17
+ let dir = start
18
+ while (dir !== dirname(dir)) {
19
+ const candidate = join(dir, 'node_modules', 'node-pty', 'prebuilds')
20
+ if (existsSync(candidate)) return candidate
21
+ dir = dirname(dir)
22
+ }
23
+ return null
24
+ }
25
+
26
+ const ptyDir = findPrebuildsDir(resolve(__dirname, '..'))
27
+
28
+ if (!ptyDir) {
29
+ process.exit(0)
30
+ }
31
+
32
+ const helpers = [
33
+ join(ptyDir, 'darwin-arm64', 'spawn-helper'),
34
+ join(ptyDir, 'darwin-x64', 'spawn-helper'),
35
+ join(ptyDir, 'linux-arm64', 'spawn-helper'),
36
+ join(ptyDir, 'linux-x64', 'spawn-helper'),
37
+ ]
38
+
39
+ for (const helper of helpers) {
40
+ if (!existsSync(helper)) continue
41
+ const mode = statSync(helper).mode
42
+ if ((mode & 0o111) === 0o111) continue
43
+ chmodSync(helper, mode | 0o111)
44
+ }
@@ -0,0 +1,40 @@
1
+ FROM node:22-slim
2
+
3
+ LABEL org.opencontainers.image.source=https://github.com/blamechris/chroxy
4
+
5
+ # Version of @anthropic-ai/claude-code to install globally. Pin to an exact
6
+ # version so image builds are reproducible. Override at build time with:
7
+ # docker build --build-arg CLAUDE_CODE_VERSION=x.y.z .
8
+ # Bump this ARG when upgrading claude-code; keep it in sync with the version
9
+ # used by the rest of the server package.
10
+ ARG CLAUDE_CODE_VERSION=2.1.128
11
+
12
+ # Install claude-code globally so the sidecar can spawn it when K8sBackend
13
+ # sends a spawn frame. This is the only external npm dependency the image
14
+ # needs at runtime; the rest (ws) lives in the sidecar package.json below.
15
+ RUN npm install -g @anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}
16
+
17
+ WORKDIR /app
18
+
19
+ # Copy package manifest + lockfile and install with `npm ci` so the build is
20
+ # fully reproducible from package-lock.json (no fresh resolution).
21
+ COPY package.json package-lock.json ./
22
+ RUN npm ci --omit=dev
23
+
24
+ COPY agent.js ./
25
+
26
+ # Give the unprivileged `node` user (already present in node:22-slim) ownership
27
+ # of /app, then drop root. K8s deployments commonly set
28
+ # `securityContext.runAsNonRoot: true`, which would refuse admission otherwise.
29
+ RUN chown -R node:node /app
30
+ USER node
31
+
32
+ # WS server port — matches the default in agent.js. K8sBackend connects here.
33
+ EXPOSE 7681
34
+
35
+ # Container-level health probe. K8s readinessProbe is the source of truth for
36
+ # pod readiness, but this lets `docker ps` and non-K8s runtimes see status too.
37
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
38
+ CMD node -e "fetch('http://127.0.0.1:7681/healthz').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"
39
+
40
+ ENTRYPOINT ["node", "/app/agent.js"]