@restranger/repi-subagents 0.0.0-stage → 0.0.1-92401bd

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.
package/README.md CHANGED
@@ -1,3 +1,285 @@
1
- # Temporary Holding Version
1
+ # @restranger/repi-subagents
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Declarative subagents for Pi. An agent is a Markdown file with YAML frontmatter plus a system
4
+ prompt; the plugin discovers it, runs it in an isolated child Pi session, and returns its final
5
+ answer to the parent.
6
+
7
+ Ships with **6 built-in default agents** adapted from Claude Code's built-ins (`general-purpose`,
8
+ `Explore`, `Plan`, `verification`, `statusline-setup`, `claude-code-guide`) for Pi's conventions
9
+ (`AGENTS.md`, `.pi/`, `ctx.ui`), plus user and
10
+ project Markdown declarations and JSON overrides.
11
+
12
+ ```bash
13
+ pi install npm:@restranger/repi-subagents
14
+ # or from this repository
15
+ pi --extension ./packages/subagents/src/index.ts
16
+ ```
17
+
18
+ ## Built-in default agents
19
+
20
+ The plugin includes six built-in subagents, adapted from Claude Code to Pi:
21
+
22
+ | Agent | Purpose | Tools | Model |
23
+ |---|---|---|---|
24
+ | `general-purpose` | Complex, multi-step tasks and research. | `*` (all) | inherit |
25
+ | `Explore` | Fast read-only codebase exploration. | `read, bash, grep, find, ls` | `haiku` (fallback: `inherit`) |
26
+ | `Plan` | Software architect for implementation planning. | `read, bash, grep, find, ls` | inherit |
27
+ | `verification` | Adversarial verification specialist to break changes. | default (`read, bash, ...`) | inherit |
28
+ | `statusline-setup` | Write a Pi extension for a custom footer / status segment. | `read, write, edit` | inherit |
29
+ | `claude-code-guide` | Answer questions about Claude Code, the Agent SDK, and the API. | `bash, read, web_search, fetch_content` | `haiku` (fallback: `inherit`) |
30
+
31
+ Any built-in agent can be overridden by placing an `.md` file with the same name in your user or
32
+ project agent directory, or customized / disabled (`"enabled": false`) in `subagents.json`.
33
+
34
+ ## Agent file
35
+
36
+ ```md
37
+ ---
38
+ name: scout
39
+ description: Fast codebase reconnaissance. Use for "where is X?" and "how does Y work?".
40
+ tools: read, grep, find, ls
41
+ model: inherit
42
+ fallback_models:
43
+ - backup/model
44
+ - inherit
45
+ thinking: low
46
+ max_turns: 12
47
+ background: false
48
+ prompt_mode: append
49
+ color: cyan
50
+ ---
51
+ You are a read-only codebase scout. Search the repository, quote exact files and line
52
+ numbers, and return a concise report. Do not modify files.
53
+ ```
54
+
55
+ The file name is the fallback agent name when `name:` is absent. `description:` is required: it is
56
+ the only thing the parent model sees before choosing an agent. This repository includes a
57
+ ready-to-use read-only example at [`.pi/agents/scout.md`](../../.pi/agents/scout.md).
58
+
59
+ ### Frontmatter
60
+
61
+ | Field | Meaning |
62
+ |---|---|
63
+ | `name` | Agent id. Letters, digits, `.`, `_`, `-`; max 64 chars. Falls back to the file name. |
64
+ | `description` | Required. Short selection hint shown in the tool description. |
65
+ | `tools` | `read, grep, find` / `[read, grep]` / `none` / `*`. Omitted means the built-in set `read, bash, edit, write, grep, find, ls`. |
66
+ | `disallowedTools` | Removed after the allowlist is built. |
67
+ | `model` | `inherit` (default) or a model id; exact `provider/model` first, then a unique fuzzy match. |
68
+ | `fallback_models` | List of models to try in order if the primary model fails (`resolution error`, `provider error`, rate limits, quota, 4xx/5xx). Supports `inherit`. Aliases: `fallbackModels`, `fallbacks`, `fallback_model`. |
69
+ | `thinking` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`. Unknown values fall back to the parent. |
70
+ | `max_turns` | Positive integer; `0`/absent = unlimited, values below 2 are raised to 2. |
71
+ | `background` | Default for the tool's `background` flag. |
72
+ | `prompt_mode` | `append` (default) appends the body to Pi's prompt; `replace` uses it as the whole system prompt. |
73
+ | `color` | Optional UI hint; stored for later presentation work. |
74
+
75
+ Aliases accepted for compatibility: `allowed-tools`, `disallowed-tools`, `maxTurns`,
76
+ `run_in_background`, `systemPromptMode`, `effort` (as `thinking`).
77
+
78
+ Unsupported fields such as `hooks`, `mcpServers`, `skills`, `memory`, `isolation`,
79
+ `permission` and `permissionMode` are ignored with a warning. They are not silently reinterpreted.
80
+
81
+ ## Discovery
82
+
83
+ Scanned recursively, lowest priority first; a later directory overrides the same name:
84
+
85
+ 1. `$PI_CODING_AGENT_DIR/agents/**/*.md`, or `~/.config/pi/agent/agents/**/*.md` and
86
+ `~/.pi/agent/agents/**/*.md`
87
+ 2. `$XDG_CONFIG_HOME/repi/agents/**/*.md` (default `~/.config/repi/agents`)
88
+ 3. `<project>/.pi/agents/**/*.md`
89
+ 4. `<project>/.repi/agents/**/*.md` (highest)
90
+
91
+ Project directories are skipped when Pi reports the workspace as untrusted. Hidden directories,
92
+ `node_modules`, `.git` and `*.chain.md` files are ignored. `/subagents reload` rescans without
93
+ restarting Pi.
94
+
95
+ ## JSON overrides
96
+
97
+ Markdown remains the declaration format, but frontmatter values can be overridden without editing
98
+ the file. Overrides live in:
99
+
100
+ 1. `$XDG_CONFIG_HOME/repi/subagents.json` (default `~/.config/repi/subagents.json`)
101
+ 2. `<project>/.repi/subagents.json` (highest priority; skipped when the workspace is untrusted)
102
+
103
+ Both files are optional. Within JSON, project values win over user values. JSON is applied after
104
+ Markdown discovery, so it overrides the already-resolved Markdown definition. The JSON file cannot
105
+ create an agent that has no Markdown declaration.
106
+
107
+ ```json
108
+ {
109
+ "version": 1,
110
+ "agents": {
111
+ "scout": {
112
+ "description": "Project-specific reconnaissance agent",
113
+ "tools": ["read", "grep", "find", "ls"],
114
+ "disallowedTools": ["bash"],
115
+ "model": "antigravity/gemini-3.8-flash",
116
+ "fallbackModels": ["anthropic/claude-3-5-sonnet", "inherit"],
117
+ "thinking": "high",
118
+ "maxTurns": 40,
119
+ "background": true,
120
+ "promptMode": "append",
121
+ "color": "cyan",
122
+ "systemPrompt": "You are a read-only scout for this repository."
123
+ },
124
+ "Explore": {
125
+ "enabled": false
126
+ }
127
+ }
128
+ }
129
+ ```
130
+
131
+ Agent names are case-insensitive. Supported fields are `description`, `tools`,
132
+ `disallowedTools`, `model`, `fallbackModels`, `thinking`, `maxTurns`, `background`, `promptMode`, `color`,
133
+ `enabled` and `systemPrompt`. Frontmatter-style aliases (`max_turns`, `prompt_mode`,
134
+ `disallowed_tools`, `run_in_background`, `systemPromptMode`, `effort`, `allowed-tools`, `prompt`,
135
+ `system_prompt`, `fallback_models`, `fallbacks`, `fallback_model`) and their hyphenated variants are accepted as well.
136
+
137
+ Special values:
138
+
139
+ - `null` removes that field from a lower-priority JSON layer and falls back to the Markdown value.
140
+ - `"model": "inherit"` / `"thinking": "inherit"` clears a model or thinking level declared in Markdown.
141
+ - `"maxTurns": 0` removes a Markdown turn limit.
142
+ - `"tools": "inherit"` resets the allowlist to the default built-in tools; `"none"` / `[]` means no tools; `"*"` means every parent tool.
143
+ - `"enabled": false` hides the agent. A higher-priority layer can re-enable it.
144
+ - `systemPrompt` replaces the Markdown body; `promptMode` then decides append vs replace.
145
+
146
+ Malformed JSON, unknown fields, unknown agent names and invalid values are reported by
147
+ `/subagents list` and `subagent_list`. Invalid values leave the Markdown value in place. The list
148
+ also shows which override files were read. Re-read both files with `/subagents reload`.
149
+
150
+ ## Tools
151
+
152
+ | Tool | Purpose |
153
+ |---|---|
154
+ | `subagent` | Run `{ agent, task, description?, background?, model?, fallbackModels?, maxTurns? }`. `prompt` is accepted as a Claude-style alias for `task`. Foreground waits; background returns a run id. |
155
+ | `subagent_status` | One run by `id`, or every run in the session. |
156
+ | `subagent_wait` | Wait for `ids` (default: all active runs) with `timeoutMs` (default 120000). |
157
+ | `subagent_abort` | Abort a queued or running run. |
158
+ | `subagent_list` | Agents, discovery directories, override config files, diagnostics and runs. |
159
+
160
+ `/subagents` prints the same catalogue; `/subagents reload` rescans the files; `/subagents fleet` opens
161
+ the live dashboard described below; `/subagents stop` stops all active subagents (or `/subagents stop <id>` stops a specific run).
162
+
163
+ `Tab` completes `/subagents ` to `fleet|list|reload|stop`, and `Tab` after `fleet ` or `stop ` lists
164
+ the run ids of the current session — generated ids cannot be typed from memory, so this is the way
165
+ to address one run without opening the dashboard. `fleet` also accepts a run id to open straight on
166
+ that run.
167
+
168
+ Children never receive `subagent*` tools, so a child cannot spawn grandchildren and make
169
+ wait/abort ownership ambiguous.
170
+
171
+ ### What the model sees before it calls the tool
172
+
173
+ Delegation quality depends on three surfaces, and each one has exactly one owner:
174
+
175
+ 1. **`<rules>`** — the `subagent` tool declares `promptGuidelines`, so Pi renders six bullets in
176
+ the ordinary system-prompt rules block, next to the `bash`/`read`/`edit` rules: delegate broad
177
+ multi-file exploration, keep one-off lookups inline, fan out independent questions in one turn,
178
+ write self-contained briefs (the child sees neither the conversation nor `AGENTS.md`), never
179
+ delegate understanding, and collect background results before reporting. They are attached to
180
+ the tool definition, so they disappear when the tool is inactive and never appear in children
181
+ (which exclude `subagent*`). `promptSnippet` adds the tool to Pi's `Available tools` list.
182
+ 2. **`<repi_subagents>`** — the catalogue injected from `before_agent_start`: name, description and
183
+ tool allowlist for every agent discovered on disk (user directories, project `.pi/agents` and
184
+ `.repi/agents`, plus override files), capped at 24 entries. Descriptions are clamped at a
185
+ sentence boundary so the "how to call this agent" sentence survives. When the catalogue fits it
186
+ closes with "do not call `subagent_list` to discover agents"; when it is truncated the closing
187
+ line points at `subagent_list` instead, so the hidden agents stay reachable.
188
+ 3. **`<repi_subagent_runs>`** — runs in flight plus finished runs whose result has not been
189
+ collected, so the model neither duplicates a run nor reports completion without reading a
190
+ background verdict. `subagent_wait` (and inspecting a finished run) marks the result as
191
+ collected, which drops it from the section; the section is deleted entirely when nothing is
192
+ left, so Pi patches the prompt back to its old shape.
193
+
194
+ ## Isolation and permissions
195
+
196
+ Each run gets an in-process child Pi session:
197
+
198
+ - `SessionManager.inMemory()` — no transcript is written for P0.
199
+ - A scoped `DefaultResourceLoader` with `noExtensions`, `noSkills`, `noPromptTemplates`,
200
+ `noThemes` and `noContextFiles`, plus a temporary `agentDir` for settings isolation. The
201
+ loader `cwd` stays the real project so the prompt's `<cwd>` matches tool execution; ambient
202
+ packages, project extensions, skills, themes, prompt templates and `AGENTS.md` do **not** leak
203
+ into the child.
204
+ - **Requested tools bring their own extensions.** After the allowlist is resolved, the parent's
205
+ `getAllTools()` provenance decides which extension modules the child needs. Those modules are
206
+ passed as `additionalExtensionPaths`, so an agent that declares `web_search` gets the
207
+ extension that registers `web_search` — not a second copy of every ambient plugin. Host built-ins
208
+ (`codemode`, `tool_search`, MCP resource tools) are recreated through the SDK factories because
209
+ SDK-created sessions do not load CLI built-ins. The parent `@restranger/repi-permission-system-core`, `@restranger/repi-permission-system-modes`
210
+ and `@restranger/repi-ui` extensions register no child tools, so they stay parent-side; `subagent*` is
211
+ always removed and `@restranger/repi-subagents` is never loaded recursively.
212
+ - **Custom providers keep their runtime.** The child receives the parent's `ModelRuntime`
213
+ (`ctx.modelRegistry.runtime`) instead of building a new one against the temporary `agentDir`.
214
+ Extension-registered providers, OAuth credentials and per-provider API adapters therefore work
215
+ exactly as in the parent — a child can use `opencode-free/*`, `antigravity/*` or any other
216
+ keyless/header-authenticated provider without re-authenticating.
217
+ - Only the declaration's body (appended to Pi's base prompt or replacing it), model/thinking level,
218
+ tool allowlist and the extensions that provide those tools are inherited.
219
+ - No parent conversation is inherited (fresh context); put all needed context in `task` (`prompt` is
220
+ accepted as an alias for Claude-style callers).
221
+
222
+ When `@restranger/repi-permission-system-core` is installed, every child tool call is checked against the **parent
223
+ session's** `re:permissions@1` service with `source: "subagent"`. Hard denies and the parent's
224
+ active mode therefore still apply. P0 fails closed on `ask` (there is no parent-prompt routing
225
+ yet). Without `@restranger/repi-permission-system-core`, the declaration's `tools:` list is the authority.
226
+
227
+ ## Concurrency and background runs
228
+
229
+ Subagent runs share an in-process FIFO pool (default 4 concurrent). Concurrency can be configured via:
230
+ 1. Programmatic option: `maxConcurrent` in `SubagentsPluginOptions`.
231
+ 2. JSON override config: `"maxConcurrent": 8` in `.repi/subagents.json` or `~/.config/repi/subagents.json`.
232
+
233
+ Runs beyond the concurrency limit enter the `queued` state and automatically start when an active slot frees up. Runs are not persisted across a Pi restart; P1 will add durable records and artifacts. `subagent_wait` can collect finished background results after they complete.
234
+
235
+ ## UI
236
+
237
+ Three surfaces share the manager's live run table. All of them are display-width aware: SGR
238
+ colours survive truncation, while cursor movement, OSC titles and other control sequences are
239
+ stripped from child/tool text before it reaches the terminal.
240
+
241
+ - **Inline progress.** A foreground `subagent` call streams into its own tool call through
242
+ `onUpdate`: status, elapsed time, tool count, turn budget, the two most recent finished steps
243
+ and the child's current tool (`↳ bash bun run test`). The result card ends with the outcome or
244
+ error. The widget stays out of the way of foreground runs, so the same progress is never shown
245
+ twice.
246
+ - **Status widget above the editor.** A tree of background runs plus the runs that just finished:
247
+ `Agents · 2 active · 1 finished · 14.2k tok`, one branch per run, the current child tool under
248
+ the active row, tool count, tokens, turn budget and the result/error preview for finished rows.
249
+ A completed run leaves the widget on the parent's next turn (errors and aborts after two turns),
250
+ and the widget is unmounted when nothing is left to show. Every line is truncated to the
251
+ `render(width)` value and the whole widget is bounded by `terminal.rows` (3–12 lines, six rows
252
+ reserved for the dock), so it cannot push Pi's editor off screen. Hosts without a TUI (RPC,
253
+ print, JSON) receive plain lines instead of the component.
254
+ - **`/subagents fleet` inspector.** A full-screen overlay (`anchor: "center"`, `width: "100%"`,
255
+ `maxHeight: "100%"`, `margin: 0`) with the same native Pi chrome as `/models` and `/llama`:
256
+ `─` rules in the border colour frame the header, the body and the hint line, the title is
257
+ accent+bold, metadata is muted and hints are `dim key` + `muted description`. The body is split
258
+ into a roster on the left and the selected run on the right by a single `│` divider that is
259
+ stitched into the rules above and below with `┬`/`┴` joints — status,
260
+ id/model, elapsed time, tool count, tokens, turn budget, current tool, step tree, forwarded
261
+ extensions, diagnostics, the task and the output/error. The component renders exactly
262
+ `terminal.rows` lines, so the overlay fills the screen without clipping; an empty fleet shows a
263
+ centered empty state and shrinks the hints to `r refresh · Esc close`.
264
+ `Enter`/`x` expands the step list; `J`/`K` or page keys scroll the transcript. Navigation uses
265
+ Pi's keybindings (`tui.select.up`/`down`/`confirm`/`cancel`), so a remap in
266
+ `keybindings.json` applies; `j`/`k`, `g`/`G`, the mouse wheel, `Enter`, `x` and `q`/`Esc` work
267
+ regardless. `D` arms cancellation and `y`/`Enter` confirms it; `n`/`Esc` keeps the run. The
268
+ roster centres the selection and the footer prints the primary bindings actually configured. In
269
+ hosts without a custom TUI component the same dashboard is emitted as a text notification.
270
+
271
+ Activity comes from the child session's `tool_execution_start`/`tool_execution_end` events and
272
+ from assistant turns, so the surfaces reflect the child's work without parsing its transcript.
273
+ The inspector keeps the chronological step list (`SubagentStep[]`), not the full conversation.
274
+
275
+ ## P0 limitations / next steps
276
+
277
+ - No parent-context fork, steering, intercom or batch fan-out. The `/subagents fleet` inspector is read-only
278
+ apart from cancelling a run; result handoff into the parent conversation is still manual via
279
+ `subagent_wait`.
280
+ - No transcript drill-in: child sessions are in-memory (`SessionManager.inMemory()`), so `/subagents fleet`
281
+ shows the result preview and the recent tool list, not the child's conversation.
282
+ - No Git worktree isolation; all children share the parent `cwd`.
283
+ - No shared task board or DAG tasks.
284
+ - `ask` is denied inside children until parent prompt routing lands.
285
+ - No structured `yield_result` contract; the final assistant text is the result.
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
- "name": "@restranger/repi-subagents",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@restranger/repi-subagents",
3
+ "version": "0.0.1-92401bd",
4
+ "description": "Declarative subagents with Markdown definitions, Fleet UI, and isolated child sessions for pi-coding-agent",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts"
10
+ },
11
+ "files": ["src", "README.md", "!src/**/__tests__"],
12
+ "keywords": ["pi-package", "pi-coding-agent", "subagents", "multi-agent", "fleet", "tui"],
13
+ "author": "ReStranger <restranger@disroot.org>",
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/ReStranger/repi-mono.git",
18
+ "directory": "packages/subagents"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/ReStranger/repi-mono/issues"
22
+ },
23
+ "homepage": "https://github.com/ReStranger/repi-mono#readme",
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "pi": {
28
+ "extensions": ["./src/index.ts"]
29
+ },
30
+ "dependencies": {
31
+ "@restranger/repi-lib": "0.0.1-92401bd",
32
+ "@restranger/repi-ui": "0.0.1-92401bd"
33
+ },
34
+ "peerDependencies": {
35
+ "@earendil-works/pi-coding-agent": ">=0.79.0"
36
+ },
37
+ "peerDependenciesMeta": {
38
+ "@earendil-works/pi-coding-agent": {
39
+ "optional": true
40
+ }
41
+ }
42
+ }
@@ -0,0 +1,297 @@
1
+ import { basename } from "node:path";
2
+ import { FRONTMATTER_CONSUMED_KEYS, agentFieldValue } from "./agent-schema.js";
3
+ import {
4
+ type FrontmatterValue,
5
+ parseBooleanValue,
6
+ parseFrontmatter,
7
+ parseIntegerValue,
8
+ parseListValue,
9
+ } from "./frontmatter.js";
10
+ import type { AgentDefinition, AgentDiagnostic, AgentPromptMode, AgentSource, AgentToolSpec } from "./types.js";
11
+
12
+ const AGENT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
13
+ const THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh"]);
14
+ const MAX_DESCRIPTION = 1024;
15
+ const MAX_NAME = 64;
16
+
17
+ const UNSUPPORTED_KEYS = new Set([
18
+ "permissionMode",
19
+ "permission_mode",
20
+ "memory",
21
+ "hooks",
22
+ "mcpServers",
23
+ "mcp_servers",
24
+ "skills",
25
+ "isolation",
26
+ "max_output_tokens",
27
+ "output",
28
+ "acceptanceRole",
29
+ "defaultContext",
30
+ "defaultReads",
31
+ "defaultProgress",
32
+ "aliases",
33
+ "inherit_context",
34
+ "inheritProjectContext",
35
+ "inheritSkills",
36
+ "systemPrompt",
37
+ ]);
38
+
39
+ export interface ParsedAgentFile {
40
+ readonly agent?: AgentDefinition;
41
+ readonly diagnostics: readonly AgentDiagnostic[];
42
+ }
43
+
44
+ /**
45
+ * Turn one Markdown file into an agent definition.
46
+ *
47
+ * The file name is the fallback agent name, so both the Claude Code convention (`name:` in
48
+ * frontmatter) and the Pi convention (`scout.md` + no `name`) work. `description` stays required:
49
+ * the parent model needs it to choose an agent, and a missing one is a configuration error rather
50
+ * than something to invent.
51
+ */
52
+ export function parseAgentFile(content: string, filePath: string, source: AgentSource): ParsedAgentFile {
53
+ const parsed = parseFrontmatter(content);
54
+ const diagnostics: AgentDiagnostic[] = parsed.issues.map((issue) => ({
55
+ path: filePath,
56
+ level: issue.level,
57
+ message: issue.message,
58
+ }));
59
+
60
+ if (parsed.issues.some((issue) => issue.level === "error")) {
61
+ return { diagnostics };
62
+ }
63
+ if (Object.keys(parsed.data).length === 0 && parsed.body.length > 0) {
64
+ diagnostics.push({
65
+ path: filePath,
66
+ level: "error",
67
+ message: "Agent file has no YAML frontmatter.",
68
+ });
69
+ return { diagnostics };
70
+ }
71
+
72
+ const data = parsed.data;
73
+ if (parseBooleanValue(agentFieldValue(data, "enabled")) === false) {
74
+ return { diagnostics };
75
+ }
76
+
77
+ const rawName = firstString(agentFieldValue(data, "name")) ?? basename(filePath, ".md");
78
+ const name = rawName.trim();
79
+ if (!AGENT_NAME.test(name) || name.length > MAX_NAME) {
80
+ diagnostics.push({
81
+ path: filePath,
82
+ level: "error",
83
+ message: `Invalid agent name "${name}": use letters, digits, dot, underscore or hyphen (max ${MAX_NAME} chars).`,
84
+ });
85
+ return { diagnostics };
86
+ }
87
+
88
+ let description = firstString(agentFieldValue(data, "description"))?.replace(/\s+/g, " ").trim() ?? "";
89
+ if (description.length === 0) {
90
+ diagnostics.push({
91
+ path: filePath,
92
+ level: "error",
93
+ message: `Agent "${name}" is missing a description. The parent model uses it to select the agent.`,
94
+ });
95
+ return { diagnostics };
96
+ }
97
+ if (description.length > MAX_DESCRIPTION) {
98
+ description = `${description.slice(0, MAX_DESCRIPTION - 1).trimEnd()}…`;
99
+ diagnostics.push({
100
+ path: filePath,
101
+ level: "warning",
102
+ message: `Agent "${name}" description is longer than ${MAX_DESCRIPTION} characters; truncated.`,
103
+ });
104
+ }
105
+
106
+ const tools = parseTools(agentFieldValue(data, "tools"), name, filePath, diagnostics);
107
+ const disallowedTools = parseListValue(agentFieldValue(data, "disallowedTools"))?.filter(Boolean) ?? [];
108
+
109
+ const model = normalizeModel(firstString(agentFieldValue(data, "model")));
110
+ const fallbackModels = parseFallbackModels(agentFieldValue(data, "fallbackModels"));
111
+ const thinking = parseThinking(firstString(agentFieldValue(data, "thinking")), name, filePath, diagnostics);
112
+ const maxTurns = parseMaxTurns(agentFieldValue(data, "maxTurns"), name, filePath, diagnostics);
113
+ const background = parseOptionalBoolean(
114
+ agentFieldValue(data, "background"),
115
+ "background",
116
+ name,
117
+ filePath,
118
+ diagnostics,
119
+ );
120
+ const promptMode = parsePromptMode(firstString(agentFieldValue(data, "promptMode")));
121
+ const color = firstString(agentFieldValue(data, "color"))?.trim() || undefined;
122
+
123
+ const unsupported = Object.keys(data).filter(
124
+ (key) => !FRONTMATTER_CONSUMED_KEYS.has(key) && (UNSUPPORTED_KEYS.has(key) || !key.startsWith("_")),
125
+ );
126
+ if (unsupported.length > 0) {
127
+ diagnostics.push({
128
+ path: filePath,
129
+ level: "warning",
130
+ message: `Agent "${name}" ignores unsupported frontmatter field${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`,
131
+ });
132
+ }
133
+
134
+ const agent: AgentDefinition = {
135
+ name,
136
+ description,
137
+ tools,
138
+ disallowedTools,
139
+ ...(model ? { model } : {}),
140
+ ...(fallbackModels ? { fallbackModels } : {}),
141
+ ...(thinking ? { thinking } : {}),
142
+ ...(maxTurns !== undefined ? { maxTurns } : {}),
143
+ ...(background !== undefined ? { background } : {}),
144
+ promptMode,
145
+ ...(color ? { color } : {}),
146
+ systemPrompt: parsed.body.trim(),
147
+ source,
148
+ filePath,
149
+ };
150
+
151
+ return { agent, diagnostics };
152
+ }
153
+
154
+ function firstString(value: FrontmatterValue | undefined): string | undefined {
155
+ if (typeof value === "string") {
156
+ return value.length > 0 ? value : undefined;
157
+ }
158
+ return undefined;
159
+ }
160
+
161
+ function parseTools(
162
+ value: FrontmatterValue | undefined,
163
+ name: string,
164
+ filePath: string,
165
+ diagnostics: AgentDiagnostic[],
166
+ ): AgentToolSpec {
167
+ if (value === undefined) {
168
+ return undefined;
169
+ }
170
+ if (typeof value === "string" && value.trim() === "*") {
171
+ return "*";
172
+ }
173
+ // `tools: none` is an explicit "no tools". An empty list is not: a `tools:` block whose only
174
+ // content is comments parsed to an empty string, and returning `[]` there started the agent with
175
+ // zero tools and no explanation.
176
+ const explicitNone = typeof value === "string" && value.trim() === "none";
177
+ const items = parseListValue(value);
178
+ if (!items) {
179
+ return undefined;
180
+ }
181
+ if (items.length === 0 && !explicitNone) {
182
+ diagnostics.push({
183
+ path: filePath,
184
+ level: "warning",
185
+ message: `Agent "${name}" has an empty tools list; using the default tool set.`,
186
+ });
187
+ return undefined;
188
+ }
189
+ if (items.includes("*")) {
190
+ if (items.length > 1) {
191
+ diagnostics.push({
192
+ path: filePath,
193
+ level: "warning",
194
+ message: `Agent "${name}" combines "*" with explicit tools; "*" wins.`,
195
+ });
196
+ }
197
+ return "*";
198
+ }
199
+ return items;
200
+ }
201
+
202
+ function normalizeModel(value: string | undefined): string | undefined {
203
+ const trimmed = value?.trim();
204
+ if (!trimmed || trimmed === "inherit" || trimmed === "default") {
205
+ return undefined;
206
+ }
207
+ return trimmed;
208
+ }
209
+
210
+ function parseFallbackModels(value: FrontmatterValue | undefined): readonly string[] | undefined {
211
+ const list = parseListValue(value);
212
+ if (!list || list.length === 0) {
213
+ return undefined;
214
+ }
215
+ const normalized = list.map((item) => item.trim()).filter(Boolean);
216
+ return normalized.length > 0 ? normalized : undefined;
217
+ }
218
+
219
+ function parseThinking(
220
+ value: string | undefined,
221
+ name: string,
222
+ filePath: string,
223
+ diagnostics: AgentDiagnostic[],
224
+ ): string | undefined {
225
+ if (!value) {
226
+ return undefined;
227
+ }
228
+ const normalized = value.trim().toLowerCase();
229
+ const level = normalized === "none" ? "off" : normalized;
230
+ if (!THINKING_LEVELS.has(level)) {
231
+ diagnostics.push({
232
+ path: filePath,
233
+ level: "warning",
234
+ message: `Agent "${name}" has unknown thinking level "${value}"; inheriting the parent level.`,
235
+ });
236
+ return undefined;
237
+ }
238
+ return level;
239
+ }
240
+
241
+ function parseMaxTurns(
242
+ value: FrontmatterValue | undefined,
243
+ name: string,
244
+ filePath: string,
245
+ diagnostics: AgentDiagnostic[],
246
+ ): number | undefined {
247
+ if (value === undefined) {
248
+ return undefined;
249
+ }
250
+ const parsed = parseIntegerValue(value);
251
+ if (parsed === undefined) {
252
+ diagnostics.push({
253
+ path: filePath,
254
+ level: "warning",
255
+ message: `Agent "${name}" has invalid max_turns; expected a non-negative integer.`,
256
+ });
257
+ return undefined;
258
+ }
259
+ if (parsed === 0) {
260
+ return undefined;
261
+ }
262
+ if (parsed < 2) {
263
+ diagnostics.push({
264
+ path: filePath,
265
+ level: "warning",
266
+ message: `Agent "${name}" max_turns is below 2; raised to 2.`,
267
+ });
268
+ return 2;
269
+ }
270
+ return parsed;
271
+ }
272
+
273
+ function parseOptionalBoolean(
274
+ value: FrontmatterValue | undefined,
275
+ field: string,
276
+ name: string,
277
+ filePath: string,
278
+ diagnostics: AgentDiagnostic[],
279
+ ): boolean | undefined {
280
+ if (value === undefined) {
281
+ return undefined;
282
+ }
283
+ const parsed = parseBooleanValue(value);
284
+ if (parsed === undefined) {
285
+ diagnostics.push({
286
+ path: filePath,
287
+ level: "warning",
288
+ message: `Agent "${name}" has invalid ${field}; expected true or false.`,
289
+ });
290
+ }
291
+ return parsed;
292
+ }
293
+
294
+ function parsePromptMode(value: string | undefined): AgentPromptMode {
295
+ const normalized = value?.trim().toLowerCase();
296
+ return normalized === "replace" ? "replace" : "append";
297
+ }