@jbkjr/relay 0.0.0-stage → 1.2.2
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/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +201 -0
- package/LICENSES/README.md +19 -0
- package/LICENSES/codex-NOTICE.txt +6 -0
- package/README.md +393 -2
- package/SECURITY.md +145 -0
- package/adapters/briefs/claude.md +43 -0
- package/adapters/briefs/codex.md +56 -0
- package/adapters/briefs/models.json +33 -0
- package/adapters/build.mjs +8 -0
- package/adapters/claude/.claude-plugin/marketplace.json +13 -0
- package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/relay/agents/codex.md +21 -0
- package/adapters/claude/relay/agents/operator.md +21 -0
- package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
- package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
- package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
- package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
- package/adapters/claude/relay/skills/review/SKILL.md +21 -0
- package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
- package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
- package/adapters/codex/.agents/plugins/marketplace.json +20 -0
- package/adapters/codex/AGENTS.snippet.md +5 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
- package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
- package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
- package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
- package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
- package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
- package/adapters/generate.mjs +124 -0
- package/bin/relay +59 -0
- package/codex-pin.json +12 -0
- package/dist/backends/acp.js +1424 -0
- package/dist/backends/claude.js +890 -0
- package/dist/backends/cli-version.js +112 -0
- package/dist/backends/codex-app.js +1539 -0
- package/dist/backends/codex-daybreak.js +75 -0
- package/dist/backends/codex-env.js +656 -0
- package/dist/backends/codex-network.js +304 -0
- package/dist/backends/codex-pin.js +345 -0
- package/dist/backends/codex-shell-policy.js +182 -0
- package/dist/backends/codex-stage2.js +998 -0
- package/dist/backends/codex-subagents.js +47 -0
- package/dist/backends/codex.js +641 -0
- package/dist/backends/copilot.js +246 -0
- package/dist/backends/env.js +147 -0
- package/dist/backends/gemini.js +607 -0
- package/dist/backends/grok.js +337 -0
- package/dist/backends/index.js +8 -0
- package/dist/backends/native-temp.js +187 -0
- package/dist/backends/never-admission.js +90 -0
- package/dist/backends/run.js +67 -0
- package/dist/backends/stream.js +230 -0
- package/dist/backends/tool-discovery.js +15 -0
- package/dist/backends/types.js +264 -0
- package/dist/build-info.json +5 -0
- package/dist/cli.js +344 -0
- package/dist/confine/bridge.js +113 -0
- package/dist/confine/broker-core.js +76 -0
- package/dist/confine/broker-http.js +650 -0
- package/dist/confine/broker-names.js +9 -0
- package/dist/confine/broker.js +258 -0
- package/dist/confine/canary.js +380 -0
- package/dist/confine/diagnostics.js +122 -0
- package/dist/confine/gemini-tools-main.js +8 -0
- package/dist/confine/gemini-tools.js +181 -0
- package/dist/confine/hardlinks.js +58 -0
- package/dist/confine/harness-config.js +16 -0
- package/dist/confine/index.js +117 -0
- package/dist/confine/leases.js +217 -0
- package/dist/confine/paths.js +6 -0
- package/dist/confine/peer.js +115 -0
- package/dist/confine/port-policy.js +8 -0
- package/dist/confine/ports.js +365 -0
- package/dist/confine/private-root.js +208 -0
- package/dist/confine/probe-stage2.js +501 -0
- package/dist/confine/probe.js +1109 -0
- package/dist/confine/proxy.js +783 -0
- package/dist/confine/sbcheck.js +208 -0
- package/dist/confine/seatbelt-never.js +41 -0
- package/dist/confine/seatbelt-stage2.js +139 -0
- package/dist/confine/seatbelt.js +1129 -0
- package/dist/confine/sockets.js +36 -0
- package/dist/confine/turn-probe.js +19 -0
- package/dist/confine/turn.js +86 -0
- package/dist/core/adoption.js +124 -0
- package/dist/core/api-keys.js +423 -0
- package/dist/core/approvals.js +740 -0
- package/dist/core/build-identity.js +248 -0
- package/dist/core/caller.js +749 -0
- package/dist/core/calls.js +102 -0
- package/dist/core/claude-settings.js +1045 -0
- package/dist/core/config.js +453 -0
- package/dist/core/context.js +186 -0
- package/dist/core/db.js +753 -0
- package/dist/core/dispatch.js +110 -0
- package/dist/core/env-broker.js +505 -0
- package/dist/core/env-policy.js +182 -0
- package/dist/core/escalation-authority.js +76 -0
- package/dist/core/escalation-contract.js +13 -0
- package/dist/core/escalation-person-path.js +131 -0
- package/dist/core/escalation-policy.js +79 -0
- package/dist/core/escalation-runtime.js +135 -0
- package/dist/core/escalation-state.js +42 -0
- package/dist/core/escalations.js +191 -0
- package/dist/core/events.js +235 -0
- package/dist/core/executables.js +147 -0
- package/dist/core/extensions.js +645 -0
- package/dist/core/families.js +204 -0
- package/dist/core/git.js +657 -0
- package/dist/core/identity.js +113 -0
- package/dist/core/liveness.js +68 -0
- package/dist/core/mediated-network-provider.js +81 -0
- package/dist/core/never-checkpoint.js +76 -0
- package/dist/core/never-coverage.js +97 -0
- package/dist/core/never-network.js +49 -0
- package/dist/core/never-policy.js +302 -0
- package/dist/core/never-proxy-policy.js +109 -0
- package/dist/core/never-schema.js +61 -0
- package/dist/core/never-tools.js +56 -0
- package/dist/core/notices.js +48 -0
- package/dist/core/ops.js +959 -0
- package/dist/core/outcome.js +224 -0
- package/dist/core/params.js +32 -0
- package/dist/core/presence.js +174 -0
- package/dist/core/procs.js +546 -0
- package/dist/core/prompts.js +363 -0
- package/dist/core/protected-config.js +238 -0
- package/dist/core/raw-network.js +192 -0
- package/dist/core/redact.js +152 -0
- package/dist/core/refusal.js +33 -0
- package/dist/core/relay-command.js +310 -0
- package/dist/core/reported.js +3 -0
- package/dist/core/restart-overlay.js +651 -0
- package/dist/core/retention.js +1135 -0
- package/dist/core/secrets.js +329 -0
- package/dist/core/session-token.js +175 -0
- package/dist/core/session.js +744 -0
- package/dist/core/shell.js +2 -0
- package/dist/core/shipped-pin.js +47 -0
- package/dist/core/shown.js +42 -0
- package/dist/core/slots.js +67 -0
- package/dist/core/stage2-executors.js +453 -0
- package/dist/core/stage2-switch.js +5 -0
- package/dist/core/steering.js +149 -0
- package/dist/core/storage.js +358 -0
- package/dist/core/toml.js +175 -0
- package/dist/core/views.js +324 -0
- package/dist/core/wait.js +114 -0
- package/dist/core/wake.js +207 -0
- package/dist/core/watch.js +247 -0
- package/dist/core/worktree.js +213 -0
- package/dist/hosts/claude-desktop.js +274 -0
- package/dist/hosts/claude.js +249 -0
- package/dist/hosts/codex.js +345 -0
- package/dist/hosts/desktop-shared.js +20 -0
- package/dist/hosts/index.js +11 -0
- package/dist/hosts/types.js +4 -0
- package/dist/install/basics.js +18 -0
- package/dist/install/claude-init.js +133 -0
- package/dist/install/common.js +655 -0
- package/dist/install/doctor.js +635 -0
- package/dist/install/qualify-codex.js +205 -0
- package/dist/install.js +524 -0
- package/dist/mcp/elicit.js +209 -0
- package/dist/mcp/gateway.js +218 -0
- package/dist/mcp/host.js +253 -0
- package/dist/mcp/server.js +1124 -0
- package/dist/mcp/stdio.js +37 -0
- package/dist/modes/discussion.js +393 -0
- package/dist/modes/review.js +722 -0
- package/dist/native/relay-sbcheck +0 -0
- package/dist/targets/briefs.js +86 -0
- package/dist/targets/claude.js +94 -0
- package/dist/targets/codex.js +66 -0
- package/dist/targets/copilot.js +93 -0
- package/dist/targets/gemini.js +119 -0
- package/dist/targets/grok.js +126 -0
- package/dist/targets/index.js +192 -0
- package/dist/targets/types.js +18 -0
- package/dist/targets/verified.js +35 -0
- package/dist/worker.js +113 -0
- package/docs/UPGRADING.md +1518 -0
- package/docs/pinned-codex.md +333 -0
- package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
- package/experiments/stage2-redteam/lib/report.mjs +35 -0
- package/npm-shrinkwrap.json +1632 -0
- package/package.json +82 -4
- package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
- package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
- package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
- package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
- package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
- package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
- package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
- package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
- package/scripts/codex-qualify/main-module.mjs +14 -0
- package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
- package/scripts/codex-qualify/scratch-env.mjs +31 -0
- package/scripts/codex-qualify/session.mjs +96 -0
- package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
- package/test/codex-permissions.test.ts +875 -0
- package/test/fixtures/boundary-probes.mjs +17 -0
- package/test/fixtures/denial-stream-host.mjs +7 -0
- package/test/fixtures/families.json +246 -0
- package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
- package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
- package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
- package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
- package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
- package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
- package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
- package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
- package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
- package/test/fixtures/link-parent.mjs +6 -0
- package/test/fixtures/mediated-command.cjs +72 -0
- package/test/fixtures/native-skill-isolation.json +280 -0
- package/test/fixtures/pinned-codex-app-server.mjs +25 -0
- package/test/fixtures/qualified-ext-adapters.mjs +36 -0
- package/test/fixtures/refusals/README.md +52 -0
- package/test/fixtures/refusals/claude-source-result.json +7 -0
- package/test/fixtures/refusals/openai-app-capacity.json +24 -0
- package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
- package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
- package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
- package/test/fixtures/refusals/openai-review-capacity.json +24 -0
- package/test/fixtures/relay-0.2.0.sql +57 -0
- package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
- package/test/fixtures/relay-0.9.1.sql +340 -0
- package/test/fixtures/slow-boundary-probes.mjs +37 -0
- package/test/fixtures/stable-surfaces/config.json +1122 -0
- package/test/fixtures/stable-surfaces/escalation.json +128 -0
- package/test/fixtures/stable-surfaces/events.json +37 -0
- package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
- package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
- package/test/fixtures/stable-surfaces/notice.txt +1 -0
- package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
- package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
- package/test/fixtures/stable-surfaces/registry.json +49 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
- package/test/fixtures/stable-surfaces/tools.json +716 -0
- package/test/fixtures/stable-surfaces/usage.txt +46 -0
- package/test/fixtures/stage2-acp-native.mjs +138 -0
- package/test/fixtures/stage2-app-server.mjs +23 -0
- package/test/fixtures/stage2-catalog.json +91 -0
- package/test/fixtures/stage2-hostile-web.mjs +35 -0
- package/test/fixtures/stage2-native-network.mjs +62 -0
- package/test/fixtures/stage2-worker.ts +87 -0
- package/test/fixtures/status-views/expected.json +7825 -0
- package/test/fixtures/status-views/registries.json +1 -0
- package/test/fixtures/steering.json +209 -0
- package/test/helpers.ts +740 -0
- package/test/host-env.ts +7 -0
- package/test/keychain-decoy.ts +197 -0
- package/test/live-scope.ts +44 -0
- package/test/mediated-network.test.ts +192 -0
- package/test/mediated-proxy.test.ts +264 -0
- package/test/native-temp-alias.ts +10 -0
- package/test/never-policy.test.ts +629 -0
- package/test/never-tools.test.ts +136 -0
- package/test/process-home.ts +18 -0
- package/test/proxy.test.ts +531 -0
- package/test/restart-overlay-live.test.ts +85 -0
- package/test/restart-overlay-profile.test.ts +66 -0
- package/test/restart-overlay.test.ts +416 -0
- package/test/stable-surfaces.test.ts +249 -0
- package/test/stage2-escalation-live.test.ts +544 -0
- package/test/stage2-escalation-qualification.test.ts +170 -0
- package/test/stage2-escalation.test.ts +747 -0
- package/test/stage2-executor.test.ts +849 -0
- package/test/stage2-grant.test.ts +603 -0
- package/test/stage2-native-live.test.ts +647 -0
- package/test/stage2-network-decisions.test.ts +70 -0
- package/test/stage2-probe.test.ts +845 -0
- package/test/stage2-standing-live.test.ts +203 -0
- package/test/stubs/broker-host.mjs +59 -0
- package/test/stubs/broker-peer.mjs +20 -0
- package/test/stubs/confined-harness.mjs +91 -0
- package/test/stubs/ext-broken-server.mjs +2 -0
- package/test/stubs/ext-odd-server.mjs +21 -0
- package/test/stubs/ext-server.mjs +31 -0
- package/test/stubs/fake-host-cli.mjs +218 -0
- package/test/stubs/procargs.mjs +30 -0
- package/test/stubs/stub-acp +4 -0
- package/test/stubs/stub-agent.mjs +322 -0
- package/test/stubs/stub-claude +4 -0
- package/test/stubs/stub-codex +4 -0
- package/test/stubs/targets/acp.mjs +307 -0
- package/test/stubs/targets/claude.mjs +149 -0
- package/test/stubs/targets/codex.mjs +479 -0
- package/test/stubs/targets/gemini.mjs +604 -0
- package/test/temp-root.ts +11 -0
- package/test/wp4-adapters.test.ts +353 -0
- package/test/wp4-interlock.test.ts +136 -0
|
@@ -0,0 +1,890 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { assertNeverAdapter } from "./never-admission.js";
|
|
3
|
+
import { neverFloorApplies } from "../core/never-coverage.js";
|
|
4
|
+
import { neverProfileInputs } from "../core/never-policy.js";
|
|
5
|
+
import { anthropicRefusal } from "../core/refusal.js";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import net from "node:net";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { privateStateRoot } from "../confine/private-root.js";
|
|
11
|
+
import { relaySocketsDir } from "../confine/sockets.js";
|
|
12
|
+
import { HARNESS_CONFIG } from "../confine/seatbelt.js";
|
|
13
|
+
import { nativeTemp } from "./native-temp.js";
|
|
14
|
+
import { configProtection, relayWriteProtected, relayCredentialProtected, relayCodexProtected } from "../core/protected-config.js";
|
|
15
|
+
import { keyAuthority, keyPathsToDeny } from "../core/api-keys.js";
|
|
16
|
+
import { managedNetworkProblem, managedSettings, managedSettingsRefusal, settingsEnvProblem } from "../core/claude-settings.js";
|
|
17
|
+
import { git } from "../core/git.js";
|
|
18
|
+
import { authFor, canonical, relayHome } from "../core/config.js";
|
|
19
|
+
import { claudeSkillNames, mcpFileNames, SKILLS_PLUGIN } from "../core/extensions.js";
|
|
20
|
+
import { CONTEXT_DIR } from "../core/context.js";
|
|
21
|
+
import { writing } from "../core/storage.js";
|
|
22
|
+
import { agentEnv, hostSession } from "./env.js";
|
|
23
|
+
import { afterTurn, streamTurn } from "./stream.js";
|
|
24
|
+
import { openTurnProxy } from "../confine/turn.js";
|
|
25
|
+
import { activityOf, usageFrom, relayServerCommand, turnPolicy } from "./types.js";
|
|
26
|
+
import { installedVersion } from "./cli-version.js";
|
|
27
|
+
import { VERIFIED } from "../targets/verified.js";
|
|
28
|
+
/** Explicit disables, also used by the scratch native-skill probe. See the version evidence below. */
|
|
29
|
+
export const CLAUDE_BUILTIN_PLUGINS = [
|
|
30
|
+
"cc-plugin-agents-md", "cc-plugin-claude-test", "cc-plugin-diff", "cc-plugin-easel",
|
|
31
|
+
"cc-plugin-mermaid", "cc-plugin-mods-guide", "cc-plugin-plugin-authoring", "cc-plugin-privacy",
|
|
32
|
+
"cc-plugin-responsive-mode", "cc-plugin-sec-default", "cc-plugin-telemetry", "cc-plugin-tips",
|
|
33
|
+
"cc-plugin-you-should-know", "claude-platform",
|
|
34
|
+
];
|
|
35
|
+
/**
|
|
36
|
+
* The one built-in relay leaves on (decided 2026-11-16): a deny-only tool.check hook that refuses a
|
|
37
|
+
* call putting the signed-in account's email into a client's identity (a User-Agent, a From header,
|
|
38
|
+
* git's user.email, an SEC EDGAR identity), which an interactive Claude Code session has and relay
|
|
39
|
+
* has no equivalent of. It stays in CLAUDE_BUILTIN_PLUGINS, so the release watcher keeps comparing it.
|
|
40
|
+
* Kept only on the versions in VERIFIED.claudePrivacyPlugin, whose copy of it relay has read: a hook
|
|
41
|
+
* module with the fs.list, fs.read and session.identity calls whose tool.check hook decides only
|
|
42
|
+
* "deny", from 2.1.326 also a session.identity hook that only refuses or withholds the identity it is
|
|
43
|
+
* asked for, and no skills, MCP servers, agents, commands or tools (docs/research/claude-builtin-plugins.md).
|
|
44
|
+
* On any other version, or one relay cannot read, it is disabled as before.
|
|
45
|
+
*/
|
|
46
|
+
export const CLAUDE_KEPT_BUILTIN = "cc-plugin-privacy";
|
|
47
|
+
/** Whether relay leaves CLAUDE_KEPT_BUILTIN on for Claude Code `version` (null: unreadable, so no). */
|
|
48
|
+
export function keepsPrivacyPlugin(version) {
|
|
49
|
+
const v = typeof version === "string" ? version : version?.join(".");
|
|
50
|
+
return typeof v === "string" && VERIFIED.claudePrivacyPlugin.includes(v);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Shared by real launches and doctor's init-only probe; unfamiliar plugins still fail closed.
|
|
54
|
+
* `version` is the Claude Code version the launch will run (installedVersion), which decides only
|
|
55
|
+
* whether CLAUDE_KEPT_BUILTIN is left on; the init report is checked against its own version.
|
|
56
|
+
*/
|
|
57
|
+
export function claudeSkillIsolation(cwd, env, version = null) {
|
|
58
|
+
const keep = keepsPrivacyPlugin(version);
|
|
59
|
+
return {
|
|
60
|
+
disableBundledSkills: true,
|
|
61
|
+
// The built-in registry of the versions in VERIFIED.claudeBuiltinPlugins (targets/verified.ts;
|
|
62
|
+
// 2.1.303's Tce, 2.1.308's Lpe: the same twelve; 2.1.325's pRe: those twelve, cc-plugin-privacy
|
|
63
|
+
// and claude-platform, the one name without the cc-plugin- prefix); older versions accept the
|
|
64
|
+
// extra false entries. cc-plugin-privacy is a deny-only tool.check hook; it takes its enabled
|
|
65
|
+
// state from trusted settings only, flagSettings (this file) among them, so this false holds
|
|
66
|
+
// unless managed settings enable it. On a version in VERIFIED.claudePrivacyPlugin it is left out
|
|
67
|
+
// of this list, so its own default (on) applies, as in an interactive session: the person's or an
|
|
68
|
+
// organisation's settings can still turn it off. docs/research/claude-builtin-plugins.md.
|
|
69
|
+
enabledPlugins: Object.fromEntries(CLAUDE_BUILTIN_PLUGINS.filter((name) => !(keep && name === CLAUDE_KEPT_BUILTIN))
|
|
70
|
+
.map((name) => [`${name}@builtin`, false])),
|
|
71
|
+
skillOverrides: Object.fromEntries([...claudeSkillNames(cwd, env), "doctor", "plugin-authoring"].map((name) => [name, "off"])),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** Native shell and file tools consume the same final floor. Settings variants are gated above. */
|
|
75
|
+
export function applyClaudeNeverPolicy(policy, sandbox, denyRules) {
|
|
76
|
+
const floor = neverProfileInputs(policy);
|
|
77
|
+
const filesystem = sandbox.filesystem;
|
|
78
|
+
const writes = [...floor.denyAll, ...floor.denyWrite];
|
|
79
|
+
filesystem.denyRead = [...new Set([...(filesystem.denyRead ?? []), ...floor.denyAll])];
|
|
80
|
+
filesystem.denyWrite = [...new Set([...(filesystem.denyWrite ?? []), ...writes])];
|
|
81
|
+
sandbox.allowUnsandboxedCommands = false;
|
|
82
|
+
for (const [tool, paths] of [["Read", floor.denyAll], ["Edit", writes]])
|
|
83
|
+
for (const p of paths) {
|
|
84
|
+
const escaped = p.replace(/([*?[\]{}!\\])/g, "\\$1");
|
|
85
|
+
denyRules.push(`${tool}(/${escaped})`, `${tool}(/${escaped}/**)`);
|
|
86
|
+
}
|
|
87
|
+
if (policy.hosts.length)
|
|
88
|
+
denyRules.push("WebSearch", "WebFetch");
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* How the parent session identifies and configures itself; a launched agent is its own session.
|
|
92
|
+
* CLAUDE_AUTO_BACKGROUND_TASKS too: under claude -p it moves an MCP call still running after two
|
|
93
|
+
* minutes to the background, and -p then ends the turn without its result and stops the call
|
|
94
|
+
* (Claude Code 2.1.302, experiments/answers.md), which would drop the agent's own waits on relay.
|
|
95
|
+
*/
|
|
96
|
+
const AUTH = /^CLAUDE_CODE_(USE_|OAUTH_TOKEN|SKIP_)/;
|
|
97
|
+
const scrub = (k) => k === "CLAUDECODE" || k === "CLAUDE_AGENT_SDK_VERSION" || k === "CLAUDE_AUTO_BACKGROUND_TASKS" || (k.startsWith("CLAUDE_CODE_") && !AUTH.test(k));
|
|
98
|
+
/**
|
|
99
|
+
* The deny rules in the person's own Claude Code settings, which a launched agent that loads none
|
|
100
|
+
* of their settings would otherwise go without. Only permissions.deny is taken from the file:
|
|
101
|
+
* allow and ask rules, directories, env, apiKeyHelper and the rest are neither kept nor passed on.
|
|
102
|
+
* A deny rule can only take something away from a job. A file relay cannot read, or whose deny
|
|
103
|
+
* list it cannot make sense of, stops the launch: the person expects those rules to hold.
|
|
104
|
+
*/
|
|
105
|
+
export function userDenyRules(env = process.env) {
|
|
106
|
+
// Where Claude Code looks for user settings; the launched agent gets the same CLAUDE_CONFIG_DIR.
|
|
107
|
+
const dir = path.resolve(env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"));
|
|
108
|
+
const file = path.join(dir, "settings.json");
|
|
109
|
+
const cannot = (why) => new Error(`relay carries the deny rules in your Claude Code settings (${file}) to every Claude it launches, and ${why}, so it does not launch Claude. Fix the file, or move it aside`);
|
|
110
|
+
let text;
|
|
111
|
+
try {
|
|
112
|
+
text = fs.readFileSync(file, "utf8");
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
if (e.code === "ENOENT")
|
|
116
|
+
return [];
|
|
117
|
+
throw cannot(`could not read the file (${e.code ?? "error"})`);
|
|
118
|
+
}
|
|
119
|
+
let parsed;
|
|
120
|
+
try {
|
|
121
|
+
parsed = JSON.parse(text);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// The parser's own message quotes the file, which may hold a key.
|
|
125
|
+
throw cannot("the file is not valid JSON");
|
|
126
|
+
}
|
|
127
|
+
const obj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
128
|
+
if (!obj(parsed))
|
|
129
|
+
throw cannot("the file does not hold a JSON object");
|
|
130
|
+
const permissions = parsed.permissions;
|
|
131
|
+
if (permissions === undefined)
|
|
132
|
+
return [];
|
|
133
|
+
if (!obj(permissions))
|
|
134
|
+
throw cannot('its "permissions" is not an object');
|
|
135
|
+
const deny = permissions.deny;
|
|
136
|
+
if (deny === undefined)
|
|
137
|
+
return [];
|
|
138
|
+
if (!Array.isArray(deny) || deny.some((r) => typeof r !== "string"))
|
|
139
|
+
throw cannot('its "permissions.deny" is not a list of strings');
|
|
140
|
+
// A Read or Edit path with one leading slash is relative to the file that holds the rule: in user
|
|
141
|
+
// settings that is their directory, in relay's settings file the turn's. Anchored absolutely, it
|
|
142
|
+
// means what it meant where it was written. The directory goes into a gitignore-style pattern, so
|
|
143
|
+
// one whose name would read as pattern syntax cannot be put there faithfully.
|
|
144
|
+
const anchored = /^(Read|Edit)\(\/(?!\/)/;
|
|
145
|
+
if (/[*?[\]{}!\\\r\n]/.test(dir) && deny.some((r) => anchored.test(r))) {
|
|
146
|
+
throw cannot(`a Read or Edit rule there is relative to ${dir}, whose name holds characters a rule would read as a pattern, so relay cannot anchor it there`);
|
|
147
|
+
}
|
|
148
|
+
return deny.map((r) => r.replace(anchored, (_, tool) => `${tool}(/${dir}/`));
|
|
149
|
+
}
|
|
150
|
+
/** Built-in tools of a read-only turn: no editing tools at all. */
|
|
151
|
+
const READ_TOOLS = ["Read", "Grep", "Glob", "Bash", "WebSearch", "WebFetch"];
|
|
152
|
+
/**
|
|
153
|
+
* Built-in tools of a write turn: what working on code takes, including Claude's own subagents.
|
|
154
|
+
* Left out on purpose are the tools that reach beyond the job: scheduling, remote triggers,
|
|
155
|
+
* messages to the user's other sessions, notifications.
|
|
156
|
+
*/
|
|
157
|
+
const WRITE_TOOLS = [
|
|
158
|
+
...READ_TOOLS, "Edit", "Write", "NotebookEdit", "LSP", "Monitor", "Skill", "ToolSearch",
|
|
159
|
+
"Task", "TaskCreate", "TaskGet", "TaskList", "TaskStop", "TaskUpdate",
|
|
160
|
+
];
|
|
161
|
+
// Kept as a public backend export for callers of the existing preflight helper.
|
|
162
|
+
export { settingsEnvProblem } from "../core/claude-settings.js";
|
|
163
|
+
/** A Claude model id as Claude Code reports it: claude-…, or through Bedrock (us.anthropic.claude-…) or Vertex (claude-…@date). */
|
|
164
|
+
const CLAUDE_MODEL = /^(?:[a-z]+\.)?(?:anthropic\.)?claude-[\w.:@[\]-]+$/i;
|
|
165
|
+
/**
|
|
166
|
+
* What Claude reports about itself as it starts, checked against what relay asked for. This is
|
|
167
|
+
* the nearest thing to reading back the effective configuration: settings relay does not control
|
|
168
|
+
* (an organisation's, say) can change any of it.
|
|
169
|
+
*/
|
|
170
|
+
function initProblem(event, spec) {
|
|
171
|
+
const cfg = spec.config;
|
|
172
|
+
// Which family answers is checked whatever else is: relay reaches other families only.
|
|
173
|
+
if (typeof event.model !== "string" || !CLAUDE_MODEL.test(event.model)) {
|
|
174
|
+
return typeof event.model === "string" ? `Claude reported the model ${JSON.stringify(event.model)}, which is not a Claude model` : "Claude did not report its model, so relay cannot tell which family of model would answer";
|
|
175
|
+
}
|
|
176
|
+
// So is what every turn loaded: the plugins and skills Claude reports do not
|
|
177
|
+
// depend on its permission mode, so a write turn under allow_dangerous is checked too.
|
|
178
|
+
const skillProblem = claudeSkillsProblem(event, spec.skills);
|
|
179
|
+
if (skillProblem)
|
|
180
|
+
return skillProblem;
|
|
181
|
+
const { dangerous, ask } = turnPolicy(spec);
|
|
182
|
+
if (dangerous)
|
|
183
|
+
return null;
|
|
184
|
+
// Each field must be there and be what relay asked for. Something Claude did not report is not something relay can rely on.
|
|
185
|
+
const mode = spec.access === "write" ? "acceptEdits" : ask ? "default" : "dontAsk";
|
|
186
|
+
if (event.permissionMode !== mode)
|
|
187
|
+
return `Claude reported permission mode ${JSON.stringify(event.permissionMode ?? null)}, not the ${mode} relay asked for`;
|
|
188
|
+
if (!Array.isArray(event.tools) || event.tools.some((t) => typeof t !== "string"))
|
|
189
|
+
return "Claude did not report its tools as relay expects";
|
|
190
|
+
const allowed = new Set(toolsFor(spec));
|
|
191
|
+
// Relay's own tools may be listed with the built-in ones.
|
|
192
|
+
const extra = event.tools.filter((t) => !allowed.has(t) && !t.startsWith("mcp__relay__"));
|
|
193
|
+
if (extra.length)
|
|
194
|
+
return `Claude started with tools relay did not give it (${extra.join(", ")})`;
|
|
195
|
+
if (!Array.isArray(event.mcp_servers))
|
|
196
|
+
return "Claude did not report its MCP servers as relay expects";
|
|
197
|
+
if (cfg.child_mcp === "relay-only") {
|
|
198
|
+
const servers = event.mcp_servers.map((m) => m?.name).filter((n) => n !== "relay");
|
|
199
|
+
if (servers.length)
|
|
200
|
+
return `Claude started with MCP servers relay did not give it (${servers.map(String).join(", ")})`;
|
|
201
|
+
}
|
|
202
|
+
// "none" is what Claude reports when it is signed in with an account and no key is in play.
|
|
203
|
+
if (authFor(cfg, "claude") === "login" && event.apiKeySource !== "none") {
|
|
204
|
+
return typeof event.apiKeySource === "string"
|
|
205
|
+
? `Claude is signing in with an API key (${event.apiKeySource}), not an account login, and relay is set not to run on API keys ("child_auth": "any" allows it)`
|
|
206
|
+
: 'Claude did not report how it is signed in, so relay cannot tell that it is not an API key ("child_auth": "any" skips this check)';
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
/** The built-in tools a turn gets: a read turn given skills also gets Skill, to load them. */
|
|
211
|
+
const toolsFor = (spec) => (spec.access === "write" ? WRITE_TOOLS : spec.skills ? [...READ_TOOLS, "Skill"] : READ_TOOLS);
|
|
212
|
+
/** The init report's lists a plugin could add to, besides its own entry in `plugins`. */
|
|
213
|
+
const PLUGIN_CONTRIBUTIONS = ["skills", "slash_commands", "agents", "mcp_servers", "tools"];
|
|
214
|
+
/**
|
|
215
|
+
* Whether `p`, an entry of `event`'s plugins, is CLAUDE_KEPT_BUILTIN as relay read it: the init
|
|
216
|
+
* report of a version in VERIFIED.claudePrivacyPlugin, the entry exactly the built-in's (name, path
|
|
217
|
+
* "builtin", source `<name>@builtin`, nothing else), and nothing of it among the skills, commands,
|
|
218
|
+
* agents, MCP servers or tools, each of which the report must list. Anything else is not admitted,
|
|
219
|
+
* and claudeSkillsProblem refuses it as it refuses any other plugin relay did not give.
|
|
220
|
+
*/
|
|
221
|
+
function keptBuiltin(event, p) {
|
|
222
|
+
if (typeof p !== "object" || p === null || Array.isArray(p))
|
|
223
|
+
return false;
|
|
224
|
+
const entry = p;
|
|
225
|
+
if (Object.keys(entry).sort().join() !== "name,path,source")
|
|
226
|
+
return false;
|
|
227
|
+
if (entry.name !== CLAUDE_KEPT_BUILTIN || entry.path !== "builtin" || entry.source !== `${CLAUDE_KEPT_BUILTIN}@builtin`)
|
|
228
|
+
return false;
|
|
229
|
+
if (typeof event.claude_code_version !== "string" || !keepsPrivacyPlugin(event.claude_code_version))
|
|
230
|
+
return false;
|
|
231
|
+
return PLUGIN_CONTRIBUTIONS.every((k) => Array.isArray(event[k]) && !JSON.stringify(event[k]).includes(CLAUDE_KEPT_BUILTIN));
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Every turn's init report must name exactly relay's package and its skills, or empty lists
|
|
235
|
+
* when it was given none. Bundled skills/plugins are disabled too: no name-only ambiguity. The one
|
|
236
|
+
* exception is CLAUDE_KEPT_BUILTIN, admitted only as keptBuiltin describes, at most once.
|
|
237
|
+
*/
|
|
238
|
+
export function claudeSkillsProblem(event, skills) {
|
|
239
|
+
const reported = event.plugins;
|
|
240
|
+
const listed = event.skills;
|
|
241
|
+
if (!Array.isArray(reported) || !Array.isArray(listed) || listed.some((x) => typeof x !== "string")) {
|
|
242
|
+
return "Claude did not report its skills and plugins, so relay cannot confirm that it loaded only the skills relay gave it";
|
|
243
|
+
}
|
|
244
|
+
const kept = reported.filter((p) => keptBuiltin(event, p));
|
|
245
|
+
if (kept.length > 1)
|
|
246
|
+
return "Claude reported duplicate skills or plugins relay did not give it";
|
|
247
|
+
const plugins = reported.filter((p) => !keptBuiltin(event, p));
|
|
248
|
+
const pkg = skills ? canonical(skills.dir) : null;
|
|
249
|
+
const foreign = plugins.filter((p) => !(pkg && p?.name === SKILLS_PLUGIN && typeof p.path === "string" && canonical(p.path) === pkg));
|
|
250
|
+
if (foreign.length) {
|
|
251
|
+
const builtin = (p) => typeof p?.source === "string" && p.source.endsWith("@builtin");
|
|
252
|
+
const bundled = foreign.filter(builtin).map((p) => String(p?.name));
|
|
253
|
+
const other = foreign.filter((p) => !builtin(p)).map((p) => String(p?.name));
|
|
254
|
+
return [
|
|
255
|
+
...(other.length ? [`Claude started with plugins relay did not give it (${other.join(", ")})`] : []),
|
|
256
|
+
...(bundled.length ? [`Claude started with plugins bundled with this Claude Code version that relay does not yet disable (${bundled.join(", ")}). Update relay or pin Claude Code to a tested version`] : []),
|
|
257
|
+
].join(". ");
|
|
258
|
+
}
|
|
259
|
+
if (pkg && plugins.length === 0)
|
|
260
|
+
return "Claude did not report relay's skills plugin at its package path";
|
|
261
|
+
if (new Set(listed).size !== listed.length || plugins.length > (pkg ? 1 : 0))
|
|
262
|
+
return "Claude reported duplicate skills or plugins relay did not give it";
|
|
263
|
+
const want = (skills?.names ?? []).map((n) => `${SKILLS_PLUGIN}:${n}`);
|
|
264
|
+
const missing = want.filter((w) => !listed.includes(w));
|
|
265
|
+
if (missing.length)
|
|
266
|
+
return `Claude did not load the skills relay gave it (${missing.join(", ")})`;
|
|
267
|
+
const stray = listed.filter((x) => !want.includes(x));
|
|
268
|
+
if (stray.length)
|
|
269
|
+
return `Claude started with skills relay did not give it (${stray.join(", ")})`;
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* The notice Claude Code puts on a headless session's stream when it refused a fast request and
|
|
274
|
+
* retried it at standard speed: usage credits run out, an organisation's spend cap reached
|
|
275
|
+
* (2.1.302: a system notification with this key, once per turn; code.claude.com/docs/en/fast-mode,
|
|
276
|
+
* 2026-10-17). Its result then still says fast mode is on, and need not say the speed it ran at.
|
|
277
|
+
*/
|
|
278
|
+
const OVERAGE_NOTICE = "fast-mode-overage-rejected";
|
|
279
|
+
/**
|
|
280
|
+
* What Claude's result says about fast mode (Claude Code 2.1.302: fast_mode_state,
|
|
281
|
+
* fast_mode_disabled_reason, usage.speed), with the turn's fast-mode notice from its stream, or
|
|
282
|
+
* null when it says nothing.
|
|
283
|
+
*/
|
|
284
|
+
function speedReport(event, notices = []) {
|
|
285
|
+
const str = (v) => (typeof v === "string" && v ? v : undefined);
|
|
286
|
+
const r = {
|
|
287
|
+
fast_mode_state: str(event.fast_mode_state), fast_mode_disabled_reason: str(event.fast_mode_disabled_reason),
|
|
288
|
+
speed: str(event.usage?.speed),
|
|
289
|
+
notice: notices.length ? [...new Set(notices)].join("; ") : undefined,
|
|
290
|
+
};
|
|
291
|
+
for (const k of Object.keys(r))
|
|
292
|
+
if (r[k] === undefined)
|
|
293
|
+
delete r[k];
|
|
294
|
+
return Object.keys(r).length ? r : null;
|
|
295
|
+
}
|
|
296
|
+
/** Claude's fast_mode_disabled_reason values (Claude Code 2.1.302), in words, for the warning that says a fast turn ran slower. */
|
|
297
|
+
const FAST_MODE_REASONS = {
|
|
298
|
+
extra_usage_disabled: "usage credits are off for this account, and fast mode is billed to them",
|
|
299
|
+
// 2.1.302: Opus, which fast mode runs, is not among the organisation's allowed models (and the model
|
|
300
|
+
// that ran is not an allowed fast one either), or the API refused fast mode for the model.
|
|
301
|
+
model_not_allowed: "fast mode is not allowed for this model here: Opus is not among the organisation's allowed models, or Claude's API refused fast mode for the model",
|
|
302
|
+
free: "fast mode needs a paid plan",
|
|
303
|
+
preference: "fast mode is turned off for this organisation",
|
|
304
|
+
network_error: "Claude could not check fast mode's availability",
|
|
305
|
+
not_first_party: "fast mode needs Anthropic's own API",
|
|
306
|
+
disabled_by_env: "fast mode is turned off in its environment",
|
|
307
|
+
sdk_opt_in_required: "this session did not opt in to fast mode",
|
|
308
|
+
pending: "Claude was still checking whether fast mode is available",
|
|
309
|
+
unknown: "fast mode is unavailable",
|
|
310
|
+
};
|
|
311
|
+
/**
|
|
312
|
+
* What to tell the caller when a turn asked for fast mode and Claude says it ran at standard
|
|
313
|
+
* speed, in part or throughout, or null when it ran fast. Only Claude knows, once it has run (its
|
|
314
|
+
* account's usage credits, a rate limit's cooldown), so this is said with the result, with
|
|
315
|
+
* Claude's own reason, or its notice where it gave no reason (usage credits run out, which leaves
|
|
316
|
+
* fast mode on in its result). Claude saying nothing is said too: relay cannot tell the turn ran fast.
|
|
317
|
+
*/
|
|
318
|
+
function ranSlower(report) {
|
|
319
|
+
if (!report)
|
|
320
|
+
return "fast was asked for, but Claude did not report the speed this turn ran at, so relay cannot tell that it ran fast.";
|
|
321
|
+
const reason = report.fast_mode_disabled_reason;
|
|
322
|
+
const said = [
|
|
323
|
+
reason ? `Claude's reason: ${reason}, ${FAST_MODE_REASONS[reason] ?? "not one relay knows"}` : "",
|
|
324
|
+
report.notice ? `Claude's notice: ${JSON.stringify(report.notice)}` : "",
|
|
325
|
+
].filter(Boolean);
|
|
326
|
+
const why = said.length ? ` (${said.join("; ")})` : "";
|
|
327
|
+
const cooldown = report.fast_mode_state === "cooldown";
|
|
328
|
+
if (report.speed === "fast" || (report.speed === undefined && report.fast_mode_state === "on")) {
|
|
329
|
+
// The notice says Claude refused a fast request and retried it at standard, whatever its result says.
|
|
330
|
+
if (report.notice)
|
|
331
|
+
return `fast was asked for, but Claude refused fast mode for this turn's requests and ran them at standard speed${report.speed === "fast" ? ", in part at least" : ""}${why}.`;
|
|
332
|
+
return cooldown ? `fast was asked for, and Claude's fast mode went into cooldown after a rate limit, so part of this turn may have run at standard speed${why}.` : null;
|
|
333
|
+
}
|
|
334
|
+
return `fast was asked for, but Claude ran this turn at standard speed${cooldown ? ", its fast mode cooling down after a rate limit" : ""}${why}.`;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Headless Claude Code: one `claude -p` process per turn, stream-json out, prompt on stdin.
|
|
338
|
+
* Continuity comes from --session-id on the first turn and --resume afterwards.
|
|
339
|
+
*/
|
|
340
|
+
const claude = {
|
|
341
|
+
prepare(spec, tmpDir, agentTmp = tmpDir) {
|
|
342
|
+
assertNeverAdapter(spec);
|
|
343
|
+
// The agent's environment, built and checked first (review C6): its endpoint is refused before anything else is.
|
|
344
|
+
const env = agentEnv(spec, scrub, hostSession() ? ' Under the desktop app or another Agent SDK host, relay removes it itself where Claude signs in with its login ("child_auth": "login").' : "");
|
|
345
|
+
// 2.1.302's Jj and fl gates: no silent fallback or same-model refusal retry.
|
|
346
|
+
env.CLAUDE_CODE_DISABLE_REFUSAL_RETRY = "1";
|
|
347
|
+
env.CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK = "1";
|
|
348
|
+
// Claude measures CLAUDE_CODE_TMPDIR as given and resolves it only for its sandbox's allow list.
|
|
349
|
+
env.TMPDIR = agentTmp;
|
|
350
|
+
env.CLAUDE_CODE_TMPDIR = agentTmp;
|
|
351
|
+
spec.checkEnvironment?.(env);
|
|
352
|
+
const managed = managedSettings();
|
|
353
|
+
if (managed && spec.neverPolicy && neverFloorApplies("claude", spec.config))
|
|
354
|
+
throw new Error("never: managed Claude settings can override the checked floor; this settings variant is unavailable. Use a qualified isolated settings route.");
|
|
355
|
+
// Kept for a launch without a never policy (never-admission.ts screens nothing then); a floored
|
|
356
|
+
// one was refused just above, whatever claude_managed_settings says.
|
|
357
|
+
if (managed && spec.config.claude_managed_settings === "refuse")
|
|
358
|
+
throw new Error(managedSettingsRefusal(managed));
|
|
359
|
+
const unvetted = settingsEnvProblem(spec.config, managed);
|
|
360
|
+
if (unvetted)
|
|
361
|
+
throw new Error(unvetted);
|
|
362
|
+
if (spec.config.claude_settings_env === "accept" && settingsEnvProblem({ ...spec.config, claude_settings_env: "refuse" }, managed))
|
|
363
|
+
spec.onWaived?.("claude_settings_env");
|
|
364
|
+
// Under "inherit" Claude loads the user's settings, deny rules and all, by itself.
|
|
365
|
+
const deny = spec.config.child_settings === "isolated" ? userDenyRules(env) : [];
|
|
366
|
+
// The version gate's read (cli-version.ts), with the environment Claude is launched with. It
|
|
367
|
+
// decides only whether relay leaves CLAUDE_KEPT_BUILTIN on; the init report is checked by its own.
|
|
368
|
+
// A read that fails in any way counts as unreadable: the plugin is then disabled, the launch not refused here.
|
|
369
|
+
let version = null;
|
|
370
|
+
try {
|
|
371
|
+
version = installedVersion("claude", spec.config.targets.claude.bin, env);
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
version = null;
|
|
375
|
+
}
|
|
376
|
+
// Relay picks the session id up front so it is known before the process reports anything.
|
|
377
|
+
return { newSessionId: spec.sessionId ? undefined : crypto.randomUUID(), deny, env, tmpDir, version };
|
|
378
|
+
},
|
|
379
|
+
invocation(spec, prepared) {
|
|
380
|
+
const cfg = spec.config;
|
|
381
|
+
const args = ["-p", "--output-format", "stream-json", "--verbose"];
|
|
382
|
+
if (spec.sessionId)
|
|
383
|
+
args.push("--resume", spec.sessionId);
|
|
384
|
+
else
|
|
385
|
+
args.push("--session-id", prepared.newSessionId);
|
|
386
|
+
// MCP: the injected entry is named "relay", which replaces a user-level entry of that name.
|
|
387
|
+
const server = spec.relay ? relayServerCommand(spec.relay) : null;
|
|
388
|
+
const mcpFile = path.join(spec.dir, "claude-mcp.json");
|
|
389
|
+
// A launch file that cannot be written refuses the turn, said as the write it was (storage.ts writing).
|
|
390
|
+
writing(() => fs.writeFileSync(mcpFile, JSON.stringify({ mcpServers: server ? { relay: { type: "stdio", ...server } } : {} }, null, 2)));
|
|
391
|
+
args.push("--mcp-config", mcpFile);
|
|
392
|
+
if (cfg.child_mcp === "relay-only")
|
|
393
|
+
args.push("--strict-mcp-config");
|
|
394
|
+
// Only relay's own settings file (and any managed settings) applies, unless the user chose
|
|
395
|
+
// otherwise. Claude merges allow rules, extra directories and allowed domains from every
|
|
396
|
+
// settings file it loads into the sandbox, and reloads them while it runs, so a loaded file
|
|
397
|
+
// is a way to widen a job: the user's by accident, or one the job writes into its worktree.
|
|
398
|
+
if (cfg.child_settings === "isolated")
|
|
399
|
+
args.push("--setting-sources", "");
|
|
400
|
+
// The skills this turn was given come as a plugin of relay's own, for this session only, and
|
|
401
|
+
// the init report is checked against it (claudeSkillsProblem). Nothing goes into the person's ~/.claude.
|
|
402
|
+
if (spec.skills)
|
|
403
|
+
args.push("--plugin-dir", spec.skills.dir);
|
|
404
|
+
else
|
|
405
|
+
args.push("--disable-slash-commands");
|
|
406
|
+
// MCP auto-backgrounding off: a settings file's env (the user's under "inherit", an
|
|
407
|
+
// organisation's) can set CLAUDE_AUTO_BACKGROUND_TASKS, which the environment scrub above does
|
|
408
|
+
// not reach, and under -p it drops the agent's relay calls that run past two minutes (P-a). Zero
|
|
409
|
+
// turns it off, by Claude Code's documentation (code.claude.com/docs/en/mcp, 2026-10-17; not
|
|
410
|
+
// run), and this file outranks user, project and local settings; managed settings can still set it.
|
|
411
|
+
const settings = { env: { CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS: "0", TMPDIR: prepared.env.TMPDIR, CLAUDE_CODE_TMPDIR: prepared.env.TMPDIR, CLAUDE_CODE_DISABLE_REFUSAL_RETRY: "1", CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: "1" } };
|
|
412
|
+
// 2.1.302: bundled skills and the built-in plugins are separate. In inherited settings,
|
|
413
|
+
// skillOverrides also hides user/repository skills without touching their source files.
|
|
414
|
+
// The init report must contain exactly our package; new/managed/hidden roots fail closed.
|
|
415
|
+
Object.assign(settings, claudeSkillIsolation(spec.cwd, prepared.env, prepared.version ?? null));
|
|
416
|
+
if (!cfg.child_hooks)
|
|
417
|
+
settings.disableAllHooks = true;
|
|
418
|
+
// Speed, pinned on every turn: fast mode on only when asked for (relay's settings file is
|
|
419
|
+
// Claude Code's flag settings, which outrank any settings of the person's that load, and a
|
|
420
|
+
// fastMode there is also the opt-in a headless session needs), off otherwise.
|
|
421
|
+
settings.fastMode = spec.speed === "fast";
|
|
422
|
+
// With escalation, anything that would prompt is sent to relay's permission tool, which asks
|
|
423
|
+
// the root session. Without it, such actions are denied on the spot.
|
|
424
|
+
const { dangerous, ask, network, writePaths: extra } = turnPolicy(spec);
|
|
425
|
+
const allowed = server ? ["mcp__relay"] : [];
|
|
426
|
+
if (network)
|
|
427
|
+
allowed.push("WebSearch", "WebFetch");
|
|
428
|
+
// failIfUnavailable: without it, a sandbox that cannot start means commands run unsandboxed.
|
|
429
|
+
const never = spec.neverPolicy && neverFloorApplies("claude", cfg) ? spec.neverPolicy : undefined;
|
|
430
|
+
const sandbox = { enabled: true, failIfUnavailable: true, autoAllowBashIfSandboxed: true, allowUnsandboxedCommands: never ? false : ask };
|
|
431
|
+
// Without a grant, the sandbox's own network question would go nowhere: under -p Claude Code
|
|
432
|
+
// answers it "user denied" at once and never sends it to the permission prompt tool (checked in
|
|
433
|
+
// Claude Code 2.1.301). strictAllowlist has the sandbox refuse by itself, saying the host is not
|
|
434
|
+
// on the allow list, so the agent is not told that a person refused.
|
|
435
|
+
// With the network, every connection the sandbox's commands make goes to relay's proxy for the
|
|
436
|
+
// turn (public mode, confine/proxy.ts), which reaches public addresses only: Claude Code's own
|
|
437
|
+
// proxy, under allowedDomains ["*"], dials loopback and LAN addresses for them, and its deny
|
|
438
|
+
// list cannot express a private range (relay 1.0.5; smoke/claude-network-probe.mjs checks it).
|
|
439
|
+
// Both ports are relay's, or Claude Code starts its own proxy for the one left out. Local binding
|
|
440
|
+
// and Unix sockets stay closed whatever other settings say (these outrank user settings under
|
|
441
|
+
// child_settings "inherit"; a merged allowUnixSockets list is the residual).
|
|
442
|
+
const closed = { allowLocalBinding: false, allowAllUnixSockets: false };
|
|
443
|
+
if (network && !dangerous && !prepared.proxy)
|
|
444
|
+
throw new Error("relay gives a Claude turn the network only through its own proxy, and none was opened for this turn");
|
|
445
|
+
sandbox.network = network && prepared.proxy
|
|
446
|
+
// strictAllowlist too: a Claude Code that ignored the external ports and started a proxy of its
|
|
447
|
+
// own would then refuse every host by itself (no allowedDomains), not ask, which -p answers "denied".
|
|
448
|
+
? { httpProxyPort: prepared.proxy.port, socksProxyPort: prepared.proxy.port, strictAllowlist: true, ...closed }
|
|
449
|
+
: { strictAllowlist: true, ...closed };
|
|
450
|
+
if (network && prepared.proxy) {
|
|
451
|
+
// The Claude process itself (its WebFetch, which runs outside the sandbox, and its model
|
|
452
|
+
// requests) is pointed at the same proxy, with the turn's token. NO_PROXY is empty here and in
|
|
453
|
+
// relay's settings, which outrank a user's settings env, but console-delivered settings relay
|
|
454
|
+
// cannot see can still exempt hosts; the runtime check (claudeBackend.start) proves only that
|
|
455
|
+
// some token request reached the model host through the proxy, not that every one did. SRT_DEBUG makes the
|
|
456
|
+
// sandbox report the proxy ports it uses, which relay checks (claudeProxyReport).
|
|
457
|
+
Object.assign(prepared.env, claudeProxyEnv(prepared.proxy));
|
|
458
|
+
// The start of each response as it streams (message_start), where relay checks the proxy before a tool can run.
|
|
459
|
+
args.push("--include-partial-messages");
|
|
460
|
+
Object.assign(settings.env, { NO_PROXY: "", no_proxy: "" });
|
|
461
|
+
}
|
|
462
|
+
// Ask rules outrank the user's own allow rules. Sandboxed commands are unaffected.
|
|
463
|
+
const askRules = [];
|
|
464
|
+
if (ask) {
|
|
465
|
+
args.push("--permission-prompt-tool", "mcp__relay__permission_prompt");
|
|
466
|
+
// Without this, an allow rule in the user's settings (say Bash(git fetch:*)) would let a
|
|
467
|
+
// matching command run outside the sandbox with no request.
|
|
468
|
+
askRules.push("Bash");
|
|
469
|
+
}
|
|
470
|
+
// child_web "ask": the host's web tools need a grant or an approval, whatever the user's own
|
|
471
|
+
// rules allow. (Where nothing can be asked, an ask rule amounts to a refusal.) So they do for a
|
|
472
|
+
// turn given MCP servers, whose requests only the person can allow (docs/extensions.md).
|
|
473
|
+
if ((cfg.child_web === "ask" || spec.extensionServers?.length) && !network)
|
|
474
|
+
askRules.push("WebSearch", "WebFetch");
|
|
475
|
+
// The user's deny rules outrank every allow and ask rule, relay's included.
|
|
476
|
+
const userDeny = prepared.deny;
|
|
477
|
+
// Relay's own deny rules for this turn: the edit tools' side of what the sandbox denies below.
|
|
478
|
+
const denyRules = [];
|
|
479
|
+
// Relay's control directory decides who may do what, and its config and the directories that
|
|
480
|
+
// decide which API key relay hands a key-only target (core/api-keys.ts keyAuthority) whose
|
|
481
|
+
// account that target runs on. No job may write there, whatever else it is given: a grant
|
|
482
|
+
// the session keeps from before relay refused one over them included.
|
|
483
|
+
const keyDirs = keyAuthority().dirs.flatMap(([, d]) => (fs.existsSync(d) ? [d, fs.realpathSync(d)] : [d]));
|
|
484
|
+
// And what relay runs outside any sandbox, and its PATH (protected-config.ts relayWriteProtected; review r_0c11d860 X1).
|
|
485
|
+
const codexPaths = relayCodexProtected(spec.config);
|
|
486
|
+
const protectedDirs = [...new Set([fs.realpathSync(relayHome()), privateStateRoot(), ...configProtection().paths, ...keyDirs, ...relayWriteProtected().map((x) => x.path), ...codexPaths.homes.map((x) => x.path), ...codexPaths.stores.map((x) => x.path)])];
|
|
487
|
+
const privatePattern = privateStateRoot().replace(/([*?[\]{}!\\])/g, "\\$1");
|
|
488
|
+
denyRules.push(`Edit(/${privatePattern})`, `Edit(/${privatePattern}/**)`);
|
|
489
|
+
// A path git reports for the turn's directory: in a job's worktree with the git directory the
|
|
490
|
+
// repository records for it (spec.gitEnv), never through the worktree's own `.git` file.
|
|
491
|
+
const gitPath = (flag) => {
|
|
492
|
+
const r = git(spec.cwd, ["rev-parse", flag], spec.gitEnv);
|
|
493
|
+
if (!r.ok || !r.out)
|
|
494
|
+
return null;
|
|
495
|
+
try {
|
|
496
|
+
return fs.realpathSync(path.resolve(spec.cwd, r.out));
|
|
497
|
+
}
|
|
498
|
+
catch {
|
|
499
|
+
return null;
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
if (dangerous) {
|
|
503
|
+
args.push("--dangerously-skip-permissions");
|
|
504
|
+
}
|
|
505
|
+
else if (spec.access === "write") {
|
|
506
|
+
// Edits are auto-approved inside cwd (the worktree); Bash runs inside the OS sandbox.
|
|
507
|
+
args.push("--permission-mode", "acceptEdits", "--tools", toolsFor(spec).join(","));
|
|
508
|
+
if (!ask)
|
|
509
|
+
args.push("--permission-prompts", "none");
|
|
510
|
+
// In the worktree itself, its `.git` file (which tells git where the repository is) and relay's
|
|
511
|
+
// identity directory: nothing in the job's work changes either, and relay reads both.
|
|
512
|
+
const top = spec.gitEnv?.GIT_WORK_TREE ?? gitPath("--show-toplevel");
|
|
513
|
+
// And the harness and developer-tool configuration that relay's own sandbox denies at the top
|
|
514
|
+
// of each writable root (confine/seatbelt.ts HARNESS_CONFIG): here the worktree and each granted
|
|
515
|
+
// directory, only at their top, as there. Claude Code 2.1.303 protects its own `.claude`
|
|
516
|
+
// settings, `.mcp.json` and git's internals by itself, but not `.codex`, `.agents`, `.gemini` or
|
|
517
|
+
// `.aws`, nor `.envrc` from the shell; a job's branch would carry what it planted there into the
|
|
518
|
+
// person's own agents once merged. On macOS each plain denyWrite path becomes
|
|
519
|
+
// `(deny file-write* (subpath P))`, which refuses creating a missing P too.
|
|
520
|
+
const configRoots = [top ?? fs.realpathSync(spec.cwd), ...extra];
|
|
521
|
+
const guarded = [...new Set([
|
|
522
|
+
...(top ? [path.join(top, ".git"), path.join(top, CONTEXT_DIR)] : []),
|
|
523
|
+
...configRoots.flatMap((root) => HARNESS_CONFIG.map((name) => path.join(root, name))),
|
|
524
|
+
])];
|
|
525
|
+
sandbox.filesystem = { denyWrite: [...protectedDirs, ...guarded], allowWrite: [prepared.tmpDir, ...extra] };
|
|
526
|
+
// The sandbox governs the shell; the edit tools follow permission rules ("//" starts an absolute
|
|
527
|
+
// path; a directory's name is escaped, so a granted one with `[` in it matches only itself).
|
|
528
|
+
for (const p of guarded) {
|
|
529
|
+
const escaped = p.replace(/([*?[\]{}!\\])/g, "\\$1");
|
|
530
|
+
denyRules.push(`Edit(/${escaped})`, `Edit(/${escaped}/**)`);
|
|
531
|
+
}
|
|
532
|
+
// The sandbox governs shell writes; --add-dir extends where the edit tools are auto-approved.
|
|
533
|
+
if (extra.length)
|
|
534
|
+
args.push("--add-dir", ...extra);
|
|
535
|
+
settings.sandbox = sandbox;
|
|
536
|
+
}
|
|
537
|
+
else {
|
|
538
|
+
// Read-only: the editing tools are absent. Bash runs in the OS sandbox with writes to the
|
|
539
|
+
// working directory and the repository's git directories denied, so the agent can run tests
|
|
540
|
+
// and inspect history without changing anything. The web tools are present; whether a given
|
|
541
|
+
// search or fetch runs is decided by the user's own rules, a network grant, or a request.
|
|
542
|
+
args.push("--permission-mode", ask ? "manual" : "dontAsk", "--tools", toolsFor(spec).join(","));
|
|
543
|
+
const deny = new Set([fs.realpathSync(spec.cwd), ...protectedDirs]);
|
|
544
|
+
for (const flag of ["--show-toplevel", "--git-common-dir", "--git-dir"]) {
|
|
545
|
+
const p = gitPath(flag);
|
|
546
|
+
if (p)
|
|
547
|
+
deny.add(p);
|
|
548
|
+
}
|
|
549
|
+
sandbox.filesystem = { denyWrite: [...deny], allowWrite: [prepared.tmpDir] };
|
|
550
|
+
settings.sandbox = sandbox;
|
|
551
|
+
}
|
|
552
|
+
if (spec.reviewReadDeny?.length && spec.access === "read" && !dangerous) {
|
|
553
|
+
// Both layers are needed: denyRead restricts Bash's subprocesses; Read deny rules cover
|
|
554
|
+
// Claude's built-in file tools. Only the independent review turn gets these extra denies.
|
|
555
|
+
// https://code.claude.com/docs/en/sandboxing#configure-sandboxing
|
|
556
|
+
// https://code.claude.com/docs/en/permissions#read-and-edit
|
|
557
|
+
const configHome = path.resolve(prepared.env.CLAUDE_CONFIG_DIR || path.join(prepared.env.HOME || os.homedir(), ".claude"));
|
|
558
|
+
const real = (dir) => { try {
|
|
559
|
+
return fs.realpathSync(dir);
|
|
560
|
+
}
|
|
561
|
+
catch {
|
|
562
|
+
return path.resolve(dir);
|
|
563
|
+
} };
|
|
564
|
+
const homes = spec.reviewReadDeny;
|
|
565
|
+
// Same-family reviewers share their caller's config home. Keep their own tool results,
|
|
566
|
+
// shell snapshots, skills, plugins and memory readable while denying conversation stores.
|
|
567
|
+
// JSONL globs include subagent transcripts and orphaned/superseded session copies.
|
|
568
|
+
// https://code.claude.com/docs/en/claude-directory#application-data
|
|
569
|
+
const conversation = ["projects/**/*.jsonl*", "projects/**/sessions-index.json", "history.jsonl", "debug", "paste-cache", "feedback-bundles", "feedback/drafts", "usage-data"];
|
|
570
|
+
const readDenies = homes.flatMap((home) => {
|
|
571
|
+
// Permission paths use // for absolute paths and gitignore patterns, unlike denyRead.
|
|
572
|
+
const escaped = home.replace(/([*?[\]{}!\\])/g, "\\$1");
|
|
573
|
+
const suffixes = real(home) === real(configHome) ? conversation : [""];
|
|
574
|
+
for (const suffix of suffixes) {
|
|
575
|
+
const pattern = path.join(escaped, suffix);
|
|
576
|
+
denyRules.push(`Read(/${pattern})`, `Read(/${pattern}/**)`);
|
|
577
|
+
}
|
|
578
|
+
return suffixes.map((suffix) => path.join(home, suffix));
|
|
579
|
+
});
|
|
580
|
+
sandbox.filesystem.denyRead = readDenies;
|
|
581
|
+
}
|
|
582
|
+
if (!dangerous) {
|
|
583
|
+
// Nor may a Claude turn read the API key relay hands a key-only target: the default key
|
|
584
|
+
// directory and a key file the local config moves elsewhere (core/api-keys.ts keyPathsToDeny,
|
|
585
|
+
// which relay's own sandbox denies to every agent it confines). Both layers, as above: the
|
|
586
|
+
// sandbox for the shell, Read deny rules for Claude's file tools. Relay does not hand Claude
|
|
587
|
+
// the key; this keeps a turn steered by what it reads from taking it. Relay's Codex permission
|
|
588
|
+
// profile reads everything, so a Codex turn still can (docs/gemini.md §2.6).
|
|
589
|
+
const keyReads = [...new Set(keyPathsToDeny().flatMap((p) => (fs.existsSync(p) ? [p, fs.realpathSync(p)] : [p])))];
|
|
590
|
+
// Nor relay's sockets directory (confine/sockets.ts), where a confined turn's broker keeps the
|
|
591
|
+
// file its own tool helper reads the turn's secret from (Gemini's tool discovery, Broker.secretFile);
|
|
592
|
+
// relay's sandbox denies the directory to every other turn. The secret alone gets nothing: the
|
|
593
|
+
// broker serves only its turn's own process tree. Only the sockets directory, not all of relay's
|
|
594
|
+
// private root, whose temp directories Claude's own turns use.
|
|
595
|
+
const sockets = relaySocketsDir();
|
|
596
|
+
const reads = [...keyReads, sockets, ...relayCredentialProtected(spec.config).map((p) => p.path)];
|
|
597
|
+
const filesystem = sandbox.filesystem;
|
|
598
|
+
filesystem.denyRead = [...new Set([...(filesystem.denyRead ?? []), ...reads])];
|
|
599
|
+
for (const p of reads) {
|
|
600
|
+
const escaped = p.replace(/([*?[\]{}!\\])/g, "\\$1");
|
|
601
|
+
denyRules.push(`Read(/${escaped})`, `Read(/${escaped}/**)`);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
// Relay's MCP definitions may hold credentials, which an agent with the network could use past
|
|
605
|
+
// relay's gate: no launched Claude agent reads them, by any name of the file (docs/extensions.md).
|
|
606
|
+
// Both layers again: the sandbox for Bash, a Read rule for Claude's own file tools.
|
|
607
|
+
const secrets = dangerous ? [] : mcpFileNames();
|
|
608
|
+
if (secrets.length) {
|
|
609
|
+
for (const f of secrets)
|
|
610
|
+
denyRules.push(`Read(/${f.replace(/([*?[\]{}!\\])/g, "\\$1")})`);
|
|
611
|
+
const filesystem = sandbox.filesystem;
|
|
612
|
+
filesystem.denyRead = [...(filesystem.denyRead ?? []), ...secrets];
|
|
613
|
+
}
|
|
614
|
+
if (never)
|
|
615
|
+
applyClaudeNeverPolicy(never, sandbox, denyRules);
|
|
616
|
+
const allDeny = [...userDeny, ...denyRules];
|
|
617
|
+
if (askRules.length || allDeny.length)
|
|
618
|
+
settings.permissions = { ...(allDeny.length ? { deny: allDeny } : {}), ...(askRules.length ? { ask: askRules } : {}) };
|
|
619
|
+
if (allowed.length && !dangerous)
|
|
620
|
+
args.push("--allowedTools", ...allowed);
|
|
621
|
+
const settingsFile = path.join(spec.dir, "claude-settings.json");
|
|
622
|
+
writing(() => fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2)));
|
|
623
|
+
args.push("--settings", settingsFile);
|
|
624
|
+
if (spec.model)
|
|
625
|
+
args.push("--model", spec.model);
|
|
626
|
+
if (spec.effort)
|
|
627
|
+
args.push("--effort", spec.effort);
|
|
628
|
+
return { command: cfg.targets.claude.bin, args, env: prepared.env };
|
|
629
|
+
},
|
|
630
|
+
onEvent(event, state, spec) {
|
|
631
|
+
if (event.type === "system" && event.subtype === "notification") {
|
|
632
|
+
// Kept for the turn's speed report: the result does not say that Claude refused fast mode and ran at standard.
|
|
633
|
+
if (event.key === OVERAGE_NOTICE && typeof event.text === "string" && event.text)
|
|
634
|
+
state.speedNotices = [...(state.speedNotices ?? []), event.text.slice(0, 200)];
|
|
635
|
+
}
|
|
636
|
+
else if (event.type === "system" && event.subtype === "init") {
|
|
637
|
+
if (typeof event.session_id === "string")
|
|
638
|
+
state.sessionId = event.session_id;
|
|
639
|
+
const problem = initProblem(event, spec);
|
|
640
|
+
if (problem)
|
|
641
|
+
state.refuse = `${problem}. Relay stopped it before it did anything.`;
|
|
642
|
+
}
|
|
643
|
+
else if (event.type === "assistant") {
|
|
644
|
+
const refusal = anthropicRefusal(event);
|
|
645
|
+
if (refusal) {
|
|
646
|
+
state.refusal = refusal;
|
|
647
|
+
state.ended = true;
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
// What it is doing now: its latest tool call.
|
|
651
|
+
const content = event.message?.content;
|
|
652
|
+
for (const block of Array.isArray(content) ? content : []) {
|
|
653
|
+
if (block?.type !== "tool_use" || typeof block.name !== "string")
|
|
654
|
+
continue;
|
|
655
|
+
const text = activityOf(block.name, (block.input ?? {}));
|
|
656
|
+
if (text)
|
|
657
|
+
spec.onActivity?.(text);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
else if (event.type === "result") {
|
|
661
|
+
// Claude 2.1.303 print mode with closed stdin holds normal results while local_agent
|
|
662
|
+
// tasks run (bundled ig.route/Kk); shell tasks can outlive a result, but streamTurn
|
|
663
|
+
// already waits for CLI exit and its native wind-down. Do not infer unfinished agents
|
|
664
|
+
// from the result alone. Source/event details: docs/research/native-subagent-lifecycle.md.
|
|
665
|
+
state.ended = true;
|
|
666
|
+
// Source-evidenced in Claude Code 2.1.302's Kte/common result builders and SDK
|
|
667
|
+
// result schemas; NOT observed in a live refusal. subtype success/is_error alone is
|
|
668
|
+
// insufficient: a safety stop is a normal API response with stop_reason refusal.
|
|
669
|
+
const refusal = anthropicRefusal(event);
|
|
670
|
+
if (refusal)
|
|
671
|
+
state.refusal = { ...refusal, message: refusal.message || state.refusal?.message || "" };
|
|
672
|
+
const report = speedReport(event, state.speedNotices);
|
|
673
|
+
const usage = usageFrom(event.usage, {
|
|
674
|
+
...(typeof event.total_cost_usd === "number" ? { cost_usd: event.total_cost_usd } : {}),
|
|
675
|
+
...(typeof event.num_turns === "number" ? { agent_steps: event.num_turns } : {}),
|
|
676
|
+
// With the speed relay asked for, so that status pairs a report with the request it answers (views.ts speedView).
|
|
677
|
+
...(report ? { speed_report: report, speed_requested: spec.speed ?? "standard" } : {}),
|
|
678
|
+
});
|
|
679
|
+
const slower = spec.speed === "fast" ? ranSlower(report) : null;
|
|
680
|
+
if (slower)
|
|
681
|
+
state.speedWarnings = [...(state.speedWarnings ?? []), slower];
|
|
682
|
+
if (usage)
|
|
683
|
+
spec.onUsage?.(usage);
|
|
684
|
+
if (typeof event.session_id === "string")
|
|
685
|
+
state.sessionId = event.session_id;
|
|
686
|
+
// Every permission Claude was refused in the turn, by a rule, its permission mode, or relay's answer to its prompt.
|
|
687
|
+
if (Array.isArray(event.permission_denials) && event.permission_denials.length) {
|
|
688
|
+
state.denials = event.permission_denials.map((d) => {
|
|
689
|
+
const tool = String(d?.tool_name ?? "a tool");
|
|
690
|
+
return activityOf(tool, (d?.tool_input ?? {})) ?? tool;
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
if (event.is_error || event.subtype !== "success") {
|
|
694
|
+
const errors = Array.isArray(event.errors) ? event.errors.join("; ") : "";
|
|
695
|
+
state.failed = `claude reported ${String(event.subtype)}${errors ? `: ${errors}` : ""}${typeof event.result === "string" ? `: ${event.result}` : ""}`;
|
|
696
|
+
}
|
|
697
|
+
else {
|
|
698
|
+
state.finalMessage = typeof event.result === "string" ? event.result : "";
|
|
699
|
+
state.completed = true;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
},
|
|
703
|
+
};
|
|
704
|
+
/** The proxy variables a network turn's Claude process gets: everything pointed at the turn's proxy, with its token, nothing exempt in these variables (settings relay cannot see may still exempt hosts), and the sandbox's report of its proxy ports on stderr. */
|
|
705
|
+
export function claudeProxyEnv(proxy) {
|
|
706
|
+
const url = `http://relay:${proxy.token}@127.0.0.1:${proxy.port}`;
|
|
707
|
+
const env = { NO_PROXY: "", no_proxy: "", SRT_DEBUG: "1" };
|
|
708
|
+
for (const k of ["HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY"])
|
|
709
|
+
env[k] = env[k.toLowerCase()] = url;
|
|
710
|
+
return env;
|
|
711
|
+
}
|
|
712
|
+
/** The proxy variables that point a process at another proxy (NO_PROXY alone does not). */
|
|
713
|
+
const UPSTREAM_PROXY = /^(https?|all)_proxy$/i;
|
|
714
|
+
/**
|
|
715
|
+
* What Claude Code's sandbox reports, under SRT_DEBUG, about the proxy it uses: with external ports,
|
|
716
|
+
* one line for each, as it starts its sandbox (Claude Code 2.1.309, which does so after reading its
|
|
717
|
+
* prompt and before its first model request). `seen` takes each stderr line and answers "other" when
|
|
718
|
+
* a port named is not relay's (settings relay does not control replaced it), which stops the turn at
|
|
719
|
+
* once; `confirmed` is true once both ports named are relay's, which must be so by Claude's first
|
|
720
|
+
* message, or the turn is stopped then (claudeBackend). A Claude Code that no longer reports this
|
|
721
|
+
* fails closed the same way.
|
|
722
|
+
*/
|
|
723
|
+
export function claudeProxyReport(port) {
|
|
724
|
+
const seen = { HTTP: false, SOCKS: false };
|
|
725
|
+
return {
|
|
726
|
+
seen(line) {
|
|
727
|
+
const m = /^\[SandboxDebug\] Using external (HTTP|SOCKS) proxy on port (\d+)$/.exec(line.trim());
|
|
728
|
+
if (!m)
|
|
729
|
+
return null;
|
|
730
|
+
if (Number(m[2]) !== port)
|
|
731
|
+
return "other";
|
|
732
|
+
seen[m[1]] = true;
|
|
733
|
+
return null;
|
|
734
|
+
},
|
|
735
|
+
confirmed: () => seen.HTTP && seen.SOCKS,
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
/** The refusal when the sandbox reports a proxy port other than relay's. */
|
|
739
|
+
export const CLAUDE_OTHER_PROXY = "Claude Code's sandbox reported a proxy port other than relay's for this turn: settings relay does not control replaced relay's sandbox network settings. " +
|
|
740
|
+
"Relay gives a Claude job the network only through its own proxy, so it stopped the job";
|
|
741
|
+
/** The refusal when the sandbox has not confirmed relay's ports by Claude's first message. */
|
|
742
|
+
export const CLAUDE_UNCONFIRMED = "Claude Code did not confirm that its sandbox sends every connection through relay's proxy for this turn (it reports its proxy ports as it starts its sandbox, when SRT_DEBUG is set). " +
|
|
743
|
+
"Settings relay does not control may have replaced relay's sandbox network settings, or this Claude Code version reports them differently. Relay gives a Claude job the network only through that proxy, " +
|
|
744
|
+
"so it stopped the job at its first message. Run the job without the network, or check this Claude Code version with smoke/claude-network-probe.mjs (README, Development)";
|
|
745
|
+
/** The refusal when Claude's model traffic did not reach the turn's proxy by its first response. */
|
|
746
|
+
export const CLAUDE_UNPROXIED = "Claude Code's model requests did not go through relay's proxy for this turn (no request carrying the turn's token named the model endpoint before Claude's first response): settings relay does not control may have replaced its HTTPS_PROXY or NO_PROXY. " +
|
|
747
|
+
"With the network granted, WebFetch, which goes the same way, could then reach this machine and its local network, so relay stopped the job";
|
|
748
|
+
/**
|
|
749
|
+
* The hosts Claude's model requests go to, by the provider in the environment relay passes:
|
|
750
|
+
* Anthropic's API, unless CLAUDE_CODE_USE_BEDROCK or CLAUDE_CODE_USE_VERTEX picks Amazon Bedrock or
|
|
751
|
+
* Google Vertex AI. Relay refuses another endpoint (ANTHROPIC_BASE_URL and the like) before this. A
|
|
752
|
+
* provider relay does not know (another CLAUDE_CODE_USE_*) leaves it unable to check the model
|
|
753
|
+
* traffic, and so refuses the network: `{ problem }`.
|
|
754
|
+
*/
|
|
755
|
+
export function claudeModelHosts(env) {
|
|
756
|
+
const on = (k) => Boolean(env[k]) && !/^(0|false|no|off)$/i.test(env[k].trim());
|
|
757
|
+
const providers = Object.keys(env).filter((k) => /^CLAUDE_CODE_USE_/.test(k) && on(k)).sort();
|
|
758
|
+
if (!providers.length)
|
|
759
|
+
return { name: "api.anthropic.com", test: (h) => h === "api.anthropic.com" };
|
|
760
|
+
if (providers.length === 1 && providers[0] === "CLAUDE_CODE_USE_BEDROCK")
|
|
761
|
+
return { name: "Amazon Bedrock's runtime endpoint", test: (h) => /^bedrock-runtime(-fips)?\.[a-z0-9-]+\.amazonaws\.com$/.test(h) };
|
|
762
|
+
if (providers.length === 1 && providers[0] === "CLAUDE_CODE_USE_VERTEX")
|
|
763
|
+
return { name: "Google Vertex AI's endpoint", test: (h) => /^([a-z0-9-]+-)?aiplatform\.googleapis\.com$/.test(h) };
|
|
764
|
+
return { problem: `the environment relay passes to Claude sets ${providers.join(", ")}, a model provider whose endpoint relay does not know, so it could not check that Claude's model traffic, and its WebFetch with it, goes through relay's proxy. Relay does not give this job the network` };
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Development only: the stub model relay's own smoke probe and tests serve Claude's model requests
|
|
768
|
+
* from, through the turn's proxy (ProxyOptions.modelStub), so that they pass relay's check of the
|
|
769
|
+
* model traffic like real ones. Off unless relay's own environment sets RELAY_DEV_MODEL_STUB=1, which
|
|
770
|
+
* relay's smoke and test launchers do and a launched job cannot (it sets nothing in the root's or the
|
|
771
|
+
* worker's environment); with the flag, read from dev/claude-model-stub.json ({ "host", "port" }) in
|
|
772
|
+
* a relay home that is not relay's default. With the flag set, a file that is malformed, or names a
|
|
773
|
+
* port nothing listens on (left from an earlier run), refuses the turn; without it the file is ignored.
|
|
774
|
+
*/
|
|
775
|
+
export async function devModelStub() {
|
|
776
|
+
if (process.env.RELAY_DEV_MODEL_STUB !== "1")
|
|
777
|
+
return undefined;
|
|
778
|
+
const home = relayHome();
|
|
779
|
+
if (!process.env.RELAY_HOME || path.resolve(home) === path.join(os.homedir(), ".local", "state", "relay")) {
|
|
780
|
+
throw new Error("RELAY_DEV_MODEL_STUB is set, but relay runs in its default state directory: the development model stub is for a scratch RELAY_HOME only");
|
|
781
|
+
}
|
|
782
|
+
const file = path.join(home, "dev", "claude-model-stub.json");
|
|
783
|
+
if (!fs.existsSync(file))
|
|
784
|
+
return undefined;
|
|
785
|
+
let v;
|
|
786
|
+
try {
|
|
787
|
+
v = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
788
|
+
}
|
|
789
|
+
catch (e) {
|
|
790
|
+
throw new Error(`RELAY_DEV_MODEL_STUB: ${file} could not be read as JSON (${e.message})`);
|
|
791
|
+
}
|
|
792
|
+
if (typeof v.host !== "string" || !/^[a-z0-9.-]+$/.test(v.host) || !Number.isInteger(v.port))
|
|
793
|
+
throw new Error(`RELAY_DEV_MODEL_STUB: ${file} must hold { "host": "<host name>", "port": <number> }`);
|
|
794
|
+
const port = v.port;
|
|
795
|
+
const live = await new Promise((resolve) => {
|
|
796
|
+
const c = net.connect({ host: "127.0.0.1", port });
|
|
797
|
+
const done = (ok) => (c.destroy(), resolve(ok));
|
|
798
|
+
c.setTimeout(2000, () => done(false));
|
|
799
|
+
c.once("connect", () => done(true));
|
|
800
|
+
c.once("error", () => done(false));
|
|
801
|
+
});
|
|
802
|
+
if (!live)
|
|
803
|
+
throw new Error(`RELAY_DEV_MODEL_STUB: nothing listens on 127.0.0.1:${port}, the stub ${file} names (left from an earlier run?)`);
|
|
804
|
+
return { host: v.host, port };
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* A network turn's proxy (public mode), opened before the turn starts, with the test for the hosts
|
|
808
|
+
* Claude's model requests go to, or null for a turn without the network or with full access (whose
|
|
809
|
+
* sandbox is off). Refused here: a proxy in the environment relay passes to Claude (relay's proxy
|
|
810
|
+
* would have to go through it, which would resolve names where relay cannot check them), a model
|
|
811
|
+
* provider relay does not know, and managed settings on disk that would take the job around
|
|
812
|
+
* relay's proxy.
|
|
813
|
+
*/
|
|
814
|
+
export async function networkProxy(spec, env) {
|
|
815
|
+
const { dangerous, network } = turnPolicy(spec);
|
|
816
|
+
if (!network || dangerous)
|
|
817
|
+
return null;
|
|
818
|
+
const upstream = Object.keys(env).filter((k) => UPSTREAM_PROXY.test(k) && env[k]).sort();
|
|
819
|
+
if (upstream.length) {
|
|
820
|
+
throw new Error(`the environment relay passes to Claude sets ${upstream.join(", ")}. A Claude job with the network reaches the web only through relay's own proxy, which checks every address it connects to; ` +
|
|
821
|
+
"behind another proxy, that proxy would resolve the names relay checks, so relay does not give this job the network. Run it without the network, or leave the proxy out of the environment relay passes to Claude (child_env)");
|
|
822
|
+
}
|
|
823
|
+
const stub = await devModelStub();
|
|
824
|
+
const model = stub ? { name: stub.host, test: (h) => h === stub.host } : claudeModelHosts(env);
|
|
825
|
+
if ("problem" in model)
|
|
826
|
+
throw new Error(model.problem);
|
|
827
|
+
const managed = managedNetworkProblem();
|
|
828
|
+
if (managed)
|
|
829
|
+
throw new Error(managed);
|
|
830
|
+
const proxy = await openTurnProxy({ neverPolicy: spec.neverPolicy, mode: "public", allow: [], logFile: path.join(spec.dir, "proxy.jsonl"), label: `${spec.markers.nodeId}/${spec.relay?.turnId ?? spec.turnId ?? "-"}`, ...(stub ? { modelStub: stub } : {}) });
|
|
831
|
+
return { proxy, model };
|
|
832
|
+
}
|
|
833
|
+
export const claudeBackend = {
|
|
834
|
+
start: async (spec) => nativeTemp(spec, async (tmpDir, agentTmp) => {
|
|
835
|
+
const prepared = claude.prepare(spec, tmpDir, agentTmp);
|
|
836
|
+
const net = await networkProxy(spec, prepared.env);
|
|
837
|
+
const proxy = net?.proxy;
|
|
838
|
+
try {
|
|
839
|
+
if (proxy)
|
|
840
|
+
prepared.proxy = { port: proxy.port, token: proxy.token };
|
|
841
|
+
const invocation = claude.invocation(spec, prepared);
|
|
842
|
+
turnPolicy(spec); // Last check, after settings and git discovery, immediately before spawn.
|
|
843
|
+
if (!net || !proxy)
|
|
844
|
+
return streamTurn(spec, { invocation, onEvent: claude.onEvent });
|
|
845
|
+
// At the start of Claude's first response (message_start, from --include-partial-messages),
|
|
846
|
+
// before any tool in it can run, relay requires that the sandbox has reported relay's proxy
|
|
847
|
+
// ports, and that the Claude process has sent at least one request carrying the turn's token to
|
|
848
|
+
// the model host through relay's proxy; else the turn is stopped. The first assistant message
|
|
849
|
+
// is the backstop for a Claude Code that does not stream partial messages.
|
|
850
|
+
// What this proves: the Claude process uses relay's proxy variables, and NO_PROXY does not
|
|
851
|
+
// cover the model host. What it does not prove: that the model requests themselves, or
|
|
852
|
+
// WebFetch, went through the proxy. Claude also sends other requests to the model host at
|
|
853
|
+
// start, and a request is not visible inside TLS (smoke --control collision shows the case).
|
|
854
|
+
// Settings relay cannot see (delivered from the claude.ai console: a managed ANTHROPIC_BASE_URL
|
|
855
|
+
// with a NO_PROXY for its host, a NO_PROXY listing local ranges) can send model requests or
|
|
856
|
+
// WebFetch around the proxy while other traffic stays on it; they are outside what relay
|
|
857
|
+
// guarantees (docs/known-limits.md). Managed settings on disk are refused above.
|
|
858
|
+
const report = claudeProxyReport(proxy.port);
|
|
859
|
+
let checked = false;
|
|
860
|
+
const check = (state) => {
|
|
861
|
+
checked = true;
|
|
862
|
+
if (!report.confirmed())
|
|
863
|
+
state.stop ??= `${CLAUDE_UNCONFIRMED}.`;
|
|
864
|
+
else if (![...proxy.tokenHosts()].some(net.model.test))
|
|
865
|
+
state.stop ??= `${CLAUDE_UNPROXIED} (expected a request to ${net.model.name}).`;
|
|
866
|
+
};
|
|
867
|
+
const onEvent = (event, state, s) => {
|
|
868
|
+
const first = event.type === "assistant" || (event.type === "stream_event" && event.event?.type === "message_start");
|
|
869
|
+
if (!checked && first) {
|
|
870
|
+
check(state);
|
|
871
|
+
if (state.stop)
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
claude.onEvent(event, state, s);
|
|
875
|
+
};
|
|
876
|
+
const onStderr = (line, state) => {
|
|
877
|
+
if (report.seen(line) === "other")
|
|
878
|
+
state.stop ??= `${CLAUDE_OTHER_PROXY}.`;
|
|
879
|
+
};
|
|
880
|
+
// The partial messages' token deltas stay out of the agent log; their message_start is kept.
|
|
881
|
+
const unlogged = (event) => event.type === "stream_event" && event.event?.type !== "message_start";
|
|
882
|
+
const handle = streamTurn(spec, { invocation, onEvent, onStderr, unlogged });
|
|
883
|
+
return afterTurn(handle, async (result) => (await proxy.close(), result));
|
|
884
|
+
}
|
|
885
|
+
catch (error) {
|
|
886
|
+
await proxy?.close();
|
|
887
|
+
throw error;
|
|
888
|
+
}
|
|
889
|
+
}),
|
|
890
|
+
};
|