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

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 (79) hide show
  1. package/README.md +24 -5
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +286 -0
  4. package/package.json +4 -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/review-response.mjs +54 -27
  10. package/src/checks/rulesets.mjs +9 -8
  11. package/src/checks/secrets-and-variables.mjs +220 -43
  12. package/src/checks/stages.mjs +705 -0
  13. package/src/cli.mjs +277 -31
  14. package/src/deep-scan/agent.mjs +145 -117
  15. package/src/deep-scan/credential.mjs +88 -42
  16. package/src/deep-scan/docker-driver.mjs +131 -49
  17. package/src/deep-scan/harness-text.mjs +99 -0
  18. package/src/deep-scan/lifecycle.mjs +92 -199
  19. package/src/deep-scan/limits.mjs +13 -7
  20. package/src/deep-scan/model-proxy.mjs +47 -602
  21. package/src/deep-scan/preflight.mjs +81 -1
  22. package/src/deep-scan/recipe.mjs +7 -7
  23. package/src/deep-scan/runtime.mjs +54 -6
  24. package/src/deep-scan/sandbox-run.mjs +232 -0
  25. package/src/deep-scan/sbx-driver.mjs +242 -50
  26. package/src/deep-scan/tar.mjs +69 -22
  27. package/src/deep-scan/verify.mjs +6 -1
  28. package/src/deep-scan.mjs +98 -14
  29. package/src/doctor.mjs +113 -4
  30. package/src/harness/adapters.mjs +30 -0
  31. package/src/harness/antigravity.mjs +187 -0
  32. package/src/harness/claude-code.mjs +236 -0
  33. package/src/harness/codex.mjs +219 -0
  34. package/src/harness/cursor.mjs +199 -0
  35. package/src/harness/custom/registry.mjs +21 -0
  36. package/src/harness/custom/schema.mjs +90 -0
  37. package/src/harness/custom.mjs +299 -0
  38. package/src/harness/facts.mjs +157 -0
  39. package/src/harness/gemini.mjs +164 -0
  40. package/src/harness/install-layer.mjs +141 -0
  41. package/src/harness/opencode.mjs +289 -0
  42. package/src/harness/resolve.mjs +156 -0
  43. package/src/harness/support-levels.mjs +197 -0
  44. package/src/harness-live/assess.mjs +291 -0
  45. package/src/harness-live/cursor-real.mjs +146 -0
  46. package/src/harness-live/cursor-version.mjs +70 -0
  47. package/src/harness-live/cursor.mjs +80 -0
  48. package/src/harness-live/custom.mjs +91 -0
  49. package/src/harness-live/fixture-harness.mjs +45 -0
  50. package/src/harness-live/harnesses.mjs +263 -0
  51. package/src/harness-live/host.mjs +414 -0
  52. package/src/harness-live/opencode.mjs +289 -0
  53. package/src/harness-live/probes.mjs +239 -0
  54. package/src/harness-live/run.mjs +214 -0
  55. package/src/harness-live/setup.mjs +126 -0
  56. package/src/harness-live/stage.mjs +161 -0
  57. package/src/harness-live/suite.mjs +481 -0
  58. package/src/harness-test.mjs +116 -0
  59. package/src/init.mjs +339 -23
  60. package/src/model-proxy/core.mjs +657 -0
  61. package/src/model-proxy/profiles/anthropic.mjs +241 -0
  62. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  63. package/src/model-proxy/profiles/openai.mjs +327 -0
  64. package/src/model-proxy/stub-dialects/anthropic.mjs +110 -0
  65. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  66. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  67. package/src/model-proxy/stub.mjs +182 -0
  68. package/src/stage/audit.mjs +79 -0
  69. package/src/stage/egress-route.mjs +207 -0
  70. package/src/stage/implement/carry.mjs +308 -0
  71. package/src/stage/implement/sandbox.mjs +271 -0
  72. package/src/stage/implement/verify.mjs +70 -0
  73. package/src/stage/implement.mjs +218 -0
  74. package/src/stage/plan.mjs +115 -0
  75. package/src/stage/review-response.mjs +172 -0
  76. package/src/stage/review.mjs +185 -0
  77. package/src/stage/workspace.mjs +274 -0
  78. package/src/stage.mjs +1068 -0
  79. package/src/deep-scan/claude-code.mjs +0 -25
