@mnaimfaizy/agent-kit 1.0.0-beta.13 → 1.0.0-beta.15

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.
Files changed (79) hide show
  1. package/README.md +24 -5
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +286 -0
  4. package/package.json +4 -2
  5. package/src/checks/ci-workflow.mjs +105 -0
  6. package/src/checks/claude-app.mjs +11 -2
  7. package/src/checks/custom-harness.mjs +157 -0
  8. package/src/checks/github-app.mjs +214 -0
  9. package/src/checks/review-response.mjs +54 -27
  10. package/src/checks/rulesets.mjs +9 -8
  11. package/src/checks/secrets-and-variables.mjs +220 -43
  12. package/src/checks/stages.mjs +705 -0
  13. package/src/cli.mjs +277 -31
  14. package/src/deep-scan/agent.mjs +145 -117
  15. package/src/deep-scan/credential.mjs +88 -42
  16. package/src/deep-scan/docker-driver.mjs +131 -49
  17. package/src/deep-scan/harness-text.mjs +99 -0
  18. package/src/deep-scan/lifecycle.mjs +92 -199
  19. package/src/deep-scan/limits.mjs +13 -7
  20. package/src/deep-scan/model-proxy.mjs +47 -602
  21. package/src/deep-scan/preflight.mjs +81 -1
  22. package/src/deep-scan/recipe.mjs +7 -7
  23. package/src/deep-scan/runtime.mjs +54 -6
  24. package/src/deep-scan/sandbox-run.mjs +232 -0
  25. package/src/deep-scan/sbx-driver.mjs +242 -50
  26. package/src/deep-scan/tar.mjs +69 -22
  27. package/src/deep-scan/verify.mjs +6 -1
  28. package/src/deep-scan.mjs +98 -14
  29. package/src/doctor.mjs +113 -4
  30. package/src/harness/adapters.mjs +30 -0
  31. package/src/harness/antigravity.mjs +187 -0
  32. package/src/harness/claude-code.mjs +236 -0
  33. package/src/harness/codex.mjs +219 -0
  34. package/src/harness/cursor.mjs +199 -0
  35. package/src/harness/custom/registry.mjs +21 -0
  36. package/src/harness/custom/schema.mjs +90 -0
  37. package/src/harness/custom.mjs +299 -0
  38. package/src/harness/facts.mjs +157 -0
  39. package/src/harness/gemini.mjs +164 -0
  40. package/src/harness/install-layer.mjs +141 -0
  41. package/src/harness/opencode.mjs +289 -0
  42. package/src/harness/resolve.mjs +156 -0
  43. package/src/harness/support-levels.mjs +197 -0
  44. package/src/harness-live/assess.mjs +291 -0
  45. package/src/harness-live/cursor-real.mjs +146 -0
  46. package/src/harness-live/cursor-version.mjs +70 -0
  47. package/src/harness-live/cursor.mjs +80 -0
  48. package/src/harness-live/custom.mjs +91 -0
  49. package/src/harness-live/fixture-harness.mjs +45 -0
  50. package/src/harness-live/harnesses.mjs +263 -0
  51. package/src/harness-live/host.mjs +414 -0
  52. package/src/harness-live/opencode.mjs +289 -0
  53. package/src/harness-live/probes.mjs +239 -0
  54. package/src/harness-live/run.mjs +214 -0
  55. package/src/harness-live/setup.mjs +126 -0
  56. package/src/harness-live/stage.mjs +161 -0
  57. package/src/harness-live/suite.mjs +481 -0
  58. package/src/harness-test.mjs +116 -0
  59. package/src/init.mjs +339 -23
  60. package/src/model-proxy/core.mjs +657 -0
  61. package/src/model-proxy/profiles/anthropic.mjs +241 -0
  62. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  63. package/src/model-proxy/profiles/openai.mjs +327 -0
  64. package/src/model-proxy/stub-dialects/anthropic.mjs +110 -0
  65. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  66. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  67. package/src/model-proxy/stub.mjs +182 -0
  68. package/src/stage/audit.mjs +79 -0
  69. package/src/stage/egress-route.mjs +207 -0
  70. package/src/stage/implement/carry.mjs +308 -0
  71. package/src/stage/implement/sandbox.mjs +271 -0
  72. package/src/stage/implement/verify.mjs +70 -0
  73. package/src/stage/implement.mjs +218 -0
  74. package/src/stage/plan.mjs +115 -0
  75. package/src/stage/review-response.mjs +172 -0
  76. package/src/stage/review.mjs +185 -0
  77. package/src/stage/workspace.mjs +274 -0
  78. package/src/stage.mjs +1068 -0
  79. package/src/deep-scan/claude-code.mjs +0 -25
