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

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 (180) hide show
  1. package/README.md +22 -4
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +244 -6
  4. package/package.json +3 -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/rulesets.mjs +9 -8
  10. package/src/checks/secrets-and-variables.mjs +27 -8
  11. package/src/checks/stages.mjs +705 -0
  12. package/src/cli.mjs +583 -36
  13. package/src/deep-scan/agent.mjs +88 -21
  14. package/src/deep-scan/credential.mjs +81 -32
  15. package/src/deep-scan/docker-driver.mjs +105 -42
  16. package/src/deep-scan/harness-text.mjs +99 -0
  17. package/src/deep-scan/lifecycle.mjs +68 -178
  18. package/src/deep-scan/limits.mjs +13 -7
  19. package/src/deep-scan/model-proxy.mjs +21 -10
  20. package/src/deep-scan/preflight.mjs +19 -6
  21. package/src/deep-scan/recipe.mjs +4 -0
  22. package/src/deep-scan/runtime.mjs +54 -6
  23. package/src/deep-scan/sandbox-run.mjs +232 -0
  24. package/src/deep-scan/sbx-driver.mjs +224 -39
  25. package/src/deep-scan/tar.mjs +69 -22
  26. package/src/deep-scan/verify.mjs +6 -1
  27. package/src/deep-scan.mjs +73 -13
  28. package/src/doctor.mjs +166 -5
  29. package/src/exec.mjs +14 -5
  30. package/src/factory/budget/budget.mjs +259 -0
  31. package/src/factory/build/command.mjs +321 -0
  32. package/src/factory/build/factory.mjs +473 -0
  33. package/src/factory/build/findings.mjs +55 -0
  34. package/src/factory/build/host.mjs +230 -0
  35. package/src/factory/build/notes.mjs +191 -0
  36. package/src/factory/build/pull-request.mjs +74 -0
  37. package/src/factory/bundle.mjs +146 -0
  38. package/src/factory/checks/allowed-paths.mjs +50 -0
  39. package/src/factory/checks/plan-header.mjs +296 -0
  40. package/src/factory/checks/qa.mjs +85 -0
  41. package/src/factory/checks/review.mjs +73 -0
  42. package/src/factory/checks/security.mjs +50 -0
  43. package/src/factory/checks/stage-check.mjs +89 -0
  44. package/src/factory/claims/command.mjs +187 -0
  45. package/src/factory/claims/release.mjs +111 -0
  46. package/src/factory/decision/answers.mjs +103 -0
  47. package/src/factory/decision/command.mjs +64 -0
  48. package/src/factory/decision/plan.mjs +99 -0
  49. package/src/factory/decision/request.mjs +116 -0
  50. package/src/factory/doctor/files.mjs +329 -0
  51. package/src/factory/doctor/index.mjs +56 -0
  52. package/src/factory/doctor/local.mjs +497 -0
  53. package/src/factory/doctor/orchestrate.mjs +146 -0
  54. package/src/factory/engine/lease.mjs +146 -0
  55. package/src/factory/engine/local-engine.mjs +177 -0
  56. package/src/factory/engine/lockfile.mjs +64 -0
  57. package/src/factory/engine/workflow-engine.mjs +124 -0
  58. package/src/factory/gate/comment.mjs +88 -0
  59. package/src/factory/gate/config.mjs +57 -0
  60. package/src/factory/gate/gate-core.mjs +250 -0
  61. package/src/factory/gate/guarded.mjs +17 -0
  62. package/src/factory/gate/reads.mjs +105 -0
  63. package/src/factory/gate/task.mjs +193 -0
  64. package/src/factory/gate/trip-reads.mjs +82 -0
  65. package/src/factory/gate/trip.mjs +87 -0
  66. package/src/factory/init/blueprint.mjs +174 -0
  67. package/src/factory/init/index.mjs +337 -0
  68. package/src/factory/labels/evidence.mjs +162 -0
  69. package/src/factory/labels/moves.mjs +32 -0
  70. package/src/factory/labels/reconcile.mjs +267 -0
  71. package/src/factory/labels/revert.mjs +87 -0
  72. package/src/factory/labels/timeline.mjs +72 -0
  73. package/src/factory/labels/voided.mjs +59 -0
  74. package/src/factory/limits/harness.mjs +39 -0
  75. package/src/factory/limits/limits.mjs +123 -0
  76. package/src/factory/merge/command.mjs +172 -0
  77. package/src/factory/outbox/check.mjs +240 -0
  78. package/src/factory/outbox/rulings.mjs +195 -0
  79. package/src/factory/plan/command.mjs +66 -0
  80. package/src/factory/plan/comment.mjs +156 -0
  81. package/src/factory/plan/publish.mjs +149 -0
  82. package/src/factory/plan/risk.mjs +153 -0
  83. package/src/factory/qa/command.mjs +163 -0
  84. package/src/factory/records/engine-record.mjs +133 -0
  85. package/src/factory/records/main.mjs +96 -0
  86. package/src/factory/records/record.mjs +226 -0
  87. package/src/factory/records/sink.mjs +57 -0
  88. package/src/factory/report/build.mjs +92 -0
  89. package/src/factory/report/command.mjs +80 -0
  90. package/src/factory/report/facts.mjs +226 -0
  91. package/src/factory/report/gate-section.mjs +122 -0
  92. package/src/factory/report/metrics.mjs +111 -0
  93. package/src/factory/report/reads.mjs +246 -0
  94. package/src/factory/report/render.mjs +121 -0
  95. package/src/factory/report/rollout.mjs +154 -0
  96. package/src/factory/review/command.mjs +182 -0
  97. package/src/factory/run/awake.mjs +70 -0
  98. package/src/factory/run/collect.mjs +77 -0
  99. package/src/factory/run/command.mjs +490 -0
  100. package/src/factory/run/gh.mjs +46 -0
  101. package/src/factory/run/launch.mjs +47 -0
  102. package/src/factory/run/pipelines.mjs +261 -0
  103. package/src/factory/run/raw.mjs +96 -0
  104. package/src/factory/run/restart.mjs +83 -0
  105. package/src/factory/run/s3.mjs +193 -0
  106. package/src/factory/run/secrets.mjs +142 -0
  107. package/src/factory/run/teardown.mjs +242 -0
  108. package/src/factory/run/token.mjs +68 -0
  109. package/src/factory/security/command.mjs +157 -0
  110. package/src/factory/setup/app.mjs +122 -0
  111. package/src/factory/setup/command.mjs +409 -0
  112. package/src/factory/setup/labels.mjs +25 -0
  113. package/src/factory/setup/reads.mjs +129 -0
  114. package/src/factory/setup/writes.mjs +126 -0
  115. package/src/factory/snapshot/write.mjs +176 -0
  116. package/src/factory/stop/command.mjs +136 -0
  117. package/src/factory/sweep/actions-main.mjs +117 -0
  118. package/src/factory/sweep/command.mjs +65 -0
  119. package/src/factory/sweep/knobs.mjs +78 -0
  120. package/src/factory/sweep/marker-version.mjs +15 -0
  121. package/src/factory/sweep/markers.mjs +112 -0
  122. package/src/factory/sweep/overlap.mjs +24 -0
  123. package/src/factory/sweep/run.mjs +198 -0
  124. package/src/factory/sweep/shell.mjs +394 -0
  125. package/src/factory/sweep/split.mjs +104 -0
  126. package/src/factory/sweep/states.mjs +87 -0
  127. package/src/factory/sweep/sweep-core.mjs +1781 -0
  128. package/src/factory/tracker/github.mjs +674 -0
  129. package/src/factory/tracker/operations.mjs +153 -0
  130. package/src/factory/upgrade/index.mjs +83 -0
  131. package/src/harness/adapters.mjs +30 -0
  132. package/src/harness/antigravity.mjs +187 -0
  133. package/src/harness/claude-code.mjs +8 -1
  134. package/src/harness/codex.mjs +219 -0
  135. package/src/harness/cursor.mjs +199 -0
  136. package/src/harness/custom/registry.mjs +21 -0
  137. package/src/harness/custom/schema.mjs +90 -0
  138. package/src/harness/custom.mjs +299 -0
  139. package/src/harness/facts.mjs +44 -7
  140. package/src/harness/gemini.mjs +164 -0
  141. package/src/harness/install-layer.mjs +86 -3
  142. package/src/harness/opencode.mjs +289 -0
  143. package/src/harness/resolve.mjs +156 -0
  144. package/src/harness/support-levels.mjs +151 -3
  145. package/src/harness-live/assess.mjs +29 -6
  146. package/src/harness-live/cursor-real.mjs +146 -0
  147. package/src/harness-live/cursor-version.mjs +70 -0
  148. package/src/harness-live/cursor.mjs +80 -0
  149. package/src/harness-live/custom.mjs +91 -0
  150. package/src/harness-live/fixture-harness.mjs +45 -0
  151. package/src/harness-live/harnesses.mjs +263 -0
  152. package/src/harness-live/host.mjs +113 -4
  153. package/src/harness-live/opencode.mjs +289 -0
  154. package/src/harness-live/probes.mjs +87 -7
  155. package/src/harness-live/run.mjs +101 -20
  156. package/src/harness-live/setup.mjs +126 -0
  157. package/src/harness-live/stage.mjs +25 -15
  158. package/src/harness-live/suite.mjs +276 -95
  159. package/src/harness-test.mjs +116 -0
  160. package/src/init.mjs +374 -36
  161. package/src/kit-owned-paths.mjs +1 -1
  162. package/src/model-proxy/core.mjs +128 -20
  163. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  164. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  165. package/src/model-proxy/profiles/openai.mjs +327 -0
  166. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  167. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  168. package/src/model-proxy/stub.mjs +9 -1
  169. package/src/stage/audit.mjs +79 -0
  170. package/src/stage/egress-route.mjs +207 -0
  171. package/src/stage/implement/carry.mjs +308 -0
  172. package/src/stage/implement/sandbox.mjs +271 -0
  173. package/src/stage/implement/verify.mjs +70 -0
  174. package/src/stage/implement.mjs +218 -0
  175. package/src/stage/plan.mjs +115 -0
  176. package/src/stage/review-response.mjs +172 -0
  177. package/src/stage/review.mjs +185 -0
  178. package/src/stage/workspace.mjs +274 -0
  179. package/src/stage.mjs +1087 -0
  180. package/src/upgrade.mjs +39 -7
