@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,307 @@
|
|
|
1
|
+
// A stub ACP agent (Agent Client Protocol v1 over stdio), standing in for GitHub Copilot CLI's
|
|
2
|
+
// `copilot --acp`: initialize with a login-reuse auth method, authenticate, session/new and
|
|
3
|
+
// session/load (with replay), modes and a model reported and settable, session/prompt with
|
|
4
|
+
// streamed updates, session/request_permission, session/cancel, and requests to the client that
|
|
5
|
+
// relay must refuse. Steps come from the shared scenario (stub-agent.mjs).
|
|
6
|
+
//
|
|
7
|
+
// Started as Grok Build's `grok … agent … stdio`, it answers as Grok 1.0.62 does where relay
|
|
8
|
+
// relies on it: `cached_token` offered only with a stored login (the file at $GROK_AUTH_PATH, where
|
|
9
|
+
// relay points it, as 1.0.62's build_auth_methods looks), authenticating with it failing without one,
|
|
10
|
+
// a session opened without authenticating only with a stored login (without one, "Authentication required"), no session
|
|
11
|
+
// modes, its model reported in `models` (current and available) and in configOptions, on new and
|
|
12
|
+
// resumed sessions alike, from its built-in catalog (grok-4.6, its default, and grok-4.5; a test
|
|
13
|
+
// can give another with STUB_ACP_REPORT's `catalog`), an `-m` naming a model not in the catalog
|
|
14
|
+
// falling back to grok-4.6 without a word, its reasoning effort reported as a thought_level option
|
|
15
|
+
// (STUB_ACP_REPORT's `noEffortOption`: none), session/resume advertised and served (without a
|
|
16
|
+
// replay), its session files under $GROK_HOME, and its Grok, xAI and OTEL variables in the start
|
|
17
|
+
// record.
|
|
18
|
+
//
|
|
19
|
+
// It runs under relay's own sandbox, so it writes only where a confined harness may: its session
|
|
20
|
+
// files go in $COPILOT_HOME or $GROK_HOME (the harness state relay prepares), and its records go to
|
|
21
|
+
// stderr as `STUB-RECORD <json>` lines, which relay keeps in the agent's log.
|
|
22
|
+
import crypto from "node:crypto";
|
|
23
|
+
import fs from "node:fs";
|
|
24
|
+
import path from "node:path";
|
|
25
|
+
import readline from "node:readline";
|
|
26
|
+
import { runSteps } from "../stub-agent.mjs";
|
|
27
|
+
|
|
28
|
+
const AGENT_MODE = "https://agentclientprotocol.com/protocol/session-modes#agent";
|
|
29
|
+
const MODES = [AGENT_MODE, "https://agentclientprotocol.com/protocol/session-modes#plan", "https://agentclientprotocol.com/protocol/session-modes#autopilot"];
|
|
30
|
+
// "unlisted-model": one the harness offers that relay's model list does not name (its family is unknown).
|
|
31
|
+
const MODELS = ["auto", "claude-sonnet-5.5", "claude-opus-5.5", "gpt-6.1-sol", "gpt-5.4", "gemini-3.8-flash", "unlisted-model"];
|
|
32
|
+
// Grok 1.0.62's built-in catalog, as session/new reports it without a signed-in catalog (a decoy login, 2026-10-17),
|
|
33
|
+
// with each model's reasoning-effort menu; an effort the menu lacks runs as "high", the default.
|
|
34
|
+
const GROK_CATALOG = ["grok-4.6", "grok-4.5"];
|
|
35
|
+
const GROK_EFFORTS = { "grok-4.6": ["xhigh", "high", "medium", "low"], "grok-4.5": ["high", "medium", "low"], "grok-4.7": ["xhigh", "high", "medium", "low"] };
|
|
36
|
+
/** Whether this is Grok Build's ACP agent: `grok [options] agent [options] stdio`. */
|
|
37
|
+
const isGrok = (argv) => argv.includes("agent") && argv[argv.length - 1] === "stdio";
|
|
38
|
+
/** Whether Grok has a stored login: a file where GROK_AUTH_PATH says (relay always sets it), looked at, never read. */
|
|
39
|
+
const grokLogin = () => Boolean(process.env.GROK_AUTH_PATH) && fs.existsSync(process.env.GROK_AUTH_PATH);
|
|
40
|
+
|
|
41
|
+
const record = (obj) => process.stderr.write(`STUB-RECORD ${JSON.stringify({ t: Date.now(), pid: process.pid, ...obj })}\n`);
|
|
42
|
+
const flag = (argv, name) => {
|
|
43
|
+
const i = argv.findIndex((a) => a === name || a.startsWith(`${name}=`));
|
|
44
|
+
if (i < 0) return undefined;
|
|
45
|
+
return argv[i].includes("=") ? argv[i].slice(argv[i].indexOf("=") + 1) : argv[i + 1];
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
function sessionFile(id, grok) {
|
|
49
|
+
const dir = grok ? path.join(process.env.GROK_HOME ?? process.cwd(), "sessions", "stub") : path.join(process.env.COPILOT_HOME ?? process.cwd(), "session-state", "stub");
|
|
50
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
51
|
+
return path.join(dir, `${id}.json`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function acpServer(argv) {
|
|
55
|
+
// As Copilot 1.0.98 does with no stored login it can use: it gives up before ACP's initialize.
|
|
56
|
+
if (process.env.STUB_ACP_EXIT_AT_START) {
|
|
57
|
+
process.stderr.write("Error: no stored login\n");
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
const out = (m) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...m }) + "\n");
|
|
61
|
+
const answers = new Map();
|
|
62
|
+
let nextId = 1000;
|
|
63
|
+
const toClient = (method, params, timeoutMs = 120000) => new Promise((resolve) => {
|
|
64
|
+
const id = nextId++;
|
|
65
|
+
const timer = setTimeout(() => { answers.delete(id); resolve({ timeout: true }); }, timeoutMs);
|
|
66
|
+
answers.set(id, (m) => { clearTimeout(timer); resolve(m); });
|
|
67
|
+
out({ id, method, params });
|
|
68
|
+
});
|
|
69
|
+
const update = (sessionId, u) => out({ method: "session/update", params: { sessionId, update: u } });
|
|
70
|
+
|
|
71
|
+
const grok = isGrok(argv);
|
|
72
|
+
// Grok reports no session modes. A test's own values come after the persona's defaults, and win.
|
|
73
|
+
const report = { ...(grok ? { noModes: true } : {}), ...(process.env.STUB_ACP_REPORT ? JSON.parse(process.env.STUB_ACP_REPORT) : {}) };
|
|
74
|
+
const persona = grok ? "grok" : "copilot";
|
|
75
|
+
const models = grok ? (report.catalog ?? GROK_CATALOG) : MODELS;
|
|
76
|
+
let session = null;
|
|
77
|
+
let mode = AGENT_MODE;
|
|
78
|
+
// Grok runs a model its catalog does not offer as its default, grok-4.6, and says nothing (1.0.62, `-m grok-4.7`).
|
|
79
|
+
let model = grok ? (models.includes(flag(argv, "-m")) ? flag(argv, "-m") : "grok-4.6") : (flag(argv, "--model") ?? "claude-sonnet-5.5");
|
|
80
|
+
const effortMenu = () => GROK_EFFORTS[model] ?? ["high"];
|
|
81
|
+
const effort = () => (effortMenu().includes(flag(argv, "--reasoning-effort")) ? flag(argv, "--reasoning-effort") : "high");
|
|
82
|
+
let cancelled = false;
|
|
83
|
+
/** Whether an authenticate call succeeded on this connection. */
|
|
84
|
+
let authenticated = false;
|
|
85
|
+
/** Settles when relay first asks the agent to stop (session/cancel), whatever the agent then does. */
|
|
86
|
+
let cancelAsked;
|
|
87
|
+
const cancelSeen = new Promise((r) => (cancelAsked = r));
|
|
88
|
+
let finishPrompt = null;
|
|
89
|
+
let calls = 0;
|
|
90
|
+
|
|
91
|
+
const sessionResult = () => ({
|
|
92
|
+
...(report.noModes ? {} : { modes: { currentModeId: mode, availableModes: MODES.map((id) => ({ id, name: id.split("#")[1] })) } }),
|
|
93
|
+
...(report.noModel ? {} : { models: { currentModelId: report.model ?? model, availableModels: models.map((modelId) => ({ modelId, name: modelId })) } }),
|
|
94
|
+
configOptions: [
|
|
95
|
+
...(report.noModel ? [] : [{ id: "model", name: "Model", category: "model", type: "select", currentValue: report.model ?? model, options: models.map((value) => ({ value, name: value })) }]),
|
|
96
|
+
...(grok && !report.noEffortOption ? [{ id: "reasoning_effort", name: "Reasoning effort", category: "thought_level", type: "select", currentValue: effort(), options: effortMenu().map((value) => ({ value, name: value })) }] : []),
|
|
97
|
+
],
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
/** How this agent asks for permission, for each kind of scenario request; resolves to what relay answered. */
|
|
101
|
+
const ask = async (request) => {
|
|
102
|
+
const sessionId = session.id;
|
|
103
|
+
const toolCallId = `call_${++calls}`;
|
|
104
|
+
let options = request.noAllowOnce
|
|
105
|
+
? [{ optionId: "always", name: "Always allow", kind: "allow_always" }, { optionId: "no", name: "Reject", kind: "reject_once" }]
|
|
106
|
+
: [{ optionId: "once", name: "Allow once", kind: "allow_once" }, { optionId: "always", name: "Always allow", kind: "allow_always" }, { optionId: "no", name: "Reject", kind: "reject_once" }];
|
|
107
|
+
let toolCall;
|
|
108
|
+
if (request.path !== undefined) {
|
|
109
|
+
// Copilot 1.0.98's own check of a path outside its trusted directories, as a signed-in run
|
|
110
|
+
// sent it (2026-10-17, j_a7963b11): the tool call announced first (`tool`: an apply_patch
|
|
111
|
+
// adding the file, its file viewer, a command, or none), then a request of kind "read",
|
|
112
|
+
// whatever the call would do, with the path in rawInput and locations, and Copilot's options.
|
|
113
|
+
const p = request.path;
|
|
114
|
+
if (request.tool === "edit") update(sessionId, { sessionUpdate: "tool_call", toolCallId, title: "apply_patch", kind: "edit", status: "pending", rawInput: `*** Begin Patch\n*** Add File: ${p}\n+hi\n*** End Patch\n` });
|
|
115
|
+
else if (request.tool === "read") update(sessionId, { sessionUpdate: "tool_call", toolCallId, title: `Viewing ${p}`, kind: "read", status: "pending", rawInput: { path: p } });
|
|
116
|
+
else if (request.tool === "execute") update(sessionId, { sessionUpdate: "tool_call", toolCallId, title: "Copy the file", kind: "execute", status: "pending", rawInput: { command: `cp ${p} .`, description: "Copy the file" } });
|
|
117
|
+
toolCall = { toolCallId, title: "Access paths outside trusted directories", kind: "read", status: "pending", ...(p ? { rawInput: { path: p }, locations: [{ path: p }] } : { rawInput: {} }) };
|
|
118
|
+
options = [{ optionId: "allow_once", kind: "allow_once", name: "Allow once" }, { optionId: "allow_always", kind: "allow_always", name: "Always allow" }, { optionId: "reject_once", kind: "reject_once", name: "Deny" }];
|
|
119
|
+
} else if (request.sparse) {
|
|
120
|
+
// A request that refers to nothing relay has seen, and says nothing about what it would do.
|
|
121
|
+
toolCall = { toolCallId, title: "Do something" };
|
|
122
|
+
} else if (typeof request === "string" || request.command) {
|
|
123
|
+
const command = typeof request === "string" ? request : request.command;
|
|
124
|
+
// Announced as a tool call first; the request refers to it by id only.
|
|
125
|
+
update(sessionId, { sessionUpdate: "tool_call", toolCallId, title: "Run shell command", kind: "execute", status: "pending", rawInput: { command, description: "stub needs it", ...(request.cwd ? { cwd: request.cwd } : {}) } });
|
|
126
|
+
toolCall = { toolCallId };
|
|
127
|
+
} else if (request.edit) {
|
|
128
|
+
update(sessionId, { sessionUpdate: "tool_call", toolCallId, title: "Editing", kind: "edit", status: "pending", locations: [{ path: request.edit }] });
|
|
129
|
+
toolCall = { toolCallId, content: [{ type: "diff", path: request.edit, oldText: "a", newText: "b" }] };
|
|
130
|
+
} else if (request.web || request.fetch) {
|
|
131
|
+
toolCall = { toolCallId, title: "Fetching URL", kind: "fetch", rawInput: { url: request.web ?? request.fetch } };
|
|
132
|
+
} else {
|
|
133
|
+
toolCall = { toolCallId, title: "Unknown", kind: "other" };
|
|
134
|
+
}
|
|
135
|
+
const reply = await toClient("session/request_permission", { sessionId, toolCall, options });
|
|
136
|
+
const o = reply.result?.outcome;
|
|
137
|
+
const kind = o?.outcome === "selected" ? options.find((x) => x.optionId === o.optionId)?.kind ?? `unoffered:${o.optionId}` : o?.outcome ?? "no answer";
|
|
138
|
+
// Past its path check, Copilot goes on with the call: whether that works is for relay's sandbox to say.
|
|
139
|
+
let attempt;
|
|
140
|
+
if (request.path && (kind === "allow_once" || kind === "allow_always") && (request.tool === "edit" || request.tool === "read")) {
|
|
141
|
+
try {
|
|
142
|
+
if (request.tool === "edit") fs.writeFileSync(request.path, "hi\n");
|
|
143
|
+
else fs.readFileSync(request.path);
|
|
144
|
+
attempt = { op: request.tool === "edit" ? "write" : "read", ok: true };
|
|
145
|
+
} catch (err) {
|
|
146
|
+
attempt = { op: request.tool === "edit" ? "write" : "read", ok: false, code: err.code ?? String(err) };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
update(sessionId, { sessionUpdate: "tool_call_update", toolCallId, status: kind === "allow_once" && attempt?.ok !== false ? "completed" : "failed",
|
|
150
|
+
...(request.path !== undefined && kind === "reject_once" ? { rawOutput: { message: "The user rejected this tool call.", code: "rejected" } } : {}) });
|
|
151
|
+
return { decision: kind === "allow_once" || kind === "allow_always" ? "allow" : "deny", optionKind: kind, ...(kind === "allow_always" ? { scope: "always" } : {}), ...(attempt ? { attempt } : {}) };
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// Each message is handled as it comes, never waiting on another: a prompt waits on the client's
|
|
155
|
+
// answers to its requests, which arrive as further lines.
|
|
156
|
+
const handle = async (line) => {
|
|
157
|
+
let m;
|
|
158
|
+
try { m = JSON.parse(line); } catch { return; }
|
|
159
|
+
if (m.id !== undefined && m.method === undefined) { answers.get(m.id)?.(m); answers.delete(m.id); return; }
|
|
160
|
+
const p = m.params ?? {};
|
|
161
|
+
switch (m.method) {
|
|
162
|
+
case "initialize":
|
|
163
|
+
record({ event: "initialize", protocolVersion: p.protocolVersion, clientCapabilities: p.clientCapabilities });
|
|
164
|
+
out({ id: m.id, result: {
|
|
165
|
+
protocolVersion: Number(process.env.STUB_ACP_PROTOCOL ?? 1),
|
|
166
|
+
agentCapabilities: { loadSession: true, promptCapabilities: {}, mcpCapabilities: {}, sessionCapabilities: grok ? { list: {}, resume: {}, close: {} } : {} },
|
|
167
|
+
authMethods: process.env.STUB_ACP_NO_AUTH_METHOD ? []
|
|
168
|
+
: grok ? [...(grokLogin() ? [{ id: "cached_token", name: "cached_token" }] : []), { id: "grok.com", name: "Grok", description: "Sign in with Grok" }]
|
|
169
|
+
: [{ id: "copilot-login", name: "Log in with Copilot CLI", description: "Run copilot login" }],
|
|
170
|
+
...(grok ? { _meta: { agentVersion: "1.0.62" } } : { agentInfo: { name: "stub-copilot", version: "1.0.98" } }),
|
|
171
|
+
} });
|
|
172
|
+
break;
|
|
173
|
+
case "authenticate":
|
|
174
|
+
record({ event: "authenticate", methodId: p.methodId, session: Boolean(session), sessionId: session?.id ?? null });
|
|
175
|
+
if ((grok ? !grokLogin() : process.env.STUB_LOGIN === "none") || (process.env.STUB_LOGIN === "lost-after-session" && session)) out({ id: m.id, error: { code: -32000, message: "Authentication required" } });
|
|
176
|
+
else {
|
|
177
|
+
authenticated = true;
|
|
178
|
+
out({ id: m.id, result: {} });
|
|
179
|
+
}
|
|
180
|
+
break;
|
|
181
|
+
case "session/new":
|
|
182
|
+
case "session/load":
|
|
183
|
+
case "session/resume": {
|
|
184
|
+
if (m.method === "session/resume" && !grok) { out({ id: m.id, error: { code: -32601, message: "unsupported session/resume" } }); return; }
|
|
185
|
+
// Grok 1.0.62 with no stored login, when nothing authenticated first; with a stored login (a decoy) it opens the session unasked.
|
|
186
|
+
if (grok && !grokLogin() && !authenticated) { out({ id: m.id, error: { code: -32000, message: "Authentication required", data: "no auth method id provided" } }); return; }
|
|
187
|
+
const loading = m.method !== "session/new";
|
|
188
|
+
const id = loading ? p.sessionId : crypto.randomUUID();
|
|
189
|
+
const file = sessionFile(id, grok);
|
|
190
|
+
if (loading && !fs.existsSync(file)) { out({ id: m.id, error: { code: -32002, message: `Resource not found: session ${id}` } }); return; }
|
|
191
|
+
const sess = loading ? JSON.parse(fs.readFileSync(file, "utf8")) : { turns: 0 };
|
|
192
|
+
session = { id, sess, file, loading, mcpServers: p.mcpServers ?? [], cwd: p.cwd };
|
|
193
|
+
record({ event: "session", method: m.method, sessionId: id, cwd: p.cwd, mcpServers: (p.mcpServers ?? []).map((s) => s.name), additionalDirectories: p.additionalDirectories ?? null });
|
|
194
|
+
// A load replays the conversation before it answers; a resume does not.
|
|
195
|
+
if (m.method === "session/load") update(id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `REPLAYED turn ${sess.turns}` } });
|
|
196
|
+
out({ id: m.id, result: loading ? sessionResult() : { sessionId: id, ...sessionResult() } });
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
case "session/set_mode":
|
|
200
|
+
if (!MODES.includes(p.modeId)) { out({ id: m.id, error: { code: -32602, message: "unknown mode" } }); return; }
|
|
201
|
+
mode = p.modeId;
|
|
202
|
+
update(session.id, { sessionUpdate: "current_mode_update", currentModeId: mode });
|
|
203
|
+
out({ id: m.id, result: {} });
|
|
204
|
+
break;
|
|
205
|
+
case "session/set_config_option":
|
|
206
|
+
record({ event: "set_config_option", configId: p.configId, value: p.value });
|
|
207
|
+
if (p.configId !== "model" || !models.includes(p.value)) { out({ id: m.id, error: { code: -32602, message: `Unknown config option value ${p.value}` } }); return; }
|
|
208
|
+
// A harness that says yes and keeps its model, when a test asks for one.
|
|
209
|
+
if (!report.pinModel) model = p.value;
|
|
210
|
+
out({ id: m.id, result: { configOptions: sessionResult().configOptions } });
|
|
211
|
+
break;
|
|
212
|
+
case "session/cancel":
|
|
213
|
+
record({ event: "cancel" });
|
|
214
|
+
cancelAsked();
|
|
215
|
+
// A misbehaving agent, when a test asks for one, takes no notice.
|
|
216
|
+
if (process.env.STUB_ACP_IGNORE_TERM) return;
|
|
217
|
+
cancelled = true;
|
|
218
|
+
finishPrompt?.({ stopReason: "cancelled" });
|
|
219
|
+
break;
|
|
220
|
+
case "session/prompt": {
|
|
221
|
+
session.sess.turns += 1;
|
|
222
|
+
fs.writeFileSync(session.file, JSON.stringify(session.sess));
|
|
223
|
+
const prompt = (p.prompt ?? []).map((b) => b.text ?? "").join("");
|
|
224
|
+
const relay = session.mcpServers.find((s) => s.name === "relay");
|
|
225
|
+
const parsed = { relay: relay ? { command: relay.command, args: relay.args ?? [], env: Object.fromEntries((relay.env ?? []).map((e) => [e.name, e.value])) } : undefined };
|
|
226
|
+
// Client methods relay never offered must be refused, at once.
|
|
227
|
+
const fsReply = await toClient("fs/read_text_file", { sessionId: session.id, path: path.join(session.cwd, "README.md") }, 5000);
|
|
228
|
+
const termReply = await toClient("terminal/create", { sessionId: session.id, command: "true" }, 5000);
|
|
229
|
+
record({
|
|
230
|
+
event: "start", target: persona, via: "acp", argv, prompt, sessionId: session.id, resumed: session.loading, turn: session.sess.turns,
|
|
231
|
+
cwd: process.cwd(), hasRelay: Boolean(parsed.relay), mode, model,
|
|
232
|
+
env: {
|
|
233
|
+
copilotHome: process.env.COPILOT_HOME ?? null, cacheHome: process.env.COPILOT_CACHE_HOME ?? null, autoUpdate: process.env.COPILOT_AUTO_UPDATE ?? null,
|
|
234
|
+
copilotToken: Boolean(process.env.COPILOT_GITHUB_TOKEN), ghToken: Boolean(process.env.GH_TOKEN), githubToken: Boolean(process.env.GITHUB_TOKEN),
|
|
235
|
+
allowAll: process.env.COPILOT_ALLOW_ALL ?? null, anthropicKey: Boolean(process.env.ANTHROPIC_API_KEY), tmpdir: process.env.TMPDIR ?? null,
|
|
236
|
+
home: process.env.HOME ?? null,
|
|
237
|
+
...(grok ? { grok: Object.fromEntries(Object.entries(process.env).filter(([k]) => /^(GROK_|XAI_|OTEL_)/.test(k) || k === "SENTRY_DSN" || k === "DISABLE_ERROR_REPORTING")) } : {}),
|
|
238
|
+
},
|
|
239
|
+
clientMethods: { fs: fsReply.error?.code ?? (fsReply.timeout ? "timeout" : "answered"), terminal: termReply.error?.code ?? (termReply.timeout ? "timeout" : "answered") },
|
|
240
|
+
});
|
|
241
|
+
if (process.env.STUB_ACP_IGNORE_TERM) for (const sig of ["SIGTERM", "SIGINT"]) { process.removeAllListeners(sig); process.on(sig, () => {}); }
|
|
242
|
+
// Something said before a tool call is not the reply.
|
|
243
|
+
update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Let me look. " } });
|
|
244
|
+
update(session.id, { sessionUpdate: "tool_call", toolCallId: "read_1", title: "Reading README.md", kind: "read", status: "completed", locations: [{ path: "README.md" }] });
|
|
245
|
+
const done = new Promise((resolve) => (finishPrompt = resolve));
|
|
246
|
+
void (async () => {
|
|
247
|
+
// A step can make the agent switch its model in the middle of the turn, as it reports it.
|
|
248
|
+
const hook = async (h) => {
|
|
249
|
+
if (!h.switchModel) return;
|
|
250
|
+
model = h.switchModel;
|
|
251
|
+
update(session.id, h.currentModelUpdate
|
|
252
|
+
? { sessionUpdate: "current_model_update", ...(h.missingModel ? {} : { currentModelId: model }) }
|
|
253
|
+
: { sessionUpdate: "config_option_update", configOptions: sessionResult().configOptions });
|
|
254
|
+
// Same ACP stream: the method-not-found response proves relay processed the model
|
|
255
|
+
// notification before a nested call goes over the separate bridge connection.
|
|
256
|
+
if (h.awaitModel) await toClient("relay/test-model-barrier", {});
|
|
257
|
+
// With awaitCancel the agent goes on only once relay has asked it to stop, which relay
|
|
258
|
+
// does in the same step as taking its relay tools away: a relay call after this is one
|
|
259
|
+
// made after relay acted on the switch. The report goes out on the ACP stream and a relay
|
|
260
|
+
// call on the bridge socket, two channels whose order relay does not control, so no fixed
|
|
261
|
+
// pause could make that certain. Bounded, so that a relay that never asks fails the test
|
|
262
|
+
// rather than holding it.
|
|
263
|
+
if (h.awaitCancel) await Promise.race([cancelSeen, new Promise((r) => setTimeout(r, 60000))]);
|
|
264
|
+
};
|
|
265
|
+
const r = await runSteps({ id: persona, hook }, parsed, prompt, session.sess, ask);
|
|
266
|
+
if (cancelled) return;
|
|
267
|
+
record({ event: "end", target: persona, sessionId: session.id, ...r });
|
|
268
|
+
if (r.failure) return finishPrompt({ error: r.failure });
|
|
269
|
+
// A notice of the harness's own, sent as a message chunk ahead of the reply (Copilot's "Info: Disabled tools: task").
|
|
270
|
+
if (process.env.STUB_ACP_NOTICE) update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: process.env.STUB_ACP_NOTICE } });
|
|
271
|
+
// The reply, streamed in pieces.
|
|
272
|
+
const half = Math.ceil(r.reply.length / 2);
|
|
273
|
+
update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: r.reply.slice(0, half) } });
|
|
274
|
+
update(session.id, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: r.reply.slice(half) } });
|
|
275
|
+
update(session.id, { sessionUpdate: "usage_update", used: 1500, size: 200000, cost: { amount: 0.0123, currency: "USD" } });
|
|
276
|
+
// A harness that names the model that answered only in its prompt response (Gemini CLI's _meta),
|
|
277
|
+
// when a test asks: for the served-model hook to be built on family steering's served_model.
|
|
278
|
+
finishPrompt({ stopReason: report.stopReason ?? "end_turn", usage: { inputTokens: 120, outputTokens: 30, totalTokens: 150, cachedReadTokens: 10 }, ...(report.served ? { _meta: { quota: { token_count: { input_tokens: 120, output_tokens: 30 }, model_usage: [report.served].flat().map((m) => ({ model: m, token_count: { input_tokens: 60, output_tokens: 15 } })) } } } : {}) });
|
|
279
|
+
})().catch((err) => {
|
|
280
|
+
record({ event: "steps-error", error: String(err?.message ?? err) });
|
|
281
|
+
finishPrompt({ error: String(err?.stack ?? err) });
|
|
282
|
+
});
|
|
283
|
+
const res = await done;
|
|
284
|
+
if (res.error) out({ id: m.id, error: { code: -32000, message: res.error } });
|
|
285
|
+
else out({ id: m.id, result: { stopReason: res.stopReason, ...(res.usage ? { usage: res.usage } : {}), ...(res._meta ? { _meta: res._meta } : {}) } });
|
|
286
|
+
if (cancelled) process.exit(0);
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
default:
|
|
290
|
+
if (m.id !== undefined) out({ id: m.id, error: { code: -32601, message: `unsupported ${m.method}` } });
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
294
|
+
rl.on("line", (line) => void handle(line).catch((err) => record({ event: "stub-error", error: String(err?.stack ?? err) })));
|
|
295
|
+
await new Promise((resolve) => rl.on("close", resolve));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const acp = {
|
|
299
|
+
id: "copilot",
|
|
300
|
+
// What `--version` prints: Grok's, for a launcher named grok.
|
|
301
|
+
get version() {
|
|
302
|
+
return path.basename(process.argv[1] ?? "") === "grok" ? "grok 1.0.62 (stub)" : "GitHub Copilot CLI 1.0.98.\nRun 'copilot update' to check for updates.";
|
|
303
|
+
},
|
|
304
|
+
serve: (argv) => (argv.includes("--acp") || isGrok(argv) ? acpServer(argv) : null),
|
|
305
|
+
parse: () => { throw new Error("the stub ACP agent runs only as `--acp` or `agent … stdio`"); },
|
|
306
|
+
};
|
|
307
|
+
export default acp;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// The stub's Claude Code: `claude -p` with stream-json output. Permission prompts go to the tool
|
|
2
|
+
// named by --permission-prompt-tool; without one the action is simply denied.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { emit, record } from "../stub-agent.mjs";
|
|
7
|
+
|
|
8
|
+
/** What a plugin directory (--plugin-dir) holds, as the real CLI would load it: its name and its skills. */
|
|
9
|
+
function pluginOf(dir) {
|
|
10
|
+
if (!dir) return null;
|
|
11
|
+
const name = JSON.parse(fs.readFileSync(path.join(dir, ".claude-plugin", "plugin.json"), "utf8")).name;
|
|
12
|
+
const skillsDir = path.join(dir, "skills");
|
|
13
|
+
const skills = fs.existsSync(skillsDir) ? fs.readdirSync(skillsDir).sort() : [];
|
|
14
|
+
// Each skill's SKILL.md and files as they are now, for tests of what relay put there (the directory is gone after the turn).
|
|
15
|
+
const files = (d, pre = "") => fs.readdirSync(d).flatMap((f) => (fs.lstatSync(path.join(d, f)).isDirectory() ? files(path.join(d, f), `${pre}${f}/`) : [`${pre}${f}`]));
|
|
16
|
+
const content = Object.fromEntries(skills.map((s) => [s, { skill: fs.readFileSync(path.join(skillsDir, s, "SKILL.md"), "utf8"), files: files(path.join(skillsDir, s)) }]));
|
|
17
|
+
return { name, dir, skills, content };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Permissions refused in this turn. The real CLI lists them in its result as permission_denials. */
|
|
21
|
+
const denied = [];
|
|
22
|
+
/** Whether this turn was asked to run in fast mode (its settings' fastMode). */
|
|
23
|
+
let fast = false;
|
|
24
|
+
|
|
25
|
+
export default {
|
|
26
|
+
id: "claude",
|
|
27
|
+
version: "2.1.302 (stub Claude Code)",
|
|
28
|
+
|
|
29
|
+
parse(argv) {
|
|
30
|
+
const val = (flag) => (argv.includes(flag) ? argv[argv.indexOf(flag) + 1] : undefined);
|
|
31
|
+
const resume = val("--resume");
|
|
32
|
+
const mcpFile = val("--mcp-config");
|
|
33
|
+
const relay = mcpFile ? JSON.parse(fs.readFileSync(mcpFile, "utf8")).mcpServers?.relay : undefined;
|
|
34
|
+
const mode = val("--permission-mode");
|
|
35
|
+
// The settings file relay passes (--settings), for tests of what it sets there (fastMode, say).
|
|
36
|
+
const settingsFile = val("--settings");
|
|
37
|
+
const settings = settingsFile && fs.existsSync(settingsFile) ? JSON.parse(fs.readFileSync(settingsFile, "utf8")) : null;
|
|
38
|
+
return {
|
|
39
|
+
sessionId: resume ?? val("--session-id"), resumed: Boolean(resume), relay,
|
|
40
|
+
access: mode === "dontAsk" || mode === "manual" ? "read" : mode === "acceptEdits" ? "write" : argv.includes("--dangerously-skip-permissions") ? "danger" : "unknown",
|
|
41
|
+
strict: argv.includes("--strict-mcp-config"),
|
|
42
|
+
promptTool: val("--permission-prompt-tool"),
|
|
43
|
+
plugin: pluginOf(val("--plugin-dir")),
|
|
44
|
+
get extra() {
|
|
45
|
+
return this.plugin ? { pluginSkills: this.plugin.content } : {};
|
|
46
|
+
},
|
|
47
|
+
settings,
|
|
48
|
+
skillSources: val("--setting-sources")?.split(",") ?? ["user", "project", "local"],
|
|
49
|
+
noSkills: argv.includes("--disable-slash-commands"),
|
|
50
|
+
};
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Once it has read its prompt, as Claude Code 2.1.309 does: its sandbox, given external proxy
|
|
55
|
+
* ports and SRT_DEBUG, reports them on stderr as it starts (STUB_SRT_SILENT: it does not;
|
|
56
|
+
* STUB_SRT_PORT: it reports another port); and with HTTPS_PROXY its model request goes through
|
|
57
|
+
* that proxy with the URL's credentials (STUB_UNPROXIED: it does not; STUB_PROXY_HOST: to another
|
|
58
|
+
* host than the model endpoint). The endpoint is the test home's stub (helpers.ts), which relay's
|
|
59
|
+
* proxy maps to a closed loopback port: the stub needs no network.
|
|
60
|
+
*/
|
|
61
|
+
async afterPrompt(parsed) {
|
|
62
|
+
const ports = parsed.settings?.sandbox?.network;
|
|
63
|
+
if (ports?.httpProxyPort && process.env.SRT_DEBUG && !process.env.STUB_SRT_SILENT) {
|
|
64
|
+
const port = process.env.STUB_SRT_PORT ?? ports.httpProxyPort;
|
|
65
|
+
process.stderr.write(`[SandboxDebug] Sandbox configuration updated\n[SandboxDebug] Using external HTTP proxy on port ${port}\n[SandboxDebug] Using external SOCKS proxy on port ${ports.socksProxyPort}\n[SandboxDebug] Network infrastructure initialized\n`);
|
|
66
|
+
}
|
|
67
|
+
const proxy = process.env.HTTPS_PROXY ? new URL(process.env.HTTPS_PROXY) : null;
|
|
68
|
+
if (!proxy || process.env.STUB_UNPROXIED) return;
|
|
69
|
+
const auth = Buffer.from(`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`).toString("base64");
|
|
70
|
+
await new Promise((resolve) => {
|
|
71
|
+
const s = net.connect(Number(proxy.port), proxy.hostname.replace(/^\[|\]$/g, ""));
|
|
72
|
+
const host = process.env.STUB_PROXY_HOST ?? "model.relay-test.invalid";
|
|
73
|
+
// A model request as the real CLI sends one to an http:// base URL: absolute-form, through the proxy.
|
|
74
|
+
s.on("connect", () => s.write(`POST http://${host}/v1/messages HTTP/1.1\r\nHost: ${host}\r\nProxy-Authorization: Basic ${auth}\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}`));
|
|
75
|
+
s.on("data", () => {});
|
|
76
|
+
s.on("end", () => s.destroy());
|
|
77
|
+
s.on("error", resolve);
|
|
78
|
+
s.on("close", resolve);
|
|
79
|
+
});
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
start(argv, parsed, sessionId) {
|
|
83
|
+
// What the real CLI reports for the permission mode it was given (checked against Claude Code 2.1.286).
|
|
84
|
+
const reportedMode = { acceptEdits: "acceptEdits", manual: "default", dontAsk: "dontAsk", bypassPermissions: "bypassPermissions" }[argv[argv.indexOf("--permission-mode") + 1]] ?? (argv.includes("--dangerously-skip-permissions") ? "bypassPermissions" : "default");
|
|
85
|
+
// The model as the real CLI reports it: an alias such as opus is resolved to a full Claude model id.
|
|
86
|
+
const asked = argv.includes("--model") ? argv[argv.indexOf("--model") + 1] : "sonnet";
|
|
87
|
+
const model = asked.startsWith("claude-") ? asked : `claude-${asked}-stub`;
|
|
88
|
+
// Its skills and plugins as Claude Code 2.1.302 reports them: a bundled skill, a built-in plugin,
|
|
89
|
+
// and a plugin from --plugin-dir with its skills as <plugin>:<skill>. A test's STUB_INIT may
|
|
90
|
+
// name the plugin directory as @PKG@.
|
|
91
|
+
// A skill whose front matter says user-invocable false is loaded but left out of the list, as 2.1.302 does.
|
|
92
|
+
const p = parsed.plugin;
|
|
93
|
+
const listedSkill = (s) => !/^user-invocable:[ \t]*["']?(?:false|no|off|0)["']?[ \t]*$/im.test(p.content[s].skill.split(/^---$/m)[1] ?? "");
|
|
94
|
+
const own = [];
|
|
95
|
+
const from = (dir) => {
|
|
96
|
+
if (!fs.existsSync(dir)) return;
|
|
97
|
+
for (const name of fs.readdirSync(dir)) if (fs.existsSync(path.join(dir, name, "SKILL.md"))) {
|
|
98
|
+
if (parsed.settings?.skillOverrides?.[name] !== "off") own.push(name);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
if (parsed.skillSources.includes("user")) from(path.join(process.env.CLAUDE_CONFIG_DIR || path.join(process.env.HOME, ".claude"), "skills"));
|
|
102
|
+
if (parsed.skillSources.includes("project")) for (let d = process.cwd(); ; d = path.dirname(d)) {
|
|
103
|
+
from(path.join(d, ".claude/skills"));
|
|
104
|
+
if (fs.existsSync(path.join(d, ".git")) || path.dirname(d) === d) break;
|
|
105
|
+
}
|
|
106
|
+
const skills = parsed.noSkills ? [] : [...own, ...(parsed.settings?.disableBundledSkills ? [] : ["debug"]), ...(p ? p.skills.filter(listedSkill).map((s) => `${p.name}:${s}`) : [])];
|
|
107
|
+
const plugins = [...(p ? [{ name: p.name, path: p.dir, source: `${p.name}@inline` }] : []), ...(parsed.settings?.disableBundledSkills ? [] : [{ name: "cc-plugin-telemetry", path: "builtin", source: "cc-plugin-telemetry@builtin" }])];
|
|
108
|
+
// Fast mode as the real CLI reports it (2.1.302): on when its settings ask for it, off otherwise. A test can overlay it.
|
|
109
|
+
fast = Boolean(parsed.settings?.fastMode);
|
|
110
|
+
const overlay = JSON.parse((process.env.STUB_INIT ?? "{}").replaceAll("@PKG@", p?.dir ?? ""));
|
|
111
|
+
record({ event: "skills-init", target: "claude", skills: overlay.skills ?? skills, plugins: overlay.plugins ?? plugins });
|
|
112
|
+
emit({ type: "system", subtype: "init", session_id: sessionId, model, permissionMode: reportedMode, apiKeySource: "none", tools: [], mcp_servers: [], skills, plugins, fast_mode_state: fast ? "on" : "off", ...overlay });
|
|
113
|
+
// The model's first message, for tests of what relay checks when it arrives.
|
|
114
|
+
// With --include-partial-messages, the response's start first, as the real CLI streams it.
|
|
115
|
+
if (process.env.STUB_ASSISTANT && argv.includes("--include-partial-messages")) emit({ type: "stream_event", event: { type: "message_start", message: { id: "msg_stub", role: "assistant", content: [] } }, session_id: sessionId });
|
|
116
|
+
if (process.env.STUB_ASSISTANT) emit({ type: "assistant", message: { role: "assistant", content: [{ type: "text", text: "working" }] }, session_id: sessionId });
|
|
117
|
+
},
|
|
118
|
+
|
|
119
|
+
ask: (parsed) => async (command, callTool) => {
|
|
120
|
+
// A request is a shell command to run outside the sandbox by default; { sandboxed: "command" } is one that asks while staying
|
|
121
|
+
// in it, and { web: "query" }, { fetch: "url" } and { edit: "path" } use the other tools.
|
|
122
|
+
const args = typeof command === "string" ? { tool_name: "Bash", input: { command, dangerouslyDisableSandbox: true } }
|
|
123
|
+
: command.sandboxed ? { tool_name: "Bash", input: { command: command.sandboxed } }
|
|
124
|
+
: command.web ? { tool_name: "WebSearch", input: { query: command.web } }
|
|
125
|
+
: command.fetch ? { tool_name: "WebFetch", input: { url: command.fetch } }
|
|
126
|
+
: { tool_name: "Edit", input: { file_path: command.edit.replaceAll("$RELAY_HOME", process.env.RELAY_HOME ?? "") } };
|
|
127
|
+
// With nowhere to ask, the real CLI refuses the permission on the spot, and lists it all the same.
|
|
128
|
+
if (!parsed.promptTool) {
|
|
129
|
+
denied.push({ tool_name: args.tool_name, tool_use_id: "toolu_stub", tool_input: args.input });
|
|
130
|
+
return { decision: "deny", message: "no approval channel" };
|
|
131
|
+
}
|
|
132
|
+
const res = await callTool(parsed.promptTool.split("__").pop(), { ...args, tool_use_id: "toolu_stub" });
|
|
133
|
+
if (res.behavior !== "allow") denied.push({ tool_name: args.tool_name, tool_use_id: "toolu_stub", tool_input: args.input });
|
|
134
|
+
// What an allowed call goes ahead with is the input relay hands back.
|
|
135
|
+
return res.behavior === "allow" ? { decision: "allow", input: res.updatedInput } : { decision: "deny", message: res.message ?? res.error };
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
fail: (failure, sessionId) => emit({ type: "result", subtype: "error_during_execution", is_error: true, errors: [failure], session_id: sessionId, permission_denials: denied }),
|
|
139
|
+
// Usage as the real CLI reports it for one `claude -p` invocation.
|
|
140
|
+
// With fast mode, its state and the speed the turn ran at (usage.speed), as the real CLI reports them (2.1.302); a test can overlay the result (STUB_RESULT).
|
|
141
|
+
finish: (reply, sessionId) => {
|
|
142
|
+
const extra = JSON.parse(process.env.STUB_RESULT ?? "{}");
|
|
143
|
+
emit({
|
|
144
|
+
type: "result", subtype: "success", is_error: false, result: reply, session_id: sessionId, num_turns: 3, total_cost_usd: 0.0125, permission_denials: denied,
|
|
145
|
+
fast_mode_state: fast ? "on" : "off", ...extra,
|
|
146
|
+
usage: { input_tokens: 1200, cache_creation_input_tokens: 300, cache_read_input_tokens: 5000, output_tokens: 400, speed: fast ? "fast" : "standard", ...(extra.usage ?? {}) },
|
|
147
|
+
});
|
|
148
|
+
},
|
|
149
|
+
};
|