@mnaimfaizy/agent-kit 1.0.0-beta.13 → 1.0.0-beta.14

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.
@@ -0,0 +1,300 @@
1
+ // The live suite (ADR 0031, Tier B): each scenario runs the pinned harness in
2
+ // its Harness image, in the real sandbox, behind the real model proxy, whose
3
+ // upstream is the stub model; the stub has the harness attempt a breach of
4
+ // each Guard; and the host judges what came of it (assess.mjs).
5
+ //
6
+ // The Deep scan enters through `agent-kit deep-scan` itself, with the model
7
+ // API pointed at the stub; the read-only Stage through stage.mjs.
8
+
9
+ import { EventEmitter } from "node:events";
10
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { main } from "../cli.mjs";
14
+ import { claudeCode, TOOLS } from "../harness/claude-code.mjs";
15
+ import { startStubModel } from "../model-proxy/stub.mjs";
16
+ import { assess, verdictOf } from "./assess.mjs";
17
+ import {
18
+ FAKE_CREDENTIAL,
19
+ hostReachesOutside,
20
+ inspectSandbox,
21
+ listen,
22
+ markersIn,
23
+ plant,
24
+ } from "./host.mjs";
25
+ import { MARKER_DIR, probeScripts } from "./probes.mjs";
26
+ import { runReadOnlyStage, STAGE_RESULT_PATH } from "./stage.mjs";
27
+
28
+ /** Every run the suite makes: each way Claude Code is launched, on each credential kind. */
29
+ export const SCENARIOS = Object.freeze(
30
+ ["read-only-stage", "deep-scan"].flatMap((run) =>
31
+ ["api-key", "subscription"].map((credentialKind) =>
32
+ Object.freeze({ name: `claude-code ${run} (${credentialKind})`, run, credentialKind }),
33
+ ),
34
+ ),
35
+ );
36
+
37
+ /** The report's path in a Deep scan's sandbox, which its lifecycle names. */
38
+ const DEEP_SCAN_RESULT_PATH = "/agent-kit/out/report.md";
39
+
40
+ /** The targets of the network probe beside the host's own listener. */
41
+ const TARGETS = Object.freeze([
42
+ "outside-host",
43
+ "outside-address",
44
+ "metadata",
45
+ "docker-socket",
46
+ "docker-socket-run",
47
+ ]);
48
+
49
+ /** The markers the control run must leave, by the start of their names. */
50
+ const CONTROL_MARKERS = Object.freeze(["settings-", "local-", "mcp-server"]);
51
+
52
+ /** The sandbox's own container name, as the driver gives it. */
53
+ const SANDBOX = /^agent-kit-deep-[0-9a-f]{12}$/;
54
+
55
+ /**
56
+ * A line that says one of the sandbox's isolation checks failed before the
57
+ * agent step: each such failure of the Docker driver's, and of the network cut
58
+ * and the model route.
59
+ */
60
+ const NOT_ISOLATED =
61
+ /^FAILED {2}(.* is not isolated|the sandbox is not on .* alone|the network is not cut|more than the model route is open)\b/m;
62
+
63
+ /**
64
+ * The control for the checkout-config probe: the harness started again in the
65
+ * same sandbox with the checkout's config loaded on purpose, so a run in which
66
+ * none of it left a marker is known to have been able to.
67
+ * @param {{ url: string }} launch
68
+ */
69
+ function loadingConfig({ url }) {
70
+ return [
71
+ "claude",
72
+ "--print",
73
+ "--setting-sources",
74
+ "user,project,local",
75
+ "--settings",
76
+ JSON.stringify({ env: { ANTHROPIC_BASE_URL: url } }),
77
+ "--tools",
78
+ TOOLS.join(","),
79
+ "--permission-mode",
80
+ "dontAsk",
81
+ "--no-session-persistence",
82
+ "--max-turns",
83
+ "2",
84
+ ];
85
+ }
86
+
87
+ /**
88
+ * Run one scenario and judge it.
89
+ * @param {typeof SCENARIOS[number]} scenario
90
+ * @param {{
91
+ * runner: import("../exec.mjs").Runner,
92
+ * launcherCanary: string,
93
+ * runtime: import("../deep-scan/runtime.mjs").Runtime,
94
+ * expectedRuntime?: string,
95
+ * platform?: string,
96
+ * }} opts `runner` runs the launcher's commands. `launcherCanary` is a value
97
+ * on this process's own command line, which the sandbox must never see.
98
+ * `expectedRuntime` is the Docker runtime the sandbox must run under.
99
+ * @returns {Promise<{
100
+ * name: string,
101
+ * verdict: "pass" | "guard-failed" | "error",
102
+ * findings: import("./assess.mjs").Finding[],
103
+ * exit: number,
104
+ * log: string,
105
+ * outputs: Record<string, string>,
106
+ * }>} `guard-failed`: a Guard was breached or not shown held; `error`: the
107
+ * run failed for another reason, such as before the harness started.
108
+ */
109
+ export async function runScenario(
110
+ scenario,
111
+ { runner, launcherCanary, runtime, expectedRuntime = "runsc", platform = process.platform },
112
+ ) {
113
+ /** What to undo, newest first, however the run ends. */
114
+ const undo = [];
115
+ try {
116
+ return await run();
117
+ } finally {
118
+ for (const step of undo.reverse()) await step();
119
+ }
120
+
121
+ async function run() {
122
+ const planted = plant({ runner, launcherCanary });
123
+ undo.push(() => planted.remove());
124
+ const listener = await listen();
125
+ undo.push(() => listener.close());
126
+ const hostControls = { listener: await listener.check(), outside: await hostReachesOutside() };
127
+ const stageRun = scenario.run === "read-only-stage";
128
+ const resultPath = stageRun ? STAGE_RESULT_PATH : DEEP_SCAN_RESULT_PATH;
129
+ const scripts = probeScripts({
130
+ hostFiles: planted.hostFiles,
131
+ hostTargets: listener.targets,
132
+ resultPath,
133
+ });
134
+ const stub = await startStubModel({ commands: scripts.map((s) => s.script) });
135
+ undo.push(() => stub.close());
136
+ const outDir = mkdtempSync(join(tmpdir(), "agent-kit-live-out-"));
137
+ undo.push(() => rmSync(outDir, { recursive: true, force: true }));
138
+ const credential = FAKE_CREDENTIAL[scenario.credentialKind]();
139
+ const { env: variable } = claudeCode().credentials.accepted[scenario.credentialKind];
140
+ const savedCredential = process.env[variable];
141
+ process.env[variable] = credential;
142
+ undo.push(() => {
143
+ if (savedCredential === undefined) delete process.env[variable];
144
+ else process.env[variable] = savedCredential;
145
+ });
146
+ let log = "";
147
+ const say = (line) => {
148
+ log += `${line}\n`;
149
+ };
150
+
151
+ /** What the host read of the sandbox, and the probes' output at that moment. */
152
+ let seen = { sandbox: null, markers: null, transcript: null };
153
+ let outputs = null;
154
+ let controlMarkers = null;
155
+ const readSandbox = (container) => {
156
+ seen = inspectSandbox(runner, container);
157
+ outputs = Object.fromEntries(stub.results().map((r) => [scripts[r.index].guard, r.text]));
158
+ };
159
+
160
+ let exit;
161
+ if (stageRun) {
162
+ exit = await runReadOnlyStage({
163
+ runner,
164
+ runtime,
165
+ root: planted.root,
166
+ commit: planted.commit,
167
+ credential,
168
+ credentialKind: scenario.credentialKind,
169
+ modelApi: stub.url,
170
+ outDir,
171
+ out: say,
172
+ err: say,
173
+ async beforeTeardown(container, launch) {
174
+ readSandbox(container);
175
+ stub.script([]);
176
+ runner("docker", ["exec", container, "rm", "-rf", MARKER_DIR]);
177
+ const control = loadingConfig(launch);
178
+ await runner.start(
179
+ "docker",
180
+ [
181
+ "exec",
182
+ "-i",
183
+ ...launch.env.flatMap((v) => ["--env", v]),
184
+ "--workdir",
185
+ "/workspace",
186
+ container,
187
+ ...control,
188
+ ],
189
+ { stdin: "Say that you are done.", signal: AbortSignal.timeout(120_000) },
190
+ );
191
+ controlMarkers = markersIn(runner, container);
192
+ },
193
+ });
194
+ } else {
195
+ // The sandbox is read as the Deep scan removes it: its last moment.
196
+ const watching = (cmd, args, opts) => {
197
+ if (cmd === "docker" && args[0] === "rm" && SANDBOX.test(args.at(-1))) {
198
+ readSandbox(args.at(-1));
199
+ }
200
+ return runner(cmd, args, opts);
201
+ };
202
+ watching.start = runner.start;
203
+ exit = await main(
204
+ [
205
+ "deep-scan",
206
+ // A Proving run (ADR 0028): the kit's own repository running the
207
+ // Launcher, on a pair that may be below `tried`.
208
+ "--proving-run",
209
+ "--default-branch",
210
+ "main",
211
+ "--credential",
212
+ scenario.credentialKind,
213
+ "--max-turns",
214
+ "40",
215
+ "--scan-minutes",
216
+ "10",
217
+ "--report",
218
+ join(outDir, "report.md"),
219
+ ],
220
+ {
221
+ cwd: planted.root,
222
+ stdout: say,
223
+ stderr: say,
224
+ runner: watching,
225
+ platform,
226
+ // The launcher's environment: the model credential, and the
227
+ // runner's OIDC variables. It refuses to run beside a GitHub token,
228
+ // which the processes it starts inherit all the same.
229
+ env: {
230
+ [variable]: credential,
231
+ ACTIONS_ID_TOKEN_REQUEST_URL: planted.variables.ACTIONS_ID_TOKEN_REQUEST_URL,
232
+ ACTIONS_ID_TOKEN_REQUEST_TOKEN: planted.variables.ACTIONS_ID_TOKEN_REQUEST_TOKEN,
233
+ },
234
+ signals: new EventEmitter(),
235
+ modelApi: stub.url,
236
+ },
237
+ );
238
+ }
239
+
240
+ const unchanged = planted.unchanged();
241
+ const resultName = resultPath.slice(resultPath.lastIndexOf("/") + 1);
242
+ const resultFile = join(outDir, resultName);
243
+ const evidence = {
244
+ outputs: outputs ?? {},
245
+ requests: stub.requests,
246
+ launcherOutput: log,
247
+ result: existsSync(resultFile) ? readFileSync(resultFile, "utf8") : null,
248
+ ...seen,
249
+ controlMarkers,
250
+ outputFiles: readdirSync(outDir),
251
+ hostRepoUnchanged: unchanged.repo,
252
+ hostFilesUnchanged: unchanged.files,
253
+ listenerHits: listener.hits(),
254
+ hostControls,
255
+ };
256
+ const { accepted } = claudeCode().credentials;
257
+ const findings = assess(evidence, {
258
+ canaries: { ...planted.canaries, key: [credential] },
259
+ control: planted.control,
260
+ placeholderEnv: `${variable}=${accepted[scenario.credentialKind].placeholder}`,
261
+ upstreamAuth:
262
+ scenario.credentialKind === "api-key"
263
+ ? ["x-api-key", credential]
264
+ : ["authorization", `Bearer ${credential}`],
265
+ runtime: expectedRuntime,
266
+ resultName,
267
+ sweepControl: planted.sweepControl,
268
+ configControl: stageRun ? [...CONTROL_MARKERS] : [],
269
+ hostFiles: planted.hostFiles,
270
+ targets: [...TARGETS, ...listener.targets.map((_, i) => `host-${i}`)],
271
+ });
272
+ return {
273
+ name: scenario.name,
274
+ verdict: scenarioVerdict({ findings, started: stub.requests.length > 0, exit, log }),
275
+ findings,
276
+ exit,
277
+ log,
278
+ outputs: evidence.outputs,
279
+ };
280
+ }
281
+ }
282
+
283
+ /**
284
+ * A scenario's verdict from its findings. A breach counts however the run went.
285
+ * A Guard not shown counts once the harness started, or when the sandbox failed
286
+ * its own isolation check; otherwise the run failed for another reason.
287
+ * @param {{
288
+ * findings: import("./assess.mjs").Finding[],
289
+ * started: boolean,
290
+ * exit: number,
291
+ * log: string,
292
+ * }} run
293
+ * @returns {"pass" | "guard-failed" | "error"}
294
+ */
295
+ export function scenarioVerdict({ findings, started, exit, log }) {
296
+ if (findings.some((f) => f.status === "breached")) return "guard-failed";
297
+ if (!started) return NOT_ISOLATED.test(log) ? "guard-failed" : "error";
298
+ if (verdictOf(findings) !== "pass") return "guard-failed";
299
+ return exit === 0 ? "pass" : "error";
300
+ }
package/src/init.mjs CHANGED
@@ -10,6 +10,7 @@
10
10
  import { join } from "node:path";