@@ -1,30 +1,19 @@
1
- // The agent step (#370): the real Claude Code, run in the sandbox after the
2
- // network is cut, with the model proxy as its only route out.
1
+ // The agent step (#370): the harness, run in the sandbox after the network is
2
+ // cut, with the model proxy as its only route out.
3
3
  //
4
- // `--bare` skips skill and CLAUDE.md discovery, so the launcher hands the
5
- // agent everything explicitly, in a brief: the security-audit skill's `deep`
6
- // procedure (DEEP.md, with SKILL.md and report-format.md, which it builds
7
- // on), the Threat pack and the Scan recipe, all read at the trusted ref, and
8
- // the sandbox's paths. Claude Code holds only a placeholder API key. Its
9
- // model API base URL is pinned by the launcher's own `--settings`, which
10
- // outrank project settings, and project and local settings are not even
11
- // loaded (`--setting-sources user`), so the scanned repository's
12
- // `.claude/settings.json` cannot point it elsewhere. Web tools are not in
13
- // its tool set, and are denied as well. Its turn limit is the launcher's
14
- // `--max-turns` on the command line (#371).
15
- //
16
- // On the subscription path (#375) Claude Code holds a placeholder
17
- // CLAUDE_CODE_OAUTH_TOKEN instead, and runs without `--bare`, which never
18
- // reads one. So it can discover the scanned repository's CLAUDE.md and
19
- // skills: the brief says they are that repository's content, and that its
20
- // own procedure decides. The settings stay pinned the same way, hooks are
21
- // off in them, and `--strict-mcp-config` keeps any MCP server the
22
- // repository names from starting.
4
+ // The launcher hands the agent everything explicitly, in a brief: the
5
+ // security-audit skill's `deep` procedure (DEEP.md, with SKILL.md and
6
+ // report-format.md, which it builds on), the Threat pack and the Scan recipe,
7
+ // all read at the trusted ref, and the sandbox's paths. How the harness is
8
+ // started, what it holds and how it says it hit its turn limit come from its
9
+ // Harness adapter's launch plan (../harness/, ADR 0027); this module runs
10
+ // that plan.
23
11
 
24
12
  import { firstLine } from "../exec.mjs";
13
+ import { adapterFor, DEFAULT_HARNESS } from "../harness/adapters.mjs";
25
14
  import { checkSafePath, UnsafePathError } from "../safe-paths.mjs";
26
15
  import { isMapping, parseYamlSubset, stripBom } from "../yaml-subset.mjs";
27
- import { PLACEHOLDER_API_KEY, PLACEHOLDER_OAUTH_TOKEN, SUBSCRIPTION } from "./credential.mjs";
16
+ import { textFor } from "./harness-text.mjs";
28
17
 
29
18
  /** Where a Consumer's security-audit skill lives, as Agent-kit installs it. */
30
19
  export const SKILL_DIR = ".claude/skills/security-audit";
@@ -38,20 +27,71 @@ export const DEFAULT_THREAT_PACK = Object.freeze({
38
27
  findingsLedger: ".security/findings-ledger.md",
39
28
  });
40
29
 
41
- /** The tools the agent has; the web tools are not among them. */
42
- export const AGENT_TOOLS = Object.freeze(["Bash", "Read", "Write", "Edit", "Glob", "Grep"]);
43
- export const WEB_TOOLS = Object.freeze(["WebFetch", "WebSearch"]);
30
+ export { TOOLS as AGENT_TOOLS, WEB_TOOLS } from "../harness/claude-code.mjs";
31
+
32
+ /** Where the brief goes in the sandbox: the launcher's, outside /workspace. */
33
+ export const BRIEF_PATH = "/agent-kit/in/brief.md";
34
+
35
+ /** The launcher's own folder in the sandbox, outside /workspace. */
36
+ const KIT_DIR = "/agent-kit";
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"]);
44
40
 
