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

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.
Files changed (180) hide show
  1. package/README.md +22 -4
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +244 -6
  4. package/package.json +3 -2
  5. package/src/checks/ci-workflow.mjs +105 -0
  6. package/src/checks/claude-app.mjs +11 -2
  7. package/src/checks/custom-harness.mjs +157 -0
  8. package/src/checks/github-app.mjs +214 -0
  9. package/src/checks/rulesets.mjs +9 -8
  10. package/src/checks/secrets-and-variables.mjs +27 -8
  11. package/src/checks/stages.mjs +705 -0
  12. package/src/cli.mjs +583 -36
  13. package/src/deep-scan/agent.mjs +88 -21
  14. package/src/deep-scan/credential.mjs +81 -32
  15. package/src/deep-scan/docker-driver.mjs +105 -42
  16. package/src/deep-scan/harness-text.mjs +99 -0
  17. package/src/deep-scan/lifecycle.mjs +68 -178
  18. package/src/deep-scan/limits.mjs +13 -7
  19. package/src/deep-scan/model-proxy.mjs +21 -10
  20. package/src/deep-scan/preflight.mjs +19 -6
  21. package/src/deep-scan/recipe.mjs +4 -0
  22. package/src/deep-scan/runtime.mjs +54 -6
  23. package/src/deep-scan/sandbox-run.mjs +232 -0
  24. package/src/deep-scan/sbx-driver.mjs +224 -39
  25. package/src/deep-scan/tar.mjs +69 -22
  26. package/src/deep-scan/verify.mjs +6 -1
  27. package/src/deep-scan.mjs +73 -13
  28. package/src/doctor.mjs +166 -5
  29. package/src/exec.mjs +14 -5
  30. package/src/factory/budget/budget.mjs +259 -0
  31. package/src/factory/build/command.mjs +321 -0
  32. package/src/factory/build/factory.mjs +473 -0
  33. package/src/factory/build/findings.mjs +55 -0
  34. package/src/factory/build/host.mjs +230 -0
  35. package/src/factory/build/notes.mjs +191 -0
  36. package/src/factory/build/pull-request.mjs +74 -0
  37. package/src/factory/bundle.mjs +146 -0
  38. package/src/factory/checks/allowed-paths.mjs +50 -0
  39. package/src/factory/checks/plan-header.mjs +296 -0
  40. package/src/factory/checks/qa.mjs +85 -0
  41. package/src/factory/checks/review.mjs +73 -0
  42. package/src/factory/checks/security.mjs +50 -0
  43. package/src/factory/checks/stage-check.mjs +89 -0
  44. package/src/factory/claims/command.mjs +187 -0
  45. package/src/factory/claims/release.mjs +111 -0
  46. package/src/factory/decision/answers.mjs +103 -0
  47. package/src/factory/decision/command.mjs +64 -0
  48. package/src/factory/decision/plan.mjs +99 -0
  49. package/src/factory/decision/request.mjs +116 -0
  50. package/src/factory/doctor/files.mjs +329 -0
  51. package/src/factory/doctor/index.mjs +56 -0
  52. package/src/factory/doctor/local.mjs +497 -0
  53. package/src/factory/doctor/orchestrate.mjs +146 -0
  54. package/src/factory/engine/lease.mjs +146 -0
  55. package/src/factory/engine/local-engine.mjs +177 -0
  56. package/src/factory/engine/lockfile.mjs +64 -0
  57. package/src/factory/engine/workflow-engine.mjs +124 -0
  58. package/src/factory/gate/comment.mjs +88 -0
  59. package/src/factory/gate/config.mjs +57 -0
  60. package/src/factory/gate/gate-core.mjs +250 -0
  61. package/src/factory/gate/guarded.mjs +17 -0
  62. package/src/factory/gate/reads.mjs +105 -0
  63. package/src/factory/gate/task.mjs +193 -0
  64. package/src/factory/gate/trip-reads.mjs +82 -0
  65. package/src/factory/gate/trip.mjs +87 -0
  66. package/src/factory/init/blueprint.mjs +174 -0
  67. package/src/factory/init/index.mjs +337 -0
  68. package/src/factory/labels/evidence.mjs +162 -0
  69. package/src/factory/labels/moves.mjs +32 -0
  70. package/src/factory/labels/reconcile.mjs +267 -0
  71. package/src/factory/labels/revert.mjs +87 -0
  72. package/src/factory/labels/timeline.mjs +72 -0
  73. package/src/factory/labels/voided.mjs +59 -0
  74. package/src/factory/limits/harness.mjs +39 -0
  75. package/src/factory/limits/limits.mjs +123 -0
  76. package/src/factory/merge/command.mjs +172 -0
  77. package/src/factory/outbox/check.mjs +240 -0
  78. package/src/factory/outbox/rulings.mjs +195 -0
  79. package/src/factory/plan/command.mjs +66 -0
  80. package/src/factory/plan/comment.mjs +156 -0
  81. package/src/factory/plan/publish.mjs +149 -0
  82. package/src/factory/plan/risk.mjs +153 -0
  83. package/src/factory/qa/command.mjs +163 -0
  84. package/src/factory/records/engine-record.mjs +133 -0
  85. package/src/factory/records/main.mjs +96 -0
  86. package/src/factory/records/record.mjs +226 -0
  87. package/src/factory/records/sink.mjs +57 -0
  88. package/src/factory/report/build.mjs +92 -0
  89. package/src/factory/report/command.mjs +80 -0
  90. package/src/factory/report/facts.mjs +226 -0
  91. package/src/factory/report/gate-section.mjs +122 -0
  92. package/src/factory/report/metrics.mjs +111 -0
  93. package/src/factory/report/reads.mjs +246 -0
  94. package/src/factory/report/render.mjs +121 -0
  95. package/src/factory/report/rollout.mjs +154 -0
  96. package/src/factory/review/command.mjs +182 -0
  97. package/src/factory/run/awake.mjs +70 -0
  98. package/src/factory/run/collect.mjs +77 -0
  99. package/src/factory/run/command.mjs +490 -0
  100. package/src/factory/run/gh.mjs +46 -0
  101. package/src/factory/run/launch.mjs +47 -0
  102. package/src/factory/run/pipelines.mjs +261 -0
  103. package/src/factory/run/raw.mjs +96 -0
  104. package/src/factory/run/restart.mjs +83 -0
  105. package/src/factory/run/s3.mjs +193 -0
  106. package/src/factory/run/secrets.mjs +142 -0
  107. package/src/factory/run/teardown.mjs +242 -0
  108. package/src/factory/run/token.mjs +68 -0
  109. package/src/factory/security/command.mjs +157 -0
  110. package/src/factory/setup/app.mjs +122 -0
  111. package/src/factory/setup/command.mjs +409 -0
  112. package/src/factory/setup/labels.mjs +25 -0
  113. package/src/factory/setup/reads.mjs +129 -0
  114. package/src/factory/setup/writes.mjs +126 -0
  115. package/src/factory/snapshot/write.mjs +176 -0
  116. package/src/factory/stop/command.mjs +136 -0
  117. package/src/factory/sweep/actions-main.mjs +117 -0
  118. package/src/factory/sweep/command.mjs +65 -0
  119. package/src/factory/sweep/knobs.mjs +78 -0
  120. package/src/factory/sweep/marker-version.mjs +15 -0
  121. package/src/factory/sweep/markers.mjs +112 -0
  122. package/src/factory/sweep/overlap.mjs +24 -0
  123. package/src/factory/sweep/run.mjs +198 -0
  124. package/src/factory/sweep/shell.mjs +394 -0
  125. package/src/factory/sweep/split.mjs +104 -0
  126. package/src/factory/sweep/states.mjs +87 -0
  127. package/src/factory/sweep/sweep-core.mjs +1781 -0
  128. package/src/factory/tracker/github.mjs +674 -0
  129. package/src/factory/tracker/operations.mjs +153 -0
  130. package/src/factory/upgrade/index.mjs +83 -0
  131. package/src/harness/adapters.mjs +30 -0
  132. package/src/harness/antigravity.mjs +187 -0
  133. package/src/harness/claude-code.mjs +8 -1
  134. package/src/harness/codex.mjs +219 -0
  135. package/src/harness/cursor.mjs +199 -0
  136. package/src/harness/custom/registry.mjs +21 -0
  137. package/src/harness/custom/schema.mjs +90 -0
  138. package/src/harness/custom.mjs +299 -0
  139. package/src/harness/facts.mjs +44 -7
  140. package/src/harness/gemini.mjs +164 -0
  141. package/src/harness/install-layer.mjs +86 -3
  142. package/src/harness/opencode.mjs +289 -0
  143. package/src/harness/resolve.mjs +156 -0
  144. package/src/harness/support-levels.mjs +151 -3
  145. package/src/harness-live/assess.mjs +29 -6
  146. package/src/harness-live/cursor-real.mjs +146 -0
  147. package/src/harness-live/cursor-version.mjs +70 -0
  148. package/src/harness-live/cursor.mjs +80 -0
  149. package/src/harness-live/custom.mjs +91 -0
  150. package/src/harness-live/fixture-harness.mjs +45 -0
  151. package/src/harness-live/harnesses.mjs +263 -0
  152. package/src/harness-live/host.mjs +113 -4
  153. package/src/harness-live/opencode.mjs +289 -0
  154. package/src/harness-live/probes.mjs +87 -7
  155. package/src/harness-live/run.mjs +101 -20
  156. package/src/harness-live/setup.mjs +126 -0
  157. package/src/harness-live/stage.mjs +25 -15
  158. package/src/harness-live/suite.mjs +276 -95
  159. package/src/harness-test.mjs +116 -0
  160. package/src/init.mjs +374 -36
  161. package/src/kit-owned-paths.mjs +1 -1
  162. package/src/model-proxy/core.mjs +128 -20
  163. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  164. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  165. package/src/model-proxy/profiles/openai.mjs +327 -0
  166. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  167. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  168. package/src/model-proxy/stub.mjs +9 -1
  169. package/src/stage/audit.mjs +79 -0
  170. package/src/stage/egress-route.mjs +207 -0
  171. package/src/stage/implement/carry.mjs +308 -0
  172. package/src/stage/implement/sandbox.mjs +271 -0
  173. package/src/stage/implement/verify.mjs +70 -0
  174. package/src/stage/implement.mjs +218 -0
  175. package/src/stage/plan.mjs +115 -0
  176. package/src/stage/review-response.mjs +172 -0
  177. package/src/stage/review.mjs +185 -0
  178. package/src/stage/workspace.mjs +274 -0
  179. package/src/stage.mjs +1087 -0
  180. package/src/upgrade.mjs +39 -7
