@mnaimfaizy/agent-kit 1.0.0-beta.14 → 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 (76) 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 +270 -33
  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 +113 -4
  29. package/src/harness/adapters.mjs +30 -0
  30. package/src/harness/antigravity.mjs +187 -0
  31. package/src/harness/claude-code.mjs +8 -1
  32. package/src/harness/codex.mjs +219 -0
  33. package/src/harness/cursor.mjs +199 -0
  34. package/src/harness/custom/registry.mjs +21 -0
  35. package/src/harness/custom/schema.mjs +90 -0
  36. package/src/harness/custom.mjs +299 -0
  37. package/src/harness/facts.mjs +44 -7
  38. package/src/harness/gemini.mjs +164 -0
  39. package/src/harness/install-layer.mjs +86 -3
  40. package/src/harness/opencode.mjs +289 -0
  41. package/src/harness/resolve.mjs +156 -0
  42. package/src/harness/support-levels.mjs +151 -3
  43. package/src/harness-live/assess.mjs +29 -6
  44. package/src/harness-live/cursor-real.mjs +146 -0
  45. package/src/harness-live/cursor-version.mjs +70 -0
  46. package/src/harness-live/cursor.mjs +80 -0
  47. package/src/harness-live/custom.mjs +91 -0
  48. package/src/harness-live/fixture-harness.mjs +45 -0
  49. package/src/harness-live/harnesses.mjs +263 -0
  50. package/src/harness-live/host.mjs +113 -4
  51. package/src/harness-live/opencode.mjs +289 -0
  52. package/src/harness-live/probes.mjs +87 -7
  53. package/src/harness-live/run.mjs +101 -20
  54. package/src/harness-live/setup.mjs +126 -0
  55. package/src/harness-live/stage.mjs +25 -15
  56. package/src/harness-live/suite.mjs +276 -95
  57. package/src/harness-test.mjs +116 -0
  58. package/src/init.mjs +313 -13
  59. package/src/model-proxy/core.mjs +128 -20
  60. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  61. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  62. package/src/model-proxy/profiles/openai.mjs +327 -0
  63. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  64. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  65. package/src/model-proxy/stub.mjs +9 -1
  66. package/src/stage/audit.mjs +79 -0
  67. package/src/stage/egress-route.mjs +207 -0
  68. package/src/stage/implement/carry.mjs +308 -0
  69. package/src/stage/implement/sandbox.mjs +271 -0
  70. package/src/stage/implement/verify.mjs +70 -0
  71. package/src/stage/implement.mjs +218 -0
  72. package/src/stage/plan.mjs +115 -0
  73. package/src/stage/review-response.mjs +172 -0
  74. package/src/stage/review.mjs +185 -0
  75. package/src/stage/workspace.mjs +274 -0
  76. package/src/stage.mjs +1068 -0
