@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,214 @@
1
+ /**
2
+ * MCPFleet orchestrates one MCPClient per configured MCP server (#4077).
3
+ *
4
+ * One fleet per BYOK session. Lazy: start() spawns all clients in parallel;
5
+ * destroy() kills all children, waiting up to KILL_GRACE_MS for SIGTERM then
6
+ * escalating to SIGKILL.
7
+ *
8
+ * Tools are surfaced flat with the chroxy mcp__<server>__<tool> namespace
9
+ * convention (matches `mcp-tools.js` parser). Dead servers contribute zero
10
+ * tools, so a crashed-then-restart-exhausted server cleanly disappears from
11
+ * the next turn's tool list.
12
+ */
13
+
14
+ import { MCPClient, MCP_STATES, DEFAULT_TOOL_CALL_TIMEOUT_MS } from './byok-mcp-client.js'
15
+ import {
16
+ loadTrustStore,
17
+ recordTrust,
18
+ isTrusted,
19
+ withTrustStoreLock,
20
+ defaultTrustStorePath,
21
+ } from './byok-mcp-trust.js'
22
+ import { MCP_PREFIX, parseMcpToolName } from './mcp-tools.js'
23
+
24
+ export const FLEET_KILL_GRACE_MS = 2000
25
+
26
+ // #4456: wall-clock cap on fleet.start() to bound the worst-case session-
27
+ // start latency on a misconfigured MCP server. The fleet awaits each
28
+ // client's first stable state (READY or DEAD); with the post-#4453 1/2/4s
29
+ // restart backoff a single broken server adds up to ~7s to session-start.
30
+ // At the cap, clients still in STARTING/RESTARTING contribute zero tools
31
+ // to the first turn but remain alive and will surface on subsequent turns
32
+ // (the fleet re-queries .tools per turn, so a late-arriving client lands
33
+ // naturally). 1500 ms is enough for a fast happy path (the common case
34
+ // completes in ~50–200 ms) without making the user feel the bad-config
35
+ // tax. Operators can override via the `startCapMs` constructor opt.
36
+ export const DEFAULT_FLEET_START_CAP_MS = 1500
37
+
38
+ // #4451: re-export under the legacy name from this module so existing
39
+ // callers (byok-session, tests) keep working. Canonical source is
40
+ // mcp-tools.js to prevent silent parser drift.
41
+ export const MCP_TOOL_PREFIX = MCP_PREFIX
42
+ export { parseMcpToolName }
43
+
44
+ function mcpToolName(serverName, toolName) {
45
+ return `${MCP_TOOL_PREFIX}${serverName}__${toolName}`
46
+ }
47
+
48
+ export class MCPFleet {
49
+ constructor(configs, opts = {}) {
50
+ // #4457: build a per-client trust gate when a PermissionManager is
51
+ // available. The gate consults the on-disk trust store first (zero
52
+ // user friction for tuples already trusted in a prior session); on
53
+ // a miss it asks the PermissionManager — emitting a prompt visible to
54
+ // the dashboard / mobile permission UI — and persists allow decisions
55
+ // to the store so the prompt only fires once per (name, command, args[0]).
56
+ //
57
+ // No PermissionManager → no gate → spawn behaves exactly as in #4077.
58
+ // This keeps the lifecycle module testable in isolation; integration
59
+ // (session passes its _permissions in) is wired in byok-session.
60
+ const permissionManager = opts.permissionManager || null
61
+ const trustStorePath = opts.trustStorePath // tests override; undefined falls through to default
62
+ // #4460: resolve the path eagerly so the per-path async mutex below
63
+ // can key on a stable value (withTrustStoreLock uses the path as the
64
+ // map key). Without this, undefined paths would all share a single
65
+ // chain — fine for the real default case but bug-magnet if any test
66
+ // ever called the constructor without setting trustStorePath.
67
+ const resolvedTrustPath = trustStorePath || defaultTrustStorePath()
68
+ // #4456: per-fleet wall-clock cap on start(). Same defensive guard
69
+ // pattern as resultTimeoutMs in byok-session: non-finite / non-positive
70
+ // values fall back to the module default. Setting opts.startCapMs to
71
+ // Infinity (legacy behavior — wait for full convergence) requires
72
+ // explicitly opting in below.
73
+ this._startCapMs =
74
+ Number.isFinite(opts.startCapMs) && opts.startCapMs > 0
75
+ ? opts.startCapMs
76
+ : DEFAULT_FLEET_START_CAP_MS
77
+ this._clients = configs.map((cfg) => {
78
+ const clientOpts = { ...opts }
79
+ if (permissionManager) {
80
+ clientOpts.trustGate = async () => {
81
+ // #4460: serialise the load→prompt→recordTrust sequence across
82
+ // all fleet clients that share this trust-store path. Without
83
+ // the lock, two concurrent gates can both observe an empty
84
+ // store, both prompt, both call recordTrust — and the last
85
+ // writer's snapshot (read at step 1, missing the other's
86
+ // entry) clobbers the first allow. The lock also surfaces
87
+ // prompts one at a time, which the dashboard / mobile UI
88
+ // already assumes (one modal at a time).
89
+ return withTrustStoreLock(resolvedTrustPath, async () => {
90
+ const store = loadTrustStore(resolvedTrustPath, { log: opts.log })
91
+ if (isTrusted(store, cfg)) return true
92
+ const allowed = await permissionManager.requestMcpTrust({
93
+ name: cfg.name,
94
+ command: cfg.command,
95
+ args: cfg.args,
96
+ envKeys: Object.keys(cfg.env || {}).sort(),
97
+ })
98
+ if (allowed) recordTrust(cfg, resolvedTrustPath)
99
+ return allowed
100
+ })
101
+ }
102
+ }
103
+ return new MCPClient(cfg, clientOpts)
104
+ })
105
+ }
106
+
107
+ get clients() { return this._clients }
108
+
109
+ /**
110
+ * Spawn every client and resolve when either (a) every client has reached
111
+ * a stable state (READY or DEAD), or (b) the wall-clock cap fires —
112
+ * whichever is first (#4456).
113
+ *
114
+ * Trade-off: a session with one broken MCP server (e.g. command-not-found
115
+ * from a deleted binary) used to wait the FULL ~7s restart budget on
116
+ * session start. With the cap, the user gets a ready session in ≤
117
+ * `startCapMs` ms even on broken configs; clients still in STARTING /
118
+ * RESTARTING at the cap contribute zero tools to the first turn but get
119
+ * picked up automatically on the next turn (byok-session re-queries
120
+ * `fleet.tools` per turn). A transiently-flaky server that would have
121
+ * recovered on attempt 2 also loses its first-turn contribution under
122
+ * the cap — that's the cost of bounding the worst case.
123
+ *
124
+ * The per-client `start()` promises are *not* dropped at the cap — they
125
+ * continue running in the background and update `client.state` as they
126
+ * settle. We just stop *awaiting* them so the caller can move on.
127
+ */
128
+ async start() {
129
+ const startPromises = this._clients.map((c) => c.start().catch(() => {}))
130
+ if (!Number.isFinite(this._startCapMs) || this._startCapMs <= 0) {
131
+ // Defensive — should be unreachable given the constructor guard, but
132
+ // an explicit Infinity opt-in would land here and we just wait.
133
+ await Promise.all(startPromises)
134
+ return
135
+ }
136
+ let capTimer = null
137
+ const capPromise = new Promise((resolve) => {
138
+ capTimer = setTimeout(resolve, this._startCapMs)
139
+ // Don't keep the event loop alive solely for this timer — if every
140
+ // client settles before the cap, the timer's still pending and would
141
+ // otherwise hold the process open.
142
+ if (typeof capTimer.unref === 'function') capTimer.unref()
143
+ })
144
+ try {
145
+ await Promise.race([Promise.all(startPromises), capPromise])
146
+ } finally {
147
+ if (capTimer) clearTimeout(capTimer)
148
+ }
149
+ }
150
+
151
+ get tools() {
152
+ const out = []
153
+ for (const client of this._clients) {
154
+ if (client.state !== MCP_STATES.READY) continue
155
+ for (const tool of client.tools) {
156
+ out.push({
157
+ ...tool,
158
+ name: mcpToolName(client.name, tool.name),
159
+ _mcpServer: client.name,
160
+ _mcpOriginalName: tool.name,
161
+ })
162
+ }
163
+ }
164
+ return out
165
+ }
166
+
167
+ /**
168
+ * Anthropic-shaped tool definitions for messages.stream({ tools }).
169
+ *
170
+ * MCP's tools/list returns { name, description, inputSchema } per tool.
171
+ * Anthropic's API wants { name, description, input_schema }. The rename
172
+ * happens here so byok-session can `[...BUILTIN_TOOLS, ...fleet.anthropicTools]`
173
+ * without knowing the MCP shape.
174
+ *
175
+ * Internal markers (_mcpServer, _mcpOriginalName) are stripped — they're
176
+ * useful inside chroxy for routing tool_use back to the right client (#4079)
177
+ * but the SDK would reject unknown keys.
178
+ *
179
+ * Dead servers (post-restart-exhaustion) contribute zero tools because
180
+ * `this.tools` already filters by READY state.
181
+ */
182
+ get anthropicTools() {
183
+ return this.tools.map((tool) => ({
184
+ name: tool.name,
185
+ description: tool.description || '',
186
+ input_schema: tool.inputSchema || { type: 'object' },
187
+ }))
188
+ }
189
+
190
+ /**
191
+ * Dispatch a tool_use to the right MCP server. `prefixedName` is the
192
+ * chroxy-namespaced name the model emitted (`mcp__<server>__<tool>`).
193
+ * Throws if the prefix is malformed, no client owns that server name,
194
+ * or the client is not READY. JSON-RPC errors from the server
195
+ * propagate as throws — caller turns them into is_error tool_results.
196
+ */
197
+ async callTool(prefixedName, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
198
+ const parsed = parseMcpToolName(prefixedName)
199
+ if (!parsed) throw new Error(`malformed MCP tool name: ${prefixedName}`)
200
+ const client = this._clients.find((c) => c.name === parsed.serverName)
201
+ if (!client) throw new Error(`MCP server not found: ${parsed.serverName}`)
202
+ if (client.state !== MCP_STATES.READY) {
203
+ throw new Error(`MCP server ${parsed.serverName} not ready (state=${client.state})`)
204
+ }
205
+ return client.callTool(parsed.toolName, args, timeoutMs)
206
+ }
207
+
208
+ async destroy() {
209
+ await Promise.race([
210
+ Promise.all(this._clients.map((c) => c.destroy())),
211
+ new Promise((resolve) => setTimeout(resolve, FLEET_KILL_GRACE_MS + 500)),
212
+ ])
213
+ }
214
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * MCP server spawn trust store (#4457).
3
+ *
4
+ * Persists per-tuple trust decisions so a user is asked exactly ONCE per
5
+ * (server_name, command, args[0]) tuple — not on every chroxy restart. The
6
+ * tuple deliberately excludes args[1..N] so a legitimate version bump
7
+ * (e.g. args[1] = "mcp-github@1.4.2" → "mcp-github@1.5.0") doesn't re-prompt,
8
+ * but a binary swap (`command: rm -rf` instead of `node`) DOES.
9
+ *
10
+ * Storage: ~/.chroxy/mcp-trust.json (mode 0600). Atomic writes via temp +
11
+ * rename so a crashed `chroxy doctor` mid-prompt can't corrupt the file.
12
+ *
13
+ * Concurrency: #4460. Two MCPFleet clients started in parallel can both
14
+ * pass through their trustGate (load → prompt → recordTrust) interleaved,
15
+ * yielding the event loop on the prompt `await`. `recordTrust` itself is
16
+ * sync (writeFileSync + renameSync), so the in-process race exists only at
17
+ * the FLEET layer — but withTrustStoreLock() gives that layer a per-path
18
+ * async mutex it can wrap the whole gate in, so prompts surface one at a
19
+ * time (UX) AND the load+write critical section is serialised across all
20
+ * gates in the same process.
21
+ *
22
+ * v1 has no "session-only" tier — once trusted, trusted forever for that
23
+ * tuple. Users who need to revoke can edit the JSON directly. A future
24
+ * iteration can add expiry timestamps without breaking the file format.
25
+ */
26
+
27
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, chmodSync, unlinkSync } from 'node:fs'
28
+ import { homedir } from 'node:os'
29
+ import { join, dirname } from 'node:path'
30
+
31
+ // Per-path tail of an in-process async mutex chain (#4460). Each
32
+ // withTrustStoreLock call awaits the current tail, then publishes a new
33
+ // tail (its own settle-promise). When a section finishes, if its
34
+ // published tail is still the map entry (nothing queued behind), we drop
35
+ // the entry so a long-lived daemon doesn't retain resolved promises
36
+ // for every trust-store path ever written.
37
+ const _trustStoreLocks = new Map()
38
+
39
+ /**
40
+ * Run `critical` while holding the per-path async lock. Other calls for the
41
+ * same path queue behind. Used by byok-mcp-fleet.js to serialise the
42
+ * load→prompt→recordTrust sequence so two parallel trustGates can't both
43
+ * observe an empty store and clobber each other's writes (#4460), and so
44
+ * the human-facing trust prompts surface one at a time rather than two
45
+ * modals fighting over the dashboard.
46
+ *
47
+ * Re-entrancy: NOT re-entrant. Calling withTrustStoreLock from inside
48
+ * another withTrustStoreLock for the same path deadlocks. Callers MUST
49
+ * keep the critical section narrow (the gate sequence is fine; nested
50
+ * gates are not a thing).
51
+ */
52
+ export async function withTrustStoreLock(filePath, critical) {
53
+ const prev = _trustStoreLocks.get(filePath) || Promise.resolve()
54
+ let release
55
+ const myTail = new Promise((resolve) => { release = resolve })
56
+ _trustStoreLocks.set(filePath, myTail)
57
+ try {
58
+ await prev
59
+ return await critical()
60
+ } finally {
61
+ release()
62
+ // Drop the map entry only if no one else queued behind us. If someone
63
+ // did, they replaced our myTail with their own; leave that in place.
64
+ if (_trustStoreLocks.get(filePath) === myTail) {
65
+ _trustStoreLocks.delete(filePath)
66
+ }
67
+ }
68
+ }
69
+
70
+ export function defaultTrustStorePath() {
71
+ return process.env.CHROXY_MCP_TRUST_PATH || join(homedir(), '.chroxy', 'mcp-trust.json')
72
+ }
73
+
74
+ /**
75
+ * Build the canonical tuple key. server.args may be undefined or empty —
76
+ * we still produce a key (args[0] is the empty string) so the consent flow
77
+ * works for shell-built-in-style configs like { command: 'true' }.
78
+ *
79
+ * #4461: serialise via JSON.stringify so component values containing the
80
+ * separator (spaces, NUL bytes, brackets, quotes) cannot collide. The
81
+ * encoded form is also readable on disk under cat ~/.chroxy/mcp-trust.json,
82
+ * which makes hand-debugging trust entries practical. The pre-#4461 NUL
83
+ * separator (\\0-delimited triplet) is structurally vulnerable to a
84
+ * tampered on-disk entry that re-uses a NUL inside name/command — JSON-
85
+ * stringified tuples are unambiguous by construction (quoted strings escape
86
+ * every embedded quote and control char), so no separator hack is needed.
87
+ */
88
+ export function trustTupleKey(server) {
89
+ if (!server || typeof server !== 'object') throw new Error('trustTupleKey: missing server')
90
+ const name = String(server.name || '')
91
+ const command = String(server.command || '')
92
+ const arg0 = Array.isArray(server.args) && server.args.length > 0 ? String(server.args[0]) : ''
93
+ return JSON.stringify([name, command, arg0])
94
+ }
95
+
96
+ /**
97
+ * Load the trust store from disk. Missing file is normal (first run).
98
+ * Malformed file falls back to empty + warns — never throws.
99
+ */
100
+ export function loadTrustStore(filePath = defaultTrustStorePath(), { log } = {}) {
101
+ if (!existsSync(filePath)) return { tuples: new Set(), path: filePath }
102
+ try {
103
+ const raw = JSON.parse(readFileSync(filePath, 'utf8'))
104
+ const arr = Array.isArray(raw?.trustedTuples) ? raw.trustedTuples : []
105
+ const tuples = new Set()
106
+ const entries = []
107
+ for (const t of arr) {
108
+ if (!t || typeof t.key !== 'string') continue
109
+ // #4461: recompute the canonical key from the recorded components and
110
+ // drop any entry whose stored `key` doesn't match. A tampered entry
111
+ // (e.g. stored key kept but command swapped to something dangerous)
112
+ // yields a mismatch and is silently dropped — the user re-prompts
113
+ // for that tuple on next start. Pre-tamper trust is forfeit; correct
114
+ // behaviour given the integrity claim is broken.
115
+ const args0 = typeof t.args0 === 'string' ? t.args0 : ''
116
+ const recomputed = trustTupleKey({
117
+ name: typeof t.name === 'string' ? t.name : '',
118
+ command: typeof t.command === 'string' ? t.command : '',
119
+ args: [args0],
120
+ })
121
+ if (recomputed !== t.key) {
122
+ log?.warn?.(`MCP trust store ${filePath} entry "${t.name}" key tampered (recomputed mismatch); dropping`)
123
+ continue
124
+ }
125
+ tuples.add(t.key)
126
+ entries.push(t)
127
+ }
128
+ return { tuples, path: filePath, entries }
129
+ } catch (err) {
130
+ log?.warn?.(`MCP trust store ${filePath} unreadable: ${err?.message || err}`)
131
+ return { tuples: new Set(), path: filePath }
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Append a trust decision. Idempotent — re-recording an already-trusted
137
+ * tuple is a no-op (no duplicate entries). Writes via temp + rename so a
138
+ * crashed write cannot corrupt the file.
139
+ */
140
+ export function recordTrust(server, filePath = defaultTrustStorePath()) {
141
+ const key = trustTupleKey(server)
142
+ const existing = loadTrustStore(filePath)
143
+ if (existing.tuples.has(key)) return existing
144
+ const entries = Array.isArray(existing.entries) ? [...existing.entries] : []
145
+ entries.push({
146
+ key,
147
+ name: server.name,
148
+ command: server.command,
149
+ args0: Array.isArray(server.args) && server.args.length > 0 ? server.args[0] : '',
150
+ trustedAt: new Date().toISOString(),
151
+ })
152
+ const dir = dirname(filePath)
153
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
154
+ const tmp = `${filePath}.tmp`
155
+ writeFileSync(tmp, JSON.stringify({ trustedTuples: entries }, null, 2), { mode: 0o600 })
156
+ try { chmodSync(tmp, 0o600) } catch {}
157
+ // #4463: when renameSync throws (cross-device link, FS quota, ACL) the
158
+ // temp file would otherwise be left behind. Unlink it on the failure
159
+ // path and re-throw the ORIGINAL rename error so the caller sees the
160
+ // real failure rather than a cleanup-side ENOENT. The cleanup unlink
161
+ // swallows its own errors (the temp may already be gone if the rename
162
+ // partially succeeded or the FS removed it).
163
+ try {
164
+ renameSync(tmp, filePath)
165
+ } catch (err) {
166
+ try { unlinkSync(tmp) } catch {}
167
+ throw err
168
+ }
169
+ return loadTrustStore(filePath)
170
+ }
171
+
172
+ export function isTrusted(store, server) {
173
+ if (!store || !store.tuples) return false
174
+ return store.tuples.has(trustTupleKey(server))
175
+ }