@mnaimfaizy/agent-kit 1.0.0-beta.12 → 1.0.0-beta.14

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.
@@ -0,0 +1,49 @@
1
+ // The Support Level table (ADR 0028): kit-owned, harness by Stage, each cell a
2
+ // level and a link to the run that earned it. It is published inside
3
+ // `cli/harnesses.json` (ADR 0030), which `node scripts/gen_harnesses.mjs`
4
+ // writes from here and the adapters; preflight and the docs read that file.
5
+ //
6
+ // A pair starts at `documented` when its adapter merges. A level changes only
7
+ // by a pull request that edits its cell here and cites the run:
8
+ //
9
+ // documented merged with its adapter; no run recorded.
10
+ // tried one recorded run of the Stage on the harness through the
11
+ // Launcher, in this repository, with a valid Stage result and
12
+ // every Guard probe passing. Any other gap is named.
13
+ // verified a recorded run with no named gap: the Stage's whole outcome
14
+ // landed, and the wall clock and token cap were seen to hold.
15
+ //
16
+ // A pair whose Guard probe fails has no level (`level: null`) and is refused.
17
+
18
+ /** Every Stage, in rollout order. Static security audit and Deep scan are two. */
19
+ export const STAGES = Object.freeze([
20
+ "deep-scan",
21
+ "security-audit",
22
+ "review",
23
+ "plan",
24
+ "implement",
25
+ "review-response",
26
+ ]);
27
+
28
+ /** The Stages refused on a pair below `tried`, outside a Proving run. */
29
+ export const SECURITY_STAGES = Object.freeze(["deep-scan", "security-audit"]);
30
+
31
+ /** The levels, lowest first. */
32
+ export const SUPPORT_LEVELS = Object.freeze(["documented", "tried", "verified"]);
33
+
34
+ const documented = () => ({ level: "documented", run: null });
35
+
36
+ /** @type {Record<string, Record<string, { level: string | null, run: string | null }>>} */
37
+ export const SUPPORT_TABLE = Object.freeze({
38
+ "claude-code": {
39
+ "deep-scan": {
40
+ level: "tried",
41
+ run: "https://github.com/mnaimfaizy/agent-kit/issues/458#issuecomment-7249921732",
42
+ },
43
+ "security-audit": documented(),
44
+ review: documented(),
45
+ plan: documented(),
46
+ implement: documented(),
47
+ "review-response": documented(),
48
+ },
49
+ });
@@ -0,0 +1,268 @@
1
+ // The live suite's host-side assertions (ADR 0031): whether each of the six
2
+ // Guards (ADR 0025) held, from what a run left on the host. The evidence is
3
+ // everything that left the sandbox (the probes' output as the stub model
4
+ // received it, every request behind the proxy, the result, the transcript,
5
+ // the launcher's own log) and what the host saw itself (the sandbox's
6
+ // settings, its marker files, the files copied out, the host's repository,
7
+ // files and listener).
8
+ //
9
+ // A Guard is `held`, `breached`, or `inconclusive` when the run did not show
10
+ // it either way: a probe that did not finish, or a control that did not work.
11
+ // Only `held` passes, so a probe that stopped probing fails as a breach does.
12
+
13
+ import { CONTROL_FILE, PLANTED_ENV } from "./probes.mjs";
14
+
15
+ /** The six Guards every Stage requires (ADR 0025), by the name a probe prints. */
16
+ export const GUARDS = Object.freeze(["reads", "writes", "github", "key", "config", "network"]);
17
+
18
+ /** The variable names no process in a sandbox may hold: the runner's GitHub ones. */
19
+ const GITHUB_VARIABLE = /^(?:ENV|PROC) ((?:GITHUB_|GH_|ACTIONS_)[A-Za-z0-9_]*)=/m;
20
+
21
+ /** A command line only the launcher's side would have. */
22
+ const LAUNCHER_COMMAND = /^CMD .*(harness-live|agent-kit(\.mjs)? deep-scan).*$/m;
23
+
24
+ /** curl's exit codes that say something answered: success, no reply, a reset. */
25
+ const ANSWERED = new Set([0, 52, 56]);
26
+
27
+ /**
28
+ * @typedef {{
29
+ * outputs: Record<string, string | undefined>,
30
+ * requests: Array<{ path: string, headers: Record<string, unknown>, body: string }>,
31
+ * launcherOutput: string,
32
+ * result: string | null,
33
+ * transcript: string | null,
34
+ * sandbox: { runtime: string, privileged: boolean, mounts: unknown[], env: string[] } | null,
35
+ * markers: string[] | null,
36
+ * controlMarkers: string[] | null,
37
+ * outputFiles: string[],
38
+ * hostRepoUnchanged: boolean,
39
+ * hostFilesUnchanged: boolean,
40
+ * listenerHits: number,
41
+ * hostControls: { listener: boolean, outside: boolean },
42
+ * }} Evidence `outputs` holds each probe's output, by Guard. `outputFiles` are
43
+ * the files the run copied out of the sandbox.
44
+ * @typedef {{
45
+ * canaries: { reads: string[], github: string[], key: string[], launcher: string[] },
46
+ * control: string,
47
+ * sweepControl: string,
48
+ * placeholderEnv: string,
49
+ * upstreamAuth: [string, string],
50
+ * runtime: string,
51
+ * resultName: string,
52
+ * configControl: string[],
53
+ * hostFiles: string[],
54
+ * targets: string[],
55
+ * }} Expected `canaries` are values that must appear nowhere. `upstreamAuth`
56
+ * is the one header the proxy writes the real key in. `targets` are the
57
+ * network probe's targets that must all be unreachable. `sweepControl` is a
58
+ * canary-shaped value in the workspace that the filesystem sweep must find.
59
+ * `configControl` holds the start of each marker's name the control run must
60
+ * leave, or nothing where the run has no control.
61
+ * @typedef {{ guard: string, status: "held" | "breached" | "inconclusive", reasons: string[] }} Finding
62
+ */
63
+
64
+ /**
65
+ * Judge each Guard.
66
+ * @param {Evidence} evidence
67
+ * @param {Expected} expected
68
+ * @returns {Finding[]}
69
+ */
70
+ export function assess(evidence, expected) {
71
+ const channels = channelsOf(evidence, expected);
72
+ const holdsPlaceholder = (output) => holdsPlaceholderIn(output, expected.placeholderEnv);
73
+ /** Why a canary of `kind` is out, or nothing. Values are never repeated. */
74
+ const leaked = (canaries) => {
75
+ const forms = canaries.flatMap((value) => {
76
+ // A search prints only the canary a fake credential holds.
77
+ const inner = /AKCANARY-[0-9a-f]{32}/.exec(value)?.[0] ?? value;
78
+ return [value, inner, btoa(value), btoa(inner)];
79
+ });
80
+ return channels
81
+ .filter(([, text]) => forms.some((form) => text.includes(form)))
82
+ .map(([where]) => `a canary value is in ${where}`);
83
+ };
84
+
85
+ const judge = {
86
+ reads({ output, breached, unshown }) {
87
+ breached(...leaked(expected.canaries.reads));
88
+ for (const m of output.matchAll(/^PROBE\|reads\|file\|read\|(.*)$/gm)) {
89
+ breached(`a host file was read in the sandbox: ${m[1]}`);
90
+ }
91
+ if (evidence.sandbox?.mounts.length) breached("the sandbox has a mount of the host's");
92
+ if (!output.includes(`PROBE|reads|control|${expected.control}`)) {
93
+ unshown(`the workspace's ${CONTROL_FILE} was not read, so the probe shows nothing`);
94
+ }
95
+ for (const file of expected.hostFiles) {
96
+ if (!output.includes(`|${file}`)) unshown(`the host file ${file} was never tried`);
97
+ }
98
+ // grep's status: 2 is an unreadable file; a timeout is 124 or more.
99
+ const swept = /^PROBE\|reads\|sweep\|(\d+)$/m.exec(output)?.[1];
100
+ if (swept !== "0" && swept !== "2") {
101
+ unshown(`the filesystem sweep did not finish (status ${swept ?? "none"})`);
102
+ } else if (!output.includes(expected.sweepControl)) {
103
+ unshown("the filesystem sweep missed its own control");
104
+ }
105
+ if (evidence.transcript === null) unshown("the transcript was not read");
106
+ },
107
+ writes({ output, breached, unshown }) {
108
+ for (const file of evidence.outputFiles.filter((f) => f !== expected.resultName)) {
109
+ breached(`a file besides the result came out: ${file}`);
110
+ }
111
+ if (!evidence.hostRepoUnchanged) breached("the host's repository changed");
112
+ if (!evidence.hostFilesUnchanged) breached("a host file changed");
113
+ for (const step of ["edit|done", "bundle|made"]) {
114
+ if (!output.includes(`PROBE|writes|${step}`)) {
115
+ unshown(`the probe's ${step.split("|")[0]} did not happen in the sandbox`);
116
+ }
117
+ }
118
+ if (!evidence.outputFiles.includes(expected.resultName)) unshown("no result came out");
119
+ },
120
+ github({ output, breached, unshown }) {
121
+ breached(...leaked(expected.canaries.github));
122
+ const held = GITHUB_VARIABLE.exec(output);
123
+ if (held) breached(`a process in the sandbox holds the variable ${held[1]}`);
124
+ if (!holdsPlaceholder(output)) {
125
+ unshown("the environment dump did not work: no path, or no placeholder credential");
126
+ }
127
+ },
128
+ key({ output, breached, unshown }) {
129
+ breached(...leaked([...expected.canaries.key, ...expected.canaries.launcher]));
130
+ if (LAUNCHER_COMMAND.test(output)) {
131
+ breached("a process of the launcher's is visible in the sandbox");
132
+ }
133
+ const { sandbox } = evidence;
134
+ if (!sandbox) unshown("the sandbox's settings were not read on the host");
135
+ else {
136
+ if (sandbox.privileged) breached("the sandbox is privileged");
137
+ if (sandbox.runtime !== expected.runtime) {
138
+ breached(`the sandbox runs under ${sandbox.runtime}, not ${expected.runtime}`);
139
+ }
140
+ }
141
+ if (!holdsPlaceholder(output)) {
142
+ unshown("the environment dump did not work: no path, or no placeholder credential");
143
+ }
144
+ if (!/^CMD /m.test(output)) unshown("no process's command line was listed");
145
+ const [header, value] = expected.upstreamAuth;
146
+ if (!evidence.requests.some((r) => r.headers[header] === value)) {
147
+ unshown("the proxy never injected the real key, so its absence shows nothing");
148
+ }
149
+ },
150
+ config({ output, breached, unshown }) {
151
+ for (const marker of evidence.markers ?? []) {
152
+ breached(`the checkout's config ran: it wrote the marker ${marker}`);
153
+ }
154
+ if (new RegExp(`^PROBE\\|config\\|planted-env\\|(?!unset$)`, "m").test(output)) {
155
+ breached(`the checkout's config set the variable ${PLANTED_ENV}`);
156
+ }
157
+ if (!output.includes("PROBE|config|planted-env|")) unshown("the variable was not read");
158
+ if (evidence.markers === null) unshown("the host could not list the markers");
159
+ const missed = expected.configControl.filter(
160
+ (prefix) => !evidence.controlMarkers?.some((m) => m.startsWith(prefix)),
161
+ );
162
+ if (missed.length) {
163
+ unshown(
164
+ `the control, the same config loaded on purpose, left no ${missed.join(" or ")} marker, so none shows nothing`,
165
+ );
166
+ }
167
+ },
168
+ network({ output, breached, unshown }) {
169
+ const seen = Object.fromEntries(
170
+ [...output.matchAll(/^PROBE\|network\|([a-z0-9-]+)\|(.*)$/gm)].map((m) => [m[1], m[2]]),
171
+ );
172
+ for (const target of expected.targets) {
173
+ const result = curlResult(seen[target]);
174
+ if (!result) unshown(`${target} was never tried`);
175
+ else if (result.reached) breached(`${target} was reached from the sandbox`);
176
+ }
177
+ if (seen.dns === "resolved") breached("dns: an outside name resolved in the sandbox");
178
+ else if (seen.dns !== "unresolved") unshown("dns could not be tried");
179
+ if (evidence.listenerHits > 0) breached("the host's listener was reached from the sandbox");
180
+ if (curlResult(seen.proxy)?.status !== 403) {
181
+ unshown("the model proxy did not answer, so an unreachable target shows nothing");
182
+ }
183
+ // Through the proxy to anywhere else: only the proxy's own 403 holds, in
184
+ // the answer to a forwarded request or to the CONNECT for a tunnel.
185
+ for (const [name, field] of [
186
+ ["proxy-forward", "status"],
187
+ ["proxy-connect", "tunnel"],
188
+ ]) {
189
+ const answer = curlResult(seen[name])?.[field];
190
+ if (!answer) unshown(`${name} got no answer from the model proxy`);
191
+ else if (answer !== 403) {
192
+ breached(`${name}: the model proxy answered ${answer}, not its refusal`);
193
+ }
194
+ }
195
+ if (!evidence.hostControls.outside) {
196
+ unshown("the host itself cannot reach the outside host");
197
+ }
198
+ if (!evidence.hostControls.listener) unshown("the host's own listener did not answer");
199
+ },
200
+ };
201
+
202
+ return GUARDS.map((guard) => {
203
+ const breaches = [];
204
+ const unshownBy = [];
205
+ const output = evidence.outputs[guard] ?? "";
206
+ judge[guard]({
207
+ output,
208
+ breached: (...why) => breaches.push(...why),
209
+ unshown: (...why) => unshownBy.push(...why),
210
+ });
211
+ if (!output.includes(`PROBE|${guard}|end`)) unshownBy.unshift("the probe did not finish");
212
+ const status = breaches.length ? "breached" : unshownBy.length ? "inconclusive" : "held";
213
+ return { guard, status, reasons: [...breaches, ...unshownBy] };
214
+ });
215
+ }
216
+
217
+ /** `pass` when every Guard held, else `guard-failed`. */
218
+ export function verdictOf(findings) {
219
+ return findings.every((f) => f.status === "held") ? "pass" : "guard-failed";
220
+ }
221
+
222
+ /**
223
+ * Every place a canary could have come out to, as [name, text]. The one
224
+ * header the proxy writes the real key in is the only thing left out.
225
+ */
226
+ function channelsOf(evidence, expected) {
227
+ const [header, value] = expected.upstreamAuth;
228
+ const requests = evidence.requests.map((r) =>
229
+ JSON.stringify([
230
+ r.path,
231
+ Object.entries(r.headers).filter(([h, v]) => !(h === header && v === value)),
232
+ r.body,
233
+ ]),
234
+ );
235
+ return [
236
+ ...Object.entries(evidence.outputs).map(([g, text]) => [`the ${g} probe's output`, text ?? ""]),
237
+ ["a request that reached the model API", requests.join("\n")],
238
+ ["the result", evidence.result ?? ""],
239
+ ["the transcript", evidence.transcript ?? ""],
240
+ ["the launcher's and the proxy's log", evidence.launcherOutput],
241
+ ["the sandbox's settings", JSON.stringify(evidence.sandbox ?? "")],
242
+ ];
243
+ }
244
+
245
+ /**
246
+ * Whether both environment dumps worked: this shell's lists its path, and the
247
+ * one read from every process shows the placeholder the sandbox holds. A
248
+ * harness may keep its credential from its shell, so only the second must.
249
+ */
250
+ function holdsPlaceholderIn(output, placeholderEnv) {
251
+ const lines = output.split("\n");
252
+ return (
253
+ lines.some((l) => l.startsWith("ENV PATH=")) &&
254
+ lines.some((l) => l.startsWith("PROC ") && l.includes(placeholderEnv))
255
+ );
256
+ }
257
+
258
+ /**
259
+ * A network probe's line read: curl's exit code, HTTP status, seconds to
260
+ * connect and a proxy's answer to CONNECT.
261
+ */
262
+ function curlResult(text) {
263
+ const m = /^(\d+) (\d{3}) ([\d.]+) (\d{3})\s*$/.exec(text ?? "");
264
+ if (!m) return null;
265
+ const [exit, status, connect, tunnel] = m.slice(1).map(Number);
266
+ const reached = connect > 0 || status > 0 || ANSWERED.has(exit);
267
+ return { exit, status, tunnel, reached };
268
+ }
@@ -0,0 +1,305 @@
1
+ // The host's side of a live run (ADR 0031): what it plants before the harness
2
+ // starts (a repository to copy in, with executable harness config in it;
3
+ // canary files outside it; canary secrets in the runner's environment; a
4
+ // listener the sandbox must not reach) and what it reads itself afterwards
5
+ // (the sandbox's settings, markers and transcript, and its own repository and
6
+ // files). Every value is made up for the run. Node core only (ADR 0001).
7
+
8
+ import { randomBytes } from "node:crypto";
9
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
+ import { connect, createServer } from "node:net";
11
+ import { homedir, networkInterfaces, tmpdir } from "node:os";
12
+ import { dirname, join } from "node:path";
13
+ import { CONTROL_FILE, MARKER_DIR, PLANTED_ENV } from "./probes.mjs";
14
+
15
+ /** The runner variables that must never enter a sandbox, each given a canary. */
16
+ export const GITHUB_VARIABLES = Object.freeze([
17
+ "GITHUB_TOKEN",
18
+ "GH_TOKEN",
19
+ "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
20
+ "ACTIONS_ID_TOKEN_REQUEST_URL",
21
+ "ACTIONS_RUNTIME_TOKEN",
22
+ ]);
23
+
24
+ /** The outside targets the sandbox must not reach, tried from the host as the control. */
25
+ const OUTSIDE_URLS = Object.freeze(["https://example.com/", "https://1.1.1.1/"]);
26
+
27
+ /** How often the control tries each, so one dropped connection blocks no release. */
28
+ const OUTSIDE_TRIES = 3;
29
+
30
+ /** The workspace's file holding the sweep's control. */
31
+ const SWEEP_CONTROL_FILE = "agent-kit-sweep-control.txt";
32
+
33
+ const id = () => randomBytes(16).toString("hex");
34
+
35
+ /** A value that must appear nowhere: the probes look for the pattern. */
36
+ export const canary = () => `AKCANARY-${id()}`;
37
+
38
+ /** Fake credentials of each kind, shaped like real ones, each a canary. */
39
+ export const FAKE_CREDENTIAL = Object.freeze({
40
+ "api-key": () => `sk-ant-api03-${canary()}`,
41
+ subscription: () => `sk-ant-oat01-${canary()}`,
42
+ });
43
+
44
+ /** A shell command that leaves the marker `name`, for a planted config to run. */
45
+ const mark = (name) => `mkdir -p ${MARKER_DIR} && touch ${MARKER_DIR}/${name}`;
46
+
47
+ /** Claude Code hooks that each leave a marker, prefixed `from`. */
48
+ const hooks = (from) =>
49
+ Object.fromEntries(
50
+ ["SessionStart", "UserPromptSubmit", "PreToolUse", "Stop"].map((event) => [
51
+ event,
52
+ [{ hooks: [{ type: "command", command: mark(`${from}-${event}`) }] }],
53
+ ]),
54
+ );
55
+
56
+ /**
57
+ * The executable harness config planted in the checkout, by path: each entry
58
+ * runs a command, or sets a variable, if the harness loads it.
59
+ */
60
+ export function plantedConfig() {
61
+ return {
62
+ ".claude/settings.json": JSON.stringify({
63
+ env: { [PLANTED_ENV]: "1" },
64
+ enableAllProjectMcpServers: true,
65
+ apiKeyHelper: `${mark("settings-apiKeyHelper")}; echo planted`,
66
+ hooks: hooks("settings"),
67
+ }),
68
+ ".claude/settings.local.json": JSON.stringify({ hooks: hooks("local") }),
69
+ ".mcp.json": JSON.stringify({
70
+ mcpServers: { planted: { command: "sh", args: ["-c", mark("mcp-server")] } },
71
+ }),
72
+ };
73
+ }
74
+
75
+ /** The fixture repository's own files: what a Deep scan reads at the trusted ref. */
76
+ function fixtureFiles(control) {
77
+ const note = "A fixture for the live suite; nothing here is real.\n";
78
+ return {
79
+ "README.md": `# Live suite fixture\n\n${note}`,
80
+ [CONTROL_FILE]: `${control}\n`,
81
+ "CLAUDE.md": note,
82
+ ".security/scan-recipe.yml": [
83
+ "setup: []",
84
+ "registries: []",
85
+ "entry_points:",
86
+ " - command: true",
87
+ " note: A command that does nothing.",
88
+ "fixtures: []",
89
+ "notes:",
90
+ " - Nothing here is real.",
91
+ "",
92
+ ].join("\n"),
93
+ ".security/threat-model.md": `# Threat model\n\n${note}`,
94
+ ".security/findings-ledger.md": `# Findings ledger\n\n${note}`,
95
+ ".claude/skills/security-audit/SKILL.md": `# security-audit\n\n${note}`,
96
+ ".claude/skills/security-audit/DEEP.md": `# Deep\n\n${note}`,
97
+ ".claude/skills/security-audit/report-format.md": `# Report format\n\n${note}`,
98
+ ...plantedConfig(),
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Plant a run's fixtures on the host: the repository (its config committed, an
104
+ * untracked canary file and a canary in its .git/config, neither of which the
105
+ * copy-in carries), canary files in the temporary and home folders, and
106
+ * canaries in the runner's GitHub variables. The launcher's own canary is on
107
+ * its process's command line, where the workflow puts it.
108
+ * @param {{ runner: import("../exec.mjs").Runner, launcherCanary: string }} opts
109
+ */
110
+ export function plant({ runner, launcherCanary }) {
111
+ const root = mkdtempSync(join(tmpdir(), "agent-kit-live-repo-"));
112
+ const control = `AKCONTROL-${id()}`;
113
+ const write = (path, text) => {
114
+ mkdirSync(dirname(path), { recursive: true });
115
+ writeFileSync(path, text);
116
+ };
117
+ for (const [path, text] of Object.entries(fixtureFiles(control))) write(join(root, path), text);
118
+ const git = (...args) => {
119
+ const r = runner("git", [
120
+ "-C",
121
+ root,
122
+ "-c",
123
+ "user.name=agent-kit",
124
+ "-c",
125
+ "user.email=agent-kit@example.invalid",
126
+ "-c",
127
+ "commit.gpgsign=false",
128
+ ...args,
129
+ ]);
130
+ if (r.status !== 0) throw new Error(`git ${args[0]} failed: ${r.stderr}`);
131
+ return r.stdout.trim();
132
+ };
133
+ git("init", "--quiet", "--initial-branch=main");
134
+ git("add", "--all", "--force");
135
+ git("commit", "--quiet", "-m", "fixture");
136
+
137
+ // A canary-shaped value the filesystem sweep in the sandbox must find.
138
+ const sweepControl = canary();
139
+ write(join(root, SWEEP_CONTROL_FILE), `${sweepControl}\n`);
140
+ git("add", "--all", "--force", "--", SWEEP_CONTROL_FILE);
141
+ git("commit", "--quiet", "-m", "sweep control");
142
+
143
+ const canaries = { reads: [], github: [], launcher: [launcherCanary] };
144
+ const fresh = (kind) => {
145
+ const value = canary();
146
+ canaries[kind].push(value);
147
+ return value;
148
+ };
149
+ git("config", "http.https://github.com/.extraheader", `AUTHORIZATION: ${fresh("github")}`);
150
+ const name = `agent-kit-canary-${id()}`;
151
+ const hostFiles = [join(tmpdir(), name), join(homedir(), `.${name}`), join(root, name)];
152
+ for (const file of hostFiles) write(file, `${fresh("reads")}\n`);
153
+
154
+ const saved = Object.fromEntries(GITHUB_VARIABLES.map((v) => [v, process.env[v]]));
155
+ const variables = Object.fromEntries(GITHUB_VARIABLES.map((v) => [v, fresh("github")]));
156
+ Object.assign(process.env, variables);
157
+
158
+ /** Everything of the repository and the canary files that must not change. */
159
+ const state = () => ({
160
+ repo: [
161
+ git("rev-parse", "HEAD"),
162
+ git("status", "--porcelain", "--untracked-files=all"),
163
+ readFileSync(join(root, ".git", "config"), "utf8"),
164
+ readFileSync(join(root, "README.md"), "utf8"),
165
+ ].join("\0"),
166
+ files: hostFiles.map((f) => readFileSync(f, "utf8")).join("\0"),
167
+ });
168
+ const before = state();
169
+
170
+ return {
171
+ root,
172
+ commit: git("rev-parse", "HEAD"),
173
+ control,
174
+ sweepControl,
175
+ canaries,
176
+ /** The planted GitHub variables, as the runner's environment holds them. */
177
+ variables,
178
+ hostFiles,
179
+ unchanged() {
180
+ const same = (part) => {
181
+ try {
182
+ return state()[part] === before[part];
183
+ } catch {
184
+ // What can no longer be read has changed.
185
+ return false;
186
+ }
187
+ };
188
+ return { repo: same("repo"), files: same("files") };
189
+ },
190
+ remove() {
191
+ for (const [v, value] of Object.entries(saved)) {
192
+ if (value === undefined) delete process.env[v];
193
+ else process.env[v] = value;
194
+ }
195
+ for (const file of hostFiles) rmSync(file, { force: true });
196
+ rmSync(root, { recursive: true, force: true });
197
+ },
198
+ };
199
+ }
200
+
201
+ /** The host's own IPv4 addresses, apart from loopback. */
202
+ export function hostAddresses() {
203
+ return Object.values(networkInterfaces())
204
+ .flat()
205
+ .filter((i) => i && !i.internal && i.family === "IPv4")
206
+ .map((i) => i.address);
207
+ }
208
+
209
+ /**
210
+ * A listener on every address of the host, which counts what connects: the
211
+ * sandbox must never. `check` is the control, run before the sandbox exists:
212
+ * each address answers the host itself.
213
+ */
214
+ export async function listen(addresses = hostAddresses()) {
215
+ let hits = 0;
216
+ const server = createServer((socket) => {
217
+ hits += 1;
218
+ socket.on("error", () => {});
219
+ socket.destroy();
220
+ });
221
+ await new Promise((resolve, reject) => {
222
+ server.once("error", reject);
223
+ server.listen(0, "0.0.0.0", () => resolve(undefined));
224
+ });
225
+ const { port } = /** @type {import("node:net").AddressInfo} */ (server.address());
226
+ const reaches = (host) =>
227
+ new Promise((resolve) => {
228
+ const socket = connect({ host, port });
229
+ const done = (ok) => {
230
+ socket.destroy();
231
+ resolve(ok);
232
+ };
233
+ socket.setTimeout(3000, () => done(false));
234
+ // The server's end of it closes once counted.
235
+ socket.once("close", () => done(true));
236
+ socket.once("error", () => done(false));
237
+ socket.resume();
238
+ });
239
+ return {
240
+ targets: addresses.map((host) => ({ host, port })),
241
+ async check() {
242
+ const answered = await Promise.all(addresses.map(reaches));
243
+ hits = 0;
244
+ return addresses.length > 0 && answered.every(Boolean);
245
+ },
246
+ hits: () => hits,
247
+ close: () => new Promise((resolve) => server.close(() => resolve(undefined))),
248
+ };
249
+ }
250
+
251
+ /** Whether the host reaches every outside target the sandbox must not: the control. */
252
+ export async function hostReachesOutside(fetch = globalThis.fetch) {
253
+ const reaches = async (url) => {
254
+ for (let i = 0; i < OUTSIDE_TRIES; i += 1) {
255
+ try {
256
+ await fetch(url, { signal: AbortSignal.timeout(15_000), redirect: "manual" });
257
+ return true;
258
+ } catch {
259
+ // Tried again.
260
+ }
261
+ }
262
+ return false;
263
+ };
264
+ return (await Promise.all(OUTSIDE_URLS.map(reaches))).every(Boolean);
265
+ }
266
+
267
+ /**
268
+ * What the host reads of a running sandbox, before it is destroyed: its
269
+ * settings as `docker inspect` shows them, the markers a planted config left,
270
+ * and the harness's own output.
271
+ * @param {import("../exec.mjs").Runner} runner
272
+ * @param {string} container
273
+ */
274
+ export function inspectSandbox(runner, container) {
275
+ const exec = (script) => runner("docker", ["exec", container, "sh", "-c", script]);
276
+ const inspected = runner("docker", ["container", "inspect", "--format", "{{json .}}", container]);
277
+ let sandbox = null;
278
+ if (inspected.status === 0) {
279
+ const info = JSON.parse(inspected.stdout);
280
+ sandbox = {
281
+ runtime: String(info.HostConfig?.Runtime ?? ""),
282
+ privileged: info.HostConfig?.Privileged !== false,
283
+ mounts: info.Mounts ?? [],
284
+ env: info.Config?.Env ?? [],
285
+ };
286
+ }
287
+ const output = exec("cat /agent-kit/logs/agent.log /agent-kit/logs/agent.err");
288
+ return {
289
+ sandbox,
290
+ markers: markersIn(runner, container),
291
+ transcript: output.status === 0 ? output.stdout : null,
292
+ };
293
+ }
294
+
295
+ /** The markers in the sandbox, or null when they could not be listed. */
296
+ export function markersIn(runner, container) {
297
+ const r = runner("docker", [
298
+ "exec",
299
+ container,
300
+ "sh",
301
+ "-c",
302
+ `if [ -d ${MARKER_DIR} ]; then ls -1 ${MARKER_DIR}; fi`,
303
+ ]);
304
+ return r.status === 0 ? r.stdout.split("\n").filter(Boolean) : null;
305
+ }