@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.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- 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
|
+
}
|