@@ -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
+ }
@@ -14,7 +14,7 @@
14
14
  // starts, and a plain image has no /home/agent, so `-t <plain image>` never
15
15
  // starts (#375's diagnosis, run evidence d375-sbx-diag.txt). The human chose
16
16
  // (#375, option 1): Docker on the host pulls the recipe's image and layers
17
- // on it the Docker driver's pinned Claude Code (copied from the Harness
17
+ // on it the Docker driver's pinned harness (copied from the Harness
18
18
  // image, ADR 0029; a recipe with no image gets the Harness image itself as
19
19
  // the base) and what Docker's docs require of a template image (TEMPLATE_LAYER: a non-root `agent`, uid
20
20
  // 1000, home /home/agent, as its USER; curl, git, CA certificates and
@@ -23,6 +23,10 @@
23
23
  // the template and the layered image. Only the pull and that fixed layer run
24
24
  // on the host's Docker (Docker Desktop, the WSL 2 boundary a scan refuses),
25
25
  // never a Consumer's own build steps, so a `dockerfile` recipe is refused.
26
+ // A Custom harness (#472) has no Harness image: its template is the recipe's
27
+ // image, or the full Node image, with its path alone added, and its npm
28
+ // package is installed with `sbx exec` once the sandbox starts, before
29
+ // anything is copied in, with a rule for the npm registry alone.
26
30
  // - Setup egress: `sbx policy allow network --sandbox` for each registry
