@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,173 @@
1
+ // The stub model's `openai` dialect (ADR 0031): how a Responses API request
2
+ // reads and how an answer is written, whole or as a stream, in the shapes the
3
+ // pinned Codex CLI speaks. The stub itself (../stub.mjs) holds the script;
4
+ // this holds the wire shapes. Node core only (ADR 0001).
5
+ //
6
+ // Codex declares its tools in the request's `tools`, or in an
7
+ // `additional_tools` item of its input, often inside namespaces. For most
8
+ // models its shell is "code mode": one custom `exec` tool that runs
9
+ // JavaScript, from which the shell is called. For the others it is a function
10
+ // tool, `exec_command` or `shell_command`.
11
+
12
+ /** The tokens every answer reports, so the proxy has usage to count. */
13
+ const USAGE = Object.freeze({
14
+ input_tokens: 10,
15
+ input_tokens_details: Object.freeze({ cached_tokens: 0 }),
16
+ output_tokens: 5,
17
+ output_tokens_details: Object.freeze({ reasoning_tokens: 0 }),
18
+ total_tokens: 15,
19
+ });
20
+
21
+ /** The namespace whose tools are called by their bare names. */
22
+ const DEFAULT_NAMESPACE = "functions";
23
+
24
+ /** The shell function tools, and the argument each takes its command in. */
25
+ const SHELL_FUNCTIONS = Object.freeze({
26
+ exec_command: "cmd",
27
+ shell_command: "command",
28
+ // opencode's.
29
+ shell: "command",
30
+ });
31
+
32
+ /** The longest one wait on a running command, which Codex holds it to. */
33
+ const WAIT_MS = 30_000;
34
+
35
+ /** The most output tokens a command's result may keep, far above a probe's. */
36
+ const MAX_OUTPUT_TOKENS = 100_000;
37
+
38
+ /** Every tool `tools` declares, each with its namespace. */
39
+ function declared(tools, namespace) {
40
+ if (!Array.isArray(tools)) return [];
41
+ return tools.flatMap((tool) =>
42
+ tool?.type === "namespace" ? declared(tool.tools, tool.name) : [{ ...tool, namespace }],
43
+ );
44
+ }
45
+
46
+ /** The input items a request holds. */
47
+ const items = (request) => (Array.isArray(request.input) ? request.input : []);
48
+
49
+ /**
50
+ * The JavaScript that runs `command` in code mode and prints its output: the
51
+ * shell returns after WAIT_MS at most, so a command still running is waited
52
+ * for until it ends. The first line keeps the script itself from yielding.
53
+ */
54
+ function script(command, timeoutMs) {
55
+ const limits = `yield_time_ms: ${WAIT_MS}, max_output_tokens: ${MAX_OUTPUT_TOKENS}`;
56
+ return [
57
+ `// @exec: ${JSON.stringify({ yield_time_ms: timeoutMs, max_output_tokens: MAX_OUTPUT_TOKENS })}`,
58
+ `let r = await tools.exec_command({ cmd: ${JSON.stringify(command)}, login: false, ${limits} });`,
59
+ "let output = r.output;",
60
+ "while (r.session_id !== undefined) {",
61
+ ` r = await tools.write_stdin({ session_id: r.session_id, chars: "", ${limits} });`,
62
+ " output += r.output;",
63
+ "}",
64
+ "text(output);",
65
+ ].join("\n");
66
+ }
67
+
68
+ /** A tool output's text: a string, or its text parts joined. */
69
+ function textOf(output) {
70
+ if (typeof output === "string") return output;
71
+ if (!Array.isArray(output)) return "";
72
+ return output.map((part) => (typeof part?.text === "string" ? part.text : "")).join("");
73
+ }
74
+
75
+ /** The output item for one turn: a tool call, or the closing message. */
76
+ function item({ id, turn }) {
77
+ const { call } = turn;
78
+ if (!call) {
79
+ return {
80
+ type: "message",
81
+ id,
82
+ role: "assistant",
83
+ status: "completed",
84
+ content: [{ type: "output_text", text: turn.text, annotations: [] }],
85
+ };
86
+ }
87
+ const { code, namespace, args } = call.input;
88
+ const base = {
89
+ id: `${id}_call`,
90
+ call_id: call.id,
91
+ name: call.name,
92
+ ...(namespace !== undefined ? { namespace } : {}),
93
+ };
94
+ return code !== undefined
95
+ ? { type: "custom_tool_call", ...base, input: code }
96
+ : { type: "function_call", ...base, arguments: JSON.stringify(args) };
97
+ }
98
+
99
+ /** The same answer as the API's server-sent events. */
100
+ function stream(whole) {
101
+ const events = [
102
+ [
103
+ "response.created",
104
+ { response: { ...whole, status: "in_progress", output: [], usage: null } },
105
+ ],
106
+ ["response.output_item.done", { output_index: 0, item: whole.output[0] }],
107
+ ["response.completed", { response: whole }],
108
+ ];
109
+ return events
110
+ .map(([type, data]) => `event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`)
111
+ .join("");
112
+ }
113
+
114
+ /** @type {Readonly<import("../stub.mjs").StubDialect>} */
115
+ export const openaiDialect = Object.freeze({
116
+ /**
117
+ * The shell tools a request declares, each in the shape the stub picks one
118
+ * by: a name, and an input that takes a command.
119
+ */
120
+ tools(request) {
121
+ const all = [
122
+ ...declared(request.tools),
123
+ ...items(request)
124
+ .filter((i) => i?.type === "additional_tools")
125
+ .flatMap((i) => declared(i.tools)),
126
+ ];
127
+ return all
128
+ .filter(
129
+ (t) =>
130
+ (t.type === "custom" && t.name === "exec") ||
131
+ (t.type === "function" && Object.hasOwn(SHELL_FUNCTIONS, t.name)),
132
+ )
133
+ .map((t) => ({
134
+ name: t.name,
135
+ kind: t.type,
136
+ namespace: t.namespace === DEFAULT_NAMESPACE ? undefined : t.namespace,
137
+ input_schema: { type: "object", properties: { command: { type: "string" } } },
138
+ }));
139
+ },
140
+ /** What a shell tool is called with: a script for `exec`, else the function's arguments. */
141
+ shellInput(tool, command, timeoutMs) {
142
+ if (tool.kind === "custom") {
143
+ return { namespace: tool.namespace, code: script(command, timeoutMs) };
144
+ }
145
+ if (tool.name === "shell") {
146
+ return { namespace: tool.namespace, args: { command, timeout: timeoutMs } };
147
+ }
148
+ const args =
149
+ tool.name === "exec_command"
150
+ ? { cmd: command, login: false, yield_time_ms: WAIT_MS }
151
+ : { command, login: false, timeout_ms: timeoutMs };
152
+ return { namespace: tool.namespace, args };
153
+ },
154
+ /** Every tool result the conversation holds. */
155
+ toolResults: (request) =>
156
+ items(request)
157
+ .filter((i) => i?.type === "function_call_output" || i?.type === "custom_tool_call_output")
158
+ .map((i) => ({ id: String(i.call_id), text: textOf(i.output), isError: false })),
159
+ /** The answer to a POST of `path`, or null for a path this dialect does not speak. */
160
+ answer({ path, request, id, turn }) {
161
+ if (path !== "/v1/responses") return null;
162
+ const whole = {
163
+ id: id.replace(/^msg_/, "resp_"),
164
+ object: "response",
165
+ status: "completed",
166
+ model: String(request.model ?? "stub-model"),
167
+ output: [item({ id, turn: turn() })],
168
+ usage: USAGE,
169
+ };
170
+ if (request.stream !== true) return { type: "application/json", body: JSON.stringify(whole) };
171
+ return { type: "text/event-stream", body: stream(whole) };
172
+ },
173
+ });
@@ -0,0 +1,182 @@
1
+ // The stub model (ADR 0031): a kit-owned scripted server that stands in for
2
+ // a model API behind the real model proxy, as the proxy's upstream. It
3
+ // answers a harness with a fixed list of shell commands, one tool call per
4
+ // turn, calling the shell tool it picks from the tools the request declares,
5
+ // and ends once each has its result. So the live suite can make a real,
6
+ // pinned harness attempt exactly what it wants attempted, with no key, no
7
+ // spend and the same answers on every run.
8
+ //
9
+ // It also records every request that reached it, which is everything the
10
+ // harness sent past the proxy: the live suite's host-side evidence. It speaks
11
+ // one provider's wire shapes per dialect (stub-dialects/). It holds no
12
+ // credential and is not part of any Consumer's run. Node core only (ADR 0001).
13
+
14
+ import { createServer } from "node:http";
15
+ import { anthropicDialect } from "./stub-dialects/anthropic.mjs";
16
+
17
+ /** The names harnesses give their shell tool, preferred over any other tool that takes a command. */
18
+ const SHELL_NAMES = /^(bash|shell|local_shell|exec_command|run_shell_command|run_terminal_cmd)$/i;
19
+
20
+ /** The largest request the stub reads: the proxy forwards no larger one. */
21
+ const MAX_REQUEST = 32 * 1024 * 1024;
22
+
23
+ /** How long a tool call may run, for a shell tool that takes a timeout. */
24
+ const COMMAND_TIMEOUT_MS = 120_000;
25
+
26
+ /** How much of each result the closing answer repeats, so the harness's own output holds it. */
27
+ const MAX_ECHO = 4000;
28
+
29
+ /**
30
+ * @typedef {{
31
+ * tools: (request: any) => unknown,
32
+ * shellInput: (tool: any, command: string, timeoutMs: number) => object,
33
+ * toolResults: (request: any) =>
34
+ * Array<{ id: string, text: string, isError: boolean, pending?: boolean }>,
35
+ * answer: (opts: { path: string, request: any, id: string, turn: () => Turn }) =>
36
+ * { type: string, body: string } | null,
37
+ * }} StubDialect
38
+ * @typedef {{ call?: { id: string, name: string, input: object }, text?: string }} Turn
39
+ * One turn of the script: a tool call, or the closing text.
40
+ */
41
+
42
+ /**
43
+ * The shell tool among `tools`, or null: the one named `preferred` when a
44
+ * name is given, else a tool with a shell's name, else the first whose input
45
+ * takes a `command` string.
46
+ * @param {unknown} tools
47
+ * @param {string} [preferred] a Custom harness file's `probe_shell_tool`
48
+ * @returns {any}
49
+ */
50
+ export function pickShellTool(tools, preferred) {
51
+ if (!Array.isArray(tools)) return null;
52
+ const declared = tools.filter((t) => typeof t?.name === "string");
53
+ if (preferred !== undefined) return declared.find((t) => t.name === preferred) ?? null;
54
+ const runs = declared.filter((t) => t.input_schema?.properties?.command?.type === "string");
55
+ return runs.find((t) => SHELL_NAMES.test(t.name)) ?? runs[0] ?? null;
56
+ }
57
+
58
+ /**
59
+ * Start the stub model.
60
+ * @param {{ commands?: string[], shellTool?: string, bind?: string, dialect?: StubDialect }} [opts]
61
+ * `commands` is the script. `shellTool` names the tool to call, for a
62
+ * harness whose shell tool the request does not make plain.
63
+ * @returns {Promise<{
64
+ * url: string,
65
+ * requests: Array<{ method: string, path: string, headers: Record<string, unknown>, body: string }>,
66
+ * results: () => Array<{ index: number, text: string, isError: boolean }>,
67
+ * shellTool: () => string | null,
68
+ * script: (commands: string[]) => void,
69
+ * close: () => Promise<void>,
70
+ * }>} `results` are the current script's tool results, by command, as the
71
+ * harness last sent them. `shellTool` is the tool the stub called, or null
72
+ * if no request declared one. `script` replaces the script.
73
+ */
74
+ export async function startStubModel({
75
+ commands = [],
76
+ shellTool,
77
+ bind = "127.0.0.1",
78
+ dialect = anthropicDialect,
79
+ } = {}) {
80
+ const requests = [];
81
+ let generation = 0;
82
+ let script = [...commands];
83
+ let answers = 0;
84
+ let called = null;
85
+ /** @type {Map<number, { index: number, text: string, isError: boolean }>} */
86
+ const results = new Map();
87
+
88
+ /** The id of the current script's call `index`, so no other script's result counts as its. */
89
+ const callId = (index) => `toolu_stub_${generation}_${index}`;
90
+ const indexOf = (id) => {
91
+ const prefix = `toolu_stub_${generation}_`;
92
+ return id.startsWith(prefix) ? Number(id.slice(prefix.length)) : -1;
93
+ };
94
+
95
+ /** The next turn: the command after the last one the conversation has a result for. */
96
+ function turnFor(request) {
97
+ let next = 0;
98
+ let running = false;
99
+ for (const result of dialect.toolResults(request)) {
100
+ const index = indexOf(result.id);
101
+ if (!Number.isInteger(index) || index < 0 || index >= script.length) continue;
102
+ // A command the harness still runs: its result comes in a later request.
103
+ if (result.pending) {
104
+ running = true;
105
+ continue;
106
+ }
107
+ results.set(index, { index, text: result.text, isError: result.isError });
108
+ next = Math.max(next, index + 1);
109
+ }
110
+ const tool = pickShellTool(dialect.tools(request), shellTool);
111
+ // A request with no shell tool (a harness's own side calls) runs nothing.
112
+ if (!tool) return { text: "stub model: no shell tool was declared." };
113
+ if (running) return { text: "stub model: waiting for the command to finish." };
114
+ if (next < script.length) {
115
+ called = tool.name;
116
+ return {
117
+ call: {
118
+ id: callId(next),
119
+ name: tool.name,
120
+ input: dialect.shellInput(tool, script[next], COMMAND_TIMEOUT_MS),
121
+ },
122
+ };
123
+ }
124
+ const echo = [...results.values()].map((r) => r.text.slice(0, MAX_ECHO));
125
+ return { text: ["stub model: the script is done.", ...echo].join("\n") };
126
+ }
127
+
128
+ const server = createServer((req, res) => {
129
+ const chunks = [];
130
+ let size = 0;
131
+ req.on("data", (chunk) => {
132
+ size += chunk.length;
133
+ if (size <= MAX_REQUEST) chunks.push(chunk);
134
+ });
135
+ req.on("error", () => res.destroy());
136
+ req.on("end", () => {
137
+ const body = Buffer.concat(chunks).toString("utf8");
138
+ const url = req.url ?? "";
139
+ requests.push({ method: req.method ?? "", path: url, headers: { ...req.headers }, body });
140
+ let request = null;
141
+ try {
142
+ request = JSON.parse(body);
143
+ } catch {
144
+ request = null;
145
+ }
146
+ const answer =
147
+ req.method === "POST" && request && typeof request === "object"
148
+ ? dialect.answer({
149
+ path: url.split("?")[0],
150
+ request,
151
+ id: `msg_stub_${(answers += 1)}`,
152
+ turn: () => turnFor(request),
153
+ })
154
+ : null;
155
+ if (!answer) {
156
+ res.writeHead(404).end("stub model: not a route it speaks\n");
157
+ return;
158
+ }
159
+ res.writeHead(200, { "content-type": answer.type }).end(answer.body);
160
+ });
161
+ });
162
+ await new Promise((resolve, reject) => {
163
+ server.once("error", reject);
164
+ server.listen(0, bind, () => resolve(undefined));
165
+ });
166
+ const address = server.address();
167
+ return {
168
+ url: `http://${bind}:${typeof address === "object" && address ? address.port : 0}`,
169
+ requests,
170
+ results: () => [...results.values()].sort((a, b) => a.index - b.index),
171
+ shellTool: () => called,
172
+ script(next) {
173
+ generation += 1;
174
+ script = [...next];
175
+ results.clear();
176
+ },
177
+ close: () => {
178
+ server.closeAllConnections();
179
+ return new Promise((resolve) => server.close(() => resolve(undefined)));
180
+ },
181
+ };
182
+ }
@@ -0,0 +1,79 @@
1
+ // What the static security audit is as a CI Stage (ADR 0024): its limits, the
2
+ // paths its brief names in the sandbox, what the Launcher adds to the trusted
3
+ // step's brief, and when its Stage result is valid. The brief itself, with the
4
+ // skill, the prompt and the Threat pack, is built by the trusted step that
5
+ // calls the Launcher, so the report has the shape the audit always had.
6
+
7
+ import { withStopped } from "../deep-scan/limits.mjs";
8
+
9
+ /** The Stage as `cli/harnesses.json` and the settings name it. */
10
+ export const STAGE = "security-audit";
11
+
12
+ /** Where the sandbox holds the checkout. */
13
+ export const WORKSPACE = "/workspace";
14
+
15
+ /** The folder the brief and the prompt go in. */
16
+ export const IN_DIR = "/agent-kit/in";
17
+ export const BRIEF_PATH = `${IN_DIR}/brief.md`;
18
+ /** The one kit-written line the harness gets on its stdin (ADR 0027). */
19
+ export const PROMPT_PATH = `${IN_DIR}/prompt.md`;
20
+ /** The one result path every audit brief names. */
21
+ export const RESULT_PATH = "/agent-kit/out/report.md";
22
+ /** What the file is called when no flag names it. */
23
+ export const RESULT_NAME = "result.md";
24
+ /** A full audit also reads the untracked files (`--untracked`). */
25
+ export const TAKES_UNTRACKED = true;
26
+ /** The page that describes this Stage on the Launcher. */
27
+ export const DOCS_PAGE = "security-audit.md#the-audit-through-the-launcher";
28
+ /** The most of a result that is read out of the sandbox. */
29
+ export const MAX_RESULT_BYTES = 10 * 1024 * 1024;
30
+
31
+ /** The limits an audit runs within unless a flag says otherwise. */
32
+ export const LIMITS = Object.freeze({
33
+ setupMinutes: 10,
34
+ scanMinutes: 30,
35
+ turns: 100,
36
+ tokens: 5_000_000,
37
+ });
38
+
39
+ export const PROMPT = `Read the audit brief at ${BRIEF_PATH} and follow it exactly. Write your complete report to the report path it names, and put no finding, file content or report text in your answer.\n`;
40
+
41
+ /** The Launcher's own opening of the brief, before the trusted step's. */
42
+ export function briefPreamble({ checkoutConfig, instructionFiles }) {
43
+ const listed = (paths) => paths.map((p) => `\`${p}\``).join(", ");
44
+ return [
45
+ "# Stage brief, from the agent-kit Launcher",
46
+ "",
47
+ "You are running the static security audit inside a closed, disposable sandbox. Your only network route is the Launcher's model proxy, and the harness's own web and server-side tools are off. Nothing you change here is kept.",
48
+ "",
49
+ `- The repository: \`${WORKSPACE}\`, a copy of the checked-out commit, with no \`.git\` folder.`,
50
+ `- The report: write it to \`${RESULT_PATH}\`, early, and update it as each finding lands. It is the one result that leaves the sandbox.`,
51
+ `- The harness's own config is not in the copy (${listed(checkoutConfig)}), so none of it could configure you: its absence is no finding.`,
52
+ `- The files the harness loads by itself (${listed(instructionFiles)}) are the trusted commit's, whatever the audited change holds.`,
53
+ "",
54
+ "-----",
55
+ "",
56
+ "",
57
+ ].join("\n");
58
+ }
59
+
60
+ /**
61
+ * Why `data` is no Stage result, or null when it is one: an audit report,
62
+ * which opens with the heading report-format.md gives every report.
63
+ * @param {Buffer} data
64
+ * @returns {string | null}
65
+ */
66
+ export function invalid(data) {
67
+ return /^## Security audit report[ \t]*\r?$/m.test(data.toString("utf8"))
68
+ ? null
69
+ : "the file there is not an audit report (no `## Security audit report` heading)";
70
+ }
71
+
72
+ /**
73
+ * The report as the run hands it on: marked as partial when a limit stopped it.
74
+ * @param {Buffer} data
75
+ * @param {string | null} limit
76
+ */
77
+ export const markStopped = (data, limit) => withStopped(data, limit);
78
+ /** What the result's line adds on a run a limit stopped. */
79
+ export const stoppedNote = (limit) => `partial: marked Stopped: ${limit}`;
@@ -0,0 +1,207 @@
1
+ // The weaker form of the key and network Guards (ADR 0025), for a harness the
2
+ // model proxy cannot front (Cursor CLI): the sandbox's one route out is the
3
+ // Launcher's allowlist proxy, to the harness's own hosts; the vendor key sits
4
+ // in the sandbox; and a Stage result or bundle holding the key is refused.
5
+
6
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { startEgressProxy } from "../deep-scan/egress.mjs";
10
+ import { StepFailed } from "../deep-scan/steps.mjs";
11
+
12
+ /** The hosts `plan` may reach through the allowlist proxy, or null for a model-proxy harness. */
13
+ export const egressHosts = (plan) => plan.modelRoute?.egress?.hosts ?? null;
14
+
15
+ /**
16
+ * What a Stage brief says of the sandbox's one route out: the model proxy, or
17
+ * on the weaker form the allowlist proxy, with the key's rule for the agent.
18
+ * @param {{ modelRoute?: { egress?: { hosts: string[] } } }} shape
19
+ */
20
+ export function routeSentence(shape) {
21
+ return egressHosts(shape) === null
22
+ ? "Your only network route is the Launcher's model proxy"
23
+ : "Your only network route is the Launcher's allowlist proxy, which reaches the model host alone, and your API key sits in this sandbox: never write it, or any encoding of it, into a file, a commit or your result, since a Stage result or commit that holds it is refused";
24
+ }
25
+
26
+ /**
27
+ * Open the one route out: the allowlist proxy on this machine, to `hosts` on
28
+ * port 443 alone, through the driver's relay (the slot the model proxy uses on
29
+ * other harnesses), and the check from the host that nothing else is open.
30
+ * @param {{ driver: object, hosts: readonly string[] }} opts
31
+ * @returns the route (its `url` is the proxy as the sandbox reaches it) and a
32
+ * proxy-shaped handle whose `summary()` names what it refused.
33
+ */
34
+ export async function openEgressRoute({ driver, hosts }) {
35
+ let proxy = null;
36
+ const route = await driver.openModelRoute(async (bind) => {
37
+ const started = await startEgressProxy({
38
+ registries: hosts.map((host) => `https://${host}`),
39
+ bind,
40
+ });
41
+ proxy = {
42
+ ...started,
43
+ summary: () =>
44
+ started.refused.length
45
+ ? `closed; the allowlist proxy refused ${[...new Set(started.refused)].join(", ")}`
46
+ : "closed; the allowlist proxy refused nothing",
47
+ credentialRefused: () => false,
48
+ };
49
+ return proxy;
50
+ });
51
+ const extra = await driver.egressLeft();
52
+ if (extra !== null) {
53
+ throw new StepFailed([`FAILED more than the allowlist route is open: ${extra}.`]);
54
+ }
55
+ return { route, proxy };
56
+ }
57
+
58
+ /**
59
+ * The forms of `key` a leak is searched for: as it is, reversed, hex, the
60
+ * three alignments of base64 and base64url, percent-encoded, and with a
61
+ * separator between each character. The test is cheap, not complete: an
62
+ * agent set on leaking can encode it another way, which the sandbox's egress
63
+ * and the key's own spend limit are there for.
64
+ * @param {string} key
65
+ * @returns {string[]}
66
+ */
67
+ export function keyForms(key) {
68
+ const bytes = Buffer.from(key, "utf8");
69
+ const forms = new Set([key, [...key].reverse().join("")]);
70
+ forms.add(bytes.toString("hex"));
71
+ forms.add(bytes.toString("hex").toUpperCase());
72
+ forms.add(encodeURIComponent(key));
73
+ for (const sep of [" ", "-", ".", "_", ","]) forms.add([...key].join(sep));
74
+ for (let pad = 0; pad < 3; pad++) {
75
+ const b64 = Buffer.concat([Buffer.alloc(pad), bytes]).toString("base64");
76
+ // The first and last characters of a shifted run depend on its neighbours.
77
+ const inner = b64.replace(/=+$/, "").slice([0, 2, 3][pad], -2);
78
+ if (inner.length >= 8) {
79
+ forms.add(inner);
80
+ forms.add(inner.replace(/\+/g, "-").replace(/\//g, "_"));
81
+ }
82
+ }
83
+ return [...forms].filter((f) => f.length >= 8);
84
+ }
85
+
86
+ /** Whether `data` holds `key` in any of its forms. */
87
+ export function holdsKey(data, key) {
88
+ const text = Buffer.isBuffer(data) ? data.toString("latin1") : String(data);
89
+ return keyForms(key).some((form) => text.includes(Buffer.from(form, "utf8").toString("latin1")));
90
+ }
91
+
92
+ /**
93
+ * Git's variables for the host scan: no system or user config, no replace
94
+ * objects, no hooks. Never the process environment: the runner supplies what
95
+ * git needs (the scrubbed names, the model credential among them, stay out),
96
+ * and what these git processes read is the agent's untrusted bundle.
97
+ */
98
+ const SCAN_ENV = (empty) => ({
99
+ GIT_CONFIG_NOSYSTEM: "1",
100
+ GIT_CONFIG_GLOBAL: empty,
101
+ GIT_NO_REPLACE_OBJECTS: "1",
102
+ GIT_TERMINAL_PROMPT: "0",
103
+ });
104
+
105
+ const SCAN_MAX_BYTES = 1 << 30;
106
+
107
+ /**
108
+ * Whether the agent's bundle holds the key in any form, scanned on the host:
109
+ * nothing the sandbox's git, grep or PATH says is trusted. The bundle is
110
+ * fetched into a temporary bare repository that has the base commit (copied
111
+ * from the checkout at `root`, which the bundle's prerequisite names), with
112
+ * no config, no hooks and no replace objects, and every object the agent's
113
+ * commits add is read raw (commits, trees and binary blobs, never what a diff
114
+ * or an attribute chooses to show). The temporary repository is removed on
115
+ * every path. Returns "key", "replaced" (the bundle carries refs/replace/), or
116
+ * null when clean; a bundle that cannot be read throws.
117
+ * @param {{ runner: import("../exec.mjs").Runner, bundle: Buffer, root: string, commit: string, credential: string }} opts
118
+ */
119
+ export async function scanBundleForKey({ runner, bundle, root, commit, credential }) {
120
+ const dir = mkdtempSync(join(tmpdir(), "agent-kit-key-scan-"));
121
+ try {
122
+ const empty = join(dir, "empty.conf");
123
+ const hooks = join(dir, "hooks");
124
+ const repo = join(dir, "repo");
125
+ const file = join(dir, "agent.bundle");
126
+ writeFileSync(empty, "");
127
+ mkdirSync(hooks);
128
+ writeFileSync(file, bundle);
129
+ const env = SCAN_ENV(empty);
130
+ const git = async (args, input) => {
131
+ const r = await runner.start("git", ["-c", `core.hooksPath=${hooks}`, ...args], {
132
+ env,
133
+ stdin: input,
134
+ maxOutput: SCAN_MAX_BYTES,
135
+ cwd: dir,
136
+ });
137
+ if (r.status !== 0 || r.truncated) {
138
+ throw new StepFailed([
139
+ "FAILED the agent's commits could not be read to check them for the model credential. Nothing was taken.",
140
+ ]);
141
+ }
142
+ return r.stdout;
143
+ };
144
+ await git(["init", "-q", "--bare", repo]);
145
+ const inRepo = async (args, input) => git(["--git-dir", repo, ...args], input);
146
+ await inRepo([
147
+ "fetch",
148
+ "-q",
149
+ "--no-tags",
150
+ "--no-write-fetch-head",
151
+ root,
152
+ `${commit}:refs/base/tip`,
153
+ ]);
154
+ const heads = (await git(["bundle", "list-heads", file])).toString("latin1");
155
+ if (/ refs\/replace\//.test(heads)) return "replaced";
156
+ await inRepo([
157
+ "fetch",
158
+ "-q",
159
+ "--no-tags",
160
+ "--no-write-fetch-head",
161
+ file,
162
+ "HEAD:refs/agent/tip",
163
+ ]);
164
+ const listed = (
165
+ await inRepo(["rev-list", "--objects", "refs/agent/tip", "^refs/base/tip"])
166
+ ).toString("latin1");
167
+ const ids = listed
168
+ .split("\n")
169
+ .map((line) => line.split(" ")[0])
170
+ .filter(Boolean);
171
+ const raw = await inRepo(["cat-file", "--batch"], `${ids.join("\n")}\n`);
172
+ return holdsKey(raw, credential) ? "key" : null;
173
+ } finally {
174
+ rmSync(dir, { recursive: true, force: true });
175
+ }
176
+ }
177
+
178
+ /**
179
+ * The weaker form's last Guard: a Stage result, or a commit of the agent's,
180
+ * that holds the key (in any form keyForms names) fails the run, with nothing
181
+ * written. The commits are scanned on the host from the bundle that came out
182
+ * (`scanBundleForKey`), never in the sandbox. The message never repeats the key.
183
+ * @param {{ runner: import("../exec.mjs").Runner, definition: { WRITES_BUNDLE: boolean }, root: string, commit: string, credential: string, result: Buffer, bundle: Buffer | null }} opts
184
+ */
185
+ export async function refuseHeldKey({
186
+ runner,
187
+ definition,
188
+ root,
189
+ commit,
190
+ credential,
191
+ result,
192
+ bundle,
193
+ }) {
194
+ const refused = (what) =>
195
+ new StepFailed([
196
+ `FAILED the ${what} holds the model credential, which sat in the sandbox (the weaker form, ADR 0025). Nothing was taken.`,
197
+ ]);
198
+ if (holdsKey(result, credential)) throw refused("Stage result");
199
+ if (!definition.WRITES_BUNDLE || !bundle) return;
200
+ const found = await scanBundleForKey({ runner, bundle, root, commit, credential });
201
+ if (found === "key") throw refused("agent's commits");
202
+ if (found === "replaced") {
203
+ throw new StepFailed([
204
+ "FAILED the agent's bundle replaces objects (refs/replace), so its commits cannot be checked for the model credential as they are. Nothing was taken.",
205
+ ]);
206
+ }
207
+ }