@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,67 @@
|
|
|
1
|
+
import { olderVersion, targetDef } from "../targets/index.js";
|
|
2
|
+
import { installedVersion } from "./cli-version.js";
|
|
3
|
+
import { linkLaunchProblem } from "./native-temp.js";
|
|
4
|
+
import { BACKENDS } from "./index.js";
|
|
5
|
+
import { capturedRootEnvironment, selectEnvironment } from "../core/env-policy.js";
|
|
6
|
+
import { targetLaunchProblem } from "../core/protected-config.js";
|
|
7
|
+
import { endpointProblem } from "./env.js";
|
|
8
|
+
import { withTurnSecrets } from "../core/secrets.js";
|
|
9
|
+
import { freezeCodexConfig } from "./codex-pin.js";
|
|
10
|
+
import { assertNeverAdapter } from "./never-admission.js";
|
|
11
|
+
/**
|
|
12
|
+
* Why this machine cannot run the target with the confinement relay describes, or null. What
|
|
13
|
+
* relay asks of each CLI's sandbox was verified on macOS with particular CLI versions; anywhere
|
|
14
|
+
* else it is a guess, and relay does not launch an agent on a guess unless told to.
|
|
15
|
+
*/
|
|
16
|
+
export function untested(target, config, environment, checkVersion = true) {
|
|
17
|
+
// An experimental target needs its own opt-in; allow_untested is about platforms and versions.
|
|
18
|
+
const def = targetDef(target);
|
|
19
|
+
if (!def.qualified && !config.targets[target]?.experimental) {
|
|
20
|
+
return `${def.name} is experimental: relay has not qualified it with a signed-in run, so its login, model selection and protocol behaviour are unverified. Set targets.${target}.experimental to true in relay's config to run it anyway.`;
|
|
21
|
+
}
|
|
22
|
+
if (config.allow_untested)
|
|
23
|
+
return null;
|
|
24
|
+
const off = 'Set "allow_untested": true in relay\'s config to run anyway, unverified.';
|
|
25
|
+
if (process.platform !== "darwin")
|
|
26
|
+
return `relay's confinement has only been verified on macOS, and this is ${process.platform}. ${off}`;
|
|
27
|
+
if (!checkVersion)
|
|
28
|
+
return null;
|
|
29
|
+
const env = environment ?? selectEnvironment(target, config, capturedRootEnvironment).env;
|
|
30
|
+
const endpoint = endpointProblem(target, env);
|
|
31
|
+
if (endpoint)
|
|
32
|
+
return endpoint;
|
|
33
|
+
const bin = config.targets[target].bin;
|
|
34
|
+
const have = installedVersion(target, bin, env);
|
|
35
|
+
const min = targetDef(target).tested;
|
|
36
|
+
const problem = !have ? `relay could not read a version from \`${bin} --version\``
|
|
37
|
+
: olderVersion(have, min) ? `${bin} is ${have.join(".")}, older than the ${min.join(".")} relay's confinement was verified with` : null;
|
|
38
|
+
return problem ? `${problem}. Update it, or: ${off}` : null;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Starts one turn of `target`'s CLI, refusing, by rejecting, a version or platform its confinement
|
|
42
|
+
* was not verified on, and whatever its backend refuses. `backend` is the target's own, unless a
|
|
43
|
+
* test passes another.
|
|
44
|
+
*/
|
|
45
|
+
export async function launchTurn(target, spec, backend = BACKENDS[target.id]) {
|
|
46
|
+
assertNeverAdapter(spec);
|
|
47
|
+
if (target.id === "codex")
|
|
48
|
+
spec = { ...spec, config: freezeCodexConfig(spec.config) };
|
|
49
|
+
const refusal = untested(target.id, spec.config, undefined, false);
|
|
50
|
+
if (refusal)
|
|
51
|
+
throw new Error(refusal);
|
|
52
|
+
return withTurnSecrets(() => backend.start({ ...spec, checkEnvironment: (env) => {
|
|
53
|
+
const problem = untested(target.id, spec.config, env);
|
|
54
|
+
if (problem)
|
|
55
|
+
throw new Error(problem);
|
|
56
|
+
// Claude's long-home link ceiling, on the read of the environment Claude is launched with (native-temp.ts).
|
|
57
|
+
const link = target.id === "claude" ? linkLaunchProblem(spec.config, env) : null;
|
|
58
|
+
if (link)
|
|
59
|
+
throw new Error(link);
|
|
60
|
+
// The CLI as this turn's PATH finds it, which is what its launch runs: not in a write path (review r_0c11d860 X1).
|
|
61
|
+
const writes = spec.access === "write" ? spec.grant?.write_paths ?? [] : [];
|
|
62
|
+
const launch = targetLaunchProblem(`the ${target.id} target's CLI`, spec.config.targets[target.id].bin, env.PATH ?? "", writes);
|
|
63
|
+
if (launch)
|
|
64
|
+
throw new Error(launch);
|
|
65
|
+
spec.checkEnvironment?.(env);
|
|
66
|
+
} }), { reuse: true });
|
|
67
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// The default turn runner, for a CLI that reads its prompt on stdin and writes one JSON event per
|
|
2
|
+
// line (Claude, and Codex's `codex exec` fallback), and the after-turn step a backend can add. Apart
|
|
3
|
+
// from run.ts, so that the backends can use it without importing the backend registry.
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import readline from "node:readline";
|
|
6
|
+
import { drainGroup, isGroupSignalRefusal, killProcs, procStart, sendGroupSignal, stopProcs } from "../core/procs.js";
|
|
7
|
+
import { executable } from "../core/executables.js";
|
|
8
|
+
import { openAgentLog, watchProcess } from "./types.js";
|
|
9
|
+
import { diagnosticTail } from "../core/redact.js";
|
|
10
|
+
import { refusalError } from "../core/refusal.js";
|
|
11
|
+
/** The handle with `fn` run after the agent and its descendants have stopped, before the turn is reported. */
|
|
12
|
+
export function afterTurn(handle, fn) {
|
|
13
|
+
const done = handle.done.then(fn);
|
|
14
|
+
return { ...handle, done, cancel: async () => { await handle.cancel(); await done; } };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Diagnostic lines a harness prints only because relay asked it to (Claude Code's sandbox under
|
|
18
|
+
* SRT_DEBUG, which reports its proxy ports): kept in the agent's log, never in what a failed turn reports.
|
|
19
|
+
*/
|
|
20
|
+
const DEBUG_LINE = /^\[SandboxDebug\] /;
|
|
21
|
+
/**
|
|
22
|
+
* Runs one turn of a CLI that takes its prompt on stdin and writes one JSON event per line, which
|
|
23
|
+
* `onEvent` reads into the turn's state: Claude, and Codex's `codex exec` fallback.
|
|
24
|
+
*/
|
|
25
|
+
export function streamTurn(spec, { invocation: inv, onEvent, onStderr, unlogged }) {
|
|
26
|
+
const { log, warnings: logWarnings } = openAgentLog(spec.logPath, { env: inv.env });
|
|
27
|
+
log.write(`\n# ${new Date().toISOString()} ${inv.command} ${inv.args.map((a) => JSON.stringify(a)).join(" ")}\n`);
|
|
28
|
+
// Preparation may have grown the never floor since the turn captured its launch plan.
|
|
29
|
+
try {
|
|
30
|
+
spec.checkEnvironment?.(inv.env);
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
log.end();
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
// detached: the agent leads its own process group, so cancel can signal the whole group.
|
|
37
|
+
const child = spawn(executable(inv.command, inv.env.PATH), inv.args, { cwd: spec.cwd, env: inv.env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
38
|
+
const pid = child.pid ?? -1;
|
|
39
|
+
const state = { finalMessage: "", completed: false };
|
|
40
|
+
const stderrTail = diagnosticTail();
|
|
41
|
+
let reported = false;
|
|
42
|
+
let refused = false;
|
|
43
|
+
let stopped = false;
|
|
44
|
+
/** A check relay makes after the start report failed: the prompt reached the agent, so it is not undelivered, but nothing more of the turn may run. */
|
|
45
|
+
const stopIfAsked = () => {
|
|
46
|
+
if (!state.stop || refused || stopped)
|
|
47
|
+
return;
|
|
48
|
+
stopped = true;
|
|
49
|
+
settled = watch.look() || settled;
|
|
50
|
+
signalGroup("SIGKILL");
|
|
51
|
+
};
|
|
52
|
+
/** True once a look has found the agent alive after it stopped starting things: at its last word, or when told to stop. */
|
|
53
|
+
let settled = false;
|
|
54
|
+
// The prompt goes on stdin, which is then closed: the CLIs block on an open stdin pipe. (Claude
|
|
55
|
+
// Code gives up on stdin after three seconds, and starts its sandbox only after reading it, so
|
|
56
|
+
// nothing the sandbox reports can be waited for before the prompt is sent.)
|
|
57
|
+
child.stdin.on("error", () => { });
|
|
58
|
+
child.stdin.end(spec.prompt);
|
|
59
|
+
const rl = readline.createInterface({ input: child.stdout });
|
|
60
|
+
rl.on("line", (line) => {
|
|
61
|
+
let event = null;
|
|
62
|
+
if (line.trim().startsWith("{")) {
|
|
63
|
+
try {
|
|
64
|
+
event = JSON.parse(line);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// Non-JSON noise on stdout is kept in the log and otherwise ignored.
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!event || !unlogged?.(event))
|
|
71
|
+
log.write(line + "\n");
|
|
72
|
+
if (!event)
|
|
73
|
+
return;
|
|
74
|
+
try {
|
|
75
|
+
onEvent(event, state, spec);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// A backend's reading of an event it cannot make sense of is not the turn's end.
|
|
79
|
+
}
|
|
80
|
+
// The agent is not running the way relay asked. It reports this before its first request to
|
|
81
|
+
// the model, so stopping it here stops it before it has done anything.
|
|
82
|
+
if (state.refuse && !refused) {
|
|
83
|
+
refused = true;
|
|
84
|
+
// A last look first, while it can still be traced: it is being stopped, not lost.
|
|
85
|
+
settled = watch.look() || settled;
|
|
86
|
+
signalGroup("SIGKILL");
|
|
87
|
+
}
|
|
88
|
+
stopIfAsked();
|
|
89
|
+
// A vendor safety stop is terminal. Stop the harness before it can retry or start tools.
|
|
90
|
+
// Unlike a launch-policy rejection, the prompt reached the vendor and its session is kept.
|
|
91
|
+
if (state.refusal) {
|
|
92
|
+
settled = watch.look() || settled;
|
|
93
|
+
signalGroup("SIGKILL");
|
|
94
|
+
}
|
|
95
|
+
// The agent has said its last word and is about to exit: the last look, if it is still there to be looked at.
|
|
96
|
+
if (state.ended && !reported) {
|
|
97
|
+
reported = true;
|
|
98
|
+
settled = watch.look() || settled;
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
let errLine = "";
|
|
102
|
+
child.stderr.setEncoding("utf8");
|
|
103
|
+
/** One complete stderr line: to the log; to the tail a failure quotes unless it is relay-requested debug output; to the backend's own check. */
|
|
104
|
+
const errLineDone = (line, live = true) => {
|
|
105
|
+
log.write("[stderr] " + line + "\n");
|
|
106
|
+
if (!DEBUG_LINE.test(line))
|
|
107
|
+
stderrTail.write(line + "\n");
|
|
108
|
+
if (!onStderr)
|
|
109
|
+
return;
|
|
110
|
+
onStderr(line, state);
|
|
111
|
+
if (live)
|
|
112
|
+
stopIfAsked();
|
|
113
|
+
};
|
|
114
|
+
child.stderr.on("data", (text) => {
|
|
115
|
+
errLine += text;
|
|
116
|
+
const end = errLine.lastIndexOf("\n");
|
|
117
|
+
if (end >= 0) {
|
|
118
|
+
for (const line of errLine.slice(0, end).split("\n"))
|
|
119
|
+
errLineDone(line);
|
|
120
|
+
errLine = errLine.slice(end + 1);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
let cancelled = false;
|
|
124
|
+
let groupRefused = false;
|
|
125
|
+
let cleanupRefusal;
|
|
126
|
+
const watch = watchProcess(pid);
|
|
127
|
+
let resolveDone;
|
|
128
|
+
const done = new Promise((resolve) => { resolveDone = resolve; });
|
|
129
|
+
let settling;
|
|
130
|
+
let spawnError;
|
|
131
|
+
child.on("error", (err) => {
|
|
132
|
+
spawnError = `could not start ${inv.command}: ${err.message}`;
|
|
133
|
+
// A process that never started has no exit to wait for.
|
|
134
|
+
if (pid <= 0) {
|
|
135
|
+
log.end();
|
|
136
|
+
watch.stop();
|
|
137
|
+
resolveDone({ sessionId: undefined, finalMessage: "", exitCode: null, status: "failed", error: spawnError });
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
// Resolved from "exit", not "close": a detached process the agent started can hold its output
|
|
141
|
+
// open indefinitely, and the turn must not wait on that. Output gets a moment to drain.
|
|
142
|
+
const settle = (code) => settling ??= (async () => {
|
|
143
|
+
const unseenMs = watch.stop();
|
|
144
|
+
if (!groupRefused) {
|
|
145
|
+
// Cleared once the streams have closed, so that it does not keep the worker alive for a second after its last turn.
|
|
146
|
+
let drained;
|
|
147
|
+
await Promise.race([new Promise((r) => child.once("close", r)), new Promise((r) => { drained = setTimeout(r, 1000); })]);
|
|
148
|
+
clearTimeout(drained);
|
|
149
|
+
}
|
|
150
|
+
child.stdout.destroy();
|
|
151
|
+
child.stderr.destroy();
|
|
152
|
+
if (errLine)
|
|
153
|
+
errLineDone(errLine, false);
|
|
154
|
+
log.end();
|
|
155
|
+
// The turn is over only when nothing of the agent is left: children can outlive the leader.
|
|
156
|
+
if (!groupRefused)
|
|
157
|
+
groupRefused = !await drainGroup(pid);
|
|
158
|
+
if (groupRefused) {
|
|
159
|
+
cleanupRefusal ??= `Agent cleanup refused for group ${pid}`;
|
|
160
|
+
child.unref();
|
|
161
|
+
}
|
|
162
|
+
const survivors = groupRefused ? [pid, ...watch.procs().map(p => p.pid)] : await stopProcs(watch.procs());
|
|
163
|
+
const warnings = [...(state.warnings ?? []), ...logWarnings(), ...(cleanupRefusal ? [cleanupRefusal] : [])];
|
|
164
|
+
const base = {
|
|
165
|
+
sessionId: state.sessionId, finalMessage: state.finalMessage, exitCode: code, ...(state.denials?.length ? { denials: state.denials } : {}),
|
|
166
|
+
// Stopped at its start report, before its first request to the model: the prompt did no work.
|
|
167
|
+
...(refused ? { delivered: false } : {}),
|
|
168
|
+
...(warnings.length ? { warnings } : {}), ...(state.speedWarnings?.length ? { speedWarnings: state.speedWarnings } : {}),
|
|
169
|
+
...(survivors.length ? { survivors } : {}), ...(settled || pid <= 0 ? {} : { unseenMs }),
|
|
170
|
+
};
|
|
171
|
+
if (spawnError)
|
|
172
|
+
return resolveDone({ ...base, status: "failed", error: spawnError });
|
|
173
|
+
if (state.refuse)
|
|
174
|
+
return resolveDone({ ...base, status: "failed", error: state.refuse });
|
|
175
|
+
if (state.stop)
|
|
176
|
+
return resolveDone({ ...base, status: "failed", error: state.stop });
|
|
177
|
+
if (state.refusal)
|
|
178
|
+
return resolveDone({ ...base, status: "refused", refusal: state.refusal, error: refusalError(state.refusal) });
|
|
179
|
+
if (cancelled)
|
|
180
|
+
return resolveDone({ ...base, status: "interrupted", error: "cancelled" });
|
|
181
|
+
if (state.failed)
|
|
182
|
+
return resolveDone({ ...base, status: "failed", error: state.failed });
|
|
183
|
+
if (state.completed)
|
|
184
|
+
return resolveDone({ ...base, status: "ok" });
|
|
185
|
+
// The stream ended without a terminal event: the agent was killed or crashed.
|
|
186
|
+
resolveDone({ ...base, status: "failed", error: `agent exited (code ${code}) without finishing its turn. ${stderrTail.text().trim().split("\n").slice(-3).join(" ")}`.trim() });
|
|
187
|
+
})();
|
|
188
|
+
child.on("exit", (code) => void settle(code));
|
|
189
|
+
const signalGroup = (sig) => {
|
|
190
|
+
if (groupRefused)
|
|
191
|
+
return false;
|
|
192
|
+
try {
|
|
193
|
+
sendGroupSignal(pid, sig);
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
if (isGroupSignalRefusal(err)) {
|
|
197
|
+
groupRefused = true;
|
|
198
|
+
cleanupRefusal = `Agent cleanup refused for group ${pid}: ${err.message}`;
|
|
199
|
+
void settle(null);
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
// Already gone.
|
|
203
|
+
}
|
|
204
|
+
return true;
|
|
205
|
+
};
|
|
206
|
+
const cancel = async () => {
|
|
207
|
+
if (cancelled || pid <= 0) {
|
|
208
|
+
await done;
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
cancelled = true;
|
|
212
|
+
// Before anything is signalled: once the agent has exited, what it started can no longer be traced to it.
|
|
213
|
+
settled = watch.look() || settled;
|
|
214
|
+
// SIGINT first: it is the request to stop cleanly, and `codex exec` only cleans up its tool processes on it.
|
|
215
|
+
if (!signalGroup("SIGINT")) {
|
|
216
|
+
await done;
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const timer = setTimeout(() => {
|
|
220
|
+
watch.look();
|
|
221
|
+
if (signalGroup("SIGKILL"))
|
|
222
|
+
killProcs(watch.procs());
|
|
223
|
+
}, spec.config.cancel_grace_ms);
|
|
224
|
+
await done;
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
if (signalGroup("SIGKILL"))
|
|
227
|
+
killProcs(watch.procs());
|
|
228
|
+
};
|
|
229
|
+
return { pid, pgid: pid, startedAt: procStart(pid), done, cancel };
|
|
230
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { targetDef } from "../targets/index.js";
|
|
2
|
+
/** A version as a harness reports it, its whole identity: a pre-release (0.64.0-preview.0, a nightly) or build part included. */
|
|
3
|
+
const FULL_VERSION = /\b\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?/;
|
|
4
|
+
/** The whole version in a harness's version text (`--version`, or ACP's agentInfo.version), or null. */
|
|
5
|
+
export const fullVersionOf = (text) => (text ? (FULL_VERSION.exec(text)?.[0] ?? null) : null);
|
|
6
|
+
/**
|
|
7
|
+
* Whether relay's tools through `def`'s tool discovery were verified live on `version`, matched
|
|
8
|
+
* whole: a pre-release or build of a verified version is not it. Informational: an unverified
|
|
9
|
+
* version still gets the tools, and each launch checks that discovery ran.
|
|
10
|
+
*/
|
|
11
|
+
export function discoveryVerified(def, version) {
|
|
12
|
+
return Boolean(version && def.toolDiscovery?.versions.includes(version));
|
|
13
|
+
}
|
|
14
|
+
/** The name a launched agent of `target` calls one of relay's tools by: with the harness's discovery prefix, where it has one. */
|
|
15
|
+
export const relayToolName = (target, tool) => `${targetDef(target).toolDiscovery?.prefix ?? ""}${tool}`;
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { networkOn, RELAY_CLI, relayHome, worktreesHome } from "../core/config.js";
|
|
4
|
+
import { relayProcs } from "../core/db.js";
|
|
5
|
+
import { watchProcess as watchProcs } from "../core/procs.js";
|
|
6
|
+
import { checkWriteGrant } from "../confine/seatbelt.js";
|
|
7
|
+
import { ensurePrivateRoot, privateStateRoot } from "../confine/private-root.js";
|
|
8
|
+
import { clipped, oneLine } from "../core/shown.js";
|
|
9
|
+
import { redactOwnReview } from "../core/redact.js";
|
|
10
|
+
import { redact, redactor } from "../core/secrets.js";
|
|
11
|
+
import { logMaxBytes, remedy, rotateLog } from "../core/storage.js";
|
|
12
|
+
import { environmentSocketFor, workerEnvironment } from "../core/env-broker.js";
|
|
13
|
+
/**
|
|
14
|
+
* Opens the agent's log for appending. A failed write never takes the worker down, but it is not
|
|
15
|
+
* swallowed either: `warnings()` gives what the turn's result must say about it (the first failure).
|
|
16
|
+
* What is written goes to disk a whole line at a time, each line with a review's own_review
|
|
17
|
+
* arguments withheld (core/redact.ts) and the secrets relay knows the shape of cut out
|
|
18
|
+
* (core/secrets.ts: by value, those of relay's environment and of `env`, the environment the agent
|
|
19
|
+
* is launched with, which a backend passes when it holds more than relay's own). A line is held
|
|
20
|
+
* until it ends, however long, since a chunk may stop halfway through either. Past `maxBytes` (by
|
|
21
|
+
* default the process's log_max_mb, core/storage.ts) the log is rotated before the line that would
|
|
22
|
+
* take it past: moved to `<file>.1`, replacing an earlier one, and begun again, so that the newest
|
|
23
|
+
* output is kept. A single line longer than `maxBytes` is still written whole, so a file can be
|
|
24
|
+
* longer than that by that line.
|
|
25
|
+
*/
|
|
26
|
+
export function openAgentLog(file, o = {}) {
|
|
27
|
+
const max = o.maxBytes !== undefined ? o.maxBytes : logMaxBytes();
|
|
28
|
+
const cut = redactor(process.env, o.env);
|
|
29
|
+
const clean = (line) => cut(redactOwnReview(line, true));
|
|
30
|
+
/** The first write that failed: what it said, and what a person can do about it (storage.ts remedy). */
|
|
31
|
+
let failed = null;
|
|
32
|
+
const fail = (err) => {
|
|
33
|
+
failed ??= { message: err.message, hint: remedy(err) };
|
|
34
|
+
};
|
|
35
|
+
let unrotated = null;
|
|
36
|
+
let size = 0;
|
|
37
|
+
// Written synchronously: a rotation then happens between two writes, never with one in flight.
|
|
38
|
+
const open = () => {
|
|
39
|
+
try {
|
|
40
|
+
return fs.openSync(file, "a");
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
fail(err);
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
try {
|
|
48
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
49
|
+
size = fs.statSync(file, { throwIfNoEntry: false })?.size ?? 0;
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
fail(err);
|
|
53
|
+
}
|
|
54
|
+
let fd = open();
|
|
55
|
+
const out = (text) => {
|
|
56
|
+
if (!text || fd === null)
|
|
57
|
+
return;
|
|
58
|
+
const buf = Buffer.from(text);
|
|
59
|
+
if (max !== null && unrotated === null && size > 0 && size + buf.length > max) {
|
|
60
|
+
// Nothing here throws (rotateLog says what went wrong): this runs in a backend's stream
|
|
61
|
+
// handlers, where a throw would take the worker down mid-turn.
|
|
62
|
+
try {
|
|
63
|
+
fs.closeSync(fd);
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
fail(err);
|
|
67
|
+
}
|
|
68
|
+
fd = null;
|
|
69
|
+
unrotated = rotateLog(file, 0);
|
|
70
|
+
fd = open();
|
|
71
|
+
if (fd === null)
|
|
72
|
+
return;
|
|
73
|
+
try {
|
|
74
|
+
size = fs.fstatSync(fd).size;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
size = 0;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
for (let off = 0; off < buf.length;)
|
|
82
|
+
off += fs.writeSync(fd, buf, off);
|
|
83
|
+
size += buf.length;
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
fail(err);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* The end of the text written so far that is not yet a whole line, as the chunks it came in: a
|
|
91
|
+
* line break is looked for only in each new chunk, so that a long line arriving in many chunks is
|
|
92
|
+
* held in time linear in its length rather than scanned again at every chunk.
|
|
93
|
+
*/
|
|
94
|
+
let held = [];
|
|
95
|
+
let ended = false;
|
|
96
|
+
const log = {
|
|
97
|
+
write(text) {
|
|
98
|
+
if (ended)
|
|
99
|
+
return false;
|
|
100
|
+
const nl = text.lastIndexOf("\n");
|
|
101
|
+
if (nl < 0) {
|
|
102
|
+
if (text)
|
|
103
|
+
held.push(text);
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
const whole = held.join("") + text.slice(0, nl);
|
|
107
|
+
held = nl + 1 < text.length ? [text.slice(nl + 1)] : [];
|
|
108
|
+
// One line at a time, so that the log is rotated between two lines of a chunk too.
|
|
109
|
+
for (const l of whole.split("\n"))
|
|
110
|
+
out(`${clean(l)}\n`);
|
|
111
|
+
return true;
|
|
112
|
+
},
|
|
113
|
+
end(callback) {
|
|
114
|
+
if (!ended) {
|
|
115
|
+
ended = true;
|
|
116
|
+
const partial = held.join("");
|
|
117
|
+
if (partial)
|
|
118
|
+
out(clean(partial));
|
|
119
|
+
held = [];
|
|
120
|
+
try {
|
|
121
|
+
if (fd !== null)
|
|
122
|
+
fs.closeSync(fd);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// Nothing more is written to it either way.
|
|
126
|
+
}
|
|
127
|
+
fd = null;
|
|
128
|
+
}
|
|
129
|
+
if (callback)
|
|
130
|
+
queueMicrotask(callback);
|
|
131
|
+
},
|
|
132
|
+
get writableEnded() {
|
|
133
|
+
return ended;
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
return {
|
|
137
|
+
log,
|
|
138
|
+
warnings: () => [
|
|
139
|
+
...(failed ? [`relay could not write the agent's log ${file} (${failed.message}), so the log may be missing or incomplete, though the turn itself went on${failed.hint ? `: ${failed.hint}` : ""}`] : []),
|
|
140
|
+
...(unrotated ? [`relay could not rotate the agent's log ${file} at log_max_mb (${unrotated}), so it grew past that`] : []),
|
|
141
|
+
],
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
export const pathAccessOf = (ask) => {
|
|
145
|
+
const a = (ask.detail && typeof ask.detail === "object" ? ask.detail : {});
|
|
146
|
+
return a.path_access === "read" || a.path_access === "write" ? a.path_access : "read or write";
|
|
147
|
+
};
|
|
148
|
+
/**
|
|
149
|
+
* Whether a read-only turn may ask for this at all: to reach the web, to run a command, consent to
|
|
150
|
+
* extensions, a call of an extension's tool, environment values, or past a harness's own check of
|
|
151
|
+
* a path it would only read. Never to change files, nor past a check for a path it could write.
|
|
152
|
+
*/
|
|
153
|
+
export function askableReadOnly(ask) {
|
|
154
|
+
if (ask.kind === "path")
|
|
155
|
+
return pathAccessOf(ask) === "read";
|
|
156
|
+
return ["web", "command", "extensions", "mcp", "env", "escalation"].includes(ask.kind);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* What makes two approval requests the same request, for an approval for the rest of the job: the
|
|
160
|
+
* kind, the command (its argv where the agent gave one), the directory it runs in, and the files,
|
|
161
|
+
* each path resolved against that directory. `cwd` is the agent's own directory, for a request
|
|
162
|
+
* that names none.
|
|
163
|
+
*/
|
|
164
|
+
export function approvalKey(ask, cwd) {
|
|
165
|
+
const d = (ask.detail && typeof ask.detail === "object" ? ask.detail : {});
|
|
166
|
+
const dir = path.resolve(cwd, typeof d.cwd === "string" ? d.cwd : ".");
|
|
167
|
+
const paths = [...new Set((ask.paths ?? []).map((p) => path.resolve(dir, p)))].sort();
|
|
168
|
+
return JSON.stringify({ kind: ask.kind, command: Array.isArray(d.argv) ? d.argv : ask.summary, cwd: dir, paths });
|
|
169
|
+
}
|
|
170
|
+
/** Picks the numbers out of a usage object, by the names the harnesses use. Null when there are none. */
|
|
171
|
+
export function usageFrom(raw, extra = {}) {
|
|
172
|
+
if (!raw || typeof raw !== "object")
|
|
173
|
+
return null;
|
|
174
|
+
const r = raw;
|
|
175
|
+
const num = (...keys) => keys.map((k) => r[k]).find((v) => typeof v === "number" && Number.isFinite(v));
|
|
176
|
+
const u = {
|
|
177
|
+
input_tokens: num("input_tokens", "inputTokens"),
|
|
178
|
+
cached_input_tokens: num("cached_input_tokens", "cachedInputTokens", "cache_read_input_tokens"),
|
|
179
|
+
cache_creation_input_tokens: num("cache_creation_input_tokens"),
|
|
180
|
+
output_tokens: num("output_tokens", "outputTokens"),
|
|
181
|
+
reasoning_output_tokens: num("reasoning_output_tokens", "reasoningOutputTokens"),
|
|
182
|
+
total_tokens: num("total_tokens", "totalTokens"),
|
|
183
|
+
...extra,
|
|
184
|
+
};
|
|
185
|
+
for (const k of Object.keys(u))
|
|
186
|
+
if (u[k] === undefined)
|
|
187
|
+
delete u[k];
|
|
188
|
+
return Object.keys(u).some((k) => k !== "cumulative") ? u : null;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* What a tool call is doing, in a few words, for progress lines and the commands an agent was
|
|
192
|
+
* refused: the command, the file, the query. Takes Claude's tool names and inputs and Codex's item
|
|
193
|
+
* types (app server and exec). Every part the agent chose is cut of the secrets relay knows the
|
|
194
|
+
* shape of (core/secrets.ts) as the agent gave it, before it is clipped or escaped, which could cut
|
|
195
|
+
* a secret in two or turn the line break before it into text; then put on one line and escaped
|
|
196
|
+
* (oneLine: what an activity says reaches a person's terminal in relay tree and progress lines,
|
|
197
|
+
* review C12).
|
|
198
|
+
*/
|
|
199
|
+
export function activityOf(tool, input = {}) {
|
|
200
|
+
const said = (v) => redact(String(v ?? ""));
|
|
201
|
+
const line = (v, max) => oneLine(said(v), max);
|
|
202
|
+
const file = input.file_path ?? input.path ?? input.notebook_path;
|
|
203
|
+
switch (tool) {
|
|
204
|
+
case "Bash":
|
|
205
|
+
case "commandExecution":
|
|
206
|
+
case "command_execution":
|
|
207
|
+
return input.command !== undefined ? `$ ${clipped(said(Array.isArray(input.command) ? input.command.join(" ") : input.command), 160)}` : "running a command";
|
|
208
|
+
case "fileChange":
|
|
209
|
+
case "file_change": {
|
|
210
|
+
const paths = (input.changes ?? []).map((c) => c?.path).filter((x) => typeof x === "string");
|
|
211
|
+
return `editing ${paths.length ? line(paths.join(", "), 160) : "files"}`;
|
|
212
|
+
}
|
|
213
|
+
case "mcpToolCall":
|
|
214
|
+
case "mcp_tool_call":
|
|
215
|
+
return `tool ${line(input.server, 160)}.${line(input.tool, 160)}`;
|
|
216
|
+
case "webSearch":
|
|
217
|
+
case "web_search":
|
|
218
|
+
case "WebSearch":
|
|
219
|
+
return `web search: ${line(input.query, 160)}`;
|
|
220
|
+
case "WebFetch":
|
|
221
|
+
return `fetching ${line(input.url, 160)}`;
|
|
222
|
+
case "Grep":
|
|
223
|
+
case "Glob":
|
|
224
|
+
return `${tool.toLowerCase()} ${line(input.pattern, 160)}`;
|
|
225
|
+
case "reasoning":
|
|
226
|
+
case "agentMessage":
|
|
227
|
+
case "agent_message":
|
|
228
|
+
case "userMessage":
|
|
229
|
+
case "user_message":
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
if (typeof file === "string")
|
|
233
|
+
return `${line(tool, 60)} ${line(file, 160)}`;
|
|
234
|
+
return /^[A-Za-z][\w.-]*$/.test(tool) ? tool : null;
|
|
235
|
+
}
|
|
236
|
+
/** Command line for the child's relay MCP server, with its context passed as an argument. */
|
|
237
|
+
export function relayServerCommand(ctx) {
|
|
238
|
+
const env = {
|
|
239
|
+
...workerEnvironment(ctx.runId),
|
|
240
|
+
RELAY_ENV_SOCKET: environmentSocketFor(ctx.runId),
|
|
241
|
+
RELAY_RUN_ID: ctx.runId, RELAY_NODE_ID: ctx.nodeId, RELAY_DEPTH: String(ctx.depth), RELAY_INJECTED: "1",
|
|
242
|
+
RELAY_HOME: relayHome(), RELAY_WORKTREES: worktreesHome(), TMPDIR: ensurePrivateRoot(privateStateRoot()),
|
|
243
|
+
};
|
|
244
|
+
return {
|
|
245
|
+
// Native MCP launchers normally inherit the harness's entire environment. Start this trusted
|
|
246
|
+
// server with controls only, so even this turn's disclosed values cannot reach descendants.
|
|
247
|
+
command: "/usr/bin/env",
|
|
248
|
+
args: ["-i", ...Object.entries(env).filter((e) => e[1] !== undefined).map(([k, v]) => `${k}=${v}`), process.execPath, RELAY_CLI, "mcp", "--context", ctx.contextFile],
|
|
249
|
+
env: {},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* What a turn's spec makes of its policy, derived in one place: full access (allow_dangerous, for
|
|
254
|
+
* write turns only), the network (a grant or child_network, networkOn), the write paths granted
|
|
255
|
+
* beyond the worktree, and whether what would prompt goes to relay (escalation, where the agent has
|
|
256
|
+
* relay's server, and never with full access).
|
|
257
|
+
*/
|
|
258
|
+
export function turnPolicy(spec) {
|
|
259
|
+
checkWriteGrant(spec.grant?.write_paths ?? [], spec.grant?.write_path_pins);
|
|
260
|
+
const dangerous = spec.config.allow_dangerous && spec.access === "write";
|
|
261
|
+
return { dangerous, network: networkOn(spec.config, spec.grant), writePaths: spec.grant?.write_paths ?? [], ask: Boolean(spec.escalate && spec.relay) && !dangerous };
|
|
262
|
+
}
|
|
263
|
+
/** watchProcess (core/procs.ts), sparing relay's own registered processes, read afresh at each look (review C5). */
|
|
264
|
+
export const watchProcess = (pid) => watchProcs(pid, relayProcs);
|