@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
package/test/helpers.ts
ADDED
|
@@ -0,0 +1,740 @@
|
|
|
1
|
+
import { HOME_VARS } from "./process-home.ts";
|
|
2
|
+
import { removeTestNativeTempAlias } from "./native-temp-alias.ts";
|
|
3
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import net from "node:net";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { DatabaseSync } from "node:sqlite";
|
|
9
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
10
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
11
|
+
import { CancelledNotificationSchema, ElicitRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
12
|
+
import { canonical } from "../dist/core/config.js";
|
|
13
|
+
import { neverProfileInputs, type NeverPolicy } from "../dist/core/never-policy.js";
|
|
14
|
+
import { sendGroupSignal } from "../dist/core/procs.js";
|
|
15
|
+
import { TARGET_IDS, TARGETS, type Target } from "../dist/targets/index.js";
|
|
16
|
+
import { hostVar } from "./host-env.ts";
|
|
17
|
+
export { hostVar };
|
|
18
|
+
|
|
19
|
+
const ROOT = path.resolve(import.meta.dirname, "..");
|
|
20
|
+
export const CLI = path.join(ROOT, "dist", "cli.js");
|
|
21
|
+
export const UNAVAILABLE_REPLY = {
|
|
22
|
+
error: "Item unavailable.",
|
|
23
|
+
recovery: "If this is your own work from before a restart or reconnect, ask the person to adopt it: adopt with this id (they confirm), or relay adopt <id> --to <fingerprint> in a terminal.",
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Kills a process group a test started, through relay's guard (sendGroupSignal), so a stale or wrong number never reaches the test runner's own group or the shell's. */
|
|
27
|
+
export function killGroup(pgid: number | null | undefined): void {
|
|
28
|
+
try { sendGroupSignal(pgid ?? 0, "SIGKILL"); } catch { /* gone, or refused and reported */ }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The reply to any call carrying a session token relay did not issue under this relay home's key. */
|
|
32
|
+
export const SESSION_UNAVAILABLE_REPLY = {
|
|
33
|
+
error: "Session unavailable.",
|
|
34
|
+
recovery: "Pass session_token exactly as relay gave it to this conversation (new_session.token). If this conversation has none, call without session_token to get one: a new token has none of the earlier work. " +
|
|
35
|
+
"To move that work to it, the person quits and reopens the app, then runs relay adopt from a terminal (relay cancel there stops it instead).",
|
|
36
|
+
};
|
|
37
|
+
/** The Claude desktop app's shared entry, as its chat process connects (docs/d9-isolation-plan.md). */
|
|
38
|
+
export const DESKTOP_CHATS = { args: ["--desktop", "--host", "claude"], clientInfo: { name: "claude.ai", version: "2.42304.0" }, cwd: "/" };
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* One conversation on a shared relay connection: the token relay issued it on a plain status, its
|
|
42
|
+
* fingerprint, and calls that carry the token. Several can share one connection, as desktop chats do.
|
|
43
|
+
*/
|
|
44
|
+
export async function conversationOn(shared: { call: (tool: string, args?: Record<string, unknown>, opts?: CallOpts) => Promise<Rec> }) {
|
|
45
|
+
const fresh = await shared.call("status");
|
|
46
|
+
const token = fresh.new_session?.token as string | undefined;
|
|
47
|
+
if (!token) throw new Error(`no session token was issued: ${JSON.stringify(fresh)}`);
|
|
48
|
+
return {
|
|
49
|
+
token, fingerprint: fresh.session.fingerprint as string,
|
|
50
|
+
call: (tool: string, args: Record<string, unknown> = {}, opts: CallOpts = {}) => shared.call(tool, { ...args, session_token: token }, opts),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const stubBin = (target: string) => path.join(ROOT, "test", "stubs", `stub-${target}`);
|
|
55
|
+
/** The targets in relay's registry that the stub agent emulates, in registry order. */
|
|
56
|
+
export const STUB_TARGETS: readonly Target[] = TARGET_IDS.filter((t) => fs.existsSync(stubBin(t)));
|
|
57
|
+
/** Declares the same tests once for each stubbed target. */
|
|
58
|
+
export const forEachTarget = (fn: (target: Target) => void) => STUB_TARGETS.forEach((t) => fn(t));
|
|
59
|
+
|
|
60
|
+
const vendorOf = (t: string) => TARGETS.find((d) => d.id === t)?.vendor;
|
|
61
|
+
/** The host a root session reaching `target` runs in: the first stubbed target of another vendor. */
|
|
62
|
+
export const hostFor = (target: string): Target => STUB_TARGETS.find((t) => vendorOf(t) !== vendorOf(target))!;
|
|
63
|
+
|
|
64
|
+
export type Rule = { target?: string; match?: string; turn?: number; steps: Record<string, unknown>[] };
|
|
65
|
+
export type Rec = Record<string, any>;
|
|
66
|
+
|
|
67
|
+
export interface Harness {
|
|
68
|
+
home: string;
|
|
69
|
+
repo: string;
|
|
70
|
+
env: Record<string, string>;
|
|
71
|
+
call(tool: string, args?: Record<string, unknown>, opts?: CallOpts): Promise<Rec>;
|
|
72
|
+
/**
|
|
73
|
+
* Another relay MCP instance. With --context in args it is a launched agent's; with --host, a
|
|
74
|
+
* root session in that host; with host: null, a root session whose host relay cannot tell.
|
|
75
|
+
* Otherwise it is a root session whose host is chosen per call, as call's is (see harness).
|
|
76
|
+
*/
|
|
77
|
+
instance(opts: InstanceOpts): Promise<{ call: Harness["call"]; tools(): Promise<string[]>; toolDefinitions(): Promise<Rec[]>; close(): Promise<void> }>;
|
|
78
|
+
log(): Rec[];
|
|
79
|
+
starts(): Rec[];
|
|
80
|
+
ends(): Rec[];
|
|
81
|
+
/** Broker address from this node's actual native relay launcher, as a real child receives it. */
|
|
82
|
+
environmentSocket(nodeId: string): string | undefined;
|
|
83
|
+
sql(query: string, ...params: unknown[]): Rec[];
|
|
84
|
+
/**
|
|
85
|
+
* What relay would hand a launched agent's relay server for a turn of this node: a context file
|
|
86
|
+
* carrying the turn's policy, the matching env, and a turn that is running in the registry.
|
|
87
|
+
* It waits first for the node's own worker to be gone: a worker still winding down its last turn
|
|
88
|
+
* would close this one too.
|
|
89
|
+
*/
|
|
90
|
+
childOf(nodeId: string, policy?: { access?: "read" | "write"; may_delegate?: boolean; may_ask?: boolean; running?: boolean }): Promise<{ args: string[]; env: Record<string, string>; turnId: number }>;
|
|
91
|
+
/** Runs the relay CLI against this harness's control directory, with a private TMPDIR unless the test gave one (see harness). */
|
|
92
|
+
cli(...args: string[]): string;
|
|
93
|
+
/** As cli, with extra environment (a worker run by hand needs its root's RELAY_ENV_SOCKET, as relay gives one). */
|
|
94
|
+
cliEnv(extra: Record<string, string>, ...args: string[]): string;
|
|
95
|
+
/** Sets a mark a stub step waits on (`awaitMark`), instead of the stub sleeping and the test racing it. */
|
|
96
|
+
mark(name: string): void;
|
|
97
|
+
/** True once a stub step (`mark`) or the test has set this mark. */
|
|
98
|
+
marked(name: string): boolean;
|
|
99
|
+
/**
|
|
100
|
+
* A fake Claude Code inbox socket: pass its env to an instance, and read what relay posted, one
|
|
101
|
+
* entry per connection (the auth token sent, and the user message's text).
|
|
102
|
+
*/
|
|
103
|
+
inbox(): Promise<{ env: Record<string, string>; posts(): { token?: string; text: string }[] }>;
|
|
104
|
+
close(): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface InstanceOpts {
|
|
108
|
+
args?: string[]; env?: Record<string, string>; cwd?: string; host?: null;
|
|
109
|
+
/**
|
|
110
|
+
* Makes the client a host that can put relay's questions to the user, answering with this. `signal` is aborted if relay withdraws
|
|
111
|
+
* the question; `params` is the whole request (its requestedSchema, say).
|
|
112
|
+
*/
|
|
113
|
+
elicit?: (message: string, signal: AbortSignal, params: Rec) => Rec | Promise<Rec>;
|
|
114
|
+
/** The client's name and version in initialize. Default test 0, a host relay does not recognise. */
|
|
115
|
+
clientInfo?: { name: string; version: string };
|
|
116
|
+
/** Desktop MCP UI marker observed in the Codex app (answers.md XA-a). */
|
|
117
|
+
desktopUi?: boolean;
|
|
118
|
+
/** The relay CLI the server runs, and with it the workers it starts. Default this checkout's dist/cli.js. */
|
|
119
|
+
cli?: string;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** What an interactive Claude Code session in a terminal looks like to relay's server: its client info and environment. */
|
|
123
|
+
export const INTERACTIVE_CLAUDE = { clientInfo: { name: "claude-code", version: "2.1.286" }, env: { CLAUDE_CODE_ENTRYPOINT: "cli" } };
|
|
124
|
+
|
|
125
|
+
/** Per call: progress notifications as they arrive, and a signal that cancels the call. */
|
|
126
|
+
/** meta is sent as the request's _meta, as a host attaches it. */
|
|
127
|
+
export interface CallOpts { onprogress?: (p: { progress: number; message?: string }) => void; signal?: AbortSignal; meta?: Record<string, unknown> }
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The home folder of the user running the tests, from the user database rather than HOME, which a
|
|
131
|
+
* test may already have pointed somewhere else. Tests never probe, write or delete anything in it.
|
|
132
|
+
*/
|
|
133
|
+
export const REAL_HOME = fs.realpathSync(os.userInfo().homedir);
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* What relay adds to every Claude turn that is not dangerous, so that it cannot read the API key
|
|
137
|
+
* relay hands a key-only target (backends/claude.ts; core/api-keys.ts keyPathsToDeny), nor relay's
|
|
138
|
+
* sockets directory, where a confined turn's broker keeps its bridge secret's file (confine/sockets.ts):
|
|
139
|
+
* with no local config and no key saved, the default key directory under `home`, then
|
|
140
|
+
* `<home>/.relay-t/s`, in the sandbox's denyRead and as Read deny rules for its file tools, after
|
|
141
|
+
* relay's other deny rules.
|
|
142
|
+
*/
|
|
143
|
+
export const claudeReadDeny = (home: string): { paths: string[]; rules: string[] } => {
|
|
144
|
+
const keys = path.join(home, ".config", "relay-keys");
|
|
145
|
+
const sockets = path.join(fs.realpathSync(home), ".relay-t", "s");
|
|
146
|
+
const codex = path.join(home, ".local", "share", "relay-codex-home");
|
|
147
|
+
return { paths: [keys, sockets, codex], rules: [keys, sockets, codex].flatMap((p) => [`Read(/${p})`, `Read(/${p}/**)`]) };
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* The never floor relay adds last to every Claude turn (core/never-coverage.ts: Claude always gets
|
|
151
|
+
* the floor; backends/claude.ts applyClaudeNeverPolicy), from the run's durable floor
|
|
152
|
+
* (runs.config_json params_json.never_floor). `read` and `write` are the names the sandbox's denyRead
|
|
153
|
+
* and denyWrite gain (each list keeps a name only once); `rules`, the deny rules for Claude's own
|
|
154
|
+
* tools: Read rules for each name of an all-access entry, Edit rules for those and then for the
|
|
155
|
+
* write-only entries, and with never.hosts WebSearch and WebFetch. `run` picks the run; without it
|
|
156
|
+
* every run in the registry must hold the same floor.
|
|
157
|
+
*/
|
|
158
|
+
export const claudeFloor = (h: { sql: (query: string, ...params: unknown[]) => Rec[] }, run?: string): { read: string[]; write: string[]; rules: string[] } => {
|
|
159
|
+
const rows = h.sql(`SELECT json_extract(config_json, '$.params_json.never_floor.policy') AS policy FROM runs${run ? " WHERE id = ?" : ""}`, ...(run ? [run] : []));
|
|
160
|
+
const floorOf = (policy: NeverPolicy) => {
|
|
161
|
+
const floor = neverProfileInputs(policy);
|
|
162
|
+
const write = [...floor.denyAll, ...floor.denyWrite];
|
|
163
|
+
const rule = (tool: string) => (p: string) => {
|
|
164
|
+
const escaped = p.replace(/([*?[\]{}!\\])/g, "\\$1");
|
|
165
|
+
return [`${tool}(/${escaped})`, `${tool}(/${escaped}/**)`];
|
|
166
|
+
};
|
|
167
|
+
return { read: floor.denyAll, write, rules: [...floor.denyAll.flatMap(rule("Read")), ...write.flatMap(rule("Edit")), ...(policy.hosts.length ? ["WebSearch", "WebFetch"] : [])] };
|
|
168
|
+
};
|
|
169
|
+
const floors = [...new Set(rows.filter((r) => r.policy).map((r) => JSON.stringify(floorOf(JSON.parse(r.policy as string)))))];
|
|
170
|
+
if (floors.length !== 1) throw new Error(`expected one never floor across ${run ?? "the registry's runs"}, found ${floors.length}`);
|
|
171
|
+
return JSON.parse(floors[0]);
|
|
172
|
+
};
|
|
173
|
+
/** The floor's deny rules for Claude's own tools (claudeFloor). */
|
|
174
|
+
export const claudeFloorDeny = (h: { sql: (query: string, ...params: unknown[]) => Rec[] }, run?: string): string[] => claudeFloor(h, run).rules;
|
|
175
|
+
/** Where installed programs live, the Node running the tests first. Tests never probe them either. */
|
|
176
|
+
const INSTALLED_DIRS = [...new Set([
|
|
177
|
+
path.dirname(process.execPath), path.dirname(fs.realpathSync(process.execPath)),
|
|
178
|
+
"/opt/homebrew", "/usr", "/bin", "/sbin", "/Applications", "/System", "/Library", "/nix",
|
|
179
|
+
...(process.env.PATH ?? "").split(path.delimiter),
|
|
180
|
+
].filter((d) => path.isAbsolute(d) && d !== path.sep).map((d) => canonical(d)))];
|
|
181
|
+
const under = (p: string, root: string) => p === root || p.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Returns `p` if it is a scratch path, and fails the test if it resolves (through any symlinks)
|
|
185
|
+
* under the real home folder or an installed program's directory. Every path a test probes,
|
|
186
|
+
* writes, deletes or hands out as HOME goes through this first.
|
|
187
|
+
*/
|
|
188
|
+
export function scratchOnly(p: string, what = "path"): string {
|
|
189
|
+
const c = canonical(p);
|
|
190
|
+
const bin = INSTALLED_DIRS.find((d) => under(c, d));
|
|
191
|
+
if (bin) throw new Error(`test guard: ${what} ${p} resolves under an installed program directory (${bin}); tests use scratch paths only`);
|
|
192
|
+
if (under(c, REAL_HOME)) throw new Error(`test guard: ${what} ${p} resolves under the real home folder (${REAL_HOME}); tests use scratch paths only`);
|
|
193
|
+
return p;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Each nonTempScratch tree's owner, beside it as `<dir>.owner` (the creating process's pid), so a
|
|
198
|
+
* later run can tell a dead run's leftover from a live one's tree. Removed with the tree on exit.
|
|
199
|
+
*/
|
|
200
|
+
const ownerFile = (dir: string) => `${dir}.owner`;
|
|
201
|
+
|
|
202
|
+
/** Whether process `pid` may still exist: only ESRCH proves it gone (EPERM is someone else's). */
|
|
203
|
+
function mayLive(pid: number): boolean {
|
|
204
|
+
try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code !== "ESRCH"; }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Removes nonTempScratch trees under `root` whose run is over: a SIGKILLed run skips the exit
|
|
209
|
+
* handler that removes them. Only `relay-…-XXXXXX` directories (real directories, not links) owned
|
|
210
|
+
* by this user, with an owner file beside them (a regular file of this user's, not a link) naming
|
|
211
|
+
* a process that no longer exists. A tree with no owner file (made before 1.1.3) or whose owner may
|
|
212
|
+
* still live is left alone, as is anything of another user's (a CI account's). Removal errors leave it
|
|
213
|
+
* for the next run. RELAY_TEST_KEEP_SCRATCH=1 turns the start-up sweep off.
|
|
214
|
+
*/
|
|
215
|
+
export function sweepStaleScratch(root: string, o: { uid?: number; alive?: (pid: number) => boolean } = {}): string[] {
|
|
216
|
+
const uid = o.uid ?? process.getuid?.(), alive = o.alive ?? mayLive;
|
|
217
|
+
const removed: string[] = [];
|
|
218
|
+
let names: string[];
|
|
219
|
+
try { names = fs.readdirSync(root); } catch { return removed; }
|
|
220
|
+
for (const name of names) {
|
|
221
|
+
if (!/^relay-[a-z0-9-]+-[A-Za-z0-9]{6}$/.test(name)) continue;
|
|
222
|
+
const dir = path.join(root, name), owner = ownerFile(dir);
|
|
223
|
+
let st: fs.Stats, ost: fs.Stats, pid: number;
|
|
224
|
+
try { st = fs.lstatSync(dir); ost = fs.lstatSync(owner); pid = Number(fs.readFileSync(owner, "utf8").trim()); } catch { continue; }
|
|
225
|
+
if (!st.isDirectory() || !ost.isFile() || uid === undefined || st.uid !== uid || ost.uid !== uid) continue;
|
|
226
|
+
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid || alive(pid)) continue;
|
|
227
|
+
try { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(owner, { force: true }); removed.push(dir); } catch { /* the next run, or by hand */ }
|
|
228
|
+
}
|
|
229
|
+
return removed;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Disposable fixtures for write grants, which production refuses under shared temp. */
|
|
233
|
+
const nonTempTrees = new Set<string>();
|
|
234
|
+
process.on("exit", () => { for (const dir of nonTempTrees) { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(ownerFile(dir), { force: true }); } });
|
|
235
|
+
let staleSwept = false;
|
|
236
|
+
export function nonTempScratch(prefix: string): string {
|
|
237
|
+
if (!staleSwept && process.platform === "darwin" && process.env.RELAY_TEST_KEEP_SCRATCH !== "1") { staleSwept = true; sweepStaleScratch("/Users/Shared"); }
|
|
238
|
+
const dir = scratchOnly(fs.realpathSync(fs.mkdtempSync(path.join(process.platform === "darwin" ? "/Users/Shared" : os.tmpdir(), prefix))));
|
|
239
|
+
fs.writeFileSync(ownerFile(dir), `${process.pid}\n`, { flag: "wx", mode: 0o600 });
|
|
240
|
+
nonTempTrees.add(dir);
|
|
241
|
+
return dir;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The real Codex a test runs for its own sandbox (`codex sandbox`): the absolute path in
|
|
246
|
+
* RELAY_TEST_CODEX, which release gates set to the pinned binary (the qualification and red team
|
|
247
|
+
* take the same variable); otherwise `fallback()`, the test's own lookup. Under
|
|
248
|
+
* RELAY_REQUIRE_REAL_CODEX=1, as at gates, nothing stands in for the named binary: without one,
|
|
249
|
+
* `bin` is null and `required` makes that a failure, never a skip or another Codex (PATH's or
|
|
250
|
+
* Homebrew's, which update by themselves). `why` says what is missing.
|
|
251
|
+
*/
|
|
252
|
+
export function realCodexBin(fallback: () => string | null, env: NodeJS.ProcessEnv = process.env): { bin: string | null; required: boolean; why: string } {
|
|
253
|
+
const required = env.RELAY_REQUIRE_REAL_CODEX === "1";
|
|
254
|
+
const named = env.RELAY_TEST_CODEX;
|
|
255
|
+
if (named) return path.isAbsolute(named) ? { bin: named, required, why: "" } : { bin: null, required, why: `RELAY_TEST_CODEX must be an absolute path, not ${JSON.stringify(named)}` };
|
|
256
|
+
if (required) return { bin: null, required, why: "RELAY_REQUIRE_REAL_CODEX=1, and RELAY_TEST_CODEX names no Codex: at a gate, set it to the pinned binary" };
|
|
257
|
+
return { bin: fallback(), required, why: "no Codex found (RELAY_TEST_CODEX names one; RELAY_REQUIRE_REAL_CODEX=1 makes its absence a failure)" };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** The variables that say where a program keeps its user files: in a test, each must be scratch. */
|
|
261
|
+
/** Returns `env` after checking that none of its home-like variables point at real files (see scratchOnly). */
|
|
262
|
+
export function scratchEnv<T extends Record<string, string | undefined>>(env: T): T {
|
|
263
|
+
for (const k of HOME_VARS) if (env[k]) scratchOnly(env[k]!, k);
|
|
264
|
+
return env;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* The least time `until` gives a condition. A deadline only bounds how long a failing test takes:
|
|
271
|
+
* what a test asserts is what happened, never how fast a loaded machine got there, so no test
|
|
272
|
+
* waits less than this however short the deadline it names.
|
|
273
|
+
*/
|
|
274
|
+
const UNTIL_FLOOR_MS = 60_000;
|
|
275
|
+
|
|
276
|
+
/** Polls `fn` until it is true; fails the test if it is not within max(ms, UNTIL_FLOOR_MS). */
|
|
277
|
+
export async function until(fn: () => boolean | Promise<boolean>, ms = UNTIL_FLOOR_MS, label = "condition"): Promise<void> {
|
|
278
|
+
const end = Date.now() + Math.max(ms, UNTIL_FLOOR_MS);
|
|
279
|
+
while (Date.now() < end) {
|
|
280
|
+
try {
|
|
281
|
+
if (await fn()) return;
|
|
282
|
+
} catch {
|
|
283
|
+
// Not ready yet (for example the registry has not been created).
|
|
284
|
+
}
|
|
285
|
+
await sleep(50);
|
|
286
|
+
}
|
|
287
|
+
throw new Error(`timed out waiting for ${label}`);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Lets stub agents held at an `await` step of that name go on. Tests synchronize with the stubs
|
|
292
|
+
* this way rather than by sleeping: a loaded machine can stretch any sleep past what it was for.
|
|
293
|
+
*/
|
|
294
|
+
export const release = (h: Pick<Harness, "env">, name: string) => fs.writeFileSync(path.join(h.env.STUB_DIR, name), "");
|
|
295
|
+
/** True once a stub agent has passed a `signal` step of that name. */
|
|
296
|
+
export const reached = (h: Pick<Harness, "env">, name: string) => fs.existsSync(path.join(h.env.STUB_DIR, name));
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Waits until relay has read the `checkpoint` of that name from the item's agent, then lets the
|
|
300
|
+
* agent go on. Relay deals with an agent's output a line at a time, each line completely before
|
|
301
|
+
* the next, so by then it has dealt with everything the agent said before the checkpoint, while the
|
|
302
|
+
* agent was still there, held at it.
|
|
303
|
+
*/
|
|
304
|
+
export async function passed(h: Pick<Harness, "env" | "sql">, id: string, name: string): Promise<void> {
|
|
305
|
+
const said = `"checkpoint":${JSON.stringify(name)}`;
|
|
306
|
+
await until(() => {
|
|
307
|
+
const file = h.sql("SELECT log_path FROM nodes WHERE id = ?", id)[0]?.log_path;
|
|
308
|
+
return Boolean(file) && fs.existsSync(file) && fs.readFileSync(file, "utf8").includes(said);
|
|
309
|
+
}, 20000, `relay to read the agent's checkpoint "${name}"`);
|
|
310
|
+
release(h, name);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Steps after which relay has certainly looked at what the agent had started before them (see
|
|
315
|
+
* looked). Relay looks at least once a second while an agent runs. Once it has read the first
|
|
316
|
+
* checkpoint its next look is due within a second; the second checkpoint comes later than that,
|
|
317
|
+
* and relay reads the third only in a later turn of its event loop, which runs due timers first.
|
|
318
|
+
*/
|
|
319
|
+
export const lookSteps = (name: string) => [{ checkpoint: `${name}-1` }, { sleep: 1100 }, { checkpoint: `${name}-2` }, { checkpoint: `${name}-3` }];
|
|
320
|
+
/** Lets a stub agent through its lookSteps, returning once relay has looked at it while it was held there. */
|
|
321
|
+
export async function looked(h: Pick<Harness, "env" | "sql">, id: string, name: string): Promise<void> {
|
|
322
|
+
for (const n of [1, 2, 3]) await passed(h, id, `${name}-${n}`);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export const alive = (pid: number) => {
|
|
326
|
+
try {
|
|
327
|
+
process.kill(pid, 0);
|
|
328
|
+
return true;
|
|
329
|
+
} catch {
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
/** Exercise the real CLI's interactive boundary using a child PTY, never a CLI bypass flag. */
|
|
335
|
+
export function terminalAdoption(h: Pick<Harness, "repo" | "env" | "sql">, id: string, to: string, answer?: string) {
|
|
336
|
+
const run = id.startsWith("run_") ? id : h.sql("SELECT run_id FROM nodes WHERE id = ?", id)[0].run_id as string;
|
|
337
|
+
// macOS script(1) rejects Node's socketpair stdin and sends EOF ahead of confirmation
|
|
338
|
+
// with file stdin. A PTY driver waits for the actual prompt before typing the answer.
|
|
339
|
+
const driver = `import os, pty, select, signal, sys, time
|
|
340
|
+
pid, fd = pty.fork()
|
|
341
|
+
if pid == 0:
|
|
342
|
+
os.execv(sys.argv[1], sys.argv[1:-1])
|
|
343
|
+
output = b""
|
|
344
|
+
sent = False
|
|
345
|
+
deadline = time.monotonic() + 12
|
|
346
|
+
try:
|
|
347
|
+
while time.monotonic() < deadline:
|
|
348
|
+
if not select.select([fd], [], [], 0.1)[0]:
|
|
349
|
+
continue
|
|
350
|
+
try:
|
|
351
|
+
chunk = os.read(fd, 65536)
|
|
352
|
+
except OSError:
|
|
353
|
+
break
|
|
354
|
+
if not chunk:
|
|
355
|
+
break
|
|
356
|
+
sys.stdout.buffer.write(chunk)
|
|
357
|
+
sys.stdout.buffer.flush()
|
|
358
|
+
output += chunk
|
|
359
|
+
if not sent and b"Type exactly " in output:
|
|
360
|
+
os.write(fd, (sys.argv[-1] + "\\n").encode())
|
|
361
|
+
sent = True
|
|
362
|
+
else:
|
|
363
|
+
os.kill(pid, signal.SIGKILL)
|
|
364
|
+
finally:
|
|
365
|
+
os.close(fd)
|
|
366
|
+
_, status = os.waitpid(pid, 0)
|
|
367
|
+
sys.exit(os.waitstatus_to_exitcode(status))
|
|
368
|
+
`;
|
|
369
|
+
return spawnSync("python3", ["-c", driver, process.execPath, CLI, "adopt", id, "--to", to, answer ?? `adopt ${run} into ${to}`], {
|
|
370
|
+
cwd: h.repo, env: h.env, encoding: "utf8", timeout: 15000,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Allow a request through the real `relay approve`, over a child PTY: wait for the one-time code
|
|
376
|
+
* relay prints, type it back (or `answer`, to exercise a refusal), as a person at a terminal does.
|
|
377
|
+
* Never a bypass flag. Returns the final JSON object relay printed and the exit code.
|
|
378
|
+
*/
|
|
379
|
+
export function terminalApprove(
|
|
380
|
+
h: Pick<Harness, "repo" | "env">,
|
|
381
|
+
id: string,
|
|
382
|
+
opts: { job?: boolean; answer?: string; env?: Record<string, string> } = {},
|
|
383
|
+
): { json: Record<string, unknown>; status: number | null; output: string } {
|
|
384
|
+
const driver = `import os, pty, re, select, signal, sys, time
|
|
385
|
+
argv = sys.argv[1:]
|
|
386
|
+
pid, fd = pty.fork()
|
|
387
|
+
if pid == 0:
|
|
388
|
+
os.execv(argv[0], argv)
|
|
389
|
+
override = os.environ.get("APPROVE_ANSWER")
|
|
390
|
+
output = b""
|
|
391
|
+
sent = False
|
|
392
|
+
deadline = time.monotonic() + 12
|
|
393
|
+
try:
|
|
394
|
+
while time.monotonic() < deadline:
|
|
395
|
+
if not select.select([fd], [], [], 0.1)[0]:
|
|
396
|
+
continue
|
|
397
|
+
try:
|
|
398
|
+
chunk = os.read(fd, 65536)
|
|
399
|
+
except OSError:
|
|
400
|
+
break
|
|
401
|
+
if not chunk:
|
|
402
|
+
break
|
|
403
|
+
output += chunk
|
|
404
|
+
if not sent:
|
|
405
|
+
m = re.search(rb"type the code ([A-Z0-9]+)", output)
|
|
406
|
+
if m:
|
|
407
|
+
reply = override if override is not None else m.group(1).decode()
|
|
408
|
+
os.write(fd, (reply + "\\n").encode())
|
|
409
|
+
sent = True
|
|
410
|
+
else:
|
|
411
|
+
os.kill(pid, signal.SIGKILL)
|
|
412
|
+
finally:
|
|
413
|
+
os.close(fd)
|
|
414
|
+
_, status = os.waitpid(pid, 0)
|
|
415
|
+
sys.stdout.buffer.write(output)
|
|
416
|
+
sys.stdout.buffer.flush()
|
|
417
|
+
sys.exit(os.waitstatus_to_exitcode(status))
|
|
418
|
+
`;
|
|
419
|
+
const args = [CLI, "approve", id, ...(opts.job ? ["--job"] : [])];
|
|
420
|
+
const env = { ...h.env, ...(opts.answer !== undefined ? { APPROVE_ANSWER: opts.answer } : {}), ...(opts.env ?? {}) };
|
|
421
|
+
const r = spawnSync("python3", ["-c", driver, process.execPath, ...args], { cwd: h.repo, env, encoding: "utf8", timeout: 15000 });
|
|
422
|
+
const output = `${r.stdout ?? ""}${r.stderr ?? ""}`;
|
|
423
|
+
// relay prints its result as the last JSON object; the prompt lines precede it.
|
|
424
|
+
const match = output.match(/\{[\s\S]*\}\s*$/);
|
|
425
|
+
let json: Record<string, unknown> = {};
|
|
426
|
+
try { if (match) json = JSON.parse(match[0]); } catch { /* left empty: the caller asserts on output */ }
|
|
427
|
+
return { json, status: r.status, output };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Explicit person-controlled recovery in scratch state. No test relies on silent adoption. */
|
|
431
|
+
export async function authorizeRun(h: Harness, client: Pick<Harness, "call">, id: string): Promise<{ run: string; to: string; owned?: boolean }> {
|
|
432
|
+
const run = id.startsWith("run_") ? id : h.sql("SELECT run_id FROM nodes WHERE id = ?", id)[0].run_id as string;
|
|
433
|
+
const visible = await client.call("status", { id });
|
|
434
|
+
if (visible.id === id || visible.run_id === run) return { run, to: (await client.call("status")).session.fingerprint, owned: true };
|
|
435
|
+
const pid = h.sql("SELECT root_pid FROM runs WHERE id = ?", run)[0].root_pid;
|
|
436
|
+
await until(() => !alive(pid), undefined, "the old owning connection to exit before explicit recovery");
|
|
437
|
+
// Select the routed harness's host for this item without gaining any access.
|
|
438
|
+
const to = (await client.call("status")).session.fingerprint as string;
|
|
439
|
+
const terminal = terminalAdoption(h, id, to);
|
|
440
|
+
if (terminal.status !== 0) throw new Error(`terminal adoption failed: ${terminal.stdout}\n${terminal.stderr}`);
|
|
441
|
+
return { run, to };
|
|
442
|
+
}
|
|
443
|
+
export async function adoptRun(h: Harness, client: Pick<Harness, "call">, id: string): Promise<Rec> {
|
|
444
|
+
const { run, to, owned } = await authorizeRun(h, client, id);
|
|
445
|
+
if (owned) return { adopted: true, run_id: run, into_session: to };
|
|
446
|
+
const r = await client.call("adopt", { run_id: run, into_session: to });
|
|
447
|
+
if (!r.adopted) throw new Error(`confirmed adoption failed: ${JSON.stringify(r)}`);
|
|
448
|
+
return r;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Stops the detached children a stub agent's `orphan` steps started, as listed in its directory's
|
|
453
|
+
* `orphans`. They are in process groups of their own, so killing the agent's group misses them, and
|
|
454
|
+
* a test that fails before reading their pids cannot. A pid is killed only while its command line is
|
|
455
|
+
* still the orphan's, naming this stub directory: by now the pid may belong to another process.
|
|
456
|
+
*/
|
|
457
|
+
function killOrphans(stubDir: string): void {
|
|
458
|
+
let pids: number[];
|
|
459
|
+
try {
|
|
460
|
+
pids = fs.readFileSync(path.join(stubDir, "orphans"), "utf8").split("\n").filter(Boolean).map(Number).filter((p) => p > 1);
|
|
461
|
+
} catch {
|
|
462
|
+
return; // No orphan was started.
|
|
463
|
+
}
|
|
464
|
+
for (const pid of pids) {
|
|
465
|
+
const r = spawnSync("/bin/ps", ["-ww", "-o", "command=", "-p", String(pid)], { encoding: "utf8" });
|
|
466
|
+
const command = r.status === 0 ? r.stdout.trim() : "";
|
|
467
|
+
if (command.endsWith(` relay-stub-orphan ${stubDir}`)) try { process.kill(pid, "SIGKILL"); } catch {}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** The task text ends the delegation prompt, so rules anchor on it to avoid matching the preamble. */
|
|
472
|
+
export const task = (name: string) => `assignment:\\s+${name}$`;
|
|
473
|
+
|
|
474
|
+
/** `env`: variables added to the environment of every relay process the harness starts, and so of the agents. */
|
|
475
|
+
export async function harness(rules: Rule[] = [], config: Record<string, unknown> = {}, extraEnv: Record<string, string> = {}): Promise<Harness> {
|
|
476
|
+
// Write grants must not live under shared temp. A disposable tree outside it also keeps
|
|
477
|
+
// native sandboxes' default temp allowances from weakening the fixtures' fake homes.
|
|
478
|
+
const tmp = config.allow_temp_home === false
|
|
479
|
+
? fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "relay-test-")))
|
|
480
|
+
: nonTempScratch("relay-test-");
|
|
481
|
+
const home = path.join(tmp, "home");
|
|
482
|
+
const stub = path.join(tmp, "stub");
|
|
483
|
+
const repo = path.join(tmp, "repo");
|
|
484
|
+
// HOME for relay, its agents and git: a scratch one, never the real home folder.
|
|
485
|
+
// Short enough for Claude's private-temp limit (44 bytes including /claude-<uid>).
|
|
486
|
+
const userHome = nonTempScratch("rh");
|
|
487
|
+
for (const d of [home, stub, repo, userHome]) fs.mkdirSync(d, { recursive: true });
|
|
488
|
+
fs.writeFileSync(path.join(stub, "log.jsonl"), "");
|
|
489
|
+
fs.writeFileSync(path.join(tmp, "scenario.json"), JSON.stringify({ rules }));
|
|
490
|
+
// Each stubbed target's CLI is its stub; a test's own targets settings are added to that.
|
|
491
|
+
const targets: Record<string, Record<string, unknown>> = Object.fromEntries(STUB_TARGETS.map((t) => [t, { bin: stubBin(t), ...(t === "codex" ? { pinned: false } : {}) }]));
|
|
492
|
+
for (const [t, v] of Object.entries((config.targets ?? {}) as Record<string, Record<string, unknown>>)) targets[t] = { ...targets[t], ...v };
|
|
493
|
+
fs.writeFileSync(path.join(home, "config.json"), JSON.stringify({
|
|
494
|
+
// Test homes live under the temp directory, which production refuses.
|
|
495
|
+
cancel_grace_ms: 300, block_s: 30, allow_temp_home: true, ...config, targets,
|
|
496
|
+
// The fixture deliberately discloses only its synthetic stub controls. Production's default
|
|
497
|
+
// allowlist must apply in tests too; never automatically pass credential canaries in extraEnv.
|
|
498
|
+
child_env: {
|
|
499
|
+
...((config.child_env ?? {}) as Record<string, unknown>),
|
|
500
|
+
// The stubs' controls: the three this harness sets below (the stub agent reads its rules from
|
|
501
|
+
// STUB_SCENARIO), and any STUB_* a test sets in its own environment or in extraEnv.
|
|
502
|
+
pass: [...new Set(["STUB_DIR", "STUB_SCENARIO", "STUB_TEMP_ROOT", ...[...Object.keys(process.env), ...Object.keys(extraEnv)].filter((name) => name.startsWith("STUB_")), ...(((config.child_env as { pass?: string[] } | undefined)?.pass) ?? [])])],
|
|
503
|
+
},
|
|
504
|
+
}));
|
|
505
|
+
const g = (...a: string[]) => execFileSync("git", a, { cwd: repo, stdio: "pipe", env: { PATH: process.env.PATH, HOME: userHome } });
|
|
506
|
+
g("init", "-q", "-b", "main");
|
|
507
|
+
g("config", "user.name", "test");
|
|
508
|
+
g("config", "user.email", "test@example.com");
|
|
509
|
+
fs.writeFileSync(path.join(repo, "README.md"), "sample\n");
|
|
510
|
+
g("add", "-A");
|
|
511
|
+
g("commit", "-q", "-m", "init");
|
|
512
|
+
|
|
513
|
+
// The machine's temporary directory is shared with every other relay on it, the live install's
|
|
514
|
+
// among them: no test may sweep it (core/retention.ts sweepTemps). So a worker's daily
|
|
515
|
+
// housekeeping, which sweeps it, is marked done already (a test that wants it removes
|
|
516
|
+
// <home>/housekeeping and gives relay a TMPDIR of its own), and relay clean, which sweeps whatever
|
|
517
|
+
// the config, runs with a private one, unless the test gives its own. Short, so that relay's
|
|
518
|
+
// socket names fit in it: a Unix socket's path may not exceed 103 bytes.
|
|
519
|
+
fs.writeFileSync(path.join(home, "housekeeping"), "marked done by the test harness\n");
|
|
520
|
+
// Claude network turns: the stub Claude's model endpoint, which the turn's proxy serves from this
|
|
521
|
+
// tiny server (RELAY_DEV_MODEL_STUB, set below), so that its model request needs no network.
|
|
522
|
+
const modelStub = net.createServer((c) => {
|
|
523
|
+
c.on("error", () => {});
|
|
524
|
+
c.once("data", () => c.end("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"));
|
|
525
|
+
});
|
|
526
|
+
await new Promise<void>((r) => modelStub.listen(0, "127.0.0.1", r));
|
|
527
|
+
modelStub.unref();
|
|
528
|
+
fs.mkdirSync(path.join(home, "dev"), { recursive: true });
|
|
529
|
+
fs.writeFileSync(path.join(home, "dev", "claude-model-stub.json"), JSON.stringify({ host: "model.relay-test.invalid", port: (modelStub.address() as net.AddressInfo).port }));
|
|
530
|
+
const cliTmp = fs.realpathSync(fs.mkdtempSync("/tmp/rh-"));
|
|
531
|
+
|
|
532
|
+
const env: Record<string, string> = {};
|
|
533
|
+
// Nothing of the session running the tests: relay reads its host from these (and would post to its
|
|
534
|
+
// inbox), and an endpoint it set (the Claude desktop app sets one for the MCP servers it starts)
|
|
535
|
+
// would send agents elsewhere, and relay rightly refuses to pass it on (tests that need one set it
|
|
536
|
+
// through extraEnv).
|
|
537
|
+
for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith("RELAY_") && !hostVar(k) && !HOME_VARS.includes(k)) env[k] = v;
|
|
538
|
+
Object.assign(env, { HOME: userHome, STUB_TEMP_ROOT: fs.realpathSync(os.tmpdir()) }, extraEnv, { RELAY_HOME: home, RELAY_DEV_MODEL_STUB: "1", STUB_DIR: stub, STUB_SCENARIO: path.join(tmp, "scenario.json") });
|
|
539
|
+
scratchEnv(env);
|
|
540
|
+
|
|
541
|
+
const clients: Client[] = [];
|
|
542
|
+
const connect = async (o: InstanceOpts) => {
|
|
543
|
+
// Instance-specific stub controls need the same explicit fixture passes as extraEnv. Never
|
|
544
|
+
// pass arbitrary instance variables: endpoint and credential tests must keep real guards.
|
|
545
|
+
const controls = Object.keys(o.env ?? {}).filter((name) => name.startsWith("STUB_"));
|
|
546
|
+
if (controls.length) {
|
|
547
|
+
const file = path.join(home, "config.json"), cfg = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
548
|
+
cfg.child_env ??= {};
|
|
549
|
+
cfg.child_env.pass = [...new Set([...(cfg.child_env.pass ?? []), ...controls])];
|
|
550
|
+
fs.writeFileSync(file, JSON.stringify(cfg));
|
|
551
|
+
}
|
|
552
|
+
// With `elicit`, the client behaves like a host that can put relay's questions to the user.
|
|
553
|
+
const client = new Client(o.clientInfo ?? { name: o.args?.includes("--host") ? (o.args[o.args.indexOf("--host") + 1] === "claude" ? "claude-code" : "codex-mcp-client") : "test", version: "0" }, { capabilities: { ...(o.elicit ? { elicitation: {} } : {}), ...(o.desktopUi ? { extensions: { "io.modelcontextprotocol/ui": {} } } : {}) } });
|
|
554
|
+
if (o.elicit) {
|
|
555
|
+
// Withdrawn questions are tracked here: the SDK's client ignores a cancellation of request id 0, the first a server sends.
|
|
556
|
+
const open = new Map<string | number, AbortController>();
|
|
557
|
+
client.setNotificationHandler(CancelledNotificationSchema, (n) => open.get(n.params.requestId!)?.abort());
|
|
558
|
+
client.setRequestHandler(ElicitRequestSchema, async (req, extra) => {
|
|
559
|
+
const ctl = new AbortController();
|
|
560
|
+
open.set(extra.requestId, ctl);
|
|
561
|
+
try {
|
|
562
|
+
return (await o.elicit!(req.params.message, ctl.signal, req.params as Rec)) as never;
|
|
563
|
+
} finally {
|
|
564
|
+
open.delete(extra.requestId);
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
await client.connect(new StdioClientTransport({ command: process.execPath, args: [o.cli ?? CLI, "mcp", ...(o.args ?? [])], env: scratchEnv({ ...env, ...(o.env ?? {}) }), cwd: o.cwd ?? repo }));
|
|
569
|
+
clients.push(client);
|
|
570
|
+
const call = async (tool: string, args: Record<string, unknown> = {}, opts: CallOpts = {}) => {
|
|
571
|
+
const { meta, ...request } = opts;
|
|
572
|
+
const res = (await client.callTool({ name: tool, arguments: args, ...(meta ? { _meta: meta } : {}) }, undefined, { timeout: 120000, ...request })) as Rec;
|
|
573
|
+
if (res.isError) return { tool_error: res.content[0].text } as Rec;
|
|
574
|
+
return JSON.parse(res.content[0].text) as Rec;
|
|
575
|
+
};
|
|
576
|
+
const tools = async () => (await client.listTools()).tools.map((t) => t.name).sort();
|
|
577
|
+
return { call, tools, toolDefinitions: async () => (await client.listTools()).tools, close: () => client.close() };
|
|
578
|
+
};
|
|
579
|
+
const sql = (query: string, ...params: unknown[]) => {
|
|
580
|
+
const d = new DatabaseSync(path.join(home, "relay.db"));
|
|
581
|
+
d.exec("PRAGMA busy_timeout = 10000;");
|
|
582
|
+
try {
|
|
583
|
+
return d.prepare(query).all(...(params as never[])) as Rec[];
|
|
584
|
+
} finally {
|
|
585
|
+
d.close();
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* A root session whose host is chosen per call. Relay refuses to reach anything from a root
|
|
591
|
+
* session whose host it cannot tell, and refuses a target of the caller's own family, so the
|
|
592
|
+
* tests' sessions declare a host, as an installed relay does. One session per host is opened as
|
|
593
|
+
* needed: a call naming a target goes to a host of another family; a call naming existing items
|
|
594
|
+
* goes to the session whose run they are in; anything else goes to the host used last.
|
|
595
|
+
*/
|
|
596
|
+
const routed = async (o: InstanceOpts) => {
|
|
597
|
+
const sessions = new Map<Target, Awaited<ReturnType<typeof connect>>>();
|
|
598
|
+
const runHost = new Map<string, Target>();
|
|
599
|
+
let last: Target = hostFor(STUB_TARGETS[0]);
|
|
600
|
+
const session = async (host: Target) => {
|
|
601
|
+
if (!sessions.has(host)) sessions.set(host, await connect({ ...o, args: [...(o.args ?? []), "--host", host] }));
|
|
602
|
+
return sessions.get(host)!;
|
|
603
|
+
};
|
|
604
|
+
/** The run an item is in, and the target of the agent it concerns. */
|
|
605
|
+
const whereIs = (id: string): { run?: string; target?: string } => {
|
|
606
|
+
try {
|
|
607
|
+
if (id.startsWith("run_")) return { run: id };
|
|
608
|
+
const row = sql("SELECT run_id, target FROM nodes WHERE id = ?", id)[0]
|
|
609
|
+
?? sql("SELECT r.run_id, n.target FROM requests r JOIN nodes n ON n.id = r.node_id WHERE r.id = ?", id)[0];
|
|
610
|
+
return { run: row?.run_id, target: row?.target ?? undefined };
|
|
611
|
+
} catch {
|
|
612
|
+
return {}; // No registry yet.
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
const ids = (v: unknown, out: string[] = []): string[] => {
|
|
616
|
+
if (typeof v === "string" && /^(run|[jtpdrq])_[0-9a-f]{8}$/.test(v)) out.push(v);
|
|
617
|
+
else if (v && typeof v === "object") for (const x of Object.values(v)) ids(x, out);
|
|
618
|
+
return out;
|
|
619
|
+
};
|
|
620
|
+
const call = async (tool: string, args: Record<string, unknown> = {}, opts: CallOpts = {}) => {
|
|
621
|
+
const named = ["thread_id", "job_id", "id", "discussion_id", "review_id", "with", "request_id"].map((k) => args[k]).filter((v): v is string => typeof v === "string");
|
|
622
|
+
// The session whose run it is; for a run no session of this instance has used yet, a host that may reach its agent.
|
|
623
|
+
const found = named.map(whereIs);
|
|
624
|
+
const owner = found.map((f) => (f.run ? runHost.get(f.run) : undefined)).find(Boolean)
|
|
625
|
+
?? found.map((f) => (f.target && STUB_TARGETS.includes(f.target as Target) ? hostFor(f.target) : undefined)).find(Boolean);
|
|
626
|
+
// review's target is what to review; its agent is the reviewer.
|
|
627
|
+
const wanted = (tool === "review" ? args.reviewer : args.target) as string | undefined;
|
|
628
|
+
const host = owner ?? (wanted && STUB_TARGETS.includes(wanted as Target) ? hostFor(wanted) : last);
|
|
629
|
+
last = host;
|
|
630
|
+
const res = await (await session(host)).call(tool, args, opts);
|
|
631
|
+
for (const id of ids(res)) {
|
|
632
|
+
const run = whereIs(id).run;
|
|
633
|
+
if (run && !runHost.has(run)) runHost.set(run, host);
|
|
634
|
+
}
|
|
635
|
+
return res;
|
|
636
|
+
};
|
|
637
|
+
return {
|
|
638
|
+
call,
|
|
639
|
+
tools: async () => (await session(last)).tools(),
|
|
640
|
+
toolDefinitions: async () => (await session(last)).toolDefinitions(),
|
|
641
|
+
close: async () => {
|
|
642
|
+
for (const s of sessions.values()) await s.close();
|
|
643
|
+
},
|
|
644
|
+
};
|
|
645
|
+
};
|
|
646
|
+
const instance = (o: InstanceOpts) => {
|
|
647
|
+
// childOf is asynchronous: given its promise, the instance would quietly be a root session.
|
|
648
|
+
if (typeof (o as { then?: unknown }).then === "function") throw new Error("instance() was given a promise: await childOf first");
|
|
649
|
+
return o.host === null ? connect(o) : o.args?.includes("--context") || o.args?.includes("--host") ? connect(o) : routed(o);
|
|
650
|
+
};
|
|
651
|
+
const root = await routed({});
|
|
652
|
+
|
|
653
|
+
const log = () => fs.readFileSync(path.join(stub, "log.jsonl"), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l) as Rec);
|
|
654
|
+
const environmentSocket = (nodeId: string): string | undefined => {
|
|
655
|
+
const node = sql("SELECT run_id FROM nodes WHERE id = ?", nodeId)[0];
|
|
656
|
+
const file = path.join(home, "runs", node.run_id, "nodes", nodeId, "claude-mcp.json");
|
|
657
|
+
const claudeArgs: string[] = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")).mcpServers?.relay?.args ?? [] : [];
|
|
658
|
+
// Codex's launcher is in its actual -c flags, rather than a file. Both use env -i.
|
|
659
|
+
const codexArgs: string[] | undefined = log().filter((r) => r.event === "start").flatMap((r) => r.argv ?? [])
|
|
660
|
+
.filter((arg: string) => arg.startsWith("mcp_servers.relay.args="))
|
|
661
|
+
.map((arg: string) => JSON.parse(arg.slice("mcp_servers.relay.args=".length)))
|
|
662
|
+
.findLast((args: string[]) => args.includes(`RELAY_NODE_ID=${nodeId}`));
|
|
663
|
+
const args = codexArgs ?? claudeArgs;
|
|
664
|
+
return args.find((arg) => arg.startsWith("RELAY_ENV_SOCKET="))?.slice("RELAY_ENV_SOCKET=".length);
|
|
665
|
+
};
|
|
666
|
+
const servers: net.Server[] = [];
|
|
667
|
+
let inboxes = 0;
|
|
668
|
+
const inbox = async () => {
|
|
669
|
+
const socket = path.join(tmp, `inbox-${++inboxes}.sock`);
|
|
670
|
+
const posts: { token?: string; text: string }[] = [];
|
|
671
|
+
const server = net.createServer((c) => {
|
|
672
|
+
let buf = "";
|
|
673
|
+
c.on("data", (d) => (buf += d.toString("utf8")));
|
|
674
|
+
c.on("end", () => {
|
|
675
|
+
const lines = buf.split("\n").filter(Boolean).map((l) => JSON.parse(l) as Rec);
|
|
676
|
+
posts.push({ token: lines.find((l) => l.type === "auth")?.token, text: lines.find((l) => l.type === "user")?.message?.content });
|
|
677
|
+
});
|
|
678
|
+
});
|
|
679
|
+
await new Promise<void>((r) => server.listen(socket, r));
|
|
680
|
+
servers.push(server);
|
|
681
|
+
return { env: { CLAUDE_CODE_MESSAGING_SOCKET: socket, CLAUDE_CODE_MESSAGING_TOKEN: `token-${inboxes}` }, posts: () => posts };
|
|
682
|
+
};
|
|
683
|
+
return {
|
|
684
|
+
home, repo, env,
|
|
685
|
+
call: root.call,
|
|
686
|
+
instance,
|
|
687
|
+
log,
|
|
688
|
+
starts: () => log().filter((r) => r.event === "start"),
|
|
689
|
+
ends: () => log().filter((r) => r.event === "end"),
|
|
690
|
+
environmentSocket,
|
|
691
|
+
sql,
|
|
692
|
+
childOf: async (nodeId, policy = {}) => {
|
|
693
|
+
await until(() => {
|
|
694
|
+
const pid = sql("SELECT worker_pid FROM nodes WHERE id = ?", nodeId)[0]?.worker_pid;
|
|
695
|
+
return !(pid > 0 && alive(pid));
|
|
696
|
+
}, undefined, `the worker of ${nodeId} to be gone`);
|
|
697
|
+
const d = new DatabaseSync(path.join(home, "relay.db"));
|
|
698
|
+
d.exec("PRAGMA busy_timeout = 10000;");
|
|
699
|
+
const node = d.prepare("SELECT run_id, depth, params_json FROM nodes WHERE id = ?").get(nodeId) as Rec;
|
|
700
|
+
const turnId = Number(d.prepare("INSERT INTO turns (node_id, source, body, access, status, created_at, grant_json) VALUES (?, 'test', '', ?, ?, ?, ?)")
|
|
701
|
+
.run(nodeId, policy.access ?? "write", policy.running === false ? "done" : "running", Date.now(), JSON.stringify(JSON.parse(node.params_json).grant ?? {})).lastInsertRowid);
|
|
702
|
+
// A turn in progress means a session in progress.
|
|
703
|
+
if (policy.running !== false) d.prepare("UPDATE nodes SET status = 'running', ended_at = NULL WHERE id = ?").run(nodeId);
|
|
704
|
+
d.close();
|
|
705
|
+
const file = path.join(home, `ctx-${nodeId}-${turnId}.json`);
|
|
706
|
+
fs.writeFileSync(file, JSON.stringify({
|
|
707
|
+
run_id: node.run_id, node_id: nodeId, depth: node.depth, turn_id: turnId,
|
|
708
|
+
access: policy.access ?? "write", may_delegate: policy.may_delegate ?? true, may_ask: policy.may_ask ?? false,
|
|
709
|
+
}));
|
|
710
|
+
const socket = environmentSocket(nodeId);
|
|
711
|
+
return { args: ["--context", file], env: { RELAY_RUN_ID: node.run_id, RELAY_NODE_ID: nodeId, RELAY_DEPTH: String(node.depth), RELAY_INJECTED: "1", ...(socket ? { RELAY_ENV_SOCKET: socket } : {}) }, turnId };
|
|
712
|
+
},
|
|
713
|
+
cli: (...args) => spawnSync(process.execPath, [CLI, ...args], { env: { ...env, TMPDIR: extraEnv.TMPDIR ?? cliTmp }, cwd: repo, encoding: "utf8" }).stdout,
|
|
714
|
+
cliEnv: (extra, ...args) => spawnSync(process.execPath, [CLI, ...args], { env: { ...env, TMPDIR: extraEnv.TMPDIR ?? cliTmp, ...extra }, cwd: repo, encoding: "utf8" }).stdout,
|
|
715
|
+
mark: (name) => fs.writeFileSync(path.join(stub, `mark-${name}`), String(Date.now())),
|
|
716
|
+
marked: (name) => fs.existsSync(path.join(stub, `mark-${name}`)),
|
|
717
|
+
inbox,
|
|
718
|
+
close: async () => {
|
|
719
|
+
for (const c of clients) await c.close().catch(() => {});
|
|
720
|
+
for (const s of servers) s.close();
|
|
721
|
+
modelStub.close();
|
|
722
|
+
// Leave nothing running if a test failed part-way.
|
|
723
|
+
try {
|
|
724
|
+
const d = new DatabaseSync(path.join(home, "relay.db"));
|
|
725
|
+
d.exec("PRAGMA busy_timeout = 10000;");
|
|
726
|
+
const rows = d.prepare("SELECT worker_pid, agent_pgid FROM nodes").all() as Rec[];
|
|
727
|
+
d.close();
|
|
728
|
+
for (const r of rows) {
|
|
729
|
+
if (r.agent_pgid) killGroup(r.agent_pgid);
|
|
730
|
+
if (r.worker_pid > 0) try { process.kill(r.worker_pid, "SIGKILL"); } catch {}
|
|
731
|
+
}
|
|
732
|
+
} catch {}
|
|
733
|
+
killOrphans(stub);
|
|
734
|
+
removeTestNativeTempAlias(userHome, extraEnv.STUB_LINK_PARENT);
|
|
735
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
736
|
+
fs.rmSync(userHome, { recursive: true, force: true });
|
|
737
|
+
fs.rmSync(cliTmp, { recursive: true, force: true });
|
|
738
|
+
},
|
|
739
|
+
};
|
|
740
|
+
}
|