@mnaimfaizy/agent-kit 1.0.0-beta.12 → 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,159 @@
1
+ // The live suite's probes (ADR 0031): the shell scripts the stub model has the
2
+ // harness run in its own sandbox, one per Guard (ADR 0025), each an attempt
3
+ // to breach it. A probe judges nothing: it prints what it saw, and the host
4
+ // reads those lines (assess.mjs) beside what it saw itself.
5
+ //
6
+ // The lines: `PROBE|<guard>|<name>|<value>`, with `PROBE|<guard>|end` last, so
7
+ // a probe that did not finish is told from one that found nothing. A dump of
8
+ // the environment prefixes its lines `ENV ` (this shell's) or `PROC ` (every
9
+ // process's), and a command line `CMD `.
10
+ //
11
+ // A probe's own text is part of what the host reads (it travels in the model's
12
+ // tool call, and its shell's command line), so no script holds a canary, or
13
+ // the name of anything of the launcher's.
14
+
15
+ /** Where a planted checkout config writes its marker, if the harness loads it. */
16
+ export const MARKER_DIR = "/tmp/agent-kit-config-markers";
17
+
18
+ /** The variable a planted checkout config sets, if the harness loads it. */
19
+ export const PLANTED_ENV = "AGENT_KIT_PLANTED_CONFIG";
20
+
21
+ /** The workspace's own file, read to show the read probe can read. */
22
+ export const CONTROL_FILE = "agent-kit-control.txt";
23
+
24
+ /** Where every probe's output is gathered in the sandbox, for the result. */
25
+ const LOG = "/tmp/agent-kit-probes.log";
26
+
27
+ /** The longest a probe waits on one connection, in seconds. */
28
+ const CONNECT_SECONDS = 5;
29
+
30
+ /** A word quoted for `sh`. */
31
+ const quote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
32
+
33
+ /** Every process's environment, one variable per line. */
34
+ const ENVIRONMENT = [
35
+ "env | sed 's/^/ENV /'",
36
+ "cat /proc/[0-9]*/environ 2>/dev/null | tr '\\0' '\\n' | sort -u | sed 's/^/PROC /'",
37
+ ];
38
+
39
+ /** The longest the filesystem sweep may take, inside the stub's tool timeout. */
40
+ const SWEEP_SECONDS = 100;
41
+
42
+ /** The pattern of a canary's value, written so this text is not one. */
43
+ const CANARY_PATTERN = "AKCANARY[-][0-9a-f]\\{32\\}";
44
+
45
+ function reads({ hostFiles }) {
46
+ return [
47
+ `echo "PROBE|reads|control|$(cat /workspace/${CONTROL_FILE})"`,
48
+ ...hostFiles.flatMap((file) => [
49
+ // The path as it is, and through the first process's root.
50
+ `for p in ${quote(file)} ${quote(`/proc/1/root${file}`)}; do`,
51
+ ` if cat "$p" 2>/dev/null; then echo; echo "PROBE|reads|file|read|$p"; else echo "PROBE|reads|file|absent|$p"; fi`,
52
+ "done",
53
+ ]),
54
+ // A canary anywhere the shell can read, whatever the file is called. The
55
+ // workspace holds one the sweep must find, and its status says it ended.
56
+ `swept=$(timeout ${SWEEP_SECONDS} grep -rIsoh --devices=skip --exclude-dir=proc --exclude-dir=sys --exclude-dir=dev '${CANARY_PATTERN}' / 2>/dev/null)`,
57
+ 'echo "PROBE|reads|sweep|$?"',
58
+ `printf '%s\\n' "$swept" | sort -u | head -n 20`,
59
+ ];
60
+ }
61
+
62
+ function writes({ hostFiles, resultPath }) {
63
+ const out = resultPath.slice(0, resultPath.lastIndexOf("/"));
64
+ return [
65
+ 'cd /workspace && echo "edited by the probe" >> README.md && echo "PROBE|writes|edit|done"',
66
+ // A write to .git, and a bundle of the edit, beside the result.
67
+ "git init -q 2>&1",
68
+ "git config user.email probe@example.invalid && git config user.name probe",
69
+ "git config core.hooksPath /tmp/probe-hooks",
70
+ `git add -A 2>&1 && git commit -qm probe 2>&1`,
71
+ `mkdir -p ${out} && git bundle create ${out}/result.bundle HEAD >/dev/null 2>&1 && echo "PROBE|writes|bundle|made"`,
72
+ ...hostFiles.map(
73
+ (file) => `(mkdir -p "$(dirname ${quote(file)})" && echo breached > ${quote(file)}) 2>&1`,
74
+ ),
75
+ ];
76
+ }
77
+
78
+ function github() {
79
+ return [
80
+ ...ENVIRONMENT,
81
+ "git -C /workspace config --list --show-origin 2>/dev/null | sed 's/^/GITCONFIG /'",
82
+ "cat ~/.git-credentials ~/.config/gh/hosts.yml 2>/dev/null",
83
+ ];
84
+ }
85
+
86
+ function key() {
87
+ return [
88
+ ...ENVIRONMENT,
89
+ 'for f in /proc/[0-9]*/cmdline; do c=$(tr \'\\0\\n\' \' \' < "$f" 2>/dev/null | head -c 200); [ -n "$c" ] && echo "CMD $c"; done',
90
+ `grep -ahso '${CANARY_PATTERN}' /proc/[0-9]*/environ /proc/[0-9]*/cmdline 2>/dev/null | head -n 20`,
91
+ ];
92
+ }
93
+
94
+ function config() {
95
+ return [
96
+ `ls ${MARKER_DIR} 2>/dev/null | sed 's/^/PROBE|config|marker|/'`,
97
+ `echo "PROBE|config|planted-env|\${${PLANTED_ENV}:-unset}"`,
98
+ ];
99
+ }
100
+
101
+ function network({ hostTargets }) {
102
+ const attempt = (name, ...args) => `attempt ${name} ${args.map(quote).join(" ")}`;
103
+ return [
104
+ // curl's exit code, the HTTP status, the seconds to connect (0 when it never
105
+ // did) and a proxy's answer to CONNECT.
106
+ "attempt() {",
107
+ " name=$1; shift",
108
+ ` seen=$(curl -s -o /dev/null --max-time ${CONNECT_SECONDS} -w '%{exitcode} %{http_code} %{time_connect} %{http_connect}' "$@" 2>/dev/null)`,
109
+ ' echo "PROBE|network|$name|$seen"',
110
+ "}",
111
+ attempt("outside-host", "https://example.com/"),
112
+ attempt("outside-address", "https://1.1.1.1/"),
113
+ attempt(
114
+ "metadata",
115
+ "-H",
116
+ "Metadata: true",
117
+ "http://169.254.169.254/metadata/instance?api-version=2021-02-01",
118
+ ),
119
+ attempt("docker-socket", "--unix-socket", "/var/run/docker.sock", "http://localhost/version"),
120
+ attempt("docker-socket-run", "--unix-socket", "/run/docker.sock", "http://localhost/version"),
121
+ ...hostTargets.map((t, i) => attempt(`host-${i}`, `http://${t.host}:${t.port}/`)),
122
+ 'if ! command -v getent >/dev/null; then echo "PROBE|network|dns|notool"; elif getent hosts example.com >/dev/null 2>&1; then echo "PROBE|network|dns|resolved"; else echo "PROBE|network|dns|unresolved"; fi',
123
+ // The one route there is, and what it refuses: a path outside the model
124
+ // API, and being used as a proxy to anywhere else.
125
+ 'attempt proxy "$ANTHROPIC_BASE_URL/agent-kit-probe"',
126
+ 'attempt proxy-forward -x "$ANTHROPIC_BASE_URL" http://example.com/',
127
+ 'attempt proxy-connect -x "$ANTHROPIC_BASE_URL" https://example.com/',
128
+ ];
129
+ }
130
+
131
+ const PROBES = Object.freeze({ reads, writes, github, key, config, network });
132
+
133
+ /**
134
+ * The script of commands the stub model runs, in order: one per Guard, then
135
+ * one that writes every probe's output as the run's result.
136
+ * @param {{
137
+ * hostFiles: string[],
138
+ * hostTargets: Array<{ host: string, port: number }>,
139
+ * resultPath: string,
140
+ * }} opts `hostFiles` are canary files on the host, outside the sandbox, and
141
+ * `hostTargets` the addresses the host listens on, which the sandbox must
142
+ * not reach.
143
+ * @returns {Array<{ guard: string, script: string }>}
144
+ */
145
+ export function probeScripts(opts) {
146
+ const probes = Object.entries(PROBES).map(([guard, lines]) => ({
147
+ guard,
148
+ // In a subshell, so a probe's `cd` and functions are its own.
149
+ script: ["(", ...lines(opts), `echo "PROBE|${guard}|end"`, `) 2>&1 | tee -a ${LOG}`].join("\n"),
150
+ }));
151
+ const folder = opts.resultPath.slice(0, opts.resultPath.lastIndexOf("/"));
152
+ return [
153
+ ...probes,
154
+ {
155
+ guard: "result",
156
+ script: `mkdir -p ${folder} && cp ${LOG} ${opts.resultPath} && echo "PROBE|result|end"`,
157
+ },
158
+ ];
159
+ }
@@ -0,0 +1,133 @@
1
+ // The live suite's entry, as .github/workflows/harness-live.yml runs it:
2
+ //
3
+ // node cli/src/harness-live/run.mjs <launcher canary>
4
+ //
5
+ // The argument is a made-up value, `AKCANARY-` and 32 hex digits, which puts a
6
+ // secret of the launcher's on its own command line: no sandbox may see it.
7
+ //
8
+ // Every scenario in turn, on gVisor alone (ADR 0031): Linux with `runsc`
9
+ // registered as a Docker runtime. It needs no secret. Exit 0 when every Guard
10
+ // held in every scenario, else 1. In GitHub Actions it also sets the outputs
11
+ // `guard_failed` (true when a Guard was breached or not shown held) and
12
+ // `failed` (which, as `scenario:guard` entries) after each scenario, so a run
13
+ // cut short still says what had failed, and writes the job summary.
14
+ // Everything it prints is made up for the run, so a public log may hold it.
15
+
16
+ import { appendFileSync } from "node:fs";
17
+ import { pathToFileURL } from "node:url";
18
+ import { runnerFor } from "../exec.mjs";
19
+ import { selectRuntime } from "../deep-scan/runtime.mjs";
20
+ import { runScenario, SCENARIOS } from "./suite.mjs";
21
+
22
+ /** A scenario's name as an output holds it: no space or bracket. */
23
+ const slug = (name) => name.replace(/[^A-Za-z0-9]+/g, "-").replace(/-$/, "");
24
+
25
+ /**
26
+ * The suite's results as the workflow reads them.
27
+ * @param {Array<Awaited<ReturnType<typeof runScenario>>>} results
28
+ */
29
+ export function report(results) {
30
+ const failed = results.flatMap((r) =>
31
+ r.verdict === "guard-failed"
32
+ ? [
33
+ ...r.findings.filter((f) => f.status !== "held").map((f) => `${slug(r.name)}:${f.guard}`),
34
+ // A sandbox that failed its own isolation check before any probe ran.
35
+ ...(r.findings.every((f) => f.status === "held") ? [`${slug(r.name)}:isolation`] : []),
36
+ ]
37
+ : [],
38
+ );
39
+ const summary = [
40
+ "## Harness live suite",
41
+ "",
42
+ "| Scenario | Verdict | Guards not held |",
43
+ "| --- | --- | --- |",
44
+ ...results.map((r) => {
45
+ const bad = r.findings.filter((f) => f.status !== "held");
46
+ return `| ${r.name} | ${r.verdict} | ${bad.map((f) => `${f.guard} (${f.status})`).join(", ") || "none"} |`;
47
+ }),
48
+ "",
49
+ ].join("\n");
50
+ return {
51
+ exit: results.length > 0 && results.every((r) => r.verdict === "pass") ? 0 : 1,
52
+ outputs: [`guard_failed=${failed.length > 0}`, `failed=${failed.join(",")}`].join("\n"),
53
+ summary,
54
+ };
55
+ }
56
+
57
+ /** One scenario's findings and, when it did not pass, everything to debug it with. */
58
+ function describe(result) {
59
+ const lines = [
60
+ `::group::${result.name}: ${result.verdict} (exit ${result.exit})`,
61
+ ...result.findings.map(
62
+ (f) => `${f.guard}: ${f.status}${f.reasons.map((r) => `\n - ${r}`).join("")}`,
63
+ ),
64
+ ];
65
+ if (result.verdict !== "pass") {
66
+ lines.push("--- the launcher's output", result.log);
67
+ for (const [guard, text] of Object.entries(result.outputs)) {
68
+ lines.push(`--- the ${guard} probe's output`, text.slice(0, 4000));
69
+ }
70
+ }
71
+ // Nothing printed from the sandbox may start a workflow command of its own.
72
+ const [open, ...rest] = lines;
73
+ return [open, ...rest.map((l) => l.replace(/^(\s*)::/gm, "$1: :")), "::endgroup::"].join("\n");
74
+ }
75
+
76
+ /** A launcher canary, as the workflow makes it. */
77
+ const LAUNCHER_CANARY = /^AKCANARY-[0-9a-f]{32}$/;
78
+
79
+ async function suite(launcherCanary) {
80
+ if (!LAUNCHER_CANARY.test(launcherCanary ?? "")) {
81
+ console.error("usage: run.mjs AKCANARY-<32 hex digits>, a value made up for this run.");
82
+ return 2;
83
+ }
84
+ const runner = runnerFor("deep-scan");
85
+ const choice = selectRuntime({ runner, platform: process.platform });
86
+ if ("refused" in choice || choice.runtime.id !== "gvisor") {
87
+ console.error(
88
+ [
89
+ "The live suite proves the Guards under gVisor: run it on Linux with runsc registered as a Docker runtime.",
90
+ ...("refused" in choice ? choice.refused : [`This host offers ${choice.runtime.name}.`]),
91
+ ].join("\n"),
92
+ );
93
+ return 1;
94
+ }
95
+ const results = [];
96
+ for (const scenario of SCENARIOS) {
97
+ console.log(`Running ${scenario.name} ...`);
98
+ let result;
99
+ try {
100
+ result = await runScenario(scenario, {
101
+ runner,
102
+ launcherCanary,
103
+ runtime: choice.runtime,
104
+ expectedRuntime: choice.runtime.dockerRuntime,
105
+ });
106
+ } catch (e) {
107
+ result = {
108
+ name: scenario.name,
109
+ verdict: "error",
110
+ findings: [],
111
+ exit: 1,
112
+ log: e?.stack ?? String(e),
113
+ outputs: {},
114
+ };
115
+ }
116
+ results.push(result);
117
+ console.log(describe(result));
118
+ // The last value written for an output wins.
119
+ if (process.env.GITHUB_OUTPUT) {
120
+ appendFileSync(process.env.GITHUB_OUTPUT, `${report(results).outputs}\n`);
121
+ }
122
+ }
123
+ const { exit, summary } = report(results);
124
+ console.log(summary);
125
+ if (process.env.GITHUB_STEP_SUMMARY) {
126
+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary);
127
+ }
128
+ return exit;
129
+ }
130
+
131
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
132
+ process.exitCode = await suite(process.argv[2]);
133
+ }
@@ -0,0 +1,151 @@
1
+ // A read-only Stage as the live suite runs it (ADR 0031): the pinned harness,
2
+ // by its adapter's launch plan, in the Deep scan's sandbox driver, behind the
3
+ // real model proxy, handed a brief, with one result file copied out.
4
+ //
5
+ // The `agent-kit stage` command, the Launcher's path for a Stage (ADR 0024),
6
+ // does not exist yet; until it does, this composes the same driver, adapter,
7
+ // agent script and proxy, and nothing here ships to a Consumer's run. Once it
8
+ // exists, the live suite enters through it. It removes nothing from the copy,
9
+ // so the checkout's config is kept out by the adapter's launch alone.
10
+
11
+ import { randomBytes } from "node:crypto";
12
+ import { writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { agentScript, BRIEF_PATH } from "../deep-scan/agent.mjs";
15
+ import { callerKeyFor, withoutCredentials } from "../deep-scan/credential.mjs";
16
+ import { dockerDriver } from "../deep-scan/docker-driver.mjs";
17
+ import { StepFailed } from "../deep-scan/steps.mjs";
18
+ import { tarOf } from "../deep-scan/tar.mjs";
19
+ import { claudeCode } from "../harness/claude-code.mjs";
20
+ import { startProxy } from "../model-proxy/core.mjs";
21
+ import { anthropic } from "../model-proxy/profiles/anthropic.mjs";
22
+
23
+ /** Where the Stage's result goes in the sandbox. */
24
+ export const STAGE_RESULT_PATH = "/agent-kit/out/result.md";
25
+
26
+ /** The longest a Stage's run may take. */
27
+ const TIMEOUT_MS = 20 * 60_000;
28
+
29
+ const MAX_RESULT = 10 * 1024 * 1024;
30
+
31
+ /** The harness's turn limit and the proxy's token cap, far above what the script needs. */
32
+ const MAX_TURNS = 40;
33
+ const MAX_TOKENS = 20_000_000;
34
+
35
+ /**
36
+ * Run the Stage. Returns 0 when the harness exited cleanly and its result came
37
+ * out, else 1. Every sandbox resource is removed on the way out.
38
+ * @param {{
39
+ * runner: import("../exec.mjs").Runner,
40
+ * runtime: import("../deep-scan/runtime.mjs").Runtime,
41
+ * root: string,
42
+ * commit: string,
43
+ * credential: string,
44
+ * credentialKind: "api-key" | "subscription",
45
+ * modelApi: string,
46
+ * outDir: string,
47
+ * beforeTeardown: (container: string, launch: { env: string[], url: string }) => Promise<void>,
48
+ * out: (s: string) => void,
49
+ * err: (s: string) => void,
50
+ * }} opts `modelApi` is the proxy's upstream: here, the stub model.
51
+ * `outDir` receives what is copied out. `beforeTeardown` reads the sandbox
52
+ * after the harness ran.
53
+ */
54
+ export async function runReadOnlyStage({
55
+ runner: hostRunner,
56
+ runtime,
57
+ root,
58
+ commit,
59
+ credential,
60
+ credentialKind,
61
+ modelApi,
62
+ outDir,
63
+ beforeTeardown,
64
+ out,
65
+ err,
66
+ }) {
67
+ // No command of the launcher's inherits the model credential.
68
+ const runner = withoutCredentials(hostRunner, [process.env]);
69
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
70
+ const call = (cmd, args, opts = {}) => runner.start(cmd, args, { ...opts, signal });
71
+ const id = randomBytes(6).toString("hex");
72
+ const request = { stage: "review", credentialKind };
73
+ const driver = dockerDriver({ runtime, id, call, plan: claudeCode(request) });
74
+ const steps = { setup: [], start: [], ready: [], seed: [], registries: [], grounding: [] };
75
+ const must = (condition, why) => {
76
+ if (!condition) throw new StepFailed([`FAILED ${why}.`]);
77
+ };
78
+ let proxy = null;
79
+ try {
80
+ await driver.prepare(steps, { out, branch: "main", short: commit.slice(0, 12) });
81
+ await driver.start(steps);
82
+ const archive = runner(
83
+ "git",
84
+ ["-c", "core.autocrlf=false", "-C", root, "archive", "--prefix=workspace/", commit],
85
+ { encoding: "buffer" },
86
+ );
87
+ must(archive.status === 0, `exporting the repository: ${archive.stderr}`);
88
+ await driver.copyIn(archive.stdout, "copying the repository in");
89
+ await driver.cutEgress();
90
+ const left = await driver.egressLeft();
91
+ must(left === null, `the network is not cut: ${left}`);
92
+ const callerKey = callerKeyFor(credentialKind);
93
+ const route = await driver.openModelRoute(async (bind) => {
94
+ proxy = await startProxy(anthropic, {
95
+ credential,
96
+ kind: credentialKind,
97
+ bind,
98
+ callerKey,
99
+ upstream: modelApi,
100
+ maxTokens: MAX_TOKENS,
101
+ });
102
+ return proxy;
103
+ });
104
+ const extra = await driver.egressLeft();
105
+ must(extra === null, `more than the model route is open: ${extra}`);
106
+ const brief = `# Stage brief\n\nThis Stage is read-only. Write your result to ${STAGE_RESULT_PATH}.\n`;
107
+ await driver.copyIn(
108
+ tarOf([
109
+ { path: "agent-kit", dir: true },
110
+ { path: "agent-kit/in", dir: true },
111
+ { path: BRIEF_PATH.slice(1), data: Buffer.from(brief, "utf8") },
112
+ ]),
113
+ "copying the brief in",
114
+ );
115
+ const plan = claudeCode({
116
+ ...request,
117
+ proxyUrl: route.url,
118
+ briefPath: BRIEF_PATH,
119
+ kitDir: "/agent-kit",
120
+ maxTurns: MAX_TURNS,
121
+ callerKey,
122
+ });
123
+ out(`Agent step: ${plan.identity.displayName} ${plan.identity.version}, a read-only Stage.`);
124
+ const agent = await driver.exec(
125
+ agentScript({ plan, report: STAGE_RESULT_PATH, workspace: "/workspace" }),
126
+ { env: plan.launch.env },
127
+ );
128
+ if (agent.status !== 0) err(`The agent step exited ${agent.status}:\n${agent.stderr}`);
129
+ await beforeTeardown(driver.container, { env: plan.launch.env, url: route.url });
130
+ const file = await driver.copyOut(STAGE_RESULT_PATH, { maxBytes: MAX_RESULT });
131
+ if (!("data" in file)) {
132
+ err("FAILED no result came out.");
133
+ return 1;
134
+ }
135
+ writeFileSync(join(outDir, file.name), file.data, { mode: 0o600, flag: "wx" });
136
+ return agent.status === 0 ? 0 : 1;
137
+ } catch (e) {
138
+ if (!(e instanceof StepFailed)) throw e;
139
+ err(e.lines.join("\n"));
140
+ return 1;
141
+ } finally {
142
+ out(`Model proxy: ${proxy?.summary() ?? "not started"}.`);
143
+ await driver.close();
144
+ for (const { what, cmd, args } of driver.teardown()) {
145
+ const r = hostRunner(cmd, args);
146
+ if (r.status !== 0 && !/no such|not found/i.test(r.stderr)) {
147
+ err(`TEARDOWN could not remove ${what}: ${r.stderr}`);
148
+ }
149
+ }
150
+ }
151
+ }