@jbkjr/relay 0.0.0-stage → 1.2.1
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 +386 -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 +1525 -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 +320 -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 +637 -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 +329 -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 +629 -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 +1502 -0
- package/docs/pinned-codex.md +321 -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,209 @@
|
|
|
1
|
+
import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
import { insideRelaySandbox, logElicitation, onceOnly, requestView } from "../core/approvals.js";
|
|
3
|
+
import { personOnly } from "../core/extensions.js";
|
|
4
|
+
import { runConfig } from "../core/db.js";
|
|
5
|
+
import { shown } from "../core/shown.js";
|
|
6
|
+
import { lateAnswer } from "../core/watch.js";
|
|
7
|
+
/** The longest delay a Node timer takes (a longer one fires at once): about 24.8 days. */
|
|
8
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
9
|
+
/** The key in a question's _meta that names the request it is about. */
|
|
10
|
+
const REQUEST_META = "relay/request";
|
|
11
|
+
/** The decisions an approval dialog offers. */
|
|
12
|
+
const DECISIONS = ["allow", "allow for the rest of this job", "deny"];
|
|
13
|
+
/** The same, safe one first, for a form that preselects its first choice (HostProfile.safeFirst). */
|
|
14
|
+
const SAFE_FIRST = ["deny", "allow", "allow for the rest of this job"];
|
|
15
|
+
/** How soon after a cancellation relay sent a "cancel" is taken for the host's acknowledgement of it. */
|
|
16
|
+
const CANCEL_ACK_MS = 500;
|
|
17
|
+
/**
|
|
18
|
+
* Whether a host's answer is its acknowledgement of a cancellation relay sent (`cancelledAt`), not
|
|
19
|
+
* a person's answer: a "cancel" arriving within CANCEL_ACK_MS after it. Codex answers a
|
|
20
|
+
* cancellation of a form it keeps on screen with "cancel" at once.
|
|
21
|
+
*/
|
|
22
|
+
export function acknowledgesCancel(action, cancelledAt, at) {
|
|
23
|
+
return action === "cancel" && cancelledAt !== undefined && at >= cancelledAt && at - cancelledAt <= CANCEL_ACK_MS;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The approval dialog of one relay server: for a host profile, the function that asks the user
|
|
27
|
+
* about one request and says how it ended. The questions the server sent are tracked here, by the
|
|
28
|
+
* transport's messages, for hosts that keep a withdrawn form.
|
|
29
|
+
*/
|
|
30
|
+
export function questionsThrough(server) {
|
|
31
|
+
/**
|
|
32
|
+
* For hosts that keep a withdrawn form (HostProfile.withdraws false), the questions sent, by
|
|
33
|
+
* their JSON-RPC id, and when a cancellation of one went out, by request id. Relay sends such a
|
|
34
|
+
* host no cancellation: Codex answers one with "cancel" at once and stops listening for the
|
|
35
|
+
* person's answer. Should one go out all the same, a "cancel" that follows it at once is its
|
|
36
|
+
* acknowledgement, not an answer (acknowledgesCancel). Read from what the transport sends, by
|
|
37
|
+
* the request id relay puts in the question's _meta.
|
|
38
|
+
*/
|
|
39
|
+
const questionOf = new Map();
|
|
40
|
+
const cancelSentAt = new Map();
|
|
41
|
+
let tapped = false;
|
|
42
|
+
const tapQuestions = () => {
|
|
43
|
+
const t = server.server.transport;
|
|
44
|
+
if (!t || tapped)
|
|
45
|
+
return;
|
|
46
|
+
tapped = true;
|
|
47
|
+
const send = t.send.bind(t);
|
|
48
|
+
t.send = (msg, opts) => {
|
|
49
|
+
const m = msg;
|
|
50
|
+
const request = m.method === "elicitation/create" ? m.params?._meta?.[REQUEST_META] : undefined;
|
|
51
|
+
if (typeof request === "string" && m.id !== undefined)
|
|
52
|
+
questionOf.set(m.id, request);
|
|
53
|
+
const cancelled = m.method === "notifications/cancelled" && m.params?.requestId !== undefined ? questionOf.get(m.params.requestId) : undefined;
|
|
54
|
+
if (cancelled)
|
|
55
|
+
cancelSentAt.set(cancelled, Date.now());
|
|
56
|
+
return send(msg, opts);
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
/** Asks the user about one request through the host, and says how it ended. */
|
|
60
|
+
const elicitThrough = (profile) => async (r, signal) => {
|
|
61
|
+
const v = requestView(r);
|
|
62
|
+
const asked = Date.now();
|
|
63
|
+
const record = (action, reading) => logElicitation({ request: r.id, host: profile.why, action, ms: Date.now() - asked, reading });
|
|
64
|
+
/**
|
|
65
|
+
* How relay reads what the host answered, and how that goes in the log: a decision only if it
|
|
66
|
+
* is exactly one the form offered.
|
|
67
|
+
*/
|
|
68
|
+
const read = (res) => {
|
|
69
|
+
// Only an answer that is exactly one of the offered decisions decides. Anything else (no
|
|
70
|
+
// decision, one that was not offered, a note that is not text) is not what the dialog lets a
|
|
71
|
+
// person give, so it leaves the request undecided rather than being read as either.
|
|
72
|
+
const decision = res.action === "accept" ? res.content?.decision : undefined;
|
|
73
|
+
const rawNote = res.action === "accept" ? res.content?.note : undefined;
|
|
74
|
+
if (typeof decision === "string" && DECISIONS.includes(decision) && (!onceOnly(r) || decision !== "allow for the rest of this job") && (rawNote === undefined || typeof rawNote === "string")) {
|
|
75
|
+
// A host relay does not know to show the question to a person (ask_user "always") may
|
|
76
|
+
// answer it on its own: its allow of a request only the person may allow decides nothing.
|
|
77
|
+
// Its deny still binds.
|
|
78
|
+
if (decision !== "deny" && profile.elicit !== "dialog" && personOnly(r)) {
|
|
79
|
+
return { answer: { reading: "unattributed", outcome: "accept (unattributed: only the person may allow it)" }, logAs: ["accept", "unattributed allow of a person-only request: left undecided"] };
|
|
80
|
+
}
|
|
81
|
+
const note = rawNote ? rawNote : undefined;
|
|
82
|
+
return { answer: { reading: "decided", outcome: "accept", allow: decision !== "deny", forJob: decision === "allow for the rest of this job", note }, logAs: ["accept", decision] };
|
|
83
|
+
}
|
|
84
|
+
// An answer that is not one the form lets a person give is the host's, not theirs.
|
|
85
|
+
if (res.action === "accept")
|
|
86
|
+
return { answer: { reading: "unattributed", outcome: "accept (unqualified)" }, logAs: ["accept", "unqualified: left undecided"] };
|
|
87
|
+
if (res.action === "decline" && profile.declineIsDenial) {
|
|
88
|
+
return { answer: { reading: "decided", outcome: "decline", allow: false, note: "declined by the user" }, logAs: ["decline", "denied by the user"] };
|
|
89
|
+
}
|
|
90
|
+
// "cancel" carries no decision: the user closed the question (Esc), or the host could not
|
|
91
|
+
// show it. Either way the request stays pending, for the calling agent or the terminal. It is
|
|
92
|
+
// read as the person's closing only where the host is known to put it to a person and to
|
|
93
|
+
// cancel only when they close it (interactive Claude Code); elsewhere, as a decline relay does
|
|
94
|
+
// not take for a denial, it is the host's answer, which may not be anyone's.
|
|
95
|
+
if (res.action === "cancel" && profile.elicit === "dialog" && profile.declineIsDenial) {
|
|
96
|
+
return { answer: { reading: "dismissed", outcome: "cancel" }, logAs: ["cancel", "dismissed: left undecided"] };
|
|
97
|
+
}
|
|
98
|
+
return { answer: { reading: "unattributed", outcome: res.action }, logAs: [res.action, "unattributed: left undecided"] };
|
|
99
|
+
};
|
|
100
|
+
const answerOf = (res) => {
|
|
101
|
+
const { answer, logAs } = read(res);
|
|
102
|
+
record(...logAs);
|
|
103
|
+
return answer;
|
|
104
|
+
};
|
|
105
|
+
// A host that keeps a withdrawn form keeps the question open after it is decided elsewhere,
|
|
106
|
+
// and the person can still answer it. Relay sends no cancellation then (Codex would answer it
|
|
107
|
+
// with "cancel" and stop listening): it keeps the question open, and an answer that comes
|
|
108
|
+
// later is recorded and reported. The agent's turn is held either way.
|
|
109
|
+
const keeps = !profile.withdraws;
|
|
110
|
+
if (keeps)
|
|
111
|
+
tapQuestions();
|
|
112
|
+
const question = server.server.elicitInput({
|
|
113
|
+
// Claude Code shows the first lines and folds the rest, so the essentials come first: who
|
|
114
|
+
// asks and what allowing it does, what exactly, and where.
|
|
115
|
+
message: [
|
|
116
|
+
`relay: the ${v.agent} agent ${v.from} asks for approval${insideRelaySandbox(r) ? " to go ahead inside relay's sandbox" : ""}. Effect: ${v.effect}.`,
|
|
117
|
+
`Wants: ${shown(r.summary)}`,
|
|
118
|
+
`In: ${shown(String(v.in_directory))}`,
|
|
119
|
+
...(r.reason ? [`Its reason: ${shown(r.reason)}`] : []),
|
|
120
|
+
...(personOnly(r) ? ["Only you can allow this: the agent supervising the run can only deny it."] : []),
|
|
121
|
+
...(r.kind === "env" ? [`Environment disclosure (names and execution metadata only): ${shown(JSON.stringify(v.environment))}`] : []),
|
|
122
|
+
// The task is agent-written text too (whichever agent delegated the job), so it is escaped like the rest.
|
|
123
|
+
`Its task (depth ${v.depth}, ${v.session} session): ${shown(String(v.task))}`,
|
|
124
|
+
...(keeps ? ["If it is decided elsewhere first (by the agent or from a terminal), this form stays open until you answer it or press Esc; an answer then changes nothing, and relay tells the agent so."] : []),
|
|
125
|
+
].join("\n"),
|
|
126
|
+
requestedSchema: {
|
|
127
|
+
type: "object",
|
|
128
|
+
properties: {
|
|
129
|
+
// A form that preselects its first choice, where Enter submits it at once (Codex), gets
|
|
130
|
+
// deny first, so that a stray Enter allows nothing.
|
|
131
|
+
decision: { type: "string", enum: (profile.safeFirst ? [...SAFE_FIRST] : [...DECISIONS]).filter((d) => !onceOnly(r) || d !== "allow for the rest of this job"), title: "Decision" },
|
|
132
|
+
// Codex's form could not be submitted with an optional text field left empty.
|
|
133
|
+
...(profile.formNote ? { note: { type: "string", title: "Note to the agent (optional)" } } : {}),
|
|
134
|
+
},
|
|
135
|
+
required: ["decision"],
|
|
136
|
+
},
|
|
137
|
+
...(keeps ? { _meta: { [REQUEST_META]: r.id } } : {}),
|
|
138
|
+
},
|
|
139
|
+
// Open for as long as the request can be answered; withdrawn if it is decided elsewhere first.
|
|
140
|
+
// A form the host keeps can be answered for as long as it is on screen, so the SDK keeps
|
|
141
|
+
// listening as long as the connection lasts: the request's own deadline (requestApproval)
|
|
142
|
+
// withdraws the question, and the connection closing ends the wait for an answer.
|
|
143
|
+
{ timeout: keeps ? MAX_TIMER_MS : runConfig(r.run_id).approval_timeout_s * 1000, ...(keeps ? {} : { signal }) });
|
|
144
|
+
const failed = (err) => {
|
|
145
|
+
// An accepted answer that does not fit the form (the SDK checks it against the schema) is
|
|
146
|
+
// not one a person could have given in the dialog: undecided, and not asked again.
|
|
147
|
+
if (err instanceof McpError && err.code === ErrorCode.InvalidParams && /requested schema/.test(err.message)) {
|
|
148
|
+
record("accept", "unqualified: left undecided");
|
|
149
|
+
return { reading: "unattributed", outcome: "accept (unqualified)" };
|
|
150
|
+
}
|
|
151
|
+
const message = String(err.message).slice(0, 120);
|
|
152
|
+
record("error", message);
|
|
153
|
+
return { reading: "error", outcome: message };
|
|
154
|
+
};
|
|
155
|
+
if (!keeps) {
|
|
156
|
+
try {
|
|
157
|
+
return answerOf(await question);
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
if (signal.aborted) {
|
|
161
|
+
record("withdrawn", "decided elsewhere first");
|
|
162
|
+
return { reading: "withdrawn", outcome: "withdrawn" };
|
|
163
|
+
}
|
|
164
|
+
return failed(err);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
// Whichever comes first: the answer, or the request being decided elsewhere.
|
|
168
|
+
const withdrawn = new Promise((resolve) => {
|
|
169
|
+
if (signal.aborted)
|
|
170
|
+
resolve("withdrawn");
|
|
171
|
+
else
|
|
172
|
+
signal.addEventListener("abort", () => resolve("withdrawn"), { once: true });
|
|
173
|
+
});
|
|
174
|
+
const answered = question.then((res) => ({ res }), (err) => ({ err }));
|
|
175
|
+
const first = await Promise.race([answered, withdrawn]);
|
|
176
|
+
if (first !== "withdrawn") {
|
|
177
|
+
return "err" in first ? failed(first.err) : answerOf(first.res);
|
|
178
|
+
}
|
|
179
|
+
record("withdrawn", "decided elsewhere first; the host keeps the form open");
|
|
180
|
+
void answered.then((late) => {
|
|
181
|
+
for (const [q, req] of questionOf)
|
|
182
|
+
if (req === r.id)
|
|
183
|
+
questionOf.delete(q);
|
|
184
|
+
const cancelledAt = cancelSentAt.get(r.id);
|
|
185
|
+
cancelSentAt.delete(r.id);
|
|
186
|
+
if ("err" in late)
|
|
187
|
+
return record("late", `the form ended without an answer (${String(late.err?.message).slice(0, 80)})`);
|
|
188
|
+
if (acknowledgesCancel(late.res.action, cancelledAt, Date.now()))
|
|
189
|
+
return record("late", "cancel acknowledging a cancellation relay sent: not an answer");
|
|
190
|
+
// Nothing is decided by it either way, so a decline is reported too: it may well be the
|
|
191
|
+
// person's, and they may expect it to have stopped something. Whose it is goes with it: a
|
|
192
|
+
// decline relay does not take for a denial is the host's answer, which may not be anyone's.
|
|
193
|
+
const { answer, logAs } = read(late.res);
|
|
194
|
+
const said = late.res.action === "decline" ? "decline" : answer.reading === "decided" ? logAs[1] : null;
|
|
195
|
+
if (!said)
|
|
196
|
+
return record("late", `${logAs[1]} after it was decided elsewhere: nothing to report`);
|
|
197
|
+
const by = answer.reading === "decided" ? "user" : "host";
|
|
198
|
+
record("late", `${said}${by === "host" ? " (unattributed)" : ""} after it was decided elsewhere: changed nothing`);
|
|
199
|
+
try {
|
|
200
|
+
lateAnswer(r.id, said, by);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
// The registry is busy or gone; the answer is in the log.
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
return { reading: "withdrawn", outcome: "withdrawn" };
|
|
207
|
+
};
|
|
208
|
+
return elicitThrough;
|
|
209
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// The gateway (docs/extensions.md): in the relay server of a launched agent's turn given MCP
|
|
2
|
+
// servers, relay starts each server as its own client and offers the server's tools as its own,
|
|
3
|
+
// named <server>__<tool>. The harness allows relay's tools without asking (Claude's
|
|
4
|
+
// --allowedTools mcp__relay, Codex's approve mode on relay's entry), so every call reaches relay,
|
|
5
|
+
// which forwards it only if the config allows that tool outright or the person allows the call.
|
|
6
|
+
// No server is ever configured in the harness itself, so the harness's own MCP approval handling
|
|
7
|
+
// (unqualified for Codex) decides nothing.
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { expandHome, relayHome, VERSION } from "../core/config.js";
|
|
12
|
+
import { ownManifest, readMcpFile } from "../core/extensions.js";
|
|
13
|
+
import { checkpointNever } from "../core/never-checkpoint.js";
|
|
14
|
+
import { neverDigest } from "../core/never-policy.js";
|
|
15
|
+
import { extensionToolProblem, neverToolAdapters, screenExtensionCall } from "../core/never-tools.js";
|
|
16
|
+
/** How long the gateway waits for its servers before the agent's relay server answers the harness: under both harnesses' startup timeouts (30 s). */
|
|
17
|
+
const START_MS = 20_000;
|
|
18
|
+
/** A name on relay's server, as both harnesses take tool names. */
|
|
19
|
+
const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
20
|
+
function withTimeout(p, ms, what) {
|
|
21
|
+
let timer;
|
|
22
|
+
const late = new Promise((_, reject) => {
|
|
23
|
+
timer = setTimeout(() => reject(new Error(`${what} took longer than ${Math.round(ms / 1000)} s`)), ms);
|
|
24
|
+
});
|
|
25
|
+
return Promise.race([p, late]).finally(() => clearTimeout(timer));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Starts the servers a turn's manifest names and lists their tools. A server that cannot be
|
|
29
|
+
* started, or a tool relay cannot pass on (a name or an input schema it cannot offer as given),
|
|
30
|
+
* is left out and reported, never offered in some other form. The report goes beside the
|
|
31
|
+
* manifest, for the worker to put in the turn's result.
|
|
32
|
+
*/
|
|
33
|
+
export async function openGateway(manifestFile, suppliedCatalog) {
|
|
34
|
+
const warnings = [];
|
|
35
|
+
const tools = [];
|
|
36
|
+
const clients = [];
|
|
37
|
+
const close = async () => {
|
|
38
|
+
await Promise.all(clients.map((c) => c.close().catch(() => { })));
|
|
39
|
+
};
|
|
40
|
+
let manifest;
|
|
41
|
+
let policy;
|
|
42
|
+
let catalog = suppliedCatalog ?? [];
|
|
43
|
+
const screen = async (tool, args) => {
|
|
44
|
+
try {
|
|
45
|
+
if (!manifest.run_id)
|
|
46
|
+
throw new Error("gateway has no trusted run binding");
|
|
47
|
+
const current = checkpointNever(manifest.run_id, "tool");
|
|
48
|
+
return await screenExtensionCall(current, tool.identity, args, catalog);
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
return { allow: false, reason: `never: ${err.message}`, policyHash: policy?.hash ?? "unavailable" };
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
try {
|
|
55
|
+
// Only a manifest relay wrote, in its control directory, which no agent can write.
|
|
56
|
+
if (!ownManifest(manifestFile, relayHome()))
|
|
57
|
+
throw new Error("it is not in relay's control directory");
|
|
58
|
+
manifest = JSON.parse(fs.readFileSync(manifestFile, "utf8"));
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
return { tools, warnings: [`relay could not read the turn's list of MCP servers (${err.message}), so none of them is offered`], close, screen };
|
|
62
|
+
}
|
|
63
|
+
const report = () => {
|
|
64
|
+
try {
|
|
65
|
+
fs.writeFileSync(manifest.report, JSON.stringify({ started: [...new Set(tools.map((t) => t.server))], tools: tools.map((t) => t.name), warnings }, null, 2));
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// The result then says nothing about it; the agent sees the tools it has.
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
let defs;
|
|
72
|
+
try {
|
|
73
|
+
if (!manifest.run_id)
|
|
74
|
+
throw new Error("never withholds extension tools without a trusted run binding");
|
|
75
|
+
policy = checkpointNever(manifest.run_id, "tool");
|
|
76
|
+
defs = readMcpFile(manifest.mcp_file);
|
|
77
|
+
catalog = suppliedCatalog ?? await neverToolAdapters(defs);
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
warnings.push(`${err.message}, so none of the job's MCP servers is offered`);
|
|
81
|
+
report();
|
|
82
|
+
return { tools, warnings, close, screen };
|
|
83
|
+
}
|
|
84
|
+
// The servers get the agent's relay server's environment (the agent's, as its harness passes it
|
|
85
|
+
// on), without relay's own identity, plus their own variables.
|
|
86
|
+
const base = Object.fromEntries(Object.entries(process.env).filter(([k, v]) => v !== undefined && !k.startsWith("RELAY_")));
|
|
87
|
+
// The SDK's client is loaded here, by the one kind of server that uses it, rather than by every
|
|
88
|
+
// relay server at start. A failure to load it fails this server's start, as it did before.
|
|
89
|
+
const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
|
|
90
|
+
const { StdioClientTransport } = await import("@modelcontextprotocol/sdk/client/stdio.js");
|
|
91
|
+
const deadline = Date.now() + START_MS;
|
|
92
|
+
await Promise.all(manifest.servers.map(async (s) => {
|
|
93
|
+
const def = defs[s.name];
|
|
94
|
+
if (!def)
|
|
95
|
+
return void warnings.push(`the MCP server ${s.name} is no longer defined in ${manifest.mcp_file}; its tools are not offered`);
|
|
96
|
+
const definitionHash = neverDigest(def);
|
|
97
|
+
if (!catalog.some(a => a.identity.server === s.name && a.identity.definitionHash === definitionHash)) {
|
|
98
|
+
warnings.push(`never withholds every tool of ${s.name}: no qualified effects adapter for this server definition; opaque/implicit effects cannot be person-approved`);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const client = new Client({ name: "relay", version: VERSION });
|
|
102
|
+
try {
|
|
103
|
+
// Started in its own directory or the home folder, never the agent's: a file the agent wrote there must not steer it.
|
|
104
|
+
const transport = new StdioClientTransport({
|
|
105
|
+
command: expandHome(def.command), args: def.args ?? [], env: { ...base, ...(def.env ?? {}) }, cwd: def.cwd ? expandHome(def.cwd) : os.homedir(), stderr: "ignore",
|
|
106
|
+
});
|
|
107
|
+
clients.push(client);
|
|
108
|
+
await withTimeout(client.connect(transport), Math.max(1, deadline - Date.now()), "starting it");
|
|
109
|
+
const listed = [];
|
|
110
|
+
for (let cursor, pages = 0; pages < 20; pages++) {
|
|
111
|
+
const page = await withTimeout(client.listTools(cursor ? { cursor } : undefined), Math.max(1, deadline - Date.now()), "listing its tools");
|
|
112
|
+
listed.push(...page.tools);
|
|
113
|
+
cursor = page.nextCursor;
|
|
114
|
+
if (!cursor)
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
for (const t of listed) {
|
|
118
|
+
const identity = { server: s.name, version: client.getServerVersion()?.version ?? "", definitionHash, tool: t.name, schemaHash: neverDigest(t.inputSchema) };
|
|
119
|
+
const problem = extensionToolProblem(identity, catalog);
|
|
120
|
+
if (problem) {
|
|
121
|
+
warnings.push(problem);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const name = `${s.name}__${t.name}`;
|
|
125
|
+
if (tools.some((o) => o.name === name)) {
|
|
126
|
+
warnings.push(`the tool ${t.name} of ${s.name} is listed more than once; relay offers the first`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (!TOOL_NAME.test(name)) {
|
|
130
|
+
warnings.push(`the tool ${t.name} of ${s.name} is not offered: ${name} is not a name relay can give a tool`);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
let schema;
|
|
134
|
+
try {
|
|
135
|
+
schema = z.fromJSONSchema(t.inputSchema);
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
warnings.push(`the tool ${t.name} of ${s.name} is not offered: relay cannot check its input schema (${String(err.message).slice(0, 80)})`);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (!(schema instanceof z.ZodObject)) {
|
|
142
|
+
warnings.push(`the tool ${t.name} of ${s.name} is not offered: its input schema is not an object`);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
tools.push({
|
|
146
|
+
identity,
|
|
147
|
+
name, server: s.name, tool: t.name, description: t.description ?? "", schema, preauthorized: s.allow_tools.includes(t.name), client,
|
|
148
|
+
...(t.annotations ? { annotations: t.annotations } : {}),
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
const unknown = s.allow_tools.filter((a) => !listed.some((t) => t.name === a));
|
|
152
|
+
if (unknown.length)
|
|
153
|
+
warnings.push(`${s.name} has no tool ${unknown.join(", ")}, which its allow_tools names`);
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
warnings.push(`the MCP server ${s.name} could not be started (${String(err.message).slice(0, 160)}); its tools are not offered`);
|
|
157
|
+
await client.close().catch(() => { });
|
|
158
|
+
}
|
|
159
|
+
}));
|
|
160
|
+
tools.sort((a, b) => a.name.localeCompare(b.name));
|
|
161
|
+
report();
|
|
162
|
+
return { tools, warnings, close, screen };
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Offers the gateway's tools on relay's server. A call's arguments are checked against the tool's
|
|
166
|
+
* input schema first (the SDK does it, refusing malformed ones before the handler runs, so nobody
|
|
167
|
+
* is asked about them), then put to the person unless the tool runs without asking, then forwarded
|
|
168
|
+
* with exactly the arguments shown. A name relay did not list is an error and reaches no server.
|
|
169
|
+
* `over` says why the turn can no longer act (it has ended, or its work was cancelled), or null:
|
|
170
|
+
* once it is over no call is forwarded, one that runs without asking included, and nobody is asked.
|
|
171
|
+
*/
|
|
172
|
+
export function offerGateway(server, gw, ask, tick, over) {
|
|
173
|
+
const ended = (why) => ({ content: [{ type: "text", text: `Not forwarded: the turn that called it is over (${why}).` }], isError: true });
|
|
174
|
+
for (const t of gw.tools) {
|
|
175
|
+
const how = t.preauthorized ? "runs without asking the user" : "each call waits for the user's yes";
|
|
176
|
+
server.registerTool(t.name, {
|
|
177
|
+
description: `${t.description}${t.description ? " " : ""}[MCP server ${t.server}, through relay: ${how}.]`,
|
|
178
|
+
inputSchema: t.schema,
|
|
179
|
+
...(t.annotations ? { annotations: t.annotations } : {}),
|
|
180
|
+
}, async (args, extra) => {
|
|
181
|
+
const signal = extra.signal;
|
|
182
|
+
const gone = over();
|
|
183
|
+
if (gone)
|
|
184
|
+
return ended(gone);
|
|
185
|
+
const blocked = (why) => ({ content: [{ type: "text", text: `Not forwarded: ${why}` }], isError: true });
|
|
186
|
+
const first = await gw.screen(t, args);
|
|
187
|
+
if (!first.allow)
|
|
188
|
+
return blocked(first.reason);
|
|
189
|
+
if (!t.preauthorized) {
|
|
190
|
+
const summary = `${t.server}.${t.tool} ${JSON.stringify(args)}`;
|
|
191
|
+
const answer = await ask({ server: t.server, tool: t.tool, summary }, { signal, onTick: tick(extra) });
|
|
192
|
+
if (!answer.allow) {
|
|
193
|
+
return { content: [{ type: "text", text: `Not approved${answer.note ? ` (${answer.note})` : ""}. Do not try to reach ${t.server} another way; continue without it and say what you needed.` }], isError: true };
|
|
194
|
+
}
|
|
195
|
+
// Allowed, but the turn may have ended while the person was deciding.
|
|
196
|
+
const late = over();
|
|
197
|
+
if (late)
|
|
198
|
+
return ended(late);
|
|
199
|
+
}
|
|
200
|
+
// Consent and preauthorization never bypass semantic policy. Reload at invocation, after
|
|
201
|
+
// any approval wait, and invalidate changed effects rather than silently rewriting consent.
|
|
202
|
+
const checked = await gw.screen(t, args);
|
|
203
|
+
if (!checked.allow)
|
|
204
|
+
return blocked(checked.reason);
|
|
205
|
+
if (neverDigest(first.arguments) !== neverDigest(checked.arguments))
|
|
206
|
+
return blocked("never: effective tool arguments changed while approval was pending; ask again");
|
|
207
|
+
const late = over();
|
|
208
|
+
if (late)
|
|
209
|
+
return ended(late);
|
|
210
|
+
try {
|
|
211
|
+
return (await t.client.callTool({ name: t.tool, arguments: checked.arguments }, undefined, { signal, timeout: 3_600_000, resetTimeoutOnProgress: true }));
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
return { content: [{ type: "text", text: `${t.server} did not complete the call: ${String(err.message).slice(0, 300)}` }], isError: true };
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|