@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.1

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 (72) hide show
  1. package/dist/agent/channel-runner.d.ts +3 -0
  2. package/dist/agent/channel-runner.js +9 -0
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +9 -0
  5. package/dist/agent/job-manager.d.ts +5 -3
  6. package/dist/agent/job-manager.js +8 -5
  7. package/dist/agent/prompt/sections.js +46 -7
  8. package/dist/agent/prompt/types.d.ts +9 -0
  9. package/dist/agent/session-events.js +7 -42
  10. package/dist/agent/types.d.ts +4 -0
  11. package/dist/playbooks/agent-delegation.md +46 -21
  12. package/dist/playbooks/runtime-orientation.md +2 -2
  13. package/dist/runtime/bootstrap.js +45 -1
  14. package/dist/runtime/dingtalk.d.ts +1 -0
  15. package/dist/runtime/dingtalk.js +3 -0
  16. package/dist/runtime/store.d.ts +7 -0
  17. package/dist/runtime/subagent-commands.d.ts +15 -0
  18. package/dist/runtime/subagent-commands.js +122 -0
  19. package/dist/runtime/task-commands.js +5 -1
  20. package/dist/security/logger.js +3 -1
  21. package/dist/security/types.d.ts +17 -1
  22. package/dist/shared/host-process.d.ts +15 -0
  23. package/dist/shared/host-process.js +40 -0
  24. package/dist/shared/shell-words.d.ts +9 -0
  25. package/dist/shared/shell-words.js +52 -0
  26. package/dist/subagents/discovery.d.ts +42 -1
  27. package/dist/subagents/discovery.js +302 -69
  28. package/dist/subagents/external/claude-code.d.ts +2 -0
  29. package/dist/subagents/external/claude-code.js +152 -0
  30. package/dist/subagents/external/codex-cli.d.ts +2 -0
  31. package/dist/subagents/external/codex-cli.js +133 -0
  32. package/dist/subagents/external/exec.d.ts +2 -0
  33. package/dist/subagents/external/exec.js +38 -0
  34. package/dist/subagents/external/harness.d.ts +102 -0
  35. package/dist/subagents/external/harness.js +76 -0
  36. package/dist/subagents/external/registry.d.ts +2 -0
  37. package/dist/subagents/external/registry.js +11 -0
  38. package/dist/subagents/external/run.d.ts +39 -0
  39. package/dist/subagents/external/run.js +220 -0
  40. package/dist/subagents/runs.d.ts +216 -0
  41. package/dist/subagents/runs.js +522 -0
  42. package/dist/subagents/tool.d.ts +8 -0
  43. package/dist/subagents/tool.js +350 -124
  44. package/dist/subagents/workspace-lease.d.ts +36 -0
  45. package/dist/subagents/workspace-lease.js +48 -0
  46. package/dist/tasks/artifact-subject.js +50 -2
  47. package/dist/tasks/verification.d.ts +8 -0
  48. package/dist/tasks/verification.js +10 -2
  49. package/dist/tools/index.d.ts +1 -1
  50. package/dist/tools/index.js +10 -1
  51. package/dist/tools/registry.js +1 -0
  52. package/dist/tools/subagent-manage.d.ts +18 -0
  53. package/dist/tools/subagent-manage.js +141 -0
  54. package/dist/tools/tool-details.d.ts +1 -1
  55. package/dist/tui/app.js +2 -0
  56. package/dist/tui/commands.d.ts +1 -0
  57. package/dist/tui/commands.js +2 -0
  58. package/dist/tui/turn-controller.d.ts +1 -0
  59. package/dist/tui/turn-controller.js +1 -0
  60. package/dist/usage/ledger.d.ts +6 -0
  61. package/examples/sub-agents/README.md +59 -12
  62. package/examples/sub-agents/builder-hard.md +45 -0
  63. package/examples/sub-agents/builder.md +41 -0
  64. package/examples/sub-agents/documenter.md +53 -0
  65. package/examples/sub-agents/log-sifter.md +43 -0
  66. package/examples/sub-agents/planner.md +42 -0
  67. package/examples/sub-agents/reviewer.md +33 -39
  68. package/examples/sub-agents/scout.md +31 -0
  69. package/examples/sub-agents/verifier.md +29 -36
  70. package/examples/sub-agents/worker.md +36 -0
  71. package/package.json +1 -1
  72. package/examples/sub-agents/researcher.md +0 -41
@@ -1,8 +1,11 @@
1
+ import { existsSync as existsSyncFs } from "node:fs";
2
+ import { join as joinPath, delimiter as pathDelimiter } from "node:path";
1
3
  import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