@@ -6,13 +6,14 @@
6
6
  // report-format.md, which it builds on), the Threat pack and the Scan recipe,
7
7
  // all read at the trusted ref, and the sandbox's paths. How the harness is
8
8
  // started, what it holds and how it says it hit its turn limit come from its
9
- // Harness adapter's launch plan (../harness/claude-code.mjs, ADR 0027); this
10
- // module runs that plan.
9
+ // Harness adapter's launch plan (../harness/, ADR 0027); this module runs
10
+ // that plan.
11
11
 
12
12
  import { firstLine } from "../exec.mjs";
13
- import { claudeCode } from "../harness/claude-code.mjs";
13
+ import { adapterFor, DEFAULT_HARNESS } from "../harness/adapters.mjs";
14
14
  import { checkSafePath, UnsafePathError } from "../safe-paths.mjs";
15
15
  import { isMapping, parseYamlSubset, stripBom } from "../yaml-subset.mjs";
16
+ import { textFor } from "./harness-text.mjs";
16
17
 
17
18
  /** Where a Consumer's security-audit skill lives, as Agent-kit installs it. */
18
19
  export const SKILL_DIR = ".claude/skills/security-audit";
@@ -33,20 +34,31 @@ export const BRIEF_PATH = "/agent-kit/in/brief.md";
33
34
 
