@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.2

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 (83) 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 +11 -3
  6. package/dist/agent/job-manager.js +63 -6
  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.d.ts +38 -0
  14. package/dist/runtime/bootstrap.js +167 -14
  15. package/dist/runtime/dingtalk.d.ts +9 -0
  16. package/dist/runtime/dingtalk.js +3 -0
  17. package/dist/runtime/durable-dispatch.d.ts +4 -0
  18. package/dist/runtime/durable-dispatch.js +16 -0
  19. package/dist/runtime/store.d.ts +7 -0
  20. package/dist/runtime/subagent-commands.d.ts +15 -0
  21. package/dist/runtime/subagent-commands.js +122 -0
  22. package/dist/runtime/task-commands.js +5 -1
  23. package/dist/security/logger.js +10 -1
  24. package/dist/security/types.d.ts +17 -1
  25. package/dist/shared/host-process.d.ts +21 -0
  26. package/dist/shared/host-process.js +44 -0
  27. package/dist/shared/jsonl-appender.d.ts +2 -0
  28. package/dist/shared/jsonl-appender.js +25 -13
  29. package/dist/shared/shell-words.d.ts +9 -0
  30. package/dist/shared/shell-words.js +52 -0
  31. package/dist/subagents/discovery.d.ts +42 -1
  32. package/dist/subagents/discovery.js +302 -69
  33. package/dist/subagents/external/claude-code.d.ts +2 -0
  34. package/dist/subagents/external/claude-code.js +152 -0
  35. package/dist/subagents/external/codex-cli.d.ts +2 -0
  36. package/dist/subagents/external/codex-cli.js +133 -0
  37. package/dist/subagents/external/exec.d.ts +2 -0
  38. package/dist/subagents/external/exec.js +38 -0
  39. package/dist/subagents/external/harness.d.ts +102 -0
  40. package/dist/subagents/external/harness.js +76 -0
  41. package/dist/subagents/external/registry.d.ts +2 -0
  42. package/dist/subagents/external/registry.js +11 -0
  43. package/dist/subagents/external/run.d.ts +49 -0
  44. package/dist/subagents/external/run.js +266 -0
  45. package/dist/subagents/runs.d.ts +230 -0
  46. package/dist/subagents/runs.js +615 -0
  47. package/dist/subagents/tool.d.ts +26 -0
  48. package/dist/subagents/tool.js +464 -182
  49. package/dist/subagents/workspace-lease.d.ts +36 -0
  50. package/dist/subagents/workspace-lease.js +48 -0
  51. package/dist/tasks/artifact-subject.js +50 -2
  52. package/dist/tasks/control.d.ts +12 -0
  53. package/dist/tasks/control.js +20 -0
  54. package/dist/tasks/store.d.ts +21 -0
  55. package/dist/tasks/store.js +80 -0
  56. package/dist/tasks/verification.d.ts +8 -0
  57. package/dist/tasks/verification.js +10 -2
  58. package/dist/tools/index.d.ts +1 -1
  59. package/dist/tools/index.js +12 -1
  60. package/dist/tools/registry.js +1 -0
  61. package/dist/tools/subagent-manage.d.ts +23 -0
  62. package/dist/tools/subagent-manage.js +154 -0
  63. package/dist/tools/tool-details.d.ts +1 -1
  64. package/dist/tui/app.js +2 -0
  65. package/dist/tui/commands.d.ts +1 -0
  66. package/dist/tui/commands.js +2 -0
  67. package/dist/tui/turn-controller.d.ts +1 -0
  68. package/dist/tui/turn-controller.js +1 -0
  69. package/dist/usage/ledger.d.ts +13 -0
  70. package/dist/usage/ledger.js +15 -2
  71. package/dist/usage/render.js +22 -0
  72. package/examples/sub-agents/README.md +61 -12
  73. package/examples/sub-agents/builder-hard.md +45 -0
  74. package/examples/sub-agents/builder.md +41 -0
  75. package/examples/sub-agents/documenter.md +53 -0
  76. package/examples/sub-agents/log-sifter.md +43 -0
  77. package/examples/sub-agents/planner.md +42 -0
  78. package/examples/sub-agents/reviewer.md +38 -38
  79. package/examples/sub-agents/scout.md +31 -0
  80. package/examples/sub-agents/verifier.md +32 -36
  81. package/examples/sub-agents/worker.md +36 -0
  82. package/package.json +1 -1
  83. package/examples/sub-agents/researcher.md +0 -41
