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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,31 @@
1
1
  // Secrets and repository variables, worked out from the Consumer's Callers.
2
2
  // A secret is required when the reusable workflow at the pinned tag declares
3
3
  // the secret it is passed to as `required: true`; otherwise it is optional.
4
+ // The model credentials are optional there, because only the chosen harness
5
+ // needs one (ADR 0030), so they are asked for as a group.
4
6
  // A variable is optional when every read of it falls back with `||`.
5
7
 
6
8
  import { secretNames } from "../callers.mjs";
7
9
  import { parseWorkflowCallSecrets } from "../workflow-call.mjs";
8
10
  import { byHand, command, NAME_PATTERN, result } from "./result.mjs";
9
11
 
12
+ /** The secret inputs `claude-code` accepts, the preferred one first (ADR 0024). */
13
+ const CLAUDE_CODE_INPUTS = ["claude_code_oauth_token", "anthropic_api_key"];
14
+ /**
15
+ * The Deep scan takes exactly one of the two (its first step fails on both),
16
+ * and the API key is its supported one.
17
+ */
18
+ const DEEP_SCAN_REUSABLE = "deep-scan-reusable.yml";
19
+ const preferred = (file) =>
20
+ file === DEEP_SCAN_REUSABLE ? [...CLAUDE_CODE_INPUTS].reverse() : CLAUDE_CODE_INPUTS;
21
+ /** Every model credential input: the others belong to harnesses no Stage runs yet. */
22
+ const MODEL_INPUTS = new Set([
23
+ ...CLAUDE_CODE_INPUTS,
24
+ "openai_api_key",
25
+ "gemini_api_key",
26
+ "cursor_api_key",
27
+ ]);
28
+
10
29
  /** GitHub provides `secrets.GITHUB_TOKEN`; no `GITHUB_*` secret can be set by hand. */
11
30
  const isProvided = (name) => /^github_/i.test(name);
12
31
 