27
31
  // (986-987), removed with `sbx policy rm network --sandbox --resource` for
28
32
  // the cut (1148, 1179-1180); `sbx policy ls <sandbox> --json` (812, 822)
@@ -43,8 +47,15 @@ import { lstatSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSyn
43
47
  import { tmpdir } from "node:os";
44
48
  import { join } from "node:path";
45
49
  import { firstLine } from "../exec.mjs";
46
- import { layerDockerfile, pinnedHarnessImage } from "../harness/install-layer.mjs";
47
- import { LABEL } from "./docker-driver.mjs";
50
+ import {
51
+ CUSTOM_SANDBOX_BASE,
52
+ layerDockerfile,
53
+ NPM_REGISTRY,
54
+ pinnedHarnessImage,
55
+ sandboxNpmInstall,
56
+ sandboxNpmLayer,
57
+ } from "../harness/install-layer.mjs";
58
+ import { envArgs, LABEL } from "./docker-driver.mjs";
48
59
  import { allowlistOf } from "./egress.mjs";
49
60
  import { refuseMusl } from "./preflight.mjs";
50
61
  import { imageDigestNote } from "./recipe.mjs";
@@ -105,6 +116,87 @@ export function globalPolicyProblem(r) {
105
116
  ];
106
117
  }
107
118
 