45
41
  /**
46
- * What the agent step's script prints when Claude Code stopped at its turn
47
- * limit: a fixed line, so nothing of Claude Code's own output leaves the
48
- * sandbox. It is read from Claude Code's error output (where print mode says
49
- * "Error: Reached max turns"), never from its answer, which the agent writes.
42
+ * The harness's launch plan for a Deep scan. Without a `baseUrl` (before the
43
+ * model route is open) its launch is not yet one to run; its identity and
44
+ * install layer are.
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).
47
+ * `model` is a plain model id and `effort` an effort level, both checked by
48
+ * the launcher. `kind` is the credential's (default an API key).
49
+ * `callerKey` is the run's (callerKeyFor): the agent holds it in place of
50
+ * the credential.
50
51
  */
51
- export const TURNS_MARKER = "agent-kit-deep-scan: Claude Code reached its turn limit";
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)({
62
+ stage: "deep-scan",
63
+ proxyUrl: baseUrl,
64
+ briefPath: BRIEF_PATH,
65
+ kitDir: KIT_DIR,
66
+ maxTurns,
67
+ model,
68
+ effort,
69
+ credentialKind: kind,
70
+ callerKey,
71
+ });
72
+ }
52
73
 
53
- /** Where the brief goes in the sandbox: the launcher's, outside /workspace. */
54
- export const BRIEF_PATH = "/agent-kit/in/brief.md";
74
+ /**
75
+ * What the agent step's script prints when the harness stopped at its turn
76
+ * limit: a fixed line, so nothing of the harness's own output leaves the
77
+ * sandbox. It is printed on the plan's marker in the harness's error output,
78
+ * never on its answer, which the agent writes.
79
+ * @param {import("../harness/claude-code.mjs").LaunchPlan} plan
80
+ */
81
+ export const turnsMarker = (plan) =>
82
+ `agent-kit-deep-scan: ${plan.identity.displayName} reached its turn limit`;
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
+
93
+ /** The Claude Code plan's line. */
94
+ export const TURNS_MARKER = turnsMarker(agentPlan());
55
95
 
56
96
  const MAX_HANDED_BYTES = 512 * 1024;
57
97
  const CALLER_USES = /(^|\/)\.github\/workflows\/security-audit-reusable\.ya?ml(@\S+)?$/;
@@ -209,10 +249,12 @@ function plainPath(value) {
209
249
  * grounding: Array<{ source: string, at: string }>,
210
250
  * paths: { workspace: string, grounding: string, report: string },
211
251
  * discovers?: boolean,
252
+ * harness?: string,
212
253
  * }} opts `discovers`: Claude Code runs without `--bare` (the
213
254
  * subscription path), so the brief says what it discovers.
214
255
  */
