@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.6

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1244 -2
  3. package/package.json +75 -4
  4. package/src/abortable.ts +43 -0
  5. package/src/agent-color.ts +161 -0
  6. package/src/agent-file-toggle.ts +297 -0
  7. package/src/agent-manager.ts +1874 -0
  8. package/src/agent-runner.ts +1552 -0
  9. package/src/agent-source-badge.ts +75 -0
  10. package/src/agent-types.ts +346 -0
  11. package/src/child-context.ts +15 -0
  12. package/src/clock.ts +25 -0
  13. package/src/completion-outbox.ts +125 -0
  14. package/src/context.ts +58 -0
  15. package/src/cross-extension-rpc.ts +221 -0
  16. package/src/custom-agents.ts +436 -0
  17. package/src/default-agents.ts +126 -0
  18. package/src/detached-results.ts +134 -0
  19. package/src/enabled-models.ts +180 -0
  20. package/src/enterprise-local.ts +66 -0
  21. package/src/env.ts +33 -0
  22. package/src/group-join.ts +148 -0
  23. package/src/index.ts +4423 -0
  24. package/src/invocation-config.ts +189 -0
  25. package/src/memory.ts +179 -0
  26. package/src/mention-clone.ts +195 -0
  27. package/src/mention.ts +141 -0
  28. package/src/model-call.ts +83 -0
  29. package/src/model-resolver.ts +266 -0
  30. package/src/model-scope.ts +70 -0
  31. package/src/nested-tools.ts +448 -0
  32. package/src/output-file.ts +164 -0
  33. package/src/package-resources.ts +624 -0
  34. package/src/prompts.ts +156 -0
  35. package/src/quota-admission.ts +99 -0
  36. package/src/schedule-store.ts +153 -0
  37. package/src/schedule.ts +446 -0
  38. package/src/settings.ts +728 -0
  39. package/src/skill-loader.ts +137 -0
  40. package/src/startup-error.ts +29 -0
  41. package/src/status-note.ts +90 -0
  42. package/src/structured-output.ts +130 -0
  43. package/src/types.ts +404 -0
  44. package/src/ui/agent-mention.ts +216 -0
  45. package/src/ui/agent-row.ts +235 -0
  46. package/src/ui/agent-widget.ts +692 -0
  47. package/src/ui/conversation-viewer.ts +832 -0
  48. package/src/ui/fleet-list.ts +675 -0
  49. package/src/ui/notification-view.ts +120 -0
  50. package/src/ui/schedule-menu.ts +105 -0
  51. package/src/ui/select-item.ts +45 -0
  52. package/src/ui/viewer-keys.ts +39 -0
  53. package/src/ui/workflow-card.ts +462 -0
  54. package/src/ui/workflow-dialog.ts +1115 -0
  55. package/src/ui/workflow-menu.ts +193 -0
  56. package/src/usage.ts +167 -0
  57. package/src/workflow/collisions.ts +123 -0
  58. package/src/workflow/entry.ts +47 -0
  59. package/src/workflow/host.ts +401 -0
  60. package/src/workflow/journal.ts +164 -0
  61. package/src/workflow/json-schema.ts +129 -0
  62. package/src/workflow/meta.ts +326 -0
  63. package/src/workflow/progress.ts +549 -0
  64. package/src/workflow/runtime.ts +1216 -0
  65. package/src/workflow/saved.ts +259 -0
  66. package/src/workflow/task.ts +302 -0
  67. package/src/workflow/tool-description.ts +200 -0
  68. package/src/workflow/worker-source.ts +781 -0
  69. package/src/worktree.ts +230 -0
  70. package/src/xml.ts +13 -0
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Cross-extension RPC handlers for the subagents extension.
3
+ *
4
+ * Exposes ping, spawn, stop, consume, and steer RPCs over the pi.events event bus,
5
+ * using per-request scoped reply channels.
6
+ *
7
+ * Reply envelope follows pi-mono convention:
8
+ * success → { success: true, data?: T }
9
+ * error → { success: false, error: string }
10
+ *
11
+ * @see docs/rpc.md — the caller-facing integration reference: spawn options
12
+ * (including the fields spawnTopLevel strips), every error string, the
13
+ * completion-notification race, and what protocol version 2 does not promise.
14
+ */
15
+
16
+ import { isTopLevelAgent } from "./agent-manager.js";
17
+ import { type ModelRegistry, resolveModel } from "./model-resolver.js";
18
+ import { checkModelScope } from "./model-scope.js";
19
+ import type { AgentRecord } from "./types.js";
20
+
21
+ /** Minimal event bus interface needed by the RPC handlers. */
22
+ export interface EventBus {
23
+ on(event: string, handler: (data: unknown) => void): () => void;
24
+ emit(event: string, data: unknown): void;
25
+ }
26
+
27
+ /** RPC reply envelope — matches pi-mono's RpcResponse shape. */
28
+ export type RpcReply<T = void> =
29
+ | { success: true; data?: T }
30
+ | { success: false; error: string };
31
+
32
+ /** RPC protocol version — bumped when the envelope or method contracts change. */
33
+ export const PROTOCOL_VERSION = 2;
34
+
35
+ /** Minimal AgentManager interface needed by the spawn/stop/consume RPCs. */
36
+ export interface SpawnCapable {
37
+ spawn(pi: unknown, ctx: unknown, type: string, prompt: string, options: any): string;
38
+ /** Resolves once the spawned agent is running; rejects on a startup failure. */
39
+ awaitStartup(id: string): Promise<void>;
40
+ abort(id: string): boolean;
41
+ /**
42
+ * The record behind an id, for the stop handler's ownership check. Narrowed
43
+ * to the two fields `isTopLevelAgent` reads, so the RPC layer keeps its
44
+ * deliberately shallow view of the manager.
45
+ */
46
+ getRecord(id: string): Pick<AgentRecord, "parentAgentId" | "workflowId"> | undefined;
47
+ /**
48
+ * Mark a settled agent's result as read by the caller, suppressing the
49
+ * completion notification — what `get_subagent_result` does when it returns
50
+ * one. False when there is no such agent, or it has not settled yet.
51
+ */
52
+ consumeResult(id: string): boolean;
53
+ /**
54
+ * Deliver a message to a running or queued agent's conversation — what
55
+ * `steer_subagent` does. False when the agent is unknown or has settled.
56
+ */
57
+ steer(id: string, message: string): boolean;
58
+ }
59
+
60
+ export interface RpcDeps {
61
+ events: EventBus;
62
+ pi: unknown; // passed through to manager.spawn
63
+ getCtx: () => unknown | undefined; // returns current ExtensionContext
64
+ manager: SpawnCapable;
65
+ }
66
+
67
+ export interface RpcHandle {
68
+ unsubPing: () => void;
69
+ unsubSpawn: () => void;
70
+ unsubStop: () => void;
71
+ unsubConsume: () => void;
72
+ unsubSteer: () => void;
73
+ }
74
+
75
+ /**
76
+ * Wire a single RPC handler: listen on `channel`, run `fn(params)`,
77
+ * emit the reply envelope on `channel:reply:${requestId}`.
78
+ */
79
+ function handleRpc<P extends { requestId: string }>(
80
+ events: EventBus,
81
+ channel: string,
82
+ fn: (params: P) => unknown | Promise<unknown>,
83
+ ): () => void {
84
+ return events.on(channel, async (raw: unknown) => {
85
+ const params = raw as P;
86
+ try {
87
+ const data = await fn(params);
88
+ const reply: { success: true; data?: unknown } = { success: true };
89
+ if (data !== undefined) reply.data = data;
90
+ events.emit(`${channel}:reply:${params.requestId}`, reply);
91
+ } catch (err: any) {
92
+ events.emit(`${channel}:reply:${params.requestId}`, {
93
+ success: false, error: err?.message ?? String(err),
94
+ });
95
+ }
96
+ });
97
+ }
98
+
99
+ /**
100
+ * Register ping, spawn, stop, consume, and steer RPC handlers on the event bus.
101
+ * Returns unsub functions for cleanup.
102
+ */
103
+ export function registerRpcHandlers(deps: RpcDeps): RpcHandle {
104
+ const { events, pi, getCtx, manager } = deps;
105
+
106
+ const unsubPing = handleRpc(events, "subagents:rpc:ping", () => {
107
+ return { version: PROTOCOL_VERSION };
108
+ });
109
+
110
+ const unsubSpawn = handleRpc<{ requestId: string; type: string; prompt: string; options?: any }>(
111
+ events, "subagents:rpc:spawn", async ({ type, prompt, options }) => {
112
+ const ctx = getCtx();
113
+ if (!ctx) throw new Error("No active session");
114
+
115
+ // Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
116
+ // forward serializable values, so options.model can be a string like
117
+ // "openai-codex/gpt-5.5". Resolve it to a real Model instance here
118
+ // — same pattern the scheduler path already uses — so the spawned
119
+ // agent's auth lookup doesn't crash with "No API key found for
120
+ // undefined".
121
+ let normalizedOptions = options ?? {};
122
+ // `!= null` on purpose: a JSON-forwarding caller can serialize an unset
123
+ // field as null, and the runner reads `options.model ?? default`, so null
124
+ // means "inherit" — not an override to resolve or scope-check.
125
+ const override = normalizedOptions.model;
126
+ if (override != null) {
127
+ const { modelRegistry, cwd } = ctx as { modelRegistry?: ModelRegistry; cwd?: string };
128
+ // Names the override the same way in both messages below; an object
129
+ // override would otherwise interpolate as "[object Object]".
130
+ const label = typeof override === "string" ? override : `${override.provider}/${override.id}`;
131
+ if (!modelRegistry) {
132
+ throw new Error(`Model override "${label}" provided but ctx.modelRegistry is unavailable`);
133
+ }
134
+ let model = override;
135
+ if (typeof override === "string") {
136
+ const resolved = resolveModel(override, modelRegistry);
137
+ if (typeof resolved === "string") {
138
+ // resolveModel returns a human-readable error string when the
139
+ // input doesn't match any available model. Surface it instead of
140
+ // silently falling back so the caller sees the auth/typo issue.
141
+ throw new Error(resolved);
142
+ }
143
+ model = resolved;
144
+ normalizedOptions = { ...normalizedOptions, model: resolved };
145
+ }
146
+
147
+ // A model on the RPC payload is an orchestrator-level choice, exactly
148
+ // like Agent({ model }) — so it gets the Agent tool's hard error, never
149
+ // the frontmatter warn (#240). The check reads the RESOLVED model:
150
+ // resolveModel is fuzzy, so a bare "sonnet" can land on a provider the
151
+ // caller never named. Frontmatter-pinned and parent-inherited models are
152
+ // resolved later, in agent-runner, and keep warn-and-proceed.
153
+ const verdict = checkModelScope({
154
+ model,
155
+ cwd: cwd ?? process.cwd(),
156
+ modelRegistry,
157
+ callerSupplied: true,
158
+ agentLabel: type,
159
+ modelInput: label,
160
+ });
161
+ if (verdict.kind === "error") throw new Error(verdict.message);
162
+ }
163
+
164
+ const id = manager.spawn(pi, ctx, type, prompt, normalizedOptions);
165
+ // With isolation: "worktree" the agent starts asynchronously — wait for
166
+ // it, so a strict-isolation failure is still an error envelope rather
167
+ // than an id for an agent that never ran.
168
+ await manager.awaitStartup(id);
169
+ return { id };
170
+ },
171
+ );
172
+
173
+ // Only the session's own agents are this RPC's to stop or steer. A nested
174
+ // child or a workflow's agent is owned by something that is *waiting on it*,
175
+ // and aborting or redirecting it out from under that owner turns another
176
+ // extension's request into a failed step here. Defence in depth rather than
177
+ // a live hole: no RPC hands out agent ids, so a caller has no ordinary way to
178
+ // name one it does not own — but the guard is cheap and the id may leak some
179
+ // other way. Same refuse-what-we-should-not-touch stance as `consume` below.
180
+ const assertOwned = (agentId: string): void => {
181
+ const record = manager.getRecord(agentId);
182
+ if (!record) throw new Error("Agent not found");
183
+ if (!isTopLevelAgent(record)) throw new Error("Agent is owned by another agent or workflow");
184
+ };
185
+
186
+ const unsubStop = handleRpc<{ requestId: string; agentId: string }>(
187
+ events, "subagents:rpc:stop", ({ agentId }) => {
188
+ assertOwned(agentId);
189
+ // Not "not found" — the lookup above already proved it exists. `abort`
190
+ // returns false only for a record that is neither running nor queued,
191
+ // which is an agent that has already finished.
192
+ if (!manager.abort(agentId)) throw new Error("Agent is not running");
193
+ },
194
+ );
195
+
196
+ // A caller that has already shown the model an agent's result — pi-tasks'
197
+ // TaskOutput is the one in practice — says so here, so the completion
198
+ // notification for that same result is not delivered on top of it and does
199
+ // not cost the parent a turn. Deliberately outside the ping version
200
+ // handshake: an extension built against protocol v2 simply never calls it.
201
+ const unsubConsume = handleRpc<{ requestId: string; agentId: string }>(
202
+ events, "subagents:rpc:consume", ({ agentId }) => {
203
+ if (!manager.consumeResult(agentId)) throw new Error("Agent not found or still running");
204
+ },
205
+ );
206
+
207
+ // An extension that spawned an agent over the bus and then learns something
208
+ // that agent needs — a second CI failure on the head it is already fixing, a
209
+ // review that landed mid-run — can hand it over instead of spawning a second
210
+ // agent for the same work or dropping the fact. Outside the ping version
211
+ // handshake, like consume: additive and best-effort.
212
+ const unsubSteer = handleRpc<{ requestId: string; agentId: string; message: unknown }>(
213
+ events, "subagents:rpc:steer", ({ agentId, message }) => {
214
+ if (typeof message !== "string" || message.trim().length === 0) throw new Error("Steer message must be a non-empty string");
215
+ assertOwned(agentId);
216
+ if (!manager.steer(agentId, message)) throw new Error("Agent is not running");
217
+ },
218
+ );
219
+
220
+ return { unsubPing, unsubSpawn, unsubStop, unsubConsume, unsubSteer };
221
+ }
@@ -0,0 +1,436 @@
1
+ /**
2
+ * custom-agents.ts — Load user-defined agents from project (.pi/agents/, plus the shared .agents/agents/ workspace) and global ($PI_CODING_AGENT_DIR/agents/, default ~/.pi/agent/agents/) locations, plus any installed pi package that declares them (see package-resources.ts).
3
+ */
4
+
5
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
6
+ import { basename, join } from "node:path";
7
+ import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
+ import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
9
+ import {
10
+ isPackageResourceExcluded,
11
+ isProjectTrusted,
12
+ MAX_PACKAGE_RESOURCE_BYTES,
13
+ packageAgentDirs,
14
+ packageAgentFiles,
15
+ } from "./package-resources.js";
16
+ import type { AgentConfig, IsolationMode, MemoryScope, ThinkingLevel } from "./types.js";
17
+
18
+ /**
19
+ * The one thing a declared `name:` may not contain, matching Claude Code
20
+ * exactly: it reserves `:` for plugin-scoped identifiers (`my-plugin:reviewer`)
21
+ * and refuses to load a file whose name uses one.
22
+ *
23
+ * Nothing else is rejected. Claude Code's docs describe names as "lowercase
24
+ * letters and hyphens", but that is guidance — the only stated load failure is
25
+ * the colon, so `name: Code Reviewer` must work here too. (The stricter
26
+ * letters/digits/underscore/hyphen regex in Claude Code applies to the Agent
27
+ * tool's spawn-time `name` parameter, which is a different field.) Mixed case
28
+ * has to be allowed regardless: the built-in types `Explore` and `Plan` use it,
29
+ * and a file must be able to override one.
30
+ */
31
+ const RESERVED_IN_TYPE = ":";
32
+
33
+ /** Where an agent file was found. Widens `AgentConfig.source` for the loader. */
34
+ type AgentSource = "project" | "global" | "package";
35
+
36
+ /** Answers whether a `!` entry in some package manifest excludes this path. */
37
+ type Excluder = (path: string) => boolean;
38
+
39
+ /**
40
+ * Overrides for the package tier. The gate and project-trust state normally come
41
+ * from the session values in package-resources.ts, so these exist for tests and
42
+ * for a caller that has to pin a scan it already performed.
43
+ */
44
+ export interface LoadCustomAgentsOptions {
45
+ /** Explicit package directories, bypassing discovery. */
46
+ packageDirs?: string[];
47
+ /** Explicit package files, bypassing discovery. */
48
+ packageFiles?: string[];
49
+ /** Explicit `!` exclusion predicate, bypassing discovery. */
50
+ packageExcluded?: Excluder;
51
+ /**
52
+ * Whether pi trusts the project at `cwd`. Gates the project roots and, for
53
+ * discovered packages, the project's `.pi/settings.json`. Omitted falls back to
54
+ * the session state in package-resources.ts, which is untrusted until pi's
55
+ * answer is recorded.
56
+ */
57
+ projectTrusted?: boolean;
58
+ }
59
+
60
+ /**
61
+ * Scan for custom agent .md files from multiple locations.
62
+ * Discovery hierarchy (higher priority wins):
63
+ * 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
64
+ * 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
65
+ * 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
66
+ * 4. Package: paths declared by an installed pi package (read-only)
67
+ *
68
+ * The two project roots are project-supplied content and load only when pi
69
+ * trusts the project (`opts.projectTrusted`, else the session state). Untrusted,
70
+ * they are not even read: they cannot override a global or package agent, and a
71
+ * malformed file in them neither warns nor, under `strict`, throws. Global agents
72
+ * and globally configured packages are unaffected; packages configured only by
73
+ * the project's `.pi/settings.json` are gated by the same decision.
74
+ *
75
+ * Project-level agents override global ones with the same name. On a name clash
76
+ * between the two project locations, .pi/agents wins — .pi stays the project
77
+ * authority; .agents/agents is an additional read location.
78
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
79
+ *
80
+ * Package agents load *first*, so everything the user or project wrote outranks
81
+ * them. That is what makes them safe to adopt: a package can offer a `reviewer`,
82
+ * and a `.pi/agents/reviewer.md` silently takes it back. It mirrors pi's own
83
+ * resource precedence, where package-provided skills rank below every user and
84
+ * project one, and Claude Code's, where a plugin agent is the lowest tier.
85
+ *
86
+ * An agent's type comes from its frontmatter `name:`, falling back to the
87
+ * filename — Claude Code's rule, where "the filename doesn't have to match".
88
+ * Because the type is now declared rather than derived from a unique path, two
89
+ * files can claim the same one; the later load wins, as it always has for a
90
+ * filename clash, and `warnSkippedOverride` reports the substitution.
91
+ */
92
+ export function loadCustomAgents(
93
+ cwd: string,
94
+ strict = false,
95
+ opts: LoadCustomAgentsOptions = {},
96
+ ): Map<string, AgentConfig> {
97
+ const globalDir = join(getAgentDir(), "agents");
98
+ const workspaceProjectDir = join(cwd, ".agents", "agents");
99
+ const projectDir = join(cwd, ".pi", "agents");
100
+
101
+ const projectTrusted = opts.projectTrusted ?? isProjectTrusted();
102
+ const pkgDirs = opts.packageDirs ?? packageAgentDirs(cwd, { projectTrusted });
103
+ const pkgFiles = opts.packageFiles ?? packageAgentFiles(cwd, { projectTrusted });
104
+ // `!./agents/wip.md` alongside `./agents` excludes one file out of a directory
105
+ // that is only enumerated here, so the check has to run per file.
106
+ const excluded: Excluder = opts.packageExcluded ?? (path => isPackageResourceExcluded(path, cwd, "agents", { projectTrusted }));
107
+
108
+ const agents = new Map<string, AgentConfig>();
109
+ for (const dir of pkgDirs) loadFromDir(dir, agents, "package", strict, excluded); // lowest priority
110
+ for (const file of pkgFiles) loadOneFile(file, agents, "package", strict);
111
+ loadFromDir(globalDir, agents, "global", strict);
112
+ if (projectTrusted) {
113
+ loadFromDir(workspaceProjectDir, agents, "project", strict); // shared workspace
114
+ loadFromDir(projectDir, agents, "project", strict); // highest priority (overwrites)
115
+ }
116
+
117
+ warnedLastLoad = warnedThisLoad;
118
+ warnedThisLoad = new Set();
119
+ return agents;
120
+ }
121
+
122
+ /** Load agent configs from a directory into the map, skipping any `excluded` path. */
123
+ function loadFromDir(
124
+ dir: string,
125
+ agents: Map<string, AgentConfig>,
126
+ source: AgentSource,
127
+ strict: boolean,
128
+ excluded?: Excluder,
129
+ ): void {
130
+ if (!existsSync(dir)) return;
131
+
132
+ let files: string[];
133
+ try {
134
+ files = readdirSync(dir).filter(f => f.endsWith(".md"));
135
+ } catch {
136
+ return;
137
+ }
138
+
139
+ for (const file of files) {
140
+ const path = join(dir, file);
141
+ if (excluded?.(path)) continue;
142
+ loadOneFile(path, agents, source, strict);
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Load one agent file into the map.
148
+ *
149
+ * Split out of `loadFromDir` because a package manifest may name an individual
150
+ * `.md` rather than a directory, and because the size guard below has to apply
151
+ * to both paths.
152
+ */
153
+ function loadOneFile(path: string, agents: Map<string, AgentConfig>, source: AgentSource, strict: boolean): void {
154
+ const filenameType = basename(path, ".md");
155
+
156
+ // Package files are third-party content read on every `Agent` call, so a
157
+ // pathological one is skipped rather than pulled into the session. Claude
158
+ // Code applies the same 1 MB ceiling to plugin-provided agents. Local files
159
+ // are the user's own and stay unbounded, as they always have been.
160
+ if (source === "package" && !withinSizeLimit(path)) {
161
+ warnIfNew(`Skipping package agent ${path}: not a regular file, or larger than ${MAX_PACKAGE_RESOURCE_BYTES} bytes.`);
162
+ return;
163
+ }
164
+
165
+ // `strict` is deliberately not passed for a package file. Failing activation
166
+ // over a broken agent file is right for a checked-in `.pi/agents/` — the point
167
+ // is that a repo's own file cannot silently fall through to a same-named one
168
+ // elsewhere. A file inside a third-party package is not the user's to fix, and
169
+ // one bad `.md` in any installed package would otherwise stop pi from
170
+ // starting at all. Warn and skip, as for a non-strict local file.
171
+ const parsed = readAgentFile(path, strict && source !== "package");
172
+ if (!parsed) {
173
+ warnSkippedOverride(filenameType, agents);
174
+ return;
175
+ }
176
+ const { frontmatter: fm, body } = parsed;
177
+
178
+ // Claude Code's rule: `name:` IS the agent type, and the filename need not
179
+ // match. Absent, the filename stands in — Claude Code requires the field,
180
+ // but most files here predate it and must keep loading.
181
+ const declared = str(fm.name)?.trim();
182
+ if (declared?.includes(RESERVED_IN_TYPE)) {
183
+ // Refusing beats silently substituting: the file would otherwise load
184
+ // under its filename, so `Agent({subagent_type})` would succeed against
185
+ // an agent whose declared identity nothing honoured.
186
+ warnIfNew(
187
+ `Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
188
+ + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.",
189
+ );
190
+ // No `warnSkippedOverride`: this file would have registered under its
191
+ // *declared* name, which nothing else can hold (a colon keeps it out of
192
+ // the registry), so it shadowed nothing. Passing the filename instead
193
+ // would report a substitution of an unrelated agent that never happened.
194
+ return;
195
+ }
196
+ // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
197
+ // register the agent under the empty type — unspawnable, and it takes the
198
+ // filename-derived one down with it.
199
+ const name = declared || filenameType;
200
+
201
+ const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
202
+
203
+ agents.set(name, {
204
+ name,
205
+ // Only `display_name` now: `name` is the type, and `getConfig` already
206
+ // falls back to the type when no label is set — so a Claude Code file
207
+ // with `name: code-reviewer` still badges as "code-reviewer".
208
+ displayName: str(fm.display_name),
209
+ color: str(fm.color),
210
+ description: str(fm.description) ?? name,
211
+ builtinToolNames,
212
+ extSelectors,
213
+ disallowedTools: csvListOptional(fm.disallowed_tools),
214
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
215
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
216
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
217
+ model: str(fm.model),
218
+ thinking: str(fm.thinking) as ThinkingLevel | undefined,
219
+ maxTurns: nonNegativeInt(fm.max_turns),
220
+ persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
221
+ outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
222
+ sessionDir: str(fm.session_dir),
223
+ allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
224
+ systemPrompt: body.trim(),
225
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
226
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
227
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
228
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
229
+ memory: parseMemory(fm.memory),
230
+ isolation: parseIsolation(fm.isolation),
231
+ enabled: fm.enabled !== false, // default true; explicitly false disables
232
+ source,
233
+ sourcePath: path,
234
+ });
235
+ }
236
+
237
+ /**
238
+ * True when `path` is a regular file within the package-resource size ceiling.
239
+ *
240
+ * Only applied to package-provided files: they arrive from a third party and are
241
+ * re-read on every `Agent` call, so a 500 MB `.md` — or a fifo that never ends —
242
+ * must not be reachable from a spawn. A stat failure counts as "not within",
243
+ * because the alternative is reading something we could not describe.
244
+ */
245
+ function withinSizeLimit(path: string): boolean {
246
+ try {
247
+ const stat = statSync(path);
248
+ return stat.isFile() && stat.size <= MAX_PACKAGE_RESOURCE_BYTES;
249
+ } catch {
250
+ return false;
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Read and parse one agent file, or warn and return undefined for the caller to
256
+ * skip. One bad file must not take the whole extension down with it — an
257
+ * unparseable `.md` used to abort activation, so pi exited before the TUI.
258
+ *
259
+ * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
260
+ * column 14") is unactionable when agents come from three directories at once,
261
+ * and the only other symptom is `Unknown agent type`, which reads like a typo.
262
+ *
263
+ * Under `strict` the same failure rethrows, still naming the path, so callers
264
+ * that opted into failing closed stop rather than run a substituted agent.
265
+ */
266
+ /**
267
+ * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
268
+ *
269
+ * Editors across the Windows/CJK world write UTF-8 with a BOM by default, and
270
+ * pi's parser did not look past one before 0.84.3: the fence never matched, so
271
+ * the frontmatter came back empty and the *whole file* — YAML and all — became
272
+ * the body. An agent authored that way silently lost every field. `tools: none`
273
+ * going missing is the sharp edge: the agent registers with the default
274
+ * toolset rather than none, which is a wider grant than its author wrote.
275
+ *
276
+ * Stripped here rather than detected per pi version, because this is the only
277
+ * place agent files are read and the BOM is a file-encoding artifact, not
278
+ * content — normalising it at the boundary keeps one behaviour across the whole
279
+ * supported peer range instead of forking on what happens to be installed.
280
+ */
281
+ export function parseAgentFrontmatter<T extends Record<string, unknown>>(content: string): { frontmatter: T; body: string } {
282
+ return parseFrontmatter<T>(content.startsWith("\uFEFF") ? content.slice(1) : content);
283
+ }
284
+
285
+ function readAgentFile(path: string, strict: boolean): { frontmatter: Record<string, unknown>; body: string } | undefined {
286
+ try {
287
+ return parseAgentFrontmatter<Record<string, unknown>>(readFileSync(path, "utf-8"));
288
+ } catch (err) {
289
+ const reason = err instanceof Error ? err.message : String(err);
290
+ if (strict) throw new Error(`${path}: ${reason}`);
291
+ warnIfNew(`Skipping agent file ${path}: ${reason}`);
292
+ return undefined;
293
+ }
294
+ }
295
+
296
+ /**
297
+ * A skipped file that was overriding an already-loaded agent leaves the name
298
+ * pointing at a *different* file — its own prompt, model and tools. Nothing
299
+ * downstream can flag that: unlike an unknown type, the `Agent` call succeeds.
300
+ */
301
+ function warnSkippedOverride(name: string, agents: Map<string, AgentConfig>): void {
302
+ const surviving = agents.get(name);
303
+ // Nothing shadowed, or what it shadowed is disabled: dispatch refuses the type
304
+ // either way (see resolveEnabledTypeIn), so there is no substitution to report.
305
+ if (!surviving?.sourcePath || surviving.enabled === false) return;
306
+ warnIfNew(`Agent "${name}" now loads from ${surviving.sourcePath} instead`);
307
+ }
308
+
309
+ let warnedLastLoad = new Set<string>();
310
+ let warnedThisLoad = new Set<string>();
311
+
312
+ /**
313
+ * Agents reload on activation and again on every `Agent` call, so an unchanged
314
+ * problem would re-warn all session — over a painted TUI, since pi does not
315
+ * redirect console output. Compare against the previous load rather than every
316
+ * load ever, so a file that is fixed and then broken again still reports.
317
+ */
318
+ function warnIfNew(message: string): void {
319
+ warnedThisLoad.add(message);
320
+ if (warnedLastLoad.has(message)) return;
321
+ console.warn(`[pi-subagents] ${message}`);
322
+ }
323
+
324
+ // ---- Field parsers ----
325
+ // All follow the same convention: omitted → default, "none"/empty → nothing, value → exact.
326
+
327
+ /** Extract a string or undefined. */
328
+ function str(val: unknown): string | undefined {
329
+ return typeof val === "string" ? val : undefined;
330
+ }
331
+
332
+ /** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
333
+ function nonNegativeInt(val: unknown): number | undefined {
334
+ return typeof val === "number" && val >= 0 ? val : undefined;
335
+ }
336
+
337
+ /**
338
+ * Parse a raw CSV field value into items, or undefined if absent/empty/"none".
339
+ */
340
+ function parseCsvField(val: unknown): string[] | undefined {
341
+ if (val === undefined || val === null) return undefined;
342
+ const s = String(val).trim();
343
+ if (!s || s === "none") return undefined;
344
+ const items = s.split(",").map(t => t.trim()).filter(Boolean);
345
+ return items.length > 0 ? items : undefined;
346
+ }
347
+
348
+ /**
349
+ * Parse the nested-delegation allowlist. Single field, default-off:
350
+ * omitted/empty/"none"/`false` → undefined (no nested tools); "all"/"*"/`true`
351
+ * → "all" (any enabled agent); csv → only the listed types.
352
+ *
353
+ * Booleans are accepted because `extensions:`/`skills:` take them and users
354
+ * generalize: without this, YAML's `true` stringifies into an agent type
355
+ * literally named "true", so the tools appear and every spawn is refused.
356
+ */
357
+ function parseAllowedSubagents(val: unknown): "all" | string[] | undefined {
358
+ if (typeof val === "boolean") return val ? "all" : undefined;
359
+ const items = parseCsvField(val);
360
+ if (!items) return undefined;
361
+ return items.some(i => i === "*" || i.toLowerCase() === "all") ? "all" : items;
362
+ }
363
+
364
+ /**
365
+ * Parse a comma-separated list field with defaults.
366
+ * omitted → defaults; "none"/empty → []; csv → listed items.
367
+ */
368
+ function csvList(val: unknown, defaults: string[]): string[] {
369
+ if (val === undefined || val === null) return defaults;
370
+ return parseCsvField(val) ?? [];
371
+ }
372
+
373
+ /**
374
+ * Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
375
+ * `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
376
+ * built-ins; plain entries are built-in names; `ext:` entries are extension-tool
377
+ * selectors parsed later by the runner. omitted → all built-ins, no selectors.
378
+ * `tools:` present with only `ext:` entries → zero built-ins (use `*`).
379
+ */
380
+ function parseToolsField(val: unknown): { builtinToolNames: string[]; extSelectors: string[] | undefined } {
381
+ const entries = csvList(val, BUILTIN_TOOL_NAMES);
382
+ const isWildcard = (e: string) => e === "*" || e.toLowerCase() === "all";
383
+ const hasWildcard = entries.some(isWildcard);
384
+ const plain = entries.filter(e => !isWildcard(e) && !e.startsWith("ext:"));
385
+ const extEntries = entries.filter(e => e.startsWith("ext:"));
386
+ return {
387
+ builtinToolNames: hasWildcard ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain,
388
+ extSelectors: extEntries.length > 0 ? extEntries : undefined,
389
+ };
390
+ }
391
+
392
+ /**
393
+ * Parse an optional comma-separated list field.
394
+ * omitted → undefined; "none"/empty → undefined; csv → listed items.
395
+ */
396
+ function csvListOptional(val: unknown): string[] | undefined {
397
+ return parseCsvField(val);
398
+ }
399
+
400
+ /**
401
+ * Parse a memory scope field.
402
+ * omitted → undefined; "user"/"project"/"local" → MemoryScope.
403
+ */
404
+ function parseMemory(val: unknown): MemoryScope | undefined {
405
+ if (val === "user" || val === "project" || val === "local") return val;
406
+ return undefined;
407
+ }
408
+
409
+ /**
410
+ * Parse the `isolation` frontmatter field.
411
+ *
412
+ * `off` is kept as a value rather than folded into `undefined` because the two
413
+ * do not mean the same thing here: agent config outranks tool-call params, so
414
+ * `off` vetoes a caller's `worktree` while an absent field lets it through.
415
+ *
416
+ * pi's frontmatter parser is not YAML 1.1 — bare `off` and `no` arrive as
417
+ * strings and only `false` becomes a boolean — so all three spellings are
418
+ * accepted rather than leaving an author's intent silently dropped. Anything
419
+ * else stays `undefined`, as before.
420
+ */
421
+ function parseIsolation(val: unknown): IsolationMode | undefined {
422
+ if (val === "worktree") return "worktree";
423
+ if (val === "off" || val === "none" || val === "no" || val === false) return "off";
424
+ return undefined;
425
+ }
426
+
427
+ /**
428
+ * Parse an inherit field (extensions, skills).
429
+ * omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
430
+ */
431
+ function inheritField(val: unknown): true | string[] | false {
432
+ if (val === undefined || val === null || val === true) return true;
433
+ if (val === false || val === "none") return false;
434
+ const items = csvList(val, []);
435
+ return items.length > 0 ? items : false;
436
+ }