@mnaimfaizy/agent-kit 1.0.0-alpha.12 → 1.0.0-beta.10
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.
- package/README.md +14 -6
- package/bin/agent-kit.mjs +3 -1
- package/package.json +1 -1
- package/src/callers.mjs +73 -10
- package/src/checks/kit-owned-trees.mjs +47 -4
- package/src/checks/result.mjs +8 -2
- package/src/checks/review-response.mjs +205 -0
- package/src/checks/rulesets.mjs +7 -2
- package/src/checks/scan-recipe.mjs +56 -0
- package/src/checks/secrets-and-variables.mjs +65 -15
- package/src/cli.mjs +306 -19
- package/src/deep-scan/agent.mjs +410 -0
- package/src/deep-scan/claude-code.mjs +25 -0
- package/src/deep-scan/credential.mjs +215 -0
- package/src/deep-scan/docker-driver.mjs +696 -0
- package/src/deep-scan/egress.mjs +150 -0
- package/src/deep-scan/lifecycle.mjs +703 -0
- package/src/deep-scan/limits.mjs +126 -0
- package/src/deep-scan/model-proxy.mjs +378 -0
- package/src/deep-scan/preflight.mjs +78 -0
- package/src/deep-scan/recipe.mjs +447 -0
- package/src/deep-scan/relay-script.mjs +98 -0
- package/src/deep-scan/relay.mjs +130 -0
- package/src/deep-scan/runtime.mjs +181 -0
- package/src/deep-scan/sbx-driver.mjs +501 -0
- package/src/deep-scan/steps.mjs +47 -0
- package/src/deep-scan/tar.mjs +84 -0
- package/src/deep-scan/verify.mjs +272 -0
- package/src/deep-scan.mjs +474 -0
- package/src/doctor.mjs +57 -16
- package/src/exec.mjs +225 -23
- package/src/init.mjs +653 -0
- package/src/kit-owned-paths.mjs +5 -3
- package/src/kit-tag.mjs +175 -28
- package/src/local-tree.mjs +142 -27
- package/src/local-writes.mjs +278 -0
- package/src/prompt.mjs +42 -0
- package/src/safe-paths.mjs +68 -0
- package/src/tags.mjs +15 -5
- package/src/templates.mjs +137 -0
- package/src/upgrade.mjs +288 -0
- package/src/workflow-call.mjs +3 -5
- package/src/yaml-subset.mjs +134 -24
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
// The Deep scan sandbox lifecycle (#369), from image to teardown, on the
|
|
2
|
+
// runtime `selectRuntime` chose. In order: prepare the image (with a pinned
|
|
3
|
+
// Claude Code, its auto-updater off); start the sandbox with no mount; copy
|
|
4
|
+
// in an export of the trusted ref (never the working tree) and the grounding
|
|
5
|
+
// files, and nothing else; run the setup phase (`setup`, `start`, `ready`,
|
|
6
|
+
// `seed`) with no agent and no model credential, its egress limited to the
|
|
7
|
+
// recipe's `registries`; cut the network and check from the host that it is
|
|
8
|
+
// cut; open the model route (the key-injecting model proxy on the host, the
|
|
9
|
+
// scan's only way out) and check from the host that nothing else is open;
|
|
10
|
+
// hand the agent its brief and run the real Claude Code (#370); copy out the
|
|
11
|
+
// one report file; and destroy the sandbox on every exit path, an interrupt
|
|
12
|
+
// included. The real model credential reaches only the model proxy, in this
|
|
13
|
+
// process: the sandbox gets a placeholder.
|
|
14
|
+
//
|
|
15
|
+
// Every run is bounded from out here (#371): the setup wall clock runs from
|
|
16
|
+
// the image step until the agent step starts, the scan wall clock over the
|
|
17
|
+
// agent step, Claude Code runs with the launcher's `--max-turns`, and the
|
|
18
|
+
// model proxy refuses requests past the token cap. A limit that fires stops
|
|
19
|
+
// the running step through the same seam an interrupt does, then the report
|
|
20
|
+
// it left is copied out with the launcher's `Stopped:` line, and the sandbox
|
|
21
|
+
// is torn down as on every exit path.
|
|
22
|
+
//
|
|
23
|
+
// The runtime's own commands live in a driver: docker-driver.mjs (gVisor,
|
|
24
|
+
// Kata, Firecracker on Docker Engine) and sbx-driver.mjs (Docker
|
|
25
|
+
// Sandboxes). This module owns the order, the output and every refusal.
|
|
26
|
+
|
|
27
|
+
import { randomBytes } from "node:crypto";
|
|
28
|
+
import { mkdtempSync, writeFileSync } from "node:fs";
|
|
29
|
+
import { tmpdir } from "node:os";
|
|
30
|
+
import { join } from "node:path";
|
|
31
|
+
import { firstLine } from "../exec.mjs";
|
|
32
|
+
import { agentBrief, agentEnv, agentScript, BRIEF_PATH, TURNS_MARKER } from "./agent.mjs";
|
|
33
|
+
import { CLAUDE_CODE_VERSION, layerDockerfile } from "./claude-code.mjs";
|
|
34
|
+
import { dockerDriver, LABEL } from "./docker-driver.mjs";
|
|
35
|
+
import {
|
|
36
|
+
LimitReached,
|
|
37
|
+
STOPPED_EXIT,
|
|
38
|
+
stoppedStatus,
|
|
39
|
+
TOKENS,
|
|
40
|
+
TURNS,
|
|
41
|
+
WALL_CLOCK,
|
|
42
|
+
withStopped,
|
|
43
|
+
} from "./limits.mjs";
|
|
44
|
+
import { startModelProxy } from "./model-proxy.mjs";
|
|
45
|
+
import { sbxDriver } from "./sbx-driver.mjs";
|
|
46
|
+
import { ENDS_HERE, indent, Interrupted, outputLines, StepFailed } from "./steps.mjs";
|
|
47
|
+
import { tarOf } from "./tar.mjs";
|
|
48
|
+
import { checkVerificationReport, FINDINGS_PATH, verificationBrief } from "./verify.mjs";
|
|
49
|
+
|
|
50
|
+
export { CLAUDE_CODE_VERSION, LABEL, layerDockerfile };
|
|
51
|
+
|
|
52
|
+
/** Where the sandbox holds the repository, the grounding and the report. */
|
|
53
|
+
export const WORKSPACE = "/workspace";
|
|
54
|
+
export const GROUNDING_DIR = "/agent-kit/grounding";
|
|
55
|
+
export const REPORT_PATH = "/agent-kit/out/report.md";
|
|
56
|
+
|
|
57
|
+
export const MAX_REPORT_BYTES = 10 * 1024 * 1024;
|
|
58
|
+
export const MAX_GROUNDING_BYTES = 10 * 1024 * 1024;
|
|
59
|
+
/**
|
|
60
|
+
* The largest `git archive` export deep-scan holds to copy in (the tree, a
|
|
61
|
+
* grounding path, a Dockerfile's build context): above the runner's default
|
|
62
|
+
* output cap, which a repository with a few bundled assets would pass.
|
|
63
|
+
*/
|
|
64
|
+
export const MAX_EXPORT_BYTES = 1024 * 1024 * 1024;
|
|
65
|
+
const GROUNDING_TIMEOUT_MS = 60_000;
|
|
66
|
+
|
|
67
|
+
/** What the Agent step line says for a model or effort not asked for. */
|
|
68
|
+
const CLAUDE_DEFAULT = "Claude Code's default";
|
|
69
|
+
|
|
70
|
+
/** Why a line is withheld from a world-readable log. */
|
|
71
|
+
const PUBLIC_LOG = "the Public-log rule: this log is world-readable in GitHub Actions";
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The line a run prints when the model API answered every request with a
|
|
75
|
+
* 401 or 403: the credential's kind and where it came from (a variable's
|
|
76
|
+
* name, or 1Password), never its value.
|
|
77
|
+
* @param {"api-key" | "subscription"} kind
|
|
78
|
+
* @param {string} from
|
|
79
|
+
*/
|
|
80
|
+
function credentialRefusedLine(kind, from) {
|
|
81
|
+
const what =
|
|
82
|
+
kind === "subscription"
|
|
83
|
+
? `the Claude subscription token from ${from} was not accepted (its value is not shown). Make a fresh one with claude setup-token, then run deep-scan again.`
|
|
84
|
+
: `the API key from ${from} was not accepted (its value is not shown). Check that the key is current and its Anthropic Console workspace is active, then run deep-scan again.`;
|
|
85
|
+
return `The model API refused the credential: every answer was 401 or 403, so ${what}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** How many lines of Claude Code's error output a failed agent step shows. */
|
|
89
|
+
const AGENT_ERROR_LINES = 20;
|
|
90
|
+
|
|
91
|
+
/** The setup phase's fields, in the order they run: services before seeding. */
|
|
92
|
+
const SETUP_ORDER = ["setup", "start", "ready", "seed"];
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* What a runtime's driver does for each lifecycle step. Each step throws
|
|
96
|
+
* StepFailed (the run ends before the agent step) or Interrupted.
|
|
97
|
+
* @typedef {{
|
|
98
|
+
* container: string,
|
|
99
|
+
* prepare: (steps: object, ctx: { archive: Function, out: Function, branch: string, short: string }) => Promise<void>,
|
|
100
|
+
* start: (steps: object) => Promise<{ isolation?: string } | void>,
|
|
101
|
+
* copyIn: (tar: Buffer, what: string) => Promise<void>,
|
|
102
|
+
* installAgent: (out: Function) => Promise<void>,
|
|
103
|
+
* openSetupEgress: (registries: string[]) => Promise<{ env: string[], note: string }>,
|
|
104
|
+
* refused: () => string[],
|
|
105
|
+
* exec: (script: string, opts?: { env?: string[], workdir?: string | null }) => Promise<import("../exec.mjs").StartResult>,
|
|
106
|
+
* cutEgress: () => Promise<void>,
|
|
107
|
+
* egressLeft: () => Promise<string | null>,
|
|
108
|
+
* openModelRoute: (startProxy: (bind: string) => Promise<{ port: number, close: () => Promise<void> }>) => Promise<{ url: string, note: string, isolation?: string }>,
|
|
109
|
+
* copyOut: (path: string, opts: { maxBytes: number }) => Promise<{ name: string, data: Buffer } | { error: string } | { missing: import("../exec.mjs").StartResult }>,
|
|
110
|
+
* close: () => Promise<void>,
|
|
111
|
+
* teardown: () => Array<{ what: string, cmd: string, args: string[] }>,
|
|
112
|
+
* cleanup?: () => void,
|
|
113
|
+
* }} Driver
|
|
114
|
+
*/
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Run the sandbox lifecycle. Returns the exit code: 0 the report came out,
|
|
118
|
+
* 1 a step failed (or the agent step did, or teardown could not finish),
|
|
119
|
+
* 3 a limit stopped the run, 130 or 143 interrupted by SIGINT or SIGTERM.
|
|
120
|
+
*
|
|
121
|
+
* @param {{
|
|
122
|
+
* runner: import("../exec.mjs").Runner,
|
|
123
|
+
* runtime: import("./runtime.mjs").Runtime,
|
|
124
|
+
* root: string,
|
|
125
|
+
* branch: string,
|
|
126
|
+
* commit: string,
|
|
127
|
+
* steps: ReturnType<typeof import("./recipe.mjs").recipeSteps>,
|
|
128
|
+
* handIn: import("./agent.mjs").HandIn,
|
|
129
|
+
* recipePath: string,
|
|
130
|
+
* recipeText: string,
|
|
131
|
+
* credential: string,
|
|
132
|
+
* credentialKind?: "api-key" | "subscription",
|
|
133
|
+
* credentialFrom?: string,
|
|
134
|
+
* limits: import("./limits.mjs").Limits,
|
|
135
|
+
* model?: string,
|
|
136
|
+
* effort?: string,
|
|
137
|
+
* timers: { setTimeout: Function, clearTimeout: Function },
|
|
138
|
+
* modelApi?: string,
|
|
139
|
+
* fetch: typeof globalThis.fetch,
|
|
140
|
+
* signals: { on: Function, off: Function },
|
|
141
|
+
* reportDir?: string,
|
|
142
|
+
* reportFile?: string,
|
|
143
|
+
* publicLog?: boolean,
|
|
144
|
+
* target?: { name: string, commit: string },
|
|
145
|
+
* verification?: Verification,
|
|
146
|
+
* out: (s: string) => void,
|
|
147
|
+
* err: (s: string) => void,
|
|
148
|
+
* }} opts `target` is the ref copied in as the repository, when it is not
|
|
149
|
+
* the default branch's tip (`branch` and `commit`), which the grounding
|
|
150
|
+
* and a recipe's Dockerfile still come from. `verification` makes the run
|
|
151
|
+
* a Verification run (verify.mjs).
|
|
152
|
+
* @returns {Promise<number>}
|
|
153
|
+
*
|
|
154
|
+
* @typedef {{
|
|
155
|
+
* findings: import("./verify.mjs").Finding[],
|
|
156
|
+
* data: Buffer,
|
|
157
|
+
* procedure: string,
|
|
158
|
+
* }} Verification
|
|
159
|
+
*/
|
|
160
|
+
export async function runLifecycle(opts) {
|
|
161
|
+
const { runner, runtime, out, err, signals } = opts;
|
|
162
|
+
const controller = new AbortController();
|
|
163
|
+
const { signal } = controller;
|
|
164
|
+
const handlers = Object.fromEntries(
|
|
165
|
+
["SIGINT", "SIGTERM"].map((sig) => [
|
|
166
|
+
sig,
|
|
167
|
+
() => {
|
|
168
|
+
if (signal.aborted) return;
|
|
169
|
+
err(`Interrupted (${sig}): stopping the current step and destroying the sandbox.`);
|
|
170
|
+
controller.abort(sig);
|
|
171
|
+
},
|
|
172
|
+
]),
|
|
173
|
+
);
|
|
174
|
+
for (const [sig, handler] of Object.entries(handlers)) signals.on(sig, handler);
|
|
175
|
+
|
|
176
|
+
const interrupted = () => new Interrupted(String(signal.reason ?? "SIGINT"));
|
|
177
|
+
|
|
178
|
+
// The phase clocks. A limit aborts only the phase's own controller, so the
|
|
179
|
+
// steps after it (the copy-out, the teardown) still run.
|
|
180
|
+
const { timers, limits } = opts;
|
|
181
|
+
/** @type {{ controller: AbortController, timer: unknown } | null} */
|
|
182
|
+
let phase = null;
|
|
183
|
+
/** @type {{ limit: string, detail: string } | null} */
|
|
184
|
+
let stopped = null;
|
|
185
|
+
const stop = (limit, detail) => {
|
|
186
|
+
if (stopped || signal.aborted) return;
|
|
187
|
+
stopped = { limit, detail };
|
|
188
|
+
err(`${stoppedStatus(stopped)} Stopping the current step.`);
|
|
189
|
+
phase?.controller.abort(stopped);
|
|
190
|
+
};
|
|
191
|
+
const clocks = {
|
|
192
|
+
begin(name, minutes) {
|
|
193
|
+
const controller = new AbortController();
|
|
194
|
+
const timer = timers.setTimeout(
|
|
195
|
+
() => stop(WALL_CLOCK, `the ${name} phase's ${minutes}-minute limit`),
|
|
196
|
+
minutes * 60_000,
|
|
197
|
+
);
|
|
198
|
+
phase = { controller, timer };
|
|
199
|
+
if (stopped) controller.abort(stopped);
|
|
200
|
+
},
|
|
201
|
+
end() {
|
|
202
|
+
if (phase) timers.clearTimeout(phase.timer);
|
|
203
|
+
phase = null;
|
|
204
|
+
},
|
|
205
|
+
stop,
|
|
206
|
+
stopped: () => stopped,
|
|
207
|
+
/** The signal a step stops on: an interrupt, or its phase's limit. */
|
|
208
|
+
signal: () => (phase ? AbortSignal.any([signal, phase.controller.signal]) : signal),
|
|
209
|
+
/** What a step stopped by `clocks.signal()` throws. */
|
|
210
|
+
reason: () => (signal.aborted ? interrupted() : new LimitReached(stopped)),
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
/** @type {import("./docker-driver.mjs").Call} */
|
|
214
|
+
const call = async (cmd, args, { stdin, cwd, maxOutput } = {}) => {
|
|
215
|
+
const stepSignal = clocks.signal();
|
|
216
|
+
if (stepSignal.aborted) throw clocks.reason();
|
|
217
|
+
const r = await runner.start(cmd, args, { stdin, cwd, maxOutput, signal: stepSignal });
|
|
218
|
+
if (r.aborted || stepSignal.aborted) throw clocks.reason();
|
|
219
|
+
if (r.truncated) return r;
|
|
220
|
+
// Ctrl+C in a terminal reaches the runtime's child too, and can end it
|
|
221
|
+
// before the handler above runs: that is an interrupt, not a failure.
|
|
222
|
+
if (r.signal === "SIGINT" || r.signal === "SIGTERM") throw new Interrupted(r.signal);
|
|
223
|
+
return r;
|
|
224
|
+
};
|
|
225
|
+
const id = randomBytes(6).toString("hex");
|
|
226
|
+
const driver =
|
|
227
|
+
runtime.id === "sbx" ? sbxDriver({ id, call }) : dockerDriver({ runtime, id, call });
|
|
228
|
+
|
|
229
|
+
let code;
|
|
230
|
+
let thrown = null;
|
|
231
|
+
try {
|
|
232
|
+
code = await lifecycle({ ...opts, driver, clocks });
|
|
233
|
+
} catch (e) {
|
|
234
|
+
if (e instanceof LimitReached) {
|
|
235
|
+
// A limit before the agent step: there is no report to deliver.
|
|
236
|
+
out(`${stoppedStatus(e.stop)} No report came out: nothing was written, filed or posted.`);
|
|
237
|
+
code = STOPPED_EXIT;
|
|
238
|
+
} else if (e instanceof Interrupted) {
|
|
239
|
+
code = e.signal === "SIGTERM" ? 143 : 130;
|
|
240
|
+
} else if (e instanceof StepFailed) {
|
|
241
|
+
err(e.lines.join("\n"));
|
|
242
|
+
code = 1;
|
|
243
|
+
} else {
|
|
244
|
+
thrown = e;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
clocks.end();
|
|
248
|
+
await driver.close();
|
|
249
|
+
const tornDown = teardown(runner, driver.teardown(), out, err);
|
|
250
|
+
driver.cleanup?.();
|
|
251
|
+
for (const [sig, handler] of Object.entries(handlers)) signals.off(sig, handler);
|
|
252
|
+
if (thrown) throw thrown;
|
|
253
|
+
return (code === 0 || code === STOPPED_EXIT) && !tornDown ? 1 : code;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function lifecycle({
|
|
257
|
+
runner,
|
|
258
|
+
runtime,
|
|
259
|
+
root,
|
|
260
|
+
branch,
|
|
261
|
+
commit,
|
|
262
|
+
steps,
|
|
263
|
+
handIn,
|
|
264
|
+
recipePath,
|
|
265
|
+
recipeText,
|
|
266
|
+
credential,
|
|
267
|
+
credentialKind = "api-key",
|
|
268
|
+
credentialFrom = "its source",
|
|
269
|
+
limits,
|
|
270
|
+
model,
|
|
271
|
+
effort,
|
|
272
|
+
modelApi,
|
|
273
|
+
fetch,
|
|
274
|
+
reportDir,
|
|
275
|
+
reportFile,
|
|
276
|
+
publicLog = false,
|
|
277
|
+
target = { name: branch, commit },
|
|
278
|
+
verification,
|
|
279
|
+
out,
|
|
280
|
+
err,
|
|
281
|
+
driver,
|
|
282
|
+
clocks,
|
|
283
|
+
}) {
|
|
284
|
+
const short = commit.slice(0, 12);
|
|
285
|
+
// The setup wall clock: from the image step until the agent step starts.
|
|
286
|
+
clocks.begin("setup", limits.setupMinutes);
|
|
287
|
+
// The committed bytes: no line-end conversion from the host's git config.
|
|
288
|
+
const archive = ({ prefix, paths, ref = commit } = {}, what) => {
|
|
289
|
+
const r = runner(
|
|
290
|
+
"git",
|
|
291
|
+
[
|
|
292
|
+
"-c",
|
|
293
|
+
"core.autocrlf=false",
|
|
294
|
+
"-C",
|
|
295
|
+
root,
|
|
296
|
+
"archive",
|
|
297
|
+
"--format=tar",
|
|
298
|
+
...(prefix ? [`--prefix=${prefix}`] : []),
|
|
299
|
+
ref,
|
|
300
|
+
...(paths ? ["--", ...paths] : []),
|
|
301
|
+
],
|
|
302
|
+
{ encoding: "buffer", maxBuffer: MAX_EXPORT_BYTES },
|
|
303
|
+
);
|
|
304
|
+
if (r.code === "ENOBUFS") {
|
|
305
|
+
throw new StepFailed([
|
|
306
|
+
`FAILED ${what}: the export is larger than ${MAX_EXPORT_BYTES / 1024 / 1024} MiB, the most deep-scan holds in memory to copy in; keep large files out of what it exports.`,
|
|
307
|
+
ENDS_HERE,
|
|
308
|
+
]);
|
|
309
|
+
}
|
|
310
|
+
if (r.status !== 0) {
|
|
311
|
+
throw new StepFailed([
|
|
312
|
+
`FAILED ${what}: ${firstLine(r.stderr) || `git archive exit ${r.status}`}`,
|
|
313
|
+
ENDS_HERE,
|
|
314
|
+
]);
|
|
315
|
+
}
|
|
316
|
+
return r.stdout;
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
// 1. Image, and its pinned Claude Code (or the runtime's refusal).
|
|
320
|
+
await driver.prepare(steps, { archive, out, branch, short });
|
|
321
|
+
|
|
322
|
+
// 2. The sandbox: no mount, no host environment, no Docker socket.
|
|
323
|
+
out(`Sandbox: starting ${driver.container} on ${runtime.name}.`);
|
|
324
|
+
// On Docker Engine, the isolation check passed before the target starts.
|
|
325
|
+
const started = await driver.start(steps);
|
|
326
|
+
if (started?.isolation) out(started.isolation);
|
|
327
|
+
|
|
328
|
+
// 3. Copy in: the trusted ref's tree (a Verification run's: the ref the
|
|
329
|
+
// maintainer named), then the grounding, and nothing else.
|
|
330
|
+
const targetShort = target.commit.slice(0, 12);
|
|
331
|
+
await driver.copyIn(
|
|
332
|
+
archive({ prefix: "workspace/", ref: target.commit }, `export ${target.name} (${targetShort})`),
|
|
333
|
+
"copying the repository in",
|
|
334
|
+
);
|
|
335
|
+
out(
|
|
336
|
+
`Copied in: ${target.name} at ${targetShort} (a git archive, not your working tree) to ${WORKSPACE}.`,
|
|
337
|
+
);
|
|
338
|
+
const fetched = [];
|
|
339
|
+
/** Each grounding source, and where the agent finds it. */
|
|
340
|
+
const grounding = [];
|
|
341
|
+
for (const [i, source] of steps.grounding.entries()) {
|
|
342
|
+
const where = `grounding[${i}]`;
|
|
343
|
+
if (/^https?:\/\//i.test(source)) {
|
|
344
|
+
const path = `agent-kit/grounding/urls/${i}-${basename(source)}`;
|
|
345
|
+
fetched.push({
|
|
346
|
+
path,
|
|
347
|
+
data: await fetchGrounding(fetch, source, where, clocks),
|
|
348
|
+
});
|
|
349
|
+
grounding.push({ source, at: `/${path}` });
|
|
350
|
+
} else {
|
|
351
|
+
grounding.push({ source, at: `${GROUNDING_DIR}/${source}` });
|
|
352
|
+
const files = archive(
|
|
353
|
+
{ prefix: "agent-kit/grounding/", paths: [source] },
|
|
354
|
+
`${where}: ${source} is not on ${branch}`,
|
|
355
|
+
);
|
|
356
|
+
await driver.copyIn(files, `copying ${where} in`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (fetched.length) {
|
|
360
|
+
const tar = tarOf([
|
|
361
|
+
{ path: "agent-kit", dir: true },
|
|
362
|
+
{ path: "agent-kit/grounding", dir: true },
|
|
363
|
+
{ path: "agent-kit/grounding/urls", dir: true },
|
|
364
|
+
...fetched,
|
|
365
|
+
]);
|
|
366
|
+
await driver.copyIn(tar, "copying the fetched grounding in");
|
|
367
|
+
}
|
|
368
|
+
if (steps.grounding.length) {
|
|
369
|
+
out(`Copied in: ${steps.grounding.length} grounding source(s) to ${GROUNDING_DIR}.`);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// 4. The setup phase: no agent, no model credential, egress only to the
|
|
373
|
+
// registries, and only for these steps.
|
|
374
|
+
await driver.installAgent(out);
|
|
375
|
+
const egress = await driver.openSetupEgress(steps.registries);
|
|
376
|
+
out(`Setup: ${egress.note}.`);
|
|
377
|
+
for (const field of SETUP_ORDER) {
|
|
378
|
+
for (const [i, command] of steps[field].entries()) {
|
|
379
|
+
const what = `${field}[${i}]`;
|
|
380
|
+
// A service started in the background keeps its output in a log, so
|
|
381
|
+
// the step returns; the log is shown if start or ready fails.
|
|
382
|
+
const script =
|
|
383
|
+
field === "start"
|
|
384
|
+
? `mkdir -p /agent-kit/logs\nexec >>/agent-kit/logs/start-${i}.log 2>&1\n${command}`
|
|
385
|
+
: command;
|
|
386
|
+
const r = await driver.exec(script, { env: egress.env });
|
|
387
|
+
if (r.status === 0) {
|
|
388
|
+
out(`Setup: ${what} ok.`);
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const lines = [
|
|
392
|
+
`FAILED ${what} exited ${r.status ?? "abnormally"}: the run ends here, before the agent step.`,
|
|
393
|
+
`Command: ${command}`,
|
|
394
|
+
...outputLines(r),
|
|
395
|
+
];
|
|
396
|
+
if (field === "start" || field === "ready") {
|
|
397
|
+
const logs = await driver.exec("cat /agent-kit/logs/start-*.log 2>/dev/null || true", {
|
|
398
|
+
workdir: null,
|
|
399
|
+
});
|
|
400
|
+
const text = logs.stdout.toString("utf8").trimEnd();
|
|
401
|
+
if (text) lines.push("Output of start:", ...indent(text));
|
|
402
|
+
}
|
|
403
|
+
const refused = driver.refused();
|
|
404
|
+
if (refused.length) {
|
|
405
|
+
lines.push(
|
|
406
|
+
`The setup proxy refused: ${[...new Set(refused)].join(", ")} (not in registries).`,
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
throw new StepFailed(lines);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// 5. Cut the network, and check from the host that it is cut.
|
|
414
|
+
await driver.cutEgress();
|
|
415
|
+
const left = await driver.egressLeft();
|
|
416
|
+
if (left !== null) {
|
|
417
|
+
throw new StepFailed([`FAILED the network is not cut: ${left}.`, ENDS_HERE]);
|
|
418
|
+
}
|
|
419
|
+
out("Network: cut (checked from the host); the agent step has no network.");
|
|
420
|
+
|
|
421
|
+
// 6. The model route: the key-injecting model proxy on this machine, the
|
|
422
|
+
// scan's only way out, and the check from the host that nothing else is.
|
|
423
|
+
let proxy = null;
|
|
424
|
+
const route = await driver.openModelRoute(async (bind) => {
|
|
425
|
+
proxy = await startModelProxy({
|
|
426
|
+
credential,
|
|
427
|
+
kind: credentialKind,
|
|
428
|
+
bind,
|
|
429
|
+
maxTokens: limits.tokens,
|
|
430
|
+
onCap: () => clocks.stop(TOKENS, `the run's ${limits.tokens}-token cap`),
|
|
431
|
+
...(modelApi !== undefined ? { upstream: modelApi } : {}),
|
|
432
|
+
});
|
|
433
|
+
return proxy;
|
|
434
|
+
});
|
|
435
|
+
const extra = await driver.egressLeft();
|
|
436
|
+
if (extra !== null) {
|
|
437
|
+
throw new StepFailed([`FAILED more than the model route is open: ${extra}.`, ENDS_HERE]);
|
|
438
|
+
}
|
|
439
|
+
if (route.isolation) out(route.isolation);
|
|
440
|
+
out(
|
|
441
|
+
`Model route: only the model proxy on your machine (${route.note}), which forwards to the model API alone, with your ${credentialKind === "subscription" ? "token as its bearer value" : "key"}; checked from the host.`,
|
|
442
|
+
);
|
|
443
|
+
|
|
444
|
+
// 7. The agent step: Claude Code with a placeholder key, handed its brief.
|
|
445
|
+
// A Verification run's finding file goes in with it, after the setup phase
|
|
446
|
+
// and the cut, so no setup step, which has registry egress, can read it.
|
|
447
|
+
const paths = { workspace: WORKSPACE, grounding: GROUNDING_DIR, report: REPORT_PATH };
|
|
448
|
+
// The subscription path runs Claude Code without --bare (#375).
|
|
449
|
+
const subscription = credentialKind === "subscription";
|
|
450
|
+
const brief = verification
|
|
451
|
+
? verificationBrief({
|
|
452
|
+
ref: target.name,
|
|
453
|
+
short: targetShort,
|
|
454
|
+
findings: verification.findings,
|
|
455
|
+
procedure: verification.procedure,
|
|
456
|
+
recipePath,
|
|
457
|
+
recipeText,
|
|
458
|
+
handIn,
|
|
459
|
+
grounding,
|
|
460
|
+
paths,
|
|
461
|
+
discovers: subscription,
|
|
462
|
+
})
|
|
463
|
+
: agentBrief({
|
|
464
|
+
branch,
|
|
465
|
+
short,
|
|
466
|
+
recipePath,
|
|
467
|
+
recipeText,
|
|
468
|
+
handIn,
|
|
469
|
+
grounding,
|
|
470
|
+
paths,
|
|
471
|
+
discovers: subscription,
|
|
472
|
+
});
|
|
473
|
+
await driver.copyIn(
|
|
474
|
+
tarOf([
|
|
475
|
+
{ path: "agent-kit", dir: true },
|
|
476
|
+
{ path: "agent-kit/in", dir: true },
|
|
477
|
+
{ path: BRIEF_PATH.slice(1), data: Buffer.from(brief, "utf8") },
|
|
478
|
+
...(verification ? [{ path: FINDINGS_PATH.slice(1), data: verification.data }] : []),
|
|
479
|
+
]),
|
|
480
|
+
verification
|
|
481
|
+
? "copying the launcher's brief and the finding file in"
|
|
482
|
+
: "copying the launcher's brief in",
|
|
483
|
+
);
|
|
484
|
+
out(
|
|
485
|
+
`Agent step: Claude Code ${CLAUDE_CODE_VERSION} (${subscription ? "no --bare: the subscription path, with a placeholder token; project settings and MCP servers not loaded" : "--bare, a placeholder key"}, web tools off, at most ${limits.turns} turns; requested model: ${model ?? CLAUDE_DEFAULT}, effort: ${effort ?? CLAUDE_DEFAULT}), handed ${verification ? "the Verification-run procedure, the finding file" : "the deep procedure"}, the Threat pack and the Scan recipe.`,
|
|
486
|
+
);
|
|
487
|
+
clocks.end();
|
|
488
|
+
// The scan wall clock: the agent step alone.
|
|
489
|
+
clocks.begin("scan", limits.scanMinutes);
|
|
490
|
+
/** @type {import("../exec.mjs").StartResult | null} null when a limit stopped it */
|
|
491
|
+
let agent = null;
|
|
492
|
+
try {
|
|
493
|
+
agent = await driver.exec(
|
|
494
|
+
agentScript({
|
|
495
|
+
baseUrl: route.url,
|
|
496
|
+
report: REPORT_PATH,
|
|
497
|
+
workspace: WORKSPACE,
|
|
498
|
+
maxTurns: limits.turns,
|
|
499
|
+
...(model !== undefined ? { model } : {}),
|
|
500
|
+
...(effort !== undefined ? { effort } : {}),
|
|
501
|
+
kind: credentialKind,
|
|
502
|
+
}),
|
|
503
|
+
{ env: agentEnv(credentialKind) },
|
|
504
|
+
);
|
|
505
|
+
} catch (e) {
|
|
506
|
+
if (!(e instanceof LimitReached)) throw e;
|
|
507
|
+
}
|
|
508
|
+
clocks.end();
|
|
509
|
+
// Claude Code's own turn limit ended it: the script's fixed marker says so.
|
|
510
|
+
if (agent && agent.stdout.toString("utf8").split(/\r?\n/).includes(TURNS_MARKER)) {
|
|
511
|
+
clocks.stop(TURNS, `Claude Code's ${limits.turns}-turn limit`);
|
|
512
|
+
}
|
|
513
|
+
// The scan is over: no route out is left open while the report comes out.
|
|
514
|
+
await driver.close();
|
|
515
|
+
// The proxy's summary names what the agent sent: refused hosts and paths,
|
|
516
|
+
// and the model API's answers. A public log gets none of it.
|
|
517
|
+
out(
|
|
518
|
+
publicLog
|
|
519
|
+
? `Model proxy: ${proxy ? "closed" : "not started"} (${PUBLIC_LOG}).`
|
|
520
|
+
: `Model proxy: ${proxy?.summary() ?? "not started"}.`,
|
|
521
|
+
);
|
|
522
|
+
// Every answer a 401 or 403: say plainly that the credential was refused,
|
|
523
|
+
// its kind and where it came from, never its value. Locally only: a public
|
|
524
|
+
// log gets none of the model API's answers.
|
|
525
|
+
if (!publicLog && proxy?.credentialRefused())
|
|
526
|
+
err(credentialRefusedLine(credentialKind, credentialFrom));
|
|
527
|
+
const stopped = clocks.stopped();
|
|
528
|
+
if (stopped) {
|
|
529
|
+
out(`${stoppedStatus(stopped)} Copying out what report the agent left.`);
|
|
530
|
+
} else if (agent && agent.status !== 0 && publicLog) {
|
|
531
|
+
err(
|
|
532
|
+
`The agent step exited ${agent.status ?? "abnormally"}; copying out what report it left. Claude Code's error output stays in the sandbox (${PUBLIC_LOG}); run deep-scan locally to see it.`,
|
|
533
|
+
);
|
|
534
|
+
} else if (agent && agent.status !== 0) {
|
|
535
|
+
const lines = agent.stderr
|
|
536
|
+
.trimEnd()
|
|
537
|
+
.split(/\r\n|\r|\n/)
|
|
538
|
+
.filter(Boolean);
|
|
539
|
+
err(
|
|
540
|
+
[
|
|
541
|
+
`The agent step exited ${agent.status ?? "abnormally"}; copying out what report it left.`,
|
|
542
|
+
...(lines.length
|
|
543
|
+
? [
|
|
544
|
+
`Claude Code's error output (its last ${AGENT_ERROR_LINES} lines at most; the rest of its output stays in the sandbox):`,
|
|
545
|
+
...indent(lines.slice(-AGENT_ERROR_LINES).join("\n")),
|
|
546
|
+
]
|
|
547
|
+
: []),
|
|
548
|
+
].join("\n"),
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// 8. Copy out the one report file, and nothing else.
|
|
553
|
+
const file = await driver.copyOut(REPORT_PATH, { maxBytes: MAX_REPORT_BYTES });
|
|
554
|
+
if ("missing" in file && stopped) {
|
|
555
|
+
// A stop with no report: only a status naming the limit, and no file.
|
|
556
|
+
out(`${stoppedStatus(stopped)} No report came out: nothing was written, filed or posted.`);
|
|
557
|
+
return STOPPED_EXIT;
|
|
558
|
+
}
|
|
559
|
+
if ("missing" in file) {
|
|
560
|
+
const r = file.missing;
|
|
561
|
+
throw new StepFailed([
|
|
562
|
+
`FAILED no report at ${REPORT_PATH}: ${firstLine(r.stderr) || `exit ${r.status}`}`,
|
|
563
|
+
]);
|
|
564
|
+
}
|
|
565
|
+
if ("error" in file) {
|
|
566
|
+
throw new StepFailed([
|
|
567
|
+
publicLog
|
|
568
|
+
? `FAILED the report was not copied out (why stays out of the log: ${PUBLIC_LOG}).`
|
|
569
|
+
: `FAILED the report was not copied out: ${file.error}.`,
|
|
570
|
+
...(stopped ? [stoppedStatus(stopped)] : []),
|
|
571
|
+
]);
|
|
572
|
+
}
|
|
573
|
+
const path =
|
|
574
|
+
reportFile ??
|
|
575
|
+
join(reportDir ?? mkdtempSync(join(tmpdir(), "agent-kit-deep-scan-")), "report.md");
|
|
576
|
+
// The launcher's Stopped: line, when a limit ended the run; never the agent's.
|
|
577
|
+
const report = withStopped(file.data, stopped?.limit ?? null);
|
|
578
|
+
writeFileSync(path, report, { mode: 0o600, flag: "wx" });
|
|
579
|
+
out(
|
|
580
|
+
`Report: ${path} (the only file copied out of the sandbox${stopped ? `, partial: marked Stopped: ${stopped.limit}` : ""}).`,
|
|
581
|
+
);
|
|
582
|
+
if (verification) {
|
|
583
|
+
// Locally only: --verify is refused in CI, so no public log sees this.
|
|
584
|
+
const { answers, problems } = checkVerificationReport(
|
|
585
|
+
report.toString("utf8"),
|
|
586
|
+
verification.findings,
|
|
587
|
+
);
|
|
588
|
+
if (answers.length) {
|
|
589
|
+
out(
|
|
590
|
+
[
|
|
591
|
+
"Verification:",
|
|
592
|
+
...answers.map(
|
|
593
|
+
(a) =>
|
|
594
|
+
` - ${a.conceptId}: Reproduced: ${a.reproduced} (${a.reproduced === "yes" ? "the fix does not hold" : "the fix holds"})`,
|
|
595
|
+
),
|
|
596
|
+
].join("\n"),
|
|
597
|
+
);
|
|
598
|
+
}
|
|
599
|
+
if (problems.length && !stopped) {
|
|
600
|
+
err(
|
|
601
|
+
[
|
|
602
|
+
"The report does not answer every given finding in the Verification-run variant:",
|
|
603
|
+
...problems.map((p) => ` - ${p}`),
|
|
604
|
+
].join("\n"),
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
out(
|
|
608
|
+
"Nothing was filed or posted. A Verification run's report stays on your machine: file no advisory, comment or ledger note from it.",
|
|
609
|
+
);
|
|
610
|
+
if (stopped) return STOPPED_EXIT;
|
|
611
|
+
return agent?.status === 0 && !problems.length ? 0 : 1;
|
|
612
|
+
}
|
|
613
|
+
out(
|
|
614
|
+
publicLog
|
|
615
|
+
? "Nothing was filed or posted by deep-scan: in CI, the workflow's delivery steps file the report privately."
|
|
616
|
+
: "Nothing was filed or posted. To file a draft advisory, follow the security-audit skill's by-hand rule.",
|
|
617
|
+
);
|
|
618
|
+
if (stopped) return STOPPED_EXIT;
|
|
619
|
+
return agent?.status === 0 ? 0 : 1;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* Run each teardown command, whatever happened before. Synchronous, so it
|
|
624
|
+
* finishes even while an interrupt is pending.
|
|
625
|
+
* @returns {boolean} whether nothing was left behind
|
|
626
|
+
*/
|
|
627
|
+
function teardown(runner, commands, out, err) {
|
|
628
|
+
if (!commands.length) return true;
|
|
629
|
+
const left = [];
|
|
630
|
+
for (const { what, cmd, args } of commands) {
|
|
631
|
+
const r = runner(cmd, args);
|
|
632
|
+
if (r.status !== 0 && !/no such|not found/i.test(r.stderr)) {
|
|
633
|
+
left.push(`${what}: ${firstLine(r.stderr) || `exit ${r.status}`}`);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
if (left.length) {
|
|
637
|
+
err(
|
|
638
|
+
[
|
|
639
|
+
"TEARDOWN could not remove:",
|
|
640
|
+
...left.map((l) => ` - ${l}`),
|
|
641
|
+
`Remove them by hand; every Docker resource carries the label ${LABEL}, and every sandbox's name starts with agent-kit-deep-.`,
|
|
642
|
+
].join("\n"),
|
|
643
|
+
);
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
out(`Teardown: removed ${commands.map((c) => c.what).join(", ")}.`);
|
|
647
|
+
return true;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
async function fetchGrounding(fetch, url, where, clocks) {
|
|
651
|
+
const fail = (why) =>
|
|
652
|
+
new StepFailed([`FAILED ${where}: could not fetch ${url}: ${why}`, ENDS_HERE]);
|
|
653
|
+
const tooLarge = `larger than ${MAX_GROUNDING_BYTES / 1024 / 1024} MiB`;
|
|
654
|
+
// The request and the body read share one error path: an interrupt or a
|
|
655
|
+
// limit that fires mid-download stops the run as it would anywhere else.
|
|
656
|
+
try {
|
|
657
|
+
const res = await fetch(url, {
|
|
658
|
+
redirect: "follow",
|
|
659
|
+
signal: AbortSignal.any([clocks.signal(), AbortSignal.timeout(GROUNDING_TIMEOUT_MS)]),
|
|
660
|
+
});
|
|
661
|
+
if (!res.ok) throw fail(`HTTP ${res.status}`);
|
|
662
|
+
if (Number(res.headers.get("content-length") ?? "0") > MAX_GROUNDING_BYTES) {
|
|
663
|
+
throw fail(tooLarge);
|
|
664
|
+
}
|
|
665
|
+
// Counted as it streams, so a body with no content-length is never held
|
|
666
|
+
// whole past the cap.
|
|
667
|
+
const chunks = [];
|
|
668
|
+
let size = 0;
|
|
669
|
+
if (res.body) {
|
|
670
|
+
const reader = res.body.getReader();
|
|
671
|
+
for (;;) {
|
|
672
|
+
const { done, value } = await reader.read();
|
|
673
|
+
if (done) break;
|
|
674
|
+
size += value.length;
|
|
675
|
+
if (size > MAX_GROUNDING_BYTES) {
|
|
676
|
+
reader.cancel().catch(() => {});
|
|
677
|
+
throw fail(tooLarge);
|
|
678
|
+
}
|
|
679
|
+
chunks.push(value);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
return Buffer.concat(chunks);
|
|
683
|
+
} catch (e) {
|
|
684
|
+
if (clocks.signal().aborted) throw clocks.reason();
|
|
685
|
+
if (e instanceof StepFailed) throw e;
|
|
686
|
+
throw fail(e?.message ?? String(e));
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** A file name for a fetched URL: its last path segment, made safe. */
|
|
691
|
+
function basename(url) {
|
|
692
|
+
let segment = "";
|
|
693
|
+
try {
|
|
694
|
+
segment = new URL(url).pathname.split("/").filter(Boolean).at(-1) ?? "";
|
|
695
|
+
} catch {
|
|
696
|
+
segment = "";
|
|
697
|
+
}
|
|
698
|
+
const safe = segment
|
|
699
|
+
.replace(/[^A-Za-z0-9._-]/g, "_")
|
|
700
|
+
.replace(/^\.+/, "")
|
|
701
|
+
.slice(0, 60);
|
|
702
|
+
return safe || "index";
|
|
703
|
+
}
|