@@ -49,6 +68,7 @@ export function deriveVariables(callers) {
49
68
  export function deriveRequirements(callers, readReusable) {
50
69
  const secrets = new Map();
51
70
  const problems = [];
71
+ const noCredential = [];
52
72
  const specs = new Map();
53
73
  const specFor = (file) => {
54
74
  if (!specs.has(file)) {
@@ -57,7 +77,8 @@ export function deriveRequirements(callers, readReusable) {
57
77
  }
58
78
  return specs.get(file);
59
79
  };
60
- const addSecret = (names, required, where) => {
80
+ // `shown` is false under `secrets: inherit`, where the Caller writes no input.
81
+ const addSecret = (names, required, job, file, input, shown = true) => {
61
82
  // A GITHUB_* secret is always set, so an expression that falls back to one is too.
62
83
  if (names.some(isProvided)) return;
63
84
  const key = names.join(" || ");
@@ -65,7 +86,9 @@ export function deriveRequirements(callers, readReusable) {
65
86
  secrets.set(key, {
66
87
  names,
67
88
  required: Boolean(prev?.required || required),
68
- where: [...(prev?.where ?? []), where],
89
+ where: [...(prev?.where ?? []), shown ? `${job} (${input})` : job],
90
+ // The job, the reusable workflow it calls and the secret input each use fills.
91
+ uses: [...(prev?.uses ?? []), { job, file, input: input.toLowerCase() }],
69
92
  });
70
93
  };
71
94
 
@@ -80,7 +103,8 @@ export function deriveRequirements(callers, readReusable) {
80
103
  }
81
104
  if (job.secrets === "inherit") {
82
105
  for (const { name, required } of spec.values()) {
83
- addSecret([name.toUpperCase()], required, where);
106
+ // Inherited, the secret's name is the input's.
107
+ addSecret([name.toUpperCase()], required, where, job.uses.file, name, false);
84
108
  }
85
109
  continue;
86
110
  }
@@ -95,7 +119,18 @@ export function deriveRequirements(callers, readReusable) {
95
119
  );
96
120
  continue;
97
121
  }
98
- addSecret(names, declared.required, `${where} (${input})`);
122
+ addSecret(names, declared.required, where, job.uses.file, input);
123
+ }
124
+ // Optional in the workflow, so nothing refuses a job without either.
125
+ const accepted = CLAUDE_CODE_INPUTS.filter((input) => spec.has(input));
126
+ if (
127
+ accepted.length &&
128
+ accepted.every((input) => !spec.get(input).required && !passed.has(input))
129
+ ) {
130
+ noCredential.push(
131
+ `${where} passes neither ${CLAUDE_CODE_INPUTS.join(" nor ")} to ${job.uses.file}; ` +
132
+ "the run fails without one",
133
+ );
99
134
  }
100
135
  for (const { name, required } of spec.values()) {
101
136
  if (required && !passed.has(name.toLowerCase())) {
@@ -110,6 +145,7 @@ export function deriveRequirements(callers, readReusable) {
110
145
  secrets: [...secrets.values()],
111
146
  variables: deriveVariables(callers),
112
147
  problems,
148
+ noCredential,
113
149
  unsupported: unreadable(callers),
114
150
  };
115
151
  }
@@ -133,6 +169,62 @@ function listNames(github, repo, kind, ownerType) {
133
169
  return { names: new Set([...names].map((n) => n.toUpperCase())), orgNote };
134
170
  }
135
171
 
172
+ const isModelCredential = (x) =>
173
+ !x.required && x.uses.every(({ input }) => MODEL_INPUTS.has(input));
174
+
175
+ /**
176
+ * Each job that passes a Claude Code secret, with what it passes, the preferred
177
+ * input of its workflow first.
178
+ */
179
+ function claudeCodeJobs(secrets) {
180
+ const jobs = new Map();
181
+ for (const secret of secrets) {
182
+ for (const { job, file, input } of secret.uses) {
183
+ if (!CLAUDE_CODE_INPUTS.includes(input)) continue;
184
+ if (!jobs.has(job)) jobs.set(job, { file, passed: [] });
185
+ jobs.get(job).passed.push({ secret, rank: preferred(file).indexOf(input) });
186
+ }
187
+ }
188
+ for (const { passed } of jobs.values()) passed.sort((a, b) => a.rank - b.rank);
189
+ return jobs;
190
+ }
191
+
192
+ /** Jobs grouped under the secrets a message names: those that need the same ones together. */
193
+ function byNames(entries, joiner) {
194
+ const groups = new Map();
195
+ for (const { job, secrets } of entries) {
196
+ const names = secrets.map((x) => x.names.join(" or ")).join(joiner);
197
+ if (!groups.has(names)) groups.set(names, { names, first: secrets[0], where: [] });
198
+ groups.get(names).where.push(job);
199
+ }
200
+ return [...groups.values()];
201
+ }
202
+
203
+ /**
204
+ * The jobs left with no model credential: for each, the secrets that would give
205
+ * `claude-code`, the one harness that runs a Stage, its credential.
206
+ */
207
+ function jobsWithoutCredential(jobs, isSet) {
208
+ const missing = [];
209
+ for (const [job, { passed }] of jobs) {
210
+ // A required one is reported as missing on its own.
211
+ if (passed.some(({ secret }) => secret.required || isSet(secret))) continue;
212
+ missing.push({ job, secrets: passed.map((x) => x.secret) });
213
+ }
214
+ return byNames(missing, " or ");
215
+ }
216
+
217
+ /** The Deep scan jobs with more than one model credential set, which fail every run. */
218
+ function jobsWithTwoCredentials(jobs, isSet) {
219
+ const doubled = [];
220
+ for (const [job, { file, passed }] of jobs) {
221
+ if (file !== DEEP_SCAN_REUSABLE) continue;
222
+ const set = passed.map((x) => x.secret).filter(isSet);
223
+ if (set.length > 1) doubled.push({ job, secrets: set });
224
+ }
225
+ return byNames(doubled, " and ");
226
+ }
227
+
136
228
  /** `gh secret set` / `gh variable set` for a valid name, or a by-hand note. */
137
229
  function setCommand(kind, name, repo, extra = []) {
138
230
  if (!NAME_PATTERN.test(name)) return { note: byHand(`${kind} named`, name) };
@@ -149,7 +241,7 @@ function splitFixes(items) {
149
241
  export function checkSecrets({ github, repo, ownerType, requirements }) {
150
242
  const ID = "secrets";
151
243
  const TITLE = "Secrets the Callers pass are set";
152
- const { problems, unsupported = [] } = requirements;
244
+ const { problems, noCredential = [], unsupported = [] } = requirements;
153
245
  let listed;
154
246
  try {
155
247
  listed = listNames(github, repo, "secret", ownerType);
@@ -170,36 +262,58 @@ export function checkSecrets({ github, repo, ownerType, requirements }) {
170
262
  }
171
263
  const isSet = (x) => x.names.some((n) => listed.names.has(n.toUpperCase()));
172
264
  const missingRequired = requirements.secrets.filter((x) => x.required && !isSet(x));
173
- const missingOptional = requirements.secrets.filter((x) => !x.required && !isSet(x));
265
+ const missingOptional = requirements.secrets.filter(
266
+ (x) => !x.required && !isModelCredential(x) && !isSet(x),
267
+ );
268
+ const claudeCode = claudeCodeJobs(requirements.secrets);
269
+ const uncredentialed = jobsWithoutCredential(claudeCode, isSet);
270
+ const doubled = jobsWithTwoCredentials(claudeCode, isSet);
174
271
  const describe = (x) => `${x.names.join(" or ")} (${x.where.join(", ")})`;
175
272
  // No --body: gh prompts for the value, so it never lands in shell history.
273
+ const wanted = [...missingRequired, ...uncredentialed.map((x) => x.first), ...missingOptional];
176
274
  const { fix, notes } = splitFixes(
177
- [...missingRequired, ...missingOptional].map((x) => setCommand("secret", x.names[0], repo)),
275
+ [...new Set(wanted.map((x) => x.names[0]))].map((name) => setCommand("secret", name, repo)),
178
276
  );
179
277
  const details = [
180
278
  ...problems,
279
+ ...doubled.map(
280
+ (x) =>
281
+ `two model credentials set: ${x.names} (${x.where.join(", ")}); every run fails. ` +
282
+ "Delete one: the API key is the supported path.",
283
+ ),
181
284
  ...missingRequired.map((x) => `required, not set: ${describe(x)}`),
285
+ ...uncredentialed.map(
286
+ (x) =>
287
+ `no model credential set: ${x.names} (${x.where.join(", ")}); the run fails without one`,
288
+ ),
182
289
  ...missingOptional.map((x) => `optional, not set: ${describe(x)}`),
290
+ ...noCredential,
183
291
  ...unsupported,
184
292
  ...notes,
185
293
  ];
186
- if (listed.orgNote && (missingRequired.length || missingOptional.length)) {
294
+ if (listed.orgNote && wanted.length) {
187
295
  details.push(listed.orgNote);
188
296
  }
189
- if (missingRequired.length || problems.length) {
190
- const summary = missingRequired.length
191
- ? `${missingRequired.length} required secret(s) missing.`
192
- : `${problems.length} Caller problem(s) with secrets.`;
297
+ if (missingRequired.length || problems.length || doubled.length) {
298
+ const summary = [
299
+ missingRequired.length && `${missingRequired.length} required secret(s) missing.`,
300
+ doubled.length && "Two model credentials are set for the Deep scan.",
301
+ problems.length && `${problems.length} Caller problem(s) with secrets.`,
302
+ ]
303
+ .filter(Boolean)
304
+ .join(" ");
193
305
  return result(ID, TITLE, "fail", summary, { details, fix });
194
306
  }
195
- if (missingOptional.length) {
196
- return result(
197
- ID,
198
- TITLE,
199
- "warn",
200
- `${missingOptional.length} optional secret(s) referenced but not set.`,
201
- { details, fix },
202
- );
307
+ const bare = uncredentialed.length + noCredential.length;
308
+ if (bare || missingOptional.length) {
309
+ const summary = [
310
+ bare && "Some jobs have no model credential.",
311
+ missingOptional.length &&
312
+ `${missingOptional.length} optional secret(s) referenced but not set.`,
313
+ ]
314
+ .filter(Boolean)
315
+ .join(" ");
316
+ return result(ID, TITLE, "warn", summary, { details, fix });
203
317
  }
204
318
  if (unsupported.length) {
205
319
  return result(
@@ -210,17 +324,14 @@ export function checkSecrets({ github, repo, ownerType, requirements }) {
210
324
  { details: unsupported },
211
325
  );
212
326
  }
213
- return result(
214
- ID,
215
- TITLE,
216
- "pass",
217
- `All ${requirements.secrets.length} secret(s) the Callers pass are set.`,
218
- );
327
+ return result(ID, TITLE, "pass", "Every secret the Callers need is set.");
219
328
  }
220
329
 
221
330
  /**
222
- * Variables ADR 0009 renamed, old name to new. The Callers have no fallback to
223
- * an old name, so one still set does nothing once the Caller reads the new one.
331
+ * Variables the kit renamed (ADR 0009, then ADR 0022), old name to new: the
332
+ * Deprecation register's variable entries. A replacement may be an old name
333
+ * itself. The Callers have no fallback to an old name, so one still set does
334
+ * nothing once the Caller reads a newer one.
224
335
  */
225
336
  export const RENAMED_VARIABLES = {
226
337
  CLAUDE_PIPELINE_ENABLED: "CLAUDE_AGENT_FLOW_ENABLED",
@@ -229,8 +340,37 @@ export const RENAMED_VARIABLES = {
229
340
  CLAUDE_MODEL_REVIEW: "CLAUDE_REVIEW_MODEL",
230
341
  CLAUDE_MODEL_REVIEW_RESPONSE: "CLAUDE_REVIEW_RESPONSE_MODEL",
231
342
  CLAUDE_MODEL_AUDIT: "CLAUDE_SECURITY_AUDIT_MODEL",
343
+ CLAUDE_AGENT_FLOW_ENABLED: "AGENT_KIT_AGENT_FLOW_ENABLED",
344
+ CLAUDE_SECURITY_AUDIT_ENABLED: "AGENT_KIT_SECURITY_AUDIT_ENABLED",
345
+ CLAUDE_REVIEW_RESPONSE_ENABLED: "AGENT_KIT_REVIEW_RESPONSE_ENABLED",
346
+ CLAUDE_DEEP_SCAN_ENABLED: "AGENT_KIT_DEEP_SCAN_ENABLED",
347
+ CLAUDE_PLAN_ENABLED: "AGENT_KIT_PLAN_ENABLED",
348
+ CLAUDE_IMPLEMENT_ENABLED: "AGENT_KIT_IMPLEMENT_ENABLED",
349
+ CLAUDE_REVIEW_ENABLED: "AGENT_KIT_REVIEW_ENABLED",
350
+ CLAUDE_MODEL: "AGENT_KIT_MODEL",
351
+ CLAUDE_EFFORT: "AGENT_KIT_EFFORT",
352
+ CLAUDE_PLAN_MODEL: "AGENT_KIT_PLAN_MODEL",
353
+ CLAUDE_PLAN_EFFORT: "AGENT_KIT_PLAN_EFFORT",
354
+ CLAUDE_IMPLEMENT_MODEL: "AGENT_KIT_IMPLEMENT_MODEL",
355
+ CLAUDE_IMPLEMENT_EFFORT: "AGENT_KIT_IMPLEMENT_EFFORT",
356
+ CLAUDE_REVIEW_MODEL: "AGENT_KIT_REVIEW_MODEL",
357
+ CLAUDE_REVIEW_EFFORT: "AGENT_KIT_REVIEW_EFFORT",
358
+ CLAUDE_REVIEW_RESPONSE_MODEL: "AGENT_KIT_REVIEW_RESPONSE_MODEL",
359
+ CLAUDE_REVIEW_RESPONSE_EFFORT: "AGENT_KIT_REVIEW_RESPONSE_EFFORT",
360
+ CLAUDE_SECURITY_AUDIT_MODEL: "AGENT_KIT_SECURITY_AUDIT_MODEL",
361
+ CLAUDE_SECURITY_AUDIT_EFFORT: "AGENT_KIT_SECURITY_AUDIT_EFFORT",
362
+ CLAUDE_DEEP_SCAN_MODEL: "AGENT_KIT_DEEP_SCAN_MODEL",
363
+ CLAUDE_DEEP_SCAN_EFFORT: "AGENT_KIT_DEEP_SCAN_EFFORT",
364
+ CLAUDE_REVIEW_RESPONSE_MODE: "AGENT_KIT_REVIEW_RESPONSE_MODE",
232
365
  };
233
366
 
367
+ /** The first name `read` holds among those `oldName` was renamed to, or null. */
368
+ function replacementRead(oldName, read) {
369
+ let name = RENAMED_VARIABLES[oldName];
370
+ while (name && !read.has(name)) name = RENAMED_VARIABLES[name];
371
+ return name ?? null;
372
+ }
373
+
234
374
  const killSwitch = (name) => /_ENABLED$/.test(name);
235
375
 
236
376
  export function checkVariables({ github, repo, ownerType, requirements }) {
@@ -247,9 +387,11 @@ export function checkVariables({ github, repo, ownerType, requirements }) {
247
387
  const missing = required.filter((v) => !isSet(v.name));
248
388
  // An old name still set while a Caller reads its replacement: the value is ignored.
249
389
  const read = new Map(requirements.variables.map((v) => [v.name.toUpperCase(), v]));
250
- const renamed = Object.entries(RENAMED_VARIABLES)
251
- .filter(([oldName, newName]) => isSet(oldName) && read.has(newName))
252
- .map(([oldName, newName]) => ({ oldName, newName, v: read.get(newName) }));
390
+ const renamed = Object.keys(RENAMED_VARIABLES)
391
+ .filter(isSet)
392
+ .map((oldName) => ({ oldName, newName: replacementRead(oldName, read) }))
393
+ .filter(({ newName }) => newName)
394
+ .map((r) => ({ ...r, v: read.get(r.newName), stillRead: read.get(r.oldName) }));
253
395
  if (missing.length === 0 && renamed.length === 0) {
254
396
  return result(ID, TITLE, "pass", `All ${required.length} required variable(s) are set.`);
255
397
  }
@@ -261,29 +403,45 @@ export function checkVariables({ github, repo, ownerType, requirements }) {
261
403
  ? " — the Kill switch: the flow never runs until it is set to true"
262
404
  : ""),
263
405
  ),
264
- ...renamed.map(
265
- ({ oldName, newName, v }) =>
266
- `renamed: ${oldName} is still set, but the Callers read ${newName} (${v.where.join(", ")}). ` +
267
- `${oldName} is ignored: ` +
406
+ ...renamed.map(({ oldName, newName, v, stillRead }) => {
407
+ const start = `renamed: ${oldName} is still set, but ${newName} replaces it (${v.where.join(", ")}). `;
408
+ // Callers part-way through an upgrade: the old name still does something.
409
+ if (stillRead) {
410
+ return (
411
+ `${start}${oldName} is still read by ${stillRead.where.join(", ")}: ` +
412
+ (isSet(newName) ? "" : `set ${newName} to its value, and `) +
413
+ `delete ${oldName} once no Caller reads it.`
414
+ );
415
+ }
416
+ return (
417
+ `${start}${oldName} is ignored: ` +
268
418
  (isSet(newName)
269
419
  ? `${newName} is set too, so delete ${oldName}.`
270
- : `set ${newName} to its value, then delete ${oldName}.`),
271
- ),
420
+ : `set ${newName} to its value, then delete ${oldName}.`)
421
+ );
422
+ }),
272
423
  ];
273
424
  if (listed.orgNote && missing.length) details.push(listed.orgNote);
274
- // The Kill switch takes true; for anything else, gh prompts for the value.
425
+ // A missing Kill switch takes true; for anything else, gh prompts for the
426
+ // value: a renamed Stage switch may have been set to false.
427
+ const turnsOn = new Set(missing.map((v) => v.name));
275
428
  const toSet = [
276
429
  ...missing.map((v) => v.name),
277
430
  ...renamed.filter((r) => !isSet(r.newName)).map((r) => r.newName),
278
431
  ].filter((name, i, all) => all.indexOf(name) === i);
279
432
  const { fix, notes } = splitFixes(
280
433
  toSet.map((name) =>
281
- setCommand("variable", name, repo, killSwitch(name) ? ["--body", "true"] : []),
434
+ setCommand(
435
+ "variable",
436
+ name,
437
+ repo,
438
+ turnsOn.has(name) && killSwitch(name) ? ["--body", "true"] : [],
439
+ ),
282
440
  ),
283
441
  );
284
442
  // Each old name goes last, once its replacement has a value: deleting first
285
443
  // would lose the value before it is copied. The old names are the kit's own.
286
- for (const { oldName } of renamed) {
444
+ for (const { oldName } of renamed.filter((r) => !r.stillRead)) {
287
445
  fix.push(command("gh", "variable", "delete", oldName, "--repo", repo));
288
446
  }
289
447
  if (missing.length) {
package/src/cli.mjs CHANGED
@@ -121,6 +121,12 @@ Options for deep-scan:
121
121
  such as your fix branch. The recipe, the skill
122
122
  and the Threat pack still come from the default
123
123
  branch.
124
+ --proving-run Run on a harness whose Support Level for the Deep
125
+ scan is below tried, to record the evidence that
126
+ raises it (a Proving run, marked in the output
127
+ and the run summary). Without it such a run is
128
+ refused. It relaxes nothing else, and the
129
+ reusable workflows never pass it.
124
130
  In GitHub Actions (GITHUB_ACTIONS=true) deep-scan keeps the Public-log
125
131
  rule: it prints nothing the scan shaped (Claude Code's error output, the
126
132
  model proxy's refusals), since the Actions log is world-readable.
@@ -165,6 +171,7 @@ const COMMAND_OPTIONS = {
165
171
  "report",
166
172
  "verify",
167
173
  "ref",
174
+ "proving-run",
168
175
  ],
169
176
  };
170
177
 
@@ -230,6 +237,7 @@ export async function main(argv, io) {
230
237
  effort: { type: "string" },
231
238
  report: { type: "string" },
232
239
  ref: { type: "string" },
240
+ "proving-run": { type: "boolean" },
233
241
  yes: { type: "boolean", short: "y" },
234
242
  force: { type: "boolean" },
235
243
  help: { type: "boolean", short: "h" },
@@ -309,6 +317,7 @@ export async function main(argv, io) {
309
317
  reportPath: values.report,
310
318
  verifyPath: values.verify,
311
319
  ref: values.ref,
320
+ provingRun: Boolean(values["proving-run"]),
312
321
  limitFlags: {
313
322
  "setup-minutes": values["setup-minutes"],
314
323
  "scan-minutes": values["scan-minutes"],
@@ -1,30 +1,18 @@
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/claude-code.mjs, ADR 0027); this
10
+ // module runs that plan.
23
11
 
24
12
  import { firstLine } from "../exec.mjs";
13
+ import { claudeCode } from "../harness/claude-code.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";
28
16
 
29
17
  /** Where a Consumer's security-audit skill lives, as Agent-kit installs it. */
30
18
  export const SKILL_DIR = ".claude/skills/security-audit";
@@ -38,20 +26,51 @@ export const DEFAULT_THREAT_PACK = Object.freeze({
38
26
  findingsLedger: ".security/findings-ledger.md",
39
27
  });
40
28
 
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"]);
29
+ export { TOOLS as AGENT_TOOLS, WEB_TOOLS } from "../harness/claude-code.mjs";
30
+
31
+ /** Where the brief goes in the sandbox: the launcher's, outside /workspace. */
32
+ export const BRIEF_PATH = "/agent-kit/in/brief.md";
33
+
34
+ /** The launcher's own folder in the sandbox, outside /workspace. */
35
+ const KIT_DIR = "/agent-kit";
36
+ const LOGS_DIR = `${KIT_DIR}/logs`;
44
37
 
45
38
  /**
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.
39
+ * The harness's launch plan for a Deep scan. Without a `baseUrl` (before the
40
+ * model route is open) its launch is not yet one to run; its identity and
41
+ * install layer are.
42
+ * @param {{ baseUrl?: string, maxTurns?: number, model?: string, effort?: string, kind?: "api-key" | "subscription", callerKey?: string }} [opts]
43
+ * `model` is a plain model id and `effort` an effort level, both checked by
44
+ * the launcher. `kind` is the credential's (default an API key).
45
+ * `callerKey` is the run's (callerKeyFor): the agent holds it in place of
46
+ * the credential.
50
47
  */
51
- export const TURNS_MARKER = "agent-kit-deep-scan: Claude Code reached its turn limit";
48
+ export function agentPlan({ baseUrl, maxTurns, model, effort, kind, callerKey } = {}) {
49
+ return claudeCode({
50
+ stage: "deep-scan",
51
+ proxyUrl: baseUrl,
52
+ briefPath: BRIEF_PATH,
53
+ kitDir: KIT_DIR,
54
+ maxTurns,
55
+ model,
56
+ effort,
57
+ credentialKind: kind,
58
+ callerKey,
59
+ });
60
+ }
52
61
 
53
- /** Where the brief goes in the sandbox: the launcher's, outside /workspace. */
54
- export const BRIEF_PATH = "/agent-kit/in/brief.md";
62
+ /**
63
+ * What the agent step's script prints when the harness stopped at its turn
64
+ * limit: a fixed line, so nothing of the harness's own output leaves the
65
+ * sandbox. It is printed on the plan's marker in the harness's error output,
66
+ * never on its answer, which the agent writes.
67
+ * @param {import("../harness/claude-code.mjs").LaunchPlan} plan
68
+ */
69
+ export const turnsMarker = (plan) =>
70
+ `agent-kit-deep-scan: ${plan.identity.displayName} reached its turn limit`;
71
+
72
+ /** The Claude Code plan's line. */
73
+ export const TURNS_MARKER = turnsMarker(agentPlan());
55
74
 
56
75
  const MAX_HANDED_BYTES = 512 * 1024;
57
76
  const CALLER_USES = /(^|\/)\.github\/workflows\/security-audit-reusable\.ya?ml(@\S+)?$/;
@@ -305,101 +324,43 @@ export function threatPackAndRecipe({ handIn, recipePath, recipeText }) {
305
324
  }
306
325
 
307
326
  /**
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]
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
331
+ * 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.
314
334
  */
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
333
- */
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
335
+ export function agentScript({ report, workspace, plan, ...request }) {
336
+ 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;
343
+ const folderOf = (path) => path.slice(0, path.lastIndexOf("/"));
344
+ const folders = [...new Set([folderOf(report), logs, folderOf(transcript.path)])];
345
+ const stdin = launch.stdin ? ` < ${shQuote(launch.stdin.file)}` : "";
346
+ // The harness's error output reaches the launcher through a pipe, as it
390
347
  // happens, and a copy goes to agent.err for the turn check. The agent can
391
348
  // write that file (and agent.status), so the file is only searched, never
392
349
  // printed, and a planted status that is not a number counts as a failure.
393
350
  return [
394
351
  "set -eu",
395
- `mkdir -p ${outDir} ${logs}`,
352
+ `mkdir -p ${folders.join(" ")}`,
396
353
  `cd ${workspace}`,
397
354
  `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`,
355
+ `{ ${launch.argv.map(shQuote).join(" ")}${stdin} 2>&1 > ${shQuote(transcript.path)} || echo "$?" > ${logs}/agent.status; } | tee ${logs}/agent.err >&2`,
399
356
  "status=0",
400
357
  `if [ -s ${logs}/agent.status ]; then status=$(cat ${logs}/agent.status); fi`,
401
358
  `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`,
359
+ ...(stops.turnCap
360
+ ? [
361
+ `if grep -q ${shQuote(stops.turnCap.stderrPattern)} ${logs}/agent.err; then echo ${shQuote(turnsMarker(launched))}; fi`,
362
+ ]
363
+ : []),
403
364
  'exit "$status"',
404
365
  ].join("\n");
405
366
  }