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

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