119
+ /**
120
+ * Why the Consumer's global sbx secrets stop a scan, as refusal lines, or null
121
+ * when there are none. From `sbx secret ls --global --json`: passes only when
122
+ * `secrets`, `custom_secrets` and `shadowed_services` are all empty lists and
123
+ * `env_only_count` is 0. Any other value is refused, all kinds found in one
124
+ * refusal; so is a missing field or one of the wrong type. sbx's host proxy injects a global secret
125
+ * into any sandbox's requests to the matching service's domains, so a scan's
126
+ * setup could send the Consumer's real key to a registry it is allowed to
127
+ * reach (CVE-2026-136998 is the same class). Only service names are read:
128
+ * never a value. Output that cannot be read is a refusal.
129
+ * @param {import("../exec.mjs").StartResult} r
130
+ * @returns {string[] | null}
131
+ */
132
+ export function globalSecretsProblem(r) {
133
+ const fix = [
134
+ "deep-scan never changes your sbx secrets. Move each to one sandbox with `sbx secret set <service> --sandbox <name>`, or remove it with `sbx secret rm <service>`.",
135
+ ];
136
+ if (r.status !== 0) {
137
+ return [
138
+ `REFUSED Could not read the Docker Sandboxes global secrets: ${firstLine(r.stderr) || `exit ${r.status}`}`,
139
+ ];
140
+ }
141
+ let parsed;
142
+ try {
143
+ parsed = JSON.parse(r.stdout.toString("utf8"));
144
+ } catch {
145
+ parsed = null;
146
+ }
147
+ if (
148
+ !parsed ||
149
+ typeof parsed !== "object" ||
150
+ !Array.isArray(parsed.secrets) ||
151
+ !Array.isArray(parsed.custom_secrets) ||
152
+ !Array.isArray(parsed.shadowed_services) ||
153
+ !Number.isInteger(parsed.env_only_count) ||
154
+ parsed.env_only_count < 0
155
+ ) {
156
+ return [
157
+ "REFUSED Could not read the Docker Sandboxes global secrets: `sbx secret ls --global --json` did not give secrets, custom_secrets, shadowed_services and env_only_count.",
158
+ ];
159
+ }
160
+ const entries = [...parsed.secrets, ...parsed.custom_secrets];
161
+ const safe = (v) => (typeof v === "string" && /^[\w.:*@/-]{1,100}$/.test(v) ? v : "(unnamed)");
162
+ const shadowed = [...new Set(parsed.shadowed_services.map(safe))];
163
+ const envOnly = parsed.env_only_count;
164
+ if (entries.length === 0 && shadowed.length === 0 && envOnly === 0) return null;
165
+ // What shadowed_services and env_only_count mean is not documented by sbx,
166
+ // so a non-empty one fails closed. Every kind found is reported at once, each
167
+ // with its own fix, so fixing one does not meet a different refusal next.
168
+ const names = [
169
+ ...new Set(
170
+ entries.map((e) => {
171
+ const o = e && typeof e === "object" ? e : {};
172
+ for (const k of ["service", "name", "registry", "host", "env_name"]) {
173
+ if (safe(o[k]) !== "(unnamed)") return o[k];
174
+ }
175
+ return "(unnamed)";
176
+ }),
177
+ ),
178
+ ];
179
+ return [
180
+ "REFUSED Docker Sandboxes holds credentials its proxy may inject into any sandbox's requests to their services' domains, so a scan's setup could send your real key to a registry it may reach (CVE-2026-136998 is the same class).",
181
+ ...(entries.length
182
+ ? [`Global secrets: ${names.join(", ")} (values are never read or printed).`, ...fix]
183
+ : []),
184
+ ...(shadowed.length
185
+ ? [
186
+ `Shadowed services: ${shadowed.join(", ")}.`,
187
+ "Fix: run `sbx secret ls --global` to see them and remove each with `sbx secret rm <service>`.",
188
+ ]
189
+ : []),
190
+ ...(envOnly > 0
191
+ ? [
192
+ `Credentials taken from the host environment: ${envOnly} (values are never read or printed).`,
193
+ "Fix: unset the API key variables (such as GITHUB_TOKEN or OPENAI_API_KEY) that sbx reads from the environment you run deep-scan in. deep-scan never changes your environment.",
194
+ ]
195
+ : []),
196
+ "Then run deep-scan again.",
197
+ ];
198
+ }
199
+
108
200
  /** The rules list of `sbx policy ls --json`, or null. */