34
35
  /** The launcher's own folder in the sandbox, outside /workspace. */
35
36
  const KIT_DIR = "/agent-kit";
36
- const LOGS_DIR = `${KIT_DIR}/logs`;
37
+
38
+ /** Folders of the launcher's that a plan's config file may not sit in: each is emptied first. */
39
+ const OWN_FOLDERS = Object.freeze(["grounding", "in", "logs", "out"]);
37
40
 
38
41
  /**
39
42
  * The harness's launch plan for a Deep scan. Without a `baseUrl` (before the
40
43
  * model route is open) its launch is not yet one to run; its identity and
41
44
  * install layer are.
42
- * @param {{ baseUrl?: string, maxTurns?: number, model?: string, effort?: string, kind?: "api-key" | "subscription", callerKey?: string }} [opts]
45
+ * @param {{ harness?: string, baseUrl?: string, maxTurns?: number, model?: string, effort?: string, kind?: "api-key" | "subscription", callerKey?: string }} [opts]
46
+ * `harness` is one the kit has an adapter for (default Claude Code).
43
47
  * `model` is a plain model id and `effort` an effort level, both checked by
44
48
  * the launcher. `kind` is the credential's (default an API key).
45
49
  * `callerKey` is the run's (callerKeyFor): the agent holds it in place of
46
50
  * the credential.
47
51
  */
