@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.
@@ -1,9 +1,76 @@
1
1
  // The Deep scan launcher's pre-flight refusals (#368): before any sandbox
2
2
  // runtime is touched, refuse a GitHub token that would reach the sandbox and
3
3
  // a .env that would be forwarded into it wholesale. Both checks read only the
4
- // launcher's own environment and the trusted ref's file list.
4
+ // launcher's own environment and the trusted ref's file list. A third
5
+ // refusal comes with the image, the first thing that can show it, and still
6
+ // before any sandbox: a musl recipe image, which cannot run the Harness
7
+ // image's glibc builds (ADR 0029). Before all of them, the Support Level
8
+ // (ADR 0028): a Deep scan runs on a pair below `tried` only as a Proving run.
5
9
 
10
+ import { appendFileSync } from "node:fs";
6
11
  import { firstLine } from "../exec.mjs";
12
+ import { readHarnesses, supportFor } from "../harness/facts.mjs";
13
+ import { MUSL_MARKER } from "../harness/install-layer.mjs";
14
+ import { ENDS_HERE, outputLines, StepFailed } from "./steps.mjs";
15
+
16
+ /**
17
+ * Throw the musl refusal when the layer build `r` failed on the musl check.
18
+ * @param {import("../exec.mjs").StartResult} r
19
+ * @param {{ image?: string, dockerfile?: string }} steps the recipe's
20
+ */
21
+ export function refuseMusl(r, { image, dockerfile }) {
22
+ if (r.status === 0) return;
23
+ if (!`${r.stdout.toString("utf8")}\n${r.stderr}`.includes(MUSL_MARKER)) return;
24
+ const what =
25
+ dockerfile !== undefined
26
+ ? `The image the recipe's ${dockerfile} builds`
27
+ : `The recipe's image ${image}`;
28
+ throw new StepFailed([
29
+ `REFUSED ${what} is musl Linux (such as Alpine), and the harness runs only on glibc Linux.`,
30
+ ...outputLines(r),
31
+ "Name a glibc image, such as a Debian or Ubuntu one, or leave image and dockerfile out to run on the Harness image.",
32
+ ENDS_HERE,
33
+ ]);
34
+ }
35
+
36
+ /**
37
+ * Whether a Deep scan may run on `harness` at the Support Level
38
+ * `cli/harnesses.json` holds for the pair, and what the run says about it:
39
+ * the line it prints and the line of the GitHub Actions run summary, for a
40
+ * refused run too, then the refusal, or the warning at `documented`. All of
41
+ * it comes from that file and the flag, nothing from the scan, so a public
42
+ * log may hold it.
43
+ * @param {{ harness?: string, provingRun?: boolean }} run
44
+ * @returns {{ line: string, summary: string, refused?: string, warning?: string }}
45
+ */
46
+ export function deepScanSupport({ harness = "claude-code", provingRun = false }) {
47
+ const facts = readHarnesses().harnesses[harness];
48
+ const found = supportFor(facts, { stage: "deep-scan", provingRun });
49
+ const level = facts.supportLevels["deep-scan"]?.level ?? "none";
50
+ const proving = provingRun ? "yes" : "no";
51
+ return {
52
+ line: `Harness: ${harness}; Support Level: ${level}; Proving run: ${proving}`,
53
+ summary: `Harness: \`${harness}\` · Support Level: \`${level}\` · Proving run: ${proving}`,
54
+ ...(found.refused !== undefined ? { refused: found.refused } : {}),
55
+ ...(found.warning !== undefined ? { warning: found.warning } : {}),
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Add `line` to the GitHub Actions run summary, where `env` names one.
61
+ * @param {Record<string, string | undefined>} env
62
+ * @param {string} line
63
+ * @returns {string | null} why it could not be written, or null
64
+ */
65
+ export function writeRunSummary(env, line) {
66
+ if (!env.GITHUB_STEP_SUMMARY) return null;
67
+ try {
68
+ appendFileSync(env.GITHUB_STEP_SUMMARY, `${line}\n`);
69
+ return null;
70
+ } catch (e) {
71
+ return firstLine(e.message);
72
+ }
73
+ }
7
74
 
8
75
  /** The GitHub token variables that must never reach the sandbox. */
9
76
  export const GITHUB_TOKEN_VARS = Object.freeze(["GH_TOKEN", "GITHUB_TOKEN"]);
@@ -132,15 +132,11 @@ export function validateRecipe(text) {
132
132
  if (problem) say(key, problem);
133
133
  }
134
134
 
135
- // image or dockerfile, exactly one.
135
+ // image or dockerfile, at most one: without either, the scan runs on the
136
+ // Harness image (ADR 0029).
136
137
  const hasImage = "image" in recipe;
137
138
  const hasDockerfile = "dockerfile" in recipe;
138
- if (!hasImage && !hasDockerfile) {
139
- say(
140
- "image or dockerfile",
141
- "name a base image (image) or a Dockerfile (dockerfile); the recipe has neither.",
142
- );
143
- } else if (hasImage && hasDockerfile) {
139
+ if (hasImage && hasDockerfile) {
144
140
  say("image and dockerfile", "give one of them, not both.");
145
141
  }
146
142
  if (hasImage && !isWord(recipe.image)) {
@@ -14,8 +14,9 @@
14
14
  // starts, and a plain image has no /home/agent, so `-t <plain image>` never
15
15
  // starts (#375's diagnosis, run evidence d375-sbx-diag.txt). The human chose
16
16
  // (#375, option 1): Docker on the host pulls the recipe's image and layers
17
- // on it the Docker driver's pinned Claude Code and what Docker's docs
18
- // require of a template image (TEMPLATE_LAYER: a non-root `agent`, uid
17
+ // on it the Docker driver's pinned Claude Code (copied from the Harness
18
+ // image, ADR 0029; a recipe with no image gets the Harness image itself as
19
+ // the base) and what Docker's docs require of a template image (TEMPLATE_LAYER: a non-root `agent`, uid
19
20
  // 1000, home /home/agent, as its USER; curl, git, CA certificates and
20
21
  // bash, checked); `docker save` writes it to a private folder, `sbx template load`
21
22
  // loads it, and `sbx create --pull never -t <it>` uses it. Teardown removes
@@ -42,9 +43,10 @@ import { lstatSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSyn
42
43
  import { tmpdir } from "node:os";
43
44
  import { join } from "node:path";
44
45
  import { firstLine } from "../exec.mjs";
45
- import { AUTO_UPDATER_OFF, layerDockerfile } from "./claude-code.mjs";
46
+ import { layerDockerfile, pinnedHarnessImage } from "../harness/install-layer.mjs";
46
47
  import { LABEL } from "./docker-driver.mjs";
47
48
  import { allowlistOf } from "./egress.mjs";
49
+ import { refuseMusl } from "./preflight.mjs";
48
50
  import { imageDigestNote } from "./recipe.mjs";
49
51
  import { ENDS_HERE, must, StepFailed } from "./steps.mjs";
50
52
 
@@ -126,10 +128,12 @@ export function sbxResources(registries) {
126
128
  }
127
129
 
128
130
  /**
129
- * @param {{ id: string, call: import("./docker-driver.mjs").Call }} opts
131
+ * @param {{ id: string, call: import("./docker-driver.mjs").Call, plan: import("../harness/claude-code.mjs").LaunchPlan }} opts
132
+ * `plan` is the harness's launch plan: its install layer goes on the template.
130
133
  * @returns {import("./lifecycle.mjs").Driver}
131
134
  */
132
- export function sbxDriver({ id, call }) {
135
+ export function sbxDriver({ id, call, plan }) {
136
+ const { displayName } = plan.identity;
133
137
  const name = `agent-kit-deep-${id}`;
134
138
  /** The layered image, and the sbx template loaded from it. */
135
139
  const template = `${name}:sbx`;
@@ -177,21 +181,26 @@ export function sbxDriver({ id, call }) {
177
181
  container: name,
178
182
 
179
183
  async prepare(steps, { out }) {
184
+ const harness = pinnedHarnessImage(plan.installLayer);
180
185
  if (steps.dockerfile !== undefined) {
181
186
  throw new StepFailed([
182
187
  `REFUSED The recipe builds ${steps.dockerfile}, and on Docker Sandboxes its build steps would run on this machine's Docker (Docker Desktop's WSL 2 VM on Windows), outside the sandbox.`,
183
- "On Docker Sandboxes, name a base image with `image:` instead (one with Node.js and npm), or run on another accepted runtime.",
188
+ "On Docker Sandboxes, name a glibc base image with `image:` instead, or none to run on the Harness image, or run on another accepted runtime.",
184
189
  ]);
185
190
  }
186
191
  const problem = globalPolicyProblem(await sbx(["policy", "ls", "--json"]));
187
192
  if (problem) throw new StepFailed(problem);
188
193
  out("Network policy: Docker Sandboxes' global policy is deny-all (checked read-only).");
194
+ const own = steps.image !== undefined;
195
+ const base = own ? steps.image : harness;
189
196
  out(
190
- `Image: layering the pinned Claude Code on ${steps.image} with Docker on this machine, auto-updater off, as the sandbox's template.`,
197
+ own
198
+ ? `Image: layering the pinned ${displayName} on ${base} with Docker on this machine, auto-updater off, as the sandbox's template; ${displayName} comes from the Harness image ${harness}.`
199
+ : `Image: the Harness image ${harness}, which holds the pinned ${displayName}, as the sandbox's template, built with Docker on this machine; the recipe names no image.`,
191
200
  );
192
- const note = imageDigestNote(steps.image);
201
+ const note = own ? imageDigestNote(base) : null;
193
202
  if (note) out(note);
194
- const pulled = await docker(["pull", steps.image]);
203
+ const pulled = await docker(["pull", base]);
195
204
  if (pulled.status === null) {
196
205
  throw new StepFailed([
197
206
  "FAILED Docker Sandboxes' template is built with Docker on this machine, and docker could not run: " +
@@ -200,15 +209,14 @@ export function sbxDriver({ id, call }) {
200
209
  ENDS_HERE,
201
210
  ]);
202
211
  }
203
- must(pulled, `pulling ${steps.image}`, { showOutput: true });
212
+ must(pulled, `pulling ${base}`, { showOutput: true });
204
213
  imageBuilt = true;
205
- must(
206
- await docker(["build", "--label", `${LABEL}=${id}`, "--tag", template, "-"], {
207
- stdin: `${layerDockerfile(steps.image)}${TEMPLATE_LAYER}`,
208
- }),
209
- `layering Claude Code on ${steps.image}`,
210
- { showOutput: true },
211
- );
214
+ const layer = own ? layerDockerfile(base, plan.installLayer) : `FROM ${base}\n`;
215
+ const built = await docker(["build", "--label", `${LABEL}=${id}`, "--tag", template, "-"], {
216
+ stdin: `${layer}${TEMPLATE_LAYER}`,
217
+ });
218
+ if (own) refuseMusl(built, steps);
219
+ must(built, `layering ${displayName} on ${base}`, { showOutput: true });
212
220
  // A private host file, by a name relative to its folder, so a Windows
213
221
  // drive letter is never read as anything else; gone once it is loaded.
214
222
  const tar = "template.tar";
@@ -245,8 +253,7 @@ export function sbxDriver({ id, call }) {
245
253
  "never",
246
254
  "-t",
247
255
  template,
248
- "-e",
249
- AUTO_UPDATER_OFF,
256
+ ...plan.installLayer.env.flatMap((v) => ["-e", v]),
250
257
  "shell",
251
258
  ]),
252
259
  "creating the sandbox",
@@ -276,7 +283,7 @@ export function sbxDriver({ id, call }) {
276
283
  );
277
284
  },
278
285
 
279
- /** Claude Code is in the template already: nothing to install. */
286
+ /** The harness is in the template already: nothing to install. */
280
287
  async installAgent() {},
281
288
 
282
289
  async openSetupEgress(registries) {
@@ -475,7 +482,7 @@ function idOf(r, repository, tag) {
475
482
  * image's package mirror from the host, which no recipe field names. An
476
483
  * existing uid 1000 account (`node`, in the Node.js images) is renamed to
477
484
  * `agent`, its home moved, rather than given a second name for one uid.
478
- * It runs as root, after the Claude Code layer, and ends on USER agent.
485
+ * It runs as root, after the harness's install layer, and ends on USER agent.
479
486
  */
480
487
  const TEMPLATE_LAYER = [
481
488
  "USER root",
package/src/deep-scan.mjs CHANGED
@@ -1,4 +1,6 @@
1
1
  // `agent-kit deep-scan`: the host-side launcher for a Deep scan (ADR 0019).
2
+ // It first refuses a harness whose Support Level for the Deep scan is below
3
+ // `tried`, unless the run is a Proving run (`--proving-run`, ADR 0028).
2
4
  // Its first stage finds the Consumer's Scan recipe at the trusted ref (the
3
5
  // default branch's tip, never the working tree) and validates it, or refuses
4
6
  // with what is wrong and a pointer to the docs. There is no fallback to a
@@ -40,7 +42,14 @@ import { DEFAULT_LIMITS, describeLimits, parseLimits, VERIFY_LIMITS } from "./de
40
42
  import { publicHttpsFetch } from "./deep-scan/grounding-url.mjs";
41
43
  import { runLifecycle } from "./deep-scan/lifecycle.mjs";
42
44
  import { MODEL_ID } from "./deep-scan/model-proxy.mjs";
43
- import { envFilesAtRef, envFilesCarriedFromDefault, strayTokens } from "./deep-scan/preflight.mjs";
45
+ import {
46
+ deepScanSupport,
47
+ envFilesAtRef,
48
+ envFilesCarriedFromDefault,
49
+ strayTokens,
50
+ writeRunSummary,
51
+ } from "./deep-scan/preflight.mjs";
52
+ import { effortFor, readHarnesses } from "./harness/facts.mjs";
44
53
  import { RUNTIMES_DOCS_URL, selectRuntime } from "./deep-scan/runtime.mjs";
45
54
  import {
46
55
  readFindingFile,
@@ -50,7 +59,14 @@ import {
50
59
  } from "./deep-scan/verify.mjs";
51
60
  import { CLI_VERSION } from "./tags.mjs";
52
61
 
62
+ /** The Deep scan's harness, as `cli/harnesses.json` describes it. */
63
+ const HARNESS = readHarnesses().harnesses["claude-code"];
64
+
65
+ /** The effort levels it accepts: nothing else reaches the command line. */
66
+ export const EFFORTS = Object.freeze(HARNESS.effortValues);
67
+
53
68
  const CREDENTIALS_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs/security-audit.md#credentials`;
69
+ const PROVING_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs/harnesses.md#proving-runs`;
54
70
 
55
71
  /**
56
72
  * @param {{
@@ -65,6 +81,7 @@ const CREDENTIALS_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CL
65
81
  * reportPath?: string,
66
82
  * verifyPath?: string,
67
83
  * ref?: string,
84
+ * provingRun?: boolean,
68
85
  * limitFlags?: Record<string, string | undefined>,
69
86
  * platform?: string,
70
87
  * env?: Record<string, string | undefined>,
@@ -78,6 +95,8 @@ const CREDENTIALS_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CL
78
95
  * }} opts `limitFlags` holds the limit flags' values, keyed by flag name.
79
96
  * `verifyPath` (a finding file) and `ref` go together, for a
80
97
  * Verification run.
98
+ * `provingRun` runs a harness below `tried` for the Deep scan, to record
99
+ * the evidence that raises its level; it relaxes nothing else.
81
100
  * `platform`, `env`, `fetch`, `signals` and `timers` are the host's
82
101
  * (`process.platform`, `process.env`, the public-HTTPS grounding fetch, `process`, the
83
102
  * real clock), and `reportDir` is a new private temporary folder, and
@@ -99,6 +118,7 @@ export async function runDeepScan({
99
118
  reportPath,
100
119
  verifyPath,
101
120
  ref,
121
+ provingRun = false,
102
122
  limitFlags = {},
103
123
  platform = process.platform,
104
124
  env = process.env,
@@ -163,7 +183,8 @@ export async function runDeepScan({
163
183
  );
164
184
  return 2;
165
185
  }
166
- if (effort !== undefined && !EFFORTS.includes(effort)) {
186
+ // The Stage's own effort: one its harness does not accept is refused.
187
+ if (effort !== undefined && (effort === "" || "refused" in effortFor(HARNESS, { effort }))) {
167
188
  err(
168
189
  `--effort must be one of ${EFFORTS.slice(0, -1).join(", ")} or ${EFFORTS.at(-1)}, got: ${JSON.stringify(effort)}`,
169
190
  );
@@ -206,6 +227,15 @@ export async function runDeepScan({
206
227
  return 2;
207
228
  }
208
229
 
230
+ // The Support Level (ADR 0028), before anything is read or run.
231
+ const support = deepScanSupport({ provingRun });
232
+ // A refused run is named too, in the log and the run summary.
233
+ out(support.line);
234
+ const unwritten = writeRunSummary(env, support.summary);
235
+ if (unwritten !== null) err(`Could not write the run summary: ${unwritten}`);
236
+ if (support.refused !== undefined) return refuse([support.refused], PROVING_DOCS_URL);
237
+ if (support.warning !== undefined) err(`Warning: ${support.warning}`);
238
+
209
239
  // The finding file, read and checked on the host before anything runs.
210
240
  let given = null;
211
241
  if (verifying) {
@@ -331,7 +361,7 @@ export async function runDeepScan({
331
361
  [
332
362
  `${tokens.join(" and ")} ${tokens.length > 1 ? "are" : "is"} set in deep-scan's environment, and a GitHub token must never reach the sandbox.`,
333
363
  `Unset ${tokens.length > 1 ? "them" : "it"} for this run, for example:`,
334
- " env -u GH_TOKEN -u GITHUB_TOKEN npx @mnaimfaizy/agent-kit deep-scan",
364
+ ` env -u GH_TOKEN -u GITHUB_TOKEN npx @mnaimfaizy/agent-kit deep-scan${provingRun ? " --proving-run" : ""}`,
335
365
  " In PowerShell: Remove-Item Env:GH_TOKEN, Env:GITHUB_TOKEN -ErrorAction SilentlyContinue, then run it again.",
336
366
  ],
337
367
  RUNTIMES_DOCS_URL,
@@ -454,12 +484,6 @@ export async function runDeepScan({
454
484
  });
455
485
  }
456
486
 
457
- /**
458
- * The effort levels Claude Code's --effort takes (2.1.328's --help), and the
459
- * static workflow's effort input: nothing else reaches the command line.
460
- */
461
- export const EFFORTS = Object.freeze(["low", "medium", "high", "xhigh", "max"]);
462
-
463
487
  /** Text with LF line ends, so a CRLF checkout of the same file compares equal. */
464
488
  const lf = (text) => text.replace(/\r\n?/g, "\n");
465
489
 
@@ -0,0 +1,229 @@
1
+ // The Claude Code Harness adapter (ADR 0027): one function that takes a
2
+ // Stage request and returns a launch plan, as plain data. The Launcher does
3
+ // everything with the plan; this module starts nothing and imports nothing.
4
+ //
5
+ // The CLI: one pinned version, in `/opt/agent-kit` of the kit's Harness image
6
+ // (ADR 0029, docker/harness-images/), which is pinned by digest, with the
7
+ // auto-updater off both by environment and by managed settings in
8
+ // /etc/claude-code, which the repository's own project settings cannot
9
+ // override. Nothing is installed at run time.
10
+ //
11
+ // The launch: print mode, the brief on stdin. `--bare` skips skill and
12
+ // CLAUDE.md discovery, so the Launcher hands the agent everything
13
+ // explicitly, in its brief. The agent holds only the run's caller key as its
14
+ // API key. Its model API base URL is pinned by the Launcher's own `--settings`, which
15
+ // outrank project settings, and project and local settings are not even
16
+ // loaded (`--setting-sources user`), so the scanned repository's
17
+ // `.claude/settings.json` cannot point it elsewhere. Web tools are not in
18
+ // its tool set, and are denied as well. Its turn limit is `--max-turns` on
19
+ // the command line (#371).
20
+ //
21
+ // On the subscription path (#375) it holds the caller key as its
22
+ // CLAUDE_CODE_OAUTH_TOKEN instead, and runs without `--bare`, which never
23
+ // reads one. So it can discover the scanned repository's CLAUDE.md and
24
+ // skills: the brief says they are that repository's content, and that its
25
+ // own procedure decides. The settings stay pinned the same way, hooks are
26
+ // off in them, and `--strict-mcp-config` keeps any MCP server the
27
+ // repository names from starting.
28
+
29
+ /** The Claude Code version every sandbox runs, pinned. */
30
+ const VERSION = "2.1.328";
31
+
32
+ /**
33
+ * The Harness image that holds that version. The `harness-images` workflow
34
+ * builds it in the pull request that changes the pin or its Dockerfile, and
35
+ * fails until this holds the digest it pushed
36
+ * (`node docker/harness-images/image.mjs record claude-code`).
37
+ */
38
+ const IMAGE = "ghcr.io/mnaimfaizy/agent-kit-sandbox-claude-code";
39
+ const IMAGE_DIGEST = "sha256:076c453ea2c86191e20e0c66d717c886dffda18549f1df2e6fdc0630d48e9a5f"; // inputs-bbd92fca1095d0aa25d8c7b8d963b90d
40
+
41
+ /** The environment that keeps the auto-updater off. */
42
+ const AUTO_UPDATER_OFF = "DISABLE_AUTOUPDATER=1";
43
+
44
+ const MANAGED_SETTINGS = JSON.stringify({ env: { DISABLE_AUTOUPDATER: "1" } });
45
+
46
+ /**
47
+ * What a Consumer needs to know about Claude Code, which `cli/harnesses.json`
48
+ * publishes per tag (ADR 0030): the kit secrets it accepts, the preferred one
49
+ * first, each with where to get it; the effort levels `--effort` takes at the
50
+ * pinned version (its --help); and the model a Stage gets when none is named.
51
+ */
52
+ export const FACTS = Object.freeze({
53
+ displayName: "Claude Code",
54
+ secrets: Object.freeze([
55
+ {
56
+ name: "claude_code_oauth_token",
57
+ whereToGet:
58
+ "Run `claude setup-token` on your machine, signed in to your Claude subscription, and paste the token.",
59
+ },
60
+ {
61
+ name: "anthropic_api_key",
62
+ whereToGet:
63
+ "Create an API key in the Anthropic Console: https://console.anthropic.com/settings/keys.",
64
+ },
65
+ ]),
66
+ effortValues: Object.freeze(["low", "medium", "high", "xhigh", "max"]),
67
+ defaultModel: "claude-opus-5-5",
68
+ });
69
+
70
+ /** The tools the agent has; the web tools are not among them. */
71
+ export const TOOLS = Object.freeze(["Bash", "Read", "Write", "Edit", "Glob", "Grep"]);
72
+ export const WEB_TOOLS = Object.freeze(["WebFetch", "WebSearch"]);
73
+
74
+ /**
75
+ * The credentials Claude Code accepts, by kind: the kit secret, the
76
+ * variable it reads in the sandbox, and the placeholder it holds there,
77
+ * which the model proxy swaps. A run with a caller key holds that instead,
78
+ * made by the Launcher to start with this placeholder. The subscription one
79
+ * is shaped like a token, in case Claude Code checks the prefix.
80
+ */
81
+ const CREDENTIALS = {
82
+ "api-key": {
83
+ secret: "anthropic_api_key",
84
+ env: "ANTHROPIC_API_KEY",
85
+ placeholder: "agent-kit-deep-scan-placeholder",
86
+ },
87
+ subscription: {
88
+ secret: "claude_code_oauth_token",
89
+ env: "CLAUDE_CODE_OAUTH_TOKEN",
90
+ placeholder: "sk-ant-oat01-agent-kit-deep-scan-placeholder",
91
+ },
92
+ };
93
+
94
+ /**
95
+ * @typedef {{
96
+ * stage?: string,
97
+ * model?: string,
98
+ * effort?: string,
99
+ * credentialKind?: "api-key" | "subscription",
100
+ * proxyUrl?: string,
101
+ * briefPath?: string,
102
+ * kitDir?: string,
103
+ * maxTurns?: number,
104
+ * callerKey?: string,
105
+ * }} StageRequest `model` and `effort` pass through verbatim, already
106
+ * checked by the Launcher; without either, Claude Code runs on its own
107
+ * default. `proxyUrl` is the model proxy as the sandbox reaches it,
108
+ * `kitDir` the Launcher's folder there, outside the workspace, and
109
+ * `maxTurns` the turn limit. `callerKey` is the run's caller key, which the
110
+ * model proxy requires: it is the chosen kind's placeholder in the plan, and
111
+ * so what the sandbox holds. A request without them (before the sandbox
112
+ * exists) gets a plan whose launch leaves them out.
113
+ *
114
+ * @typedef {{
115
+ * identity: { name: string, displayName: string, version: string, major: number },
116
+ * installLayer: { image: string, env: string[], run: string[] },
117
+ * modelRoute: { profile: string },
118
+ * credentials: {
119
+ * accepted: Record<string, { secret: string, env: string, placeholder: string }>,
120
+ * scrub: string[],
121
+ * },
122
+ * launch: {
123
+ * argv: string[],
124
+ * stdin: { file: string | undefined } | null,
125
+ * files: Array<{ path: string, text: string }>,
126
+ * env: string[],
127
+ * },
128
+ * checkoutConfig: string[],
129
+ * instructionFiles: string[],
130
+ * stops: { turnCap: { stderrPattern: string } | null },
131
+ * transcript: { path: string },
132
+ * }} LaunchPlan The nine parts of ADR 0027. `installLayer.image` is the
133
+ * Harness image, by digest: the sandbox runs from it, or its
134
+ * `/opt/agent-kit` is copied onto another glibc image, where `env` is set
135
+ * and `run`, the lines of one shell command, puts the CLI on the path.
136
+ * `credentials.scrub` names every variable a model credential of this
137
+ * harness can sit in, removed from the Launcher's own commands.
138
+ */
139
+
140
+ /**
141
+ * The launch plan for `request`.
142
+ * @param {StageRequest} [request]
143
+ * @returns {LaunchPlan}
144
+ */
145
+ export function claudeCode({
146
+ model,
147
+ effort,
148
+ credentialKind = "api-key",
149
+ proxyUrl,
150
+ briefPath,
151
+ kitDir,
152
+ maxTurns,
153
+ callerKey,
154
+ } = {}) {
155
+ const subscription = credentialKind === "subscription";
156
+ const accepted = structuredClone(CREDENTIALS);
157
+ const credential = accepted[credentialKind];
158
+ if (callerKey !== undefined) credential.placeholder = callerKey;
159
+ // The Launcher's own settings. Hooks are off where no `--bare` skips
160
+ // them: a setup step could have written some into the user settings.
161
+ const settings = {
162
+ env: {
163
+ ANTHROPIC_BASE_URL: proxyUrl,
164
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
165
+ DISABLE_AUTOUPDATER: "1",
166
+ },
167
+ permissions: { allow: [...TOOLS], deny: [...WEB_TOOLS] },
168
+ ...(subscription ? { disableAllHooks: true } : {}),
169
+ };
170
+ return {
171
+ identity: { name: "claude-code", displayName: "Claude Code", version: VERSION, major: 2 },
172
+ installLayer: {
173
+ image: `${IMAGE}@${IMAGE_DIGEST}`,
174
+ env: [AUTO_UPDATER_OFF],
175
+ run: [
176
+ "ln -sf /opt/agent-kit/bin/claude /usr/local/bin/claude \\",
177
+ " && mkdir -p /etc/claude-code \\",
178
+ ` && printf '%s\\n' '${MANAGED_SETTINGS}' > /etc/claude-code/managed-settings.json`,
179
+ ],
180
+ },
181
+ modelRoute: { profile: "anthropic" },
182
+ credentials: {
183
+ accepted,
184
+ scrub: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"],
185
+ },
186
+ launch: {
187
+ argv: [
188
+ "claude",
189
+ ...(subscription ? [] : ["--bare"]),
190
+ "--print",
191
+ "--settings",
192
+ JSON.stringify(settings),
193
+ "--setting-sources",
194
+ "user",
195
+ ...(subscription ? ["--strict-mcp-config"] : []),
196
+ "--tools",
197
+ TOOLS.join(","),
198
+ "--allowedTools",
199
+ TOOLS.join(","),
200
+ "--disallowedTools",
201
+ WEB_TOOLS.join(","),
202
+ "--permission-mode",
203
+ "dontAsk",
204
+ ...(kitDir !== undefined ? ["--add-dir", kitDir] : []),
205
+ "--no-session-persistence",
206
+ ...(maxTurns !== undefined ? ["--max-turns", String(maxTurns)] : []),
207
+ ...(model !== undefined ? ["--model", model] : []),
208
+ ...(effort !== undefined ? ["--effort", effort] : []),
209
+ ],
210
+ stdin: briefPath !== undefined ? { file: briefPath } : null,
211
+ files: [],
212
+ // The credential's variable alone: on the subscription path an API key
213
+ // would outrank the token in Claude Code's auth order.
214
+ env: [
215
+ `${credential.env}=${credential.placeholder}`,
216
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1",
217
+ ],
218
+ },
219
+ // The checkout's executable harness config, and what Claude Code loads by
220
+ // itself. Declared for the Launcher; the Deep scan keeps the config from
221
+ // loading by the flags above, and removes nothing from the copy.
222
+ checkoutConfig: [".claude/settings.json", ".claude/settings.local.json", ".mcp.json"],
223
+ instructionFiles: ["CLAUDE.md", "CLAUDE.local.md"],
224
+ // Print mode says "Error: Reached max turns" on its error output.
225
+ stops: { turnCap: { stderrPattern: "^Error: Reached max turns" } },
226
+ // Where the Launcher keeps Claude Code's own output.
227
+ transcript: { path: `${kitDir ?? "/agent-kit"}/logs/agent.log` },
228
+ };
229
+ }
@@ -0,0 +1,120 @@
1
+ // What the kit knows about each built-in harness (ADRs 0028 and 0030), and the
2
+ // two preflight rules read from it.
3
+ //
4
+ // `cli/harnesses.json` is built here from the adapters and the Support Level
5
+ // table, written by `node scripts/gen_harnesses.mjs` and held equal to them by
6
+ // a contract test. It ships with every kit tag and npm package. Its shape can
7
+ // only grow: a field may be added, and is never renamed or removed, because an
8
+ // older CLI reads a newer tag's file and a newer CLI an older one.
9
+
10
+ import { readFileSync } from "node:fs";
11
+ import { FACTS as claudeCodeFacts } from "./claude-code.mjs";
12
+ import { SECURITY_STAGES, STAGES, SUPPORT_LEVELS, SUPPORT_TABLE } from "./support-levels.mjs";
13
+
14
+ export { SECURITY_STAGES, STAGES, SUPPORT_LEVELS };
15
+
16
+ /** Each built-in harness that has an adapter, and its facts. */
17
+ const ADAPTERS = { "claude-code": claudeCodeFacts };
18
+
19
+ const COMMENT =
20
+ "Generated by scripts/gen_harnesses.mjs from cli/src/harness/: do not edit. The shape is grow-only: a field may be added, and is never renamed or removed.";
21
+
22
+ /**
23
+ * @typedef {{ level: string | null, run: string | null }} Cell
24
+ * @typedef {{
25
+ * displayName: string,
26
+ * secrets: Array<{ name: string, whereToGet: string }>,
27
+ * effortValues: string[],
28
+ * noEffort: boolean,
29
+ * defaultModel: string,
30
+ * supportLevels: Record<string, Cell>,
31
+ * }} Harness
32
+ * @typedef {{ $comment: string, stages: string[], harnesses: Record<string, Harness> }} Harnesses
33
+ */
34
+
35
+ /**
36
+ * The content of `harnesses.json`, from the adapters and the table.
37
+ * @returns {Harnesses}
38
+ */
39
+ export function buildHarnesses() {
40
+ const harnesses = Object.entries(ADAPTERS).map(([name, facts]) => [
41
+ name,
42
+ {
43
+ displayName: facts.displayName,
44
+ secrets: facts.secrets,
45
+ effortValues: facts.effortValues,
46
+ noEffort: facts.effortValues.length === 0,
47
+ defaultModel: facts.defaultModel,
48
+ supportLevels: SUPPORT_TABLE[name],
49
+ },
50
+ ]);
51
+ return structuredClone({
52
+ $comment: COMMENT,
53
+ stages: STAGES,
54
+ harnesses: Object.fromEntries(harnesses),
55
+ });
56
+ }
57
+
58
+ /**
59
+ * The shipped `harnesses.json`: what preflight goes by.
60
+ * @returns {Harnesses}
61
+ */
62
+ export function readHarnesses() {
63
+ return JSON.parse(readFileSync(new URL("../../harnesses.json", import.meta.url), "utf8"));
64
+ }
65
+
66
+ /** `a, b or c`. */
67
+ const either = (words) =>
68
+ words.length > 1 ? `${words.slice(0, -1).join(", ")} or ${words.at(-1)}` : words.join("");
69
+
70
+ /**
71
+ * The effort a Stage runs with on `harness` (ADR 0027). Its own setting must
72
+ * be one the harness accepts; one `inherited` from `AGENT_KIT_EFFORT` that is
73
+ * not is dropped, so one global does not break a mixed setup. The refused
74
+ * value is never repeated.
75
+ * @param {Pick<Harness, "displayName" | "effortValues" | "noEffort">} harness
76
+ * @param {{ effort?: string, inherited?: boolean }} setting
77
+ * @returns {{ effort: string, log?: string } | { refused: string }}
78
+ */
79
+ export function effortFor(harness, { effort = "", inherited = false }) {
80
+ if (effort === "" || harness.effortValues.includes(effort)) return { effort };
81
+ const why = harness.noEffort
82
+ ? `${harness.displayName} has no effort setting`
83
+ : `${harness.displayName} accepts ${either(harness.effortValues)}`;
84
+ if (inherited) {
85
+ return { effort: "", log: `Effort: AGENT_KIT_EFFORT is dropped for this Stage: ${why}.` };
86
+ }
87
+ return { refused: `${why}, and this Stage's effort is none of that.` };
88
+ }
89
+
90
+ /**
91
+ * Whether `stage` may run on `harness` at its pair's Support Level (ADR 0028),
92
+ * and what the run summary says about it. A security Stage below `tried` runs
93
+ * only as a Proving run; any other Stage runs at `documented` with a warning;
94
+ * a pair with no level is refused.
95
+ * @param {Pick<Harness, "displayName" | "supportLevels">} harness
96
+ * @param {{ stage: string, provingRun?: boolean }} run
97
+ * @returns {{ level?: string, summary?: string, warning?: string, refused?: string }}
98
+ */
99
+ export function supportFor(harness, { stage, provingRun = false }) {
100
+ const pair = `${harness.displayName} on the ${stage} Stage`;
101
+ const level = harness.supportLevels[stage]?.level ?? null;
102
+ if (level === null || !SUPPORT_LEVELS.includes(level)) {
103
+ return {
104
+ refused: `${pair} has no Support Level: a Guard probe failed on it, so the pair is refused.`,
105
+ };
106
+ }
107
+ const below = level === "documented";
108
+ if (below && SECURITY_STAGES.includes(stage) && !provingRun) {
109
+ return {
110
+ refused: `${pair} is at Support Level documented, below tried, and a security Stage runs there only as a Proving run (--proving-run).`,
111
+ };
112
+ }
113
+ return {
114
+ level,
115
+ summary: `Support Level: ${level}; Proving run: ${provingRun ? "yes" : "no"}`,
116
+ ...(below
117
+ ? { warning: `${pair} is at Support Level documented: no run of it has been recorded.` }
118
+ : {}),
119
+ };
120
+ }