11
11
  import { DEFAULT_KIT_REPO } from "./callers.mjs";
12
12
  import { command } from "./checks/result.mjs";
13
+ import { RENAMED_VARIABLES } from "./checks/secrets-and-variables.mjs";
13
14
  import { fileAndPinChecks, printFileAndPinChecks } from "./doctor.mjs";
14
15
  import { firstLine } from "./exec.mjs";
15
16
  import { openKitTag, PreManifestTagError, serverFromEnv } from "./kit-tag.mjs";
@@ -418,11 +419,22 @@ export function planInit({ runner, root, snap, answers, force }) {
418
419
  return { deletes, writes, conflicts, notes, dependabot, dirty, ignored, unchanged };
419
420
  }
420
421
 
422
+ /**
423
+ * The variable the written Callers read for `name`: an older tag's Callers read
424
+ * the name it replaced, and setting the newer one would turn nothing on.
425
+ */
426
+ function variableRead(name, callers) {
427
+ const reads = (n) => new RegExp(`\\bvars\\.${n}\\b`).test(callers);
428
+ if (reads(name)) return name;
429
+ const old = Object.keys(RENAMED_VARIABLES).find((n) => RENAMED_VARIABLES[n] === name && reads(n));
430
+ return old ?? name;
431
+ }
432
+
421
433
  /**
422
434
  * The GitHub-side steps init does not take, as POSIX-shell commands built
423
435
  * with checks/result.mjs `command()` (every argument fixed or allowlisted).
424
436
  */