48
- export function agentPlan({ baseUrl, maxTurns, model, effort, kind, callerKey } = {}) {
49
- return claudeCode({
52
+ export function agentPlan({
53
+ harness = DEFAULT_HARNESS,
54
+ baseUrl,
55
+ maxTurns,
56
+ model,
57
+ effort,
58
+ kind,
59
+ callerKey,
60
+ } = {}) {
61
+ return adapterFor(harness)({
50
62
  stage: "deep-scan",
51
63
  proxyUrl: baseUrl,
52
64
  briefPath: BRIEF_PATH,
@@ -69,6 +81,15 @@ export function agentPlan({ baseUrl, maxTurns, model, effort, kind, callerKey }
69
81
  export const turnsMarker = (plan) =>
70
82
  `agent-kit-deep-scan: ${plan.identity.displayName} reached its turn limit`;
71
83
 
84
+ /**
85
+ * What the agent step's script prints when the harness said it has no
86
+ * credential it reads (Antigravity CLI asks for a sign-in): a fixed line, as
87
+ * `turnsMarker`'s, printed on the plan's marker in the harness's error output.
88
+ * @param {import("../harness/claude-code.mjs").LaunchPlan} plan
89
+ */
90
+ export const credentialMarker = (plan) =>
91
+ `agent-kit-deep-scan: ${plan.identity.displayName} found no model credential`;
92
+
72
93
  /** The Claude Code plan's line. */
73
94
  export const TURNS_MARKER = turnsMarker(agentPlan());
74
95
 
@@ -228,10 +249,12 @@ function plainPath(value) {
228
249
  * grounding: Array<{ source: string, at: string }>,
229
250
  * paths: { workspace: string, grounding: string, report: string },
230
251
  * discovers?: boolean,
252
+ * harness?: string,
231
253
  * }} opts `discovers`: Claude Code runs without `--bare` (the
232
254
  * subscription path), so the brief says what it discovers.
233
255
  */
234
256
  export function agentBrief({
257
+ harness = DEFAULT_HARNESS,
235
258
  branch,
236
259
  short,
237
260
  recipePath,
@@ -244,13 +267,14 @@ export function agentBrief({
244
267
  return [
245
268
  "# Deep scan brief, from the agent-kit deep-scan launcher",
246
269
  "",
247
- "This is the launcher's brief. You are running inside the closed, disposable sandbox that `agent-kit deep-scan` started for a Deep scan: run the security-audit skill in `deep` mode, by the procedure below. Your only network route is the launcher's model proxy, and the web tools (WebFetch, WebSearch) are off.",
270
+ `This is the launcher's brief. You are running inside the closed, disposable sandbox that \`agent-kit deep-scan\` started for a Deep scan: run the security-audit skill in \`deep\` mode, by the procedure below. Your only network route is the launcher's model proxy, and ${textFor(harness).webOff}.`,
248
271
  "",
249
272
  "## Where things are",
250
273
  "",
251
274
  `- The repository: \`${paths.workspace}\`, an export of \`${branch}\` at ${short} (the trusted ref). Scan the whole repository.`,
252
275
  ...groundingLines(grounding, paths),
253
276
  `- The report: write it to \`${paths.report}\`, early, and update it as each finding lands. It is the only file that leaves the sandbox.`,
277
+ ...removedLines(harness, paths),
254
278
  SETUP_DONE,
255
279
  ...(discovers ? [DISCOVERED] : []),
256
280
  "",
@@ -272,6 +296,22 @@ export function agentBrief({
272
296
  ].join("\n");
273
297
  }
274
298
 
299
+ /**
300
+ * A brief's line on what the launcher removes from the copy before the
301
+ * harness starts, where its launch plan says it does.
302
+ * @param {string} harness
303
+ * @param {{ workspace: string }} paths
304
+ * @returns {string[]}
305
+ */
306
+ export function removedLines(harness, paths) {
307
+ const { launch, checkoutConfig } = adapterFor(harness)();
308
+ if (!launch.removeCheckoutConfig) return [];
309
+ const removed = checkoutConfig.map((path) => `\`${path}\``).join(", ");
310
+ return [
311
+ `- The harness's own config was removed from \`${paths.workspace}\` before you started (${removed}), so none of it could configure you: it is not part of this scan, and its absence is no finding.`,
312
+ ];
313
+ }
314
+
275
315
  /** A brief's line on the setup phase, which the launcher already ran. */
276
316
  export const SETUP_DONE =
277
317
  "- The launcher already ran the Scan recipe's `setup`, `start`, `ready` and `seed`: the services it starts are running. Do not run them again.";
@@ -324,23 +364,36 @@ export function threatPackAndRecipe({ handIn, recipePath, recipeText }) {
324
364
  }
325
365
 
326
366
  /**
327
- * The agent step's script, run with `sh -c` in the sandbox: the plan's
328
- * command, its stdin the plan's file, its own output kept in the plan's
329
- * transcript (its error output is passed on too), and `turnsMarker` when the
330
- * plan's turn-cap marker is in that error output. The plan's environment is
367
+ * The agent step's script, run with `sh -c` in the sandbox. It first removes
368
+ * the checkout's harness config from the workspace, where the plan's launch
369
+ * says so, and writes the plan's config files, each one's folder under the
370
+ * launcher's emptied first, so nothing a setup step left there is read. Then
371
+ * the plan's command, its stdin the plan's file, its own output kept in the
372
+ * plan's transcript (its error output is passed on too), `turnsMarker` when the
373
+ * plan's turn-cap marker is in that error output, and `credentialMarker` when
374
+ * its missing-credential marker is. The plan's environment is
331
375
  * the caller's to set.
332
- * @param {{ report: string, workspace: string, plan?: import("../harness/claude-code.mjs").LaunchPlan } & Parameters<typeof agentPlan>[0]} opts
333
- * Without a `plan`, the rest are `agentPlan`'s, which makes one.
376
+ * @param {{ report: string, workspace: string, kitDir?: string, plan?: import("../harness/claude-code.mjs").LaunchPlan } & Parameters<typeof agentPlan>[0]} opts
377
+ * Without a `plan`, the rest are `agentPlan`'s, which makes one. `kitDir`
378
+ * is the launcher's folder; only tests pass another.
334
379
  */
335
- export function agentScript({ report, workspace, plan, ...request }) {
380
+ export function agentScript({ report, workspace, kitDir = KIT_DIR, plan, ...request }) {
336
381
  const launched = plan ?? agentPlan(request);
337
- const { launch, stops, transcript } = launched;
338
- if (launch.files.length) {
339
- // No adapter has one yet: refused, rather than launched without them.
340
- throw new Error("the launcher does not write a launch plan's config files yet");
341
- }
342
- const logs = LOGS_DIR;
382
+ const { launch, stops, transcript, checkoutConfig } = launched;
383
+ const logs = `${kitDir}/logs`;
343
384
  const folderOf = (path) => path.slice(0, path.lastIndexOf("/"));
385
+ const owned = new Map();
386
+ for (const { path } of launch.files) {
387
+ // Only under a folder of its own, right under the launcher's, since the
388
+ // script empties that folder.
389
+ const parts = path.startsWith(`${kitDir}/`) ? path.slice(kitDir.length + 1).split("/") : [];
390
+ const plain = parts.length > 1 && parts.every((part) => part && !/^\.{1,2}$/.test(part));
391
+ if (!plain || OWN_FOLDERS.includes(parts[0])) {
392
+ throw new Error(`a launch plan's config file must sit in a folder of its own: ${path}`);
393
+ }
394
+ const own = `${kitDir}/${parts[0]}`;
395
+ owned.set(own, (owned.get(own) ?? new Set()).add(folderOf(path)));
396
+ }
344
397
  const folders = [...new Set([folderOf(report), logs, folderOf(transcript.path)])];
345
398
  const stdin = launch.stdin ? ` < ${shQuote(launch.stdin.file)}` : "";
346
399
  // The harness's error output reaches the launcher through a pipe, as it
@@ -351,6 +404,15 @@ export function agentScript({ report, workspace, plan, ...request }) {
351
404
  "set -eu",
352
405
  `mkdir -p ${folders.join(" ")}`,
353
406
  `cd ${workspace}`,
407
+ ...(launch.removeCheckoutConfig
408
+ ? [`rm -rf -- ${checkoutConfig.map((path) => shQuote(`./${path}`)).join(" ")}`]
409
+ : []),
410
+ // Each on a line of its own, so a failure of either ends the script.
411
+ ...[...owned].flatMap(([own, parents]) => [
412
+ `rm -rf -- ${shQuote(own)}`,
413
+ ...[...parents].map((folder) => `mkdir -p ${shQuote(folder)}`),
414
+ ]),
415
+ ...launch.files.map(({ path, text }) => `printf '%s' ${shQuote(text)} > ${shQuote(path)}`),
354
416
  `rm -f ${logs}/agent.status`,
355
417
  `{ ${launch.argv.map(shQuote).join(" ")}${stdin} 2>&1 > ${shQuote(transcript.path)} || echo "$?" > ${logs}/agent.status; } | tee ${logs}/agent.err >&2`,
356
418
  "status=0",
@@ -361,6 +423,11 @@ export function agentScript({ report, workspace, plan, ...request }) {
361
423
  `if grep -q ${shQuote(stops.turnCap.stderrPattern)} ${logs}/agent.err; then echo ${shQuote(turnsMarker(launched))}; fi`,
362
424
  ]
363
425
  : []),
426
+ ...(stops.credentialMissing
427
+ ? [
428
+ `if grep -qiE ${shQuote(stops.credentialMissing.stderrPattern)} ${logs}/agent.err; then echo ${shQuote(credentialMarker(launched))}; fi`,
429
+ ]
430
+ : []),
364
431
  'exit "$status"',
365
432
  ].join("\n");
366
433
  }
@@ -1,25 +1,33 @@
1
1
  // The Deep scan's model credential (#370): where it is read from, and the
2
- // checks it passes before anything starts. It is an Anthropic API key (the
3
- // default, `--credential api-key`) or, opted into with `--credential
4
- // subscription` (#375), a Claude subscription token from `claude
5
- // setup-token`. It is read from an environment variable (ANTHROPIC_API_KEY,
6
- // or CLAUDE_CODE_OAUTH_TOKEN for a subscription token, by default; `op run`
7
- // can fill either) or from 1Password with `op read`, never from the command
8
- // line, where other processes could see it. Once read, it lives only in the
2
+ // checks it passes before anything starts. It is the harness's API key (the
3
+ // default, `--credential api-key`: an Anthropic one on Claude Code, an OpenAI
4
+ // one on Codex CLI) or, on Claude Code alone and opted into with
5
+ // `--credential subscription` (#375), a Claude subscription token from
6
+ // `claude setup-token`. It is read from an environment variable (the one the
7
+ // harness's launch plan names, ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN or
8
+ // OPENAI_API_KEY, by default; `op run` can fill any) or from 1Password with
9
+ // `op read`, never from the command line, where other processes could see it. Once read, it lives only in the
9
10
  // launcher's memory, for the model proxy: every command the launcher runs
10
11
  // gets an environment with the model credential variables removed, and the
11
12
  // sandbox gets only a placeholder.
12
13
 
13
14
  import { randomBytes } from "node:crypto";
14
15
  import { firstLine } from "../exec.mjs";
15
- import { claudeCode } from "../harness/claude-code.mjs";
16
+ import { ADAPTERS, adapterFor, DEFAULT_HARNESS } from "../harness/adapters.mjs";
17
+ import { textFor } from "./harness-text.mjs";
16
18
  import { GITHUB_TOKEN_VARS } from "./preflight.mjs";
17
19
 
18
20
  /**
19
- * The credentials the harness accepts, from its launch plan: each kind's
21
+ * The credentials `harness` accepts, from its launch plan: each kind's
20
22
  * variable is also the one it is read from by default.
23
+ * @param {string} [harness]
24
+ * @param {string} [model] on opencode, whose model picks the provider
21
25
  */
22
- const { accepted, scrub } = claudeCode().credentials;
26
+ export const acceptedBy = (harness = DEFAULT_HARNESS, model) =>
27
+ adapterFor(harness)({ model }).credentials.accepted;
28
+
29
+ /** The Claude Code credentials, which the subscription path's checks name. */
30
+ const accepted = acceptedBy();
23
31
 
24
32
  /**
25
33
  * The start of the key the sandboxed agent holds in place of a real one;
@@ -35,15 +43,16 @@ export const PLACEHOLDER_OAUTH_TOKEN = accepted.subscription.placeholder;
35
43
 
36
44
  /**
37
45
  * The run's caller key: a placeholder with 24 random bytes added, made once
38
- * per run. The sandboxed Claude Code holds it in place of a credential, and
39
- * the model proxy forwards only a request that carries it, so a process in
40
- * the sandbox that never read Claude Code's environment cannot spend the
41
- * real credential. It is worth nothing outside the run's proxy.
46
+ * per run. The sandboxed harness holds it in place of a credential, and the
47
+ * model proxy forwards only a request that carries it, so a process in the
48
+ * sandbox that never read the harness's environment cannot spend the real
49
+ * credential. It is worth nothing outside the run's proxy.
42
50
  * @param {"api-key" | "subscription"} kind
51
+ * @param {string} [harness]
52
+ * @param {string} [model]
43
53
  */
44
- export function callerKeyFor(kind) {
45
- const start = kind === SUBSCRIPTION ? PLACEHOLDER_OAUTH_TOKEN : PLACEHOLDER_API_KEY;
46
- return `${start}-${randomBytes(24).toString("hex")}`;
54
+ export function callerKeyFor(kind, harness, model) {
55
+ return `${acceptedBy(harness, model)[kind].placeholder}-${randomBytes(24).toString("hex")}`;
47
56
  }
48
57
 
49
58
  /** The kinds `--credential` takes: an API key (the default) or the opt-in. */
@@ -51,11 +60,18 @@ export const API_KEY = "api-key";
51
60
  export const SUBSCRIPTION = "subscription";
52
61
  const CREDENTIAL_KINDS = Object.freeze([API_KEY, SUBSCRIPTION]);
53
62
 
54
- /** Model credential variables, removed from every command the launcher runs. */
55
- export const CREDENTIAL_VARS = Object.freeze(scrub);
63
+ /**
64
+ * Model credential variables, of every harness, removed from every command the
65
+ * launcher runs.
66
+ */
67
+ export const CREDENTIAL_VARS = Object.freeze([
68
+ ...new Set(Object.values(ADAPTERS).flatMap((adapter) => adapter().credentials.scrub)),
69
+ ]);
56
70
 
57
71
  /** How a Claude subscription (OAuth) token starts; an API key starts sk-ant-api. */
58
72
  const OAUTH_TOKEN_PREFIX = "sk-ant-oat";
73
+ /** How every Anthropic credential starts: no other provider's key does. */
74
+ const ANTHROPIC_PREFIX = "sk-ant-";
59
75
 
60
76
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
61
77
  const OP_REF = /^op:\/\/[^/\s][^\r\n]*$/;
@@ -82,11 +98,13 @@ export function credentialKind(value) {
82
98
  * key itself.
83
99
  * @param {string | undefined} value
84
100
  * @param {"api-key" | "subscription"} [kind]
101
+ * @param {string} [harness]
102
+ * @param {string} [model]
85
103
  * @returns {{ kind: "env", name: string } | { kind: "op", ref: string } | { error: string }}
86
104
  */
87
- export function credentialSource(value, kind = API_KEY) {
105
+ export function credentialSource(value, kind = API_KEY, harness = DEFAULT_HARNESS, model) {
88
106
  if (value === undefined) {
89
- return { kind: "env", name: accepted[kind].env };
107
+ return { kind: "env", name: acceptedBy(harness, model)[kind].env };
90
108
  }
91
109
  if (value.startsWith("env:")) {
92
110
  const name = value.slice(4);
@@ -110,10 +128,22 @@ export function credentialSource(value, kind = API_KEY) {
110
128
  * env: Record<string, string | undefined>,
111
129
  * runner: import("../exec.mjs").Runner,
112
130
  * kind?: "api-key" | "subscription",
113
- * }} opts
131
+ * harness?: string,
132
+ * model?: string,
133
+ * command?: string,
134
+ * }} opts `command` is the one the refusals name (default `deep-scan`).
114
135
  * @returns {{ credential: string, from: string } | { refused: string[] }}
115
136
  */
116
- export function readCredential({ source, env, runner, kind = API_KEY }) {
137
+ export function readCredential({
138
+ source,
139
+ env,
140
+ runner,
141
+ kind = API_KEY,
142
+ harness = DEFAULT_HARNESS,
143
+ model,
144
+ command: commandName = "deep-scan",
145
+ }) {
146
+ const claude = harness === DEFAULT_HARNESS;
117
147
  const token = kind === SUBSCRIPTION;
118
148
  if (source.kind === "op") {
119
149
  const r = runner("op", ["read", "--no-newline", source.ref]);
@@ -121,7 +151,7 @@ export function readCredential({ source, env, runner, kind = API_KEY }) {
121
151
  return {
122
152
  refused: [
123
153
  `Could not read the model credential with op read: ${firstLine(r.stderr) || `exit ${r.status}`}`,
124
- "Sign in to the 1Password CLI (op signin, or unlock the desktop app's integration) and check the reference, then run deep-scan again.",
154
+ `Sign in to the 1Password CLI (op signin, or unlock the desktop app's integration) and check the reference, then run ${commandName} again.`,
125
155
  ],
126
156
  };
127
157
  }
@@ -130,11 +160,17 @@ export function readCredential({ source, env, runner, kind = API_KEY }) {
130
160
  "the op read result",
131
161
  "1Password (op read)",
132
162
  kind,
163
+ harness,
164
+ model,
133
165
  );
134
166
  }
135
167
  const { name } = source;
136
- if (!token && name.toUpperCase() === accepted[SUBSCRIPTION].env) return notAnApiKey(name);
137
- const command = `npx @mnaimfaizy/agent-kit deep-scan${token ? " --credential subscription" : ""}`;
168
+ if (claude && !token && name.toUpperCase() === accepted[SUBSCRIPTION].env) {
169
+ return notAnApiKey(name);
170
+ }
171
+ // On opencode the model picks the key, so the command names it too.
172
+ const named = harness === "opencode" && model !== undefined ? ` --model ${model}` : "";
173
+ const command = `npx @mnaimfaizy/agent-kit ${commandName}${claude ? "" : ` --harness ${harness}${named}`}${token ? " --credential subscription" : ""}`;
138
174
  const value = valueOf(env, name);
139
175
  if (!value) {
140
176
  return {
@@ -144,7 +180,7 @@ export function readCredential({ source, env, runner, kind = API_KEY }) {
144
180
  `Make one with claude setup-token, keep it in 1Password, and read it from there: --credential-from op://<vault>/<item>/<field>, or op run -- ${command} with ${name} set to an op:// reference.`,
145
181
  ]
146
182
  : [
147
- `No model credential: ${name} is not set. deep-scan needs an Anthropic API key, which stays outside the sandbox, in its model proxy.`,
183
+ `No model credential: ${name} is not set. ${textFor(harness, model).needsKey}, which stays outside the sandbox, in its model proxy.`,
148
184
  `Set ${name} for this run, or read it from 1Password: --credential-from op://<vault>/<item>/<field>, or op run -- ${command} with ${name} set to an op:// reference.`,
149
185
  ],
150
186
  };
@@ -152,13 +188,13 @@ export function readCredential({ source, env, runner, kind = API_KEY }) {
152
188
  if (value.startsWith("op://")) {
153
189
  return {
154
190
  refused: [
155
- `${name} holds a 1Password reference, not a ${token ? "token" : "key"}: run deep-scan under op run, which resolves it, for example:`,
191
+ `${name} holds a 1Password reference, not a ${token ? "token" : "key"}: run ${commandName} under op run, which resolves it, for example:`,
156
192
  ` op run -- ${command}`,
157
193
  "or pass the reference with --credential-from instead.",
158
194
  ],
159
195
  };
160
196
  }
161
- return checked(value, name, name, kind);
197
+ return checked(value, name, name, kind, harness, model);
162
198
  }
163
199
 
164
200
  /** The variable's value, by name in any letter case (as Windows matches it). */
@@ -168,7 +204,7 @@ function valueOf(env, name) {
168
204
  return key === undefined ? undefined : env[key];
169
205
  }
170
206
 
171
- function checked(value, what, from, kind) {
207
+ function checked(value, what, from, kind, harness, model) {
172
208
  if (!value) return { refused: [`No model credential: ${what} is empty.`] };
173
209
  // The credential goes into an HTTP header: printable ASCII with no space only.
174
210
  if (!/^[\x21-\x7e]+$/.test(value)) {
@@ -179,6 +215,19 @@ function checked(value, what, from, kind) {
179
215
  };
180
216
  }
181
217
  const isToken = value.startsWith(OAUTH_TOKEN_PREFIX);
218
+ if (harness !== DEFAULT_HARNESS) {
219
+ // Another harness on an Anthropic model takes an Anthropic API key alone.
220
+ const anthropic = adapterFor(harness)({ model }).modelRoute.profile === "anthropic";
221
+ if (anthropic ? !isToken : !value.startsWith(ANTHROPIC_PREFIX)) {
222
+ return { credential: value, from };
223
+ }
224
+ const held = anthropic ? "a Claude subscription token" : "an Anthropic credential";
225
+ return {
226
+ refused: [
227
+ `${what} holds ${held} (its value is not shown). ${textFor(harness, model).needsKey}.`,
228
+ ],
229
+ };
230
+ }
182
231
  if (kind !== SUBSCRIPTION && isToken) return notAnApiKey(what);
183
232
  if (kind === SUBSCRIPTION && !isToken) {
184
233
  return {
@@ -222,8 +271,8 @@ export function withoutCredentials(runner, envs, extra = []) {
222
271
  }
223
272
  const scrub = Object.fromEntries([...names].map((n) => [n, undefined]));
224
273
  const wrapped = (cmd, args, opts = {}) =>
225
- runner(cmd, args, { ...opts, env: { ...opts.env, ...scrub } });
274
+ runner(cmd, args, { ...opts, env: { ...scrub, ...opts.env } });
226
275
  wrapped.start = (cmd, args, opts = {}) =>
227
- runner.start(cmd, args, { ...opts, env: { ...opts.env, ...scrub } });
276
+ runner.start(cmd, args, { ...opts, env: { ...scrub, ...opts.env } });
228
277
  return wrapped;
229
278
  }
@@ -32,6 +32,7 @@
32
32
  // scan's only route to the internet.
33
33
 
34
34
  import { isIPv4 } from "node:net";
35
+ import { firstLine } from "../exec.mjs";
35
36
  import { layerDockerfile, pinnedHarnessImage } from "../harness/install-layer.mjs";
36
37
  import { startEgressProxy } from "./egress.mjs";
37
38
  import { refuseMusl } from "./preflight.mjs";
@@ -51,7 +52,7 @@ export const LABEL = "agent-kit.deep-scan";
51
52
 
52
53
  /**
53
54
  * @typedef {import("../exec.mjs").StartResult} StartResult
54
- * @typedef {(cmd: string, args: string[], opts?: { stdin?: Buffer | string, cwd?: string, maxOutput?: number }) => Promise<StartResult>} Call
55
+ * @typedef {(cmd: string, args: string[], opts?: { stdin?: Buffer | string, cwd?: string, maxOutput?: number, env?: Record<string, string> }) => Promise<StartResult>} Call
55
56
  * Runs a command without blocking; throws Interrupted when the run is.
56
57
  */
57
58
 
@@ -61,6 +62,28 @@ export const ISOLATED_OPTIONS = Object.freeze([
61
62
  "com.docker.network.bridge.gateway_mode_ipv6=isolated",
62
63
  ]);
63
64
 
65
+ /**
66
+ * Split an exec's `NAME=value` entries for the runtime CLI's command line: a
67
+ * variable the harness scrubs (its model credential) goes as `NAME` alone, its
68
+ * value in that one child's environment, so no argv holds it.
69
+ * @param {string[]} env
70
+ * @param {string[]} secret the plan's `launch.secretEnv`: variables whose value is a real credential
71
+ * @param {string} flag
72
+ */
73
+ export function envArgs(env, secret, flag) {
74
+ const args = [];
75
+ const childEnv = {};
76
+ for (const entry of env) {
77
+ const eq = entry.indexOf("=");
78
+ const name = eq < 0 ? entry : entry.slice(0, eq);
79
+ if (eq >= 0 && secret.includes(name)) {
80
+ childEnv[name] = entry.slice(eq + 1);
81
+ args.push(flag, name);
82
+ } else args.push(flag, entry);
83
+ }
84
+ return { args, childEnv };
85
+ }
86
+
64
87
  /**
65
88
  * @param {{ runtime: import("./runtime.mjs").Runtime, id: string, call: Call, plan: import("../harness/claude-code.mjs").LaunchPlan }} opts
66
89
  * `plan` is the harness's launch plan: its install layer goes on the image.
@@ -100,13 +123,17 @@ export function dockerDriver({ runtime, id, call, plan }) {
100
123
  return {
101
124
  container: name,
102
125
 
103
- async prepare(steps, { archive, out, branch, short }) {
104
- const harness = pinnedHarnessImage(plan.installLayer);
126
+ async prepare(steps, { archive, out, branch, short, why = "the recipe names no image" }) {
127
+ // A Custom harness has no Harness image: its npm package is layered on
128
+ // the recipe's image, or on the kit's base.
129
+ const { npm } = plan.installLayer;
130
+ const harness = npm === undefined ? pinnedHarnessImage(plan.installLayer) : null;
131
+ const named = steps.dockerfile !== undefined || steps.image !== undefined;
105
132
  // No image of the recipe's: the sandbox runs the Harness image, which
106
133
  // is not this run's to remove.
107
- if (steps.dockerfile === undefined && steps.image === undefined) {
134
+ if (!named && harness !== null) {
108
135
  out(
109
- `Image: pulling the Harness image ${harness}, which holds the pinned ${displayName}; the recipe names no image.`,
136
+ `Image: pulling the Harness image ${harness}, which holds the pinned ${displayName}; ${why}.`,
110
137
  );
111
138
  must(await docker(["pull", harness]), `pulling the Harness image ${harness}`, {
112
139
  showOutput: true,
@@ -128,7 +155,7 @@ export function dockerDriver({ runtime, id, call, plan }) {
128
155
  `building ${steps.dockerfile}`,
129
156
  { showOutput: true },
130
157
  );
131
- } else {
158
+ } else if (steps.image !== undefined) {
132
159
  base = steps.image;
133
160
  out(`Image: pulling ${base}.`);
134
161
  const note = imageDigestNote(base);
@@ -136,14 +163,18 @@ export function dockerDriver({ runtime, id, call, plan }) {
136
163
  must(await docker(["pull", base]), `pulling ${base}`, { showOutput: true });
137
164
  }
138
165
  out(
139
- `Image: layering the pinned ${displayName}, auto-updater off, from the Harness image ${harness}.`,
166
+ npm === undefined
167
+ ? `Image: layering the pinned ${displayName}, auto-updater off, from the Harness image ${harness}.`
168
+ : `Image: installing ${npm} from npm for ${displayName}, on ${named ? "that image" : `the kit's base image; ${why}`}.`,
140
169
  );
141
170
  resources.push(["image", name]);
142
171
  const layered = await docker(["build", "--label", label, "--tag", name, "-"], {
143
172
  stdin: layerDockerfile(base, plan.installLayer),
144
173
  });
145
174
  refuseMusl(layered, steps);
146
- must(layered, `layering ${displayName} on ${base}`, { showOutput: true });
175
+ must(layered, `layering ${displayName} on ${base ?? "the kit's base image"}`, {
176
+ showOutput: true,
177
+ });
147
178
  sandboxImage = name;
148
179
  },
149
180
 
@@ -165,30 +196,7 @@ export function dockerDriver({ runtime, id, call, plan }) {
165
196
  throw new StepFailed([`FAILED the setup network is not isolated: ${why}.`, ENDS_HERE]);
166
197
  }
167
198
  resources.push(["container", name]);
168
- must(
169
- await docker([
170
- "run",
171
- "--detach",
172
- "--init",
173
- "--name",
174
- name,
175
- "--label",
176
- label,
177
- ...(runtime.dockerRuntime ? ["--runtime", runtime.dockerRuntime] : []),
178
- "--network",
179
- network,
180
- "--security-opt",
181
- "no-new-privileges",
182
- "--workdir",
183
- "/workspace",
184
- "--entrypoint",
185
- "tail",
186
- sandboxImage,
187
- "-f",
188
- "/dev/null",
189
- ]),
190
- "starting the sandbox",
191
- );
199
+ await runSandbox("starting the sandbox");
192
200
  await onAlone(network, "the setup network");
193
201
  return {
194
202
  isolation: setupRelay
@@ -215,6 +223,36 @@ export function dockerDriver({ runtime, id, call, plan }) {
215
223
  /** The harness is already in the image. */
216
224
  async installAgent() {},
217
225
 
226
+ /**
227
+ * The archive `script` writes to its output, run as root in the sandbox
228
+ * (ADR 0047). Through `docker exec`, never `docker cp`, which under gVisor
229
+ * cannot read what the sandbox wrote (#404).
230
+ */
231
+ async carryOut(script, { maxBytes }) {
232
+ const r = await docker(
233
+ ["exec", "--user", "0:0", "--workdir", "/", name, "sh", "-c", script],
234
+ { maxOutput: maxBytes },
235
+ );
236
+ if (r.truncated) return { error: `it is larger than ${maxBytes / 1024 ** 3} GiB` };
237
+ if (r.status !== 0) {
238
+ return {
239
+ error: `tar exited ${r.status ?? "abnormally"}: ${firstLine(r.stderr) || "no output"}`,
240
+ };
241
+ }
242
+ return { data: r.stdout };
243
+ },
244
+
245
+ /**
246
+ * Remove the sandbox, and every process in it, and start a fresh one from
247
+ * the same image on the same network, which the cut left with nothing to
248
+ * reach (ADR 0047). It keeps the sandbox's name.
249
+ */
250
+ async renew() {
251
+ must(await docker(["rm", "--force", name]), "removing the setup container");
252
+ await runSandbox("starting the agent's container");
253
+ await onAlone(network, "its network");
254
+ },
255
+
218
256
  /** The setup egress was opened with the network: the proxy's variables. */
219
257
  async openSetupEgress(registries) {
220
258
  return registries.length
@@ -227,16 +265,13 @@ export function dockerDriver({ runtime, id, call, plan }) {
227
265
 
228
266
  refused: () => proxy?.refused ?? [],
229
267
 
230
- exec: (script, { env = [], workdir = "/workspace" } = {}) =>
231
- docker([
232
- "exec",
233
- ...env.flatMap((v) => ["--env", v]),
234
- ...(workdir ? ["--workdir", workdir] : []),
235
- name,
236
- "sh",
237
- "-c",
238
- script,
239
- ]),
268
+ exec: (script, { env = [], workdir = "/workspace" } = {}) => {
269
+ const { args, childEnv } = envArgs(env, plan.launch?.secretEnv ?? [], "--env");
270
+ return docker(
271
+ ["exec", ...args, ...(workdir ? ["--workdir", workdir] : []), name, "sh", "-c", script],
272
+ { env: childEnv },
273
+ );
274
+ },
240
275
 
241
276
  /**
242
277
  * The cut: stop the egress proxy and remove the setup relay. Nothing is
@@ -365,6 +400,34 @@ export function dockerDriver({ runtime, id, call, plan }) {
365
400
  },
366
401
  };
367
402
 
403
+ /** `docker run` of the sandbox, on its one network, idle until a step execs. */
404
+ async function runSandbox(what) {
405
+ must(
406
+ await docker([
407
+ "run",
408
+ "--detach",
409
+ "--init",
410
+ "--name",
411
+ name,
412
+ "--label",
413
+ label,
414
+ ...(runtime.dockerRuntime ? ["--runtime", runtime.dockerRuntime] : []),
415
+ "--network",
416
+ network,
417
+ "--security-opt",
418
+ "no-new-privileges",
419
+ "--workdir",
420
+ "/workspace",
421
+ "--entrypoint",
422
+ "tail",
423
+ sandboxImage,
424
+ "-f",
425
+ "/dev/null",
426
+ ]),
427
+ what,
428
+ );
429
+ }
430
+
368
431
  async function closeProxy() {
369
432
  if (proxy) {
370
433
  const p = proxy;