@diousk/pi-subagents-fast 0.20.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 (183) hide show
  1. package/CHANGELOG.md +808 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1034 -0
  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 +125 -0
  11. package/dist/agent-file-toggle.js +260 -0
  12. package/dist/agent-manager.d.ts +472 -0
  13. package/dist/agent-manager.js +1338 -0
  14. package/dist/agent-runner.d.ts +312 -0
  15. package/dist/agent-runner.js +1034 -0
  16. package/dist/agent-types.d.ts +119 -0
  17. package/dist/agent-types.js +286 -0
  18. package/dist/child-context.d.ts +2 -0
  19. package/dist/child-context.js +12 -0
  20. package/dist/context.d.ts +12 -0
  21. package/dist/context.js +56 -0
  22. package/dist/cross-extension-rpc.d.ts +66 -0
  23. package/dist/cross-extension-rpc.js +138 -0
  24. package/dist/custom-agents.d.ts +54 -0
  25. package/dist/custom-agents.js +316 -0
  26. package/dist/default-agents.d.ts +7 -0
  27. package/dist/default-agents.js +122 -0
  28. package/dist/enabled-models.d.ts +49 -0
  29. package/dist/enabled-models.js +145 -0
  30. package/dist/env.d.ts +6 -0
  31. package/dist/env.js +28 -0
  32. package/dist/group-join.d.ts +32 -0
  33. package/dist/group-join.js +116 -0
  34. package/dist/index.d.ts +50 -0
  35. package/dist/index.js +3682 -0
  36. package/dist/invocation-config.d.ts +107 -0
  37. package/dist/invocation-config.js +83 -0
  38. package/dist/memory.d.ts +53 -0
  39. package/dist/memory.js +165 -0
  40. package/dist/mention-clone.d.ts +87 -0
  41. package/dist/mention-clone.js +153 -0
  42. package/dist/mention.d.ts +81 -0
  43. package/dist/mention.js +131 -0
  44. package/dist/model-resolver.d.ts +36 -0
  45. package/dist/model-resolver.js +95 -0
  46. package/dist/model-scope.d.ts +49 -0
  47. package/dist/model-scope.js +48 -0
  48. package/dist/nested-tools.d.ts +55 -0
  49. package/dist/nested-tools.js +299 -0
  50. package/dist/output-file.d.ts +43 -0
  51. package/dist/output-file.js +142 -0
  52. package/dist/prompts.d.ts +55 -0
  53. package/dist/prompts.js +91 -0
  54. package/dist/schedule-store.d.ts +38 -0
  55. package/dist/schedule-store.js +155 -0
  56. package/dist/schedule.d.ts +109 -0
  57. package/dist/schedule.js +359 -0
  58. package/dist/settings.d.ts +360 -0
  59. package/dist/settings.js +251 -0
  60. package/dist/skill-loader.d.ts +24 -0
  61. package/dist/skill-loader.js +93 -0
  62. package/dist/status-note.d.ts +61 -0
  63. package/dist/status-note.js +85 -0
  64. package/dist/structured-output.d.ts +61 -0
  65. package/dist/structured-output.js +112 -0
  66. package/dist/types.d.ts +371 -0
  67. package/dist/types.js +5 -0
  68. package/dist/ui/agent-mention.d.ts +82 -0
  69. package/dist/ui/agent-mention.js +187 -0
  70. package/dist/ui/agent-widget.d.ts +219 -0
  71. package/dist/ui/agent-widget.js +592 -0
  72. package/dist/ui/conversation-viewer.d.ts +120 -0
  73. package/dist/ui/conversation-viewer.js +578 -0
  74. package/dist/ui/fleet-list.d.ts +195 -0
  75. package/dist/ui/fleet-list.js +471 -0
  76. package/dist/ui/schedule-menu.d.ts +16 -0
  77. package/dist/ui/schedule-menu.js +94 -0
  78. package/dist/ui/select-item.d.ts +27 -0
  79. package/dist/ui/select-item.js +34 -0
  80. package/dist/ui/viewer-keys.d.ts +20 -0
  81. package/dist/ui/viewer-keys.js +17 -0
  82. package/dist/ui/workflow-card.d.ts +175 -0
  83. package/dist/ui/workflow-card.js +332 -0
  84. package/dist/ui/workflow-dialog.d.ts +305 -0
  85. package/dist/ui/workflow-dialog.js +843 -0
  86. package/dist/ui/workflow-menu.d.ts +60 -0
  87. package/dist/ui/workflow-menu.js +147 -0
  88. package/dist/usage.d.ts +135 -0
  89. package/dist/usage.js +120 -0
  90. package/dist/workflow/collisions.d.ts +95 -0
  91. package/dist/workflow/collisions.js +88 -0
  92. package/dist/workflow/entry.d.ts +32 -0
  93. package/dist/workflow/entry.js +29 -0
  94. package/dist/workflow/host.d.ts +62 -0
  95. package/dist/workflow/host.js +362 -0
  96. package/dist/workflow/journal.d.ts +97 -0
  97. package/dist/workflow/journal.js +120 -0
  98. package/dist/workflow/json-schema.d.ts +51 -0
  99. package/dist/workflow/json-schema.js +111 -0
  100. package/dist/workflow/meta.d.ts +67 -0
  101. package/dist/workflow/meta.js +317 -0
  102. package/dist/workflow/progress.d.ts +224 -0
  103. package/dist/workflow/progress.js +361 -0
  104. package/dist/workflow/runtime.d.ts +334 -0
  105. package/dist/workflow/runtime.js +830 -0
  106. package/dist/workflow/saved.d.ts +90 -0
  107. package/dist/workflow/saved.js +203 -0
  108. package/dist/workflow/task.d.ts +136 -0
  109. package/dist/workflow/task.js +207 -0
  110. package/dist/workflow/tool-description.d.ts +38 -0
  111. package/dist/workflow/tool-description.js +199 -0
  112. package/dist/workflow/worker-source.d.ts +47 -0
  113. package/dist/workflow/worker-source.js +778 -0
  114. package/dist/worktree.d.ts +52 -0
  115. package/dist/worktree.js +164 -0
  116. package/dist/xml.d.ts +10 -0
  117. package/dist/xml.js +12 -0
  118. package/docs/rpc.md +183 -0
  119. package/docs/workflows.md +437 -0
  120. package/examples/agent-tool-description.md +42 -0
  121. package/examples/workflows/compose.js +51 -0
  122. package/examples/workflows/fan-out-audit.js +47 -0
  123. package/examples/workflows/gated-fix.js +60 -0
  124. package/examples/workflows/lib/count-child.js +27 -0
  125. package/examples/workflows/review-panel.js +63 -0
  126. package/examples/workflows/structured-findings.js +78 -0
  127. package/package.json +68 -0
  128. package/src/abortable.ts +43 -0
  129. package/src/agent-color.ts +161 -0
  130. package/src/agent-file-toggle.ts +270 -0
  131. package/src/agent-manager.ts +1581 -0
  132. package/src/agent-runner.ts +1286 -0
  133. package/src/agent-types.ts +346 -0
  134. package/src/child-context.ts +15 -0
  135. package/src/context.ts +58 -0
  136. package/src/cross-extension-rpc.ts +198 -0
  137. package/src/custom-agents.ts +333 -0
  138. package/src/default-agents.ts +126 -0
  139. package/src/enabled-models.ts +180 -0
  140. package/src/env.ts +33 -0
  141. package/src/group-join.ts +141 -0
  142. package/src/index.ts +3991 -0
  143. package/src/invocation-config.ts +155 -0
  144. package/src/memory.ts +179 -0
  145. package/src/mention-clone.ts +196 -0
  146. package/src/mention.ts +141 -0
  147. package/src/model-resolver.ts +118 -0
  148. package/src/model-scope.ts +70 -0
  149. package/src/nested-tools.ts +422 -0
  150. package/src/output-file.ts +155 -0
  151. package/src/prompts.ts +142 -0
  152. package/src/schedule-store.ts +153 -0
  153. package/src/schedule.ts +386 -0
  154. package/src/settings.ts +587 -0
  155. package/src/skill-loader.ts +102 -0
  156. package/src/status-note.ts +90 -0
  157. package/src/structured-output.ts +130 -0
  158. package/src/types.ts +384 -0
  159. package/src/ui/agent-mention.ts +216 -0
  160. package/src/ui/agent-widget.ts +664 -0
  161. package/src/ui/conversation-viewer.ts +589 -0
  162. package/src/ui/fleet-list.ts +543 -0
  163. package/src/ui/schedule-menu.ts +105 -0
  164. package/src/ui/select-item.ts +45 -0
  165. package/src/ui/viewer-keys.ts +39 -0
  166. package/src/ui/workflow-card.ts +470 -0
  167. package/src/ui/workflow-dialog.ts +1115 -0
  168. package/src/ui/workflow-menu.ts +193 -0
  169. package/src/usage.ts +167 -0
  170. package/src/workflow/collisions.ts +123 -0
  171. package/src/workflow/entry.ts +47 -0
  172. package/src/workflow/host.ts +403 -0
  173. package/src/workflow/journal.ts +164 -0
  174. package/src/workflow/json-schema.ts +128 -0
  175. package/src/workflow/meta.ts +325 -0
  176. package/src/workflow/progress.ts +550 -0
  177. package/src/workflow/runtime.ts +1219 -0
  178. package/src/workflow/saved.ts +217 -0
  179. package/src/workflow/task.ts +302 -0
  180. package/src/workflow/tool-description.ts +200 -0
  181. package/src/workflow/worker-source.ts +781 -0
  182. package/src/worktree.ts +205 -0
  183. package/src/xml.ts +13 -0
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Cross-extension RPC handlers for the subagents extension.
3
+ *
4
+ * Exposes ping, spawn, stop, and consume 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
+ import { isTopLevelAgent } from "./agent-manager.js";
16
+ import { resolveModel } from "./model-resolver.js";
17
+ import { checkModelScope } from "./model-scope.js";
18
+ /** RPC protocol version — bumped when the envelope or method contracts change. */
19
+ export const PROTOCOL_VERSION = 2;
20
+ /**
21
+ * Wire a single RPC handler: listen on `channel`, run `fn(params)`,
22
+ * emit the reply envelope on `channel:reply:${requestId}`.
23
+ */
24
+ function handleRpc(events, channel, fn) {
25
+ return events.on(channel, async (raw) => {
26
+ const params = raw;
27
+ try {
28
+ const data = await fn(params);
29
+ const reply = { success: true };
30
+ if (data !== undefined)
31
+ reply.data = data;
32
+ events.emit(`${channel}:reply:${params.requestId}`, reply);
33
+ }
34
+ catch (err) {
35
+ events.emit(`${channel}:reply:${params.requestId}`, {
36
+ success: false, error: err?.message ?? String(err),
37
+ });
38
+ }
39
+ });
40
+ }
41
+ /**
42
+ * Register ping, spawn, stop, and consume RPC handlers on the event bus.
43
+ * Returns unsub functions for cleanup.
44
+ */
45
+ export function registerRpcHandlers(deps) {
46
+ const { events, pi, getCtx, manager } = deps;
47
+ const unsubPing = handleRpc(events, "subagents:rpc:ping", () => {
48
+ return { version: PROTOCOL_VERSION };
49
+ });
50
+ const unsubSpawn = handleRpc(events, "subagents:rpc:spawn", async ({ type, prompt, options }) => {
51
+ const ctx = getCtx();
52
+ if (!ctx)
53
+ throw new Error("No active session");
54
+ // Cross-extension RPC callers (e.g. pi-tasks TaskExecute) naturally
55
+ // forward serializable values, so options.model can be a string like
56
+ // "openai-codex/gpt-5.5". Resolve it to a real Model instance here
57
+ // — same pattern the scheduler path already uses — so the spawned
58
+ // agent's auth lookup doesn't crash with "No API key found for
59
+ // undefined".
60
+ let normalizedOptions = options ?? {};
61
+ // `!= null` on purpose: a JSON-forwarding caller can serialize an unset
62
+ // field as null, and the runner reads `options.model ?? default`, so null
63
+ // means "inherit" — not an override to resolve or scope-check.
64
+ const override = normalizedOptions.model;
65
+ if (override != null) {
66
+ const { modelRegistry, cwd } = ctx;
67
+ // Names the override the same way in both messages below; an object
68
+ // override would otherwise interpolate as "[object Object]".
69
+ const label = typeof override === "string" ? override : `${override.provider}/${override.id}`;
70
+ if (!modelRegistry) {
71
+ throw new Error(`Model override "${label}" provided but ctx.modelRegistry is unavailable`);
72
+ }
73
+ let model = override;
74
+ if (typeof override === "string") {
75
+ const resolved = resolveModel(override, modelRegistry);
76
+ if (typeof resolved === "string") {
77
+ // resolveModel returns a human-readable error string when the
78
+ // input doesn't match any available model. Surface it instead of
79
+ // silently falling back so the caller sees the auth/typo issue.
80
+ throw new Error(resolved);
81
+ }
82
+ model = resolved;
83
+ normalizedOptions = { ...normalizedOptions, model: resolved };
84
+ }
85
+ // A model on the RPC payload is an orchestrator-level choice, exactly
86
+ // like Agent({ model }) — so it gets the Agent tool's hard error, never
87
+ // the frontmatter warn (#240). The check reads the RESOLVED model:
88
+ // resolveModel is fuzzy, so a bare "sonnet" can land on a provider the
89
+ // caller never named. Frontmatter-pinned and parent-inherited models are
90
+ // resolved later, in agent-runner, and keep warn-and-proceed.
91
+ const verdict = checkModelScope({
92
+ model,
93
+ cwd: cwd ?? process.cwd(),
94
+ modelRegistry,
95
+ callerSupplied: true,
96
+ agentLabel: type,
97
+ modelInput: label,
98
+ });
99
+ if (verdict.kind === "error")
100
+ throw new Error(verdict.message);
101
+ }
102
+ const id = manager.spawn(pi, ctx, type, prompt, normalizedOptions);
103
+ // With isolation: "worktree" the agent starts asynchronously — wait for
104
+ // it, so a strict-isolation failure is still an error envelope rather
105
+ // than an id for an agent that never ran.
106
+ await manager.awaitStartup(id);
107
+ return { id };
108
+ });
109
+ const unsubStop = handleRpc(events, "subagents:rpc:stop", ({ agentId }) => {
110
+ const record = manager.getRecord(agentId);
111
+ if (!record)
112
+ throw new Error("Agent not found");
113
+ // Only the session's own agents are this RPC's to stop. A nested child or
114
+ // a workflow's agent is owned by something that is *waiting on it*, and
115
+ // aborting it out from under that owner turns another extension's stop
116
+ // into a failed step here. Defence in depth rather than a live hole: no
117
+ // RPC hands out agent ids, so a caller has no ordinary way to name one it
118
+ // does not own — but the guard is cheap and the id may leak some other
119
+ // way. Same refuse-what-we-should-not-touch stance as `consume` below.
120
+ if (!isTopLevelAgent(record))
121
+ throw new Error("Agent is owned by another agent or workflow");
122
+ // Not "not found" — the lookup above already proved it exists. `abort`
123
+ // returns false only for a record that is neither running nor queued,
124
+ // which is an agent that has already finished.
125
+ if (!manager.abort(agentId))
126
+ throw new Error("Agent is not running");
127
+ });
128
+ // A caller that has already shown the model an agent's result — pi-tasks'
129
+ // TaskOutput is the one in practice — says so here, so the completion
130
+ // notification for that same result is not delivered on top of it and does
131
+ // not cost the parent a turn. Deliberately outside the ping version
132
+ // handshake: an extension built against protocol v2 simply never calls it.
133
+ const unsubConsume = handleRpc(events, "subagents:rpc:consume", ({ agentId }) => {
134
+ if (!manager.consumeResult(agentId))
135
+ throw new Error("Agent not found or still running");
136
+ });
137
+ return { unsubPing, unsubSpawn, unsubStop, unsubConsume };
138
+ }
@@ -0,0 +1,54 @@
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.
3
+ */
4
+ import type { AgentConfig } from "./types.js";
5
+ /**
6
+ * Scan for custom agent .md files from multiple locations.
7
+ * Discovery hierarchy (higher priority wins):
8
+ * 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
9
+ * 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
10
+ * 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
11
+ *
12
+ * Project-level agents override global ones with the same name. On a name clash
13
+ * between the two project locations, .pi/agents wins — .pi stays the project
14
+ * authority; .agents/agents is an additional read location.
15
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
16
+ *
17
+ * An agent's type comes from its frontmatter `name:`, falling back to the
18
+ * filename — Claude Code's rule, where "the filename doesn't have to match".
19
+ * Because the type is now declared rather than derived from a unique path, two
20
+ * files can claim the same one; the later load wins, as it always has for a
21
+ * filename clash, and `warnSkippedOverride` reports the substitution.
22
+ */
23
+ export declare function loadCustomAgents(cwd: string, strict?: boolean): Map<string, AgentConfig>;
24
+ /**
25
+ * Read and parse one agent file, or warn and return undefined for the caller to
26
+ * skip. One bad file must not take the whole extension down with it — an
27
+ * unparseable `.md` used to abort activation, so pi exited before the TUI.
28
+ *
29
+ * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
30
+ * column 14") is unactionable when agents come from three directories at once,
31
+ * and the only other symptom is `Unknown agent type`, which reads like a typo.
32
+ *
33
+ * Under `strict` the same failure rethrows, still naming the path, so callers
34
+ * that opted into failing closed stop rather than run a substituted agent.
35
+ */
36
+ /**
37
+ * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
38
+ *
39
+ * Editors across the Windows/CJK world write UTF-8 with a BOM by default, and
40
+ * pi's parser did not look past one before 0.84.3: the fence never matched, so
41
+ * the frontmatter came back empty and the *whole file* — YAML and all — became
42
+ * the body. An agent authored that way silently lost every field. `tools: none`
43
+ * going missing is the sharp edge: the agent registers with the default
44
+ * toolset rather than none, which is a wider grant than its author wrote.
45
+ *
46
+ * Stripped here rather than detected per pi version, because this is the only
47
+ * place agent files are read and the BOM is a file-encoding artifact, not
48
+ * content — normalising it at the boundary keeps one behaviour across the whole
49
+ * supported peer range instead of forking on what happens to be installed.
50
+ */
51
+ export declare function parseAgentFrontmatter<T extends Record<string, unknown>>(content: string): {
52
+ frontmatter: T;
53
+ body: string;
54
+ };
@@ -0,0 +1,316 @@
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.
3
+ */
4
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
5
+ import { basename, join } from "node:path";
6
+ import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
7
+ import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
8
+ /**
9
+ * The one thing a declared `name:` may not contain, matching Claude Code
10
+ * exactly: it reserves `:` for plugin-scoped identifiers (`my-plugin:reviewer`)
11
+ * and refuses to load a file whose name uses one.
12
+ *
13
+ * Nothing else is rejected. Claude Code's docs describe names as "lowercase
14
+ * letters and hyphens", but that is guidance — the only stated load failure is
15
+ * the colon, so `name: Code Reviewer` must work here too. (The stricter
16
+ * letters/digits/underscore/hyphen regex in Claude Code applies to the Agent
17
+ * tool's spawn-time `name` parameter, which is a different field.) Mixed case
18
+ * has to be allowed regardless: the built-in types `Explore` and `Plan` use it,
19
+ * and a file must be able to override one.
20
+ */
21
+ const RESERVED_IN_TYPE = ":";
22
+ /**
23
+ * Scan for custom agent .md files from multiple locations.
24
+ * Discovery hierarchy (higher priority wins):
25
+ * 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
26
+ * 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
27
+ * 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
28
+ *
29
+ * Project-level agents override global ones with the same name. On a name clash
30
+ * between the two project locations, .pi/agents wins — .pi stays the project
31
+ * authority; .agents/agents is an additional read location.
32
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
33
+ *
34
+ * An agent's type comes from its frontmatter `name:`, falling back to the
35
+ * filename — Claude Code's rule, where "the filename doesn't have to match".
36
+ * Because the type is now declared rather than derived from a unique path, two
37
+ * files can claim the same one; the later load wins, as it always has for a
38
+ * filename clash, and `warnSkippedOverride` reports the substitution.
39
+ */
40
+ export function loadCustomAgents(cwd, strict = false) {
41
+ const globalDir = join(getAgentDir(), "agents");
42
+ const workspaceProjectDir = join(cwd, ".agents", "agents");
43
+ const projectDir = join(cwd, ".pi", "agents");
44
+ const agents = new Map();
45
+ loadFromDir(globalDir, agents, "global", strict); // lowest priority
46
+ loadFromDir(workspaceProjectDir, agents, "project", strict); // shared workspace
47
+ loadFromDir(projectDir, agents, "project", strict); // highest priority (overwrites)
48
+ warnedLastLoad = warnedThisLoad;
49
+ warnedThisLoad = new Set();
50
+ return agents;
51
+ }
52
+ /** Load agent configs from a directory into the map. */
53
+ function loadFromDir(dir, agents, source, strict) {
54
+ if (!existsSync(dir))
55
+ return;
56
+ let files;
57
+ try {
58
+ files = readdirSync(dir).filter(f => f.endsWith(".md"));
59
+ }
60
+ catch {
61
+ return;
62
+ }
63
+ for (const file of files) {
64
+ const filenameType = basename(file, ".md");
65
+ const path = join(dir, file);
66
+ const parsed = readAgentFile(path, strict);
67
+ if (!parsed) {
68
+ warnSkippedOverride(filenameType, agents);
69
+ continue;
70
+ }
71
+ const { frontmatter: fm, body } = parsed;
72
+ // Claude Code's rule: `name:` IS the agent type, and the filename need not
73
+ // match. Absent, the filename stands in — Claude Code requires the field,
74
+ // but most files here predate it and must keep loading.
75
+ const declared = str(fm.name)?.trim();
76
+ if (declared?.includes(RESERVED_IN_TYPE)) {
77
+ // Refusing beats silently substituting: the file would otherwise load
78
+ // under its filename, so `Agent({subagent_type})` would succeed against
79
+ // an agent whose declared identity nothing honoured.
80
+ warnIfNew(`Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
81
+ + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.");
82
+ // No `warnSkippedOverride`: this file would have registered under its
83
+ // *declared* name, which nothing else can hold (a colon keeps it out of
84
+ // the registry), so it shadowed nothing. Passing the filename instead
85
+ // would report a substitution of an unrelated agent that never happened.
86
+ continue;
87
+ }
88
+ // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
89
+ // register the agent under the empty type — unspawnable, and it takes the
90
+ // filename-derived one down with it.
91
+ const name = declared || filenameType;
92
+ const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
93
+ agents.set(name, {
94
+ name,
95
+ // Only `display_name` now: `name` is the type, and `getConfig` already
96
+ // falls back to the type when no label is set — so a Claude Code file
97
+ // with `name: code-reviewer` still badges as "code-reviewer".
98
+ displayName: str(fm.display_name),
99
+ color: str(fm.color),
100
+ description: str(fm.description) ?? name,
101
+ builtinToolNames,
102
+ extSelectors,
103
+ disallowedTools: csvListOptional(fm.disallowed_tools),
104
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
105
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
106
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
107
+ model: str(fm.model),
108
+ thinking: str(fm.thinking),
109
+ serviceTier: parseServiceTier(fm.service_tier),
110
+ maxTurns: nonNegativeInt(fm.max_turns),
111
+ persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
112
+ outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
113
+ sessionDir: str(fm.session_dir),
114
+ allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
115
+ systemPrompt: body.trim(),
116
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
117
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
118
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
119
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
120
+ memory: parseMemory(fm.memory),
121
+ isolation: parseIsolation(fm.isolation),
122
+ enabled: fm.enabled !== false, // default true; explicitly false disables
123
+ source,
124
+ sourcePath: path,
125
+ });
126
+ }
127
+ }
128
+ /**
129
+ * Read and parse one agent file, or warn and return undefined for the caller to
130
+ * skip. One bad file must not take the whole extension down with it — an
131
+ * unparseable `.md` used to abort activation, so pi exited before the TUI.
132
+ *
133
+ * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
134
+ * column 14") is unactionable when agents come from three directories at once,
135
+ * and the only other symptom is `Unknown agent type`, which reads like a typo.
136
+ *
137
+ * Under `strict` the same failure rethrows, still naming the path, so callers
138
+ * that opted into failing closed stop rather than run a substituted agent.
139
+ */
140
+ /**
141
+ * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
142
+ *
143
+ * Editors across the Windows/CJK world write UTF-8 with a BOM by default, and
144
+ * pi's parser did not look past one before 0.84.3: the fence never matched, so
145
+ * the frontmatter came back empty and the *whole file* — YAML and all — became
146
+ * the body. An agent authored that way silently lost every field. `tools: none`
147
+ * going missing is the sharp edge: the agent registers with the default
148
+ * toolset rather than none, which is a wider grant than its author wrote.
149
+ *
150
+ * Stripped here rather than detected per pi version, because this is the only
151
+ * place agent files are read and the BOM is a file-encoding artifact, not
152
+ * content — normalising it at the boundary keeps one behaviour across the whole
153
+ * supported peer range instead of forking on what happens to be installed.
154
+ */
155
+ export function parseAgentFrontmatter(content) {
156
+ return parseFrontmatter(content.startsWith("\uFEFF") ? content.slice(1) : content);
157
+ }
158
+ function readAgentFile(path, strict) {
159
+ try {
160
+ return parseAgentFrontmatter(readFileSync(path, "utf-8"));
161
+ }
162
+ catch (err) {
163
+ const reason = err instanceof Error ? err.message : String(err);
164
+ if (strict)
165
+ throw new Error(`${path}: ${reason}`);
166
+ warnIfNew(`Skipping agent file ${path}: ${reason}`);
167
+ return undefined;
168
+ }
169
+ }
170
+ /**
171
+ * A skipped file that was overriding an already-loaded agent leaves the name
172
+ * pointing at a *different* file — its own prompt, model and tools. Nothing
173
+ * downstream can flag that: unlike an unknown type, the `Agent` call succeeds.
174
+ */
175
+ function warnSkippedOverride(name, agents) {
176
+ const surviving = agents.get(name);
177
+ // Nothing shadowed, or what it shadowed is disabled: dispatch refuses the type
178
+ // either way (see resolveEnabledTypeIn), so there is no substitution to report.
179
+ if (!surviving?.sourcePath || surviving.enabled === false)
180
+ return;
181
+ warnIfNew(`Agent "${name}" now loads from ${surviving.sourcePath} instead`);
182
+ }
183
+ let warnedLastLoad = new Set();
184
+ let warnedThisLoad = new Set();
185
+ /**
186
+ * Agents reload on activation and again on every `Agent` call, so an unchanged
187
+ * problem would re-warn all session — over a painted TUI, since pi does not
188
+ * redirect console output. Compare against the previous load rather than every
189
+ * load ever, so a file that is fixed and then broken again still reports.
190
+ */
191
+ function warnIfNew(message) {
192
+ warnedThisLoad.add(message);
193
+ if (warnedLastLoad.has(message))
194
+ return;
195
+ console.warn(`[pi-subagents] ${message}`);
196
+ }
197
+ // ---- Field parsers ----
198
+ // All follow the same convention: omitted → default, "none"/empty → nothing, value → exact.
199
+ /** Extract a string or undefined. */
200
+ function str(val) {
201
+ return typeof val === "string" ? val : undefined;
202
+ }
203
+ /** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
204
+ function nonNegativeInt(val) {
205
+ return typeof val === "number" && val >= 0 ? val : undefined;
206
+ }
207
+ /**
208
+ * Parse a raw CSV field value into items, or undefined if absent/empty/"none".
209
+ */
210
+ function parseCsvField(val) {
211
+ if (val === undefined || val === null)
212
+ return undefined;
213
+ const s = String(val).trim();
214
+ if (!s || s === "none")
215
+ return undefined;
216
+ const items = s.split(",").map(t => t.trim()).filter(Boolean);
217
+ return items.length > 0 ? items : undefined;
218
+ }
219
+ /**
220
+ * Parse the nested-delegation allowlist. Single field, default-off:
221
+ * omitted/empty/"none"/`false` → undefined (no nested tools); "all"/"*"/`true`
222
+ * → "all" (any enabled agent); csv → only the listed types.
223
+ *
224
+ * Booleans are accepted because `extensions:`/`skills:` take them and users
225
+ * generalize: without this, YAML's `true` stringifies into an agent type
226
+ * literally named "true", so the tools appear and every spawn is refused.
227
+ */
228
+ function parseAllowedSubagents(val) {
229
+ if (typeof val === "boolean")
230
+ return val ? "all" : undefined;
231
+ const items = parseCsvField(val);
232
+ if (!items)
233
+ return undefined;
234
+ return items.some(i => i === "*" || i.toLowerCase() === "all") ? "all" : items;
235
+ }
236
+ /**
237
+ * Parse a comma-separated list field with defaults.
238
+ * omitted → defaults; "none"/empty → []; csv → listed items.
239
+ */
240
+ function csvList(val, defaults) {
241
+ if (val === undefined || val === null)
242
+ return defaults;
243
+ return parseCsvField(val) ?? [];
244
+ }
245
+ /**
246
+ * Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
247
+ * `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
248
+ * built-ins; plain entries are built-in names; `ext:` entries are extension-tool
249
+ * selectors parsed later by the runner. omitted → all built-ins, no selectors.
250
+ * `tools:` present with only `ext:` entries → zero built-ins (use `*`).
251
+ */
252
+ function parseToolsField(val) {
253
+ const entries = csvList(val, BUILTIN_TOOL_NAMES);
254
+ const isWildcard = (e) => e === "*" || e.toLowerCase() === "all";
255
+ const hasWildcard = entries.some(isWildcard);
256
+ const plain = entries.filter(e => !isWildcard(e) && !e.startsWith("ext:"));
257
+ const extEntries = entries.filter(e => e.startsWith("ext:"));
258
+ return {
259
+ builtinToolNames: hasWildcard ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain,
260
+ extSelectors: extEntries.length > 0 ? extEntries : undefined,
261
+ };
262
+ }
263
+ /**
264
+ * Parse an optional comma-separated list field.
265
+ * omitted → undefined; "none"/empty → undefined; csv → listed items.
266
+ */
267
+ function csvListOptional(val) {
268
+ return parseCsvField(val);
269
+ }
270
+ /**
271
+ * Parse a memory scope field.
272
+ * omitted → undefined; "user"/"project"/"local" → MemoryScope.
273
+ */
274
+ function parseMemory(val) {
275
+ if (val === "user" || val === "project" || val === "local")
276
+ return val;
277
+ return undefined;
278
+ }
279
+ /** Parse the OpenAI Responses/Codex `service_tier` frontmatter field. */
280
+ function parseServiceTier(val) {
281
+ if (val === "auto" || val === "default" || val === "flex" || val === "priority" || val === "scale") {
282
+ return val;
283
+ }
284
+ return undefined;
285
+ }
286
+ /**
287
+ * Parse the `isolation` frontmatter field.
288
+ *
289
+ * `off` is kept as a value rather than folded into `undefined` because the two
290
+ * do not mean the same thing here: agent config outranks tool-call params, so
291
+ * `off` vetoes a caller's `worktree` while an absent field lets it through.
292
+ *
293
+ * pi's frontmatter parser is not YAML 1.1 — bare `off` and `no` arrive as
294
+ * strings and only `false` becomes a boolean — so all three spellings are
295
+ * accepted rather than leaving an author's intent silently dropped. Anything
296
+ * else stays `undefined`, as before.
297
+ */
298
+ function parseIsolation(val) {
299
+ if (val === "worktree")
300
+ return "worktree";
301
+ if (val === "off" || val === "none" || val === "no" || val === false)
302
+ return "off";
303
+ return undefined;
304
+ }
305
+ /**
306
+ * Parse an inherit field (extensions, skills).
307
+ * omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
308
+ */
309
+ function inheritField(val) {
310
+ if (val === undefined || val === null || val === true)
311
+ return true;
312
+ if (val === false || val === "none")
313
+ return false;
314
+ const items = csvList(val, []);
315
+ return items.length > 0 ? items : false;
316
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * default-agents.ts — Embedded default agent configurations.
3
+ *
4
+ * These are always available but can be overridden by user .md files with the same name.
5
+ */
6
+ import type { AgentConfig } from "./types.js";
7
+ export declare const DEFAULT_AGENTS: Map<string, AgentConfig>;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * default-agents.ts — Embedded default agent configurations.
3
+ *
4
+ * These are always available but can be overridden by user .md files with the same name.
5
+ */
6
+ const READ_ONLY_TOOLS = ["read", "bash", "grep", "find", "ls"];
7
+ export const DEFAULT_AGENTS = new Map([
8
+ [
9
+ "general-purpose",
10
+ {
11
+ name: "general-purpose",
12
+ displayName: "Agent",
13
+ description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
14
+ // builtinToolNames omitted — means "all available tools" (resolved at lookup time)
15
+ // inheritContext / runInBackground / isolated omitted — strategy fields, callers decide per-call.
16
+ // Setting them to false would lock callsite intent (see resolveAgentInvocationConfig in invocation-config.ts).
17
+ extensions: true,
18
+ skills: true,
19
+ systemPrompt: "",
20
+ promptMode: "append",
21
+ isDefault: true,
22
+ },
23
+ ],
24
+ [
25
+ "Explore",
26
+ {
27
+ name: "Explore",
28
+ displayName: "Explore",
29
+ description: "Fast read-only search agent for locating code. Use it to find files by pattern (eg. \"src/components/**/*.tsx\"), grep for symbols or keywords (eg. \"API endpoints\"), or answer \"where is X defined / which files reference Y.\" Do NOT use it for code review, design-doc auditing, cross-file consistency checks, or open-ended analysis — it reads excerpts rather than whole files and will miss content past its read window. When calling, specify search breadth: \"quick\" for a single targeted lookup, \"medium\" for moderate exploration, or \"very thorough\" to search across multiple locations and naming conventions.",
30
+ builtinToolNames: READ_ONLY_TOOLS,
31
+ extensions: true,
32
+ skills: true,
33
+ // Fast/cheap model for read-only search. Provider-preferred but resilient:
34
+ // resolveModel matches this fuzzily (date-stamp optional) and falls back to
35
+ // the same model under another provider if anthropic doesn't expose it.
36
+ model: "anthropic/claude-haiku-4-5",
37
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
38
+ You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
39
+ Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
40
+
41
+ You are STRICTLY PROHIBITED from:
42
+ - Creating new files
43
+ - Modifying existing files
44
+ - Deleting files
45
+ - Moving or copying files
46
+ - Creating temporary files anywhere, including /tmp
47
+ - Using redirect operators (>, >>, |) or heredocs to write to files
48
+ - Running ANY commands that change system state
49
+
50
+ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
51
+
52
+ # Tool Usage
53
+ - Use the find tool for file pattern matching (NOT the bash find command)
54
+ - Use the grep tool for content search (NOT bash grep/rg command)
55
+ - Use the read tool for reading files (NOT bash cat/head/tail)
56
+ - Use Bash ONLY for read-only operations
57
+ - Make independent tool calls in parallel for efficiency
58
+ - Adapt search approach based on thoroughness level specified
59
+
60
+ # Output
61
+ - Use absolute file paths in all references
62
+ - Report findings as regular messages
63
+ - Do not use emojis
64
+ - Be thorough and precise`,
65
+ promptMode: "replace",
66
+ isDefault: true,
67
+ },
68
+ ],
69
+ [
70
+ "Plan",
71
+ {
72
+ name: "Plan",
73
+ displayName: "Plan",
74
+ description: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
75
+ builtinToolNames: READ_ONLY_TOOLS,
76
+ extensions: true,
77
+ skills: true,
78
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
79
+ You are a software architect and planning specialist.
80
+ Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
81
+ You do NOT have access to file editing tools — attempting to edit files will fail.
82
+
83
+ You are STRICTLY PROHIBITED from:
84
+ - Creating new files
85
+ - Modifying existing files
86
+ - Deleting files
87
+ - Moving or copying files
88
+ - Creating temporary files anywhere, including /tmp
89
+ - Using redirect operators (>, >>, |) or heredocs to write to files
90
+ - Running ANY commands that change system state
91
+
92
+ # Planning Process
93
+ 1. Understand requirements
94
+ 2. Explore thoroughly (read files, find patterns, understand architecture)
95
+ 3. Design solution based on your assigned perspective
96
+ 4. Detail the plan with step-by-step implementation strategy
97
+
98
+ # Requirements
99
+ - Consider trade-offs and architectural decisions
100
+ - Identify dependencies and sequencing
101
+ - Anticipate potential challenges
102
+ - Follow existing patterns where appropriate
103
+
104
+ # Tool Usage
105
+ - Use the find tool for file pattern matching (NOT the bash find command)
106
+ - Use the grep tool for content search (NOT bash grep/rg command)
107
+ - Use the read tool for reading files (NOT bash cat/head/tail)
108
+ - Use Bash ONLY for read-only operations
109
+
110
+ # Output Format
111
+ - Use absolute file paths
112
+ - Do not use emojis
113
+ - End your response with:
114
+
115
+ ### Critical Files for Implementation
116
+ List 3-5 files most critical for implementing this plan:
117
+ - /absolute/path/to/file.ts - [Brief reason]`,
118
+ promptMode: "replace",
119
+ isDefault: true,
120
+ },
121
+ ],
122
+ ]);