2
4
  import { existsSync, readdirSync, readFileSync } from "fs";
3
5
  import { join } from "path";
4
6
  import { findExactModelReferenceMatch, formatModelReference } from "../models/utils.js";
5
7
  import { SUB_AGENTS_DIR_NAME } from "../paths.js";
8
+ import { splitShellWords } from "../shared/shell-words.js";
6
9
  import { errorMessage } from "../shared/text-utils.js";
7
10
  const ALLOWED_SUB_AGENT_TOOLS = ["read", "grep", "bash", "edit", "write", "web_search", "web_fetch"];
8
11
  const DEFAULT_SUB_AGENT_TOOLS = ["read", "bash"];
@@ -10,11 +13,18 @@ const DEFAULT_MAX_TURNS = 24;
10
13
  const DEFAULT_MAX_TOOL_CALLS = 48;
11
14
  const DEFAULT_MAX_WALL_TIME_SEC = 300;
12
15
  const DEFAULT_BASH_TIMEOUT_SEC = 120;
16
+ /** External runs have no turn/tool-call budget (D5); wall time is their only lever. */
17
+ const DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC = 1800;
13
18
  const MAX_SUB_AGENT_TASK_CHARS = 12000;
14
19
  const MAX_SUB_AGENT_SYSTEM_PROMPT_CHARS = 16000;
15
20
  const ALLOWED_CONTEXT_MODES = ["isolated", "contextual"];
16
21
  const ALLOWED_MEMORY_MODES = ["none", "session", "relevant"];