@@ -0,0 +1,178 @@
1
+ // The stub model's `gemini-api` dialect (ADR 0031): how a Gemini API request
2
+ // reads and how an answer is written, whole or as a stream, in the shapes the
3
+ // pinned Gemini CLI speaks. The stub itself (../stub.mjs) holds the script;
4
+ // this holds the wire shapes. Node core only (ADR 0001).
5
+ //
6
+ // The model and the method are in the path. Gemini CLI declares its tools as
7
+ // function declarations, prefixes a call's id with the tool's name when it
8
+ // sends the result back, and wraps its shell's output in an
9
+ // `untrusted_context` element with `Output:` before it and the command's
10
+ // status after it.
11
+ //
12
+ // Antigravity CLI speaks the same API. Its shell tool is `run_command`, which
13
+ // takes the command as `CommandLine`, reports it with its exit status before
14
+ // its output, cuts the middle out of a long output, and after ten seconds at
15
+ // most puts a command in the background, reporting it later in a message of
16
+ // its own. So its command goes to bash encoded and the output comes back
17
+ // compressed, and a command still in the background is pending.
18
+ //
19
+ // Headless, Gemini CLI denies a command that repeats a flag, a URL or a path
20
+ // outside the workspace seen in an earlier tool's output, even with every tool
21
+ // approved. So each of the script's commands is handed to the shell encoded:
22
+ // what the live suite probes is the sandbox's Guards, not that filter, which
23
+ // anything the agent runs can pass the same way.
24
+
25
+ import { gunzipSync } from "node:zlib";
26
+
27
+ /** The tokens every answer reports, so the proxy has usage to count. */
28
+ const USAGE = Object.freeze({
29
+ promptTokenCount: 10,
30
+ candidatesTokenCount: 5,
31
+ totalTokenCount: 15,
32
+ });
33
+
34
+ /** Antigravity CLI's shell tool. */
35
+ const AGY_SHELL = "run_command";
36
+
37
+ /** The longest Antigravity CLI waits on a command before it backgrounds it. */
38
+ const AGY_WAIT_MS = 10_000;
39
+
40
+ /** What Antigravity CLI says of a command it put in the background, with its task's id. */
41
+ const BACKGROUND = /^Tool is running as a background task with task id: (\S+)/;
42
+
43
+ /** A command's exit status, as Antigravity CLI reports it. */
44
+ const EXITED = /Command exited with code (\d+)\./;
45
+
46
+ /** A command's output, compressed, as `agyCommand` writes it. */
47
+ const PACKED = /<gz>([A-Za-z0-9+/=\s]*)<\/gz>/;
48
+
49
+ /** The most a command's output may unpack to. */
50
+ const MAX_UNPACKED = 10 * 1024 * 1024;
51
+
52
+ /** The bash line that runs `command`, writes its output compressed and keeps its status. */
53
+ const agyCommand = (command) =>
54
+ [
55
+ "printf '<gz>'",
56
+ `echo ${Buffer.from(command, "utf8").toString("base64")} | base64 -d | bash 2>&1 | gzip -9nc | base64 -w0`,
57
+ "status=${PIPESTATUS[2]}",
58
+ "printf '</gz>'",
59
+ "exit $status",
60
+ ].join("; ");
61
+
62
+ /** Every text part of the conversation. */
63
+ const texts = (request) =>
64
+ (Array.isArray(request.contents) ? request.contents : [])
65
+ .flatMap((content) => (Array.isArray(content?.parts) ? content.parts : []))
66
+ .map((part) => part?.text)
67
+ .filter((text) => typeof text === "string");
68
+
69
+ /** A `run_command` result: pending while its task has not been reported. */
70
+ function agyResult(request, { id, response }) {
71
+ const failed = typeof response?.error === "string";
72
+ let said = failed ? response.error : String(response?.output ?? "");
73
+ const task = BACKGROUND.exec(said)?.[1];
74
+ if (task !== undefined) {
75
+ const finished = `Task id "${task}" finished with result:`;
76
+ const report = texts(request).find((text) => text.includes(finished));
77
+ if (report === undefined) return { id: String(id), text: "", isError: false, pending: true };
78
+ said = report.slice(report.indexOf(finished) + finished.length);
79
+ }
80
+ const status = EXITED.exec(said)?.[1];
81
+ const packed = PACKED.exec(said)?.[1];
82
+ let text = said;
83
+ if (packed !== undefined) {
84
+ try {
85
+ text = gunzipSync(Buffer.from(packed, "base64"), {
86
+ maxOutputLength: MAX_UNPACKED,
87
+ }).toString("utf8");
88
+ } catch {
89
+ text = said;
90
+ }
91
+ }
92
+ return { id: String(id), text, isError: failed || (status ?? "0") !== "0" };
93
+ }
94
+
95
+ const PATH = /^\/v1beta\/models\/([^/:]+):(generateContent|streamGenerateContent|countTokens)$/;
96
+
97
+ /** What Gemini CLI appends to a shell's output, each on a line of its own. */
98
+ const STATUS = /\n(?:Error|Exit Code|Signal|Background PIDs|Process Group PGID): [^\n]*$/;
99
+
100
+ /** A shell result's text as the command printed it; any other text as it is. */
101
+ function printed(text) {
102
+ const wrapped = /^<untrusted_context[^>]*>\n([\s\S]*)\n<\/untrusted_context>$/.exec(text);
103
+ let inner = wrapped ? wrapped[1] : text;
104
+ inner = inner.replaceAll("&lt;/untrusted_context&gt;", "</untrusted_context>");
105
+ if (!inner.startsWith("Output: ")) return inner;
106
+ inner = inner.slice("Output: ".length);
107
+ while (STATUS.test(inner)) inner = inner.replace(STATUS, "");
108
+ return inner;
109
+ }
110
+
111
+ /** The function responses the conversation holds. */
112
+ const responses = (request) =>
113
+ (Array.isArray(request.contents) ? request.contents : [])
114
+ .flatMap((content) => (Array.isArray(content?.parts) ? content.parts : []))
115
+ .map((part) => part?.functionResponse)
116
+ .filter(Boolean);
117
+
118
+ /** @type {Readonly<import("../stub.mjs").StubDialect>} */
119
+ export const geminiApiDialect = Object.freeze({
120
+ /** The functions a request declares, each in the shape the stub picks a shell by. */
121
+ tools: (request) =>
122
+ (Array.isArray(request.tools) ? request.tools : [])
123
+ .flatMap((tool) => tool?.functionDeclarations ?? [])
124
+ .map((f) => {
125
+ const schema = f?.parametersJsonSchema ?? f?.parameters;
126
+ // The stub picks a shell by its `command` input.
127
+ return f?.name === AGY_SHELL && schema?.properties?.CommandLine
128
+ ? { name: f.name, input_schema: { properties: { command: { type: "string" } } } }
129
+ : { name: f?.name, input_schema: schema };
130
+ }),
131
+ /** What the shell tool is called with: the command, encoded, for bash to run. */
132
+ shellInput: (tool, command) =>
133
+ tool?.name === AGY_SHELL
134
+ ? {
135
+ CommandLine: agyCommand(command),
136
+ toolSummary: "Stub probe",
137
+ WaitMsBeforeAsync: AGY_WAIT_MS,
138
+ }
139
+ : { command: `echo ${Buffer.from(command, "utf8").toString("base64")} | base64 -d | bash` },
140
+ /** Every tool result the conversation holds, each by the id the stub gave its call. */
141
+ toolResults: (request) =>
142
+ responses(request).map(({ id, name, response }) => {
143
+ if (name === AGY_SHELL) return agyResult(request, { id, response });
144
+ const failed = typeof response?.error === "string";
145
+ return {
146
+ id: String(id).replace(new RegExp(`^${String(name).replace(/\W/g, "\\$&")}__`), ""),
147
+ // Gemini CLI's result is `output`; opencode's is `content`.
148
+ text: failed
149
+ ? response.error
150
+ : printed(String(response?.output ?? response?.content ?? "")),
151
+ isError: failed,
152
+ };
153
+ }),
154
+ /** The answer to a POST of `path`, or null for a path this dialect does not speak. */
155
+ answer({ path, request, turn }) {
156
+ const [, model, method] = PATH.exec(path) ?? [];
157
+ if (!model) return null;
158
+ if (method === "countTokens") return json({ totalTokens: USAGE.promptTokenCount });
159
+ // A side call that asks for JSON, as Gemini CLI's model router does, gets
160
+ // an empty object, which it reads as no choice of its own.
161
+ const asksJson = request.generationConfig?.responseMimeType === "application/json";
162
+ const next = asksJson && !request.tools ? { text: "{}" } : turn();
163
+ const part = next.call
164
+ ? { functionCall: { id: next.call.id, name: next.call.name, args: next.call.input } }
165
+ : { text: next.text };
166
+ const whole = {
167
+ candidates: [{ content: { role: "model", parts: [part] }, finishReason: "STOP", index: 0 }],
168
+ usageMetadata: USAGE,
169
+ modelVersion: model,
170
+ };
171
+ if (method === "generateContent") return json(whole);
172
+ return { type: "text/event-stream", body: `data: ${JSON.stringify(whole)}\r\n\r\n` };
173
+ },
174
+ });
175
+
176
+ function json(body) {
177
+ return { type: "application/json", body: JSON.stringify(body) };
178
+ }
@@ -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
+ });
@@ -30,7 +30,8 @@ const MAX_ECHO = 4000;
30
30
  * @typedef {{
31
31
  * tools: (request: any) => unknown,
32
32
  * shellInput: (tool: any, command: string, timeoutMs: number) => object,
33
- * toolResults: (request: any) => Array<{ id: string, text: string, isError: boolean }>,
33
+ * toolResults: (request: any) =>
34
+ * Array<{ id: string, text: string, isError: boolean, pending?: boolean }>,
34
35
  * answer: (opts: { path: string, request: any, id: string, turn: () => Turn }) =>
35
36
  * { type: string, body: string } | null,
36
37
  * }} StubDialect
@@ -94,15 +95,22 @@ export async function startStubModel({
94
95
  /** The next turn: the command after the last one the conversation has a result for. */
95
96
  function turnFor(request) {
96
97
  let next = 0;
98
+ let running = false;
97
99
  for (const result of dialect.toolResults(request)) {
98
100
  const index = indexOf(result.id);
99
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
+ }
100
107
  results.set(index, { index, text: result.text, isError: result.isError });
101
108
  next = Math.max(next, index + 1);
102
109
  }
103
110
  const tool = pickShellTool(dialect.tools(request), shellTool);
104
111
  // A request with no shell tool (a harness's own side calls) runs nothing.
105
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." };
106
114
  if (next < script.length) {
107
115
  called = tool.name;
108
116
  return {
@@ -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
+ }