@ymy88/pi-subagents 0.0.0-stage → 0.24.0

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 (196) hide show
  1. package/CHANGELOG.md +904 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1170 -2
  5. package/SECURITY.md +95 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/agent-color.d.ts +35 -0
  9. package/dist/agent-color.js +123 -0
  10. package/dist/agent-file-toggle.d.ts +133 -0
  11. package/dist/agent-file-toggle.js +287 -0
  12. package/dist/agent-manager.d.ts +552 -0
  13. package/dist/agent-manager.js +1466 -0
  14. package/dist/agent-record-entry.d.ts +96 -0
  15. package/dist/agent-record-entry.js +121 -0
  16. package/dist/agent-runner.d.ts +310 -0
  17. package/dist/agent-runner.js +1195 -0
  18. package/dist/agent-source-badge.d.ts +50 -0
  19. package/dist/agent-source-badge.js +74 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +2 -0
  23. package/dist/child-context.js +12 -0
  24. package/dist/completion-outbox.d.ts +63 -0
  25. package/dist/completion-outbox.js +104 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +72 -0
  29. package/dist/cross-extension-rpc.js +153 -0
  30. package/dist/custom-agents.d.ts +77 -0
  31. package/dist/custom-agents.js +396 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +121 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/group-join.d.ts +32 -0
  39. package/dist/group-join.js +116 -0
  40. package/dist/index.d.ts +50 -0
  41. package/dist/index.js +4111 -0
  42. package/dist/invocation-config.d.ts +108 -0
  43. package/dist/invocation-config.js +83 -0
  44. package/dist/memory.d.ts +53 -0
  45. package/dist/memory.js +165 -0
  46. package/dist/mention-clone.d.ts +79 -0
  47. package/dist/mention-clone.js +155 -0
  48. package/dist/mention.d.ts +81 -0
  49. package/dist/mention.js +131 -0
  50. package/dist/model-resolver.d.ts +36 -0
  51. package/dist/model-resolver.js +95 -0
  52. package/dist/model-scope.d.ts +49 -0
  53. package/dist/model-scope.js +48 -0
  54. package/dist/nested-tools.d.ts +57 -0
  55. package/dist/nested-tools.js +303 -0
  56. package/dist/output-file.d.ts +43 -0
  57. package/dist/output-file.js +153 -0
  58. package/dist/package-resources.d.ts +240 -0
  59. package/dist/package-resources.js +519 -0
  60. package/dist/prompts.d.ts +76 -0
  61. package/dist/prompts.js +121 -0
  62. package/dist/schedule-store.d.ts +38 -0
  63. package/dist/schedule-store.js +155 -0
  64. package/dist/schedule.d.ts +109 -0
  65. package/dist/schedule.js +359 -0
  66. package/dist/settings.d.ts +398 -0
  67. package/dist/settings.js +282 -0
  68. package/dist/skill-loader.d.ts +24 -0
  69. package/dist/skill-loader.js +93 -0
  70. package/dist/status-note.d.ts +61 -0
  71. package/dist/status-note.js +85 -0
  72. package/dist/structured-output.d.ts +61 -0
  73. package/dist/structured-output.js +112 -0
  74. package/dist/types.d.ts +391 -0
  75. package/dist/types.js +5 -0
  76. package/dist/ui/agent-mention.d.ts +82 -0
  77. package/dist/ui/agent-mention.js +187 -0
  78. package/dist/ui/agent-widget.d.ts +219 -0
  79. package/dist/ui/agent-widget.js +585 -0
  80. package/dist/ui/conversation-viewer.d.ts +177 -0
  81. package/dist/ui/conversation-viewer.js +905 -0
  82. package/dist/ui/fleet-list.d.ts +211 -0
  83. package/dist/ui/fleet-list.js +489 -0
  84. package/dist/ui/schedule-menu.d.ts +16 -0
  85. package/dist/ui/schedule-menu.js +94 -0
  86. package/dist/ui/select-item.d.ts +27 -0
  87. package/dist/ui/select-item.js +34 -0
  88. package/dist/ui/viewer-keys.d.ts +22 -0
  89. package/dist/ui/viewer-keys.js +18 -0
  90. package/dist/ui/workflow-card.d.ts +175 -0
  91. package/dist/ui/workflow-card.js +332 -0
  92. package/dist/ui/workflow-dialog.d.ts +305 -0
  93. package/dist/ui/workflow-dialog.js +843 -0
  94. package/dist/ui/workflow-menu.d.ts +60 -0
  95. package/dist/ui/workflow-menu.js +147 -0
  96. package/dist/usage.d.ts +135 -0
  97. package/dist/usage.js +120 -0
  98. package/dist/workflow/collisions.d.ts +95 -0
  99. package/dist/workflow/collisions.js +88 -0
  100. package/dist/workflow/entry.d.ts +32 -0
  101. package/dist/workflow/entry.js +29 -0
  102. package/dist/workflow/host.d.ts +62 -0
  103. package/dist/workflow/host.js +419 -0
  104. package/dist/workflow/journal.d.ts +97 -0
  105. package/dist/workflow/journal.js +120 -0
  106. package/dist/workflow/json-schema.d.ts +52 -0
  107. package/dist/workflow/json-schema.js +112 -0
  108. package/dist/workflow/meta.d.ts +67 -0
  109. package/dist/workflow/meta.js +317 -0
  110. package/dist/workflow/progress.d.ts +224 -0
  111. package/dist/workflow/progress.js +361 -0
  112. package/dist/workflow/runtime.d.ts +334 -0
  113. package/dist/workflow/runtime.js +830 -0
  114. package/dist/workflow/saved.d.ts +102 -0
  115. package/dist/workflow/saved.js +247 -0
  116. package/dist/workflow/task.d.ts +136 -0
  117. package/dist/workflow/task.js +207 -0
  118. package/dist/workflow/tool-description.d.ts +38 -0
  119. package/dist/workflow/tool-description.js +199 -0
  120. package/dist/workflow/worker-source.d.ts +47 -0
  121. package/dist/workflow/worker-source.js +778 -0
  122. package/dist/worktree.d.ts +52 -0
  123. package/dist/worktree.js +164 -0
  124. package/dist/xml.d.ts +10 -0
  125. package/dist/xml.js +12 -0
  126. package/docs/packages.md +211 -0
  127. package/docs/rpc.md +192 -0
  128. package/docs/workflows.md +447 -0
  129. package/examples/agent-tool-description.md +42 -0
  130. package/examples/workflows/compose.js +51 -0
  131. package/examples/workflows/fan-out-audit.js +47 -0
  132. package/examples/workflows/gated-fix.js +60 -0
  133. package/examples/workflows/lib/count-child.js +27 -0
  134. package/examples/workflows/review-panel.js +63 -0
  135. package/examples/workflows/structured-findings.js +78 -0
  136. package/package.json +74 -4
  137. package/src/abortable.ts +43 -0
  138. package/src/agent-color.ts +161 -0
  139. package/src/agent-file-toggle.ts +297 -0
  140. package/src/agent-manager.ts +1735 -0
  141. package/src/agent-record-entry.ts +153 -0
  142. package/src/agent-runner.ts +1468 -0
  143. package/src/agent-source-badge.ts +75 -0
  144. package/src/agent-types.ts +346 -0
  145. package/src/child-context.ts +15 -0
  146. package/src/completion-outbox.ts +116 -0
  147. package/src/context.ts +58 -0
  148. package/src/cross-extension-rpc.ts +221 -0
  149. package/src/custom-agents.ts +452 -0
  150. package/src/default-agents.ts +125 -0
  151. package/src/enabled-models.ts +180 -0
  152. package/src/env.ts +33 -0
  153. package/src/group-join.ts +141 -0
  154. package/src/index.ts +4433 -0
  155. package/src/invocation-config.ts +155 -0
  156. package/src/memory.ts +179 -0
  157. package/src/mention-clone.ts +195 -0
  158. package/src/mention.ts +141 -0
  159. package/src/model-resolver.ts +118 -0
  160. package/src/model-scope.ts +70 -0
  161. package/src/nested-tools.ts +426 -0
  162. package/src/output-file.ts +164 -0
  163. package/src/package-resources.ts +652 -0
  164. package/src/prompts.ts +171 -0
  165. package/src/schedule-store.ts +153 -0
  166. package/src/schedule.ts +386 -0
  167. package/src/settings.ts +650 -0
  168. package/src/skill-loader.ts +102 -0
  169. package/src/status-note.ts +90 -0
  170. package/src/structured-output.ts +130 -0
  171. package/src/types.ts +404 -0
  172. package/src/ui/agent-mention.ts +216 -0
  173. package/src/ui/agent-widget.ts +661 -0
  174. package/src/ui/conversation-viewer.ts +928 -0
  175. package/src/ui/fleet-list.ts +559 -0
  176. package/src/ui/schedule-menu.ts +105 -0
  177. package/src/ui/select-item.ts +45 -0
  178. package/src/ui/viewer-keys.ts +43 -0
  179. package/src/ui/workflow-card.ts +470 -0
  180. package/src/ui/workflow-dialog.ts +1115 -0
  181. package/src/ui/workflow-menu.ts +193 -0
  182. package/src/usage.ts +167 -0
  183. package/src/workflow/collisions.ts +123 -0
  184. package/src/workflow/entry.ts +47 -0
  185. package/src/workflow/host.ts +467 -0
  186. package/src/workflow/journal.ts +164 -0
  187. package/src/workflow/json-schema.ts +129 -0
  188. package/src/workflow/meta.ts +325 -0
  189. package/src/workflow/progress.ts +551 -0
  190. package/src/workflow/runtime.ts +1219 -0
  191. package/src/workflow/saved.ts +259 -0
  192. package/src/workflow/task.ts +302 -0
  193. package/src/workflow/tool-description.ts +200 -0
  194. package/src/workflow/worker-source.ts +781 -0
  195. package/src/worktree.ts +205 -0
  196. 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,452 @@
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
+ MAX_PACKAGE_RESOURCE_BYTES,
12
+ packageAgentDirs,
13
+ packageAgentFiles,
14
+ } from "./package-resources.js";
15
+ import type { AgentConfig, IsolationMode, MemoryScope, ThinkingLevel } from "./types.js";
16
+
17
+ /**
18
+ * The one thing a declared `name:` may not contain, matching Claude Code
19
+ * exactly: it reserves `:` for plugin-scoped identifiers (`my-plugin:reviewer`)
20
+ * and refuses to load a file whose name uses one.
21
+ *
22
+ * Nothing else is rejected. Claude Code's docs describe names as "lowercase
23
+ * letters and hyphens", but that is guidance — the only stated load failure is
24
+ * the colon, so `name: Code Reviewer` must work here too. (The stricter
25
+ * letters/digits/underscore/hyphen regex in Claude Code applies to the Agent
26
+ * tool's spawn-time `name` parameter, which is a different field.) Mixed case
27
+ * has to be allowed regardless: the built-in types `Explore` and `Plan` use it,
28
+ * and a file must be able to override one.
29
+ */
30
+ const RESERVED_IN_TYPE = ":";
31
+
32
+ /** Where an agent file was found. Widens `AgentConfig.source` for the loader. */
33
+ type AgentSource = "project" | "global" | "package";
34
+
35
+ /** Answers whether a `!` entry in some package manifest excludes this path. */
36
+ type Excluder = (path: string) => boolean;
37
+
38
+ /**
39
+ * Overrides for the package tier. The gate and project-trust state normally come
40
+ * from the session values in package-resources.ts, so these exist for tests and
41
+ * for a caller that has to pin a scan it already performed.
42
+ */
43
+ export interface LoadCustomAgentsOptions {
44
+ /** Explicit package directories, bypassing discovery. */
45
+ packageDirs?: string[];
46
+ /** Explicit package files, bypassing discovery. */
47
+ packageFiles?: string[];
48
+ /** Explicit `!` exclusion predicate, bypassing discovery. */
49
+ packageExcluded?: Excluder;
50
+ }
51
+
52
+ /**
53
+ * Scan for custom agent .md files from multiple locations.
54
+ * Discovery hierarchy (higher priority wins):
55
+ * 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
56
+ * 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
57
+ * 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
58
+ * 4. Package: paths declared by an installed pi package (read-only)
59
+ *
60
+ * Project-level agents override global ones with the same name. On a name clash
61
+ * between the two project locations, .pi/agents wins — .pi stays the project
62
+ * authority; .agents/agents is an additional read location.
63
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
64
+ *
65
+ * Package agents load *first*, so everything the user or project wrote outranks
66
+ * them. That is what makes them safe to adopt: a package can offer a `reviewer`,
67
+ * and a `.pi/agents/reviewer.md` silently takes it back. It mirrors pi's own
68
+ * resource precedence, where package-provided skills rank below every user and
69
+ * project one, and Claude Code's, where a plugin agent is the lowest tier.
70
+ *
71
+ * An agent's type comes from its frontmatter `name:`, falling back to the
72
+ * filename — Claude Code's rule, where "the filename doesn't have to match".
73
+ * Because the type is now declared rather than derived from a unique path, two
74
+ * files can claim the same one; the later load wins, as it always has for a
75
+ * filename clash, and `warnSkippedOverride` reports the substitution.
76
+ */
77
+ export function loadCustomAgents(
78
+ cwd: string,
79
+ strict = false,
80
+ opts: LoadCustomAgentsOptions = {},
81
+ ): Map<string, AgentConfig> {
82
+ const globalDir = join(getAgentDir(), "agents");
83
+ const workspaceProjectDir = join(cwd, ".agents", "agents");
84
+ const projectDir = join(cwd, ".pi", "agents");
85
+
86
+ const pkgDirs = opts.packageDirs ?? packageAgentDirs(cwd);
87
+ const pkgFiles = opts.packageFiles ?? packageAgentFiles(cwd);
88
+ // `!./agents/wip.md` alongside `./agents` excludes one file out of a directory
89
+ // that is only enumerated here, so the check has to run per file.
90
+ const excluded: Excluder = opts.packageExcluded ?? (path => isPackageResourceExcluded(path, cwd, "agents"));
91
+
92
+ const agents = new Map<string, AgentConfig>();
93
+ for (const dir of pkgDirs) loadFromDir(dir, agents, "package", strict, excluded); // lowest priority
94
+ for (const file of pkgFiles) loadOneFile(file, agents, "package", strict);
95
+ loadFromDir(globalDir, agents, "global", strict);
96
+ loadFromDir(workspaceProjectDir, agents, "project", strict); // shared workspace
97
+ loadFromDir(projectDir, agents, "project", strict); // highest priority (overwrites)
98
+
99
+ warnedLastLoad = warnedThisLoad;
100
+ warnedThisLoad = new Set();
101
+ return agents;
102
+ }
103
+
104
+ /** Load agent configs from a directory into the map, skipping any `excluded` path. */
105
+ function loadFromDir(
106
+ dir: string,
107
+ agents: Map<string, AgentConfig>,
108
+ source: AgentSource,
109
+ strict: boolean,
110
+ excluded?: Excluder,
111
+ ): void {
112
+ if (!existsSync(dir)) return;
113
+
114
+ let files: string[];
115
+ try {
116
+ files = readdirSync(dir).filter(f => f.endsWith(".md"));
117
+ } catch {
118
+ return;
119
+ }
120
+
121
+ for (const file of files) {
122
+ const path = join(dir, file);
123
+ if (excluded?.(path)) continue;
124
+ loadOneFile(path, agents, source, strict);
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Load one agent file into the map.
130
+ *
131
+ * Split out of `loadFromDir` because a package manifest may name an individual
132
+ * `.md` rather than a directory, and because the size guard below has to apply
133
+ * to both paths.
134
+ */
135
+ function loadOneFile(path: string, agents: Map<string, AgentConfig>, source: AgentSource, strict: boolean): void {
136
+ const filenameType = basename(path, ".md");
137
+
138
+ // Package files are third-party content read on every `Agent` call, so a
139
+ // pathological one is skipped rather than pulled into the session. Claude
140
+ // Code applies the same 1 MB ceiling to plugin-provided agents. Local files
141
+ // are the user's own and stay unbounded, as they always have been.
142
+ if (source === "package" && !withinSizeLimit(path)) {
143
+ warnIfNew(`Skipping package agent ${path}: not a regular file, or larger than ${MAX_PACKAGE_RESOURCE_BYTES} bytes.`);
144
+ return;
145
+ }
146
+
147
+ // `strict` is deliberately not passed for a package file. Failing activation
148
+ // over a broken agent file is right for a checked-in `.pi/agents/` — the point
149
+ // is that a repo's own file cannot silently fall through to a same-named one
150
+ // elsewhere. A file inside a third-party package is not the user's to fix, and
151
+ // one bad `.md` in any installed package would otherwise stop pi from
152
+ // starting at all. Warn and skip, as for a non-strict local file.
153
+ const parsed = readAgentFile(path, strict && source !== "package");
154
+ if (!parsed) {
155
+ warnSkippedOverride(filenameType, agents);
156
+ return;
157
+ }
158
+ const { frontmatter: fm, body } = parsed;
159
+
160
+ // Claude Code's rule: `name:` IS the agent type, and the filename need not
161
+ // match. Absent, the filename stands in — Claude Code requires the field,
162
+ // but most files here predate it and must keep loading.
163
+ const declared = str(fm.name)?.trim();
164
+ if (declared?.includes(RESERVED_IN_TYPE)) {
165
+ // Refusing beats silently substituting: the file would otherwise load
166
+ // under its filename, so `Agent({subagent_type})` would succeed against
167
+ // an agent whose declared identity nothing honoured.
168
+ warnIfNew(
169
+ `Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
170
+ + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.",
171
+ );
172
+ // No `warnSkippedOverride`: this file would have registered under its
173
+ // *declared* name, which nothing else can hold (a colon keeps it out of
174
+ // the registry), so it shadowed nothing. Passing the filename instead
175
+ // would report a substitution of an unrelated agent that never happened.
176
+ return;
177
+ }
178
+ // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
179
+ // register the agent under the empty type — unspawnable, and it takes the
180
+ // filename-derived one down with it.
181
+ const name = declared || filenameType;
182
+
183
+ const { builtinToolNames, extSelectors, mcpToolPatterns } = parseToolsField(fm.tools);
184
+
185
+ agents.set(name, {
186
+ name,
187
+ // Only `display_name` now: `name` is the type, and `getConfig` already
188
+ // falls back to the type when no label is set — so a Claude Code file
189
+ // with `name: code-reviewer` still badges as "code-reviewer".
190
+ displayName: str(fm.display_name),
191
+ color: str(fm.color),
192
+ description: str(fm.description) ?? name,
193
+ builtinToolNames,
194
+ extSelectors,
195
+ mcpToolPatterns,
196
+ // `disallowedTools` is Claude Code's spelling of the key. Each entry denies the tool
197
+ // with exactly that name, as in Claude Code, and the pi built-in it maps to, so an
198
+ // extension tool named `glob` stays denied rather than becoming `find`.
199
+ disallowedTools: csvListOptional(fm.disallowed_tools ?? fm.disallowedTools)?.flatMap(n => [
200
+ ...new Set([n, normalizeToolName(n)]),
201
+ ]),
202
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
203
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
204
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
205
+ model: str(fm.model),
206
+ thinking: str(fm.thinking) as ThinkingLevel | undefined,
207
+ maxTurns: nonNegativeInt(fm.max_turns),
208
+ persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
209
+ outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
210
+ sessionDir: str(fm.session_dir),
211
+ allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
212
+ systemPrompt: body.trim(),
213
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
214
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
215
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
216
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
217
+ memory: parseMemory(fm.memory),
218
+ isolation: parseIsolation(fm.isolation),
219
+ enabled: fm.enabled !== false, // default true; explicitly false disables
220
+ source,
221
+ sourcePath: path,
222
+ });
223
+ }
224
+
225
+ /**
226
+ * True when `path` is a regular file within the package-resource size ceiling.
227
+ *
228
+ * Only applied to package-provided files: they arrive from a third party and are
229
+ * re-read on every `Agent` call, so a 500 MB `.md` — or a fifo that never ends —
230
+ * must not be reachable from a spawn. A stat failure counts as "not within",
231
+ * because the alternative is reading something we could not describe.
232
+ */
233
+ function withinSizeLimit(path: string): boolean {
234
+ try {
235
+ const stat = statSync(path);
236
+ return stat.isFile() && stat.size <= MAX_PACKAGE_RESOURCE_BYTES;
237
+ } catch {
238
+ return false;
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Read and parse one agent file, or warn and return undefined for the caller to
244
+ * skip. One bad file must not take the whole extension down with it — an
245
+ * unparseable `.md` used to abort activation, so pi exited before the TUI.
246
+ *
247
+ * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
248
+ * column 14") is unactionable when agents come from three directories at once,
249
+ * and the only other symptom is `Unknown agent type`, which reads like a typo.
250
+ *
251
+ * Under `strict` the same failure rethrows, still naming the path, so callers
252
+ * that opted into failing closed stop rather than run a substituted agent.
253
+ */
254
+ /**
255
+ * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
256
+ *
257
+ * Editors across the Windows/CJK world write UTF-8 with a BOM by default, and
258
+ * pi's parser did not look past one before 0.84.3: the fence never matched, so
259
+ * the frontmatter came back empty and the *whole file* — YAML and all — became
260
+ * the body. An agent authored that way silently lost every field. `tools: none`
261
+ * going missing is the sharp edge: the agent registers with the default
262
+ * toolset rather than none, which is a wider grant than its author wrote.
263
+ *
264
+ * Stripped here rather than detected per pi version, because this is the only
265
+ * place agent files are read and the BOM is a file-encoding artifact, not
266
+ * content — normalising it at the boundary keeps one behaviour across the whole
267
+ * supported peer range instead of forking on what happens to be installed.
268
+ */
269
+ export function parseAgentFrontmatter<T extends Record<string, unknown>>(content: string): { frontmatter: T; body: string } {
270
+ return parseFrontmatter<T>(content.startsWith("\uFEFF") ? content.slice(1) : content);
271
+ }
272
+
273
+ function readAgentFile(path: string, strict: boolean): { frontmatter: Record<string, unknown>; body: string } | undefined {
274
+ try {
275
+ return parseAgentFrontmatter<Record<string, unknown>>(readFileSync(path, "utf-8"));
276
+ } catch (err) {
277
+ const reason = err instanceof Error ? err.message : String(err);
278
+ if (strict) throw new Error(`${path}: ${reason}`);
279
+ warnIfNew(`Skipping agent file ${path}: ${reason}`);
280
+ return undefined;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * A skipped file that was overriding an already-loaded agent leaves the name
286
+ * pointing at a *different* file — its own prompt, model and tools. Nothing
287
+ * downstream can flag that: unlike an unknown type, the `Agent` call succeeds.
288
+ */
289
+ function warnSkippedOverride(name: string, agents: Map<string, AgentConfig>): void {
290
+ const surviving = agents.get(name);
291
+ // Nothing shadowed, or what it shadowed is disabled: dispatch refuses the type
292
+ // either way (see resolveEnabledTypeIn), so there is no substitution to report.
293
+ if (!surviving?.sourcePath || surviving.enabled === false) return;
294
+ warnIfNew(`Agent "${name}" now loads from ${surviving.sourcePath} instead`);
295
+ }
296
+
297
+ let warnedLastLoad = new Set<string>();
298
+ let warnedThisLoad = new Set<string>();
299
+
300
+ /**
301
+ * Agents reload on activation and again on every `Agent` call, so an unchanged
302
+ * problem would re-warn all session — over a painted TUI, since pi does not
303
+ * redirect console output. Compare against the previous load rather than every
304
+ * load ever, so a file that is fixed and then broken again still reports.
305
+ */
306
+ function warnIfNew(message: string): void {
307
+ warnedThisLoad.add(message);
308
+ if (warnedLastLoad.has(message)) return;
309
+ console.warn(`[pi-subagents] ${message}`);
310
+ }
311
+
312
+ // ---- Field parsers ----
313
+ // All follow the same convention: omitted → default, "none"/empty → nothing, value → exact.
314
+
315
+ /** Extract a string or undefined. */
316
+ function str(val: unknown): string | undefined {
317
+ return typeof val === "string" ? val : undefined;
318
+ }
319
+
320
+ /** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
321
+ function nonNegativeInt(val: unknown): number | undefined {
322
+ return typeof val === "number" && val >= 0 ? val : undefined;
323
+ }
324
+
325
+ /**
326
+ * Parse a raw CSV field value into items, or undefined if absent/empty/"none".
327
+ */
328
+ function parseCsvField(val: unknown): string[] | undefined {
329
+ if (val === undefined || val === null) return undefined;
330
+ const s = String(val).trim();
331
+ if (!s || s === "none") return undefined;
332
+ const items = s.split(",").map(t => t.trim()).filter(Boolean);
333
+ return items.length > 0 ? items : undefined;
334
+ }
335
+
336
+ /**
337
+ * Parse the nested-delegation allowlist. Single field, default-off:
338
+ * omitted/empty/"none"/`false` → undefined (no nested tools); "all"/"*"/`true`
339
+ * → "all" (any enabled agent); csv → only the listed types.
340
+ *
341
+ * Booleans are accepted because `extensions:`/`skills:` take them and users
342
+ * generalize: without this, YAML's `true` stringifies into an agent type
343
+ * literally named "true", so the tools appear and every spawn is refused.
344
+ */
345
+ function parseAllowedSubagents(val: unknown): "all" | string[] | undefined {
346
+ if (typeof val === "boolean") return val ? "all" : undefined;
347
+ const items = parseCsvField(val);
348
+ if (!items) return undefined;
349
+ return items.some(i => i === "*" || i.toLowerCase() === "all") ? "all" : items;
350
+ }
351
+
352
+ /**
353
+ * Parse a comma-separated list field with defaults.
354
+ * omitted → defaults; "none"/empty → []; csv → listed items.
355
+ */
356
+ function csvList(val: unknown, defaults: string[]): string[] {
357
+ if (val === undefined || val === null) return defaults;
358
+ return parseCsvField(val) ?? [];
359
+ }
360
+
361
+ /** Claude Code tool names whose pi built-in is named differently. Keys are lowercase. */
362
+ const CLAUDE_CODE_TOOL_ALIASES: Record<string, string> = { glob: "find", multiedit: "edit" };
363
+
364
+ /**
365
+ * A tool name as pi spells it. Built-ins match case-insensitively, so Claude Code's
366
+ * `Read` and `LS` work, and a Claude Code name with a differently named pi built-in
367
+ * maps to it. Anything else comes back unchanged, so runAgent still warns about it.
368
+ */
369
+ function normalizeToolName(name: string): string {
370
+ const lower = name.toLowerCase();
371
+ return BUILTIN_TOOL_NAMES.find(b => b === lower) ?? CLAUDE_CODE_TOOL_ALIASES[lower] ?? name;
372
+ }
373
+
374
+ /**
375
+ * Partition the `tools:` CSV into the built-in tool allowlist, raw `ext:` selectors
376
+ * and bare `mcp__` entries. `*` (and the case-insensitive alias `all`, for
377
+ * `tools: all`) expands to all built-ins; plain entries are built-in names, in pi's
378
+ * or Claude Code's spelling; `ext:` entries are extension-tool selectors parsed
379
+ * later by the runner; `mcp__<server>__<tool>` entries (exact or `*` patterns)
380
+ * narrow MCP tools, as pi's `--tools` does. omitted → all built-ins, no selectors.
381
+ * `tools:` present with only `ext:` or `mcp__` entries → zero built-ins (use `*`).
382
+ */
383
+ function parseToolsField(val: unknown): {
384
+ builtinToolNames: string[];
385
+ extSelectors: string[] | undefined;
386
+ mcpToolPatterns: string[] | undefined;
387
+ } {
388
+ const entries = csvList(val, BUILTIN_TOOL_NAMES);
389
+ const isWildcard = (e: string) => e === "*" || e.toLowerCase() === "all";
390
+ const isMcp = (e: string) => e.startsWith("mcp__");
391
+ const hasWildcard = entries.some(isWildcard);
392
+ const plain = [
393
+ ...new Set(entries.filter(e => !isWildcard(e) && !e.startsWith("ext:") && !isMcp(e)).map(normalizeToolName)),
394
+ ];
395
+ const extEntries = entries.filter(e => e.startsWith("ext:"));
396
+ // A server-level `mcp__<server>` means every tool of that server, as in Claude Code.
397
+ const mcpEntries = entries.filter(isMcp).map(e => {
398
+ const server = e.slice("mcp__".length);
399
+ return server && !server.includes("__") ? `${e}__*` : e;
400
+ });
401
+ return {
402
+ builtinToolNames: hasWildcard ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain,
403
+ extSelectors: extEntries.length > 0 ? extEntries : undefined,
404
+ mcpToolPatterns: mcpEntries.length > 0 ? mcpEntries : undefined,
405
+ };
406
+ }
407
+
408
+ /**
409
+ * Parse an optional comma-separated list field.
410
+ * omitted → undefined; "none"/empty → undefined; csv → listed items.
411
+ */
412
+ function csvListOptional(val: unknown): string[] | undefined {
413
+ return parseCsvField(val);
414
+ }
415
+
416
+ /**
417
+ * Parse a memory scope field.
418
+ * omitted → undefined; "user"/"project"/"local" → MemoryScope.
419
+ */
420
+ function parseMemory(val: unknown): MemoryScope | undefined {
421
+ if (val === "user" || val === "project" || val === "local") return val;
422
+ return undefined;
423
+ }
424
+
425
+ /**
426
+ * Parse the `isolation` frontmatter field.
427
+ *
428
+ * `off` is kept as a value rather than folded into `undefined` because the two
429
+ * do not mean the same thing here: agent config outranks tool-call params, so
430
+ * `off` vetoes a caller's `worktree` while an absent field lets it through.
431
+ *
432
+ * pi's frontmatter parser is not YAML 1.1 — bare `off` and `no` arrive as
433
+ * strings and only `false` becomes a boolean — so all three spellings are
434
+ * accepted rather than leaving an author's intent silently dropped. Anything
435
+ * else stays `undefined`, as before.
436
+ */
437
+ function parseIsolation(val: unknown): IsolationMode | undefined {
438
+ if (val === "worktree") return "worktree";
439
+ if (val === "off" || val === "none" || val === "no" || val === false) return "off";
440
+ return undefined;
441
+ }
442
+
443
+ /**
444
+ * Parse an inherit field (extensions, skills).
445
+ * omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
446
+ */
447
+ function inheritField(val: unknown): true | string[] | false {
448
+ if (val === undefined || val === null || val === true) return true;
449
+ if (val === false || val === "none") return false;
450
+ const items = csvList(val, []);
451
+ return items.length > 0 ? items : false;
452
+ }