@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,289 @@
1
+ // What the live suite knows about opencode (ADR 0031): one entry that runs it
2
+ // through each model proxy profile, the control that loads the checkout's
3
+ // config on purpose, and its four named assertions (ADR 0027), with what it
4
+ // does in the sandbox to judge two of them:
5
+ //
6
+ // - a decoy shared server, started before the agent step with a model of its
7
+ // own, which `--standalone` must leave alone; and, as its control, the same
8
+ // run without `--standalone`, which must attach to it;
9
+ // - a denied-egress log: opencode run again with its HTTP proxy variables
10
+ // pointed at a listener in the sandbox that logs every request and refuses
11
+ // it, so an update check, or model traffic past the model proxy, is written
12
+ // down. The sandbox has no route out, and an attempt that dies on its name
13
+ // would otherwise leave no trace.
14
+ //
15
+ // The stub model's canary names a model no catalogue knows, so it reaches the
16
+ // stub only if opencode read the Launcher's config.
17
+
18
+ import { randomBytes } from "node:crypto";
19
+ import { opencode, PROVIDERS } from "../harness/opencode.mjs";
20
+ import { anthropicDialect } from "../model-proxy/stub-dialects/anthropic.mjs";
21
+ import { geminiApiDialect } from "../model-proxy/stub-dialects/gemini-api.mjs";
22
+ import { openaiDialect } from "../model-proxy/stub-dialects/openai.mjs";
23
+ import { canary, plantedConfig } from "./host.mjs";
24
+
25
+ /** A made-up model id, which no canary search looks for. */
26
+ const madeUp = (prefix) => `${prefix}-${randomBytes(8).toString("hex")}`;
27
+
28
+ /** The model each run names, and the one the decoy server runs on. */
29
+ const MODEL = madeUp("akmodel");
30
+ const DECOY = madeUp("akdecoy");
31
+
32
+ /** Where the decoy server and the egress listener keep their files in the sandbox. */
33
+ const DECOY_DIR = "/agent-kit/decoy";
34
+ const EGRESS_DIR = "/agent-kit/egress";
35
+ const EGRESS_PORT = 18090;
36
+
37
+ /** The name the egress listener's own control asks for. */
38
+ const EGRESS_CONTROL = "egress-control.invalid";
39
+
40
+ /** Where opencode looks for a release, or fetches one from. */
41
+ const UPDATE_HOSTS = /\b(opencode\.ai|registry\.npmjs\.org|github\.com|formulae\.brew\.sh)\b/i;
42
+
43
+ /** The model APIs' own hosts, which only the model proxy may reach. */
44
+ const MODEL_HOSTS =
45
+ /\b(api\.anthropic\.com|api\.openai\.com|generativelanguage\.googleapis\.com|chatgpt\.com)\b/i;
46
+
47
+ const DONE = "Say that you are done.";
48
+
49
+ /** The longest one of these runs of opencode may take. */
50
+ const RUN_MS = 120_000;
51
+
52
+ /** A word quoted for `sh`. */
53
+ const quote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
54
+
55
+ /** Whether a request that reached the stub asks for the model `id`. */
56
+ export function namesModel({ path, body }, id) {
57
+ if (path.includes(`/models/${id}:`)) return true;
58
+ try {
59
+ return JSON.parse(body).model === id;
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ /** The decoy server's config: the run's own, on the decoy's model. */
66
+ function decoyConfig(plan) {
67
+ const config = JSON.parse(plan.launch.files[0].text);
68
+ const [provider] = config.model.split("/");
69
+ config.model = `${provider}/${DECOY}`;
70
+ config.providers[provider].models = { [DECOY]: {} };
71
+ return JSON.stringify(config);
72
+ }
73
+
74
+ /** The listener: it logs each connection's first line, and refuses it. */
75
+ const LISTENER = [
76
+ 'const fs = require("node:fs");',
77
+ 'require("node:net").createServer((socket) => {',
78
+ ' socket.on("error", () => {});',
79
+ ' socket.once("data", (data) => {',
80
+ ` fs.appendFileSync("${EGRESS_DIR}/log", String(data).split("\\r\\n")[0] + "\\n");`,
81
+ ' socket.end("HTTP/1.1 403 Forbidden\\r\\nContent-Length: 0\\r\\nConnection: close\\r\\n\\r\\n");',
82
+ " });",
83
+ `}).listen(${EGRESS_PORT}, "127.0.0.1");`,
84
+ ].join("\n");
85
+
86
+ /**
87
+ * @typedef {(argv: string[], opts?: { env?: string[], stdin?: string, detach?: boolean }) =>
88
+ * Promise<{ status: number | null, stdout: string }>} SandboxExec runs a
89
+ * command in the sandbox's workspace, with the launch's environment and
90
+ * `env` over it.
91
+ */
92
+
93
+ /**
94
+ * Before the agent step: a shared server, as a user's machine would have one
95
+ * running, registered where opencode looks for it.
96
+ * @param {{ exec: SandboxExec, plan: import("../harness/claude-code.mjs").LaunchPlan }} sandbox
97
+ */
98
+ async function startDecoy({ exec, plan }) {
99
+ const env = [`OPENCODE_CONFIG=${DECOY_DIR}/opencode.json`, `XDG_CONFIG_HOME=${DECOY_DIR}/config`];
100
+ await exec([
101
+ "sh",
102
+ "-c",
103
+ `mkdir -p ${DECOY_DIR} && printf '%s' ${quote(decoyConfig(plan))} > ${DECOY_DIR}/opencode.json`,
104
+ ]);
105
+ await exec(["sh", "-c", `exec opencode serve --service > ${DECOY_DIR}/log 2>&1`], {
106
+ env,
107
+ detach: true,
108
+ });
109
+ const registered = await exec([
110
+ "sh",
111
+ "-c",
112
+ 'i=0; while [ "$i" -lt 60 ]; do ls "$XDG_STATE_HOME"/opencode/service*.json && exit 0; i=$((i + 1)); sleep 1; done; exit 1',
113
+ ]);
114
+ return { registered: registered.status === 0 };
115
+ }
116
+
117
+ /**
118
+ * After the agent step: the two runs that show what the sandbox's run did not.
119
+ * @param {{
120
+ * exec: SandboxExec,
121
+ * plan: import("../harness/claude-code.mjs").LaunchPlan,
122
+ * url: string,
123
+ * requests: () => ReadonlyArray<{ path: string, body: string }>,
124
+ * state: { registered: boolean },
125
+ * }} sandbox
126
+ */
127
+ async function afterAgent({ exec, plan, url, requests, state }) {
128
+ const run = (argv, env = []) => exec(argv, { env, stdin: DONE });
129
+ const before = requests().length;
130
+ const asked = (list) => list.some((r) => namesModel(r, DECOY));
131
+ const attachedByStage = asked(requests().slice(0, before));
132
+ await run(plan.launch.argv.filter((arg) => arg !== "--standalone"));
133
+ const decoy = {
134
+ registered: state.registered,
135
+ attachedByStage,
136
+ attachedWithout: asked(requests().slice(before)),
137
+ };
138
+
139
+ await exec([
140
+ "sh",
141
+ "-c",
142
+ `mkdir -p ${EGRESS_DIR} && printf '%s' ${quote(LISTENER)} > ${EGRESS_DIR}/listen.js && : > ${EGRESS_DIR}/log`,
143
+ ]);
144
+ await exec(["node", `${EGRESS_DIR}/listen.js`], { detach: true });
145
+ const proxy = `http://127.0.0.1:${EGRESS_PORT}`;
146
+ const direct = `127.0.0.1,localhost,${new URL(url).hostname}`;
147
+ await exec([
148
+ "sh",
149
+ "-c",
150
+ `curl -s --retry 10 --retry-delay 1 --retry-connrefused -o /dev/null -x ${proxy} http://${EGRESS_CONTROL}/ || true`,
151
+ ]);
152
+ await run(plan.launch.argv, [
153
+ ...["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"].map((v) => `${v}=${proxy}`),
154
+ `NO_PROXY=${direct}`,
155
+ `no_proxy=${direct}`,
156
+ ]);
157
+ const log = await exec(["cat", `${EGRESS_DIR}/log`]);
158
+ const lines = log.stdout.split("\n").filter(Boolean);
159
+ return {
160
+ decoy,
161
+ egress: {
162
+ logging: lines.some((line) => line.includes(EGRESS_CONTROL)),
163
+ lines: lines.filter((line) => !line.includes(EGRESS_CONTROL)),
164
+ },
165
+ };
166
+ }
167
+
168
+ /**
169
+ * The four named assertions. `stage` says the run was the read-only Stage, the
170
+ * one that runs the decoy server and the egress log.
171
+ * @type {ReadonlyArray<import("./harnesses.mjs").NamedAssertion>}
172
+ */
173
+ const ASSERTIONS = Object.freeze([
174
+ {
175
+ name: "opencode-standalone-ignores-shared-server",
176
+ check({ stage, decoy }) {
177
+ if (!stage) return null;
178
+ if (!decoy?.registered) {
179
+ return "the decoy shared server did not register, so nothing shows it was left alone: read its log.";
180
+ }
181
+ if (decoy.attachedByStage) {
182
+ return "the agent step asked for the decoy server's model: it attached to the shared server despite --standalone.";
183
+ }
184
+ return decoy.attachedWithout
185
+ ? null
186
+ : "the control, the same run without --standalone, did not attach to the decoy server, so leaving it alone shows nothing.";
187
+ },
188
+ },
189
+ {
190
+ name: "opencode-reads-launcher-config",
191
+ check({ requests }) {
192
+ return requests.some((r) => namesModel(r, MODEL))
193
+ ? null
194
+ : "no request asked for the canary model, which only the Launcher-written OPENCODE_CONFIG names: opencode did not read it.";
195
+ },
196
+ },
197
+ {
198
+ name: "opencode-no-update-attempt",
199
+ check({ stage, egress }) {
200
+ if (!stage) return null;
201
+ if (!egress?.logging) {
202
+ return "the denied-egress log did not record its control, so its silence shows nothing.";
203
+ }
204
+ const attempt = egress.lines.find((line) => UPDATE_HOSTS.test(line));
205
+ return attempt === undefined
206
+ ? null
207
+ : `an update attempt is in the denied-egress log, though OPENCODE_DISABLE_AUTOUPDATE is set: ${attempt}`;
208
+ },
209
+ },
210
+ {
211
+ name: "opencode-transport-http",
212
+ check({ stage, requests, egress, launcherOutput }) {
213
+ if (requests.length === 0) return "no model request reached the model API through the proxy.";
214
+ const other = requests.find((r) => r.method !== "POST");
215
+ if (other !== undefined) {
216
+ return `a ${other.method} request reached the model API: only HTTP POSTs are expected with transport "http".`;
217
+ }
218
+ // A WebSocket opens with a GET, which the proxy refuses and names.
219
+ const socket = /^Model proxy: .*refused \d+ \([^)]*\bGET \/v1\/responses\b/m.exec(
220
+ launcherOutput,
221
+ );
222
+ if (socket) return `the model proxy refused a WebSocket's request: ${socket[0]}`;
223
+ if (!stage) return null;
224
+ if (!egress?.logging) {
225
+ return "the denied-egress log did not record its control, so its silence shows nothing.";
226
+ }
227
+ const past = egress.lines.find((line) => MODEL_HOSTS.test(line));
228
+ return past === undefined ? null : `model traffic went past the proxy: ${past}`;
229
+ },
230
+ },
231
+ ]);
232
+
233
+ /** What differs by the provider: the stub's dialect and the credential's header. */
234
+ const BY_PROVIDER = {
235
+ anthropic: {
236
+ dialect: anthropicDialect,
237
+ credential: () => `sk-ant-api03-${canary()}`,
238
+ upstreamAuth: (_kind, credential) => ["x-api-key", credential],
239
+ },
240
+ openai: {
241
+ dialect: openaiDialect,
242
+ credential: () => `sk-proj-${canary()}`,
243
+ upstreamAuth: (_kind, credential) => ["authorization", `Bearer ${credential}`],
244
+ },
245
+ google: {
246
+ dialect: geminiApiDialect,
247
+ credential: () => `AIza-${canary()}`,
248
+ upstreamAuth: (_kind, credential) => ["x-goog-api-key", credential],
249
+ },
250
+ };
251
+
252
+ const removed = opencode().checkoutConfig;
253
+
254
+ /** @type {Readonly<import("./harnesses.mjs").LiveHarness>} */
255
+ export const liveOpencode = Object.freeze({
256
+ adapter: opencode,
257
+ // One run of every scenario for each provider, so each profile is proven.
258
+ profiles: Object.freeze(
259
+ Object.fromEntries(
260
+ Object.keys(PROVIDERS).map((provider) => [
261
+ provider,
262
+ Object.freeze({ ...BY_PROVIDER[provider], model: `${provider}/${MODEL}` }),
263
+ ]),
264
+ ),
265
+ ),
266
+ baseUrlVariable: "AGENT_KIT_MODEL_PROXY_URL",
267
+ removed: Object.freeze([...removed]),
268
+ harmlessVariables: Object.freeze([]),
269
+ configControl: Object.freeze(["opencode-mcp-server", "opencode-dir-mcp-server"]),
270
+ assertions: ASSERTIONS,
271
+ before: startDecoy,
272
+ after: afterAgent,
273
+ // The removed config is put back, and project config turned on again.
274
+ control({ plan }) {
275
+ const planted = Object.entries(plantedConfig()).filter(
276
+ ([path]) => path.startsWith("opencode.json") || path.startsWith(".opencode/"),
277
+ );
278
+ const script = [
279
+ "set -eu",
280
+ "mkdir -p /workspace/.opencode",
281
+ ...planted.map(
282
+ ([path, text]) => `printf '%s' ${quote(text)} > ${quote(`/workspace/${path}`)}`,
283
+ ),
284
+ "unset OPENCODE_DISABLE_PROJECT_CONFIG",
285
+ `exec timeout ${RUN_MS / 1000} ${plan.launch.argv.map(quote).join(" ")}`,
286
+ ].join("\n");
287
+ return { argv: ["sh", "-c", script], stdin: DONE };
288
+ },
289
+ });
@@ -0,0 +1,239 @@
1
+ // The live suite's probes (ADR 0031): the shell scripts the stub model has the
2
+ // harness run in its own sandbox, one per Guard (ADR 0025), each an attempt
3
+ // to breach it. A probe judges nothing: it prints what it saw, and the host
4
+ // reads those lines (assess.mjs) beside what it saw itself.
5
+ //
6
+ // The lines: `PROBE|<guard>|<name>|<value>`, with `PROBE|<guard>|end` last, so
7
+ // a probe that did not finish is told from one that found nothing. A dump of
8
+ // the environment prefixes its lines `ENV ` (this shell's) or `PROC ` (every
9
+ // process's), and a command line `CMD `.
10
+ //
11
+ // A probe's own text is part of what the host reads (it travels in the model's
12
+ // tool call, and its shell's command line), so no script holds a canary, or
13
+ // the name of anything of the launcher's.
14
+
15
+ /** Where a planted checkout config writes its marker, if the harness loads it. */
16
+ export const MARKER_DIR = "/tmp/agent-kit-config-markers";
17
+
18
+ /** The variable a planted checkout config sets, if the harness loads it. */
19
+ export const PLANTED_ENV = "AGENT_KIT_PLANTED_CONFIG";
20
+
21
+ /** The workspace's own file, read to show the read probe can read. */
22
+ export const CONTROL_FILE = "agent-kit-control.txt";
23
+
24
+ /** Where every probe's output is gathered in the sandbox, for the result. */
25
+ const LOG = "/tmp/agent-kit-probes.log";
26
+
27
+ /** The longest a probe waits on one connection, in seconds. */
28
+ const CONNECT_SECONDS = 5;
29
+
30
+ /**
31
+ * Python that writes a review Stage result holding its input as one note, cut so
32
+ * the file stays under the result's size cap.
33
+ */
34
+ const REVIEW_RESULT = [
35
+ "import json, sys",
36
+ 'note = sys.stdin.buffer.read().decode("utf-8", "replace")[:100000] or "no output"',
37
+ 'print(json.dumps({"entries": [], "fixed": {}, "checked": {"correctness": [note]}, "replies": []}, ensure_ascii=False))',
38
+ ].join("\n");
39
+
40
+ /**
41
+ * The probes' output as a plan Stage result: the heading, then the output, with
42
+ * nothing in it the result may not hold and no more than fits its size cap.
43
+ */
44
+ const PLAN_RESULT = [
45
+ "import re, sys",
46
+ 'log = sys.stdin.buffer.read().decode("utf-8", "replace")',
47
+ 'log = re.sub(r"[\\x00-\\x08\\x0b-\\x1f\\x7f]", "?", log)[:60000] or "no output"',
48
+ 'sys.stdout.buffer.write(("## Agent plan\\n\\n" + log + "\\n").encode("utf-8"))',
49
+ ].join("\n");
50
+
51
+ /**
52
+ * Python that writes an implement Stage result holding its input as the body,
53
+ * cut until the file is under the result's size cap.
54
+ */
55
+ const IMPLEMENT_RESULT = [
56
+ "import json, sys",
57
+ 'note = sys.stdin.buffer.read().decode("utf-8", "replace")[:60000] or "no output"',
58
+ 'text = lambda: json.dumps({"title": "probe", "body": note}, ensure_ascii=False)',
59
+ "while len(text().encode()) > 60000: note = note[: len(note) * 3 // 4]",
60
+ "print(text())",
61
+ ].join("\n");
62
+
63
+ /**
64
+ * Python that writes a Review response Stage result: no findings, which the
65
+ * schema holds as a round with nothing to answer. The probes' output stays in
66
+ * the stub model's tool results.
67
+ */
68
+ const RESPONSE_RESULT = `print('{"findings": []}')`;
69
+
70
+ /** A word quoted for `sh`. */
71
+ const quote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
72
+
73
+ /** Every process's environment, one variable per line. */
74
+ const ENVIRONMENT = [
75
+ "env | sed 's/^/ENV /'",
76
+ "cat /proc/[0-9]*/environ 2>/dev/null | tr '\\0' '\\n' | sort -u | sed 's/^/PROC /'",
77
+ ];
78
+
79
+ /** The longest the filesystem sweep may take, inside the stub's tool timeout. */
80
+ const SWEEP_SECONDS = 100;
81
+
82
+ /** The pattern of a canary's value, written so this text is not one. */
83
+ const CANARY_PATTERN = "AKCANARY[-][0-9a-f]\\{32\\}";
84
+
85
+ function reads({ hostFiles }) {
86
+ return [
87
+ `echo "PROBE|reads|control|$(cat /workspace/${CONTROL_FILE})"`,
88
+ ...hostFiles.flatMap((file) => [
89
+ // The path as it is, and through the first process's root.
90
+ `for p in ${quote(file)} ${quote(`/proc/1/root${file}`)}; do`,
91
+ ` if cat "$p" 2>/dev/null; then echo; echo "PROBE|reads|file|read|$p"; else echo "PROBE|reads|file|absent|$p"; fi`,
92
+ "done",
93
+ ]),
94
+ // A canary anywhere the shell can read, whatever the file is called. The
95
+ // workspace holds one the sweep must find, and its status says it ended.
96
+ `swept=$(timeout ${SWEEP_SECONDS} grep -rIsoh --devices=skip --exclude-dir=proc --exclude-dir=sys --exclude-dir=dev '${CANARY_PATTERN}' / 2>/dev/null)`,
97
+ 'echo "PROBE|reads|sweep|$?"',
98
+ `printf '%s\\n' "$swept" | sort -u | head -n 20`,
99
+ ];
100
+ }
101
+
102
+ function writes({ hostFiles, resultPath }) {
103
+ const out = resultPath.slice(0, resultPath.lastIndexOf("/"));
104
+ return [
105
+ 'cd /workspace && echo "edited by the probe" >> README.md && echo "PROBE|writes|edit|done"',
106
+ // A write to .git, and a bundle of the edit, beside the result.
107
+ "git init -q 2>&1",
108
+ "git config user.email probe@example.invalid && git config user.name probe",
109
+ "git config core.hooksPath /tmp/probe-hooks",
110
+ `git add -A 2>&1 && git commit -qm probe 2>&1`,
111
+ `mkdir -p ${out} && git bundle create ${out}/result.bundle HEAD >/dev/null 2>&1 && echo "PROBE|writes|bundle|made"`,
112
+ ...hostFiles.map(
113
+ (file) => `(mkdir -p "$(dirname ${quote(file)})" && echo breached > ${quote(file)}) 2>&1`,
114
+ ),
115
+ ];
116
+ }
117
+
118
+ function github() {
119
+ return [
120
+ ...ENVIRONMENT,
121
+ "git -C /workspace config --list --show-origin 2>/dev/null | sed 's/^/GITCONFIG /'",
122
+ "cat ~/.git-credentials ~/.config/gh/hosts.yml 2>/dev/null",
123
+ ];
124
+ }
125
+
126
+ function key() {
127
+ return [
128
+ ...ENVIRONMENT,
129
+ 'for f in /proc/[0-9]*/cmdline; do c=$(tr \'\\0\\n\' \' \' < "$f" 2>/dev/null | head -c 200); [ -n "$c" ] && echo "CMD $c"; done',
130
+ `grep -ahso '${CANARY_PATTERN}' /proc/[0-9]*/environ /proc/[0-9]*/cmdline 2>/dev/null | head -n 20`,
131
+ ];
132
+ }
133
+
134
+ function config({ removed = [] }) {
135
+ return [
136
+ `ls ${MARKER_DIR} 2>/dev/null | sed 's/^/PROBE|config|marker|/'`,
137
+ `echo "PROBE|config|planted-env|\${${PLANTED_ENV}:-unset}"`,
138
+ // What the Launcher removes from the copy must not be there.
139
+ ...removed.map(
140
+ (path) =>
141
+ `if [ -e ${quote(`/workspace/${path}`)} ]; then echo "PROBE|config|present|${path}"; else echo "PROBE|config|absent|${path}"; fi`,
142
+ ),
143
+ ];
144
+ }
145
+
146
+ function network({ hostTargets, baseUrlVariable = "ANTHROPIC_BASE_URL" }) {
147
+ const attempt = (name, ...args) => `attempt ${name} ${args.map(quote).join(" ")}`;
148
+ return [
149
+ // curl's exit code, the HTTP status, the seconds to connect (0 when it never
150
+ // did) and a proxy's answer to CONNECT.
151
+ "attempt() {",
152
+ " name=$1; shift",
153
+ ` seen=$(curl -s -o /dev/null --max-time ${CONNECT_SECONDS} -w '%{exitcode} %{http_code} %{time_connect} %{http_connect}' "$@" 2>/dev/null)`,
154
+ ' echo "PROBE|network|$name|$seen"',
155
+ "}",
156
+ attempt("outside-host", "https://example.com/"),
157
+ attempt("outside-address", "https://1.1.1.1/"),
158
+ attempt(
159
+ "metadata",
160
+ "-H",
161
+ "Metadata: true",
162
+ "http://169.254.169.254/metadata/instance?api-version=2021-02-01",
163
+ ),
164
+ attempt("docker-socket", "--unix-socket", "/var/run/docker.sock", "http://localhost/version"),
165
+ attempt("docker-socket-run", "--unix-socket", "/run/docker.sock", "http://localhost/version"),
166
+ ...hostTargets.map((t, i) => attempt(`host-${i}`, `http://${t.host}:${t.port}/`)),
167
+ 'if ! command -v getent >/dev/null; then echo "PROBE|network|dns|notool"; elif getent hosts example.com >/dev/null 2>&1; then echo "PROBE|network|dns|resolved"; else echo "PROBE|network|dns|unresolved"; fi',
168
+ // The one route there is, and what it refuses: a path outside the model
169
+ // API, and being used as a proxy to anywhere else.
170
+ // The proxy's origin: the variable may name the API's base, ending /v1.
171
+ `proxy=\${${baseUrlVariable}%/v1}`,
172
+ 'attempt proxy "$proxy/agent-kit-probe"',
173
+ 'attempt proxy-forward -x "$proxy" http://example.com/',
174
+ 'attempt proxy-connect -x "$proxy" https://example.com/',
175
+ ];
176
+ }
177
+
178
+ const PROBES = Object.freeze({ reads, writes, github, key, config, network });
179
+
180
+ /**
181
+ * The script of commands the stub model runs, in order: one per Guard, then
182
+ * one that writes every probe's output as the run's result.
183
+ * @param {{
184
+ * hostFiles: string[],
185
+ * hostTargets: Array<{ host: string, port: number }>,
186
+ * resultPath: string,
187
+ * baseUrlVariable?: string,
188
+ * removed?: readonly string[],
189
+ * resultHeading?: string,
190
+ * resultAsReview?: boolean,
191
+ * resultAsPlan?: boolean,
192
+ * resultAsImplement?: boolean,
193
+ * resultAsReviewResponse?: boolean,
194
+ * extra?: Readonly<Record<string, string>>,
195
+ * }} opts `hostFiles` are canary files on the host, outside the sandbox, and
196
+ * `hostTargets` the addresses the host listens on, which the sandbox must
197
+ * not reach. `baseUrlVariable` names the model proxy in the sandbox, and
198
+ * `removed` are the checkout paths the Launcher removes from the copy.
199
+ * `resultHeading` is written as the result's first line, where the run's
200
+ * result is valid only with it. With `resultAsReview`, the result is a review
201
+ * Stage result whose one note holds the probes' output, with `resultAsPlan`
202
+ * a plan that holds it, and with `resultAsImplement` an implement result
203
+ * whose body does. `extra` adds a scenario's own probes, by name, after the
204
+ * Guards' and before the result is written.
205
+ * @returns {Array<{ guard: string, script: string }>}
206
+ */
207
+ export function probeScripts(opts) {
208
+ const probes = Object.entries(PROBES).map(([guard, lines]) => ({
209
+ guard,
210
+ // In a subshell, so a probe's `cd` and functions are its own.
211
+ script: ["(", ...lines(opts), `echo "PROBE|${guard}|end"`, `) 2>&1 | tee -a ${LOG}`].join("\n"),
212
+ }));
213
+ for (const [guard, script] of Object.entries(opts.extra ?? {})) {
214
+ probes.push({ guard, script: ["(", script, `) 2>&1 | tee -a ${LOG}`].join("\n") });
215
+ }
216
+ const folder = opts.resultPath.slice(0, opts.resultPath.lastIndexOf("/"));
217
+ // With a heading, the result opens with it, before every probe's output.
218
+ const encoder = opts.resultAsReview
219
+ ? REVIEW_RESULT
220
+ : opts.resultAsPlan
221
+ ? PLAN_RESULT
222
+ : opts.resultAsImplement
223
+ ? IMPLEMENT_RESULT
224
+ : opts.resultAsReviewResponse
225
+ ? RESPONSE_RESULT
226
+ : null;
227
+ const written = encoder
228
+ ? `python3 -c ${quote(encoder)} < ${LOG} > ${opts.resultPath}`
229
+ : opts.resultHeading
230
+ ? `{ echo ${quote(opts.resultHeading)}; cat ${LOG}; } > ${opts.resultPath}`
231
+ : `cp ${LOG} ${opts.resultPath}`;
232
+ return [
233
+ ...probes,
234
+ {
235
+ guard: "result",
236
+ script: `mkdir -p ${folder} && ${written} && echo "PROBE|result|end"`,
237
+ },
238
+ ];
239
+ }