109
201
  function rulesOf(r) {
110
202
  try {
@@ -165,23 +257,47 @@ export function sbxDriver({ id, call, plan }) {
165
257
  );
166
258
  allowed.splice(allowed.indexOf(list), 1);
167
259
  };
168
- const exec = (script, { env = [], workdir = "/workspace", user } = {}) =>
169
- sbx([
170
- "exec",
171
- ...(user ? ["-u", user] : []),
172
- ...env.flatMap((v) => ["-e", v]),
173
- ...(workdir ? ["-w", workdir] : []),
174
- name,
175
- "sh",
176
- "-c",
177
- script,
178
- ]);
260
+ const exec = (script, { env = [], workdir = "/workspace", user } = {}) => {
261
+ const { args, childEnv } = envArgs(env, plan.launch?.secretEnv ?? [], "-e");
262
+ return sbx(
263
+ [
264
+ "exec",
265
+ ...(user ? ["-u", user] : []),
266
+ ...args,
267
+ ...(workdir ? ["-w", workdir] : []),
268
+ name,
269
+ "sh",
270
+ "-c",
271
+ script,
272
+ ],
273
+ { env: childEnv },
274
+ );
275
+ };
276
+
277
+ /**
278
+ * A Custom harness's package, installed while the sandbox holds nothing of
279
+ * the target's: its install scripts have only the npm registry to reach, and
280
+ * the rule is gone before anything is copied in.
281
+ */
282
+ const installPackage = async (installLayer) => {
283
+ const rule = `${NPM_REGISTRY}:443`;
284
+ await allow([rule], `allowing ${NPM_REGISTRY} for the harness's install`);
285
+ must(
286
+ await exec(sandboxNpmInstall(installLayer), { user: "root", workdir: null }),
287
+ `installing ${installLayer.npm} in the sandbox`,
288
+ { showOutput: true },
289
+ );
290
+ await disallow(rule, `removing the ${NPM_REGISTRY} rule`);
291
+ };
179
292
 
180
293
  return {
181
294
  container: name,
182
295
 
183
- async prepare(steps, { out }) {
184
- const harness = pinnedHarnessImage(plan.installLayer);
296
+ async prepare(steps, { out, why = "the recipe names no image" }) {
297
+ // A Custom harness has no Harness image: its npm package is installed
298
+ // inside the sandbox once it starts, never in a build on this machine.
299
+ const { npm } = plan.installLayer;
300
+ const harness = npm === undefined ? pinnedHarnessImage(plan.installLayer) : null;
185
301
  if (steps.dockerfile !== undefined) {
186
302
  throw new StepFailed([
187
303
  `REFUSED The recipe builds ${steps.dockerfile}, and on Docker Sandboxes its build steps would run on this machine's Docker (Docker Desktop's WSL 2 VM on Windows), outside the sandbox.`,
@@ -191,12 +307,19 @@ export function sbxDriver({ id, call, plan }) {
191
307
  const problem = globalPolicyProblem(await sbx(["policy", "ls", "--json"]));
192
308
  if (problem) throw new StepFailed(problem);
193
309
  out("Network policy: Docker Sandboxes' global policy is deny-all (checked read-only).");
310
+ const secrets = globalSecretsProblem(await sbx(["secret", "ls", "--global", "--json"]));
311
+ if (secrets) throw new StepFailed(secrets);
312
+ out(
313
+ "Secrets: Docker Sandboxes holds no global secrets, shadowed services or credentials from the host environment (checked read-only).",
314
+ );
194
315
  const own = steps.image !== undefined;
195
- const base = own ? steps.image : harness;
316
+ const base = own ? steps.image : (harness ?? CUSTOM_SANDBOX_BASE);
196
317
  out(
197
- own
198
- ? `Image: layering the pinned ${displayName} on ${base} with Docker on this machine, auto-updater off, as the sandbox's template; ${displayName} comes from the Harness image ${harness}.`
199
- : `Image: the Harness image ${harness}, which holds the pinned ${displayName}, as the sandbox's template, built with Docker on this machine; the recipe names no image.`,
318
+ npm !== undefined
319
+ ? `Image: ${own ? base : `the kit's base image ${base}; ${why}`}, as the sandbox's template, built with Docker on this machine; ${npm} is installed from npm for ${displayName} inside the sandbox, with only ${NPM_REGISTRY} reachable, before anything is copied in.`
320
+ : own
321
+ ? `Image: layering the pinned ${displayName} on ${base} with Docker on this machine, auto-updater off, as the sandbox's template; ${displayName} comes from the Harness image ${harness}.`
322
+ : `Image: the Harness image ${harness}, which holds the pinned ${displayName}, as the sandbox's template, built with Docker on this machine; ${why}.`,
200
323
  );
201
324
  const note = own ? imageDigestNote(base) : null;
202
325
  if (note) out(note);
@@ -211,7 +334,12 @@ export function sbxDriver({ id, call, plan }) {
211
334
  }
212
335
  must(pulled, `pulling ${base}`, { showOutput: true });
213
336
  imageBuilt = true;
214
- const layer = own ? layerDockerfile(base, plan.installLayer) : `FROM ${base}\n`;
337
+ const layer =
338
+ npm !== undefined
339
+ ? sandboxNpmLayer(base)
340
+ : own
341
+ ? layerDockerfile(base, plan.installLayer)
342
+ : `FROM ${base}\n`;
215
343
  const built = await docker(["build", "--label", `${LABEL}=${id}`, "--tag", template, "-"], {
216
344
  stdin: `${layer}${TEMPLATE_LAYER}`,
217
345
  });
@@ -242,23 +370,7 @@ export function sbxDriver({ id, call, plan }) {
242
370
  },
243
371
 
244
372
  async start() {
245
- created = true;
246
- must(
247
- await sbx([
248
- "create",
249
- "--name",
250
- name,
251
- "--no-progress",
252
- "--pull",
253
- "never",
254
- "-t",
255
- template,
256
- ...plan.installLayer.env.flatMap((v) => ["-e", v]),
257
- "shell",
258
- ]),
259
- "creating the sandbox",
260
- { showOutput: true },
261
- );
373
+ await create("creating the sandbox");
262
374
  },
263
375
 
264
376
  async copyIn(tar, what) {
@@ -283,9 +395,57 @@ export function sbxDriver({ id, call, plan }) {
283
395
  );
284
396
  },
285
397
 
286
- /** The harness is in the template already: nothing to install. */
398
+ /** The harness is in the sandbox already: nothing to install. */
287
399
  async installAgent() {},
288
400
 
401
+ /**
402
+ * The archive `script` writes, run as root in the sandbox into a file
403
+ * there, checked for size, then copied to a private host folder with
404
+ * `sbx cp` and read (ADR 0047).
405
+ */
406
+ async carryOut(script, { maxBytes }) {
407
+ const inside = "/tmp/agent-kit-carry.tar";
408
+ const made = await exec(
409
+ `( ${script} ) > ${inside} || exit 3; [ "$(wc -c < ${inside})" -le ${maxBytes} ] || exit 5`,
410
+ { user: "root", workdir: null },
411
+ );
412
+ if (made.status === 5) return { error: `it is larger than ${maxBytes / 1024 ** 3} GiB` };
413
+ if (made.status !== 0) {
414
+ return {
415
+ error: `tar exited ${made.status ?? "abnormally"}: ${firstLine(made.stderr) || "no output"}`,
416
+ };
417
+ }
418
+ const into = mkdtempSync(join(hostDir(), "carry-"));
419
+ try {
420
+ const r = await sbx(["cp", `${name}:${inside}`, "."], { cwd: into });
421
+ if (r.status !== 0)
422
+ return { error: `sbx cp failed: ${firstLine(r.stderr) || `exit ${r.status}`}` };
423
+ const entries = readdirSync(into);
424
+ const file = entries.length === 1 ? join(into, entries[0]) : null;
425
+ if (file === null || !lstatSync(file).isFile()) return { error: "sbx cp gave no one file" };
426
+ if (lstatSync(file).size > maxBytes) {
427
+ return { error: `it is larger than ${maxBytes / 1024 ** 3} GiB` };
428
+ }
429
+ return { data: readFileSync(file) };
430
+ } finally {
431
+ rmSync(into, { recursive: true, force: true });
432
+ }
433
+ },
434
+
435
+ /**
436
+ * Remove the sandbox, and every process in it, and create a fresh one
437
+ * from the same template, by the same name, then check from the host that
438
+ * it has no network rule (ADR 0047). The cut removed every rule first.
439
+ */
440
+ async renew() {
441
+ must(await sbx(["rm", "--force", name]), "removing the setup sandbox");
442
+ await create("creating the agent's sandbox");
443
+ const left = await this.egressLeft();
444
+ if (left !== null) {
445
+ throw new StepFailed([`FAILED the agent's sandbox has a network: ${left}.`, ENDS_HERE]);
446
+ }
447
+ },
448
+
289
449
  async openSetupEgress(registries) {
290
450
  const resources = sbxResources(registries);
291
451
  if (!resources.length) return { env: [], note: "no registries, so no network" };
@@ -427,6 +587,31 @@ export function sbxDriver({ id, call, plan }) {
427
587
  },
428
588
  };
429
589
 
590
+ /**
591
+ * `sbx create` of the sandbox from the template; a Custom harness's package
592
+ * is installed in it before anything is copied in.
593
+ */
594
+ async function create(what) {
595
+ created = true;
596
+ must(
597
+ await sbx([
598
+ "create",
599
+ "--name",
600
+ name,
601
+ "--no-progress",
602
+ "--pull",
603
+ "never",
604
+ "-t",
605
+ template,
606
+ ...plan.installLayer.env.flatMap((v) => ["-e", v]),
607
+ "shell",
608
+ ]),
609
+ what,
610
+ { showOutput: true },
611
+ );
612
+ if (plan.installLayer.npm !== undefined) await installPackage(plan.installLayer);
613
+ }
614
+
430
615
  function sandboxTeardown() {
431
616
  return [
432
617
  ...allowed.map((list) => ({