215
256
  export function agentBrief({
257
+ harness = DEFAULT_HARNESS,
216
258
  branch,
217
259
  short,
218
260
  recipePath,
@@ -225,13 +267,14 @@ export function agentBrief({
225
267
  return [
226
268
  "# Deep scan brief, from the agent-kit deep-scan launcher",
227
269
  "",
228
- "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}.`,
229
271
  "",
230
272
  "## Where things are",
231
273
  "",
232
274
  `- The repository: \`${paths.workspace}\`, an export of \`${branch}\` at ${short} (the trusted ref). Scan the whole repository.`,
233
275
  ...groundingLines(grounding, paths),
234
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),
235
278
  SETUP_DONE,
236
279
  ...(discovers ? [DISCOVERED] : []),
237
280
  "",
@@ -253,6 +296,22 @@ export function agentBrief({
253
296
  ].join("\n");
254
297
  }
255
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
+
256
315
  /** A brief's line on the setup phase, which the launcher already ran. */
257
316
  export const SETUP_DONE =
258
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.";
@@ -305,101 +364,70 @@ export function threatPackAndRecipe({ handIn, recipePath, recipeText }) {
305
364
  }
306
365
 
307
366
  /**
308
- * The launcher's own settings for the sandboxed Claude Code: the model API
309
- * base URL pinned to the proxy, and the web tools denied. On the
310
- * subscription path, where no `--bare` skips them, hooks are off too: a
311
- * setup step could have written some into the sandbox's user settings.
312
- * @param {string} baseUrl the model proxy, as the sandbox reaches it
313
- * @param {"api-key" | "subscription"} [kind]
314
- */
315
- export function agentSettings(baseUrl, kind = "api-key") {
316
- return {
317
- env: {
318
- ANTHROPIC_BASE_URL: baseUrl,
319
- CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
320
- DISABLE_AUTOUPDATER: "1",
321
- },
322
- permissions: { allow: [...AGENT_TOOLS], deny: [...WEB_TOOLS] },
323
- ...(kind === SUBSCRIPTION ? { disableAllHooks: true } : {}),
324
- };
325
- }
326
-
327
- /**
328
- * The agent's environment: the run's caller key (callerKeyFor), never the
329
- * real credential. On the subscription path it is the token alone, since an
330
- * API key would outrank it in Claude Code's auth order.
331
- * @param {"api-key" | "subscription"} [kind]
332
- * @param {string} [key] the run's caller key; without one, the bare placeholder
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
375
+ * the caller's to set.
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.
333
379
  */
334
- export function agentEnv(kind = "api-key", key) {
335
- const held = key ?? (kind === SUBSCRIPTION ? PLACEHOLDER_OAUTH_TOKEN : PLACEHOLDER_API_KEY);
336
- return [
337
- kind === SUBSCRIPTION ? `CLAUDE_CODE_OAUTH_TOKEN=${held}` : `ANTHROPIC_API_KEY=${held}`,
338
- "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1",
339
- ];
340
- }
341
-
342
- /**
343
- * The agent step's script, run with `sh -c` in the sandbox: Claude Code in
344
- * print mode, its brief on stdin, its own output kept in the sandbox (its
345
- * error output is passed on too), and TURNS_MARKER when it stopped at the
346
- * launcher's turn limit.
347
- * @param {{ baseUrl: string, report: string, workspace: string, maxTurns: number, model?: string, effort?: string, kind?: "api-key" | "subscription" }} opts
348
- * `model` is a plain model id and `effort` an effort level, both checked
349
- * by the launcher; without either, Claude Code runs on its own default. `kind` is the credential's: on the
350
- * subscription path there is no `--bare`, which would never read the
351
- * token, and no MCP server but the launcher's (none).
352
- */
353
- export function agentScript({
354
- baseUrl,
355
- report,
356
- workspace,
357
- maxTurns,
358
- model,
359
- effort,
360
- kind = "api-key",
361
- }) {
362
- const args = [
363
- "claude",
364
- ...(kind === SUBSCRIPTION ? [] : ["--bare"]),
365
- "--print",
366
- "--settings",
367
- JSON.stringify(agentSettings(baseUrl, kind)),
368
- "--setting-sources",
369
- "user",
370
- ...(kind === SUBSCRIPTION ? ["--strict-mcp-config"] : []),
371
- "--tools",
372
- AGENT_TOOLS.join(","),
373
- "--allowedTools",
374
- AGENT_TOOLS.join(","),
375
- "--disallowedTools",
376
- WEB_TOOLS.join(","),
377
- "--permission-mode",
378
- "dontAsk",
379
- "--add-dir",
380
- "/agent-kit",
381
- "--no-session-persistence",
382
- "--max-turns",
383
- String(maxTurns),
384
- ...(model !== undefined ? ["--model", model] : []),
385
- ...(effort !== undefined ? ["--effort", effort] : []),
386
- ];
387
- const outDir = report.slice(0, report.lastIndexOf("/"));
388
- const logs = "/agent-kit/logs";
389
- // Claude Code's error output reaches the launcher through a pipe, as it
380
+ export function agentScript({ report, workspace, kitDir = KIT_DIR, plan, ...request }) {
381
+ const launched = plan ?? agentPlan(request);
382
+ const { launch, stops, transcript, checkoutConfig } = launched;
383
+ const logs = `${kitDir}/logs`;
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
+ }
397
+ const folders = [...new Set([folderOf(report), logs, folderOf(transcript.path)])];
398
+ const stdin = launch.stdin ? ` < ${shQuote(launch.stdin.file)}` : "";
399
+ // The harness's error output reaches the launcher through a pipe, as it
390
400
  // happens, and a copy goes to agent.err for the turn check. The agent can
391
401
  // write that file (and agent.status), so the file is only searched, never
392
402
  // printed, and a planted status that is not a number counts as a failure.
393
403
  return [
394
404
  "set -eu",
395
- `mkdir -p ${outDir} ${logs}`,
405
+ `mkdir -p ${folders.join(" ")}`,
396
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)}`),
397
416
  `rm -f ${logs}/agent.status`,
398
- `{ ${args.map(shQuote).join(" ")} < ${BRIEF_PATH} 2>&1 > ${logs}/agent.log || echo "$?" > ${logs}/agent.status; } | tee ${logs}/agent.err >&2`,
417
+ `{ ${launch.argv.map(shQuote).join(" ")}${stdin} 2>&1 > ${shQuote(transcript.path)} || echo "$?" > ${logs}/agent.status; } | tee ${logs}/agent.err >&2`,
399
418
  "status=0",
400
419
  `if [ -s ${logs}/agent.status ]; then status=$(cat ${logs}/agent.status); fi`,
401
420
  `case "$status" in ''|*[!0-9]*) status=1 ;; esac`,
402
- `if grep -q '^Error: Reached max turns' ${logs}/agent.err; then echo ${shQuote(TURNS_MARKER)}; fi`,
421
+ ...(stops.turnCap
422
+ ? [
423
+ `if grep -q ${shQuote(stops.turnCap.stderrPattern)} ${logs}/agent.err; then echo ${shQuote(turnsMarker(launched))}; fi`,
424
+ ]
425
+ : []),
426
+ ...(stops.credentialMissing
427
+ ? [
428
+ `if grep -qiE ${shQuote(stops.credentialMissing.stderrPattern)} ${logs}/agent.err; then echo ${shQuote(credentialMarker(launched))}; fi`,
429
+ ]
430
+ : []),
403
431
  'exit "$status"',
404
432
  ].join("\n");
405
433
  }
@@ -1,46 +1,58 @@
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";
16
+ import { ADAPTERS, adapterFor, DEFAULT_HARNESS } from "../harness/adapters.mjs";
17
+ import { textFor } from "./harness-text.mjs";
15
18
  import { GITHUB_TOKEN_VARS } from "./preflight.mjs";
16
19
 
17
- /** The default variable the API key is read from. */
18
- export const API_KEY_VAR = "ANTHROPIC_API_KEY";
20
+ /**
21
+ * The credentials `harness` accepts, from its launch plan: each kind's
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
25
+ */
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();
19
31
 
20
32
  /**
21
- * The start of the key the sandboxed Claude Code holds in place of a real
22
- * one; the proxy swaps it for the real key.
33
+ * The start of the key the sandboxed agent holds in place of a real one;
34
+ * the proxy swaps it for the real key.
23
35
  */
24
- export const PLACEHOLDER_API_KEY = "agent-kit-deep-scan-placeholder";
36
+ export const PLACEHOLDER_API_KEY = accepted["api-key"].placeholder;
25
37
 
26
38
  /**
27
- * The start of the token the sandboxed Claude Code holds on the
28
- * subscription path; the proxy swaps the bearer value it sends. It is shaped
29
- * like a token, in case Claude Code checks the prefix.
39
+ * The start of the token the sandboxed agent holds on the subscription
40
+ * path; the proxy swaps the bearer value it sends.
30
41
  */
31
- export const PLACEHOLDER_OAUTH_TOKEN = "sk-ant-oat01-agent-kit-deep-scan-placeholder";
42
+ export const PLACEHOLDER_OAUTH_TOKEN = accepted.subscription.placeholder;
32
43
 
33
44
  /**
34
45
  * The run's caller key: a placeholder with 24 random bytes added, made once
35
- * per run. The sandboxed Claude Code holds it in place of a credential, and
36
- * the model proxy forwards only a request that carries it, so a process in
37
- * the sandbox that never read Claude Code's environment cannot spend the
38
- * 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.
39
50
  * @param {"api-key" | "subscription"} kind
51
+ * @param {string} [harness]
52
+ * @param {string} [model]
40
53
  */
41
- export function callerKeyFor(kind) {
42
- const start = kind === SUBSCRIPTION ? PLACEHOLDER_OAUTH_TOKEN : PLACEHOLDER_API_KEY;
43
- return `${start}-${randomBytes(24).toString("hex")}`;
54
+ export function callerKeyFor(kind, harness, model) {
55
+ return `${acceptedBy(harness, model)[kind].placeholder}-${randomBytes(24).toString("hex")}`;
44
56
  }
45
57
 
46
58
  /** The kinds `--credential` takes: an API key (the default) or the opt-in. */
@@ -48,17 +60,18 @@ export const API_KEY = "api-key";
48
60
  export const SUBSCRIPTION = "subscription";
49
61
  const CREDENTIAL_KINDS = Object.freeze([API_KEY, SUBSCRIPTION]);
50
62
 
51
- /** Model credential variables, removed from every command the launcher runs. */
63
+ /**
64
+ * Model credential variables, of every harness, removed from every command the
65
+ * launcher runs.
66
+ */
52
67
  export const CREDENTIAL_VARS = Object.freeze([
53
- "ANTHROPIC_API_KEY",
54
- "ANTHROPIC_AUTH_TOKEN",
55
- "CLAUDE_CODE_OAUTH_TOKEN",
68
+ ...new Set(Object.values(ADAPTERS).flatMap((adapter) => adapter().credentials.scrub)),
56
69
  ]);
57
70
 
58
- /** The variable Claude Code reads a subscription (OAuth) token from. */
59
- const OAUTH_TOKEN_VAR = "CLAUDE_CODE_OAUTH_TOKEN";
60
71
  /** How a Claude subscription (OAuth) token starts; an API key starts sk-ant-api. */
61
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-";
62
75
 
63
76
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
64
77
  const OP_REF = /^op:\/\/[^/\s][^\r\n]*$/;
@@ -85,11 +98,13 @@ export function credentialKind(value) {
85
98
  * key itself.
86
99
  * @param {string | undefined} value
87
100
  * @param {"api-key" | "subscription"} [kind]
101
+ * @param {string} [harness]
102
+ * @param {string} [model]
88
103
  * @returns {{ kind: "env", name: string } | { kind: "op", ref: string } | { error: string }}
89
104
  */
90
- export function credentialSource(value, kind = API_KEY) {
105
+ export function credentialSource(value, kind = API_KEY, harness = DEFAULT_HARNESS, model) {
91
106
  if (value === undefined) {
92
- return { kind: "env", name: kind === SUBSCRIPTION ? OAUTH_TOKEN_VAR : API_KEY_VAR };
107
+ return { kind: "env", name: acceptedBy(harness, model)[kind].env };
93
108
  }
94
109
  if (value.startsWith("env:")) {
95
110
  const name = value.slice(4);
@@ -113,10 +128,22 @@ export function credentialSource(value, kind = API_KEY) {
113
128
  * env: Record<string, string | undefined>,
114
129
  * runner: import("../exec.mjs").Runner,
115
130
  * kind?: "api-key" | "subscription",
116
- * }} opts
131
+ * harness?: string,
132
+ * model?: string,
133
+ * command?: string,
134
+ * }} opts `command` is the one the refusals name (default `deep-scan`).
117
135
  * @returns {{ credential: string, from: string } | { refused: string[] }}
118
136
  */
119
- 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;
120
147
  const token = kind === SUBSCRIPTION;
121
148
  if (source.kind === "op") {
122
149
  const r = runner("op", ["read", "--no-newline", source.ref]);
@@ -124,7 +151,7 @@ export function readCredential({ source, env, runner, kind = API_KEY }) {
124
151
  return {
125
152
  refused: [
126
153
  `Could not read the model credential with op read: ${firstLine(r.stderr) || `exit ${r.status}`}`,
127
- "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.`,
128
155
  ],
129
156
  };
130
157
  }
