@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
@@ -1,9 +1,89 @@
1
1
  // The Deep scan launcher's pre-flight refusals (#368): before any sandbox
2
2
  // runtime is touched, refuse a GitHub token that would reach the sandbox and
3
3
  // a .env that would be forwarded into it wholesale. Both checks read only the
4
- // launcher's own environment and the trusted ref's file list.
4
+ // launcher's own environment and the trusted ref's file list. A third
5
+ // refusal comes with the image, the first thing that can show it, and still
6
+ // before any sandbox: a musl recipe image, which cannot run the Harness
7
+ // image's glibc builds (ADR 0029). Before all of them, the Support Level
8
+ // (ADR 0028): a Deep scan runs on a pair below `tried` only as a Proving run.
5
9
 
10
+ import { appendFileSync } from "node:fs";
6
11
  import { firstLine } from "../exec.mjs";
12
+ import { harnessFacts, supportFor } from "../harness/facts.mjs";
13
+ import { MUSL_MARKER } from "../harness/install-layer.mjs";
14
+ import { ENDS_HERE, outputLines, StepFailed } from "./steps.mjs";
15
+
16
+ /**
17
+ * Throw the musl refusal when the layer build `r` failed on the musl check.
18
+ * @param {import("../exec.mjs").StartResult} r
19
+ * @param {{ image?: string, dockerfile?: string }} steps the recipe's
20
+ */
21
+ export function refuseMusl(r, { image, dockerfile }) {
22
+ if (r.status === 0) return;
23
+ if (!`${r.stdout.toString("utf8")}\n${r.stderr}`.includes(MUSL_MARKER)) return;
24
+ const what =
25
+ dockerfile !== undefined
26
+ ? `The image the recipe's ${dockerfile} builds`
27
+ : `The recipe's image ${image}`;
28
+ throw new StepFailed([
29
+ `REFUSED ${what} is musl Linux (such as Alpine), and the harness runs only on glibc Linux.`,
30
+ ...outputLines(r),
31
+ "Name a glibc image, such as a Debian or Ubuntu one, or leave image and dockerfile out to run on the Harness image.",
32
+ ENDS_HERE,
33
+ ]);
34
+ }
35
+
36
+ /**
37
+ * Whether a Deep scan may run on `harness` at the Support Level
38
+ * `cli/harnesses.json` holds for the pair, and what the run says about it:
39
+ * the line it prints and the line of the GitHub Actions run summary, for a
40
+ * refused run too, then the refusal, or the warning at `documented`. All of
41
+ * it comes from that file and the flag, nothing from the scan, so a public
42
+ * log may hold it.
43
+ * @param {{ harness?: string, provingRun?: boolean }} run
44
+ * @returns {{ line: string, summary: string, refused?: string, warning?: string }}
45
+ */
46
+ export function deepScanSupport({ harness = "claude-code", provingRun = false }) {
47
+ return stageSupport({ harness, stage: "deep-scan", provingRun });
48
+ }
49
+
50
+ /**
51
+ * The same for any Stage the Launcher runs (`security-audit`, `deep-scan`).
52
+ * A Custom harness is marked "custom, attested" where its file attests the
53
+ * pair's level, which the kit cannot check (ADR 0028).
54
+ * @param {{ harness: string, stage: string, provingRun?: boolean }} run
55
+ * @returns {{ line: string, summary: string, refused?: string, warning?: string }}
56
+ */
57
+ export function stageSupport({ harness, stage, provingRun = false }) {
58
+ const facts = harnessFacts(harness);
59
+ const found = supportFor(facts, { stage, provingRun });
60
+ const level = facts.supportLevels[stage]?.level ?? "none";
61
+ const proving = provingRun ? "yes" : "no";
62
+ const attested = level === "documented" ? "no attestation" : "attested";
63
+ const custom = facts.custom ? ` (custom, ${attested})` : "";
64
+ return {
65
+ line: `Harness: ${harness}${custom}; Support Level: ${level}; Proving run: ${proving}`,
66
+ summary: `Harness: \`${harness}\`${custom} · Support Level: \`${level}\` · Proving run: ${proving}`,
67
+ ...(found.refused !== undefined ? { refused: found.refused } : {}),
68
+ ...(found.warning !== undefined ? { warning: found.warning } : {}),
69
+ };
70
+ }
71
+
72
+ /**
73
+ * Add `line` to the GitHub Actions run summary, where `env` names one.
74
+ * @param {Record<string, string | undefined>} env
75
+ * @param {string} line
76
+ * @returns {string | null} why it could not be written, or null
77
+ */
78
+ export function writeRunSummary(env, line) {
79
+ if (!env.GITHUB_STEP_SUMMARY) return null;
80
+ try {
81
+ appendFileSync(env.GITHUB_STEP_SUMMARY, `${line}\n`);
82
+ return null;
83
+ } catch (e) {
84
+ return firstLine(e.message);
85
+ }
86
+ }
7
87
 
