@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,308 @@
1
+ // What crosses from the setup container to the agent's (ADR 0047): the
2
+ // workspace without its `.git/`, and the paths the Caller declares in
3
+ // `setup_paths`. The archive comes out of the setup container, so it is
4
+ // setup's output: the host checks every entry before any of it goes in.
5
+
6
+ /** The most the carried archive may hold: the Launcher holds it in memory. */
7
+ export const MAX_CARRY_BYTES = 2 * 1024 ** 3;
8
+
9
+ /** One absolute path, of plain names. */
10
+ const PATH = /^(\/[A-Za-z0-9._@+-]+)+$/;
11
+
12
+ /**
13
+ * Where a declared path may not be, nor lie under, nor hold: the workspace and
14
+ * the Launcher's folder, the harness's install, the kernel's and the run's
15
+ * file systems, the system config, and the folders the image's programs and
16
+ * libraries are found in (git, the shell, the Node a harness runs on).
17
+ */
18
+ export const REFUSED_PATHS = Object.freeze([
19
+ "/workspace",
20
+ "/agent-kit",
21
+ "/opt/agent-kit",
22
+ "/proc",
23
+ "/sys",
24
+ "/dev",
25
+ "/run",
26
+ "/var/run",
27
+ "/tmp",
28
+ "/var/tmp",
29
+ "/boot",
30
+ "/etc",
31
+ "/bin",
32
+ "/sbin",
33
+ "/lib",
34
+ "/lib32",
35
+ "/lib64",
36
+ "/libx32",
37
+ "/usr/bin",
38
+ "/usr/sbin",
39
+ "/usr/lib",
40
+ "/usr/lib32",
41
+ "/usr/lib64",
42
+ "/usr/libexec",
43
+ "/usr/share",
44
+ "/usr/local/bin",
45
+ "/usr/local/sbin",
46
+ "/usr/local/lib",
47
+ "/usr/local/libexec",
48
+ "/usr/local/etc",
49
+ "/usr/local/share",
50
+ ]);
51
+
52
+ /**
53
+ * In a home folder: the shell's startup files and every harness's and git's
54
+ * config, which a declared path may not be, lie under or hold.
55
+ */
56
+ export const REFUSED_IN_HOME = Object.freeze([
57
+ ".bashrc",
58
+ ".bash_profile",
59
+ ".bash_login",
60
+ ".bash_logout",
61
+ ".profile",
62
+ ".zshrc",
63
+ ".zshenv",
64
+ ".zprofile",
65
+ ".zlogin",
66
+ ".config",
67
+ ".local/bin",
68
+ ".claude",
69
+ ".claude.json",
70
+ ".codex",
71
+ ".gemini",
72
+ ".cursor",
73
+ ".opencode",
74
+ ".agents",
75
+ ".agent",
76
+ ".gitconfig",
77
+ ".git-credentials",
78
+ ".ssh",
79
+ ".gnupg",
80
+ ]);
81
+
82
+ /** Whether `path` is `folder` or lies under it. */
83
+ const within = (path, folder) => path === folder || path.startsWith(`${folder}/`);
84
+
85
+ /** The refused location `path` is, lies under or holds, or null. */
86
+ function refusedBy(path) {
87
+ const system = REFUSED_PATHS.find((p) => within(path, p) || within(p, path));
88
+ if (system !== undefined) return system;
89
+ if (path === "/home") return "/home/<name>/.config";
90
+ const home = /^\/(root|home\/[^/]+)(\/|$)/.exec(path);
91
+ if (home === null) return null;
92
+ const folder = `/${home[1]}`;
93
+ if (path === folder) return `${folder}/.config`;
94
+ const rest = path.slice(folder.length + 1);
95
+ const entry = REFUSED_IN_HOME.find((e) => within(rest, e) || within(e, rest));
96
+ return entry === undefined ? null : `${folder}/${entry}`;
97
+ }
98
+
99
+ /**
100
+ * The paths `--setup-paths` declares, one per line, or why one is wrong. An
101
+ * empty text declares none; a path under another one declared is dropped.
102
+ * @param {string} [text]
103
+ * @returns {{ paths: string[] } | { error: string }}
104
+ */
105
+ export function setupPathsOf(text = "") {
106
+ const paths = [];
107
+ for (const line of text.split(/\r?\n/)) {
108
+ const raw = line.trim();
109
+ if (!raw) continue;
110
+ const path = raw.length > 1 ? raw.replace(/\/+$/, "") : raw;
111
+ const parts = path.split("/").slice(1);
112
+ if (!PATH.test(path) || parts.some((p) => p === "." || p === "..")) {
113
+ return {
114
+ error: `--setup-paths takes absolute paths, one per line, of letters, digits and ._@+- with no . or .. part, such as /root/.cache/ms-playwright, got: ${JSON.stringify(raw)}`,
115
+ };
116
+ }
117
+ const refused = refusedBy(path);
118
+ if (refused !== null) {
119
+ return {
120
+ error: `--setup-paths refuses ${path}: it is, lies under or holds ${refused}, which setup may not hand the agent (ADR 0047).`,
121
+ };
122
+ }
123
+ paths.push(path);
124
+ }
125
+ const kept = [...new Set(paths)].sort();
126
+ return { paths: kept.filter((p) => !kept.some((q) => q !== p && within(p, q))) };
127
+ }
128
+
129
+ /** A word quoted for `sh`. */
130
+ const quote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
131
+
132
+ /**
133
+ * The script that writes the archive to its output, run as root in the setup
134
+ * container: the workspace without `.git/`, and each declared path setup made.
135
+ * @param {readonly string[]} paths
136
+ */
137
+ export function carryScript(paths) {
138
+ return [
139
+ "cd / || exit 1",
140
+ "set -- workspace",
141
+ ...(paths.length
142
+ ? [
143
+ `for p in ${paths.map((p) => quote(p.slice(1))).join(" ")}; do`,
144
+ ' if [ -e "$p" ] || [ -L "$p" ]; then set -- "$@" "$p"; fi',
145
+ "done",
146
+ ]
147
+ : []),
148
+ 'exec tar -c -f - --exclude=workspace/.git "$@"',
149
+ ].join("\n");
150
+ }
151
+
152
+ const text = (b, start, length) =>
153
+ b
154
+ .subarray(start, start + length)
155
+ .toString("utf8")
156
+ .replace(/\0.*$/s, "");
157
+ const octal = (b, start, length) => {
158
+ const s = text(b, start, length).trim();
159
+ return /^[0-7]*$/.test(s) ? parseInt(s || "0", 8) : NaN;
160
+ };
161
+
162
+ /** The header's checksum, its own field counted as spaces. */
163
+ function checksumOf(h) {
164
+ let sum = 0;
165
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 0x20 : h[i];
166
+ return sum;
167
+ }
168
+
169
+ /** The records of a PAX header, as { key: value }, or null when malformed. */
170
+ function paxOf(data) {
171
+ const records = {};
172
+ let o = 0;
173
+ while (o < data.length) {
174
+ const space = data.indexOf(0x20, o);
175
+ if (space < 0) return null;
176
+ const length = Number(data.subarray(o, space).toString("latin1"));
177
+ if (!Number.isInteger(length) || length <= space - o + 1 || o + length > data.length) {
178
+ return null;
179
+ }
180
+ const record = data.subarray(space + 1, o + length - 1).toString("utf8");
181
+ const eq = record.indexOf("=");
182
+ if (eq < 0) return null;
183
+ records[record.slice(0, eq)] = record.slice(eq + 1);
184
+ o += length;
185
+ }
186
+ return records;
187
+ }
188
+
189
+ /**
190
+ * The names in an archive the Launcher built with `tarOf`, without a trailing
191
+ * `/`, and every folder above each: the paths a restore writes, or writes
192
+ * through.
193
+ * @param {Buffer} archive
194
+ * @returns {Set<string>}
195
+ */
196
+ export function pathsIn(archive) {
197
+ const paths = new Set();
198
+ let long = null;
199
+ for (let o = 0; o + 512 <= archive.length;) {
200
+ const h = archive.subarray(o, o + 512);
201
+ if (h.every((b) => b === 0)) break;
202
+ const size = octal(h, 124, 12);
203
+ const start = o + 512;
204
+ o = start + Math.ceil(size / 512) * 512;
205
+ const type = h[156] === 0 ? "0" : String.fromCharCode(h[156]);
206
+ if (type === "x") {
207
+ long = paxOf(archive.subarray(start, start + size))?.path ?? null;
208
+ continue;
209
+ }
210
+ const parts = (long ?? text(h, 0, 100)).replace(/\/+$/, "").split("/");
211
+ long = null;
212
+ for (let i = 1; i <= parts.length; i++) paths.add(parts.slice(0, i).join("/"));
213
+ }
214
+ return paths;
215
+ }
216
+
217
+ /**
218
+ * Check the archive that came out of the setup container, and clear the
219
+ * setuid, setgid and sticky bits in it, in place. Every entry must lie under
220
+ * `workspace/` or one declared path, none under `workspace/.git`, none under
221
+ * a symbolic link the archive made; a hard link must name an earlier file;
222
+ * and only files, folders and links are taken.
223
+ * @param {Buffer} archive
224
+ * @param {readonly string[]} paths the declared paths
225
+ * @returns {{ tar: Buffer, entries: number, missing: string[] } | { error: string }}
226
+ */
227
+ export function checkCarry(archive, paths) {
228
+ const roots = ["workspace", ...paths.map((p) => p.slice(1))];
229
+ const reached = new Set();
230
+ const links = new Set();
231
+ const files = new Set();
232
+ const fail = (why) => ({ error: why });
233
+ let entries = 0;
234
+ /** What a PAX or GNU long-name header says of the next entry. */
235
+ let next = {};
236
+ let o = 0;
237
+ for (;;) {
238
+ if (o + 512 > archive.length) return fail("the archive ends without its end blocks");
239
+ const h = archive.subarray(o, o + 512);
240
+ if (h.every((b) => b === 0)) break;
241
+ if (octal(h, 148, 8) !== checksumOf(h)) return fail("a header's checksum is wrong");
242
+ if (h[124] & 0x80) return fail("an entry is too large");
243
+ const size = octal(h, 124, 12);
244
+ if (Number.isNaN(size)) return fail("a header's size is not a number");
245
+ const type = h[156] === 0 ? "0" : String.fromCharCode(h[156]);
246
+ const start = o + 512;
247
+ const end = start + size;
248
+ if (end > archive.length) return fail("an entry runs past the end of the archive");
249
+ o = start + Math.ceil(size / 512) * 512;
250
+ const data = archive.subarray(start, end);
251
+ if (type === "x") {
252
+ const pax = paxOf(data);
253
+ if (pax === null) return fail("a PAX header is malformed");
254
+ if ("size" in pax || Object.keys(pax).some((k) => k.startsWith("GNU.sparse"))) {
255
+ return fail("a PAX header changes an entry's size");
256
+ }
257
+ if ("path" in pax) next.path = pax.path;
258
+ if ("linkpath" in pax) next.link = pax.linkpath;
259
+ continue;
260
+ }
261
+ if (type === "L" || type === "K") {
262
+ next[type === "L" ? "path" : "link"] = data.toString("utf8").replace(/\0.*$/s, "");
263
+ continue;
264
+ }
265
+ const ustar = text(h, 257, 6) === "ustar";
266
+ const prefix = ustar && h[263] === 0x30 ? text(h, 345, 155) : "";
267
+ const raw = next.path ?? (prefix ? `${prefix}/${text(h, 0, 100)}` : text(h, 0, 100));
268
+ const target = next.link ?? text(h, 157, 100);
269
+ next = {};
270
+ const name = raw.replace(/\/+$/, "");
271
+ const parts = name.split("/");
272
+ if (!name || name.startsWith("/") || parts.some((p) => p === "" || p === "." || p === "..")) {
273
+ return fail(`an entry's name is not a plain relative path: ${JSON.stringify(raw)}`);
274
+ }
275
+ const root = roots.find((r) => within(name, r));
276
+ if (root === undefined) {
277
+ return fail(`an entry lies outside the workspace and setup_paths: /${name}`);
278
+ }
279
+ if (within(name, "workspace/.git")) return fail("an entry lies in the workspace's .git/");
280
+ for (let i = 1; i <= parts.length; i++) {
281
+ const above = parts.slice(0, i).join("/");
282
+ if (links.has(above)) return fail(`an entry lies under a symbolic link: /${name}`);
283
+ }
284
+ if (type === "1") {
285
+ if (!files.has(target)) return fail(`a hard link names no earlier file: /${name}`);
286
+ } else if (type === "2") {
287
+ links.add(name);
288
+ } else if (type === "0" || type === "7") {
289
+ files.add(name);
290
+ } else if (type !== "5") {
291
+ return fail(`an entry is neither a file, a folder nor a link: /${name}`);
292
+ }
293
+ const mode = octal(h, 100, 8);
294
+ if (Number.isNaN(mode)) return fail("a header's mode is not a number");
295
+ if (mode & 0o7000) {
296
+ h.write(`${(mode & 0o777).toString(8).padStart(7, "0")}\0`, 100, "latin1");
297
+ h.write(`${checksumOf(h).toString(8).padStart(6, "0")}\0 `, 148, "latin1");
298
+ }
299
+ reached.add(root);
300
+ entries++;
301
+ }
302
+ if (!reached.has("workspace")) return fail("the archive holds no workspace");
303
+ return {
304
+ tar: archive,
305
+ entries,
306
+ missing: paths.filter((p) => !reached.has(p.slice(1))),
307
+ };
308
+ }
@@ -0,0 +1,271 @@
1
+ // The Sandbox image and the setup of a Stage that takes them, implement
2
+ // (ADRs 0025, 0029 and 0047): the Caller's `sandbox_image` resolved to the
3
+ // digest the run logs and layers the harness on, and `setup_commands` run in
4
+ // a setup container of their own before the network cut, with egress to
5
+ // `setup_registries` alone. Only the workspace and the `setup_paths` cross to
6
+ // the fresh container the agent then runs in. The verify run uses the same
7
+ // steps.
8
+
9
+ import { readFileSync, statSync } from "node:fs";
10
+ import { StepFailed } from "../../deep-scan/steps.mjs";
11
+ import { tarOf } from "../../deep-scan/tar.mjs";
12
+ import { firstLine } from "../../exec.mjs";
13
+ import { carryScript, checkCarry, MAX_CARRY_BYTES, pathsIn, setupPathsOf } from "./carry.mjs";
14
+
15
+ /** Where the sandbox holds the Caller's commands. */
16
+ const FOLDER = "/agent-kit/setup";
17
+ /** The most a commands file holds. */
18
+ const MAX_COMMANDS_BYTES = 1024 * 1024;
19
+ /** The end of a command run's output that comes out to the log. */
20
+ const MAX_LOG_BYTES = 200_000;
21
+
22
+ // One reference, never an option of docker's or a second Dockerfile line.
23
+ const IMAGE = /^[A-Za-z0-9][A-Za-z0-9._/:@-]*$/;
24
+ // A host name, with the port where it is not 80 or 443.
25
+ const REGISTRY = /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?(:\d{1,5})?$/;
26
+
27
+ /**
28
+ * What the flags ask of the sandbox, or why one is wrong. An empty
29
+ * `--sandbox-image` or `--setup-registries` counts as left out.
30
+ * @param {{ image?: string, registries?: string, setupPath?: string, paths?: string }} flags
31
+ * @returns {{ image: string | null, registries: string[], setup: string | null, paths: string[] } | { error: string }}
32
+ */
33
+ export function sandboxFlags({ image, registries = "", setupPath, paths: pathsText }) {
34
+ const named = image?.trim() ?? "";
35
+ if (named && !IMAGE.test(named)) {
36
+ return {
37
+ error: `--sandbox-image must be one image reference, such as node:22-bookworm, got: ${JSON.stringify(image)}`,
38
+ };
39
+ }
40
+ const hosts = registries.split(/[\s,]+/).filter(Boolean);
41
+ const bad = hosts.find((host) => !REGISTRY.test(host));
42
+ if (bad !== undefined) {
43
+ return {
44
+ error: `--setup-registries takes host names, such as registry.npmjs.org, got: ${JSON.stringify(bad)}`,
45
+ };
46
+ }
47
+ const declared = setupPathsOf(pathsText);
48
+ if ("error" in declared) return declared;
49
+ let setup = null;
50
+ if (setupPath !== undefined) {
51
+ setup = readCommands(setupPath);
52
+ if (setup === null) return { error: commandsError("--setup-commands", setupPath) };
53
+ }
54
+ return { image: named || null, registries: [...new Set(hosts)], setup, paths: declared.paths };
55
+ }
56
+
57
+ /** The commands in `file`, or null when it is no file of commands. */
58
+ export function readCommands(file) {
59
+ try {
60
+ const stat = statSync(file);
61
+ if (!stat.isFile() || stat.size > MAX_COMMANDS_BYTES) return null;
62
+ // A Caller's block from a Windows checkout still runs in bash.
63
+ const text = readFileSync(file, "utf8").replace(/\r\n/g, "\n");
64
+ return text.trim() ? text : null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ export const commandsError = (flag, path) =>
71
+ `${flag} ${path}: it must be a file of shell commands, of at most ${MAX_COMMANDS_BYTES / 1024 / 1024} MiB.`;
72
+
73
+ /**
74
+ * Pull `image` and resolve it to its registry digest, which the run logs and
75
+ * builds on. A pull the registry refuses falls back to the copy a trusted step
76
+ * pulled onto this machine: the Launcher holds no GitHub token (ADR 0029).
77
+ * @param {{ docker: (args: string[]) => Promise<import("../../exec.mjs").StartResult>, image: string, out: (s: string) => void }} opts
78
+ * @returns {Promise<string>} the reference to build on
79
+ */
80
+ export async function resolveImage({ docker, image, out }) {
81
+ out(`Image: pulling the Sandbox image ${image}.`);
82
+ const pulled = await docker(["pull", image]);
83
+ const found = await docker(["image", "inspect", "--format", "{{json .RepoDigests}}", image]);
84
+ if (pulled.status !== 0) {
85
+ if (found.status !== 0) {
86
+ throw new StepFailed([
87
+ `FAILED the Sandbox image ${image} could not be pulled: ${firstLine(pulled.stderr) || `exit ${pulled.status}`}.`,
88
+ "A private image is pulled from GHCR by a step before the Launcher.",
89
+ ]);
90
+ }
91
+ out(`The pull was refused, so the copy of ${image} already on this machine is used.`);
92
+ }
93
+ const resolved = digestOf(image, found);
94
+ out(
95
+ resolved === null
96
+ ? `Sandbox image: ${image} has no registry digest (it was built on this machine).`
97
+ : `Sandbox image: ${image} resolved to ${resolved}.`,
98
+ );
99
+ return resolved ?? image;
100
+ }
101
+
102
+ /** The `name@sha256:` of `image` in `docker image inspect`'s digests, or null. */
103
+ function digestOf(image, found) {
104
+ if (/@sha256:[0-9a-f]{64}$/.test(image)) return image;
105
+ if (found.status !== 0) return null;
106
+ let digests;
107
+ try {
108
+ digests = JSON.parse(found.stdout.toString("utf8"));
109
+ } catch {
110
+ return null;
111
+ }
112
+ if (!Array.isArray(digests)) return null;
113
+ // The name without its tag; a registry's port is not one.
114
+ const name = image.replace(/:[^/:]*$/, "");
115
+ return (
116
+ digests.find((d) => typeof d === "string" && d.startsWith(`${name}@`)) ??
117
+ digests.find((d) => typeof d === "string") ??
118
+ null
119
+ );
120
+ }
121
+
122
+ /**
123
+ * `runner`, with a `docker pull` of a reference in `resolved` answered at once:
124
+ * the Launcher has it already, and a private one cannot be pulled again.
125
+ * @param {import("../../exec.mjs").Runner} runner
126
+ * @param {Set<string>} resolved
127
+ */
128
+ export function withResolvedImages(runner, resolved) {
129
+ return Object.assign((...args) => runner(...args), runner, {
130
+ start: (cmd, args, opts) =>
131
+ cmd === "docker" && args.length === 2 && args[0] === "pull" && resolved.has(args[1])
132
+ ? Promise.resolve({
133
+ status: 0,
134
+ signal: null,
135
+ aborted: false,
136
+ stdout: Buffer.alloc(0),
137
+ stderr: "",
138
+ })
139
+ : runner.start(cmd, args, opts),
140
+ });
141
+ }
142
+
143
+ /**
144
+ * Run the Caller's commands in the sandbox, in the workspace, and print the end
145
+ * of their output. A non-zero exit fails the run.
146
+ * @param {{
147
+ * driver: import("../../deep-scan/lifecycle.mjs").Driver,
148
+ * name: "setup" | "verify",
149
+ * commands: string,
150
+ * env: string[],
151
+ * out: (s: string) => void,
152
+ * }} opts `out` neutralizes a line that reads as a workflow command, as every
153
+ * line the CLI prints.
154
+ */
155
+ export async function runCommands({ driver, name, commands, env, out }) {
156
+ const input = `${name}_commands`;
157
+ const script = `${FOLDER}/${name}.sh`;
158
+ const log = `${FOLDER}/${name}.log`;
159
+ await driver.copyIn(
160
+ tarOf([
161
+ { path: "agent-kit", dir: true },
162
+ { path: FOLDER.slice(1), dir: true },
163
+ { path: script.slice(1), data: Buffer.from(commands, "utf8") },
164
+ ]),
165
+ `copying ${input} in`,
166
+ );
167
+ // As the runner's `shell: bash` runs them: setup stops at the first failing
168
+ // command, verify at the Caller's own `set -e`. The log is kept outside the
169
+ // folder, which only root may write.
170
+ const shell = name === "setup" ? "bash -eo pipefail" : "bash";
171
+ const r = await driver.exec(
172
+ [
173
+ "log=$(mktemp)",
174
+ `${shell} ${script} > "$log" 2>&1 < /dev/null`,
175
+ "code=$?",
176
+ `tail -c ${MAX_LOG_BYTES} "$log"`,
177
+ "exit $code",
178
+ ].join("\n"),
179
+ { env },
180
+ );
181
+ const shown = r.stdout.toString("utf8").trimEnd();
182
+ if (shown) out(shown);
183
+ if (r.status !== 0) {
184
+ throw new StepFailed([`FAILED ${input} exited ${r.status ?? "abnormally"}.`]);
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Take what crosses out of the setup container (ADR 0047): the workspace
190
+ * without `.git/`, and each declared path setup made, as one archive checked
191
+ * on the host before any of it goes in.
192
+ * @param {{
193
+ * driver: import("../../deep-scan/lifecycle.mjs").Driver,
194
+ * paths: readonly string[],
195
+ * out: (s: string) => void,
196
+ * }} opts
197
+ * @returns {Promise<Buffer>} the checked archive
198
+ */
199
+ export async function carryOut({ driver, paths, out }) {
200
+ const taken = await driver.carryOut(carryScript(paths), { maxBytes: MAX_CARRY_BYTES });
201
+ const checked = "error" in taken ? taken : checkCarry(taken.data, paths);
202
+ if ("error" in checked) {
203
+ throw new StepFailed([
204
+ `FAILED setup's files could not be carried to the agent's container: ${checked.error}.`,
205
+ ]);
206
+ }
207
+ for (const path of checked.missing)
208
+ out(`Setup made nothing at ${path}, so nothing of it crosses.`);
209
+ const kept = paths.filter((p) => !checked.missing.includes(p));
210
+ out(
211
+ `Carried over: ${checked.entries} entries of the workspace${kept.length ? ` and ${kept.join(", ")}` : ""}, checked on the host; nothing else setup wrote crosses.`,
212
+ );
213
+ return checked.tar;
214
+ }
215
+
216
+ /**
217
+ * Put the repository's copy back as it was made, in the agent's container:
218
+ * setup ran dependency code in the workspace that crossed, so the copy holds
219
+ * no config it left out and no instructions but the trusted commit's. What
220
+ * setup installed beside them stays.
221
+ * @param {{
222
+ * driver: import("../../deep-scan/lifecycle.mjs").Driver,
223
+ * shape: { checkoutConfig: readonly string[], instructionFiles: readonly string[] },
224
+ * workspace: { tar: Buffer },
225
+ * root: string,
226
+ * }} opts
227
+ */
228
+ export async function restoreCheckout({ driver, shape, workspace, root }) {
229
+ const quote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
230
+ const matches = [...shape.checkoutConfig, ...shape.instructionFiles]
231
+ .flatMap((path) => [`-path ${quote(`./${path}`)}`, `-path ${quote(`*/${path}`)}`])
232
+ .join(" -o ");
233
+ if (matches) {
234
+ const r = await driver.exec(
235
+ `cd ${root} && find . -path ./.git -prune -o \\( ${matches} \\) -prune -exec rm -rf {} +`,
236
+ { workdir: null },
237
+ );
238
+ if (r.status !== 0) {
239
+ throw new StepFailed(["FAILED the sandbox's copy could not be cleared after setup."]);
240
+ }
241
+ }
242
+ // A link setup left where the checkout has a file or a folder would have
243
+ // the copy written through it, as root, to wherever it points; and one on a
244
+ // harness config or instruction file's path, or a folder above one, at any
245
+ // depth, would hand the agent what the clearing above never reached, since
246
+ // `find` does not follow it. Each goes.
247
+ const shaped = [...shape.checkoutConfig, ...shape.instructionFiles].flatMap((path) => {
248
+ const parts = path.split("/");
249
+ return parts.map((_, i) => parts.slice(0, i + 1).join("/"));
250
+ });
251
+ const named = (rel) => shaped.some((p) => rel === p || rel.endsWith(`/${p}`));
252
+ const links = await driver.exec(
253
+ `if [ -L ${root} ]; then printf '%s\\0' ${root}; fi; find ${root} -path ${root}/.git -prune -o -type l -print0`,
254
+ { workdir: null },
255
+ );
256
+ if (links.status !== 0) {
257
+ throw new StepFailed(["FAILED the sandbox's copy could not be checked after setup."]);
258
+ }
259
+ const written = pathsIn(workspace.tar);
260
+ const through = links.stdout
261
+ .toString("utf8")
262
+ .split("\0")
263
+ .filter((path) => path && (written.has(path.slice(1)) || named(path.slice(root.length + 1))));
264
+ if (through.length) {
265
+ const r = await driver.exec(`rm -f -- ${through.map(quote).join(" ")}`, { workdir: null });
266
+ if (r.status !== 0) {
267
+ throw new StepFailed(["FAILED the sandbox's copy could not be cleared after setup."]);
268
+ }
269
+ }
270
+ await driver.copyIn(workspace.tar, "putting the checkout back after setup");
271
+ }
@@ -0,0 +1,70 @@
1
+ // The implement Stage's verify run (ADR 0029): the Caller's `setup_commands`
2
+ // and `verify_commands` on the checked-out commit, in the same Sandbox image,
3
+ // with the same registries and the same network cut, and no agent. As for the
4
+ // agent, setup runs in a container of its own and the commands in a fresh one
5
+ // that takes only the workspace and the declared paths (ADR 0047). No model
6
+ // route is opened and no credential is read.
7
+
8
+ import { ENDS_HERE, StepFailed } from "../../deep-scan/steps.mjs";
9
+ import { runCommands } from "./sandbox.mjs";
10
+
11
+ /** The limits a verify run stays within unless a flag says otherwise. */
12
+ export const VERIFY_LIMITS = Object.freeze({
13
+ setupMinutes: 20,
14
+ scanMinutes: 30,
15
+ turns: 1,
16
+ tokens: 1,
17
+ });
18
+
19
+ /** The flags only a run with an agent takes. */
20
+ export const AGENT_FLAGS = Object.freeze([
21
+ "--brief",
22
+ "--result",
23
+ "--bundle",
24
+ "--transcript",
25
+ "--error-log",
26
+ "--input",
27
+ "--untracked",
28
+ "--model",
29
+ "--effort",
30
+ "--credential",
31
+ "--credential-from",
32
+ "--max-turns",
33
+ "--max-tokens",
34
+ "--proving-run",
35
+ "--trusted-ref",
36
+ ]);
37
+
38
+ /**
39
+ * Cut the sandbox's network, and check from the host that it is cut: before
40
+ * the fresh container starts, where setup ran (ADR 0047).
41
+ * @param {import("../../deep-scan/lifecycle.mjs").Driver} driver
42
+ * @param {(s: string) => void} out
43
+ */
44
+ export async function cutForVerify(driver, out) {
45
+ await driver.cutEgress();
46
+ const left = await driver.egressLeft();
47
+ if (left !== null) {
48
+ throw new StepFailed([`FAILED the network is not cut: ${left}.`, ENDS_HERE]);
49
+ }
50
+ out("Network: cut (checked from the host); verify_commands have no network.");
51
+ }
52
+
53
+ /**
54
+ * Run the commands in a sandbox whose network is cut.
55
+ * @param {{
56
+ * driver: import("../../deep-scan/lifecycle.mjs").Driver,
57
+ * clocks: import("../../deep-scan/sandbox-run.mjs").Clocks,
58
+ * commands: string,
59
+ * minutes: number,
60
+ * out: (s: string) => void,
61
+ * }} opts
62
+ * @returns {Promise<number>} the exit code of a run whose commands passed
63
+ */
64
+ export async function verifyInSandbox({ driver, clocks, commands, minutes, out }) {
65
+ clocks.end();
66
+ clocks.begin("verify", minutes);
67
+ await runCommands({ driver, name: "verify", commands, env: ["CI=true"], out });
68
+ out("Verify: passed.");
69
+ return 0;
70
+ }