17
- const ALLOWED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
22
+ // "max" is a real SDK ThinkingLevel; pipiclaw's own whitelist previously omitted it (spec 040, D4).
23
+ const ALLOWED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
24
+ const ALLOWED_RUNTIMES = ["internal", "external"];
25
+ const ALLOWED_HARNESSES = ["claude-code", "codex-cli", "exec"];
26
+ const ALLOWED_WORKLOADS = ["light", "heavy"];
27
+ const ALLOWED_MUTATES = ["read", "write"];
18
28
  /**
19
29
  * Execution budgets as a single named tuple. Frontmatter keeps the four numeric knobs
20
30
  * (a human editing a config file has grounds to pick numbers); the invocation surface
@@ -58,6 +68,25 @@ function validateSubAgentSystemPrompt(systemPrompt, label) {
58
68
  export function getSubAgentsDir(workspaceDir) {
59
69
  return join(workspaceDir, SUB_AGENTS_DIR_NAME);
60
70
  }
71
+ /**
72
+ * Deny `write`/`edit` on `workspace/sub-agents/` itself (spec 040, D8.1).
73
+ *
74
+ * `DEFAULT_SECURITY_CONFIG.writeAllow` is empty and `pathAllowedByDefaults` permits the whole
75
+ * workspace, so without this the main agent (and a sub-agent it dispatches) can write a
76
+ * `runtime: external` role file with an arbitrary `command` and then invoke it — a command-guard
77
+ * bypass wearing a delegation costume. This closes the `write`/`edit` path; it does not close
78
+ * `bash` (same known gap as the memory-write-deny it mirrors — see the spec's risk list). The
79
+ * role directory hot-reloads on purpose (P4): this is the only gate, and it must stay cheap.
80
+ */
81
+ export function withSubAgentsDirWriteDeny(config, workspaceDir) {
82
+ return {
83
+ ...config,
84
+ pathGuard: {
85
+ ...config.pathGuard,
86
+ writeDeny: [...config.pathGuard.writeDeny, getSubAgentsDir(workspaceDir)],
87
+ },
88
+ };
89
+ }
61
90
  function readOptionalTrimmedString(value) {
62
91
  if (typeof value !== "string") {
63
92
  return undefined;
@@ -231,6 +260,247 @@ function resolveModelReference(modelRef, availableModels) {
231
260
  }
232
261
  return { error: `Model reference "${modelRef}" was not found among available models.` };
233
262
  }
263
+ function parseRuntime(raw) {
264
+ const normalized = readOptionalTrimmedString(raw);
265
+ if (!normalized)
266
+ return { value: "internal" };
267
+ if (ALLOWED_RUNTIMES.includes(normalized)) {
268
+ return { value: normalized };
269
+ }
270
+ return {
271
+ value: "internal",
272
+ error: `Unknown runtime "${normalized}". Allowed values: ${ALLOWED_RUNTIMES.join(", ")}`,
273
+ };
274
+ }
275
+ function parseHarness(raw) {
276
+ const normalized = readOptionalTrimmedString(raw);
277
+ if (!normalized)
278
+ return {};
279
+ if (ALLOWED_HARNESSES.includes(normalized)) {
280
+ return { value: normalized };
281
+ }
282
+ return { error: `Unknown harness "${normalized}". Allowed values: ${ALLOWED_HARNESSES.join(", ")}` };
283
+ }
284
+ function parseWorkload(raw) {
285
+ const normalized = readOptionalTrimmedString(raw);
286
+ if (!normalized)
287
+ return {};
288
+ if (ALLOWED_WORKLOADS.includes(normalized)) {
289
+ return { value: normalized };
290
+ }
291
+ return { error: `Unknown workload "${normalized}". Allowed values: ${ALLOWED_WORKLOADS.join(", ")}` };
292
+ }
293
+ function parseMutates(raw) {
294
+ const normalized = readOptionalTrimmedString(raw);
295
+ if (!normalized)
296
+ return {};
297
+ if (ALLOWED_MUTATES.includes(normalized)) {
298
+ return { value: normalized };
299
+ }
300
+ return { error: `Unknown mutates "${normalized}". Allowed values: ${ALLOWED_MUTATES.join(", ")}` };
301
+ }
302
+ function parseBooleanField(raw, label) {
303
+ if (raw === undefined || raw === null)
304
+ return {};
305
+ if (typeof raw === "boolean")
306
+ return { value: raw };
307
+ if (raw === "true")
308
+ return { value: true };
309
+ if (raw === "false")
310
+ return { value: false };
311
+ return { error: `Invalid "${label}" frontmatter: expected true or false` };
312
+ }
313
+ function parseEnvMap(raw) {
314
+ if (raw === undefined || raw === null)
315
+ return {};
316
+ if (typeof raw !== "object" || Array.isArray(raw)) {
317
+ return { error: 'Invalid "env" frontmatter: expected a mapping of string to string' };
318
+ }
319
+ const value = {};
320
+ for (const [key, val] of Object.entries(raw)) {
321
+ if (typeof val !== "string") {
322
+ return { error: `Invalid "env.${key}" frontmatter: expected a string` };
323
+ }
324
+ value[key] = val;
325
+ }
326
+ return { value };
327
+ }
328
+ /** First whitespace-delimited token of `command` (its executable), respecting quotes (D4). */
329
+ function firstCommandToken(command) {
330
+ return splitShellWords(command)[0];
331
+ }
332
+ /** Existence check only (no exec-bit probe): cheap, spawn-free, good enough for "is it installed". */
333
+ function isExecutableAvailable(token) {
334
+ if (token.includes("/")) {
335
+ return existsSyncFs(token);
336
+ }
337
+ const pathEnv = process.env.PATH ?? "";
338
+ return pathEnv.split(pathDelimiter).some((dir) => dir && existsSyncFs(joinPath(dir, token)));
339
+ }
340
+ /** Fields that only mean something for one runtime; present under the other, they are rejected
341
+ * outright rather than silently ignored (spec 040, D5 — "对某种 runtime 无意义的字段一律驳回"). */
342
+ const FIELDS_REJECTED_FOR_INTERNAL = ["harness", "command"];
343
+ const FIELDS_REJECTED_FOR_EXTERNAL = ["tools", "maxTurns", "maxToolCalls", "bashTimeoutSec"];
344
+ function rejectedFieldNames(frontmatter, names) {
345
+ return names.filter((name) => frontmatter[name] !== undefined);
346
+ }
347
+ function inferMutatesFromTools(tools) {
348
+ return tools.includes("write") || tools.includes("edit") ? "write" : "read";
349
+ }
350
+ function parseInternalAgent(entryName, filePath, frontmatter, body, name, description, availableModels) {
351
+ const rejected = rejectedFieldNames(frontmatter, FIELDS_REJECTED_FOR_INTERNAL);
352
+ if (rejected.length > 0) {
353
+ return { warning: `${entryName}: field(s) ${rejected.join(", ")} are only valid for runtime: external` };
354
+ }
355
+ const toolParse = parseToolNames(frontmatter.tools);
356
+ if (toolParse.error)
357
+ return { warning: `${entryName}: ${toolParse.error}` };
358
+ const contextMode = parseContextMode(frontmatter.contextMode);
359
+ if (contextMode.error)
360
+ return { warning: `${entryName}: ${contextMode.error}` };
361
+ const memoryMode = parseMemoryMode(frontmatter.memory, contextMode.value);
362
+ if (memoryMode.error)
363
+ return { warning: `${entryName}: ${memoryMode.error}` };
364
+ const parsedPaths = parseStringList(frontmatter.paths, "paths");
365
+ if (parsedPaths.error)
366
+ return { warning: `${entryName}: ${parsedPaths.error}` };
367
+ const thinkingLevel = parseThinkingLevel(frontmatter.thinkingLevel);
368
+ if (thinkingLevel.error)
369
+ return { warning: `${entryName}: ${thinkingLevel.error}` };
370
+ const workload = parseWorkload(frontmatter.workload);
371
+ if (workload.error)
372
+ return { warning: `${entryName}: ${workload.error}` };
373
+ const mutates = parseMutates(frontmatter.mutates);
374
+ if (mutates.error)
375
+ return { warning: `${entryName}: ${mutates.error}` };
376
+ const maxTurns = parsePositiveInteger(frontmatter.maxTurns, DEFAULT_MAX_TURNS);
377
+ const maxToolCalls = parsePositiveInteger(frontmatter.maxToolCalls, DEFAULT_MAX_TOOL_CALLS);
378
+ const maxWallTimeSec = parsePositiveInteger(frontmatter.maxWallTimeSec, DEFAULT_MAX_WALL_TIME_SEC);
379
+ const bashTimeoutSec = parsePositiveInteger(frontmatter.bashTimeoutSec, DEFAULT_BASH_TIMEOUT_SEC);
380
+ const numericWarning = [maxTurns.warning, maxToolCalls.warning, maxWallTimeSec.warning, bashTimeoutSec.warning].find(Boolean);
381
+ // A malformed numeric field falls back to its default rather than dropping the whole role —
382
+ // but it is still reported, via the first warning found.
383
+ const modelRef = readOptionalTrimmedString(frontmatter.model);
384
+ let model;
385
+ if (modelRef) {
386
+ const resolved = resolveModelReference(modelRef, availableModels);
387
+ if (!resolved.model)
388
+ return { warning: `${entryName}: ${resolved.error}` };
389
+ model = resolved.model;
390
+ }
391
+ const trimmedBody = body.trim();
392
+ if (!trimmedBody)
393
+ return { warning: `${entryName}: empty system prompt body` };
394
+ const promptLengthError = validateSubAgentSystemPrompt(trimmedBody, "Sub-agent system prompt");
395
+ if (promptLengthError)
396
+ return { warning: `${entryName}: ${promptLengthError}` };
397
+ return {
398
+ warning: numericWarning ? `${entryName}: ${numericWarning}` : undefined,
399
+ agent: {
400
+ name,
401
+ description,
402
+ systemPrompt: trimmedBody,
403
+ tools: toolParse.tools,
404
+ model,
405
+ modelRef: modelRef || (model ? formatModelReference(model) : undefined),
406
+ maxTurns: maxTurns.value,
407
+ maxToolCalls: maxToolCalls.value,
408
+ maxWallTimeSec: maxWallTimeSec.value,
409
+ bashTimeoutSec: bashTimeoutSec.value,
410
+ contextMode: contextMode.value,
411
+ memory: memoryMode.value,
412
+ paths: parsedPaths.values,
413
+ thinkingLevel: thinkingLevel.value,
414
+ filePath,
415
+ source: "predefined",
416
+ runtime: "internal",
417
+ workload: workload.value ?? "light", // D11 default-by-runtime.
418
+ mutates: mutates.value ?? inferMutatesFromTools(toolParse.tools),
419
+ },
420
+ };
421
+ }
422
+ function parseExternalAgent(entryName, filePath, frontmatter, body, name, description) {
423
+ const rejected = rejectedFieldNames(frontmatter, FIELDS_REJECTED_FOR_EXTERNAL);
424
+ if (rejected.length > 0) {
425
+ return { warning: `${entryName}: field(s) ${rejected.join(", ")} are not valid for runtime: external` };
426
+ }
427
+ const harness = parseHarness(frontmatter.harness);
428
+ if (harness.error)
429
+ return { warning: `${entryName}: ${harness.error}` };
430
+ if (!harness.value)
431
+ return { warning: `${entryName}: runtime: external requires "harness"` };
432
+ const command = readOptionalTrimmedString(frontmatter.command);
433
+ if (!command)
434
+ return { warning: `${entryName}: runtime: external requires a non-empty "command"` };
435
+ const mutates = parseMutates(frontmatter.mutates);
436
+ if (mutates.error)
437
+ return { warning: `${entryName}: ${mutates.error}` };
438
+ if (!mutates.value)
439
+ return { warning: `${entryName}: runtime: external requires "mutates" (read or write)` };
440
+ const shell = parseBooleanField(frontmatter.shell, "shell");
441
+ if (shell.error)
442
+ return { warning: `${entryName}: ${shell.error}` };
443
+ const env = parseEnvMap(frontmatter.env);
444
+ if (env.error)
445
+ return { warning: `${entryName}: ${env.error}` };
446
+ const workload = parseWorkload(frontmatter.workload);
447
+ if (workload.error)
448
+ return { warning: `${entryName}: ${workload.error}` };
449
+ const thinkingLevel = parseThinkingLevel(frontmatter.thinkingLevel);
450
+ if (thinkingLevel.error)
451
+ return { warning: `${entryName}: ${thinkingLevel.error}` };
452
+ const parsedPaths = parseStringList(frontmatter.paths, "paths");
453
+ if (parsedPaths.error)
454
+ return { warning: `${entryName}: ${parsedPaths.error}` };
455
+ const contextMode = parseContextMode(frontmatter.contextMode);
456
+ if (contextMode.error)
457
+ return { warning: `${entryName}: ${contextMode.error}` };
458
+ const memoryMode = parseMemoryMode(frontmatter.memory, contextMode.value);
459
+ if (memoryMode.error)
460
+ return { warning: `${entryName}: ${memoryMode.error}` };
461
+ const maxWallTimeSec = parsePositiveInteger(frontmatter.maxWallTimeSec, DEFAULT_EXTERNAL_MAX_WALL_TIME_SEC);
462
+ const trimmedBody = body.trim();
463
+ if (!trimmedBody)
464
+ return { warning: `${entryName}: empty system prompt body` };
465
+ const promptLengthError = validateSubAgentSystemPrompt(trimmedBody, "Sub-agent system prompt");
466
+ if (promptLengthError)
467
+ return { warning: `${entryName}: ${promptLengthError}` };
468
+ // A missing binary never drops the role (that would silently push the model back onto
469
+ // internal delegation, exactly the failure mode this spec exists to close) — it is listed,
470
+ // marked unavailable, and only refuses at invocation time, with an installation hint.
471
+ const executable = firstCommandToken(command);
472
+ const unavailable = executable && !isExecutableAvailable(executable)
473
+ ? `executable "${executable}" was not found on PATH; install it or fix "command" in ${filePath}`
474
+ : undefined;
475
+ return {
476
+ agent: {
477
+ name,
478
+ description,
479
+ systemPrompt: trimmedBody,
480
+ tools: [],
481
+ modelRef: undefined,
482
+ externalModelRef: readOptionalTrimmedString(frontmatter.model),
483
+ maxTurns: DEFAULT_MAX_TURNS,
484
+ maxToolCalls: DEFAULT_MAX_TOOL_CALLS,
485
+ maxWallTimeSec: maxWallTimeSec.value,
486
+ bashTimeoutSec: DEFAULT_BASH_TIMEOUT_SEC,
487
+ contextMode: contextMode.value,
488
+ memory: memoryMode.value,
489
+ paths: parsedPaths.values,
490
+ thinkingLevel: thinkingLevel.value,
491
+ filePath,
492
+ source: "predefined",
493
+ runtime: "external",
494
+ harness: harness.value,
495
+ command,
496
+ shell: shell.value,
497
+ env: env.value,
498
+ workload: workload.value ?? "heavy", // D11 default-by-runtime.
499
+ mutates: mutates.value,
500
+ unavailable,
501
+ },
502
+ };
503
+ }
234
504
  /** Parses every `*.md` sub-agent definition in the user's workspace directory. */
235
505
  function loadAgentsFromDir(directory, availableModels) {
236
506
  if (!existsSync(directory)) {
@@ -243,6 +513,9 @@ function loadAgentsFromDir(directory, availableModels) {
243
513
  try {
244
514
  entries = readdirSync(directory, { withFileTypes: true })
245
515
  .filter((entry) => entry.name.endsWith(".md") && (entry.isFile() || entry.isSymbolicLink()))
516
+ // A README is documentation about the directory, not a role in it — a warning about its
517
+ // missing frontmatter is noise every time someone copies `examples/sub-agents/` wholesale.
518
+ .filter((entry) => entry.name.toLowerCase() !== "readme.md")
246
519
  .sort((a, b) => a.name.localeCompare(b.name));
247
520
  }
248
521
  catch (error) {
@@ -271,78 +544,25 @@ function loadAgentsFromDir(directory, availableModels) {
271
544
  }
272
545
  // Claim the name before later validation so a malformed duplicate cannot shadow a valid one.
273
546
  knownNames.add(name);
274
- const toolParse = parseToolNames(frontmatter.tools);
275
- if (toolParse.error) {
276
- warnings.push(`${entry.name}: ${toolParse.error}`);
277
- continue;
278
- }
279
- const contextMode = parseContextMode(frontmatter.contextMode);
280
- if (contextMode.error) {
281
- warnings.push(`${entry.name}: ${contextMode.error}`);
282
- continue;
283
- }
284
- const memoryMode = parseMemoryMode(frontmatter.memory, contextMode.value);
285
- if (memoryMode.error) {
286
- warnings.push(`${entry.name}: ${memoryMode.error}`);
547
+ // The working directory is a per-delegation decision (workingDirectory on the call), never
548
+ // a role default — a `cwd` default would let a model skip the thinking it must do every
549
+ // time (spec 040, D5), and would silently collide two parallel writers on one checkout.
550
+ if (frontmatter.cwd !== undefined) {
551
+ warnings.push(`${entry.name}: "cwd" is not a role field; pass workingDirectory on the delegation call instead`);
287
552
  continue;
288
553
  }
289
- const parsedPaths = parseStringList(frontmatter.paths, "paths");
290
- if (parsedPaths.error) {
291
- warnings.push(`${entry.name}: ${parsedPaths.error}`);
554
+ const runtimeParse = parseRuntime(frontmatter.runtime);
555
+ if (runtimeParse.error) {
556
+ warnings.push(`${entry.name}: ${runtimeParse.error}`);
292
557
  continue;
293
558
  }
294
- const thinkingLevel = parseThinkingLevel(frontmatter.thinkingLevel);
295
- if (thinkingLevel.error) {
296
- warnings.push(`${entry.name}: ${thinkingLevel.error}`);
297
- continue;
298
- }
299
- const maxTurns = parsePositiveInteger(frontmatter.maxTurns, DEFAULT_MAX_TURNS);
300
- const maxToolCalls = parsePositiveInteger(frontmatter.maxToolCalls, DEFAULT_MAX_TOOL_CALLS);
301
- const maxWallTimeSec = parsePositiveInteger(frontmatter.maxWallTimeSec, DEFAULT_MAX_WALL_TIME_SEC);
302
- const bashTimeoutSec = parsePositiveInteger(frontmatter.bashTimeoutSec, DEFAULT_BASH_TIMEOUT_SEC);
303
- for (const warning of [maxTurns.warning, maxToolCalls.warning, maxWallTimeSec.warning, bashTimeoutSec.warning]) {
304
- if (warning) {
305
- warnings.push(`${entry.name}: ${warning}`);
306
- }
307
- }
308
- const modelRef = readOptionalTrimmedString(frontmatter.model);
309
- let model;
310
- if (modelRef) {
311
- const resolved = resolveModelReference(modelRef, availableModels);
312
- if (!resolved.model) {
313
- warnings.push(`${entry.name}: ${resolved.error}`);
314
- continue;
315
- }
316
- model = resolved.model;
317
- }
318
- const trimmedBody = body.trim();
319
- if (!trimmedBody) {
320
- warnings.push(`${entry.name}: empty system prompt body`);
321
- continue;
322
- }
323
- const promptLengthError = validateSubAgentSystemPrompt(trimmedBody, "Sub-agent system prompt");
324
- if (promptLengthError) {
325
- warnings.push(`${entry.name}: ${promptLengthError}`);
326
- continue;
327
- }
328
- agents.push({
329
- name,
330
- description,
331
- systemPrompt: trimmedBody,
332
- tools: toolParse.tools,
333
- model,
334
- modelRef: modelRef || (model ? formatModelReference(model) : undefined),
335
- maxTurns: maxTurns.value,
336
- maxToolCalls: maxToolCalls.value,
337
- maxWallTimeSec: maxWallTimeSec.value,
338
- bashTimeoutSec: bashTimeoutSec.value,
339
- contextMode: contextMode.value,
340
- memory: memoryMode.value,
341
- paths: parsedPaths.values,
342
- thinkingLevel: thinkingLevel.value,
343
- filePath,
344
- source: "predefined",
345
- });
559
+ const parsed = runtimeParse.value === "internal"
560
+ ? parseInternalAgent(entry.name, filePath, frontmatter, body, name, description, availableModels)
561
+ : parseExternalAgent(entry.name, filePath, frontmatter, body, name, description);
562
+ if (parsed.warning)
563
+ warnings.push(parsed.warning);
564
+ if (parsed.agent)
565
+ agents.push(parsed.agent);
346
566
  }
347
567
  return { agents, warnings };
348
568
  }
@@ -363,6 +583,10 @@ subagentDefaultModelRef) {
363
583
  const available = predefinedAgents.length > 0 ? predefinedAgents.map((agent) => agent.name).join(", ") : "none";
364
584
  return { error: `Unknown sub-agent "${overrides.agent}". Available sub-agents: ${available}.` };
365
585
  }
586
+ // Listed, never dropped (spec 040, D5) — but refused here with the reason, not a fallback.
587
+ if (baseConfig?.unavailable) {
588
+ return { error: `Sub-agent "${baseConfig.name}" is currently unavailable: ${baseConfig.unavailable}` };
589
+ }
366
590
  if (!baseConfig && (!overrides.systemPrompt || !overrides.systemPrompt.trim())) {
367
591
  return { error: 'Provide either "agent" or "systemPrompt" to define the sub-agent.' };
368
592
  }
@@ -451,6 +675,15 @@ subagentDefaultModelRef) {
451
675
  thinkingLevel,
452
676
  filePath: baseConfig?.filePath,
453
677
  source: baseConfig ? "predefined" : "inline",
678
+ runtime: baseConfig?.runtime ?? "internal",
679
+ harness: baseConfig?.harness,
680
+ command: baseConfig?.command,
681
+ shell: baseConfig?.shell,
682
+ env: baseConfig?.env,
683
+ workload: baseConfig?.workload,
684
+ mutates: baseConfig?.mutates ?? inferMutatesFromTools(tools.tools),
685
+ externalModelRef: baseConfig?.externalModelRef,
686
+ unavailable: baseConfig?.unavailable,
454
687
  },
455
688
  };
456
689
  }
@@ -0,0 +1,2 @@
1
+ import { type ExternalHarness } from "./harness.js";
2
+ export declare const claudeCodeHarness: ExternalHarness;
@@ -0,0 +1,152 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { detectExistingFlags, expandPlaceholders, } from "./harness.js";
3
+ /**
4
+ * `claude-code` harness (spec 040, D3/D4). Same one-prompt-one-process model as codex-cli; the
5
+ * differences are argv shape and stdout schema.
6
+ *
7
+ * The `--session-id`-before-running approach (rather than parsing it out of the first `result`
8
+ * event) is a deliberate improvement flagged in the design doc's review: it means `resume` does
9
+ * not depend on the run having produced *any* successful output — a run that crashes on turn one
10
+ * is still resumable. `--input-format stream-json`, `--include-partial-messages`, and
11
+ * `--replay-user-messages` are deliberately not used: they exist for long-lived, bidirectional
12
+ * sessions (agentmux's use case), and D3 already reduced every harness to one prompt = one
13
+ * process, so none of those apply here.
14
+ *
15
+ * Event shapes are the design doc's D4 table, not a live-verified schema: same schema-drift risk
16
+ * as codex-cli, and `parseOutcome` is written the same way — degrade, never throw.
17
+ */
18
+ const THINKING_LEVEL_TO_CLAUDE_EFFORT = {
19
+ off: "low", // claude-code has no weaker level than "low" (D4 clamp table).
20
+ minimal: "low",
21
+ low: "low",
22
+ medium: "medium",
23
+ high: "high",
24
+ xhigh: "xhigh",
25
+ max: "max",
26
+ };
27
+ function toClaudeEffort(level) {
28
+ if (!level)
29
+ return undefined;
30
+ return THINKING_LEVEL_TO_CLAUDE_EFFORT[level] ?? level;
31
+ }
32
+ export const claudeCodeHarness = {
33
+ id: "claude-code",
34
+ buildInvocation(input) {
35
+ if (input.argv.length === 0) {
36
+ throw new Error("claude-code: command produced no argv tokens");
37
+ }
38
+ const [executable, ...rest] = input.argv;
39
+ const existing = detectExistingFlags(rest);
40
+ // D4's addendum table lists no auto-appended effort flag for claude-code — only $EFFORT
41
+ // expansion for a role author whose wrapper accepts one.
42
+ const effort = toClaudeEffort(input.thinkingLevel);
43
+ const { argv: expandedRest, used } = expandPlaceholders(rest, {
44
+ $MODEL: input.model,
45
+ $EFFORT: effort,
46
+ $PROMPT_FILE: input.promptFile,
47
+ $SYSTEM_PROMPT_FILE: input.systemPromptFile,
48
+ });
49
+ const args = [...expandedRest, "-p", "--output-format", "stream-json", "--verbose"];
50
+ if (!existing.model && input.model && !used.has("$MODEL")) {
51
+ args.push("--model", input.model);
52
+ }
53
+ if (!used.has("$SYSTEM_PROMPT_FILE")) {
54
+ args.push("--append-system-prompt-file", input.systemPromptFile);
55
+ }
56
+ let presetSessionId;
57
+ if (input.resumeSessionId) {
58
+ args.push("--resume", input.resumeSessionId);
59
+ }
60
+ else {
61
+ presetSessionId = randomUUID();
62
+ args.push("--session-id", presetSessionId);
63
+ }
64
+ const promptFiles = [input.systemPromptFile, ...(used.has("$PROMPT_FILE") ? [input.promptFile] : [])];
65
+ return { executable, args, resumable: true, promptFiles, presetSessionId };
66
+ },
67
+ parseOutcome(input) {
68
+ let finalText = "";
69
+ let sessionId;
70
+ let terminalSeen = false;
71
+ let protocolStatus = "absent";
72
+ let errorMessage;
73
+ let usage;
74
+ let usageKnown = false;
75
+ let costKnown = false;
76
+ let costTotal;
77
+ let parsedAnyLine = false;
78
+ for (const line of input.eventsText.split("\n")) {
79
+ const trimmed = line.trim();
80
+ if (!trimmed)
81
+ continue;
82
+ let event;
83
+ try {
84
+ event = JSON.parse(trimmed);
85
+ }
86
+ catch {
87
+ continue; // Tolerate a torn or non-JSON line.
88
+ }
89
+ if (typeof event !== "object" || event === null)
90
+ continue;
91
+ parsedAnyLine = true;
92
+ const record = event;
93
+ const sid = record.session_id;
94
+ if (typeof sid === "string")
95
+ sessionId = sid;
96
+ if (record.type === "result") {
97
+ terminalSeen = true;
98
+ const isError = record.is_error === true;
99
+ protocolStatus = isError ? "failed" : "completed";
100
+ if (typeof record.result === "string")
101
+ finalText = record.result;
102
+ if (isError) {
103
+ errorMessage =
104
+ typeof record.result === "string" && record.result
105
+ ? record.result
106
+ : typeof record.subtype === "string"
107
+ ? `claude-code reported ${record.subtype}`
108
+ : "claude-code reported an error result";
109
+ }
110
+ const cost = record.total_cost_usd;
111
+ if (typeof cost === "number") {
112
+ costTotal = cost;
113
+ costKnown = true;
114
+ }
115
+ const rawUsage = record.usage;
116
+ if (rawUsage) {
117
+ const inputTokens = Number(rawUsage.input_tokens ?? 0);
118
+ const outputTokens = Number(rawUsage.output_tokens ?? 0);
119
+ const cacheRead = Number(rawUsage.cache_read_input_tokens ?? 0);
120
+ const cacheWrite = Number(rawUsage.cache_creation_input_tokens ?? 0);
121
+ usage = {
122
+ input: inputTokens || 0,
123
+ output: outputTokens || 0,
124
+ cacheRead: cacheRead || 0,
125
+ cacheWrite: cacheWrite || 0,
126
+ total: (inputTokens || 0) + (outputTokens || 0) + (cacheRead || 0) + (cacheWrite || 0),
127
+ ...(costTotal !== undefined
128
+ ? { cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: costTotal } }
129
+ : {}),
130
+ };
131
+ usageKnown = true;
132
+ }
133
+ }
134
+ }
135
+ if (!parsedAnyLine && input.eventsText.trim()) {
136
+ protocolStatus = "unparsable";
137
+ }
138
+ return {
139
+ finalText,
140
+ terminalSeen,
141
+ protocolStatus,
142
+ exitCode: input.exitCode,
143
+ sessionId,
144
+ usage,
145
+ usageKnown,
146
+ costKnown,
147
+ outputTruncated: false,
148
+ stderrTail: input.stderrTail,
149
+ errorMessage,
150
+ };
151
+ },
152
+ };
@@ -0,0 +1,2 @@
1
+ import { type ExternalHarness } from "./harness.js";
2
+ export declare const codexCliHarness: ExternalHarness;