@chroxy/server 0.11.0 → 0.11.10
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 +204 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1203 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +211 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3513 -287
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +284 -10
- package/src/doctor.js +767 -61
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +330 -42
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +12 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +207 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3491 -312
- package/src/session-message-history.js +722 -16
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +23 -11
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +137 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +7 -2
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +331 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* chroxy-agent-control — stdio MCP server exposing an ORDINARY chroxy session
|
|
4
|
+
* to an external agent harness (Codex, Claude, Gemini, …) as a small set of
|
|
5
|
+
* tools, over the daemon's existing authenticated WebSocket protocol.
|
|
6
|
+
*
|
|
7
|
+
* This is NOT a new control plane: it is a thin MCP adapter over
|
|
8
|
+
* `agent-control/client.js`, which itself is a thin client over the protocol
|
|
9
|
+
* `ws-server.js` already serves. See docs/guides/agent-control.md for the
|
|
10
|
+
* connection to #7823 (durable task/handoff identity), #7437 (universal
|
|
11
|
+
* mailbox) and epic #6691 (in-daemon orchestration) — none of which this file
|
|
12
|
+
* duplicates or supersedes.
|
|
13
|
+
*
|
|
14
|
+
* Usage: `chroxy agent-control --stdio` (see cli/agent-control-cmd.js), which
|
|
15
|
+
* runs this module. Do NOT run it directly for interactive use — like
|
|
16
|
+
* chroxy-channel-server.js, it has no stdio peer unless something (the CLI
|
|
17
|
+
* command, or an MCP host such as Claude Desktop / Codex's own MCP client
|
|
18
|
+
* config) spawns it over stdio. This running session cannot hot-load this
|
|
19
|
+
* MCP server into itself — it must be configured in the HOST's own MCP
|
|
20
|
+
* config and started by that host (see docs/guides/agent-control.md).
|
|
21
|
+
*
|
|
22
|
+
* IMPORTANT: this process's stdout MUST carry ONLY MCP JSON-RPC frames — the
|
|
23
|
+
* SDK's StdioServerTransport owns stdout. Every diagnostic goes to stderr via
|
|
24
|
+
* the client's `log` option (defaults to stderr) or `logToStderr` below.
|
|
25
|
+
* Nothing in this file or in client.js ever calls console.log / process.stdout.write.
|
|
26
|
+
*/
|
|
27
|
+
import { z } from 'zod'
|
|
28
|
+
import { parseArgs } from 'node:util'
|
|
29
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
30
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
31
|
+
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
32
|
+
import { isEntryPoint } from '../utils/is-entry-point.js'
|
|
33
|
+
import { getErrorMessage } from '../utils/error-message.js'
|
|
34
|
+
import { AgentControlClient, redactPublicText, CLIENT_MESSAGE_ID_PATTERN, RESERVED_CLIENT_MESSAGE_IDS } from './client.js'
|
|
35
|
+
import { resolveConnectionTarget, validateExplicitUrl } from './local-connection.js'
|
|
36
|
+
|
|
37
|
+
export const SERVER_NAME = 'chroxy-agent-control'
|
|
38
|
+
export const SERVER_VERSION = '0.1.0'
|
|
39
|
+
|
|
40
|
+
// Mutation tools — absent from ListTools AND hard-refused at CallTool time
|
|
41
|
+
// when readOnly, so "read-only" is enforced by the dispatch gate, not merely
|
|
42
|
+
// by which tools got advertised (an MCP host could in principle call an
|
|
43
|
+
// un-advertised tool name).
|
|
44
|
+
const MUTATION_TOOL_NAMES = new Set(['chroxy_create_session', 'chroxy_send_input', 'chroxy_interrupt_session', 'chroxy_respond_permission'])
|
|
45
|
+
|
|
46
|
+
function logToStderr(...args) {
|
|
47
|
+
console.error(`[${SERVER_NAME}]`, ...args)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// #7969 — one sentence, used by BOTH the fail-fast startup refusal in `main()`
|
|
51
|
+
// and the lazy `describeConnectionFailure` case, so the two can never drift.
|
|
52
|
+
// It deliberately names neither the URL nor the host nor the token: this module
|
|
53
|
+
// never logs the URL, and a refusal line is exactly the kind of text that ends
|
|
54
|
+
// up pasted into an issue.
|
|
55
|
+
const INSECURE_REMOTE_WS_REFUSAL = 'refusing a remote ws:// endpoint: the bearer token is sent in cleartext in the first auth frame, before any key exchange, so anyone on the network path can read it, and an identity pin cannot protect it (the pin is only checked after the token has gone out). Use a wss:// URL, or pass --allow-insecure-ws to accept that risk on a network you trust.'
|
|
56
|
+
|
|
57
|
+
function textResult(value) {
|
|
58
|
+
return {
|
|
59
|
+
content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
|
|
60
|
+
...(value && typeof value === 'object' ? { structuredContent: value } : {}),
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function errorResult(message, extra = {}) {
|
|
65
|
+
return {
|
|
66
|
+
content: [{ type: 'text', text: JSON.stringify({ error: message, ...extra }, null, 2) }],
|
|
67
|
+
structuredContent: { error: message, ...extra },
|
|
68
|
+
isError: true,
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Shared across tool schemas.
|
|
73
|
+
const SessionId = z.string().min(1).max(256)
|
|
74
|
+
const ClientMessageId = z.string()
|
|
75
|
+
.regex(CLIENT_MESSAGE_ID_PATTERN)
|
|
76
|
+
.refine((v) => !RESERVED_CLIENT_MESSAGE_IDS.has(v.toLowerCase()), { message: 'reserved clientMessageId value' })
|
|
77
|
+
// Matches ALLOWED_PERMISSION_MODE_IDS minus 'auto' (see handler-utils.js
|
|
78
|
+
// MODE_IDS) — 'auto' is rejected by client.js regardless; enumerating the
|
|
79
|
+
// permitted set here gives the MCP host real validation instead of a
|
|
80
|
+
// description-only claim.
|
|
81
|
+
const PermissionMode = z.enum(['approve', 'acceptEdits', 'plan'])
|
|
82
|
+
|
|
83
|
+
// Each tool's JSON Schema (advertised in `tools/list`) is DERIVED from its
|
|
84
|
+
// zod `argsSchema` via `z.toJSONSchema` — one definition, not two hand-kept
|
|
85
|
+
// in sync. `.describe()` on the object and each field supplies what would
|
|
86
|
+
// otherwise have lived in a duplicated JSON Schema `description`.
|
|
87
|
+
const TOOLS = {
|
|
88
|
+
chroxy_daemon_info: {
|
|
89
|
+
description: 'Safe daemon metadata: server/protocol version, encryption mode, and a bounded capabilities map for the connected chroxy daemon. Does not disclose the auth token, connection.json, or any session content.',
|
|
90
|
+
argsSchema: z.object({}).strict(),
|
|
91
|
+
async handler(client) {
|
|
92
|
+
return textResult(client.daemonInfo)
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
chroxy_list_sessions: {
|
|
97
|
+
description: "List the daemon's ordinary chroxy sessions. Each row carries `modelStatus: { requested, observed, unknown, mismatch }` — `observed` is what the daemon actually reports (null means the daemon has not resolved/exposed a model, reported as `unknown: true`, never guessed); `requested` is populated only for sessions this same MCP process created. A busy row (`isBusy: true`) also carries `busyReason`: `'turn'` (the model is working) or `'background-shells'` (the model is idle and only a tracked background shell keeps the row busy; `backgroundShellCount` says how many) — absent on an older daemon.",
|
|
98
|
+
argsSchema: z.object({}).strict(),
|
|
99
|
+
async handler(client) {
|
|
100
|
+
const result = await client.listSessions()
|
|
101
|
+
return textResult(result)
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
chroxy_create_session: {
|
|
106
|
+
description: "Create a new ordinary chroxy session. Refuses provider 'user-shell' and any skipPermissions option (out of scope for agent-control — see docs/guides/agent-control.md); always sends skipPermissions:false explicitly regardless of the daemon's own default. The result's `modelStatus` MUST be checked before treating the session as running the requested model — a daemon can silently fall back to a different model (observed in production: an explicit 'claude-sonnet-5' create request booting Opus instead). Do not send an implementation task under an assumed model when `modelStatus.mismatch` or `modelStatus.unknown` is true.",
|
|
107
|
+
argsSchema: z.object({
|
|
108
|
+
name: z.string().min(1).max(200).optional().describe('Display name for the session'),
|
|
109
|
+
cwd: z.string().min(1).max(4096).optional().describe('Working directory (must be within the daemon-allowed cwd roots)'),
|
|
110
|
+
provider: z.string().min(1).max(64).optional().describe("Provider id (e.g. 'claude-sdk', 'codex', 'gemini'). Never 'user-shell'."),
|
|
111
|
+
model: z.string().min(1).max(200).optional().describe('Requested model id. The daemon may resolve a different one — see modelStatus in the result.'),
|
|
112
|
+
permissionMode: PermissionMode.optional().describe("Permission mode. Defaults to 'approve'. Never 'auto' via this tool — that mode requires host-level confirmation this client cannot honestly supply."),
|
|
113
|
+
worktree: z.boolean().optional().describe('Create the session in an isolated git worktree (requires cwd).'),
|
|
114
|
+
}).strict().refine(
|
|
115
|
+
(v) => v.provider === undefined || v.provider.trim() !== 'user-shell',
|
|
116
|
+
{ message: "provider 'user-shell' is not permitted through agent-control", path: ['provider'] },
|
|
117
|
+
),
|
|
118
|
+
async handler(client, args) {
|
|
119
|
+
const result = await client.createSession(args || {})
|
|
120
|
+
return textResult(result)
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
chroxy_send_input: {
|
|
125
|
+
description: "Send text input to a session and return the daemon's correlated input_ack VERBATIM (status/delivery/retrySafe/dedupScope). Only a session created by chroxy_create_session in this same MCP-server process can be sent input — a session created elsewhere (one a human is driving, say) is refused with `status: 'rejected', reason: 'not_owned'`, before any network I/O; observing it via chroxy_get_events is unrestricted. `status: 'uncertain'` means no FINAL ack arrived in time or the connection dropped — this is NOT a failure and NOT permission to retry; it means the outcome is unknown. `status: 'blocked'` means this client refused to send because the session's resolved model doesn't verifiably match what was requested at creation (see modelStatus), or because the daemon doesn't advertise input_context_v1 support — re-check with chroxy_list_sessions or pass acknowledgeModelMismatch:true to send anyway. Never infer task completion from this call alone.",
|
|
126
|
+
argsSchema: z.object({
|
|
127
|
+
sessionId: SessionId.describe('Target session id (from chroxy_list_sessions / chroxy_create_session)'),
|
|
128
|
+
data: z.string().min(1).max(200_000).describe('Text to send as user input to the session'),
|
|
129
|
+
clientMessageId: ClientMessageId.optional().describe("Optional: supply your own id (matches /^[A-Za-z0-9_-]{1,128}$/) to make a deliberate retry land on the daemon's dedup path instead of being treated as a brand-new send."),
|
|
130
|
+
acknowledgeModelMismatch: z.boolean().optional().describe('Send even though the model-mismatch/unknown gate would otherwise block this call.'),
|
|
131
|
+
}).strict(),
|
|
132
|
+
async handler(client, args) {
|
|
133
|
+
const ack = await client.sendInput(args.sessionId, args.data, { clientMessageId: args.clientMessageId, acknowledgeModelMismatch: args.acknowledgeModelMismatch })
|
|
134
|
+
return textResult(ack)
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
chroxy_get_events: {
|
|
139
|
+
description: "Bounded, cursor-based read of a session's retained event log (aggregated assistant text, tool start/result, permission requests, model/mode changes — never raw PTY output or, by default, thinking text). Pass the `cursor` from a previous call to read only new events. `gap: true` means some events between your cursor and what's returned could not be retained or the cursor named a wrong/future/reset point (see `gapReason`) — not that anything failed. An empty `events` array means no NEW retained events, never 'the agent finished'. `waitMs` (<=30000) long-polls for new events instead of returning immediately.",
|
|
140
|
+
argsSchema: z.object({
|
|
141
|
+
sessionId: SessionId,
|
|
142
|
+
cursor: z.string().min(1).max(2048).optional().describe('Opaque cursor from a previous chroxy_get_events call. Omit to start from the oldest retained event.'),
|
|
143
|
+
limit: z.number().int().min(1).max(200).optional().describe('Max events to return (default 50, max 200).'),
|
|
144
|
+
waitMs: z.number().int().min(0).max(30_000).optional().describe('Long-poll up to this many ms for new events (default 0 = return immediately).'),
|
|
145
|
+
}).strict(),
|
|
146
|
+
async handler(client, args) {
|
|
147
|
+
const result = await client.getEvents(args.sessionId, { cursor: args.cursor, limit: args.limit, waitMs: args.waitMs })
|
|
148
|
+
return textResult(result)
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
|
|
152
|
+
chroxy_interrupt_session: {
|
|
153
|
+
description: "Best-effort interrupt of a running session (the protocol defines no correlated ack for this). Only a session created by chroxy_create_session in this same MCP-server process can be interrupted — a session created elsewhere is refused with `status: 'rejected', reason: 'not_owned'`, before any network I/O. The result reports what was observed, not a synthesized \"stopped\".",
|
|
154
|
+
argsSchema: z.object({ sessionId: SessionId }).strict(),
|
|
155
|
+
async handler(client, args) {
|
|
156
|
+
const result = await client.interrupt(args.sessionId)
|
|
157
|
+
return textResult(result)
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
chroxy_respond_permission: {
|
|
162
|
+
description: "Answer a pending permission request (e.g. a Bash tool-use approval) with 'allow' or 'deny' — NEVER 'allowAlways', which persists a durable project rule and is out of scope here. Only sessions created by chroxy_create_session in this same MCP-server process can be answered (reason 'not_owned' otherwise) — prompts in sessions someone else is driving are left for them. Refuses (before any network I/O) to answer a requestId this MCP process has not itself observed as pending for the given sessionId, via chroxy_get_events' permission_request events — an unknown, already-resolved, or sibling-session requestId is rejected, never guessed at. 'allow' is refused unconditionally (reason 'not_delegable', whatever the floor says) for mcp_spawn (an allow persists a permanent MCP-binary trust grant) and codex's request_permissions (a sandbox-scope escalation) — both require a human. 'allow' is ALSO only ever permitted for an ALLOWLISTED tool (#7975): Read, Write, Edit, NotebookEdit, or codex apply_patch (exactly the tools whose ENTIRE file-selecting input the protected-path floor actually inspects), or a command-style tool (Bash, PowerShell, Monitor, codex shell) when this MCP server was started with --allow-command-approvals — a command-style tool without that flag is refused 'command_approval_disabled'; any other tool (an MCP tool, WebFetch/WebSearch, Task/Agent, codex mcp_elicitation, Glob, Grep, or a future Claude Code tool this client doesn't recognize) is refused 'not_allowlisted', because 'floored: false' on a tool the floor cannot see into at all is not a safety signal — Glob and Grep are refused for this same reason despite carrying a floor-inspected 'path' field: Glob's 'pattern' selects files the floor never inspects, and a Grep with no 'glob' reads every non-ignored file under its 'path', a committed secret included, while the floor sees only the path. For an allowlisted or flagged tool, 'allow' is additionally refused when the observed permission_request was marked floor-forced by the daemon (docs/security/permission-floor.md — a secret read, or a write into .git/ or .claude/, that must go to a human): `floored: true` refuses with reason 'floored', and an ABSENT floored flag (an older daemon that predates this check) refuses with reason 'floor_unknown', fail-closed — only `floored: false` (an ordinary, non-floored prompt) permits 'allow'. 'deny' is never gated by any of the above. `status: 'uncertain'` on the result means no confirmation arrived in time; do not assume the decision was or was not applied, and do not retry automatically. A hook-routed prompt that maps to a session (claude-tui, claude-cli, claude-channel) is confirmed like an SDK one (#7976). An UNMAPPED legacy prompt can still go unconfirmed, and 'uncertain' then reflects a real protocol limitation, not a client bug.",
|
|
163
|
+
argsSchema: z.object({
|
|
164
|
+
sessionId: SessionId,
|
|
165
|
+
requestId: z.string().min(1).max(256).describe("The permission request id, from a chroxy_get_events 'permission_request' event."),
|
|
166
|
+
decision: z.enum(['allow', 'deny']),
|
|
167
|
+
}).strict(),
|
|
168
|
+
async handler(client, args) {
|
|
169
|
+
const result = await client.respondPermission(args.sessionId, args.requestId, args.decision)
|
|
170
|
+
return textResult(result)
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Freeze each tool's derived MCP `definition` (name/description/inputSchema)
|
|
176
|
+
// once, at module load — the JSON Schema is pure derivation from argsSchema
|
|
177
|
+
// and never changes at runtime, so deriving it per `tools/list` call would
|
|
178
|
+
// just be repeated work for the same answer.
|
|
179
|
+
for (const [name, tool] of Object.entries(TOOLS)) {
|
|
180
|
+
tool.definition = {
|
|
181
|
+
name,
|
|
182
|
+
description: tool.description,
|
|
183
|
+
inputSchema: z.toJSONSchema(tool.argsSchema),
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Lazily owns ONE connected AgentControlClient, reconnecting a fresh client
|
|
189
|
+
* (AgentControlClient is single-use per connection — see client.js doc) on
|
|
190
|
+
* demand if the previous one is not ready. Never auto-retries a MUTATION —
|
|
191
|
+
* this only re-establishes the TRANSPORT; individual tool calls still surface
|
|
192
|
+
* their own uncertain/failed outcomes rather than silently retrying.
|
|
193
|
+
*
|
|
194
|
+
* Concurrency-safe: `get()` may be called by several CallTool dispatches
|
|
195
|
+
* before any of them resolve (an MCP host is free to pipeline requests).
|
|
196
|
+
* Without coordination, each concurrent caller would see `this._client` as
|
|
197
|
+
* not-ready and start its OWN `connect()`, leaving all-but-one connection
|
|
198
|
+
* (and its in-memory event log / model expectations) orphaned. A single
|
|
199
|
+
* shared in-flight promise means every concurrent caller awaits the SAME
|
|
200
|
+
* connect attempt and gets the SAME client.
|
|
201
|
+
*/
|
|
202
|
+
class ClientManager {
|
|
203
|
+
constructor(connectionOpts, clientOpts = {}) {
|
|
204
|
+
this._connectionOpts = connectionOpts
|
|
205
|
+
this._clientOpts = clientOpts
|
|
206
|
+
this._client = null
|
|
207
|
+
this._connecting = null
|
|
208
|
+
// The RAW client instance currently inside `client.connect()`, tracked
|
|
209
|
+
// separately from `this._client` (which is only set once `connect()`
|
|
210
|
+
// SUCCEEDS) — this is what lets `close()` interrupt an in-flight connect
|
|
211
|
+
// immediately instead of idling for up to `connectTimeoutMs`.
|
|
212
|
+
this._connectingClient = null
|
|
213
|
+
this._lastToken = null
|
|
214
|
+
// Owned by the MANAGER, not any one client instance, and passed into
|
|
215
|
+
// every client it creates — a model expectation recorded by
|
|
216
|
+
// `createSession` must survive a reconnect within this same MCP-server
|
|
217
|
+
// process (the transport dropping has nothing to do with what model a
|
|
218
|
+
// session was created with).
|
|
219
|
+
this._modelExpectations = new Map()
|
|
220
|
+
// Same lifetime, same reason: the sessions this MCP-server process
|
|
221
|
+
// created (and therefore may answer permission prompts for) must not be
|
|
222
|
+
// forgotten because the transport reconnected.
|
|
223
|
+
this._ownedSessions = new Set()
|
|
224
|
+
// Set by `close()`. Once true, `get()` refuses outright and an
|
|
225
|
+
// in-flight `_connect()` self-closes its result instead of storing it —
|
|
226
|
+
// without this, `close()` racing an in-flight connect would return
|
|
227
|
+
// having closed nothing (this._client is still null at that point), and
|
|
228
|
+
// the connect would then resurrect a live client moments later; a
|
|
229
|
+
// subsequent `get()` could reconnect a manager that was told to shut
|
|
230
|
+
// down.
|
|
231
|
+
this._closed = false
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** For redacting a resolved token out of error text at the MCP layer too. */
|
|
235
|
+
get lastToken() {
|
|
236
|
+
return this._lastToken
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async get() {
|
|
240
|
+
if (this._closed) {
|
|
241
|
+
throw Object.assign(new Error('ClientManager is closed'), { code: 'MANAGER_CLOSED' })
|
|
242
|
+
}
|
|
243
|
+
if (this._client && this._client.state === 'ready') return this._client
|
|
244
|
+
if (this._connecting) return this._connecting
|
|
245
|
+
this._connecting = this._connect().finally(() => { this._connecting = null })
|
|
246
|
+
return this._connecting
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async _connect() {
|
|
250
|
+
const target = resolveConnectionTarget(this._connectionOpts)
|
|
251
|
+
if (!target.ok) {
|
|
252
|
+
throw Object.assign(new Error(describeConnectionFailure(target.reason)), { code: target.reason })
|
|
253
|
+
}
|
|
254
|
+
this._lastToken = target.token
|
|
255
|
+
const client = new AgentControlClient({
|
|
256
|
+
url: target.url,
|
|
257
|
+
token: target.token,
|
|
258
|
+
readOnly: this._clientOpts.readOnly === true,
|
|
259
|
+
identityPublicKey: this._clientOpts.identityPublicKey,
|
|
260
|
+
allowCommandApprovals: this._clientOpts.allowCommandApprovals === true,
|
|
261
|
+
// TEST SEAM ONLY: `undefined` in production (the client then uses the
|
|
262
|
+
// `ws` library). Set solely by a programmatic caller of
|
|
263
|
+
// `createAgentControlMcpServer`; `main()` never passes it, so it cannot
|
|
264
|
+
// be reached from argv or the environment.
|
|
265
|
+
WebSocketImpl: this._clientOpts.WebSocketImpl,
|
|
266
|
+
modelExpectations: this._modelExpectations,
|
|
267
|
+
ownedSessions: this._ownedSessions,
|
|
268
|
+
log: logToStderr,
|
|
269
|
+
})
|
|
270
|
+
this._connectingClient = client
|
|
271
|
+
try {
|
|
272
|
+
await client.connect()
|
|
273
|
+
} catch (err) {
|
|
274
|
+
// A FAILED connect must not linger as `this._client` — the next
|
|
275
|
+
// `get()` needs to try again, not return a dead/half-open client.
|
|
276
|
+
try { await client.close() } catch { /* already tearing down */ }
|
|
277
|
+
throw err
|
|
278
|
+
} finally {
|
|
279
|
+
this._connectingClient = null
|
|
280
|
+
}
|
|
281
|
+
if (this._closed) {
|
|
282
|
+
// `close()` ran while this connect was in flight — do not resurrect a
|
|
283
|
+
// client after the manager was told to shut down; close what we just
|
|
284
|
+
// opened instead of storing it.
|
|
285
|
+
try { await client.close() } catch { /* already tearing down */ }
|
|
286
|
+
throw Object.assign(new Error('ClientManager was closed while connecting'), { code: 'MANAGER_CLOSED' })
|
|
287
|
+
}
|
|
288
|
+
// A SUPERSEDED client (this._client was set by a still-open call from a
|
|
289
|
+
// previous, now-replaced connection attempt — shouldn't happen given the
|
|
290
|
+
// single in-flight promise above, but closing defensively costs nothing
|
|
291
|
+
// and prevents a leaked socket if that invariant is ever loosened).
|
|
292
|
+
if (this._client && this._client !== client && this._client.state !== 'closed') {
|
|
293
|
+
try { await this._client.close() } catch { /* best effort */ }
|
|
294
|
+
}
|
|
295
|
+
this._client = client
|
|
296
|
+
return client
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async close() {
|
|
300
|
+
this._closed = true
|
|
301
|
+
// Interrupt an in-flight connect IMMEDIATELY, rather than idling until
|
|
302
|
+
// its own `connectTimeoutMs` elapses: closing the raw client's socket
|
|
303
|
+
// makes `client.connect()`'s pending handshake awaits reject right away
|
|
304
|
+
// (see AgentControlClient's `_onSocketClosed` / `_abortHandshakeWaiters`),
|
|
305
|
+
// so the `await this._connecting` below returns promptly instead of
|
|
306
|
+
// after a potentially many-second timeout.
|
|
307
|
+
if (this._connectingClient) {
|
|
308
|
+
try { await this._connectingClient.close() } catch { /* best effort */ }
|
|
309
|
+
}
|
|
310
|
+
// Wait out any in-flight connect — otherwise its client (once
|
|
311
|
+
// `_connect()` finishes moments after this method returns) would never
|
|
312
|
+
// get closed, and would sit there as a live, un-tracked socket. The
|
|
313
|
+
// `_closed` check inside `_connect()` (above) is what makes this await
|
|
314
|
+
// actually terminate the connection rather than just observe it land.
|
|
315
|
+
if (this._connecting) {
|
|
316
|
+
try { await this._connecting } catch { /* connect failed/self-closed on its own */ }
|
|
317
|
+
}
|
|
318
|
+
if (this._client) {
|
|
319
|
+
try { await this._client.close() } catch { /* best effort */ }
|
|
320
|
+
this._client = null
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function describeConnectionFailure(reason) {
|
|
326
|
+
switch (reason) {
|
|
327
|
+
case 'not_running':
|
|
328
|
+
return 'chroxy daemon is not running locally (no connection.json). Start it with `chroxy start`, or pass --url with CHROXY_AGENT_CONTROL_TOKEN set for a remote daemon.'
|
|
329
|
+
case 'no_local_token':
|
|
330
|
+
return 'chroxy daemon is running without an auth token (--no-auth) or the token could not be read locally.'
|
|
331
|
+
case 'remote_requires_token':
|
|
332
|
+
return '--url was given without a token. Set CHROXY_AGENT_CONTROL_TOKEN — there is no --token argv flag (a token in argv is visible in process listings).'
|
|
333
|
+
case 'invalid_url':
|
|
334
|
+
case 'invalid_url_scheme':
|
|
335
|
+
return '--url must be a valid ws:// or wss:// URL.'
|
|
336
|
+
case 'url_contains_credentials':
|
|
337
|
+
return '--url must not embed credentials (ws://token@host/...) — pass the token via CHROXY_AGENT_CONTROL_TOKEN instead.'
|
|
338
|
+
case 'insecure_remote_ws':
|
|
339
|
+
return INSECURE_REMOTE_WS_REFUSAL
|
|
340
|
+
default:
|
|
341
|
+
return `could not resolve a daemon connection (${reason})`
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Build the MCP `Server` with every agent-control tool registered, gated by
|
|
347
|
+
* `readOnly`. Connection is NOT established here — it happens lazily on the
|
|
348
|
+
* first tool call via `ClientManager`, so `chroxy agent-control --stdio` can
|
|
349
|
+
* be spawned by an MCP host before (or independently of) the daemon starting.
|
|
350
|
+
*
|
|
351
|
+
* @param {object} [opts]
|
|
352
|
+
* @param {boolean} [opts.readOnly]
|
|
353
|
+
* @param {string} [opts.url] - explicit remote URL (never inferred)
|
|
354
|
+
* @param {string} [opts.token] - explicit token for a remote URL
|
|
355
|
+
* @param {string} [opts.identityPublicKey] - pin the daemon identity
|
|
356
|
+
* @param {boolean} [opts.allowCommandApprovals] - #7973: let chroxy_respond_permission
|
|
357
|
+
* approve a command-style tool (Bash/PowerShell/Monitor/codex shell). Default false. See client.js's
|
|
358
|
+
* respondPermission doc comment.
|
|
359
|
+
* @param {boolean} [opts.allowInsecureWs] - #7969: opt in to a cleartext `ws://`
|
|
360
|
+
* endpoint on a host that is not loopback (only the boolean `true` counts).
|
|
361
|
+
* Default false: the first connect then fails with `insecure_remote_ws`.
|
|
362
|
+
* @param {typeof WebSocket} [opts.WebSocketImpl] - TEST SEAM: a WebSocket
|
|
363
|
+
* constructor forwarded to `AgentControlClient`, so a test can observe or
|
|
364
|
+
* fake the transport instead of letting the `ws` library resolve a name and
|
|
365
|
+
* open a socket. Programmatic only — `main()` does not pass it, and nothing
|
|
366
|
+
* reads it from argv or the environment.
|
|
367
|
+
* @returns {{ mcp: Server, clientManager: ClientManager }}
|
|
368
|
+
*/
|
|
369
|
+
export function createAgentControlMcpServer(opts = {}) {
|
|
370
|
+
const readOnly = opts.readOnly === true
|
|
371
|
+
const clientManager = opts.clientManager || new ClientManager(
|
|
372
|
+
{ explicitUrl: opts.url, explicitToken: opts.token, allowInsecureWs: opts.allowInsecureWs === true },
|
|
373
|
+
{ readOnly, identityPublicKey: opts.identityPublicKey, allowCommandApprovals: opts.allowCommandApprovals === true, WebSocketImpl: opts.WebSocketImpl },
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
const toolNames = Object.keys(TOOLS).filter((name) => readOnly ? !MUTATION_TOOL_NAMES.has(name) : true)
|
|
377
|
+
|
|
378
|
+
const mcp = new Server(
|
|
379
|
+
{ name: SERVER_NAME, version: SERVER_VERSION },
|
|
380
|
+
{ capabilities: { tools: {} } },
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
384
|
+
tools: toolNames.map((name) => TOOLS[name].definition),
|
|
385
|
+
}))
|
|
386
|
+
|
|
387
|
+
mcp.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
388
|
+
const name = req.params.name
|
|
389
|
+
const tool = TOOLS[name]
|
|
390
|
+
if (!tool) return errorResult(`unknown tool: ${name}`)
|
|
391
|
+
// Hard gate — independent of what ListTools advertised. "read-only mode
|
|
392
|
+
// mutation tools must be absent AND unavailable by direct call."
|
|
393
|
+
if (readOnly && MUTATION_TOOL_NAMES.has(name)) {
|
|
394
|
+
return errorResult(`'${name}' is a mutation tool and this agent-control server is running in --read-only mode`, { code: 'READ_ONLY_MODE' })
|
|
395
|
+
}
|
|
396
|
+
// Runtime validation against the BOUNDED zod schema — the JSON Schema in
|
|
397
|
+
// `definition.inputSchema` documents shape to the MCP host, but a
|
|
398
|
+
// description is not a guard; this is the actual enforcement, run
|
|
399
|
+
// before any connect/I/O.
|
|
400
|
+
const parsed = tool.argsSchema.safeParse(req.params.arguments || {})
|
|
401
|
+
if (!parsed.success) {
|
|
402
|
+
return errorResult(`invalid arguments for '${name}': ${parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; ')}`, { code: 'INVALID_ARGUMENTS' })
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
const client = await clientManager.get()
|
|
406
|
+
return await tool.handler(client, parsed.data)
|
|
407
|
+
} catch (err) {
|
|
408
|
+
const message = redactPublicText(getErrorMessage(err), clientManager.lastToken)
|
|
409
|
+
logToStderr(`tool '${name}' failed:`, message)
|
|
410
|
+
return errorResult(message, typeof err?.code === 'string' ? { code: redactPublicText(err.code, clientManager.lastToken) } : {})
|
|
411
|
+
}
|
|
412
|
+
})
|
|
413
|
+
|
|
414
|
+
return { mcp, clientManager }
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export async function main(options) {
|
|
418
|
+
const parsed = options ?? (() => {
|
|
419
|
+
const { values } = parseArgs({
|
|
420
|
+
args: process.argv.slice(2),
|
|
421
|
+
options: {
|
|
422
|
+
stdio: { type: 'boolean' },
|
|
423
|
+
'read-only': { type: 'boolean' },
|
|
424
|
+
url: { type: 'string' },
|
|
425
|
+
'pin-identity': { type: 'string' },
|
|
426
|
+
'allow-command-approvals': { type: 'boolean' },
|
|
427
|
+
'allow-insecure-ws': { type: 'boolean' },
|
|
428
|
+
},
|
|
429
|
+
})
|
|
430
|
+
return {
|
|
431
|
+
readOnly: values['read-only'],
|
|
432
|
+
url: values.url,
|
|
433
|
+
identityPublicKey: values['pin-identity'],
|
|
434
|
+
allowCommandApprovals: values['allow-command-approvals'],
|
|
435
|
+
allowInsecureWs: values['allow-insecure-ws'],
|
|
436
|
+
}
|
|
437
|
+
})()
|
|
438
|
+
const readOnly = parsed.readOnly === true
|
|
439
|
+
const url = parsed.url
|
|
440
|
+
const allowCommandApprovals = parsed.allowCommandApprovals === true
|
|
441
|
+
// #7969: argv only — deliberately NO environment-variable equivalent, so a
|
|
442
|
+
// URL configured through CHROXY_AGENT_CONTROL_URL still needs this flag in
|
|
443
|
+
// the arguments that spawn the process.
|
|
444
|
+
const allowInsecureWs = parsed.allowInsecureWs === true
|
|
445
|
+
// `CHROXY_AGENT_CONTROL_URL` selects the explicit (remote) path inside
|
|
446
|
+
// resolveConnectionTarget exactly like `--url` does, so it counts here too.
|
|
447
|
+
const explicitTarget = url || process.env.CHROXY_AGENT_CONTROL_URL
|
|
448
|
+
|
|
449
|
+
// #7969: FAIL FAST, before the MCP server exists and before the stdio
|
|
450
|
+
// transport connects. The bearer token goes out in the first `auth` frame,
|
|
451
|
+
// before any key exchange, so over plain ws:// to another host it is readable
|
|
452
|
+
// on the path and no identity pin can protect it. Without this, the refusal
|
|
453
|
+
// would surface only as a tool-call error on the first call — after the host
|
|
454
|
+
// had already registered the server as healthy. One line to stderr, nothing
|
|
455
|
+
// on stdout (that stream is MCP frames only), a non-zero exit. Only THIS
|
|
456
|
+
// refusal is fail-fast; every other `validateExplicitUrl` / resolver failure
|
|
457
|
+
// keeps surfacing lazily, exactly as before. The rule itself is the same
|
|
458
|
+
// `validateExplicitUrl` the resolver calls — there is no second copy of it.
|
|
459
|
+
//
|
|
460
|
+
// `process.exitCode` + return (not a throw): cli.js calls `program.parse()`,
|
|
461
|
+
// not `parseAsync`, so a rejected action promise is an unhandled rejection
|
|
462
|
+
// with a stack trace, and `process.exit()` can truncate a pipe write. Nothing
|
|
463
|
+
// has been started yet — no listeners, no socket, no stdin handle — so
|
|
464
|
+
// returning here lets the process drain stderr and end on its own.
|
|
465
|
+
const urlCheck = explicitTarget ? validateExplicitUrl(explicitTarget, { allowInsecureWs }) : null
|
|
466
|
+
if (urlCheck && !urlCheck.ok && urlCheck.reason === 'insecure_remote_ws') {
|
|
467
|
+
logToStderr(INSECURE_REMOTE_WS_REFUSAL)
|
|
468
|
+
process.exitCode = 1
|
|
469
|
+
return
|
|
470
|
+
}
|
|
471
|
+
// Deliberately NO --token argv flag — argv is visible to every other
|
|
472
|
+
// process on the machine (`ps`), unlike an env var scoped to this
|
|
473
|
+
// process's own environment block. A remote connection's token is read
|
|
474
|
+
// ONLY from CHROXY_AGENT_CONTROL_TOKEN.
|
|
475
|
+
const token = url ? process.env.CHROXY_AGENT_CONTROL_TOKEN : undefined
|
|
476
|
+
const identityPublicKey = parsed.identityPublicKey ?? process.env.CHROXY_AGENT_CONTROL_PIN
|
|
477
|
+
|
|
478
|
+
// #7973: a clear, unambiguous operator-facing warning — printed once, at
|
|
479
|
+
// startup, not per-call — whenever this flag widens what an external
|
|
480
|
+
// planner may approve. Still says something useful in --read-only mode,
|
|
481
|
+
// where the flag is a harmless no-op (chroxy_respond_permission is absent
|
|
482
|
+
// and hard-refused entirely), so an operator who passes both doesn't
|
|
483
|
+
// wrongly conclude command approvals are live.
|
|
484
|
+
if (allowCommandApprovals) {
|
|
485
|
+
if (readOnly) {
|
|
486
|
+
logToStderr('--allow-command-approvals has no effect: this server is running --read-only, so chroxy_respond_permission (and every other mutation tool) is absent and hard-refused regardless.')
|
|
487
|
+
} else {
|
|
488
|
+
logToStderr('WARNING: --allow-command-approvals is ENABLED. An external planner connected to this MCP server may approve Bash/PowerShell/Monitor/codex-shell tool calls — arbitrary commands the protected-path floor cannot inspect (e.g. `cat .env` looks like an ordinary, unfloored Bash call). This is off by default; the floored/ownership gates still apply on top. Only enable this for a planner you trust with shell-level authority over this daemon.')
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// #7969: same shape as the --allow-command-approvals notice above — a loud
|
|
493
|
+
// one-time WARNING when the flag is actually admitting something, and a plain
|
|
494
|
+
// "has no effect" when it is moot, so an operator who passes it needlessly
|
|
495
|
+
// does not conclude cleartext transport is in play. "Moot" means the gate
|
|
496
|
+
// would never have refused this target: no explicit target at all, or one
|
|
497
|
+
// that validates with `insecureRemoteWs` false. A target that fails
|
|
498
|
+
// validation for ANOTHER reason (`invalid_url`, a bad scheme, embedded
|
|
499
|
+
// credentials) is neither: the flag's relevance is unknown until the URL is
|
|
500
|
+
// fixed, so say nothing about it — the lazy path reports the real problem on
|
|
501
|
+
// the first tool call, exactly when it always did.
|
|
502
|
+
if (allowInsecureWs) {
|
|
503
|
+
if (urlCheck?.ok && urlCheck.insecureRemoteWs) {
|
|
504
|
+
logToStderr('WARNING: --allow-insecure-ws is ENABLED and the target is a ws:// endpoint on another host. The bearer token will travel in cleartext in the first auth frame, before any key exchange, so anyone on the network path can read it; an identity pin does not protect it. Only use this on a network you trust, or switch to wss://.')
|
|
505
|
+
} else if (!urlCheck || urlCheck.ok) {
|
|
506
|
+
logToStderr('--allow-insecure-ws has no effect: the target is not a remote ws:// URL (the local default, a loopback ws:// URL and any wss:// URL are never refused).')
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const { mcp, clientManager } = createAgentControlMcpServer({ readOnly, url, token, identityPublicKey, allowCommandApprovals, allowInsecureWs })
|
|
511
|
+
|
|
512
|
+
let shuttingDown = false
|
|
513
|
+
const shutdown = async (signal) => {
|
|
514
|
+
if (shuttingDown) return
|
|
515
|
+
shuttingDown = true
|
|
516
|
+
logToStderr(`shutting down (${signal})`)
|
|
517
|
+
await clientManager.close()
|
|
518
|
+
process.exit(0)
|
|
519
|
+
}
|
|
520
|
+
// The MCP host normally tears this process down by closing stdin (the
|
|
521
|
+
// transport's 'close' fires) or sending a signal — either way, the
|
|
522
|
+
// underlying WS socket and any in-flight `getEvents` long-poll must be
|
|
523
|
+
// closed explicitly, or the process can linger on an open timer/socket
|
|
524
|
+
// after its stdio peer is gone.
|
|
525
|
+
process.stdin.on('end', () => { shutdown('stdin-eof') })
|
|
526
|
+
process.on('SIGTERM', () => { shutdown('SIGTERM') })
|
|
527
|
+
process.on('SIGINT', () => { shutdown('SIGINT') })
|
|
528
|
+
|
|
529
|
+
await mcp.connect(new StdioServerTransport())
|
|
530
|
+
// Deliberately never logs the URL itself — even a validated ws(s):// URL
|
|
531
|
+
// with no embedded credentials is still connection metadata this process
|
|
532
|
+
// doesn't need to put in a log stream; "remote" vs "local" is all a reader
|
|
533
|
+
// needs to know which path was taken.
|
|
534
|
+
// `explicitTarget` (hoisted above) counts `CHROXY_AGENT_CONTROL_URL` too —
|
|
535
|
+
// otherwise an env-configured remote target would be logged as 'local'.
|
|
536
|
+
logToStderr(`ready (readOnly=${readOnly}, target=${explicitTarget ? 'remote' : 'local'})`)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const isDirectRun = isEntryPoint(import.meta.url)
|
|
540
|
+
if (isDirectRun) {
|
|
541
|
+
main().catch((err) => {
|
|
542
|
+
logToStderr('fatal:', getErrorMessage(err))
|
|
543
|
+
process.exit(1)
|
|
544
|
+
})
|
|
545
|
+
}
|
|
@@ -96,7 +96,17 @@ const FORBIDDEN_SECRET_KEYS = Object.freeze(['apiKey', 'api_key', 'key', 'token'
|
|
|
96
96
|
// Keys an entry is allowed to carry. Anything else gets an
|
|
97
97
|
// "(will be ignored)" warning so typos (`model` vs `defaultModel`)
|
|
98
98
|
// surface at startup instead of silently doing nothing.
|
|
99
|
-
|
|
99
|
+
//
|
|
100
|
+
// #7547: exported and named `*_ENTRY_KEYS` so the CONFIG.md doc gate
|
|
101
|
+
// (packages/server/tests/config-supported-keys-docs.test.js) compares the
|
|
102
|
+
// entry shape documented on the `providers` row against THIS set. It is
|
|
103
|
+
// deliberately not `*_SUPPORTED_KEYS`: that suffix is the gate's registry for
|
|
104
|
+
// config BLOCKS (a "Recognised sub-keys" row + a warnUnknownKeys call site per
|
|
105
|
+
// block), and an array ENTRY is neither. The gate sweeps `*_ENTRY_KEYS`
|
|
106
|
+
// declarations separately, so a new entry roster is still picked up rather than
|
|
107
|
+
// escaping. Shared by `anthropicCompatible` and `openaiCompatible` (one
|
|
108
|
+
// validator, two block labels).
|
|
109
|
+
export const COMPATIBLE_ENTRY_KEYS = new Set([
|
|
100
110
|
'id', 'label', 'baseUrl', 'apiKeyEnv', 'credentialsKey',
|
|
101
111
|
'defaultModel', 'models', 'pricing', 'contextWindow', 'modelDiscovery',
|
|
102
112
|
])
|
|
@@ -162,7 +172,7 @@ function validateEntry(raw, path, seenIds, reservedIds, warnings) {
|
|
|
162
172
|
}
|
|
163
173
|
|
|
164
174
|
for (const key of Object.keys(raw)) {
|
|
165
|
-
if (!
|
|
175
|
+
if (!COMPATIBLE_ENTRY_KEYS.has(key) && !FORBIDDEN_SECRET_KEYS.includes(key)) {
|
|
166
176
|
warnings.push(`Unknown key '${path}.${key}' (will be ignored)`)
|
|
167
177
|
}
|
|
168
178
|
}
|
|
@@ -490,6 +500,22 @@ function validateCompatibleProviders(configKey, value, opts = {}) {
|
|
|
490
500
|
return { entries, warnings }
|
|
491
501
|
}
|
|
492
502
|
|
|
503
|
+
// Recognised sub-keys of the OBJECT form of the top-level `providers` block.
|
|
504
|
+
//
|
|
505
|
+
// #7319 — 'acp' is a KNOWN key here (so it doesn't warn as unrecognized), but
|
|
506
|
+
// its entries are validated by config.js directly via `validateAcpProviders`
|
|
507
|
+
// (acp-config.js), not here: acp-config.js already imports
|
|
508
|
+
// RESERVED_PROVIDER_IDS from this module, so importing back from acp-config.js
|
|
509
|
+
// here would be circular.
|
|
510
|
+
//
|
|
511
|
+
// #7449: hoisted out of validateProvidersConfigBlock and exported so the
|
|
512
|
+
// CONFIG.md doc gate (packages/server/tests/config-supported-keys-docs.test.js)
|
|
513
|
+
// reads the same roster the validator enforces. It is named
|
|
514
|
+
// `*_SUPPORTED_KEYS` deliberately — that suffix is what the gate's
|
|
515
|
+
// declaration sweep looks for, so a future sibling roster is picked up
|
|
516
|
+
// automatically instead of quietly escaping the comparison.
|
|
517
|
+
export const PROVIDERS_SUPPORTED_KEYS = new Set(['anthropicCompatible', 'openaiCompatible', 'allowAnyModel', 'acp'])
|
|
518
|
+
|
|
493
519
|
/**
|
|
494
520
|
* Validate the top-level `providers` value when it is an OBJECT (#5419).
|
|
495
521
|
* The legacy form — an array of provider-id strings written by
|
|
@@ -500,9 +526,8 @@ function validateCompatibleProviders(configKey, value, opts = {}) {
|
|
|
500
526
|
* @param {string[]} warnings - Accumulator the caller logs/returns
|
|
501
527
|
*/
|
|
502
528
|
export function validateProvidersConfigBlock(providers, warnings) {
|
|
503
|
-
const KNOWN_PROVIDER_BLOCK_KEYS = new Set(['anthropicCompatible', 'openaiCompatible', 'allowAnyModel'])
|
|
504
529
|
for (const key of Object.keys(providers)) {
|
|
505
|
-
if (!
|
|
530
|
+
if (!PROVIDERS_SUPPORTED_KEYS.has(key)) {
|
|
506
531
|
warnings.push(`Unknown key 'providers.${key}' (will be ignored)`)
|
|
507
532
|
}
|
|
508
533
|
}
|