8
88
  /** The GitHub token variables that must never reach the sandbox. */
9
89
  export const GITHUB_TOKEN_VARS = Object.freeze(["GH_TOKEN", "GITHUB_TOKEN"]);
@@ -56,6 +56,10 @@ const CREDENTIALS = [
56
56
  [/\bgh[pousr]_[A-Za-z0-9]{20,}/, "a GitHub token"],
57
57
  [/\bgithub_pat_[A-Za-z0-9_]{20,}/, "a GitHub token"],
58
58
  [/\bsk-ant-[A-Za-z0-9_-]{10,}/, "an Anthropic API key"],
59
+ [/\bsk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{10,}/, "an OpenAI API key"],
60
+ // A legacy user key, by the marker inside it.
61
+ [/\bsk-[A-Za-z0-9_-]{0,100}T3BlbkFJ/, "an OpenAI API key"],
62
+ [/\bAIza[0-9A-Za-z_-]{35}/, "a Google API key"],
59
63
  [/\bAKIA[0-9A-Z]{16}\b/, "an AWS access key"],
60
64
  [/\bxox[abposr]-[A-Za-z0-9-]{10,}/, "a Slack token"],
61
65
  [/-----BEGIN [A-Z ]*PRIVATE KEY-----/, "a private key"],
@@ -132,15 +136,11 @@ export function validateRecipe(text) {
132
136
  if (problem) say(key, problem);
133
137
  }
134
138
 
135
- // image or dockerfile, exactly one.
139
+ // image or dockerfile, at most one: without either, the scan runs on the
140
+ // Harness image (ADR 0029).
136
141
  const hasImage = "image" in recipe;
137
142
  const hasDockerfile = "dockerfile" in recipe;
138
- if (!hasImage && !hasDockerfile) {
139
- say(
140
- "image or dockerfile",
141
- "name a base image (image) or a Dockerfile (dockerfile); the recipe has neither.",
142
- );
143
- } else if (hasImage && hasDockerfile) {
143
+ if (hasImage && hasDockerfile) {
144
144
  say("image and dockerfile", "give one of them, not both.");
145
145
  }
146
146
  if (hasImage && !isWord(recipe.image)) {
@@ -3,7 +3,7 @@
3
3
  // maintainer's other environments. The launcher chooses the runtime itself,
4
4
  // from checks made on the host (the runtimes' own CLIs and Docker's runtime
5
5
  // registry), never from a check inside the sandbox, which the target could
6
- // fake. Preference: Docker Sandboxes, then Kata or Firecracker (Linux), then
6
+ // fake. Preference: Docker Sandboxes (0.55.0 or later), then Kata or Firecracker (Linux), then
7
7
  // gVisor (Linux), the last two on Docker Engine 28.0 or later, whose
8
8
  // isolated gateway mode leaves the host no address on a sandbox network
9
9
  // (#404). A Mac uses Docker Sandboxes: Docker Desktop for macOS has no way
@@ -17,13 +17,53 @@ export const RUNTIMES_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v
17
17
 
18
18
  /** The lines every runtime refusal ends with: what is accepted, and the CI path. */
19
19
  export const ACCEPTED_LINES = Object.freeze([
20
- "Accepted runtimes: Docker Sandboxes (sbx); Kata Containers or Firecracker on Linux; gVisor (runsc) on Linux; the last two on Docker Engine 28.0 or later.",
20
+ "Accepted runtimes: Docker Sandboxes (sbx) 0.55.0 or later; Kata Containers or Firecracker on Linux; gVisor (runsc) on Linux; the last two on Docker Engine 28.0 or later.",
21
21
  "There is no override: on a host without one of them, use the CI path.",
22
22
  "CI path: the deep-scan reusable workflow runs the scan in a gVisor container on an ephemeral GitHub-hosted runner.",
23
23
  ]);
24
24
 
25
25
  const PLATFORMS = { linux: "Linux", darwin: "macOS", win32: "Windows" };
26
26
 
27
+ /**
28
+ * The oldest Docker Sandboxes deep-scan runs on. Before 0.55.0, sbx's host-side
29
+ * key injection sent a stored API key to the domains a third-party kit named,
30
+ * not the ones the developer approved (CVE-2026-136998).
31
+ */
32
+ export const MIN_SBX = Object.freeze({ major: 0, minor: 55, patch: 0 });
33
+ const MIN_SBX_TEXT = `${MIN_SBX.major}.${MIN_SBX.minor}.${MIN_SBX.patch}`;
34
+
35
+ /**
36
+ * Refusal lines when `sbx version`'s output names a version older than
37
+ * MIN_SBX or none that can be read (as in "sbx version v0.54.0 4bec4a5c"),
38
+ * else null.
39
+ * @param {string} text
40
+ * @returns {string[] | null}
41
+ */
42
+ export function sbxProblem(text) {
43
+ const m = /(?:^|\s)v?(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?/.exec(text);
44
+ const upgrade = `Upgrade Docker Sandboxes (sbx) to ${MIN_SBX_TEXT} or later, then run deep-scan again.`;
45
+ if (!m) {
46
+ return [
47
+ `Could not read the Docker Sandboxes version from \`sbx version\` (${JSON.stringify(firstLine(text))}); deep-scan runs it only on ${MIN_SBX_TEXT} or later (CVE-2026-136998).`,
48
+ upgrade,
49
+ ];
50
+ }
51
+ const [major, minor, patch] = [Number(m[1]), Number(m[2]), Number(m[3])];
52
+ // A pre-release of the minimum (0.55.0-rc.1) sorts before it (semver).
53
+ const pre = m[4];
54
+ const ok =
55
+ major !== MIN_SBX.major
56
+ ? major > MIN_SBX.major
57
+ : minor !== MIN_SBX.minor
58
+ ? minor > MIN_SBX.minor
59
+ : patch > MIN_SBX.patch || (patch === MIN_SBX.patch && !pre);
60
+ if (ok) return null;
61
+ return [
62
+ `Docker Sandboxes (sbx) ${major}.${minor}.${patch}${pre ?? ""} is older than ${MIN_SBX_TEXT}, the oldest deep-scan runs on: before ${MIN_SBX_TEXT} sbx could send a stored API key to domains the developer never approved (CVE-2026-136998).`,
63
+ upgrade,
64
+ ];
65
+ }
66
+
27
67
  /** The oldest Docker Engine deep-scan runs Kata, Firecracker or gVisor on. */
28
68
  export const MIN_DOCKER_ENGINE = Object.freeze({ major: 28, minor: 0 });
29
69
 
@@ -41,19 +81,23 @@ export function selectRuntime({ runner, platform }) {
41
81
  const host = PLATFORMS[platform] ?? platform;
42
82
  const succeeds = (cmd, args) => runner(cmd, args).status === 0;
43
83
 
44
- if (succeeds("sbx", ["version"])) {
45
- return { runtime: { id: "sbx", name: "Docker Sandboxes (sbx)" } };
84
+ const sbxVersion = runner("sbx", ["version"]);
85
+ let sbxNote = [];
86
+ if (sbxVersion.status === 0) {
87
+ const old = sbxProblem(sbxVersion.stdout.toString("utf8"));
88
+ if (old === null) return { runtime: { id: "sbx", name: "Docker Sandboxes (sbx)" } };
89
+ sbxNote = old;
46
90
  }
47
91
 
48
92
  const info = dockerInfo(runner);
49
93
  // A Mac's one accepted runtime is Docker Sandboxes: say so in every refusal.
50
94
  const mac =
51
- platform === "darwin"
95
+ platform === "darwin" && sbxNote.length === 0
52
96
  ? [
53
97
  "On macOS, deep-scan runs on Docker Sandboxes (sbx), whose per-sandbox policy lets the sandbox reach the model proxy's port alone: install it. Docker Desktop for macOS has no way to keep a container from your machine's other services.",
54
98
  ]
55
99
  : [];
56
- const refuse = (...lines) => ({ refused: [...lines, ...mac, ...ACCEPTED_LINES] });
100
+ const refuse = (...lines) => ({ refused: [...sbxNote, ...lines, ...mac, ...ACCEPTED_LINES] });
57
101
 
58
102
  if (platform === "linux" && info.ok) {
59
103
  const viaDocker = (id, label, pattern, cli) => {
@@ -77,6 +121,8 @@ export function selectRuntime({ runner, platform }) {
77
121
  `Upgrade Docker Engine to ${MIN} or later, or use Docker Sandboxes (sbx).`,
78
122
  );
79
123
  }
124
+ // An old sbx is installed: say to upgrade it, not to install one.
125
+ if (sbxNote.length) return refuse();
80
126
  const install =
81
127
  "Install one of: gVisor (runsc), Kata Containers or Firecracker, each registered as a Docker runtime, or Docker Sandboxes (sbx).";
82
128
  if (info.os === "Docker Desktop") {
@@ -91,6 +137,8 @@ export function selectRuntime({ runner, platform }) {
91
137
  );
92
138
  }
93
139
 
140
+ if (sbxNote.length) return refuse();
141
+
94
142
  if (
95
143
  platform === "win32" &&
96
144
  info.ok &&
@@ -0,0 +1,232 @@
1
+ // What every run in the Launcher's sandbox shares, a Deep scan's and a CI
2
+ // Stage's alike (ADR 0024): the driver for the chosen runtime, the phase wall
3
+ // clocks and the interrupts that stop a step, the network cut and the model
4
+ // route with their checks from the host, and the teardown on every exit path.
5
+
6
+ import { randomBytes } from "node:crypto";
7
+ import { firstLine } from "../exec.mjs";
8
+ import { adapterFor } from "../harness/adapters.mjs";
9
+ import { callerKeyFor } from "./credential.mjs";
10
+ import { dockerDriver, LABEL } from "./docker-driver.mjs";
11
+ import { LimitReached, STOPPED_EXIT, stoppedStatus, TOKENS, WALL_CLOCK } from "./limits.mjs";
12
+ import { startModelProxy } from "./model-proxy.mjs";
13
+ import { sbxDriver } from "./sbx-driver.mjs";
14
+ import { ENDS_HERE, Interrupted, StepFailed } from "./steps.mjs";
15
+
16
+ /**
17
+ * The run's clocks: a phase's wall clock, which stops only that phase's steps,
18
+ * and `stop`, which a limit seen elsewhere calls.
19
+ * @typedef {{
20
+ * begin: (name: string, minutes: number) => void,
21
+ * end: () => void,
22
+ * stop: (limit: string, detail: string) => void,
23
+ * stopped: () => { limit: string, detail: string } | null,
24
+ * signal: () => AbortSignal,
25
+ * reason: () => Error,
26
+ * }} Clocks
27
+ */
28
+
29
+ /**
30
+ * Run `body` with the sandbox driver of `runtime` and the run's clocks, then
31
+ * close the driver and tear the sandbox down, however the run ended. Returns
32
+ * `body`'s exit code, or 1 when a step failed (or teardown could not finish),
33
+ * 3 when a limit stopped the run before `body` could say, 130 or 143 when
34
+ * interrupted by SIGINT or SIGTERM.
35
+ *
36
+ * @param {{
37
+ * runner: import("../exec.mjs").Runner,
38
+ * runtime: import("./runtime.mjs").Runtime,
39
+ * plan: import("../harness/claude-code.mjs").LaunchPlan,
40
+ * signals: { on: Function, off: Function },
41
+ * timers: { setTimeout: Function, clearTimeout: Function },
42
+ * out: (s: string) => void,
43
+ * err: (s: string) => void,
44
+ * }} opts `plan`'s install layer goes on the sandbox's image.
45
+ * @param {(sandbox: { driver: import("./lifecycle.mjs").Driver, clocks: Clocks }) => Promise<number>} body
46
+ * @returns {Promise<number>}
47
+ */
48
+ export async function runInSandbox({ runner, runtime, plan, signals, timers, out, err }, body) {
49
+ const controller = new AbortController();
50
+ const { signal } = controller;
51
+ const handlers = Object.fromEntries(
52
+ ["SIGINT", "SIGTERM"].map((sig) => [
53
+ sig,
54
+ () => {
55
+ if (signal.aborted) return;
56
+ err(`Interrupted (${sig}): stopping the current step and destroying the sandbox.`);
57
+ controller.abort(sig);
58
+ },
59
+ ]),
60
+ );
61
+ for (const [sig, handler] of Object.entries(handlers)) signals.on(sig, handler);
62
+
63
+ const interrupted = () => new Interrupted(String(signal.reason ?? "SIGINT"));
64
+
65
+ // The phase clocks. A limit aborts only the phase's own controller, so the
66
+ // steps after it (the copy-out, the teardown) still run.
67
+ /** @type {{ controller: AbortController, timer: unknown } | null} */
68
+ let phase = null;
69
+ /** @type {{ limit: string, detail: string } | null} */
70
+ let stopped = null;
71
+ const stop = (limit, detail) => {
72
+ if (stopped || signal.aborted) return;
73
+ stopped = { limit, detail };
74
+ err(`${stoppedStatus(stopped)} Stopping the current step.`);
75
+ phase?.controller.abort(stopped);
76
+ };
77
+ /** @type {Clocks} */
78
+ const clocks = {
79
+ begin(name, minutes) {
80
+ const controller = new AbortController();
81
+ const timer = timers.setTimeout(
82
+ () => stop(WALL_CLOCK, `the ${name} phase's ${minutes}-minute limit`),
83
+ minutes * 60_000,
84
+ );
85
+ phase = { controller, timer };
86
+ if (stopped) controller.abort(stopped);
87
+ },
88
+ end() {
89
+ if (phase) timers.clearTimeout(phase.timer);
90
+ phase = null;
91
+ },
92
+ stop,
93
+ stopped: () => stopped,
94
+ /** The signal a step stops on: an interrupt, or its phase's limit. */
95
+ signal: () => (phase ? AbortSignal.any([signal, phase.controller.signal]) : signal),
96
+ /** What a step stopped by `clocks.signal()` throws. */
97
+ reason: () => (signal.aborted ? interrupted() : new LimitReached(stopped)),
98
+ };
99
+
100
+ /** @type {import("./docker-driver.mjs").Call} */
101
+ const call = async (cmd, args, { stdin, cwd, maxOutput, env } = {}) => {
102
+ const stepSignal = clocks.signal();
103
+ if (stepSignal.aborted) throw clocks.reason();
104
+ const r = await runner.start(cmd, args, { stdin, cwd, maxOutput, env, signal: stepSignal });
105
+ if (r.aborted || stepSignal.aborted) throw clocks.reason();
106
+ if (r.truncated) return r;
107
+ // Ctrl+C in a terminal reaches the runtime's child too, and can end it
108
+ // before the handler above runs: that is an interrupt, not a failure.
109
+ if (r.signal === "SIGINT" || r.signal === "SIGTERM") throw new Interrupted(r.signal);
110
+ return r;
111
+ };
112
+ const id = randomBytes(6).toString("hex");
113
+ const driver =
114
+ runtime.id === "sbx"
115
+ ? sbxDriver({ id, call, plan })
116
+ : dockerDriver({ runtime, id, call, plan });
117
+
118
+ let code;
119
+ let thrown = null;
120
+ try {
121
+ code = await body({ driver, clocks });
122
+ } catch (e) {
123
+ if (e instanceof LimitReached) {
124
+ // A limit before the agent step: there is no report to deliver.
125
+ out(`${stoppedStatus(e.stop)} No report came out: nothing was written, filed or posted.`);
126
+ code = STOPPED_EXIT;
127
+ } else if (e instanceof Interrupted) {
128
+ code = e.signal === "SIGTERM" ? 143 : 130;
129
+ } else if (e instanceof StepFailed) {
130
+ err(e.lines.join("\n"));
131
+ code = 1;
132
+ } else {
133
+ thrown = e;
134
+ }
135
+ }
136
+ clocks.end();
137
+ await driver.close();
138
+ const tornDown = teardown(runner, driver.teardown(), out, err);
139
+ driver.cleanup?.();
140
+ for (const [sig, handler] of Object.entries(handlers)) signals.off(sig, handler);
141
+ if (thrown) throw thrown;
142
+ return (code === 0 || code === STOPPED_EXIT) && !tornDown ? 1 : code;
143
+ }
144
+
145
+ /** Cut the sandbox's network, and check from the host that it is cut. */
146
+ export async function cutNetwork(driver, out) {
147
+ await driver.cutEgress();
148
+ const left = await driver.egressLeft();
149
+ if (left !== null) {
150
+ throw new StepFailed([`FAILED the network is not cut: ${left}.`, ENDS_HERE]);
151
+ }
152
+ out("Network: cut (checked from the host); the agent step has no network.");
153
+ }
154
+
155
+ /**
156
+ * Open the model route: the key-injecting model proxy on this machine, the
157
+ * sandbox's only way out, and the check from the host that nothing else is.
158
+ * It makes the run's caller key: the sandboxed harness holds it, and the proxy
159
+ * forwards only a request that carries it.
160
+ * @param {{
161
+ * driver: import("./lifecycle.mjs").Driver,
162
+ * clocks: Clocks,
163
+ * harness: string,
164
+ * model?: string,
165
+ * credential: string,
166
+ * credentialKind: "api-key" | "subscription",
167
+ * maxTokens: number,
168
+ * modelApi?: string,
169
+ * }} opts `modelApi` is the proxy's upstream; only tests pass another. On
170
+ * opencode, `model` picks the provider, so the profile.
171
+ * @returns the caller key, the route, and the proxy.
172
+ */
173
+ export async function openModelRoute({
174
+ driver,
175
+ clocks,
176
+ harness,
177
+ model,
178
+ credential,
179
+ credentialKind,
180
+ maxTokens,
181
+ modelApi,
182
+ }) {
183
+ const callerKey = callerKeyFor(credentialKind, harness, model);
184
+ let proxy = null;
185
+ const route = await driver.openModelRoute(async (bind) => {
186
+ proxy = await startModelProxy({
187
+ profile: adapterFor(harness)({ model }).modelRoute.profile,
188
+ credential,
189
+ kind: credentialKind,
190
+ bind,
191
+ callerKey,
192
+ maxTokens,
193
+ onCap: () => clocks.stop(TOKENS, `the run's ${maxTokens}-token cap`),
194
+ ...(modelApi !== undefined ? { upstream: modelApi } : {}),
195
+ });
196
+ return proxy;
197
+ });
198
+ const extra = await driver.egressLeft();
199
+ if (extra !== null) {
200
+ throw new StepFailed([`FAILED more than the model route is open: ${extra}.`, ENDS_HERE]);
201
+ }
202
+ // Read when asked: the driver starts the proxy while it opens the route.
203
+ return { callerKey, route, proxy };
204
+ }
205
+
206
+ /**
207
+ * Run each teardown command, whatever happened before. Synchronous, so it
208
+ * finishes even while an interrupt is pending.
209
+ * @returns {boolean} whether nothing was left behind
210
+ */
211
+ function teardown(runner, commands, out, err) {
212
+ if (!commands.length) return true;
213
+ const left = [];
214
+ for (const { what, cmd, args } of commands) {
215
+ const r = runner(cmd, args);
216
+ if (r.status !== 0 && !/no such|not found/i.test(r.stderr)) {
217
+ left.push(`${what}: ${firstLine(r.stderr) || `exit ${r.status}`}`);
218
+ }
219
+ }
220
+ if (left.length) {
221
+ err(
222
+ [
223
+ "TEARDOWN could not remove:",
224
+ ...left.map((l) => ` - ${l}`),
225
+ `Remove them by hand; every Docker resource carries the label ${LABEL}, and every sandbox's name starts with agent-kit-deep-.`,
226
+ ].join("\n"),
227
+ );
228
+ return false;
229
+ }
230
+ out(`Teardown: removed ${commands.map((c) => c.what).join(", ")}.`);
231
+ return true;
232
+ }