@@ -133,11 +160,17 @@ export function readCredential({ source, env, runner, kind = API_KEY }) {
133
160
  "the op read result",
134
161
  "1Password (op read)",
135
162
  kind,
163
+ harness,
164
+ model,
136
165
  );
137
166
  }
138
167
  const { name } = source;
139
- if (!token && name.toUpperCase() === OAUTH_TOKEN_VAR) return notAnApiKey(name);
140
- 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" : ""}`;
141
174
  const value = valueOf(env, name);
142
175
  if (!value) {
143
176
  return {
@@ -147,7 +180,7 @@ export function readCredential({ source, env, runner, kind = API_KEY }) {
147
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.`,
148
181
  ]
149
182
  : [
150
- `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.`,
151
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.`,
152
185
  ],
153
186
  };
@@ -155,13 +188,13 @@ export function readCredential({ source, env, runner, kind = API_KEY }) {
155
188
  if (value.startsWith("op://")) {
156
189
  return {
157
190
  refused: [
158
- `${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:`,
159
192
  ` op run -- ${command}`,
160
193
  "or pass the reference with --credential-from instead.",
161
194
  ],
162
195
  };
163
196
  }
164
- return checked(value, name, name, kind);
197
+ return checked(value, name, name, kind, harness, model);
165
198
  }
166
199
 
167
200
  /** The variable's value, by name in any letter case (as Windows matches it). */
@@ -171,7 +204,7 @@ function valueOf(env, name) {
171
204
  return key === undefined ? undefined : env[key];
172
205
  }
173
206
 
174
- function checked(value, what, from, kind) {
207
+ function checked(value, what, from, kind, harness, model) {
175
208
  if (!value) return { refused: [`No model credential: ${what} is empty.`] };
176
209
  // The credential goes into an HTTP header: printable ASCII with no space only.
177
210
  if (!/^[\x21-\x7e]+$/.test(value)) {
@@ -182,6 +215,19 @@ function checked(value, what, from, kind) {
182
215
  };
183
216
  }
184
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
+ }
185
231
  if (kind !== SUBSCRIPTION && isToken) return notAnApiKey(what);
186
232
  if (kind === SUBSCRIPTION && !isToken) {
187
233
  return {
@@ -225,8 +271,8 @@ export function withoutCredentials(runner, envs, extra = []) {
225
271
  }
226
272
  const scrub = Object.fromEntries([...names].map((n) => [n, undefined]));
227
273
  const wrapped = (cmd, args, opts = {}) =>
228
- runner(cmd, args, { ...opts, env: { ...opts.env, ...scrub } });
274
+ runner(cmd, args, { ...opts, env: { ...scrub, ...opts.env } });
229
275
  wrapped.start = (cmd, args, opts = {}) =>
230
- runner.start(cmd, args, { ...opts, env: { ...opts.env, ...scrub } });
276
+ runner.start(cmd, args, { ...opts, env: { ...scrub, ...opts.env } });
231
277
  return wrapped;
232
278
  }