@restranger/repi-subagents 0.0.0-stage → 0.0.1-sha.2ba2721
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 +270 -2
- package/package.json +40 -5
- package/src/agent-file.ts +297 -0
- package/src/agent-schema.ts +90 -0
- package/src/child-guard.ts +151 -0
- package/src/command.ts +256 -0
- package/src/default-agents.ts +400 -0
- package/src/discovery.ts +354 -0
- package/src/extensions.ts +119 -0
- package/src/fleet-ui.ts +472 -0
- package/src/format.ts +974 -0
- package/src/frontmatter.ts +302 -0
- package/src/index.ts +112 -0
- package/src/manager.ts +1164 -0
- package/src/model-resolver.ts +58 -0
- package/src/overrides.ts +693 -0
- package/src/plugin.ts +568 -0
- package/src/prompt.ts +127 -0
- package/src/registry.ts +71 -0
- package/src/session.ts +304 -0
- package/src/status-widget.ts +65 -0
- package/src/tool-policy.ts +77 -0
- package/src/tools.ts +546 -0
- package/src/types.ts +161 -0
package/README.md
CHANGED
|
@@ -1,3 +1,271 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @restranger/repi-subagents
|
|
2
2
|
|
|
3
|
-
|
|
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** ported directly from Claude Code (`general-purpose`,
|
|
8
|
+
`Explore`, `Plan`, `verification`, `statusline-setup`, `claude-code-guide`), plus user and
|
|
9
|
+
project Markdown declarations and JSON overrides.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pi install npm:@restranger/repi-subagents
|
|
13
|
+
# or from this repository
|
|
14
|
+
pi --extension ./packages/subagents/src/index.ts
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Built-in default agents
|
|
18
|
+
|
|
19
|
+
The plugin includes six built-in subagents ported from Claude Code:
|
|
20
|
+
|
|
21
|
+
| Agent | Purpose | Tools | Model |
|
|
22
|
+
|---|---|---|---|
|
|
23
|
+
| `general-purpose` | Complex, multi-step tasks and research. | `*` (all) | inherit |
|
|
24
|
+
| `Explore` | Fast read-only codebase exploration. | `read, bash, grep, find, ls` | `haiku` (fallback: `inherit`) |
|
|
25
|
+
| `Plan` | Software architect for implementation planning. | `read, bash, grep, find, ls` | inherit |
|
|
26
|
+
| `verification` | Adversarial verification specialist to break changes. | default (`read, bash, ...`) | inherit |
|
|
27
|
+
| `statusline-setup` | Configure Claude Code / statusline settings. | `read, edit` | inherit |
|
|
28
|
+
| `claude-code-guide` | Answer questions about CLI, SDK, and APIs. | `bash, read, web_search, fetch_content` | `haiku` (fallback: `inherit`) |
|
|
29
|
+
|
|
30
|
+
Any built-in agent can be overridden by placing an `.md` file with the same name in your user or
|
|
31
|
+
project agent directory, or customized / disabled (`"enabled": false`) in `subagents.json`.
|
|
32
|
+
|
|
33
|
+
## Agent file
|
|
34
|
+
|
|
35
|
+
```md
|
|
36
|
+
---
|
|
37
|
+
name: scout
|
|
38
|
+
description: Fast codebase reconnaissance. Use for "where is X?" and "how does Y work?".
|
|
39
|
+
tools: read, grep, find, ls
|
|
40
|
+
model: inherit
|
|
41
|
+
fallback_models:
|
|
42
|
+
- backup/model
|
|
43
|
+
- inherit
|
|
44
|
+
thinking: low
|
|
45
|
+
max_turns: 12
|
|
46
|
+
background: false
|
|
47
|
+
prompt_mode: append
|
|
48
|
+
color: cyan
|
|
49
|
+
---
|
|
50
|
+
You are a read-only codebase scout. Search the repository, quote exact files and line
|
|
51
|
+
numbers, and return a concise report. Do not modify files.
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The file name is the fallback agent name when `name:` is absent. `description:` is required: it is
|
|
55
|
+
the only thing the parent model sees before choosing an agent. This repository includes a
|
|
56
|
+
ready-to-use read-only example at [`.pi/agents/scout.md`](../../.pi/agents/scout.md).
|
|
57
|
+
|
|
58
|
+
### Frontmatter
|
|
59
|
+
|
|
60
|
+
| Field | Meaning |
|
|
61
|
+
|---|---|
|
|
62
|
+
| `name` | Agent id. Letters, digits, `.`, `_`, `-`; max 64 chars. Falls back to the file name. |
|
|
63
|
+
| `description` | Required. Short selection hint shown in the tool description. |
|
|
64
|
+
| `tools` | `read, grep, find` / `[read, grep]` / `none` / `*`. Omitted means the built-in set `read, bash, edit, write, grep, find, ls`. |
|
|
65
|
+
| `disallowedTools` | Removed after the allowlist is built. |
|
|
66
|
+
| `model` | `inherit` (default) or a model id; exact `provider/model` first, then a unique fuzzy match. |
|
|
67
|
+
| `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`. |
|
|
68
|
+
| `thinking` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`. Unknown values fall back to the parent. |
|
|
69
|
+
| `max_turns` | Positive integer; `0`/absent = unlimited, values below 2 are raised to 2. |
|
|
70
|
+
| `background` | Default for the tool's `background` flag. |
|
|
71
|
+
| `prompt_mode` | `append` (default) appends the body to Pi's prompt; `replace` uses it as the whole system prompt. |
|
|
72
|
+
| `color` | Optional UI hint; stored for later presentation work. |
|
|
73
|
+
|
|
74
|
+
Aliases accepted for compatibility: `allowed-tools`, `disallowed-tools`, `maxTurns`,
|
|
75
|
+
`run_in_background`, `systemPromptMode`, `effort` (as `thinking`).
|
|
76
|
+
|
|
77
|
+
Unsupported fields such as `hooks`, `mcpServers`, `skills`, `memory`, `isolation`,
|
|
78
|
+
`permission` and `permissionMode` are ignored with a warning. They are not silently reinterpreted.
|
|
79
|
+
|
|
80
|
+
## Discovery
|
|
81
|
+
|
|
82
|
+
Scanned recursively, lowest priority first; a later directory overrides the same name:
|
|
83
|
+
|
|
84
|
+
1. `$PI_CODING_AGENT_DIR/agents/**/*.md`, or `~/.config/pi/agent/agents/**/*.md` and
|
|
85
|
+
`~/.pi/agent/agents/**/*.md`
|
|
86
|
+
2. `$XDG_CONFIG_HOME/repi/agents/**/*.md` (default `~/.config/repi/agents`)
|
|
87
|
+
3. `<project>/.pi/agents/**/*.md`
|
|
88
|
+
4. `<project>/.repi/agents/**/*.md` (highest)
|
|
89
|
+
|
|
90
|
+
Project directories are skipped when Pi reports the workspace as untrusted. Hidden directories,
|
|
91
|
+
`node_modules`, `.git` and `*.chain.md` files are ignored. `/subagents reload` rescans without
|
|
92
|
+
restarting Pi.
|
|
93
|
+
|
|
94
|
+
## JSON overrides
|
|
95
|
+
|
|
96
|
+
Markdown remains the declaration format, but frontmatter values can be overridden without editing
|
|
97
|
+
the file. Overrides live in:
|
|
98
|
+
|
|
99
|
+
1. `$XDG_CONFIG_HOME/repi/subagents.json` (default `~/.config/repi/subagents.json`)
|
|
100
|
+
2. `<project>/.repi/subagents.json` (highest priority; skipped when the workspace is untrusted)
|
|
101
|
+
|
|
102
|
+
Both files are optional. Within JSON, project values win over user values. JSON is applied after
|
|
103
|
+
Markdown discovery, so it overrides the already-resolved Markdown definition. The JSON file cannot
|
|
104
|
+
create an agent that has no Markdown declaration.
|
|
105
|
+
|
|
106
|
+
```json
|
|
107
|
+
{
|
|
108
|
+
"version": 1,
|
|
109
|
+
"agents": {
|
|
110
|
+
"scout": {
|
|
111
|
+
"description": "Project-specific reconnaissance agent",
|
|
112
|
+
"tools": ["read", "grep", "find", "ls"],
|
|
113
|
+
"disallowedTools": ["bash"],
|
|
114
|
+
"model": "antigravity/gemini-3.8-flash",
|
|
115
|
+
"fallbackModels": ["anthropic/claude-3-5-sonnet", "inherit"],
|
|
116
|
+
"thinking": "high",
|
|
117
|
+
"maxTurns": 40,
|
|
118
|
+
"background": true,
|
|
119
|
+
"promptMode": "append",
|
|
120
|
+
"color": "cyan",
|
|
121
|
+
"systemPrompt": "You are a read-only scout for this repository."
|
|
122
|
+
},
|
|
123
|
+
"Explore": {
|
|
124
|
+
"enabled": false
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Agent names are case-insensitive. Supported fields are `description`, `tools`,
|
|
131
|
+
`disallowedTools`, `model`, `fallbackModels`, `thinking`, `maxTurns`, `background`, `promptMode`, `color`,
|
|
132
|
+
`enabled` and `systemPrompt`. Frontmatter-style aliases (`max_turns`, `prompt_mode`,
|
|
133
|
+
`disallowed_tools`, `run_in_background`, `systemPromptMode`, `effort`, `allowed-tools`, `prompt`,
|
|
134
|
+
`system_prompt`, `fallback_models`, `fallbacks`, `fallback_model`) and their hyphenated variants are accepted as well.
|
|
135
|
+
|
|
136
|
+
Special values:
|
|
137
|
+
|
|
138
|
+
- `null` removes that field from a lower-priority JSON layer and falls back to the Markdown value.
|
|
139
|
+
- `"model": "inherit"` / `"thinking": "inherit"` clears a model or thinking level declared in Markdown.
|
|
140
|
+
- `"maxTurns": 0` removes a Markdown turn limit.
|
|
141
|
+
- `"tools": "inherit"` resets the allowlist to the default built-in tools; `"none"` / `[]` means no tools; `"*"` means every parent tool.
|
|
142
|
+
- `"enabled": false` hides the agent. A higher-priority layer can re-enable it.
|
|
143
|
+
- `systemPrompt` replaces the Markdown body; `promptMode` then decides append vs replace.
|
|
144
|
+
|
|
145
|
+
Malformed JSON, unknown fields, unknown agent names and invalid values are reported by
|
|
146
|
+
`/subagents list` and `subagent_list`. Invalid values leave the Markdown value in place. The list
|
|
147
|
+
also shows which override files were read. Re-read both files with `/subagents reload`.
|
|
148
|
+
|
|
149
|
+
## Tools
|
|
150
|
+
|
|
151
|
+
| Tool | Purpose |
|
|
152
|
+
|---|---|
|
|
153
|
+
| `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. |
|
|
154
|
+
| `subagent_status` | One run by `id`, or every run in the session. |
|
|
155
|
+
| `subagent_wait` | Wait for `ids` (default: all active runs) with `timeoutMs` (default 120000). |
|
|
156
|
+
| `subagent_abort` | Abort a queued or running run. |
|
|
157
|
+
| `subagent_list` | Agents, discovery directories, override config files, diagnostics and runs. |
|
|
158
|
+
|
|
159
|
+
`/subagents` prints the same catalogue; `/subagents reload` rescans the files; `/subagents fleet` opens
|
|
160
|
+
the live dashboard described below; `/subagents stop` stops all active subagents (or `/subagents stop <id>` stops a specific run).
|
|
161
|
+
|
|
162
|
+
`Tab` completes `/subagents ` to `fleet|list|reload|stop`, and `Tab` after `fleet ` or `stop ` lists
|
|
163
|
+
the run ids of the current session — generated ids cannot be typed from memory, so this is the way
|
|
164
|
+
to address one run without opening the dashboard. `fleet` also accepts a run id to open straight on
|
|
165
|
+
that run.
|
|
166
|
+
|
|
167
|
+
Children never receive `subagent*` tools, so a child cannot spawn grandchildren and make
|
|
168
|
+
wait/abort ownership ambiguous.
|
|
169
|
+
|
|
170
|
+
### What the model sees before it calls the tool
|
|
171
|
+
|
|
172
|
+
Delegation quality depends on three surfaces, and each one has exactly one owner:
|
|
173
|
+
|
|
174
|
+
1. **`<rules>`** — the `subagent` tool declares `promptGuidelines`, so Pi renders five bullets in
|
|
175
|
+
the ordinary system-prompt rules block, next to the `bash`/`read`/`edit` rules: delegate broad
|
|
176
|
+
multi-file exploration, keep one-off lookups inline, fan out independent questions in one turn,
|
|
177
|
+
write self-contained briefs, and never delegate understanding. They are attached to the tool
|
|
178
|
+
definition, so they disappear when the tool is inactive and never appear in children (which
|
|
179
|
+
exclude `subagent*`). `promptSnippet` adds the tool to Pi's `Available tools` list.
|
|
180
|
+
2. **`<repi_subagents>`** — the catalogue injected from `before_agent_start`: name, description and
|
|
181
|
+
tool allowlist for every agent discovered on disk (user directories, project `.pi/agents` and
|
|
182
|
+
`.repi/agents`, plus override files), capped at 24 entries. It closes with "do not call
|
|
183
|
+
`subagent_list` to discover agents", because the list is already complete.
|
|
184
|
+
3. **`<repi_subagent_runs>`** — runs in flight, so the model does not launch a duplicate. The
|
|
185
|
+
section is deleted when nothing is active, so Pi patches the prompt back to its old shape.
|
|
186
|
+
|
|
187
|
+
## Isolation and permissions
|
|
188
|
+
|
|
189
|
+
Each run gets an in-process child Pi session:
|
|
190
|
+
|
|
191
|
+
- `SessionManager.inMemory()` — no transcript is written for P0.
|
|
192
|
+
- A scoped `DefaultResourceLoader` with `noExtensions`, `noSkills`, `noPromptTemplates`,
|
|
193
|
+
`noThemes` and `noContextFiles`, plus a temporary `agentDir` for settings isolation. The
|
|
194
|
+
loader `cwd` stays the real project so the prompt's `<cwd>` matches tool execution; ambient
|
|
195
|
+
packages, project extensions, skills, themes, prompt templates and `AGENTS.md` do **not** leak
|
|
196
|
+
into the child.
|
|
197
|
+
- **Requested tools bring their own extensions.** After the allowlist is resolved, the parent's
|
|
198
|
+
`getAllTools()` provenance decides which extension modules the child needs. Those modules are
|
|
199
|
+
passed as `additionalExtensionPaths`, so an agent that declares `web_search` gets the
|
|
200
|
+
extension that registers `web_search` — not a second copy of every ambient plugin. Host built-ins
|
|
201
|
+
(`codemode`, `tool_search`, MCP resource tools) are recreated through the SDK factories because
|
|
202
|
+
SDK-created sessions do not load CLI built-ins. The parent `@restranger/repi-permission-system-core`, `@restranger/repi-permission-modes`
|
|
203
|
+
and `@restranger/repi-ui` extensions register no child tools, so they stay parent-side; `subagent*` is
|
|
204
|
+
always removed and `@restranger/repi-subagents` is never loaded recursively.
|
|
205
|
+
- **Custom providers keep their runtime.** The child receives the parent's `ModelRuntime`
|
|
206
|
+
(`ctx.modelRegistry.runtime`) instead of building a new one against the temporary `agentDir`.
|
|
207
|
+
Extension-registered providers, OAuth credentials and per-provider API adapters therefore work
|
|
208
|
+
exactly as in the parent — a child can use `opencode-free/*`, `antigravity/*` or any other
|
|
209
|
+
keyless/header-authenticated provider without re-authenticating.
|
|
210
|
+
- Only the declaration's body (appended to Pi's base prompt or replacing it), model/thinking level,
|
|
211
|
+
tool allowlist and the extensions that provide those tools are inherited.
|
|
212
|
+
- No parent conversation is inherited (fresh context); put all needed context in `task` (`prompt` is
|
|
213
|
+
accepted as an alias for Claude-style callers).
|
|
214
|
+
|
|
215
|
+
When `@restranger/repi-permission-system-core` is installed, every child tool call is checked against the **parent
|
|
216
|
+
session's** `re:permissions@1` service with `source: "subagent"`. Hard denies and the parent's
|
|
217
|
+
active mode therefore still apply. P0 fails closed on `ask` (there is no parent-prompt routing
|
|
218
|
+
yet). Without `@restranger/repi-permission-system-core`, the declaration's `tools:` list is the authority.
|
|
219
|
+
|
|
220
|
+
## Concurrency and background runs
|
|
221
|
+
|
|
222
|
+
Subagent runs share an in-process FIFO pool (default 4 concurrent). Concurrency can be configured via:
|
|
223
|
+
1. Programmatic option: `maxConcurrent` in `SubagentsPluginOptions`.
|
|
224
|
+
2. JSON override config: `"maxConcurrent": 8` in `.repi/subagents.json` or `~/.config/repi/subagents.json`.
|
|
225
|
+
|
|
226
|
+
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.
|
|
227
|
+
|
|
228
|
+
## UI
|
|
229
|
+
|
|
230
|
+
Three surfaces share the manager's live run table. All of them are display-width aware: SGR
|
|
231
|
+
colours survive truncation, while cursor movement, OSC titles and other control sequences are
|
|
232
|
+
stripped from child/tool text before it reaches the terminal.
|
|
233
|
+
|
|
234
|
+
- **Inline progress.** A foreground `subagent` call streams into its own tool call through
|
|
235
|
+
`onUpdate`: status, elapsed time, tool count, turn budget, the two most recent finished steps
|
|
236
|
+
and the child's current tool (`↳ bash bun run test`). The result card ends with the outcome or
|
|
237
|
+
error. The widget stays out of the way of foreground runs, so the same progress is never shown
|
|
238
|
+
twice.
|
|
239
|
+
- **Status widget above the editor.** A tree of background runs plus the runs that just finished:
|
|
240
|
+
`Agents · 2 active · 1 finished · 14.2k tok`, one branch per run, the current child tool under
|
|
241
|
+
the active row, tool count, tokens, turn budget and the result/error preview for finished rows.
|
|
242
|
+
A completed run leaves the widget on the parent's next turn (errors and aborts after two turns),
|
|
243
|
+
and the widget is unmounted when nothing is left to show. Every line is truncated to the
|
|
244
|
+
`render(width)` value and the whole widget is bounded by `terminal.rows` (3–12 lines, six rows
|
|
245
|
+
reserved for the dock), so it cannot push Pi's editor off screen. Hosts without a TUI (RPC,
|
|
246
|
+
print, JSON) receive plain lines instead of the component.
|
|
247
|
+
- **`/subagents fleet` inspector.** An overlay pane (`anchor: "center"`, `width: "95%"`, `maxHeight: "85%"`) —
|
|
248
|
+
matching `pi-subagents` — with a bordered roster on the left and the selected run on the right: status, id/model, elapsed time, tool count, tokens, turn budget,
|
|
249
|
+
current tool, step tree, forwarded extensions, diagnostics, the task and the output/error.
|
|
250
|
+
`Enter` expands the detail to the full pane; `u`/`d` or page keys scroll it. Navigation uses
|
|
251
|
+
Pi's keybindings (`tui.select.up`/`down`/`confirm`/`cancel`), so a remap in
|
|
252
|
+
`keybindings.json` applies; `j`/`k`, `Enter`, `x` and `q`/`Esc` work regardless. `x` arms
|
|
253
|
+
cancellation and a second `x`/`y` confirms it; `n`/`Esc` keeps the run. The roster scrolls to
|
|
254
|
+
keep the selection visible and the footer prints the bindings actually configured. In hosts
|
|
255
|
+
without a custom TUI component the same dashboard is emitted as a text notification.
|
|
256
|
+
|
|
257
|
+
Activity comes from the child session's `tool_execution_start`/`tool_execution_end` events and
|
|
258
|
+
from assistant turns, so the surfaces reflect the child's work without parsing its transcript.
|
|
259
|
+
The inspector keeps the chronological step list (`SubagentStep[]`), not the full conversation.
|
|
260
|
+
|
|
261
|
+
## P0 limitations / next steps
|
|
262
|
+
|
|
263
|
+
- No parent-context fork, steering, intercom or batch fan-out. The `/subagents fleet` inspector is read-only
|
|
264
|
+
apart from cancelling a run; result handoff into the parent conversation is still manual via
|
|
265
|
+
`subagent_wait`.
|
|
266
|
+
- No transcript drill-in: child sessions are in-memory (`SessionManager.inMemory()`), so `/subagents fleet`
|
|
267
|
+
shows the result preview and the recent tool list, not the child's conversation.
|
|
268
|
+
- No Git worktree isolation; all children share the parent `cwd`.
|
|
269
|
+
- No shared task board or DAG tasks.
|
|
270
|
+
- `ask` is denied inside children until parent prompt routing lands.
|
|
271
|
+
- No structured `yield_result` contract; the final assistant text is the result.
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@restranger/repi-subagents",
|
|
3
|
+
"version": "0.0.1-sha.2ba2721",
|
|
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-sha.2ba2721"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@earendil-works/pi-coding-agent": ">=0.79.0"
|
|
35
|
+
},
|
|
36
|
+
"peerDependenciesMeta": {
|
|
37
|
+
"@earendil-works/pi-coding-agent": {
|
|
38
|
+
"optional": true
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -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
|
+
}
|