@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,1424 @@
|
|
|
1
|
+
// The generic ACP driver: one turn of a harness that speaks the Agent Client Protocol, version 1,
|
|
2
|
+
// as JSON-RPC over the harness's stdio (https://agentclientprotocol.com/protocol/v1). One process
|
|
3
|
+
// per turn, as with every other target, so no long-lived agent keeps an earlier turn's authority.
|
|
4
|
+
//
|
|
5
|
+
// ACP is relay's transport for these harnesses, not their security layer: nothing in the protocol
|
|
6
|
+
// sets or reports a sandbox, a login or the effective configuration. What a harness needs for
|
|
7
|
+
// those is in its profile (AcpProfile), and confinement is relay's own (see launch()).
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { assertNeverAdapter } from "./never-admission.js";
|
|
10
|
+
import { neverFloorApplies } from "../core/never-coverage.js";
|
|
11
|
+
import { neverIdentityProblem } from "../core/never-policy.js";
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import crypto from "node:crypto";
|
|
14
|
+
import { diagnosticTail } from "../core/redact.js";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import readline from "node:readline";
|
|
18
|
+
import { BRIDGE_SECRET_ENV } from "../confine/broker-names.js";
|
|
19
|
+
import { confinement, quarantineTokenStore } from "../confine/index.js";
|
|
20
|
+
import { loginStore, openTurnProxy, privateTurnTemp, turnPolicy } from "../confine/turn.js";
|
|
21
|
+
import { boundaryProbe, NO_PROBE } from "../confine/turn-probe.js";
|
|
22
|
+
import { streamSandboxDenials } from "../confine/diagnostics.js";
|
|
23
|
+
import { authFor, networkOn, relayHome, VERSION } from "../core/config.js";
|
|
24
|
+
import { executable } from "../core/executables.js";
|
|
25
|
+
import { drainGroup, isGroupSignalRefusal, killProcs, procStart, sendGroupSignal, stopProcs } from "../core/procs.js";
|
|
26
|
+
import { VENDOR_NAMES, targetLabel, vendorFor } from "../targets/index.js";
|
|
27
|
+
import { oneLine } from "../core/shown.js";
|
|
28
|
+
import { getTurn, updateTurn } from "../core/db.js";
|
|
29
|
+
import { redact, registerTurnSecret, streamSecretValues, withTurnSecrets } from "../core/secrets.js";
|
|
30
|
+
import { childEnv, endpointProblem } from "./env.js";
|
|
31
|
+
import { activityOf, approvalKey, askableReadOnly, openAgentLog, usageFrom, watchProcess } from "./types.js";
|
|
32
|
+
/** The one ACP protocol version relay speaks. v2 changes how a turn completes, so it is refused, not guessed at. */
|
|
33
|
+
const ACP_VERSION = 1;
|
|
34
|
+
/** JSON-RPC: the method does not exist (here: a client method relay does not provide). */
|
|
35
|
+
const METHOD_NOT_FOUND = -32601;
|
|
36
|
+
/** The shortest secret relay redacts: a shorter one could occur in ordinary text by chance. */
|
|
37
|
+
const MIN_SECRET = 16;
|
|
38
|
+
/** The streamed text updates relay reads as one stream for a turn's secrets (secretSafeLog). */
|
|
39
|
+
const STREAMED_TEXT = new Set(["agent_message_chunk", "agent_thought_chunk", "user_message_chunk"]);
|
|
40
|
+
/**
|
|
41
|
+
* The agent's log for a turn's known by-value secrets (profile, environment and registered
|
|
42
|
+
* proxy/bridge credentials, in every form core/secrets.ts cuts). Each line the agent writes is
|
|
43
|
+
* redacted on its own before anything reads it (redactor), but a model streams its words in
|
|
44
|
+
* pieces, and a secret split across two text chunks is whole in neither line. So, for such a turn
|
|
45
|
+
* only, everything written to the log is queued in the order it came, and the text of the streamed
|
|
46
|
+
* chunks (message, thought and replayed user chunks, whatever lines come between them) is read as
|
|
47
|
+
* one stream. A chunk's line is written once the stream has gone on past it by one character less
|
|
48
|
+
* than the longest secret, or when the log ends: by then any secret it holds a piece of is whole in
|
|
49
|
+
* the stream. Each occurrence is replaced by "[redacted]" in the line it starts in and cut from the
|
|
50
|
+
* lines it runs on into, and a line whose text changed is written re-serialized. Other lines wait
|
|
51
|
+
* only for the chunks before them, so that the log keeps its order. Only the log waits: what relay
|
|
52
|
+
* does with each line does not. A secret the agent encodes (base64, reversed) is not caught.
|
|
53
|
+
*/
|
|
54
|
+
export function secretSafeLog(log, secrets) {
|
|
55
|
+
const list = [...new Set(secrets)].filter((s) => s.length > 0);
|
|
56
|
+
if (!list.length) {
|
|
57
|
+
return {
|
|
58
|
+
write: (text) => log.write(text),
|
|
59
|
+
end: (callback) => log.end(callback),
|
|
60
|
+
get writableEnded() {
|
|
61
|
+
return log.writableEnded;
|
|
62
|
+
},
|
|
63
|
+
agent: (_m, line) => {
|
|
64
|
+
if (!log.writableEnded)
|
|
65
|
+
log.write(line + "\n");
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** How far the stream must run on past a chunk before every secret it holds a piece of is whole. */
|
|
70
|
+
const span = Math.max(...list.map((s) => s.length)) - 1;
|
|
71
|
+
const queue = [];
|
|
72
|
+
/** The stream's last `span` characters, where an occurrence that ends in text still to come starts. */
|
|
73
|
+
let tail = "";
|
|
74
|
+
/** The stream's length so far. */
|
|
75
|
+
let total = 0;
|
|
76
|
+
/** Occurrences [start, end) in the stream, by start, while a line not yet written holds part of one. */
|
|
77
|
+
let found = [];
|
|
78
|
+
const textOf = (m) => {
|
|
79
|
+
const u = m?.method === "session/update" ? m.params?.update : undefined;
|
|
80
|
+
return u && STREAMED_TEXT.has(u.sessionUpdate) && u.content?.type === "text" && typeof u.content.text === "string" ? u.content.text : null;
|
|
81
|
+
};
|
|
82
|
+
/** A chunk's text with every occurrence cut out, "[redacted]" where one starts in it. */
|
|
83
|
+
const masked = (c) => {
|
|
84
|
+
const cut = new Array(c.text.length).fill(false);
|
|
85
|
+
const starts = new Set();
|
|
86
|
+
for (const [a, b] of found) {
|
|
87
|
+
if (b <= c.start || a >= c.end)
|
|
88
|
+
continue;
|
|
89
|
+
for (let i = Math.max(a, c.start); i < Math.min(b, c.end); i++)
|
|
90
|
+
cut[i - c.start] = true;
|
|
91
|
+
if (a >= c.start)
|
|
92
|
+
starts.add(a - c.start);
|
|
93
|
+
}
|
|
94
|
+
let out = "";
|
|
95
|
+
for (let i = 0; i < c.text.length;) {
|
|
96
|
+
if (!cut[i]) {
|
|
97
|
+
out += c.text[i++];
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
let j = i;
|
|
101
|
+
let starting = false;
|
|
102
|
+
for (; j < c.text.length && cut[j]; j++)
|
|
103
|
+
if (starts.has(j))
|
|
104
|
+
starting = true;
|
|
105
|
+
if (starting)
|
|
106
|
+
out += "[redacted]";
|
|
107
|
+
i = j;
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
};
|
|
111
|
+
const drain = (all) => {
|
|
112
|
+
const safe = all ? Infinity : total - span;
|
|
113
|
+
while (queue.length) {
|
|
114
|
+
const e = queue[0];
|
|
115
|
+
if ("text" in e && e.end > safe)
|
|
116
|
+
break;
|
|
117
|
+
queue.shift();
|
|
118
|
+
if (log.writableEnded)
|
|
119
|
+
continue;
|
|
120
|
+
if (!("text" in e)) {
|
|
121
|
+
log.write(e.raw);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const out = masked(e);
|
|
125
|
+
if (out === e.text) {
|
|
126
|
+
log.write(e.line + "\n");
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const copy = JSON.parse(e.line);
|
|
130
|
+
copy.params.update.content.text = out;
|
|
131
|
+
log.write(JSON.stringify(copy) + "\n");
|
|
132
|
+
}
|
|
133
|
+
const held = queue.find((e) => "text" in e);
|
|
134
|
+
const from = held ? held.start : total;
|
|
135
|
+
found = found.filter(([, b]) => b > from);
|
|
136
|
+
};
|
|
137
|
+
return {
|
|
138
|
+
write(text) {
|
|
139
|
+
if (queue.length) {
|
|
140
|
+
queue.push({ raw: text });
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
return log.write(text);
|
|
144
|
+
},
|
|
145
|
+
end(callback) {
|
|
146
|
+
drain(true);
|
|
147
|
+
log.end(callback);
|
|
148
|
+
},
|
|
149
|
+
get writableEnded() {
|
|
150
|
+
return log.writableEnded;
|
|
151
|
+
},
|
|
152
|
+
agent(m, line) {
|
|
153
|
+
const text = textOf(m);
|
|
154
|
+
if (text === null) {
|
|
155
|
+
if (queue.length)
|
|
156
|
+
queue.push({ raw: line + "\n" });
|
|
157
|
+
else if (!log.writableEnded)
|
|
158
|
+
log.write(line + "\n");
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
// Occurrences that end in this text: each starts in the tail or in the text itself.
|
|
162
|
+
const before = tail.length;
|
|
163
|
+
const stream = tail + text;
|
|
164
|
+
const origin = total - before;
|
|
165
|
+
for (const s of list) {
|
|
166
|
+
for (let i = stream.indexOf(s, Math.max(0, before - s.length + 1)); i !== -1; i = stream.indexOf(s, i + 1))
|
|
167
|
+
found.push([origin + i, origin + i + s.length]);
|
|
168
|
+
}
|
|
169
|
+
found.sort((x, y) => x[0] - y[0]);
|
|
170
|
+
queue.push({ m, line, start: total, end: total + text.length, text });
|
|
171
|
+
total += text.length;
|
|
172
|
+
tail = span > 0 ? stream.slice(-span) : "";
|
|
173
|
+
drain(false);
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* What relay does to everything it reads from an agent that holds secrets (PreparedState.secrets):
|
|
179
|
+
* each occurrence of one is replaced by "[redacted]". Applied to each line of the ACP stream before
|
|
180
|
+
* it is parsed, so the reply, progress, approval requests and the agent's log all come from
|
|
181
|
+
* redacted text; to stderr a whole line at a time, so a secret split across two reads is caught;
|
|
182
|
+
* and to the reply once assembled, since a reply streamed in pieces can split one. A secret that
|
|
183
|
+
* the agent encodes (base64, reversed) is not caught.
|
|
184
|
+
*/
|
|
185
|
+
export function redactor(secrets) {
|
|
186
|
+
const list = [...new Set(secrets)].sort((a, b) => b.length - a.length);
|
|
187
|
+
if (list.some((s) => s.length < MIN_SECRET))
|
|
188
|
+
throw new Error(`a secret relay is to redact is too short (under ${MIN_SECRET} characters) to tell from ordinary text`);
|
|
189
|
+
if (!list.length)
|
|
190
|
+
return (text) => text;
|
|
191
|
+
return (text) => list.reduce((t, s) => t.split(s).join("[redacted]"), text);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* How much of a harness's stderr a failure quotes, at most: the tail of its complete lines and
|
|
195
|
+
* whatever it wrote after the last line break, together, each redacted before it is cut.
|
|
196
|
+
*/
|
|
197
|
+
const STDERR_TAIL = 2000;
|
|
198
|
+
/**
|
|
199
|
+
* A JSON-RPC error from the agent as relay reports it: its message, and the detail the agent put in
|
|
200
|
+
* its data, `data.details` or `data` itself when that is a string. Gemini CLI 0.64.0 answers a
|
|
201
|
+
* session it cannot load with the message "Internal error" and the reason in `data.details`
|
|
202
|
+
* ("Invalid session identifier …"), so the message alone says nothing. The detail is cut of the
|
|
203
|
+
* turn's secrets (`cut`, the profile's redactor; the line it came in was cut already, but a parsed
|
|
204
|
+
* string may spell a secret that its JSON escaped), cleaned and clipped as the stderr tail a
|
|
205
|
+
* failure quotes is (diagnosticTail, which also cuts credentials by their shape), and put on one
|
|
206
|
+
* line. Other shapes of data are left out.
|
|
207
|
+
*/
|
|
208
|
+
export function rpcErrorText(error, cut = (t) => t) {
|
|
209
|
+
const e = (error && typeof error === "object" ? error : {});
|
|
210
|
+
const data = e.data;
|
|
211
|
+
const raw = typeof data === "string" ? data : typeof data?.details === "string" ? data.details : "";
|
|
212
|
+
let detail = "";
|
|
213
|
+
if (raw.trim()) {
|
|
214
|
+
const tail = diagnosticTail(STDERR_TAIL);
|
|
215
|
+
tail.write(cut(raw));
|
|
216
|
+
detail = tail.text().replace(/\s*\n\s*/g, " ").trim();
|
|
217
|
+
}
|
|
218
|
+
const message = typeof e.message === "string" && e.message ? cut(e.message) : detail ? `error ${JSON.stringify(e.code ?? null)}` : JSON.stringify(error);
|
|
219
|
+
return detail ? `${message}: ${detail}` : message;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* The models a Gemini CLI prompt response says answered: `_meta.quota.model_usage[].model`, in order
|
|
223
|
+
* of first use (gemini-cli v0.64.0, packages/cli/src/acp/acpSession.ts, buildPromptResponse). Its
|
|
224
|
+
* session reports only the configured alias, often "auto", and sends no current_model_update.
|
|
225
|
+
*/
|
|
226
|
+
export function promptModels(response) {
|
|
227
|
+
const usage = response?._meta?.quota?.model_usage;
|
|
228
|
+
if (!Array.isArray(usage))
|
|
229
|
+
return [];
|
|
230
|
+
return [...new Set(usage.map((u) => u?.model).filter((m) => typeof m === "string" && m.trim() !== ""))];
|
|
231
|
+
}
|
|
232
|
+
/** The agent's description of a tool call, merged into what is known about it. Fields not sent are kept. */
|
|
233
|
+
export function mergeToolCall(known, update) {
|
|
234
|
+
const out = { ...(known ?? { toolCallId: String(update.toolCallId) }) };
|
|
235
|
+
for (const k of ["title", "kind", "status", "rawInput", "locations", "content"]) {
|
|
236
|
+
if (update[k] !== undefined && update[k] !== null)
|
|
237
|
+
out[k] = update[k];
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
/** The options of an approval request (session/request_permission) that relay can use: well-formed ones only. */
|
|
242
|
+
export function permissionOptions(raw) {
|
|
243
|
+
if (!Array.isArray(raw))
|
|
244
|
+
return [];
|
|
245
|
+
return raw.filter((o) => Boolean(o) && typeof o.optionId === "string" && typeof o.kind === "string");
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The answer to an approval request, as an ACP outcome. Relay answers only with an option the agent
|
|
249
|
+
* offered, and never with allow_always: what "always" means is the agent's (some persist it to
|
|
250
|
+
* their settings), so a decision for the rest of the job is held by relay and each later request
|
|
251
|
+
* is answered allow_once. With no allow_once offered, an allowed request is refused; with no
|
|
252
|
+
* reject_once offered, a refusal is "cancelled", which every agent must accept.
|
|
253
|
+
*/
|
|
254
|
+
export function permissionOutcome(options, allow) {
|
|
255
|
+
const pick = (allow ? options.find((o) => o.kind === "allow_once") : undefined) ?? options.find((o) => o.kind === "reject_once");
|
|
256
|
+
return pick ? { outcome: "selected", optionId: pick.optionId } : { outcome: "cancelled" };
|
|
257
|
+
}
|
|
258
|
+
const str = (v) => (typeof v === "string" && v.trim() ? v : undefined);
|
|
259
|
+
/** Paths a tool call says it touches: its locations, and the path fields of its input and diffs. */
|
|
260
|
+
export function callPaths(call) {
|
|
261
|
+
const out = new Set();
|
|
262
|
+
for (const l of call.locations ?? [])
|
|
263
|
+
if (str(l?.path))
|
|
264
|
+
out.add(l.path);
|
|
265
|
+
const input = call.rawInput && typeof call.rawInput === "object" ? call.rawInput : {};
|
|
266
|
+
for (const k of ["path", "file_path", "filePath", "fileName", "file", "target", "destination"])
|
|
267
|
+
if (str(input[k]))
|
|
268
|
+
out.add(input[k]);
|
|
269
|
+
if (Array.isArray(input.paths))
|
|
270
|
+
for (const p of input.paths)
|
|
271
|
+
if (str(p))
|
|
272
|
+
out.add(p);
|
|
273
|
+
for (const c of call.content ?? []) {
|
|
274
|
+
const d = c;
|
|
275
|
+
if (d?.type === "diff" && str(d.path))
|
|
276
|
+
out.add(d.path);
|
|
277
|
+
}
|
|
278
|
+
return [...out];
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The common reading of an ACP tool call, for profiles to build on: a command needs its command
|
|
282
|
+
* line, a change its paths, a fetch its URL. Every other kind of tool call is refused: relay has no
|
|
283
|
+
* reviewed reading of what it would do, and a summary of its raw input is not one. What cannot be
|
|
284
|
+
* established is null, and the request is refused without reaching anyone: nobody can decide what
|
|
285
|
+
* they cannot see.
|
|
286
|
+
*/
|
|
287
|
+
export function genericApproval(call) {
|
|
288
|
+
const input = call.rawInput && typeof call.rawInput === "object" && !Array.isArray(call.rawInput) ? call.rawInput : null;
|
|
289
|
+
const title = str(call.title);
|
|
290
|
+
switch (call.kind) {
|
|
291
|
+
case "execute": {
|
|
292
|
+
const argv = Array.isArray(input?.command) && input.command.length && input.command.every((a) => typeof a === "string") ? input.command : undefined;
|
|
293
|
+
const command = str(input?.command) ?? argv?.join(" ");
|
|
294
|
+
if (!command)
|
|
295
|
+
return null;
|
|
296
|
+
// The argv, when the agent gives one, is the command's identity: its joined form can be ambiguous.
|
|
297
|
+
return { kind: "command", summary: command, reason: str(input?.description) ?? title, detail: { ...(str(input?.cwd) ? { cwd: input.cwd } : {}), ...(argv ? { argv } : {}), tool_call: call.toolCallId } };
|
|
298
|
+
}
|
|
299
|
+
case "edit":
|
|
300
|
+
case "delete":
|
|
301
|
+
case "move": {
|
|
302
|
+
const paths = callPaths(call);
|
|
303
|
+
if (!paths.length)
|
|
304
|
+
return null;
|
|
305
|
+
return { kind: "file", summary: `${call.kind} ${paths.join(", ")}`, reason: title, paths, detail: { tool_call: call.toolCallId } };
|
|
306
|
+
}
|
|
307
|
+
case "fetch": {
|
|
308
|
+
const url = str(input?.url) ?? str(input?.query);
|
|
309
|
+
if (!url)
|
|
310
|
+
return null;
|
|
311
|
+
return { kind: "web", summary: str(input?.url) ? `fetch ${url}` : `web search: ${url}`, reason: title, detail: { tool_call: call.toolCallId } };
|
|
312
|
+
}
|
|
313
|
+
default:
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* What a tool call is doing, in a few words, for progress lines, as the native backends report it
|
|
319
|
+
* (activityOf): the command, the files, the URL, else the agent's own title for it.
|
|
320
|
+
*/
|
|
321
|
+
function callActivity(call) {
|
|
322
|
+
const input = call.rawInput && typeof call.rawInput === "object" && !Array.isArray(call.rawInput) ? call.rawInput : {};
|
|
323
|
+
if (call.kind === "execute" && input.command !== undefined)
|
|
324
|
+
return activityOf("Bash", { command: input.command });
|
|
325
|
+
if (call.kind === "edit" || call.kind === "delete" || call.kind === "move") {
|
|
326
|
+
const paths = callPaths(call);
|
|
327
|
+
if (paths.length)
|
|
328
|
+
return activityOf("fileChange", { changes: paths.map((p) => ({ path: p })) });
|
|
329
|
+
}
|
|
330
|
+
if (call.kind === "fetch" && str(input.url))
|
|
331
|
+
return activityOf("WebFetch", { url: input.url });
|
|
332
|
+
if (call.kind === "think")
|
|
333
|
+
return null;
|
|
334
|
+
const title = str(call.title);
|
|
335
|
+
// The agent's own words: escaped like every other activity (review C12).
|
|
336
|
+
return title ? oneLine(title, 160) : null;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Token usage from an ACP prompt response's `usage` (unstable in ACP v1: inputTokens, outputTokens,
|
|
340
|
+
* totalTokens, cachedReadTokens, cachedWriteTokens, thoughtTokens), in relay's names: this turn's.
|
|
341
|
+
*/
|
|
342
|
+
function acpUsage(raw) {
|
|
343
|
+
if (!raw || typeof raw !== "object")
|
|
344
|
+
return null;
|
|
345
|
+
const r = raw;
|
|
346
|
+
return usageFrom({
|
|
347
|
+
...r,
|
|
348
|
+
...(typeof r.cachedReadTokens === "number" ? { cached_input_tokens: r.cachedReadTokens } : {}),
|
|
349
|
+
...(typeof r.cachedWriteTokens === "number" ? { cache_creation_input_tokens: r.cachedWriteTokens } : {}),
|
|
350
|
+
...(typeof r.thoughtTokens === "number" ? { reasoning_output_tokens: r.thoughtTokens } : {}),
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
/** An executable named on PATH (or given as a path), as an absolute path, or null. */
|
|
354
|
+
function resolveBin(bin, env) {
|
|
355
|
+
const ok = (p) => {
|
|
356
|
+
try {
|
|
357
|
+
fs.accessSync(p, fs.constants.X_OK);
|
|
358
|
+
return fs.statSync(p).isFile();
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
if (bin.includes("/")) {
|
|
365
|
+
const p = path.resolve(bin);
|
|
366
|
+
return ok(p) ? fs.realpathSync(p) : null;
|
|
367
|
+
}
|
|
368
|
+
for (const dir of (env.PATH ?? "").split(path.delimiter)) {
|
|
369
|
+
if (!dir)
|
|
370
|
+
continue;
|
|
371
|
+
const p = path.join(dir, bin);
|
|
372
|
+
if (ok(p))
|
|
373
|
+
return fs.realpathSync(p);
|
|
374
|
+
}
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Starts the harness and speaks JSON-RPC over its stdio. onMessage sees everything that is not a
|
|
379
|
+
* reply to relay. Each line the agent writes is passed through `cutLine` before anything reads it.
|
|
380
|
+
*/
|
|
381
|
+
function connect(command, args, cwd, env, onMessage, cutLine = (t) => t) {
|
|
382
|
+
const child = spawn(executable(command, env.PATH), args, { cwd, env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
383
|
+
child.stdin.on("error", () => { });
|
|
384
|
+
let next = 1;
|
|
385
|
+
const waiting = new Map();
|
|
386
|
+
const send = (m) => {
|
|
387
|
+
if (!child.stdin.writable)
|
|
388
|
+
return;
|
|
389
|
+
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", ...m }) + "\n");
|
|
390
|
+
};
|
|
391
|
+
readline.createInterface({ input: child.stdout }).on("line", (raw) => {
|
|
392
|
+
const line = cutLine(raw);
|
|
393
|
+
let m;
|
|
394
|
+
try {
|
|
395
|
+
m = JSON.parse(line);
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (!m || typeof m !== "object")
|
|
401
|
+
return;
|
|
402
|
+
if (m.id !== undefined && m.method === undefined) {
|
|
403
|
+
const w = waiting.get(m.id);
|
|
404
|
+
waiting.delete(m.id);
|
|
405
|
+
// With the detail its data carries, which is where Gemini says why a session would not load.
|
|
406
|
+
if (m.error)
|
|
407
|
+
w?.reject(Object.assign(new Error(rpcErrorText(m.error, cutLine)), { code: m.error.code }));
|
|
408
|
+
else
|
|
409
|
+
w?.resolve(m.result);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
onMessage(m, line);
|
|
413
|
+
});
|
|
414
|
+
let closed = null;
|
|
415
|
+
const rejectPending = (err) => {
|
|
416
|
+
closed ??= err;
|
|
417
|
+
for (const w of waiting.values())
|
|
418
|
+
w.reject(closed);
|
|
419
|
+
waiting.clear();
|
|
420
|
+
};
|
|
421
|
+
child.on("close", () => rejectPending(new Error("the agent exited")));
|
|
422
|
+
return {
|
|
423
|
+
child, pid: child.pid ?? -1, send,
|
|
424
|
+
disconnect: () => rejectPending(new Error("relay disconnected the agent after cleanup was refused")),
|
|
425
|
+
request: (method, params, timeoutMs) => new Promise((resolve, reject) => {
|
|
426
|
+
if (closed)
|
|
427
|
+
return reject(closed);
|
|
428
|
+
const id = next++;
|
|
429
|
+
let timer;
|
|
430
|
+
waiting.set(id, {
|
|
431
|
+
resolve: (v) => {
|
|
432
|
+
clearTimeout(timer);
|
|
433
|
+
resolve(v);
|
|
434
|
+
},
|
|
435
|
+
reject: (e) => {
|
|
436
|
+
clearTimeout(timer);
|
|
437
|
+
reject(e);
|
|
438
|
+
},
|
|
439
|
+
});
|
|
440
|
+
// A deadline on the wait, for requests that should answer at once (initialize, login). It
|
|
441
|
+
// ends relay's wait, not the agent; the turn is then refused and the agent stopped.
|
|
442
|
+
if (timeoutMs) {
|
|
443
|
+
timer = setTimeout(() => {
|
|
444
|
+
waiting.delete(id);
|
|
445
|
+
reject(new Error(`no answer to ${method} within ${Math.round(timeoutMs / 1000)}s`));
|
|
446
|
+
}, timeoutMs);
|
|
447
|
+
timer.unref();
|
|
448
|
+
}
|
|
449
|
+
send({ id, method, params });
|
|
450
|
+
}),
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
async function launch(spec, bin, args, state) {
|
|
454
|
+
const c = spec.target.capabilities.confinement;
|
|
455
|
+
// Verified confinement means checking, through the harness, that its own sandbox took; no ACP
|
|
456
|
+
// harness has a verifier for that yet, so none is launched on its own sandbox's word.
|
|
457
|
+
if (c === "verified")
|
|
458
|
+
throw new Error(`relay has no way yet to verify ${targetLabel(spec.target)}'s own sandbox over ACP, so it does not launch it on that sandbox.`);
|
|
459
|
+
if (c === "relay-enforced")
|
|
460
|
+
return confinedLaunch(spec, bin, args, state);
|
|
461
|
+
throw new Error(`${targetLabel(spec.target)} has no confinement relay can enforce or verify, so relay does not launch it.`);
|
|
462
|
+
}
|
|
463
|
+
/** Unit tests replace launch resources, while exercising the protocol and cleanup themselves. */
|
|
464
|
+
let testLaunch = null;
|
|
465
|
+
export function setAcpLaunchForTests(fn) { testLaunch = fn; }
|
|
466
|
+
/** How long relay waits for the kernel to report the harness sandboxed before it gives up and stops it. */
|
|
467
|
+
const CONFINED_WAIT_MS = 5000;
|
|
468
|
+
/** The longest pause between two of those asks. */
|
|
469
|
+
const CONFINED_PAUSE_MS = 100;
|
|
470
|
+
/**
|
|
471
|
+
* Asks the mechanism whether `pid` is confined until it says so, or until `waitMs` have passed;
|
|
472
|
+
* true only on the kernel's yes. The pauses between asks start at 5 ms and double up to
|
|
473
|
+
* CONFINED_PAUSE_MS: the harness reads as sandboxed once sandbox-exec has compiled and applied its
|
|
474
|
+
* profile, some tens of milliseconds after the spawn, so the first ask usually comes too early, and
|
|
475
|
+
* a fixed 100 ms pause after it was mostly spent waiting on a process that was already confined.
|
|
476
|
+
*/
|
|
477
|
+
export async function awaitConfined(confined, pid, waitMs = CONFINED_WAIT_MS) {
|
|
478
|
+
const until = Date.now() + waitMs;
|
|
479
|
+
for (let pause = 5;; pause = Math.min(pause * 2, CONFINED_PAUSE_MS)) {
|
|
480
|
+
if (confined(pid))
|
|
481
|
+
return true;
|
|
482
|
+
if (Date.now() > until)
|
|
483
|
+
return false;
|
|
484
|
+
await new Promise((r) => setTimeout(r, pause));
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Relay-owned confinement (src/confine), in the order the architecture notes give: the turn is
|
|
489
|
+
* already running in the registry; relay opens the turn's broker, makes a private temp directory,
|
|
490
|
+
* wraps the harness in the mechanism's sandbox with the bridge socket as its only Unix socket,
|
|
491
|
+
* gives the harness `relay bridge <socket>` as its relay MCP server, confirms from the kernel that
|
|
492
|
+
* the process is sandboxed before the prompt is sent, and closes the broker when the turn ends.
|
|
493
|
+
* Where the mechanism cannot enforce, the harness is refused, never run unconfined.
|
|
494
|
+
*/
|
|
495
|
+
async function confinedLaunch(spec, bin, args, state) {
|
|
496
|
+
const name = targetLabel(spec.target);
|
|
497
|
+
const mech = confinement();
|
|
498
|
+
if ("reason" in mech)
|
|
499
|
+
throw new Error(`${name} runs only inside relay's own sandbox, and ${mech.reason}, so relay does not launch it.`);
|
|
500
|
+
const sandbox = mech.mechanism;
|
|
501
|
+
const probe = boundaryProbe();
|
|
502
|
+
if (!probe)
|
|
503
|
+
throw new Error(`${NO_PROBE}, so it does not launch ${name}.`);
|
|
504
|
+
// Without network access the turn reaches only its target's declared API hosts, through a proxy
|
|
505
|
+
// relay runs for this turn alone (src/confine/proxy.ts); the sandbox lets it reach nothing else.
|
|
506
|
+
const hosts = spec.target.apiHosts ?? [];
|
|
507
|
+
const online = networkOn(spec.config, spec.grant);
|
|
508
|
+
if (!online && !hosts.length)
|
|
509
|
+
throw new Error(`relay cannot keep ${name} off the network: relay does not know which hosts it needs to reach its model, so its network proxy would admit none. Grant network access for this work, or use another agent.`);
|
|
510
|
+
// The worker's stop, while the turn is still starting: give up before anything is launched (E18).
|
|
511
|
+
const stopped = () => {
|
|
512
|
+
if (spec.signal?.aborted)
|
|
513
|
+
throw new Error(`the turn was stopped while relay was starting ${name}`);
|
|
514
|
+
};
|
|
515
|
+
stopped();
|
|
516
|
+
const tmpDir = privateTurnTemp();
|
|
517
|
+
let broker = null;
|
|
518
|
+
/** The bridge secret's file, for a harness that reads it itself (bridgeReady): its turn's profile alone may read it. */
|
|
519
|
+
let bridgeSecret;
|
|
520
|
+
let proxy = null;
|
|
521
|
+
/** The proxy's decisions, held until the turn's log takes them. */
|
|
522
|
+
const decisions = [];
|
|
523
|
+
let sink = null;
|
|
524
|
+
const refusals = [];
|
|
525
|
+
let refusalSink = null;
|
|
526
|
+
/** Ends the agent's access to relay and to the network: when the turn is over, and on release. */
|
|
527
|
+
const cut = async () => {
|
|
528
|
+
await broker?.close().catch(() => { });
|
|
529
|
+
await proxy?.close().catch(() => { });
|
|
530
|
+
};
|
|
531
|
+
const release = async () => {
|
|
532
|
+
await cut();
|
|
533
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
534
|
+
};
|
|
535
|
+
try {
|
|
536
|
+
const turnId = spec.turnId ?? spec.relay?.turnId;
|
|
537
|
+
if (turnId !== undefined) {
|
|
538
|
+
const turn = getTurn(turnId);
|
|
539
|
+
if (!turn || turn.node_id !== spec.markers.nodeId || turn.status !== "running")
|
|
540
|
+
throw new Error("cannot record a private temporary directory for an unknown or inactive turn");
|
|
541
|
+
const st = fs.lstatSync(tmpDir);
|
|
542
|
+
updateTurn(turnId, { tmp_dir: tmpDir, tmp_dev: st.dev, tmp_ino: st.ino });
|
|
543
|
+
}
|
|
544
|
+
if (spec.relay) {
|
|
545
|
+
if (spec.relay.turnId === undefined)
|
|
546
|
+
throw new Error("relay has no turn to serve this agent's relay tools for");
|
|
547
|
+
// The broker brings the MCP server and SDK, which only a turn with relay tools needs.
|
|
548
|
+
const { openBroker } = await import("../confine/broker.js");
|
|
549
|
+
broker = await openBroker({ nodeId: spec.relay.nodeId, turnId: spec.relay.turnId, mayDelegate: spec.relay.mayDelegate ?? false, mayAsk: spec.relay.mayAsk ?? false }, {
|
|
550
|
+
onRefusal: (reason) => (refusalSink ? refusalSink(reason) : refusals.push(reason)),
|
|
551
|
+
});
|
|
552
|
+
registerTurnSecret(broker.bridgeCommand.env[BRIDGE_SECRET_ENV], "bridge secret");
|
|
553
|
+
// A harness that takes relay's tools another way than the bridge entry is told how to reach
|
|
554
|
+
// this broker, before it starts (Gemini's tool discovery): the secret in a file of the broker's,
|
|
555
|
+
// which this turn's profile alone may read (ConfinementPolicy.bridgeSecret).
|
|
556
|
+
if (state.bridgeReady) {
|
|
557
|
+
bridgeSecret = broker.secretFile();
|
|
558
|
+
await state.bridgeReady({ socketPath: broker.socketPath, secretFile: bridgeSecret, listTools: broker.listTools, tmpDir });
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
const proxyLog = path.join(spec.dir, "proxy.jsonl");
|
|
562
|
+
if (!online) {
|
|
563
|
+
proxy = await openTurnProxy({
|
|
564
|
+
neverPolicy: spec.neverPolicy,
|
|
565
|
+
allow: [...hosts], logFile: proxyLog, label: `${spec.markers.nodeId}/${spec.relay?.turnId ?? "-"}`,
|
|
566
|
+
onDecision: (d) => (sink ? sink(d) : decisions.push(d)),
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
const network = proxy ? proxy.network : { mode: "on" };
|
|
570
|
+
stopped();
|
|
571
|
+
const store = spec.target.tokenStore ? loginStore(spec.target.tokenStore, os.homedir()) : undefined;
|
|
572
|
+
const policy = turnPolicy(spec, state, tmpDir, network, os.homedir(), name, broker?.socketPath, bridgeSecret);
|
|
573
|
+
if (spec.neverPolicy) {
|
|
574
|
+
const problem = neverIdentityProblem(spec.neverPolicy);
|
|
575
|
+
if (problem)
|
|
576
|
+
throw new Error(problem);
|
|
577
|
+
if (neverFloorApplies(spec.target.id, spec.config) && (state.keychain || state.certificateTrust || state.tokenFiles?.length || spec.target.tokenStore))
|
|
578
|
+
throw new Error("never: this ACP credential/TRUST variant bypasses the shared floor; use a qualified key-only/store-denying route");
|
|
579
|
+
}
|
|
580
|
+
// Wrapped for this turn and probed under exactly that confinement (turn-probe.ts).
|
|
581
|
+
const checkedSandbox = { ...sandbox, wrap: (p, command, argv) => {
|
|
582
|
+
const wrapped = sandbox.wrap(p, command, argv);
|
|
583
|
+
const complete = { ...spec.environment, ...wrapped.env };
|
|
584
|
+
const problem = endpointProblem(spec.target.id, complete);
|
|
585
|
+
if (problem)
|
|
586
|
+
throw new Error(problem);
|
|
587
|
+
spec.checkEnvironment?.(complete);
|
|
588
|
+
return wrapped;
|
|
589
|
+
} };
|
|
590
|
+
const { launch: wrapped, probes } = await probe(checkedSandbox, policy, bin, args, spec.signal, spec.environment);
|
|
591
|
+
stopped();
|
|
592
|
+
return {
|
|
593
|
+
command: wrapped.command, args: wrapped.args, env: wrapped.env, probes, diagnosticTag: wrapped.diagnosticTag,
|
|
594
|
+
relay: broker ? broker.bridgeCommand : null,
|
|
595
|
+
network: proxy ? { mode: "proxy", hosts, log: proxyLog, trust: Boolean(state.certificateTrust) } : { mode: "on" },
|
|
596
|
+
...(store ? { loginStore: store } : {}),
|
|
597
|
+
proxyDecisions(take) {
|
|
598
|
+
sink = take;
|
|
599
|
+
for (const d of decisions.splice(0))
|
|
600
|
+
take(d);
|
|
601
|
+
},
|
|
602
|
+
brokerRefusals(take) {
|
|
603
|
+
refusalSink = take;
|
|
604
|
+
for (const reason of refusals.splice(0))
|
|
605
|
+
take(reason);
|
|
606
|
+
},
|
|
607
|
+
async verify(pid) {
|
|
608
|
+
// Pin the exact process we just spawned before it receives its MCP bridge entry.
|
|
609
|
+
if (broker) {
|
|
610
|
+
const start = procStart(pid, { fresh: true });
|
|
611
|
+
if (!start)
|
|
612
|
+
return `relay could not determine ${name}'s process identity for its broker, so it stopped it.`;
|
|
613
|
+
broker.bindHarness({ pid, start });
|
|
614
|
+
}
|
|
615
|
+
// sandbox-exec applies the profile and then execs the harness in the same process, so the
|
|
616
|
+
// pid relay started is the one to ask about; it may take a moment to read as sandboxed.
|
|
617
|
+
if (await awaitConfined((p) => sandbox.confined(p), pid))
|
|
618
|
+
return null;
|
|
619
|
+
return `relay could not confirm from the kernel that ${name} is running under its sandbox, so it stopped it before it did anything.`;
|
|
620
|
+
},
|
|
621
|
+
revoke: cut,
|
|
622
|
+
close: release,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
catch (err) {
|
|
626
|
+
await release();
|
|
627
|
+
throw err;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
export { loginStore } from "../confine/turn.js";
|
|
631
|
+
// Vendor classifier refusal shapes through ACP have not been observed/verified (A17).
|
|
632
|
+
// Do not infer a safety stop from arbitrary provider error prose or permission denials.
|
|
633
|
+
const fail = (error) => ({ status: "failed", error });
|
|
634
|
+
/**
|
|
635
|
+
* Runs one turn over ACP. Before the prompt is sent: the protocol version, the login, the session
|
|
636
|
+
* (new, resumed or loaded, with this turn's relay server), the mode and the model, each as the
|
|
637
|
+
* agent reports it back, and the launch's own check of the process. Anything not as asked stops
|
|
638
|
+
* the agent before it has done anything.
|
|
639
|
+
*/
|
|
640
|
+
export function startAcpTurn(spec, profile) {
|
|
641
|
+
return withTurnSecrets(() => startScopedAcpTurn(spec, profile), { reuse: true });
|
|
642
|
+
}
|
|
643
|
+
async function startScopedAcpTurn(spec, profile) {
|
|
644
|
+
assertNeverAdapter(spec);
|
|
645
|
+
const target = spec.target;
|
|
646
|
+
const name = targetLabel(target);
|
|
647
|
+
const cfg = spec.config;
|
|
648
|
+
const bin = cfg.targets[target.id].bin;
|
|
649
|
+
const refusal = profile.refuse?.(spec) ?? loginStrategyProblem(profile, spec);
|
|
650
|
+
if (refusal)
|
|
651
|
+
throw new Error(refusal);
|
|
652
|
+
// Which family answers: a harness that runs several families' models runs only the one asked for.
|
|
653
|
+
const model = spec.model;
|
|
654
|
+
const pinned = Boolean(model && model !== target.autoModel);
|
|
655
|
+
const strict = cfg.same_family === "refuse";
|
|
656
|
+
if (target.vendor === null && strict) {
|
|
657
|
+
// Grok's listed models are all one family's, but it is judged per model all the same: it is not said to run several.
|
|
658
|
+
const several = new Set(Object.values(target.models ?? {})).size > 1;
|
|
659
|
+
if (!model)
|
|
660
|
+
throw new Error(`${several ? `${name} runs models of several families` : `The family of ${name} is judged by the model it runs`}, and this turn names none, so relay cannot tell which family would answer. It does not launch it.`);
|
|
661
|
+
if (!vendorFor(target, model))
|
|
662
|
+
throw new Error(`relay does not know which family the model ${JSON.stringify(model)} is, so it does not launch ${name} with it.`);
|
|
663
|
+
}
|
|
664
|
+
// A harness relay's own settings hold to its listed models (listedModelsOnly) runs no other, under either setting.
|
|
665
|
+
if (target.listedModelsOnly && model && !vendorFor(target, model)) {
|
|
666
|
+
throw new Error(`relay lets ${name} run only the models its list names (${Object.keys(target.models ?? {}).join(", ")}), so it does not launch it with ${JSON.stringify(model)}.`);
|
|
667
|
+
}
|
|
668
|
+
const env = childEnv(spec, profile.scrub);
|
|
669
|
+
const absolute = resolveBin(bin, env);
|
|
670
|
+
if (!absolute)
|
|
671
|
+
throw new Error(`relay could not find the ${name} harness (\`${bin}\`). Install ${target.product}, or set targets.${target.id}.bin in relay's config to its full path.`);
|
|
672
|
+
const endpoint = endpointProblem(target.id, env);
|
|
673
|
+
if (endpoint)
|
|
674
|
+
throw new Error(`${endpoint}.`);
|
|
675
|
+
if (spec.signal?.aborted)
|
|
676
|
+
throw new Error(`the turn was stopped while relay was starting ${name}`);
|
|
677
|
+
const state = profile.prepareState?.(spec) ?? { stateDirs: [], keychain: false };
|
|
678
|
+
let launched;
|
|
679
|
+
/** The profile's own secrets (PreparedState.secrets) cut out; core/secrets.ts redact cuts what relay knows of the turn and its environment. */
|
|
680
|
+
let cutSecrets;
|
|
681
|
+
/** Both, for what relay reports of the turn (its error, reply, warnings and sandbox denials). */
|
|
682
|
+
let cleanReport;
|
|
683
|
+
try {
|
|
684
|
+
cutSecrets = redactor(state.secrets ?? []);
|
|
685
|
+
cleanReport = (text) => redact(cutSecrets(text));
|
|
686
|
+
launched = await (testLaunch ?? launch)({ ...spec, environment: env }, absolute, profile.args(spec, model), state);
|
|
687
|
+
// The profile's environment reaches the harness through the launch (the sandbox layer sets it),
|
|
688
|
+
// so the environment the harness gets is checked as a whole, not only what relay passed on (E10).
|
|
689
|
+
Object.assign(env, launched.env);
|
|
690
|
+
const added = endpointProblem(target.id, env);
|
|
691
|
+
if (added) {
|
|
692
|
+
await launched.close().catch(() => { });
|
|
693
|
+
throw new Error(`${added}.`);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
catch (err) {
|
|
697
|
+
state.cleanup?.();
|
|
698
|
+
throw err;
|
|
699
|
+
}
|
|
700
|
+
const { log: agentLog, warnings: logWarnings } = openAgentLog(spec.logPath);
|
|
701
|
+
// A turn with secrets keeps one split across streamed text chunks out of its log (secretSafeLog).
|
|
702
|
+
const log = secretSafeLog(agentLog, streamSecretValues(state.secrets ?? [], env, state.env));
|
|
703
|
+
/** What the proxy, the broker and the sandbox report before the log's header is written: held, in the order it came, for after it. */
|
|
704
|
+
let early = [];
|
|
705
|
+
const report = (line) => {
|
|
706
|
+
if (early)
|
|
707
|
+
early.push(line);
|
|
708
|
+
else if (!log.writableEnded)
|
|
709
|
+
log.write(line);
|
|
710
|
+
};
|
|
711
|
+
/**
|
|
712
|
+
* The log's header (the launch's command line, the probes it passed, its network and login store),
|
|
713
|
+
* then what was held for after it. Written in the same step as the harness's spawn, just after it,
|
|
714
|
+
* so that nothing the harness sends comes before it, and so that cutting secrets out of the long
|
|
715
|
+
* command line (the whole sandbox profile, some 20 ms) runs while the harness starts up, not
|
|
716
|
+
* before relay starts it. Once only.
|
|
717
|
+
*/
|
|
718
|
+
const writeHeader = () => {
|
|
719
|
+
if (!early)
|
|
720
|
+
return;
|
|
721
|
+
log.write(`\n# ${new Date().toISOString()} ${launched.command} ${launched.args.map((a) => JSON.stringify(a)).join(" ")}\n`);
|
|
722
|
+
if (launched.probes) {
|
|
723
|
+
const p = launched.probes;
|
|
724
|
+
const skipped = p.results.filter((r) => r.got.startsWith("skipped"));
|
|
725
|
+
log.write(`# relay boundary probes: ${p.results.length} passed in ${p.ms} ms${skipped.length ? ` (${skipped.length} not applicable this turn: ${skipped.map((r) => r.name).join(", ")})` : ""}; profile ${p.profile}, relay ${p.relay}, ${p.os}\n`);
|
|
726
|
+
}
|
|
727
|
+
if (launched.network) {
|
|
728
|
+
const n = launched.network;
|
|
729
|
+
// With the trust downgrade the network-off claim has an exception, said here too (review r_7feaed80 C2).
|
|
730
|
+
log.write(n.mode === "on" ? "# relay network: on (granted)\n" : `# relay network: off, except relay's proxy to ${n.hosts.join(", ")}${n.trust ? ", and what the certificate-trust daemons fetch for it, past the proxy (a stated downgrade)" : ""} (decisions in ${n.log})\n`);
|
|
731
|
+
}
|
|
732
|
+
if (launched.loginStore) {
|
|
733
|
+
const st = launched.loginStore;
|
|
734
|
+
log.write(`# relay login store: ${st.name} (${st.dir}): its token, lock and temp names only (${[...st.files, ...st.locks].join(", ")}, ${st.tempName}), as regular files; a stated downgrade\n`);
|
|
735
|
+
}
|
|
736
|
+
const held = early;
|
|
737
|
+
early = null;
|
|
738
|
+
for (const line of held)
|
|
739
|
+
report(line);
|
|
740
|
+
};
|
|
741
|
+
// What the proxy let through or refused, as it happens: a harness that needs a host relay does
|
|
742
|
+
// not admit says so here.
|
|
743
|
+
launched.proxyDecisions?.((d) => report(`[proxy] ${d.event} ${d.target}${d.reason ? ` (${d.reason})` : ""}\n`));
|
|
744
|
+
launched.brokerRefusals?.((reason) => report(`[broker] refused: ${reason}\n`));
|
|
745
|
+
// This turn's sandbox denials, streamed from the system log into the agent's log, so that a harness
|
|
746
|
+
// the profile stops says which rule stopped it. A diagnostic only; nothing of the boundary rests on it.
|
|
747
|
+
const denialStream = launched.diagnosticTag
|
|
748
|
+
? streamSandboxDenials(launched.diagnosticTag, (d) => report(`[sandbox] denied ${d.operation}${d.process ? ` (${d.process})` : ""}\n`))
|
|
749
|
+
: null;
|
|
750
|
+
let sessionId = spec.sessionId;
|
|
751
|
+
/** Set once the agent has answered initialize: before that, an exit says nothing about the turn itself. */
|
|
752
|
+
let initialized = false;
|
|
753
|
+
let finalMessage = "";
|
|
754
|
+
let prompting = false;
|
|
755
|
+
/** Whether this turn's session was loaded (session/load), whose replay a profile may send after its answer (replaysAfterLoad). */
|
|
756
|
+
let loaded = false;
|
|
757
|
+
/** When this turn's session last sent an update, for the wait on a replay that follows the load's answer. */
|
|
758
|
+
let lastUpdate = 0;
|
|
759
|
+
/** Set once a replay is seen to go on after the prompt was sent (replaysAfterLoad), so that it is said once. */
|
|
760
|
+
let replayLate = false;
|
|
761
|
+
/** Set once the mode and model have been read back as asked; from then on any other model the agent reports ends the turn. */
|
|
762
|
+
let verified = false;
|
|
763
|
+
/** What the caller must be told about the turn (models switched to, under same_family "allow"; how the profile prepared it). */
|
|
764
|
+
const notes = [...(state.notes ?? [])];
|
|
765
|
+
/** Models of the pinned model's own family the turn switched to, all in the one note at `withinNote`. */
|
|
766
|
+
const withinModels = [];
|
|
767
|
+
let withinNote = -1;
|
|
768
|
+
/** Approval requests relay itself refused while the turn was live, so the turn is reported blocked, not done (review ACP C1). */
|
|
769
|
+
const denials = [];
|
|
770
|
+
/** This turn's usage as the agent reports it: cost from usage_update, tokens with the prompt's response. */
|
|
771
|
+
const usage = {};
|
|
772
|
+
const noted = new Set();
|
|
773
|
+
const servedModels = [];
|
|
774
|
+
const served = (value) => {
|
|
775
|
+
try {
|
|
776
|
+
spec.onServed?.(value ?? null);
|
|
777
|
+
}
|
|
778
|
+
catch {
|
|
779
|
+
finish(fail("relay could not record the model reported by the agent, so it stopped the turn and took away its relay tools."));
|
|
780
|
+
return false;
|
|
781
|
+
}
|
|
782
|
+
if (value && servedModels.at(-1) !== value)
|
|
783
|
+
servedModels.push(value);
|
|
784
|
+
return true;
|
|
785
|
+
};
|
|
786
|
+
let cancelled = false;
|
|
787
|
+
const stderrTail = diagnosticTail(STDERR_TAIL);
|
|
788
|
+
/** Set once the turn's result is known; the handle resolves only after the process has gone. */
|
|
789
|
+
let outcome = null;
|
|
790
|
+
let resolveDone;
|
|
791
|
+
const done = new Promise((r) => (resolveDone = r));
|
|
792
|
+
const calls = new Map();
|
|
793
|
+
/** Each tool call as the agent's session updates described it, without what approval requests said of it (normalizeApproval's `announced`). */
|
|
794
|
+
const announced = new Map();
|
|
795
|
+
/** Approval requests (session/request_permission) not yet answered, so that a cancel can answer them "cancelled", as ACP requires. */
|
|
796
|
+
const pending = new Map();
|
|
797
|
+
/** Decisions for the rest of the job taken in this turn (earlier turns' are in the registry). */
|
|
798
|
+
const heldHere = new Set();
|
|
799
|
+
const current = { options: new Map() };
|
|
800
|
+
const takeOptions = (list) => {
|
|
801
|
+
if (!Array.isArray(list))
|
|
802
|
+
return;
|
|
803
|
+
current.options.clear();
|
|
804
|
+
for (const o of list) {
|
|
805
|
+
// The values a select option offers, for messages only: what is checked is currentValue.
|
|
806
|
+
const values = Array.isArray(o?.options) ? o.options.map((v) => v?.value).filter((v) => typeof v === "string") : undefined;
|
|
807
|
+
if (typeof o?.id === "string")
|
|
808
|
+
current.options.set(o.id, { category: typeof o.category === "string" ? o.category : undefined, currentValue: o.currentValue, ...(values?.length ? { values } : {}) });
|
|
809
|
+
}
|
|
810
|
+
};
|
|
811
|
+
const optionFor = (category) => [...current.options.entries()].find(([, o]) => o.category === category);
|
|
812
|
+
const modelNow = () => {
|
|
813
|
+
const o = optionFor("model");
|
|
814
|
+
return typeof o?.[1].currentValue === "string" ? o[1].currentValue : current.model;
|
|
815
|
+
};
|
|
816
|
+
const modeNow = () => {
|
|
817
|
+
const o = optionFor("mode");
|
|
818
|
+
return current.mode ?? (typeof o?.[1].currentValue === "string" ? o[1].currentValue : undefined);
|
|
819
|
+
};
|
|
820
|
+
const takeSession = (res) => {
|
|
821
|
+
if (typeof res?.modes?.currentModeId === "string")
|
|
822
|
+
current.mode = res.modes.currentModeId;
|
|
823
|
+
if (typeof res?.models?.currentModelId === "string")
|
|
824
|
+
current.model = res.models.currentModelId;
|
|
825
|
+
takeOptions(res?.configOptions);
|
|
826
|
+
};
|
|
827
|
+
let groupRefused = false;
|
|
828
|
+
let cleanupRefusal;
|
|
829
|
+
const stopTimers = [];
|
|
830
|
+
const signalGroup = (sig) => {
|
|
831
|
+
if (groupRefused || rpc.pid <= 1)
|
|
832
|
+
return false;
|
|
833
|
+
try {
|
|
834
|
+
sendGroupSignal(rpc.pid, sig);
|
|
835
|
+
}
|
|
836
|
+
catch (err) {
|
|
837
|
+
if (isGroupSignalRefusal(err)) {
|
|
838
|
+
groupRefused = true;
|
|
839
|
+
cleanupRefusal = `Agent cleanup refused for group ${rpc.pid}: ${err.message}`;
|
|
840
|
+
void Promise.resolve().then(() => settle(null));
|
|
841
|
+
return false;
|
|
842
|
+
}
|
|
843
|
+
// Already gone.
|
|
844
|
+
}
|
|
845
|
+
return true;
|
|
846
|
+
};
|
|
847
|
+
let watch;
|
|
848
|
+
/** True once a look has found the agent alive after the turn stopped starting things. */
|
|
849
|
+
let settled = false;
|
|
850
|
+
const finish = (r) => {
|
|
851
|
+
if (outcome)
|
|
852
|
+
return;
|
|
853
|
+
outcome = r;
|
|
854
|
+
// The turn is over: the agent's relay tools and its network go with it, whatever it is still doing.
|
|
855
|
+
void launched.revoke();
|
|
856
|
+
for (const answer of pending.values())
|
|
857
|
+
answer();
|
|
858
|
+
pending.clear();
|
|
859
|
+
// The last look, while what the agent started can still be traced to it.
|
|
860
|
+
settled = watch.look() || settled;
|
|
861
|
+
rpc.child.stdin.end();
|
|
862
|
+
// The agent has no reason to outlive its one turn.
|
|
863
|
+
stopTimers.push(setTimeout(() => signalGroup("SIGTERM"), 200).unref());
|
|
864
|
+
stopTimers.push(setTimeout(() => {
|
|
865
|
+
if (signalGroup("SIGKILL"))
|
|
866
|
+
killProcs(watch.procs());
|
|
867
|
+
}, 200 + cfg.cancel_grace_ms).unref());
|
|
868
|
+
};
|
|
869
|
+
const onPermission = async (m) => {
|
|
870
|
+
const p = (m.params ?? {});
|
|
871
|
+
const options = permissionOptions(p.options);
|
|
872
|
+
let answered = false;
|
|
873
|
+
const reply = (allow, why, denied) => {
|
|
874
|
+
if (answered)
|
|
875
|
+
return;
|
|
876
|
+
answered = true;
|
|
877
|
+
pending.delete(m.id);
|
|
878
|
+
const result = outcome || cancelled ? { outcome: { outcome: "cancelled" } } : { outcome: permissionOutcome(options, allow) };
|
|
879
|
+
// A refusal relay imposed on a live turn is a denial, so the turn ends blocked, not done. A
|
|
880
|
+
// refusal because the turn is already over or cancelled is not: the turn failed for that reason.
|
|
881
|
+
if (!allow && denied && !outcome && !cancelled)
|
|
882
|
+
denials.push(denied);
|
|
883
|
+
log.write(`# relay: approval request answered ${JSON.stringify(result.outcome)} (${why})\n`);
|
|
884
|
+
rpc.send({ id: m.id, result });
|
|
885
|
+
};
|
|
886
|
+
pending.set(m.id, () => reply(false, "the turn is over"));
|
|
887
|
+
if (outcome || cancelled)
|
|
888
|
+
return reply(false, "the turn is over");
|
|
889
|
+
if (p.sessionId !== sessionId)
|
|
890
|
+
return reply(false, "not this turn's session");
|
|
891
|
+
const update = p.toolCall && typeof p.toolCall === "object" ? p.toolCall : {};
|
|
892
|
+
const id = typeof update.toolCallId === "string" ? update.toolCallId : undefined;
|
|
893
|
+
const call = mergeToolCall(id ? calls.get(id) : undefined, { ...update, toolCallId: id ?? "(none)" });
|
|
894
|
+
if (id)
|
|
895
|
+
calls.set(id, call);
|
|
896
|
+
const ask = profile.normalizeApproval(call, spec, id ? announced.get(id) : undefined);
|
|
897
|
+
if (!ask)
|
|
898
|
+
return reply(false, "what it would do could not be established", `a tool call relay could not read${str(call.title) ? ` (${str(call.title)})` : ""}`);
|
|
899
|
+
if (!options.some((o) => o.kind === "allow_once"))
|
|
900
|
+
return reply(false, "the agent offered no allow-once option", ask.summary);
|
|
901
|
+
// A read-only turn never asks to change files, nor to pass a check for a path the agent could
|
|
902
|
+
// write; not even what was allowed for the rest of the job in one of its write turns (askableReadOnly).
|
|
903
|
+
if (spec.access === "read" && !askableReadOnly(ask))
|
|
904
|
+
return reply(false, "this turn is read-only", ask.summary);
|
|
905
|
+
const key = approvalKey(ask, spec.cwd);
|
|
906
|
+
if (heldHere.has(key) || spec.heldForJob?.(ask))
|
|
907
|
+
return reply(true, "allowed earlier for the rest of the job");
|
|
908
|
+
if (!spec.escalate || !spec.onApproval)
|
|
909
|
+
return reply(false, "this turn cannot ask for approval", ask.summary);
|
|
910
|
+
let allow = false;
|
|
911
|
+
let why = "refused";
|
|
912
|
+
try {
|
|
913
|
+
const answer = await spec.onApproval(ask, () => outcome !== null || cancelled);
|
|
914
|
+
allow = answer.allow;
|
|
915
|
+
if (answer.allow && answer.forJob)
|
|
916
|
+
heldHere.add(key);
|
|
917
|
+
// Relay's own reason, where it refused without anyone deciding (a protected path, nobody answering), for the log.
|
|
918
|
+
if (!answer.allow && !answer.decider && answer.note)
|
|
919
|
+
why = `refused: ${oneLine(answer.note, 300)}`;
|
|
920
|
+
}
|
|
921
|
+
catch {
|
|
922
|
+
allow = false;
|
|
923
|
+
}
|
|
924
|
+
reply(allow, allow ? "allowed" : why, allow ? undefined : ask.summary);
|
|
925
|
+
};
|
|
926
|
+
const onUpdate = (u) => {
|
|
927
|
+
lastUpdate = Date.now();
|
|
928
|
+
switch (u.sessionUpdate) {
|
|
929
|
+
case "user_message_chunk":
|
|
930
|
+
// Sent by such a harness only in a replay: once the prompt is out, the replay was not over.
|
|
931
|
+
if (prompting && loaded && profile.replaysAfterLoad && !replayLate) {
|
|
932
|
+
replayLate = true;
|
|
933
|
+
notes.push(`${name} was still replaying the earlier conversation after relay sent this turn's prompt, so its reply may begin with part of an earlier one.`);
|
|
934
|
+
}
|
|
935
|
+
break;
|
|
936
|
+
case "agent_message_chunk":
|
|
937
|
+
// A session/load replays the conversation as updates; only this turn's words are its reply.
|
|
938
|
+
if (prompting && u.content?.type === "text" && typeof u.content.text === "string" && !profile.notice?.(u.content.text))
|
|
939
|
+
finalMessage += u.content.text;
|
|
940
|
+
break;
|
|
941
|
+
case "tool_call":
|
|
942
|
+
case "tool_call_update": {
|
|
943
|
+
if (typeof u.toolCallId !== "string")
|
|
944
|
+
break;
|
|
945
|
+
calls.set(u.toolCallId, mergeToolCall(calls.get(u.toolCallId), u));
|
|
946
|
+
announced.set(u.toolCallId, mergeToolCall(announced.get(u.toolCallId), u));
|
|
947
|
+
// The reply is what the agent says after its last tool call.
|
|
948
|
+
if (prompting && u.sessionUpdate === "tool_call")
|
|
949
|
+
finalMessage = "";
|
|
950
|
+
// What it has just started doing, for progress lines (a load's replay is not this turn's).
|
|
951
|
+
if (prompting && (u.sessionUpdate === "tool_call" || u.status === "in_progress")) {
|
|
952
|
+
const text = callActivity(calls.get(u.toolCallId));
|
|
953
|
+
if (text)
|
|
954
|
+
spec.onActivity?.(text);
|
|
955
|
+
}
|
|
956
|
+
break;
|
|
957
|
+
}
|
|
958
|
+
case "usage_update": {
|
|
959
|
+
// ACP reports cost here, when the agent knows it; tokens come with the prompt's response.
|
|
960
|
+
const cost = u.cost;
|
|
961
|
+
if (prompting && typeof cost?.amount === "number" && cost.currency === "USD") {
|
|
962
|
+
usage.cost_usd = cost.amount;
|
|
963
|
+
spec.onUsage?.({ ...usage });
|
|
964
|
+
}
|
|
965
|
+
break;
|
|
966
|
+
}
|
|
967
|
+
case "current_mode_update":
|
|
968
|
+
if (typeof u.currentModeId === "string")
|
|
969
|
+
current.mode = u.currentModeId;
|
|
970
|
+
break;
|
|
971
|
+
case "config_option_update":
|
|
972
|
+
takeOptions(u.configOptions);
|
|
973
|
+
current.model = typeof optionFor("model")?.[1].currentValue === "string" ? optionFor("model")[1].currentValue : undefined;
|
|
974
|
+
break;
|
|
975
|
+
// Not in ACP v1, but a model report all the same where an agent sends one.
|
|
976
|
+
case "current_model_update":
|
|
977
|
+
current.model = typeof u.currentModelId === "string" ? u.currentModelId : undefined;
|
|
978
|
+
for (const [key, option] of current.options)
|
|
979
|
+
if (option.category === "model")
|
|
980
|
+
current.options.set(key, { ...option, currentValue: current.model });
|
|
981
|
+
break;
|
|
982
|
+
}
|
|
983
|
+
if (verified && (u.sessionUpdate === "current_model_update" || u.sessionUpdate === "config_option_update")) {
|
|
984
|
+
// Only away from a model relay pinned is a switch: under "auto" or no model, a model reported
|
|
985
|
+
// mid-turn is what was chosen (design-family-steering.md §2.9), recorded as any report is.
|
|
986
|
+
const next = modelNow();
|
|
987
|
+
if (pinned && next !== model)
|
|
988
|
+
switchedModel(next);
|
|
989
|
+
served(next);
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
/**
|
|
993
|
+
* A switch away from the model relay pinned. Within the pinned model's own family it goes on with a
|
|
994
|
+
* note under either policy: the same_family policy is not at stake (Gemini falling back from pro to
|
|
995
|
+
* flash, Copilot from one Claude model to another). Otherwise it continues and relabels under
|
|
996
|
+
* "allow", and under "refuse" stops the turn and revokes its tools.
|
|
997
|
+
*/
|
|
998
|
+
const switchedModel = (now) => {
|
|
999
|
+
if (outcome)
|
|
1000
|
+
return;
|
|
1001
|
+
const family = now ? vendorFor(target, now) : null;
|
|
1002
|
+
const asked = vendorFor(target, model);
|
|
1003
|
+
const to = oneLine(JSON.stringify(now ?? null), 120);
|
|
1004
|
+
const from = oneLine(JSON.stringify(model ?? null), 120);
|
|
1005
|
+
const note = (text) => {
|
|
1006
|
+
const key = JSON.stringify(now ?? null);
|
|
1007
|
+
if (!noted.has(key)) {
|
|
1008
|
+
noted.add(key);
|
|
1009
|
+
notes.push(text);
|
|
1010
|
+
}
|
|
1011
|
+
};
|
|
1012
|
+
if (family && family === asked) {
|
|
1013
|
+
// One note for the turn, however many models of the family answered (a helper call beside the main one).
|
|
1014
|
+
if (!withinModels.includes(to))
|
|
1015
|
+
withinModels.push(to);
|
|
1016
|
+
const text = `${name} changed its model in the middle of the turn to ${withinModels.join(", then ")}, from ${from} (switched within ${VENDOR_NAMES[family]}; same_family policy unaffected).`;
|
|
1017
|
+
if (withinNote < 0)
|
|
1018
|
+
withinNote = notes.push(text) - 1;
|
|
1019
|
+
else
|
|
1020
|
+
notes[withinNote] = text;
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
if (!strict)
|
|
1024
|
+
return note(`${name} changed its model in the middle of the turn to ${to} (${family ? `${VENDOR_NAMES[family]}'s` : "family unknown"}), from ${from}. same_family is "allow", so relay let the turn go on; this reply may be from that model.`);
|
|
1025
|
+
if (sessionId)
|
|
1026
|
+
rpc.send({ method: "session/cancel", params: { sessionId } });
|
|
1027
|
+
const why = !now ? "it no longer reports which model it runs, so relay cannot tell which family answers"
|
|
1028
|
+
: !family ? `relay cannot tell which family ${to} is, so another family's model may have answered`
|
|
1029
|
+
: asked ? `${VENDOR_NAMES[family]}'s model may have answered, not ${VENDOR_NAMES[asked]}'s`
|
|
1030
|
+
: "another family's model may have answered";
|
|
1031
|
+
finish(fail(`${name} changed its model mid-turn to ${JSON.stringify(now ?? null)}, from the ${JSON.stringify(model)} relay asked for, so relay stopped it and took away its relay tools: ${why}.`));
|
|
1032
|
+
};
|
|
1033
|
+
// Wait (briefly, bounded) for the denial stream to attach before the harness starts, so its early
|
|
1034
|
+
// denials are not missed; a slow or absent log stream resolves this after a short grace (review C4).
|
|
1035
|
+
if (denialStream)
|
|
1036
|
+
await denialStream.ready;
|
|
1037
|
+
// The last moment a stop can come before the harness exists: after this its turn is in the worker's
|
|
1038
|
+
// hands, and a stop cancels it like any other (E18).
|
|
1039
|
+
if (spec.signal?.aborted) {
|
|
1040
|
+
writeHeader();
|
|
1041
|
+
denialStream?.close();
|
|
1042
|
+
log.end();
|
|
1043
|
+
await launched.close().catch(() => { });
|
|
1044
|
+
state.cleanup?.();
|
|
1045
|
+
throw new Error(`the turn was stopped while relay was starting ${name}`);
|
|
1046
|
+
}
|
|
1047
|
+
let started;
|
|
1048
|
+
try {
|
|
1049
|
+
started = connect(launched.command, launched.args, spec.cwd, env, (m, line) => {
|
|
1050
|
+
log.agent(m, line);
|
|
1051
|
+
if (m.id !== undefined && m.method) {
|
|
1052
|
+
if (m.method === "session/request_permission")
|
|
1053
|
+
return void onPermission(m).catch(() => { });
|
|
1054
|
+
// Relay offers no file system, terminal or other client methods (it advertised none), and
|
|
1055
|
+
// answers at once, so that an agent never waits on a request nobody will serve.
|
|
1056
|
+
return rpc.send({ id: m.id, error: { code: METHOD_NOT_FOUND, message: `relay does not provide ${m.method}` } });
|
|
1057
|
+
}
|
|
1058
|
+
if (m.method === "session/update" && m.params?.sessionId === sessionId && m.params?.update)
|
|
1059
|
+
onUpdate(m.params.update);
|
|
1060
|
+
}, cutSecrets);
|
|
1061
|
+
}
|
|
1062
|
+
finally {
|
|
1063
|
+
// Before anything the harness or a stream sends can be read: those come in later events.
|
|
1064
|
+
writeHeader();
|
|
1065
|
+
}
|
|
1066
|
+
const rpc = started;
|
|
1067
|
+
// Kept in the log a whole line at a time, so that a line split across reads stays one line, and
|
|
1068
|
+
// redacted a whole line at a time: the tail quoted in an error is made of redacted lines only.
|
|
1069
|
+
let errLine = "";
|
|
1070
|
+
const logErr = (text) => {
|
|
1071
|
+
if (!text)
|
|
1072
|
+
return;
|
|
1073
|
+
const clean = cutSecrets(text);
|
|
1074
|
+
stderrTail.write(clean + "\n");
|
|
1075
|
+
if (!log.writableEnded)
|
|
1076
|
+
log.write(clean.replace(/^/gm, "[stderr] ") + "\n");
|
|
1077
|
+
};
|
|
1078
|
+
rpc.child.stderr.on("data", (chunk) => {
|
|
1079
|
+
errLine += chunk.toString();
|
|
1080
|
+
const cut = errLine.lastIndexOf("\n");
|
|
1081
|
+
if (cut >= 0) {
|
|
1082
|
+
logErr(errLine.slice(0, cut));
|
|
1083
|
+
errLine = errLine.slice(cut + 1);
|
|
1084
|
+
}
|
|
1085
|
+
});
|
|
1086
|
+
watch = watchProcess(rpc.pid);
|
|
1087
|
+
let settling;
|
|
1088
|
+
const settle = (code) => settling ??= (async () => {
|
|
1089
|
+
for (const timer of stopTimers)
|
|
1090
|
+
clearTimeout(timer);
|
|
1091
|
+
// The harness is gone: its relay tools and its network go now, not after the drain below, which
|
|
1092
|
+
// anything it left running would otherwise keep using (review r_7feaed80 C3).
|
|
1093
|
+
void launched.revoke();
|
|
1094
|
+
const unseenMs = watch.stop();
|
|
1095
|
+
if (!outcome) {
|
|
1096
|
+
// The tail of complete lines and whatever came after the last line break, quoted together:
|
|
1097
|
+
// cleaned as the tail's lines are (diagnosticTail), each part after this profile's redaction,
|
|
1098
|
+
// and cut to the tail's bound.
|
|
1099
|
+
const quoted = diagnosticTail(STDERR_TAIL);
|
|
1100
|
+
quoted.write(stderrTail.text() + cutSecrets(errLine));
|
|
1101
|
+
outcome = cancelled
|
|
1102
|
+
? { status: "interrupted", error: "cancelled" }
|
|
1103
|
+
: fail(`${name} exited (code ${code}) before the turn finished${initialized ? "" : `, before relay could check its login (a harness that is not signed in can stop there). ${profile.login.how}`}. ${quoted.text().trim().split("\n").slice(-3).join(" ")}`.trim());
|
|
1104
|
+
}
|
|
1105
|
+
for (const answer of pending.values())
|
|
1106
|
+
answer();
|
|
1107
|
+
pending.clear();
|
|
1108
|
+
// Whatever the agent started may be holding its output open. The streams get a moment to
|
|
1109
|
+
// drain and are then closed, so that neither the turn nor this worker waits on them.
|
|
1110
|
+
rpc.child.stdin.end();
|
|
1111
|
+
if (groupRefused)
|
|
1112
|
+
rpc.disconnect();
|
|
1113
|
+
else {
|
|
1114
|
+
// Cleared once the streams have closed, so that it does not keep the worker alive for a second after its last turn.
|
|
1115
|
+
let drained;
|
|
1116
|
+
await Promise.race([new Promise((r) => rpc.child.once("close", r)), new Promise((r) => { drained = setTimeout(r, 1000); })]);
|
|
1117
|
+
clearTimeout(drained);
|
|
1118
|
+
}
|
|
1119
|
+
rpc.child.stdout?.destroy();
|
|
1120
|
+
rpc.child.stderr?.destroy();
|
|
1121
|
+
logErr(errLine);
|
|
1122
|
+
log.end();
|
|
1123
|
+
// The turn is over only when nothing of the agent is left: children can outlive the leader.
|
|
1124
|
+
if (!groupRefused && rpc.pid > 1)
|
|
1125
|
+
groupRefused = !await drainGroup(rpc.pid);
|
|
1126
|
+
if (groupRefused) {
|
|
1127
|
+
cleanupRefusal ??= `Agent cleanup refused for group ${rpc.pid}`;
|
|
1128
|
+
rpc.child.unref();
|
|
1129
|
+
}
|
|
1130
|
+
const survivors = groupRefused ? [rpc.pid, ...watch.procs().map(p => p.pid)] : await stopProcs(watch.procs());
|
|
1131
|
+
denialStream?.close();
|
|
1132
|
+
await launched.close().catch(() => { });
|
|
1133
|
+
state.cleanup?.();
|
|
1134
|
+
// The login store as the turn left it (a stated downgrade): an exchange of two names can put a link
|
|
1135
|
+
// or a directory at the token's name, which no rule can tell from a rename (review r_75bf1f48).
|
|
1136
|
+
// Quarantine outside the sandbox before reporting, so a later personal harness cannot follow it.
|
|
1137
|
+
// Standalone turns have no registry turn id; give them a unique id as well.
|
|
1138
|
+
const turn = String(spec.relay?.turnId ?? crypto.randomUUID());
|
|
1139
|
+
const component = (s) => {
|
|
1140
|
+
if (!/^[A-Za-z0-9_-]+$/.test(s))
|
|
1141
|
+
throw new Error(`invalid quarantine identity: ${JSON.stringify(s)}`);
|
|
1142
|
+
return s;
|
|
1143
|
+
};
|
|
1144
|
+
let quarantine;
|
|
1145
|
+
try {
|
|
1146
|
+
if (launched.loginStore)
|
|
1147
|
+
quarantine = quarantineTokenStore(launched.loginStore, path.join(relayHome(), "quarantine", component(spec.markers.runId), component(spec.markers.nodeId), component(turn)), turn);
|
|
1148
|
+
}
|
|
1149
|
+
catch (err) {
|
|
1150
|
+
quarantine = { problem: err.message, moved: [], errors: [`QUARANTINE FAILED: ${err.message}`] };
|
|
1151
|
+
}
|
|
1152
|
+
if (quarantine?.problem) {
|
|
1153
|
+
const moved = quarantine.moved.length ? `Relay quarantined ${quarantine.moved.map((m) => `${JSON.stringify(m.name)} to ${JSON.stringify(m.to)}`).join("; ")}. ` : "";
|
|
1154
|
+
const failure = quarantine.errors.length ? `${quarantine.errors.join("; ")}. Do not use ${target.product} yourself until these names are put right. ` : "";
|
|
1155
|
+
const text = `${launched.loginStore.name} is not as relay left it: ${quarantine.problem}. ${moved}${failure}You must log in again before using ${target.product}. ${profile.login.how || `Run \`${target.id} login\`.`} Relay refuses this harness's turns until the store passes its check and its login is restored.`;
|
|
1156
|
+
outcome = fail(outcome?.status === "failed" ? `${outcome.error}\n${text}` : text);
|
|
1157
|
+
}
|
|
1158
|
+
notes.push(...logWarnings());
|
|
1159
|
+
if (cleanupRefusal)
|
|
1160
|
+
notes.push(cleanupRefusal);
|
|
1161
|
+
resolveDone({
|
|
1162
|
+
served: servedModels,
|
|
1163
|
+
...outcome, ...(outcome?.error !== undefined ? { error: cleanReport(outcome.error) } : {}),
|
|
1164
|
+
sessionId, finalMessage: cleanReport(finalMessage), exitCode: code, ...(notes.length ? { warnings: notes.map(cleanReport) } : {}), ...(prompting ? {} : { delivered: false }),
|
|
1165
|
+
...(survivors.length ? { survivors } : {}), ...(settled || rpc.pid <= 1 ? {} : { unseenMs }), ...(denials.length ? { denials: denials.map(cleanReport) } : {}),
|
|
1166
|
+
});
|
|
1167
|
+
})();
|
|
1168
|
+
rpc.child.on("error", (err) => {
|
|
1169
|
+
outcome = fail(`could not start ${bin}: ${err.message}`);
|
|
1170
|
+
if (rpc.pid <= 1)
|
|
1171
|
+
void settle(null);
|
|
1172
|
+
});
|
|
1173
|
+
// "exit", not "close": something the agent started can hold its output open.
|
|
1174
|
+
rpc.child.on("exit", (code) => void settle(code));
|
|
1175
|
+
(async () => {
|
|
1176
|
+
// What the launch must confirm about the running process (relay's sandbox) comes first.
|
|
1177
|
+
const unconfined = await launched.verify(rpc.pid);
|
|
1178
|
+
if (unconfined)
|
|
1179
|
+
return finish(fail(unconfined));
|
|
1180
|
+
// No file system or terminal: the agent uses its own tools, inside relay's confinement.
|
|
1181
|
+
const init = await rpc.request("initialize", {
|
|
1182
|
+
protocolVersion: ACP_VERSION,
|
|
1183
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
1184
|
+
clientInfo: { name: "relay", title: "relay", version: VERSION },
|
|
1185
|
+
}, 60_000);
|
|
1186
|
+
initialized = true;
|
|
1187
|
+
if (init?.protocolVersion !== ACP_VERSION) {
|
|
1188
|
+
return finish(fail(`${name} speaks ACP version ${JSON.stringify(init?.protocolVersion ?? null)}, and relay speaks only version ${ACP_VERSION}, so it does not run it.`));
|
|
1189
|
+
}
|
|
1190
|
+
// The version: agentInfo's, else _meta.agentVersion (Grok 1.0.62 sends no agentInfo).
|
|
1191
|
+
log.write(`# relay: ${name} ${JSON.stringify(init?.agentInfo?.version ?? init?._meta?.agentVersion ?? null)} speaks ACP ${init.protocolVersion}; login methods offered ${JSON.stringify(Array.isArray(init?.authMethods) ? init.authMethods.map((m) => m?.id) : [])}\n`);
|
|
1192
|
+
const loginProblem = await checkLogin(rpc, init, profile, spec);
|
|
1193
|
+
if (loginProblem)
|
|
1194
|
+
return finish(fail(loginProblem));
|
|
1195
|
+
if (state.authenticate) {
|
|
1196
|
+
const authProblem = await authenticateAsPrepared(rpc, init, state.authenticate, name);
|
|
1197
|
+
if (authProblem)
|
|
1198
|
+
return finish(fail(authProblem));
|
|
1199
|
+
log.write(`# relay: signed in with ${JSON.stringify(state.authenticate.methodId)}, as the profile prepared\n`);
|
|
1200
|
+
}
|
|
1201
|
+
// What the harness did while answering initialize that its session's setup must show afresh.
|
|
1202
|
+
state.afterInitialize?.();
|
|
1203
|
+
const caps = (init.agentCapabilities ?? {});
|
|
1204
|
+
const mcpServers = launched.relay
|
|
1205
|
+
? [{ name: "relay", command: launched.relay.command, args: launched.relay.args, env: Object.entries(launched.relay.env).map(([n, value]) => ({ name: n, value })) }]
|
|
1206
|
+
: [];
|
|
1207
|
+
const extra = spec.access === "write" ? (spec.grant?.write_paths ?? []) : [];
|
|
1208
|
+
const session = { cwd: spec.cwd, mcpServers, ...(extra.length && caps.sessionCapabilities?.additionalDirectories ? { additionalDirectories: extra } : {}) };
|
|
1209
|
+
let res;
|
|
1210
|
+
if (spec.sessionId) {
|
|
1211
|
+
// Resume reconnects without replay; load replays the conversation, which is not this turn's reply.
|
|
1212
|
+
if (caps.sessionCapabilities?.resume)
|
|
1213
|
+
res = await rpc.request("session/resume", { sessionId: spec.sessionId, ...session });
|
|
1214
|
+
else if (caps.loadSession) {
|
|
1215
|
+
res = await rpc.request("session/load", { sessionId: spec.sessionId, ...session });
|
|
1216
|
+
loaded = true;
|
|
1217
|
+
lastUpdate = Date.now();
|
|
1218
|
+
}
|
|
1219
|
+
else
|
|
1220
|
+
return finish(fail(`${name} cannot continue an earlier session over ACP, so relay cannot resume this one.`));
|
|
1221
|
+
}
|
|
1222
|
+
else {
|
|
1223
|
+
res = await rpc.request("session/new", session);
|
|
1224
|
+
if (typeof res?.sessionId !== "string")
|
|
1225
|
+
return finish(fail(`${name} did not give the new session an id.`));
|
|
1226
|
+
sessionId = res.sessionId;
|
|
1227
|
+
}
|
|
1228
|
+
takeSession(res);
|
|
1229
|
+
// What the session reports, for the turn's log: the evidence for the checks below.
|
|
1230
|
+
const offered = Array.isArray(res?.models?.availableModels) ? res.models.availableModels.map((m) => m?.modelId).filter((m) => typeof m === "string") : null;
|
|
1231
|
+
log.write(`# relay: ${spec.sessionId ? "continued" : "new"} session ${JSON.stringify(sessionId ?? null)}; mode ${JSON.stringify(modeNow() ?? null)}, model ${JSON.stringify(modelNow() ?? null)}${offered ? `, offered ${JSON.stringify(offered)}` : ""}\n`);
|
|
1232
|
+
// A model the harness does not offer this account (Copilot Free offers only "auto") is said
|
|
1233
|
+
// plainly, before relay asks for it.
|
|
1234
|
+
if (model && offered?.length && !offered.includes(model) && !profile.acceptsUnlistedModels) {
|
|
1235
|
+
return finish(fail(`${name} does not offer the model ${JSON.stringify(model)} to this account (it offers ${[...new Set(offered)].map((m) => JSON.stringify(m)).join(", ")}), so relay stopped it before it did anything.`));
|
|
1236
|
+
}
|
|
1237
|
+
// The login again, now that the session exists: a resumed or loaded session is checked as a new one is.
|
|
1238
|
+
const after = await checkLogin(rpc, init, profile, spec);
|
|
1239
|
+
if (after)
|
|
1240
|
+
return finish(fail(after));
|
|
1241
|
+
// The mode and the model, set where they are not already, and then read back as the agent reports them.
|
|
1242
|
+
const mode = profile.mode?.(spec);
|
|
1243
|
+
if (mode && modeNow() !== mode) {
|
|
1244
|
+
const opt = optionFor("mode");
|
|
1245
|
+
if (res?.modes)
|
|
1246
|
+
await rpc.request("session/set_mode", { sessionId, modeId: mode });
|
|
1247
|
+
else if (opt)
|
|
1248
|
+
takeOptions((await rpc.request("session/set_config_option", { sessionId, configId: opt[0], value: mode }))?.configOptions);
|
|
1249
|
+
}
|
|
1250
|
+
if (model && modelNow() !== model) {
|
|
1251
|
+
const opt = optionFor("model");
|
|
1252
|
+
if (opt)
|
|
1253
|
+
takeOptions((await rpc.request("session/set_config_option", { sessionId, configId: opt[0], value: model }))?.configOptions);
|
|
1254
|
+
}
|
|
1255
|
+
if (mode && modeNow() !== mode)
|
|
1256
|
+
return finish(fail(`${name} reports the mode ${JSON.stringify(modeNow() ?? null)}, not the ${JSON.stringify(mode)} relay set, so relay stopped it before it did anything.`));
|
|
1257
|
+
// The reasoning effort, where the profile says the session reports it: exactly the one asked for.
|
|
1258
|
+
if (spec.effort && profile.effortOption) {
|
|
1259
|
+
const opt = optionFor(profile.effortOption)?.[1];
|
|
1260
|
+
if (opt?.currentValue !== spec.effort) {
|
|
1261
|
+
const offers = opt?.values ? ` (it offers ${opt.values.map((v) => JSON.stringify(v)).join(", ")}${model ? ` for ${JSON.stringify(model)}` : ""})` : "";
|
|
1262
|
+
return finish(fail(`${name} reports the reasoning effort ${JSON.stringify(opt?.currentValue ?? null)}, not the ${JSON.stringify(spec.effort)} relay asked for${offers}, so relay stopped it before it did anything.`));
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
if (pinned || strict) {
|
|
1266
|
+
const reported = modelNow();
|
|
1267
|
+
if (reported === undefined)
|
|
1268
|
+
return finish(fail(`${name} does not report which model the session uses, so relay cannot tell which family would answer. It stopped it before it did anything.`));
|
|
1269
|
+
if (pinned && reported !== model)
|
|
1270
|
+
return finish(fail(`${name} reports the model ${JSON.stringify(reported)}, not the ${JSON.stringify(model)} relay asked for, so relay stopped it before it did anything.`));
|
|
1271
|
+
}
|
|
1272
|
+
// A replay the harness streams after the load's answer (replaysAfterLoad) is over before the
|
|
1273
|
+
// prompt goes out: until then nothing it sends is this turn's.
|
|
1274
|
+
if (loaded && profile.replaysAfterLoad) {
|
|
1275
|
+
const { quietMs, maxMs } = profile.replaysAfterLoad;
|
|
1276
|
+
const giveUp = Date.now() + maxMs;
|
|
1277
|
+
for (;;) {
|
|
1278
|
+
if (outcome)
|
|
1279
|
+
return;
|
|
1280
|
+
const idle = Date.now() - lastUpdate;
|
|
1281
|
+
if (idle >= quietMs)
|
|
1282
|
+
break;
|
|
1283
|
+
if (Date.now() > giveUp)
|
|
1284
|
+
return finish(fail(`${name} was still replaying the earlier conversation ${Math.round(maxMs / 1000)}s after loading the session, so relay could not tell this turn's reply from it. It stopped it before sending the prompt.`));
|
|
1285
|
+
await new Promise((r) => setTimeout(r, Math.min(quietMs - idle, 50)));
|
|
1286
|
+
}
|
|
1287
|
+
log.write(`# relay: ${name}'s replay of the session is over (no update for ${quietMs} ms); sending the prompt\n`);
|
|
1288
|
+
}
|
|
1289
|
+
const reported = modelNow();
|
|
1290
|
+
if (!served(reported))
|
|
1291
|
+
return;
|
|
1292
|
+
// What the profile has to say now that the session is set up (Gemini: whether its tool discovery
|
|
1293
|
+
// ran), before the prompt and in the same message, so that the agent reads it before it acts.
|
|
1294
|
+
const agentVersion = typeof init?.agentInfo?.version === "string" ? init.agentInfo.version : null;
|
|
1295
|
+
const before = state.beforePrompt?.({ agentVersion });
|
|
1296
|
+
for (const note of before?.notes ?? []) {
|
|
1297
|
+
notes.push(note);
|
|
1298
|
+
log.write(`# relay: ${note}\n`);
|
|
1299
|
+
}
|
|
1300
|
+
const text = profile.promptText?.(spec.prompt) ?? spec.prompt;
|
|
1301
|
+
// Session setup/replay may have grown the never floor; refuse before sending agent work.
|
|
1302
|
+
spec.checkEnvironment?.(env);
|
|
1303
|
+
verified = true;
|
|
1304
|
+
prompting = true;
|
|
1305
|
+
const r = await rpc.request("session/prompt", { sessionId, prompt: [{ type: "text", text: before?.promptPrefix ? `${before.promptPrefix}\n\n${text}` : text }] });
|
|
1306
|
+
const tokens = acpUsage(r?.usage);
|
|
1307
|
+
if (tokens) {
|
|
1308
|
+
Object.assign(usage, tokens);
|
|
1309
|
+
spec.onUsage?.({ ...usage });
|
|
1310
|
+
}
|
|
1311
|
+
// The response's own list of models, before the profile reads it (Gemini's drops the entries that
|
|
1312
|
+
// stand for another model's rounds): replies to relay's requests are not in the agent's log, so
|
|
1313
|
+
// this line is the record of what the harness said, against which what relay recorded is checked.
|
|
1314
|
+
const listed = promptModels(r);
|
|
1315
|
+
if (listed.length)
|
|
1316
|
+
log.write(`# relay: ${name}'s prompt response lists ${listed.map((m) => oneLine(JSON.stringify(m), 120)).join(", ")} in _meta.quota.model_usage\n`);
|
|
1317
|
+
// The models that answered, where only the prompt's response says: model reports like the rest.
|
|
1318
|
+
let answered = [];
|
|
1319
|
+
try {
|
|
1320
|
+
answered = profile.servedModels?.(r, reported) ?? [];
|
|
1321
|
+
}
|
|
1322
|
+
catch (err) {
|
|
1323
|
+
return finish(fail(`relay could not read which model ${name} says answered (${err.message}), so it does not count the turn as done.`));
|
|
1324
|
+
}
|
|
1325
|
+
if (answered.length)
|
|
1326
|
+
log.write(`# relay: ${name} reports ${answered.map((m) => JSON.stringify(m)).join(", then ")} answered this turn (in its prompt response)\n`);
|
|
1327
|
+
for (const m of answered) {
|
|
1328
|
+
if (pinned && m !== model)
|
|
1329
|
+
switchedModel(m);
|
|
1330
|
+
// Every model the response names is recorded, even after one has stopped the turn: each answered
|
|
1331
|
+
// all the same (review r_75bf1f48 X1). A stop already taken stays: nothing here restores the tools.
|
|
1332
|
+
if (!served(m))
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
if (outcome)
|
|
1336
|
+
return;
|
|
1337
|
+
const stop = r?.stopReason;
|
|
1338
|
+
if (stop === "end_turn")
|
|
1339
|
+
finish({ status: "ok" });
|
|
1340
|
+
else if (stop === "cancelled" || cancelled)
|
|
1341
|
+
finish({ status: "interrupted", error: "cancelled" });
|
|
1342
|
+
else
|
|
1343
|
+
finish(fail(`${name}'s turn ended with ${JSON.stringify(stop ?? null)}${stop === "refusal" ? " (the model refused)" : stop === "max_tokens" || stop === "max_turn_requests" ? " (it ran out of room before finishing)" : ""}.`));
|
|
1344
|
+
})().catch((err) => finish(cancelled ? { status: "interrupted", error: "cancelled" } : fail(`${name} over ACP: ${err.message}`)));
|
|
1345
|
+
const cancel = async () => {
|
|
1346
|
+
if (cancelled || rpc.pid <= 1) {
|
|
1347
|
+
await done;
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
cancelled = true;
|
|
1351
|
+
// Cancelled: relay tools and network end at once, whether or not the agent heeds session/cancel.
|
|
1352
|
+
void launched.revoke();
|
|
1353
|
+
settled = watch.look() || settled;
|
|
1354
|
+
// The clean way to stop a turn is to ask the agent, which then stops what it started and
|
|
1355
|
+
// answers the prompt "cancelled"; requests it was waiting on are answered "cancelled" first.
|
|
1356
|
+
for (const answer of pending.values())
|
|
1357
|
+
answer();
|
|
1358
|
+
pending.clear();
|
|
1359
|
+
if (sessionId && prompting)
|
|
1360
|
+
rpc.send({ method: "session/cancel", params: { sessionId } });
|
|
1361
|
+
else
|
|
1362
|
+
signalGroup("SIGINT");
|
|
1363
|
+
const timer = setTimeout(() => {
|
|
1364
|
+
watch.look();
|
|
1365
|
+
if (signalGroup("SIGKILL"))
|
|
1366
|
+
killProcs(watch.procs());
|
|
1367
|
+
}, cfg.cancel_grace_ms);
|
|
1368
|
+
await done;
|
|
1369
|
+
clearTimeout(timer);
|
|
1370
|
+
};
|
|
1371
|
+
return { pid: rpc.pid, pgid: rpc.pid, startedAt: procStart(rpc.pid), done, cancel };
|
|
1372
|
+
}
|
|
1373
|
+
const signsInWithLogin = (spec) => authFor(spec.config, spec.target.id) === "login";
|
|
1374
|
+
/** Why relay cannot check this harness's login at all, or null: under child_auth "login" a profile must name a way. */
|
|
1375
|
+
export function loginStrategyProblem(profile, spec) {
|
|
1376
|
+
if (!signsInWithLogin(spec) || profile.login.reuse?.length || profile.login.verify)
|
|
1377
|
+
return null;
|
|
1378
|
+
return `relay has no way to check that ${targetLabel(spec.target)} is signed in with an account, and it is set to run agents on their logins only ("child_auth": "any" for targets.${spec.target.id} allows it), so it does not launch it.`;
|
|
1379
|
+
}
|
|
1380
|
+
/** The profile's login check, made before the session and again once it exists. Returns what is wrong, or null. */
|
|
1381
|
+
async function checkLogin(rpc, init, profile, spec) {
|
|
1382
|
+
const name = targetLabel(spec.target);
|
|
1383
|
+
// With child_auth "any", whatever the harness signs in with is accepted.
|
|
1384
|
+
if (!signsInWithLogin(spec))
|
|
1385
|
+
return null;
|
|
1386
|
+
const strategy = loginStrategyProblem(profile, spec);
|
|
1387
|
+
if (strategy)
|
|
1388
|
+
return strategy;
|
|
1389
|
+
if (profile.login.verify) {
|
|
1390
|
+
const own = profile.login.verify(init);
|
|
1391
|
+
if (own)
|
|
1392
|
+
return own;
|
|
1393
|
+
}
|
|
1394
|
+
if (!profile.login.reuse?.length)
|
|
1395
|
+
return null;
|
|
1396
|
+
const offered = Array.isArray(init?.authMethods) ? init.authMethods.map((m) => m?.id) : [];
|
|
1397
|
+
const method = profile.login.reuse.find((id) => offered.includes(id));
|
|
1398
|
+
if (!method)
|
|
1399
|
+
return `${name} does not offer the login check relay knows (${profile.login.reuse.join(", ")}), so relay cannot tell that it is signed in with an account. ${profile.login.how}`;
|
|
1400
|
+
try {
|
|
1401
|
+
await rpc.request("authenticate", { methodId: method }, 30_000);
|
|
1402
|
+
return null;
|
|
1403
|
+
}
|
|
1404
|
+
catch (err) {
|
|
1405
|
+
return `${name} is not signed in (${err.message}). ${profile.login.how}`;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
/** The authenticate request a profile prepared (PreparedState.authenticate), made once: what is wrong, or null. */
|
|
1409
|
+
async function authenticateAsPrepared(rpc, init, auth, name) {
|
|
1410
|
+
const offered = Array.isArray(init?.authMethods) ? init.authMethods.map((m) => m?.id) : [];
|
|
1411
|
+
if (!offered.includes(auth.methodId))
|
|
1412
|
+
return `${name} does not offer the sign-in relay hands it (${JSON.stringify(auth.methodId)}), so relay stopped it before it did anything.`;
|
|
1413
|
+
try {
|
|
1414
|
+
await rpc.request("authenticate", { methodId: auth.methodId, ...(auth.meta ? { _meta: auth.meta } : {}) }, 30_000);
|
|
1415
|
+
return null;
|
|
1416
|
+
}
|
|
1417
|
+
catch (err) {
|
|
1418
|
+
return `${name} did not accept the sign-in relay handed it (${err.message}), so relay stopped it before it did anything.`;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
/** A Backend for a target driven over ACP with `profile`. */
|
|
1422
|
+
export function acpBackend(profile) {
|
|
1423
|
+
return { start: (spec) => startAcpTurn(spec, profile) };
|
|
1424
|
+
}
|