@@ -93,7 +93,7 @@ export function createJsonlAppender(options) {
93
93
  await appendFile(filePath, line, { encoding: "utf-8", mode });
94
94
  sizes.set(filePath, (await currentSize(filePath)) + lineBytes);
95
95
  };
96
- const serialize = (record) => {
96
+ const serialize = (record, strict) => {
97
97
  try {
98
98
  const json = JSON.stringify(options.recordForWrite ? options.recordForWrite(record) : record);
99
99
  if (json === undefined)
@@ -101,7 +101,9 @@ export function createJsonlAppender(options) {
101
101
  const line = `${json}\n`;
102
102
  return { filePath: resolvePath(new Date(), record), line, bytes: Buffer.byteLength(line) };
103
103
  }
104
- catch {
104
+ catch (error) {
105
+ if (strict)
106
+ throw error;
105
107
  if (!warnedDrop) {
106
108
  warnedDrop = true;
107
109
  fallbackWarning("runtime.log_sink.dropped", "Failed to serialize JSONL record; record was dropped");
@@ -109,15 +111,20 @@ export function createJsonlAppender(options) {
109
111
  return null;
110
112
  }
111
113
  };
112
- const enqueue = (record, priority) => {
113
- if (closed)
114
+ const enqueue = (record, priority, strict = false) => {
115
+ if (closed) {
116
+ if (strict)
117
+ throw new Error("JSONL appender is closed");
114
118
  return null;
115
- const serialized = serialize(record);
119
+ }
120
+ const serialized = serialize(record, strict);
116
121
  if (!serialized)
117
122
  return null;
118
123
  const recordLimit = priority === "critical" ? maxPendingRecords : maxPendingRecords - reservedCriticalRecords;
119
124
  const byteLimit = priority === "critical" ? maxPendingBytes : maxPendingBytes - reservedCriticalBytes;
120
125
  if (pending.size >= recordLimit || pendingBytes + serialized.bytes > byteLimit) {
126
+ if (strict)
127
+ throw new Error("JSONL queue limit reached");
121
128
  if (!warnedDrop) {
122
129
  warnedDrop = true;
123
130
  fallbackWarning("runtime.log_sink.dropped", "JSONL queue limit reached; record was dropped");
@@ -125,20 +132,19 @@ export function createJsonlAppender(options) {
125
132
  return null;
126
133
  }
127
134
  const previous = chains.get(serialized.filePath) ?? Promise.resolve();
128
- const result = previous
135
+ const writeResult = previous
129
136
  .catch(() => undefined)
130
- .then(async () => {
131
- try {
132
- await write(serialized.filePath, serialized.line, serialized.bytes);
137
+ .then(() => write(serialized.filePath, serialized.line, serialized.bytes));
138
+ const result = strict
139
+ ? writeResult
140
+ : writeResult.then(() => {
133
141
  warnedWrite = false;
134
- }
135
- catch {
142
+ }, () => {
136
143
  if (!warnedWrite) {
137
144
  warnedWrite = true;
138
145
  fallbackWarning("runtime.log_sink.failed", "Failed to append JSONL record; continuing without it");
139
146
  }
140
- }
141
- });
147
+ });
142
148
  const completion = result.finally(() => {
143
149
  pending.delete(completion);
144
150
  pendingBytes -= serialized.bytes;
@@ -161,6 +167,12 @@ export function createJsonlAppender(options) {
161
167
  async append(record, priority = "critical") {
162
168
  await enqueue(record, priority)?.completion;
163
169
  },
170
+ async appendStrict(record, priority = "critical") {
171
+ const pendingLine = enqueue(record, priority, true);
172
+ if (!pendingLine)
173
+ throw new Error("JSONL record was not accepted");
174
+ await pendingLine.completion;
175
+ },
164
176
  tryAppend(record, priority = "normal") {
165
177
  return enqueue(record, priority) !== null;
166
178
  },
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Split a shell-style command line into argv tokens, respecting single/double quotes and
3
+ * backslash escapes, without invoking a shell (spec 040, D4 — external delegation runs never go
4
+ * through `sh -c`, so the "argv, not a shell string" guarantee has to start at tokenization).
5
+ *
6
+ * This is word-splitting only: no globbing, no variable expansion, no command substitution.
7
+ * An unterminated quote is tolerated by treating the rest of the string as part of that token.
8
+ */
9
+ export declare function splitShellWords(command: string): string[];
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Split a shell-style command line into argv tokens, respecting single/double quotes and
3
+ * backslash escapes, without invoking a shell (spec 040, D4 — external delegation runs never go
4
+ * through `sh -c`, so the "argv, not a shell string" guarantee has to start at tokenization).
5
+ *
6
+ * This is word-splitting only: no globbing, no variable expansion, no command substitution.
7
+ * An unterminated quote is tolerated by treating the rest of the string as part of that token.
8
+ */
9
+ export function splitShellWords(command) {
10
+ const tokens = [];
11
+ let current = "";
12
+ let inToken = false;
13
+ let quote;
14
+ for (let i = 0; i < command.length; i++) {
15
+ const ch = command[i];
16
+ if (quote) {
17
+ if (ch === quote) {
18
+ quote = undefined;
19
+ }
20
+ else if (quote === '"' && ch === "\\" && i + 1 < command.length && /["\\$`]/.test(command[i + 1])) {
21
+ current += command[++i];
22
+ }
23
+ else {
24
+ current += ch;
25
+ }
26
+ continue;
27
+ }
28
+ if (ch === "'" || ch === '"') {
29
+ quote = ch;
30
+ inToken = true;
31
+ continue;
32
+ }
33
+ if (ch === "\\" && i + 1 < command.length) {
34
+ current += command[++i];
35
+ inToken = true;
36
+ continue;
37
+ }
38
+ if (/\s/.test(ch)) {
39
+ if (inToken) {
40
+ tokens.push(current);
41
+ current = "";
42
+ inToken = false;
43
+ }
44
+ continue;
45
+ }
46
+ current += ch;
47
+ inToken = true;
48
+ }
49
+ if (inToken)
50
+ tokens.push(current);
51
+ return tokens;
52
+ }
@@ -1,12 +1,21 @@
1
1
  import type { Api, Model } from "@earendil-works/pi-ai";
2
+ import type { SecurityConfig } from "../security/types.js";
2
3
  declare const ALLOWED_SUB_AGENT_TOOLS: readonly ["read", "grep", "bash", "edit", "write", "web_search", "web_fetch"];
3
4
  declare const ALLOWED_CONTEXT_MODES: readonly ["isolated", "contextual"];
4
5
  declare const ALLOWED_MEMORY_MODES: readonly ["none", "session", "relevant"];
5
- declare const ALLOWED_THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh"];
6
+ declare const ALLOWED_THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
7
+ declare const ALLOWED_RUNTIMES: readonly ["internal", "external"];
8
+ declare const ALLOWED_HARNESSES: readonly ["claude-code", "codex-cli", "exec"];
9
+ declare const ALLOWED_WORKLOADS: readonly ["light", "heavy"];
10
+ declare const ALLOWED_MUTATES: readonly ["read", "write"];
6
11
  export type SubAgentToolName = (typeof ALLOWED_SUB_AGENT_TOOLS)[number];
7
12
  export type SubAgentContextMode = (typeof ALLOWED_CONTEXT_MODES)[number];
8
13
  export type SubAgentMemoryMode = (typeof ALLOWED_MEMORY_MODES)[number];
9
14
  export type SubAgentThinkingLevel = (typeof ALLOWED_THINKING_LEVELS)[number];
15
+ export type SubAgentRuntime = (typeof ALLOWED_RUNTIMES)[number];
16
+ export type SubAgentHarness = (typeof ALLOWED_HARNESSES)[number];
17
+ export type SubAgentWorkload = (typeof ALLOWED_WORKLOADS)[number];
18
+ export type SubAgentMutates = (typeof ALLOWED_MUTATES)[number];
10
19
  /**
11
20
  * Execution budgets as a single named tuple. Frontmatter keeps the four numeric knobs
12
21
  * (a human editing a config file has grounds to pick numbers); the invocation surface
@@ -61,6 +70,27 @@ export interface SubAgentConfig {
61
70
  thinkingLevel?: SubAgentThinkingLevel;
62
71
  filePath?: string;
63
72
  source: "predefined" | "inline";
73
+ /** Defaults to "internal"; existing role files therefore parse unchanged (spec 040, D5). */
74
+ runtime: SubAgentRuntime;
75
+ /** External only. */
76
+ harness?: SubAgentHarness;
77
+ /** External only: the raw, unvalidated command line. Tokenized by the harness at invocation
78
+ * time (D4), never by discovery — discovery only checks that it is non-empty. */
79
+ command?: string;
80
+ /** External only: run `command` through `/bin/sh -lc` instead of argv-direct spawn (D4). */
81
+ shell?: boolean;
82
+ /** External only: env vars appended to (and overriding) the inherited environment (D8.2). */
83
+ env?: Record<string, string>;
84
+ /** Drives system-prompt directory grouping (D11); defaults by runtime when unset. */
85
+ workload?: SubAgentWorkload;
86
+ /** Required for external (an explicit declaration); optional for internal (inferred from `tools`). */
87
+ mutates?: SubAgentMutates;
88
+ /** External only: the harness's own model string, passed through unresolved (D5) — never
89
+ * looked up in `models.json`, because pipiclaw cannot validate another CLI's model names. */
90
+ externalModelRef?: string;
91
+ /** Set when the role is otherwise valid but currently cannot be invoked (e.g. missing binary).
92
+ * The role is still listed — never silently dropped (D5) — and invocation must explain why. */
93
+ unavailable?: string;
64
94
  }
65
95
  export interface ResolvedSubAgentConfig extends Omit<SubAgentConfig, "model" | "modelRef" | "thinkingLevel"> {
66
96
  model: Model<Api>;
@@ -89,6 +119,17 @@ export interface SubAgentInvocationOverrides {
89
119
  }
90
120
  export declare function validateSubAgentTask(task: string): string | undefined;
91
121
  export declare function getSubAgentsDir(workspaceDir: string): string;
122
+ /**
123
+ * Deny `write`/`edit` on `workspace/sub-agents/` itself (spec 040, D8.1).
124
+ *
125
+ * `DEFAULT_SECURITY_CONFIG.writeAllow` is empty and `pathAllowedByDefaults` permits the whole
126
+ * workspace, so without this the main agent (and a sub-agent it dispatches) can write a
127
+ * `runtime: external` role file with an arbitrary `command` and then invoke it — a command-guard
128
+ * bypass wearing a delegation costume. This closes the `write`/`edit` path; it does not close
129
+ * `bash` (same known gap as the memory-write-deny it mirrors — see the spec's risk list). The
130
+ * role directory hot-reloads on purpose (P4): this is the only gate, and it must stay cheap.
131
+ */
132
+ export declare function withSubAgentsDirWriteDeny(config: SecurityConfig, workspaceDir: string): SecurityConfig;
92
133
  export declare function validateToolNames(values: string[] | undefined): {
93
134
  tools: SubAgentToolName[];
94
135
  error?: string;
@@ -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;