425
- export function manualSteps({ flows, tag, kitRepo, serverUrl }) {
437
+ export function manualSteps({ flows, tag, kitRepo, serverUrl, callers = "" }) {
426
438
  const pipeline = flows.includes("pipeline");
427
439
  const audit = flows.includes("audit");
428
440
  const response = flows.includes("review-response");
@@ -432,8 +444,14 @@ export function manualSteps({ flows, tag, kitRepo, serverUrl }) {
432
444
  lines.push(`${++n}. ${title}`);
433
445
  for (const c of cmds) lines.push(` $ ${c}`);
434
446
  };
447
+ // Offered only when the Callers pass it; an older tag's do not.
448
+ const apiKey = /\bsecrets\.ANTHROPIC_API_KEY\b/.test(callers)
449
+ ? ", or set ANTHROPIC_API_KEY instead"
450
+ : "";
451
+ const setVariable = (name, value) =>
452
+ command("gh", "variable", "set", variableRead(name, callers), "--body", value);
435
453
  step(
436
- "Secrets (gh asks for each value; CLAUDE_CODE_OAUTH_TOKEN comes from `claude setup-token`):",
454
+ `Secrets (gh asks for each value; CLAUDE_CODE_OAUTH_TOKEN comes from \`claude setup-token\`${apiKey}):`,
437
455
  command("gh", "secret", "set", "CLAUDE_CODE_OAUTH_TOKEN"),
438
456
  ...(audit ? [command("gh", "secret", "set", "AGENT_KIT_ADVISORIES_TOKEN")] : []),
439
457
  );
@@ -456,22 +474,16 @@ export function manualSteps({ flows, tag, kitRepo, serverUrl }) {
456
474
  );
457
475
  step(
458
476
  "Last, after you have reviewed and pushed the Callers, turn the flows on (Kill switch variables):",
459
- ...(pipeline
460
- ? [command("gh", "variable", "set", "CLAUDE_AGENT_FLOW_ENABLED", "--body", "true")]
461
- : []),
462
- ...(audit
463
- ? [command("gh", "variable", "set", "CLAUDE_SECURITY_AUDIT_ENABLED", "--body", "true")]
464
- : []),
465
- ...(response
466
- ? [command("gh", "variable", "set", "CLAUDE_REVIEW_RESPONSE_ENABLED", "--body", "true")]
467
- : []),
477
+ ...(pipeline ? [setVariable("AGENT_KIT_AGENT_FLOW_ENABLED", "true")] : []),
478
+ ...(audit ? [setVariable("AGENT_KIT_SECURITY_AUDIT_ENABLED", "true")] : []),
479
+ ...(response ? [setVariable("AGENT_KIT_REVIEW_RESPONSE_ENABLED", "true")] : []),
468
480
  );
469
481
  if (response) {
470
482
  step(
471
483
  "Optional, Review response auto mode (a finished review starts a round): first give your " +
472
484
  "review Caller response_mode and response_workflow, as " +
473
485
  `${serverUrl}/${kitRepo}/blob/${tag}/docs/review-response.md#auto-mode says, then:`,
474
- command("gh", "variable", "set", "CLAUDE_REVIEW_RESPONSE_MODE", "--body", "auto"),
486
+ setVariable("AGENT_KIT_REVIEW_RESPONSE_MODE", "auto"),
475
487
  );
476
488
  }
477
489
  return lines;
@@ -637,6 +649,10 @@ export async function runInit({
637
649
  tag: answers.tag,
638
650
  kitRepo: DEFAULT_KIT_REPO,
639
651
  serverUrl,
652
+ callers: answers.flows
653
+ .map((flow) => FLOWS[flow].caller)
654
+ .map((path) => plan.writes.find((w) => w.path === path).bytes.toString("utf8"))
655
+ .join("\n"),
640
656
  })) {
641
657
  out(line);
642
658
  }