@@ -0,0 +1,214 @@
1
+ // The live suite's entry, as .github/workflows/harness-live.yml runs it:
2
+ //
3
+ // node cli/src/harness-live/run.mjs <launcher canary> [leg]
4
+ //
5
+ // `leg` names one harness (`claude-code`, `codex`, ...) or `custom` (the fixture
6
+ // Custom harness) and runs only its scenarios, so the workflow can run the
7
+ // legs in parallel; without it every scenario runs.
8
+ //
9
+ // The argument is a made-up value, `AKCANARY-` and 32 hex digits, which puts a
10
+ // secret of the launcher's on its own command line: no sandbox may see it.
11
+ //
12
+ // Every scenario in turn, on gVisor alone (ADR 0031): Linux with `runsc`
13
+ // registered as a Docker runtime. It needs no secret. Exit 0 when every Guard
14
+ // held in every scenario, else 1. In GitHub Actions it also sets the outputs
15
+ // `guard_failed` (true when a Guard was breached or not shown held) and
16
+ // `failed` (which, as `scenario:guard` entries) after each scenario, so a run
17
+ // cut short still says what had failed, and writes the job summary.
18
+ // Everything it prints is made up for the run, so a public log may hold it.
19
+
20
+ import { appendFileSync } from "node:fs";
21
+ import { pathToFileURL } from "node:url";
22
+ import { runnerFor } from "../exec.mjs";
23
+ import { selectRuntime } from "../deep-scan/runtime.mjs";
24
+ import { cursorRefusals } from "./cursor.mjs";
25
+ import { fixtureScenarios } from "./custom.mjs";
26
+ import { runScenario, SCENARIOS } from "./suite.mjs";
27
+
28
+ /** A scenario's name as an output holds it: no space or bracket. */
29
+ const slug = (name) => name.replace(/[^A-Za-z0-9]+/g, "-").replace(/-$/, "");
30
+
31
+ /**
32
+ * The suite's results as the workflow reads them.
33
+ * @param {Array<Awaited<ReturnType<typeof runScenario>>>} results
34
+ */
35
+ export function report(results) {
36
+ const failed = results.flatMap((r) =>
37
+ r.verdict === "guard-failed"
38
+ ? [
39
+ ...r.findings.filter((f) => f.status !== "held").map((f) => `${slug(r.name)}:${f.guard}`),
40
+ // A sandbox that failed its own isolation check before any probe ran.
41
+ ...(r.findings.every((f) => f.status === "held") ? [`${slug(r.name)}:isolation`] : []),
42
+ ]
43
+ : [],
44
+ );
45
+ const summary = [
46
+ "## Harness live suite",
47
+ "",
48
+ "| Scenario | Verdict | Guards not held |",
49
+ "| --- | --- | --- |",
50
+ ...results.map((r) => {
51
+ const bad = r.findings.filter((f) => f.status !== "held");
52
+ return `| ${r.name} | ${r.verdict} | ${bad.map((f) => `${f.guard} (${f.status})`).join(", ") || "none"} |`;
53
+ }),
54
+ "",
55
+ ...results.flatMap((r) =>
56
+ (r.failedAssertions ?? []).map(({ name }) => `- ${r.name}: the ${name} assertion failed.`),
57
+ ),
58
+ ].join("\n");
59
+ return {
60
+ exit: results.length > 0 && results.every((r) => r.verdict === "pass") ? 0 : 1,
61
+ outputs: [`guard_failed=${failed.length > 0}`, `failed=${failed.join(",")}`].join("\n"),
62
+ summary,
63
+ };
64
+ }
65
+
66
+ /** One scenario's findings and, when it did not pass, everything to debug it with. */
67
+ export function describe(result) {
68
+ const lines = [
69
+ `::group::${result.name}: ${result.verdict} (exit ${result.exit})`,
70
+ ...(result.failedAssertions ?? []).map(({ name, why }) => `${name}: failed\n - ${why}`),
71
+ ...result.findings.map(
72
+ (f) => `${f.guard}: ${f.status}${f.reasons.map((r) => `\n - ${r}`).join("")}`,
73
+ ),
74
+ ];
75
+ if (result.verdict !== "pass") {
76
+ lines.push("--- the launcher's output", result.log);
77
+ for (const [guard, text] of Object.entries(result.outputs)) {
78
+ lines.push(`--- the ${guard} probe's output`, text.slice(0, 4000));
79
+ }
80
+ }
81
+ // Nothing printed from the sandbox may start a workflow command of its own.
82
+ const [open, ...rest] = lines;
83
+ return [open, ...rest.map((l) => l.replace(/^(\s*)::/gm, "$1: :")), "::endgroup::"].join("\n");
84
+ }
85
+
86
+ /** A launcher canary, as the workflow makes it. */
87
+ const LAUNCHER_CANARY = /^AKCANARY-[0-9a-f]{32}$/;
88
+
89
+ /** The scenarios of `leg`, or all of them. A harness's own scenarios, or the Custom harness's. */
90
+ export function scenariosOf(scenarios, leg) {
91
+ if (leg === undefined) return scenarios;
92
+ return scenarios.filter((s) =>
93
+ leg === "custom" ? s.harness.startsWith("custom:") : s.harness === leg,
94
+ );
95
+ }
96
+
97
+ /** The outputs and summary of `leg`'s results, written where the workflow reads them. */
98
+ function finish(results, leg) {
99
+ if (process.env.GITHUB_OUTPUT) {
100
+ const { outputs } = report(results);
101
+ const named = leg ? outputs.replace(/^(guard_failed|failed)=/gm, `$1_${leg}=`) : outputs;
102
+ appendFileSync(
103
+ process.env.GITHUB_OUTPUT,
104
+ `${named}
105
+ `,
106
+ );
107
+ }
108
+ const { exit, summary } = report(results);
109
+ console.log(summary);
110
+ if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary);
111
+ return exit;
112
+ }
113
+
114
+ async function suite(launcherCanary, leg) {
115
+ if (!LAUNCHER_CANARY.test(launcherCanary ?? "")) {
116
+ console.error("usage: run.mjs AKCANARY-<32 hex digits>, a value made up for this run.");
117
+ return 2;
118
+ }
119
+ // Cursor CLI cannot be fronted by the stub model: its leg runs the refusals,
120
+ // which start no sandbox (cursor.mjs).
121
+ if (leg === "cursor") {
122
+ const results = await cursorRefusals();
123
+ for (const r of results) console.log(describe(r));
124
+ return finish(results, leg);
125
+ }
126
+ const runner = runnerFor("deep-scan");
127
+ const choice = selectRuntime({ runner, platform: process.platform });
128
+ if ("refused" in choice || choice.runtime.id !== "gvisor") {
129
+ console.error(
130
+ [
131
+ "The live suite proves the Guards under gVisor: run it on Linux with runsc registered as a Docker runtime.",
132
+ ...("refused" in choice ? choice.refused : [`This host offers ${choice.runtime.name}.`]),
133
+ ].join("\n"),
134
+ );
135
+ return 1;
136
+ }
137
+ const scenarios = scenariosOf([...SCENARIOS, ...fixtureScenarios()], leg);
138
+ if (scenarios.length === 0) {
139
+ console.error(`No scenario belongs to the leg "${leg}".`);
140
+ return 2;
141
+ }
142
+ const results = await runScenarios(scenarios, {
143
+ runner,
144
+ runtime: choice.runtime,
145
+ launcherCanary,
146
+ out: console.log,
147
+ // The last value written for an output wins.
148
+ after(results) {
149
+ if (process.env.GITHUB_OUTPUT) {
150
+ const { outputs } = report(results);
151
+ // A leg's outputs carry its name, so the matrix's legs do not overwrite each other.
152
+ const named = leg ? outputs.replace(/^(guard_failed|failed)=/gm, `$1_${leg}=`) : outputs;
153
+ appendFileSync(process.env.GITHUB_OUTPUT, `${named}\n`);
154
+ }
155
+ },
156
+ });
157
+ const { exit, summary } = report(results);
158
+ console.log(summary);
159
+ if (process.env.GITHUB_STEP_SUMMARY) {
160
+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary);
161
+ }
162
+ return exit;
163
+ }
164
+
165
+ /**
166
+ * Every scenario in turn, printing what each showed. A scenario that throws is
167
+ * an `error` result.
168
+ * @param {ReadonlyArray<Parameters<typeof runScenario>[0]>} scenarios
169
+ * @param {{
170
+ * runner: import("../exec.mjs").Runner,
171
+ * runtime: import("../deep-scan/runtime.mjs").Runtime,
172
+ * launcherCanary: string,
173
+ * out: (s: string) => void,
174
+ * after?: (results: object[]) => void,
175
+ * platform?: string,
176
+ * scenarioRunner?: typeof runScenario,
177
+ * }} opts
178
+ */
179
+ export async function runScenarios(
180
+ scenarios,
181
+ { runner, runtime, launcherCanary, out, after, platform, scenarioRunner = runScenario },
182
+ ) {
183
+ const results = [];
184
+ for (const scenario of scenarios) {
185
+ out(`Running ${scenario.name} ...`);
186
+ let result;
187
+ try {
188
+ result = await scenarioRunner(scenario, {
189
+ runner,
190
+ launcherCanary,
191
+ runtime,
192
+ expectedRuntime: runtime.dockerRuntime,
193
+ ...(platform === undefined ? {} : { platform }),
194
+ });
195
+ } catch (e) {
196
+ result = {
197
+ name: scenario.name,
198
+ verdict: "error",
199
+ findings: [],
200
+ exit: 1,
201
+ log: e?.stack ?? String(e),
202
+ outputs: {},
203
+ };
204
+ }
205
+ results.push(result);
206
+ out(describe(result));
207
+ after?.(results);
208
+ }
209
+ return results;
210
+ }
211
+
212
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
213
+ process.exitCode = await suite(process.argv[2], process.argv[3]);
214
+ }
@@ -0,0 +1,126 @@
1
+ // The live suite's setup scenario (ADRs 0025, 0029 and 0047): the implement
2
+ // Stage on a Consumer's `sandbox_image`, with `setup_commands` that try the
3
+ // network while setup's egress is open, and leave behind what could steer the
4
+ // agent: harness config, an instruction file and a git hook outside the
5
+ // workspace, an edit to the harness's files, and a running process. The Guards
6
+ // are judged as for every scenario, and two named assertions hold that the
7
+ // registry named was reached and no other host, and that none of what setup
8
+ // left reached the agent's container while the declared path did.
9
+
10
+ /** The harness the scenario runs on: the setup is the Launcher's, not a harness's. */
11
+ export const SETUP_HARNESS = "claude-code";
12
+
13
+ /** The node preset's image, by tag, so the run resolves its digest. */
14
+ export const SETUP_IMAGE = "node:22-bookworm";
15
+
16
+ /** The one registry the scenario names. */
17
+ export const SETUP_REGISTRY = "registry.npmjs.org";
18
+
19
+ /** The path the scenario declares in `--setup-paths`, which must cross. */
20
+ export const SETUP_PATH = "/root/.cache/agent-kit-carried";
21
+
22
+ /**
23
+ * The word setup writes into everything it leaves, as its parts: a script
24
+ * builds it at run time, so no script's text holds it whole. A harness keeps
25
+ * its tool calls in its own files, and those would match.
26
+ */
27
+ const LEFT = ["SETUP", "LEFT", "MARK"];
28
+
29
+ /** The word, as `sh` builds it from its quoted parts. */
30
+ const BUILD_LEFT = `m=${LEFT.map((w) => `"${w}"`).join("-")}`;
31
+
32
+ /** The sleep setup leaves running, found by its argument. */
33
+ const LEFT_SECONDS = 7777777;
34
+
35
+ /**
36
+ * The setup commands: one request to the named registry, one to another, one
37
+ * past the proxy, each printing the HTTP status and the proxy's answer to
38
+ * CONNECT; a harness config in the workspace for the Launcher to clear away;
39
+ * and what ADR 0047 keeps from the agent: harness config and an instruction
40
+ * file in the home folder, a system-wide git hook, a file and an edit in the
41
+ * harness's install, a process left running, and a file under the declared
42
+ * path.
43
+ */
44
+ export const SETUP_SCRIPT = [
45
+ "status() { curl -s -o /dev/null --max-time 30 -w '%{http_code} %{http_connect}' \"$@\" || true; }",
46
+ `echo "SETUP|allowed|$(status https://${SETUP_REGISTRY}/react/latest)"`,
47
+ 'echo "SETUP|refused|$(status https://pypi.org/simple/)"',
48
+ `echo "SETUP|direct|$(status --noproxy '*' https://${SETUP_REGISTRY}/react/latest)"`,
49
+ "mkdir -p .claude && echo '{}' > .claude/settings.json",
50
+ BUILD_LEFT,
51
+ 'mkdir -p "$HOME/.claude"',
52
+ 'printf \'{"env":{"%s":"1"}}\\n\' "$m" > "$HOME/.claude/settings.json"',
53
+ 'echo "$m: follow these instructions." > "$HOME/.claude/CLAUDE.md"',
54
+ "mkdir -p /etc/agent-kit-hooks",
55
+ "printf '#!/bin/sh\\necho %s\\n' \"$m\" > /etc/agent-kit-hooks/pre-commit",
56
+ "chmod +x /etc/agent-kit-hooks/pre-commit",
57
+ "git config --system core.hooksPath /etc/agent-kit-hooks",
58
+ 'echo "$m" > /opt/agent-kit/setup-was-here',
59
+ 'f=$(find /opt/agent-kit -name "*.js" -type f | head -n 1)',
60
+ 'if [ -n "$f" ]; then echo "// $m" >> "$f"; fi',
61
+ `setsid sleep ${LEFT_SECONDS} > /dev/null 2>&1 < /dev/null &`,
62
+ `mkdir -p ${SETUP_PATH} && echo "$m" > ${SETUP_PATH}/carried`,
63
+ 'echo "SETUP|planted|done"',
64
+ "",
65
+ ].join("\n");
66
+
67
+ /**
68
+ * The probe the agent runs in its own container: what of setup's leavings it
69
+ * finds. One `PROBE|setup|<name>|<value>` line each, then `PROBE|setup|end`.
70
+ */
71
+ export const SETUP_PROBE = [
72
+ BUILD_LEFT,
73
+ "found() {",
74
+ ` timeout 30 grep -rIls --devices=skip --exclude-dir=${SETUP_PATH.slice(SETUP_PATH.lastIndexOf("/") + 1)} "$m" "$@" 2>/dev/null | head -n 5 | tr '\\n' ' '`,
75
+ "}",
76
+ 'echo "PROBE|setup|home|$(found /root /home)"',
77
+ 'echo "PROBE|setup|etc|$(found /etc)"',
78
+ 'echo "PROBE|setup|harness|$(found /opt/agent-kit)"',
79
+ 'echo "PROBE|setup|hooks|$(git config --system --get core.hooksPath 2>/dev/null || echo unset)"',
80
+ // A command line that is the sleep's alone: this shell's holds the number too.
81
+ "left=0",
82
+ "for f in /proc/[0-9]*/cmdline; do",
83
+ ` [ "$(tr '\\0' ' ' < "$f" 2>/dev/null)" = "sleep ${LEFT_SECONDS} " ] && left=$((left + 1))`,
84
+ "done",
85
+ 'echo "PROBE|setup|process|$left"',
86
+ `echo "PROBE|setup|declared|$(cat ${SETUP_PATH}/carried 2>/dev/null || echo absent)"`,
87
+ 'echo "PROBE|setup|end"',
88
+ ].join("\n");
89
+
90
+ /** @type {Readonly<import("./harnesses.mjs").NamedAssertion>} */
91
+ export const SETUP_REACHES_ITS_REGISTRY_ALONE = Object.freeze({
92
+ name: "setup reaches the named registry alone",
93
+ check({ launcherOutput }) {
94
+ const seen = (probe) => new RegExp(`^SETUP\\|${probe}\\|(.*)$`, "m").exec(launcherOutput)?.[1];
95
+ const wanted = [
96
+ ["allowed", "200 200", "the named registry was not reached"],
97
+ ["refused", "000 403", "the proxy did not refuse another host"],
98
+ ["direct", "000 000", "a request past the proxy got through"],
99
+ ];
100
+ const failed = wanted.find(([probe, answer]) => seen(probe) !== answer);
101
+ return failed ? `${failed[2]} (saw ${seen(failed[0]) ?? "nothing"})` : null;
102
+ },
103
+ });
104
+
105
+ /** @type {Readonly<import("./harnesses.mjs").NamedAssertion>} */
106
+ export const SETUP_LEAVES_THE_AGENT_ALONE = Object.freeze({
107
+ name: "nothing setup left outside the workspace reaches the agent but the declared path",
108
+ check({ launcherOutput, outputs = {} }) {
109
+ if (!/^SETUP\|planted\|done$/m.test(launcherOutput))
110
+ return "setup did not plant what it leaves";
111
+ const output = outputs.setup ?? "";
112
+ if (!output.includes("PROBE|setup|end")) return "the setup probe did not finish";
113
+ const seen = (name) =>
114
+ new RegExp(`^PROBE\\|setup\\|${name}\\|(.*)$`, "m").exec(output)?.[1].trim();
115
+ const wanted = [
116
+ ["home", "", "setup's harness config or instruction file reached the agent's home"],
117
+ ["etc", "", "setup's system git hook reached the agent"],
118
+ ["harness", "", "setup's edit to the harness's files reached the agent"],
119
+ ["hooks", "unset", "setup's git hooksPath reached the agent"],
120
+ ["process", "0", "a process setup left runs beside the agent"],
121
+ ["declared", LEFT.join("-"), "the declared setup path did not reach the agent"],
122
+ ];
123
+ const failed = wanted.find(([name, answer]) => seen(name) !== answer);
124
+ return failed ? `${failed[2]} (saw ${JSON.stringify(seen(failed[0]) ?? null)})` : null;
125
+ },
126
+ });
@@ -0,0 +1,161 @@
1
+ // A read-only Stage as the live suite runs it (ADR 0031): the pinned harness,
2
+ // by its adapter's launch plan, in the Deep scan's sandbox driver, behind the
3
+ // real model proxy, handed a brief, with one result file copied out.
4
+ //
5
+ // The CI Stages the kit runs enter through `agent-kit stage` itself
6
+ // (suite.mjs). This composes the same driver, adapter, agent script and proxy
7
+ // for the checkout-config control beside them, and nothing here ships to a
8
+ // Consumer's run. The checkout's config is kept out
9
+ // as the adapter's launch plan says: by its launch, and where the plan says so
10
+ // by removing it from the copy.
11
+
12
+ import { randomBytes } from "node:crypto";
13
+ import { writeFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { agentScript, BRIEF_PATH } from "../deep-scan/agent.mjs";
16
+ import { callerKeyFor, withoutCredentials } from "../deep-scan/credential.mjs";
17
+ import { dockerDriver } from "../deep-scan/docker-driver.mjs";
18
+ import { StepFailed } from "../deep-scan/steps.mjs";
19
+ import { tarOf } from "../deep-scan/tar.mjs";
20
+ import { adapterFor } from "../harness/adapters.mjs";
21
+ import { startModelProxy } from "../deep-scan/model-proxy.mjs";
22
+
23
+ /** Where the Stage's result goes in the sandbox. */
24
+ export const STAGE_RESULT_PATH = "/agent-kit/out/result.md";
25
+
26
+ /** The longest a Stage's run may take. */
27
+ const TIMEOUT_MS = 20 * 60_000;
28
+
29
+ const MAX_RESULT = 10 * 1024 * 1024;
30
+
31
+ /** The harness's turn limit and the proxy's token cap, far above what the script needs. */
32
+ const MAX_TURNS = 40;
33
+ const MAX_TOKENS = 20_000_000;
34
+
35
+ /**
36
+ * Run the Stage. Returns 0 when the harness exited cleanly and its result came
37
+ * out, else 1. Every sandbox resource is removed on the way out.
38
+ * @param {{
39
+ * runner: import("../exec.mjs").Runner,
40
+ * runtime: import("../deep-scan/runtime.mjs").Runtime,
41
+ * root: string,
42
+ * commit: string,
43
+ * harness?: string,
44
+ * credential: string,
45
+ * credentialKind: "api-key" | "subscription",
46
+ * model?: string,
47
+ * modelApi: string,
48
+ * outDir: string,
49
+ * beforeAgent?: (container: string, launch: { env: string[], url: string, plan: import("../harness/claude-code.mjs").LaunchPlan }) => Promise<void>,
50
+ * beforeTeardown: (container: string, launch: { env: string[], url: string, plan: import("../harness/claude-code.mjs").LaunchPlan }) => Promise<void>,
51
+ * out: (s: string) => void,
52
+ * err: (s: string) => void,
53
+ * }} opts `modelApi` is the proxy's upstream: here, the stub model.
54
+ * `outDir` receives what is copied out. `beforeTeardown` reads the sandbox
55
+ * after the harness ran.
56
+ */
57
+ export async function runReadOnlyStage({
58
+ runner: hostRunner,
59
+ runtime,
60
+ root,
61
+ commit,
62
+ harness = "claude-code",
63
+ credential,
64
+ credentialKind,
65
+ model,
66
+ modelApi,
67
+ outDir,
68
+ beforeAgent = async () => {},
69
+ beforeTeardown,
70
+ out,
71
+ err,
72
+ }) {
73
+ // No command of the launcher's inherits the model credential.
74
+ const runner = withoutCredentials(hostRunner, [process.env]);
75
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
76
+ const call = (cmd, args, opts = {}) => runner.start(cmd, args, { ...opts, signal });
77
+ const id = randomBytes(6).toString("hex");
78
+ const request = { stage: "review", credentialKind, model };
79
+ const adapter = adapterFor(harness);
80
+ const driver = dockerDriver({ runtime, id, call, plan: adapter(request) });
81
+ const steps = { setup: [], start: [], ready: [], seed: [], registries: [], grounding: [] };
82
+ const must = (condition, why) => {
83
+ if (!condition) throw new StepFailed([`FAILED ${why}.`]);
84
+ };
85
+ let proxy = null;
86
+ try {
87
+ await driver.prepare(steps, { out, branch: "main", short: commit.slice(0, 12) });
88
+ await driver.start(steps);
89
+ const archive = runner(
90
+ "git",
91
+ ["-c", "core.autocrlf=false", "-C", root, "archive", "--prefix=workspace/", commit],
92
+ { encoding: "buffer" },
93
+ );
94
+ must(archive.status === 0, `exporting the repository: ${archive.stderr}`);
95
+ await driver.copyIn(archive.stdout, "copying the repository in");
96
+ await driver.cutEgress();
97
+ const left = await driver.egressLeft();
98
+ must(left === null, `the network is not cut: ${left}`);
99
+ const callerKey = callerKeyFor(credentialKind, harness, model);
100
+ const route = await driver.openModelRoute(async (bind) => {
101
+ proxy = await startModelProxy({
102
+ profile: adapter(request).modelRoute.profile,
103
+ credential,
104
+ kind: credentialKind,
105
+ bind,
106
+ callerKey,
107
+ upstream: modelApi,
108
+ maxTokens: MAX_TOKENS,
109
+ });
110
+ return proxy;
111
+ });
112
+ const extra = await driver.egressLeft();
113
+ must(extra === null, `more than the model route is open: ${extra}`);
114
+ const brief = `# Stage brief\n\nThis Stage is read-only. Write your result to ${STAGE_RESULT_PATH}.\n`;
115
+ await driver.copyIn(
116
+ tarOf([
117
+ { path: "agent-kit", dir: true },
118
+ { path: "agent-kit/in", dir: true },
119
+ { path: BRIEF_PATH.slice(1), data: Buffer.from(brief, "utf8") },
120
+ ]),
121
+ "copying the brief in",
122
+ );
123
+ const plan = adapter({
124
+ ...request,
125
+ proxyUrl: route.url,
126
+ briefPath: BRIEF_PATH,
127
+ kitDir: "/agent-kit",
128
+ maxTurns: MAX_TURNS,
129
+ callerKey,
130
+ });
131
+ out(`Agent step: ${plan.identity.displayName} ${plan.identity.version}, a read-only Stage.`);
132
+ const launch = { env: plan.launch.env, url: route.url, plan };
133
+ await beforeAgent(driver.container, launch);
134
+ const agent = await driver.exec(
135
+ agentScript({ plan, report: STAGE_RESULT_PATH, workspace: "/workspace" }),
136
+ { env: plan.launch.env },
137
+ );
138
+ if (agent.status !== 0) err(`The agent step exited ${agent.status}:\n${agent.stderr}`);
139
+ await beforeTeardown(driver.container, launch);
140
+ const file = await driver.copyOut(STAGE_RESULT_PATH, { maxBytes: MAX_RESULT });
141
+ if (!("data" in file)) {
142
+ err("FAILED no result came out.");
143
+ return 1;
144
+ }
145
+ writeFileSync(join(outDir, file.name), file.data, { mode: 0o600, flag: "wx" });
146
+ return agent.status === 0 ? 0 : 1;
147
+ } catch (e) {
148
+ if (!(e instanceof StepFailed)) throw e;
149
+ err(e.lines.join("\n"));
150
+ return 1;
151
+ } finally {
152
+ out(`Model proxy: ${proxy?.summary() ?? "not started"}.`);
153
+ await driver.close();
154
+ for (const { what, cmd, args } of driver.teardown()) {
155
+ const r = hostRunner(cmd, args);
156
+ if (r.status !== 0 && !/no such|not found/i.test(r.stderr)) {
157
+ err(`TEARDOWN could not remove ${what}: ${r.stderr}`);
158
+ }
159
+ }
160
+ }
161
+ }