@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.
@@ -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,11 @@ 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";
50
+ import { imageDigestNote } from "./recipe.mjs";
48
51
  import { ENDS_HERE, must, StepFailed } from "./steps.mjs";
49
52
 
50
53
  const UNINITIALIZED = /global network policy has not been initialized/i;
@@ -125,10 +128,12 @@ export function sbxResources(registries) {
125
128
  }
126
129
 
127
130
  /**
128
- * @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.
129
133
  * @returns {import("./lifecycle.mjs").Driver}
130
134
  */
131
- export function sbxDriver({ id, call }) {
135
+ export function sbxDriver({ id, call, plan }) {
136
+ const { displayName } = plan.identity;
132
137
  const name = `agent-kit-deep-${id}`;
133
138
  /** The layered image, and the sbx template loaded from it. */
134
139
  const template = `${name}:sbx`;
@@ -176,19 +181,26 @@ export function sbxDriver({ id, call }) {
176
181
  container: name,
177
182
 
178
183
  async prepare(steps, { out }) {
184
+ const harness = pinnedHarnessImage(plan.installLayer);
179
185
  if (steps.dockerfile !== undefined) {
180
186
  throw new StepFailed([
181
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.`,
182
- "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.",
183
189
  ]);
184
190
  }
185
191
  const problem = globalPolicyProblem(await sbx(["policy", "ls", "--json"]));
186
192
  if (problem) throw new StepFailed(problem);
187
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;
188
196
  out(
189
- `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.`,
190
200
  );
191
- const pulled = await docker(["pull", steps.image]);
201
+ const note = own ? imageDigestNote(base) : null;
202
+ if (note) out(note);
203
+ const pulled = await docker(["pull", base]);
192
204
  if (pulled.status === null) {
193
205
  throw new StepFailed([
194
206
  "FAILED Docker Sandboxes' template is built with Docker on this machine, and docker could not run: " +
@@ -197,15 +209,14 @@ export function sbxDriver({ id, call }) {
197
209
  ENDS_HERE,
198
210
  ]);
199
211
  }
200
- must(pulled, `pulling ${steps.image}`, { showOutput: true });
212
+ must(pulled, `pulling ${base}`, { showOutput: true });
201
213
  imageBuilt = true;
202
- must(
203
- await docker(["build", "--label", `${LABEL}=${id}`, "--tag", template, "-"], {
204
- stdin: `${layerDockerfile(steps.image)}${TEMPLATE_LAYER}`,
205
- }),
206
- `layering Claude Code on ${steps.image}`,
207
- { showOutput: true },
208
- );
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 });
209
220
  // A private host file, by a name relative to its folder, so a Windows
210
221
  // drive letter is never read as anything else; gone once it is loaded.
211
222
  const tar = "template.tar";
@@ -242,8 +253,7 @@ export function sbxDriver({ id, call }) {
242
253
  "never",
243
254
  "-t",
244
255
  template,
245
- "-e",
246
- AUTO_UPDATER_OFF,
256
+ ...plan.installLayer.env.flatMap((v) => ["-e", v]),
247
257
  "shell",
248
258
  ]),
249
259
  "creating the sandbox",
@@ -273,7 +283,7 @@ export function sbxDriver({ id, call }) {
273
283
  );
274
284
  },
275
285
 
276
- /** Claude Code is in the template already: nothing to install. */
286
+ /** The harness is in the template already: nothing to install. */
277
287
  async installAgent() {},
278
288
 
279
289
  async openSetupEgress(registries) {
@@ -472,7 +482,7 @@ function idOf(r, repository, tag) {
472
482
  * image's package mirror from the host, which no recipe field names. An
473
483
  * existing uid 1000 account (`node`, in the Node.js images) is renamed to
474
484
  * `agent`, its home moved, rather than given a second name for one uid.
475
- * 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.
476
486
  */
477
487
  const TEMPLATE_LAYER = [
478
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
@@ -37,9 +39,17 @@ import {
37
39
  withoutCredentials,
38
40
  } from "./deep-scan/credential.mjs";
39
41
  import { DEFAULT_LIMITS, describeLimits, parseLimits, VERIFY_LIMITS } from "./deep-scan/limits.mjs";
42
+ import { publicHttpsFetch } from "./deep-scan/grounding-url.mjs";
40
43
  import { runLifecycle } from "./deep-scan/lifecycle.mjs";
41
44
  import { MODEL_ID } from "./deep-scan/model-proxy.mjs";
42
- 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";
43
53
  import { RUNTIMES_DOCS_URL, selectRuntime } from "./deep-scan/runtime.mjs";
44
54
  import {
45
55
  readFindingFile,
@@ -49,7 +59,14 @@ import {
49
59
  } from "./deep-scan/verify.mjs";
50
60
  import { CLI_VERSION } from "./tags.mjs";
51
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
+
52
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`;
53
70
 
54
71
  /**
55
72
  * @param {{
@@ -64,6 +81,7 @@ const CREDENTIALS_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CL
64
81
  * reportPath?: string,
65
82
  * verifyPath?: string,
66
83
  * ref?: string,
84
+ * provingRun?: boolean,
67
85
  * limitFlags?: Record<string, string | undefined>,
68
86
  * platform?: string,
69
87
  * env?: Record<string, string | undefined>,
@@ -77,8 +95,10 @@ const CREDENTIALS_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CL
77
95
  * }} opts `limitFlags` holds the limit flags' values, keyed by flag name.
78
96
  * `verifyPath` (a finding file) and `ref` go together, for a
79
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.
80
100
  * `platform`, `env`, `fetch`, `signals` and `timers` are the host's
81
- * (`process.platform`, `process.env`, the global fetch, `process`, the
101
+ * (`process.platform`, `process.env`, the public-HTTPS grounding fetch, `process`, the
82
102
  * real clock), and `reportDir` is a new private temporary folder, and
83
103
  * `modelApi` is the real model API; only tests pass others, and no flag
84
104
  * can change them.
@@ -98,10 +118,11 @@ export async function runDeepScan({
98
118
  reportPath,
99
119
  verifyPath,
100
120
  ref,
121
+ provingRun = false,
101
122
  limitFlags = {},
102
123
  platform = process.platform,
103
124
  env = process.env,
104
- fetch = globalThis.fetch,
125
+ fetch = publicHttpsFetch,
105
126
  signals = process,
106
127
  reportDir,
107
128
  modelApi,
@@ -162,7 +183,8 @@ export async function runDeepScan({
162
183
  );
163
184
  return 2;
164
185
  }
165
- 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 }))) {
166
188
  err(
167
189
  `--effort must be one of ${EFFORTS.slice(0, -1).join(", ")} or ${EFFORTS.at(-1)}, got: ${JSON.stringify(effort)}`,
168
190
  );
@@ -205,6 +227,15 @@ export async function runDeepScan({
205
227
  return 2;
206
228
  }
207
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
+
208
239
  // The finding file, read and checked on the host before anything runs.
209
240
  let given = null;
210
241
  if (verifying) {
@@ -330,7 +361,7 @@ export async function runDeepScan({
330
361
  [
331
362
  `${tokens.join(" and ")} ${tokens.length > 1 ? "are" : "is"} set in deep-scan's environment, and a GitHub token must never reach the sandbox.`,
332
363
  `Unset ${tokens.length > 1 ? "them" : "it"} for this run, for example:`,
333
- " 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" : ""}`,
334
365
  " In PowerShell: Remove-Item Env:GH_TOKEN, Env:GITHUB_TOKEN -ErrorAction SilentlyContinue, then run it again.",
335
366
  ],
336
367
  RUNTIMES_DOCS_URL,
@@ -453,12 +484,6 @@ export async function runDeepScan({
453
484
  });
454
485
  }
455
486
 
456
- /**
457
- * The effort levels Claude Code's --effort takes (2.1.328's --help), and the
458
- * static workflow's effort input: nothing else reaches the command line.
459
- */
460
- export const EFFORTS = Object.freeze(["low", "medium", "high", "xhigh", "max"]);
461
-
462
487
  /** Text with LF line ends, so a CRLF checkout of the same file compares equal. */
463
488
  const lf = (text) => text.replace(/\r\n?/g, "\n");
464
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
+ }
@@ -0,0 +1,58 @@
1
+ // The Launcher's side of a launch plan's install layer (ADR 0027, ADR 0029):
2
+ // the Harness image, by digest only, and the Dockerfile that puts the
3
+ // harness on another image, by copying `/opt/agent-kit` from it. Both Deep
4
+ // scan drivers build that with Docker: the Docker driver as its runtime's
5
+ // image, the Docker Sandboxes driver as the template it loads into sbx
6
+ // (#375). Nothing is installed from a registry at run time.
7
+
8
+ /** An image reference that ends in a sha256 digest, with nothing else on the line. */
9
+ const BY_DIGEST = /^[^\s@]+@sha256:[0-9a-f]{64}$/;
10
+
11
+ /** The two halves of the musl check's line: its command text never holds it whole. */
12
+ const MARKER = ["agent-kit", "musl-image"];
13
+
14
+ /** The line the musl check prints. */
15
+ export const MUSL_MARKER = MARKER.join("-");
16
+
17
+ /**
18
+ * The build step that fails on a musl image: the harness's CLI and Node are
19
+ * glibc builds. A glibc image answers `getconf GNU_LIBC_VERSION`, even one
20
+ * that also has the musl loader installed.
21
+ */
22
+ const MUSL_CHECK = `RUN if ! getconf GNU_LIBC_VERSION >/dev/null 2>&1 && ls /lib/ld-musl-* >/dev/null 2>&1; then printf '%s-%s\\n' ${MARKER.join(" ")} >&2; exit 1; fi`;
23
+
24
+ /**
25
+ * The plan's Harness image. Throws unless it is named by digest: a tag alone
26
+ * can come to mean another image.
27
+ * @param {import("./claude-code.mjs").LaunchPlan["installLayer"]} installLayer
28
+ * @returns {string}
29
+ */
30
+ export function pinnedHarnessImage({ image }) {
31
+ if (typeof image !== "string" || !BY_DIGEST.test(image)) {
32
+ throw new Error(
33
+ `the Harness image must be pinned by digest (name@sha256:<64 hex digits>), got: ${JSON.stringify(image)}`,
34
+ );
35
+ }
36
+ return image;
37
+ }
38
+
39
+ /**
40
+ * The Dockerfile that layers a plan's `installLayer` on `base`, which must be
41
+ * glibc Linux: the musl check, then `/opt/agent-kit` from the Harness image,
42
+ * its `bin` (the harness's CLI alone, never its Node) first on the path, so a
43
+ * CLI of the same name in the image never runs in the pinned one's place.
44
+ * @param {string} base
45
+ * @param {import("./claude-code.mjs").LaunchPlan["installLayer"]} installLayer
46
+ */
47
+ export function layerDockerfile(base, installLayer) {
48
+ const { env, run } = installLayer;
49
+ return [
50
+ `FROM ${base}`,
51
+ MUSL_CHECK,
52
+ `COPY --from=${pinnedHarnessImage(installLayer)} /opt/agent-kit /opt/agent-kit`,
53
+ 'ENV PATH="/opt/agent-kit/bin:${PATH}"',
54
+ ...env.map((v) => `ENV ${v}`),
55
+ `RUN ${run.join("\n")}`,
56
+ "",
57
+ ].join("\n");
58
+ }