@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,583 @@
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 { readdir, readFile } from "node:fs/promises";
6
+ import { basename, join } from "node:path";
7
+ import { inspect } from "node:util";
8
+ import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
9
+ import { BUILTIN_TOOL_NAMES, cloneAgentDefinition } from "./agent-types.js";
10
+ /**
11
+ * The one thing a declared `name:` may not contain, matching Claude Code
12
+ * exactly: it reserves `:` for plugin-scoped identifiers (`my-plugin:reviewer`)
13
+ * and refuses to load a file whose name uses one.
14
+ *
15
+ * Nothing else is rejected. Claude Code's docs describe names as "lowercase
16
+ * letters and hyphens", but that is guidance — the only stated load failure is
17
+ * the colon, so `name: Code Reviewer` must work here too. (The stricter
18
+ * letters/digits/underscore/hyphen regex in Claude Code applies to the Agent
19
+ * tool's spawn-time `name` parameter, which is a different field.) Mixed case
20
+ * has to be allowed regardless: the built-in types `Explore` and `Plan` use it,
21
+ * and a file must be able to override one.
22
+ */
23
+ const RESERVED_IN_TYPE = ":";
24
+ const THINKING_FIELDS = ["thinking", "thinkingLevel", "thinking-level", "thinking_level", "effort"];
25
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
26
+ const FALLBACK_MODEL_FIELDS = ["fallback_model", "fallbackModel"];
27
+ // `advisors` is a tolerated spelling for the same per-agent advisor on/off pin;
28
+ // canonical `advisor` wins a conflict, same shape as the alias groups above.
29
+ const ADVISOR_FIELDS = ["advisor", "advisors"];
30
+ /**
31
+ * Scan for custom agent .md files from multiple locations.
32
+ * Discovery hierarchy (higher priority wins):
33
+ * 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
34
+ * 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
35
+ * 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
36
+ *
37
+ * Project-level agents override global ones with the same name. On a name clash
38
+ * between the two project locations, .pi/agents wins — .pi stays the project
39
+ * authority; .agents/agents is an additional read location.
40
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
41
+ *
42
+ * An agent's type comes from its frontmatter `name:`, falling back to the
43
+ * filename — Claude Code's rule, where "the filename doesn't have to match".
44
+ * Because the type is now declared rather than derived from a unique path, two
45
+ * files can claim the same one; the later load wins, as it always has for a
46
+ * filename clash, and `warnSkippedOverride` reports the substitution.
47
+ */
48
+ export function loadCustomAgents(cwd, strict = false) {
49
+ const { globalDir, workspaceProjectDir, projectDir } = agentDirs(cwd);
50
+ const warnings = beginLoadWarnings();
51
+ const agents = new Map();
52
+ loadFromDirSync(globalDir, agents, "global", strict, warnings); // lowest priority
53
+ loadFromDirSync(workspaceProjectDir, agents, "project", strict, warnings); // shared workspace
54
+ loadFromDirSync(projectDir, agents, "project", strict, warnings); // highest priority (overwrites)
55
+ commitLoadWarnings(warnings);
56
+ return agents;
57
+ }
58
+ /**
59
+ * Async twin of {@link loadCustomAgents} for ordinary awaitable admission.
60
+ *
61
+ * Discovery and content reads are fresh every call; only the raw YAML parse is
62
+ * reused, and only when the bytes just read are identical. That distinction is
63
+ * deliberate: caching a size/mtime stamp would let a same-size edit through,
64
+ * and caching a validated AgentConfig would make a lenient load's skipped or
65
+ * coerced field authorize a strict request. Cache entries are bounded by both
66
+ * entry count and retained bytes, so a pathological directory cannot pin
67
+ * arbitrary content for the process lifetime.
68
+ *
69
+ * Concurrent callers for the same three-directory scope and strictness share
70
+ * one refresh. Each gets its own Map so a caller mutating its result cannot
71
+ * rewrite another caller's registry; warnings are collected per load and
72
+ * committed atomically when the shared load finishes.
73
+ */
74
+ export async function loadCustomAgentsAsync(cwd, strict = false) {
75
+ const { globalDir, workspaceProjectDir, projectDir } = agentDirs(cwd);
76
+ const key = [globalDir, workspaceProjectDir, projectDir, strict ? "strict" : "lenient"].join("\0");
77
+ const inflight = inflightAsyncLoads.get(key);
78
+ if (inflight)
79
+ return cloneRegistry(await inflight);
80
+ const warnings = beginLoadWarnings();
81
+ let shared;
82
+ shared = loadAllDirsAsync({ globalDir, workspaceProjectDir, projectDir }, strict, warnings).finally(() => {
83
+ if (inflightAsyncLoads.get(key) === shared)
84
+ inflightAsyncLoads.delete(key);
85
+ });
86
+ inflightAsyncLoads.set(key, shared);
87
+ return cloneRegistry(await shared);
88
+ }
89
+ /** Coalescing shares I/O, never mutable definitions or tool-policy arrays. */
90
+ function cloneRegistry(agents) {
91
+ return new Map([...agents].map(([name, config]) => [name, cloneAgentDefinition(config)]));
92
+ }
93
+ function agentDirs(cwd) {
94
+ return {
95
+ globalDir: join(getAgentDir(), "agents"),
96
+ workspaceProjectDir: join(cwd, ".agents", "agents"),
97
+ projectDir: join(cwd, ".pi", "agents"),
98
+ };
99
+ }
100
+ async function loadAllDirsAsync(dirs, strict, warnings) {
101
+ const agents = new Map();
102
+ await loadFromDirAsync(dirs.globalDir, agents, "global", strict, warnings);
103
+ await loadFromDirAsync(dirs.workspaceProjectDir, agents, "project", strict, warnings);
104
+ await loadFromDirAsync(dirs.projectDir, agents, "project", strict, warnings);
105
+ commitLoadWarnings(warnings);
106
+ return agents;
107
+ }
108
+ /** Load agent configs from a directory into the map. */
109
+ function loadFromDirSync(dir, agents, source, strict, warnings) {
110
+ syncReads++;
111
+ if (!existsSync(dir))
112
+ return;
113
+ let files;
114
+ try {
115
+ syncReads++;
116
+ files = readdirSync(dir).filter(f => f.endsWith(".md"));
117
+ }
118
+ catch {
119
+ // Missing/unreadable directory: skip it, as discovery always has. Strict
120
+ // mode is about a READABLE file's contents, not an optional directory.
121
+ return;
122
+ }
123
+ for (const file of files) {
124
+ const filenameType = basename(file, ".md");
125
+ const path = join(dir, file);
126
+ const parsed = readAgentFileSync(path, strict, warnings);
127
+ if (!parsed) {
128
+ warnSkippedOverride(filenameType, agents, warnings);
129
+ continue;
130
+ }
131
+ addAgent(path, filenameType, parsed, agents, source, strict, warnings);
132
+ }
133
+ }
134
+ async function loadFromDirAsync(dir, agents, source, strict, warnings) {
135
+ let files;
136
+ try {
137
+ asyncReads++;
138
+ files = (await readdir(dir)).filter(f => f.endsWith(".md"));
139
+ }
140
+ catch {
141
+ // Same deliberate skip as the synchronous fallback: the three discovery
142
+ // directories are optional, and an absent one is not a load failure.
143
+ return;
144
+ }
145
+ for (const file of files) {
146
+ const filenameType = basename(file, ".md");
147
+ const path = join(dir, file);
148
+ const parsed = await readAgentFileAsync(path, strict, warnings);
149
+ if (!parsed) {
150
+ warnSkippedOverride(filenameType, agents, warnings);
151
+ continue;
152
+ }
153
+ addAgent(path, filenameType, parsed, agents, source, strict, warnings);
154
+ }
155
+ }
156
+ /**
157
+ * Turn one freshly parsed file into an AgentConfig, applying the current
158
+ * strictness and precedence policy. The parsed frontmatter is raw cache data;
159
+ * every validation, alias conflict and skip decision is rerun here so a strict
160
+ * request never inherits a lenient load's decision.
161
+ */
162
+ function addAgent(path, filenameType, parsed, agents, source, strict, warnings) {
163
+ const { frontmatter: fm, body } = parsed;
164
+ // Claude Code's rule: `name:` IS the agent type, and the filename need not
165
+ // match. Absent, the filename stands in — Claude Code requires the field,
166
+ // but most files here predate it and must keep loading.
167
+ const declared = str(fm.name)?.trim();
168
+ if (declared?.includes(RESERVED_IN_TYPE)) {
169
+ // Refusing beats silently substituting: the file would otherwise load
170
+ // under its filename, so `Agent({subagent_type})` would succeed against
171
+ // an agent whose declared identity nothing honoured.
172
+ warnIfNew(warnings, `Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
173
+ + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.");
174
+ // No `warnSkippedOverride`: this file would have registered under its
175
+ // *declared* name, which nothing else can hold (a colon keeps it out of
176
+ // the registry), so it shadowed nothing. Passing the filename instead
177
+ // would report a substitution of an unrelated agent that never happened.
178
+ return;
179
+ }
180
+ // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
181
+ // register the agent under the empty type — unspawnable, and it takes the
182
+ // filename-derived one down with it.
183
+ const name = declared || filenameType;
184
+ let thinking;
185
+ let fallbackModel;
186
+ let advisor;
187
+ try {
188
+ // AgentConfig uses pi-ai's streaming type (which omits "off"), while
189
+ // session settings accept it. Cast only AFTER validating the seven levels.
190
+ thinking = parseAliasedString(fm, path, THINKING_FIELDS, THINKING_LEVELS, warnings);
191
+ fallbackModel = parseAliasedString(fm, path, FALLBACK_MODEL_FIELDS, undefined, warnings);
192
+ advisor = parseAliasedBoolean(fm, path, ADVISOR_FIELDS, warnings);
193
+ }
194
+ catch (err) {
195
+ const reason = err instanceof Error ? err.message : String(err);
196
+ if (strict)
197
+ throw new Error(`${path}: ${reason}`);
198
+ warnIfNew(warnings, `Skipping agent file ${path}: ${reason}`);
199
+ warnSkippedOverride(name, agents, warnings);
200
+ return;
201
+ }
202
+ const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
203
+ agents.set(name, {
204
+ name,
205
+ // Only `display_name` now: `name` is the type, and `getConfig` already
206
+ // falls back to the type when no label is set — so a Claude Code file
207
+ // with `name: code-reviewer` still badges as "code-reviewer".
208
+ displayName: str(fm.display_name),
209
+ color: str(fm.color),
210
+ description: str(fm.description) ?? name,
211
+ builtinToolNames,
212
+ extSelectors,
213
+ disallowedTools: csvListOptional(fm.disallowed_tools),
214
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
215
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
216
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
217
+ model: str(fm.model),
218
+ fallbackModel,
219
+ thinking,
220
+ advisor,
221
+ maxTurns: nonNegativeInt(fm.max_turns),
222
+ persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
223
+ outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
224
+ sessionDir: str(fm.session_dir),
225
+ allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
226
+ systemPrompt: body.trim(),
227
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
228
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
229
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
230
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
231
+ memory: parseMemory(fm.memory),
232
+ isolation: parseIsolation(fm.isolation),
233
+ enabled: fm.enabled !== false, // default true; explicitly false disables
234
+ source,
235
+ sourcePath: path,
236
+ });
237
+ }
238
+ /**
239
+ * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
240
+ *
241
+ * Editors across the Windows/CJK world write UTF-8 with a BOM by default, and
242
+ * pi's parser did not look past one before 0.84.3: the fence never matched, so
243
+ * the frontmatter came back empty and the *whole file* — YAML and all — became
244
+ * the body. An agent authored that way silently lost every field. `tools: none`
245
+ * going missing is the sharp edge: the agent registers with the default
246
+ * toolset rather than none, which is a wider grant than its author wrote.
247
+ *
248
+ * Stripped here rather than detected per pi version, because this is the only
249
+ * place agent files are read and the BOM is a file-encoding artifact, not
250
+ * content — normalising it at the boundary keeps one behaviour across the whole
251
+ * supported peer range instead of forking on what happens to be installed.
252
+ */
253
+ export function parseAgentFrontmatter(content) {
254
+ return parseFrontmatter(content.startsWith("\uFEFF") ? content.slice(1) : content);
255
+ }
256
+ /**
257
+ * Bounds for the raw parse cache. `bytes` counts both the content used for
258
+ * exact equality and the parsed body retained beside it; it is a storage bound,
259
+ * not a limit on file size (a file larger than the cap simply is not cached).
260
+ */
261
+ export const AGENT_PARSE_CACHE_MAX_ENTRIES = 64;
262
+ export const AGENT_PARSE_CACHE_MAX_BYTES = 2 * 1024 * 1024;
263
+ const parseCache = new Map();
264
+ let parseCacheBytes = 0;
265
+ let parseCount = 0;
266
+ let parseCacheHits = 0;
267
+ let parseEvictions = 0;
268
+ let syncReads = 0;
269
+ let asyncReads = 0;
270
+ const inflightAsyncLoads = new Map();
271
+ /** Operation counts used by the definition-refresh tests. */
272
+ export function getAgentParseCacheStats() {
273
+ return {
274
+ entries: parseCache.size,
275
+ bytes: parseCacheBytes,
276
+ parses: parseCount,
277
+ hits: parseCacheHits,
278
+ evictions: parseEvictions,
279
+ syncReads,
280
+ asyncReads,
281
+ };
282
+ }
283
+ /** Drop retained parses and counters so tests start from a known cache. */
284
+ export function resetAgentParseCache() {
285
+ parseCache.clear();
286
+ parseCacheBytes = 0;
287
+ parseCount = 0;
288
+ parseCacheHits = 0;
289
+ parseEvictions = 0;
290
+ syncReads = 0;
291
+ asyncReads = 0;
292
+ }
293
+ function dropCachedParse(path) {
294
+ const existing = parseCache.get(path);
295
+ if (existing === undefined)
296
+ return;
297
+ parseCache.delete(path);
298
+ parseCacheBytes -= existing.bytes;
299
+ }
300
+ /**
301
+ * Reuse the parse for `content` only when those exact bytes were parsed
302
+ * before. A hit returns a fresh frontmatter object: all later validation reads
303
+ * it, and a shared mutable object would let one load's decisions leak into the
304
+ * next.
305
+ */
306
+ function parseCached(path, content) {
307
+ const cached = parseCache.get(path);
308
+ if (cached !== undefined && cached.content === content) {
309
+ parseCacheHits++;
310
+ // Refresh LRU position without changing retained bytes.
311
+ parseCache.delete(path);
312
+ parseCache.set(path, cached);
313
+ return { frontmatter: structuredClone(cached.frontmatter), body: cached.body };
314
+ }
315
+ if (cached !== undefined)
316
+ dropCachedParse(path);
317
+ parseCount++;
318
+ const parsed = parseAgentFrontmatter(content);
319
+ rememberParsed(path, content, parsed);
320
+ return parsed;
321
+ }
322
+ function rememberParsed(path, content, parsed) {
323
+ dropCachedParse(path);
324
+ const bytes = Buffer.byteLength(content, "utf8") + Buffer.byteLength(parsed.body, "utf8");
325
+ if (bytes > AGENT_PARSE_CACHE_MAX_BYTES)
326
+ return;
327
+ parseCache.set(path, {
328
+ content,
329
+ // The cache owns its own object; the parse returned to this load never
330
+ // aliases it, so no later load can observe a mutation made on the other.
331
+ frontmatter: structuredClone(parsed.frontmatter),
332
+ body: parsed.body,
333
+ bytes,
334
+ });
335
+ parseCacheBytes += bytes;
336
+ while (parseCache.size > AGENT_PARSE_CACHE_MAX_ENTRIES || parseCacheBytes > AGENT_PARSE_CACHE_MAX_BYTES) {
337
+ const oldest = parseCache.keys().next();
338
+ if (oldest.done)
339
+ break;
340
+ parseEvictions++;
341
+ dropCachedParse(oldest.value);
342
+ }
343
+ }
344
+ /** Shared warn/skip outcome for read and parse failures. */
345
+ function agentFileFailure(path, err, strict, warnings) {
346
+ const reason = err instanceof Error ? err.message : String(err);
347
+ if (strict)
348
+ throw new Error(`${path}: ${reason}`);
349
+ warnIfNew(warnings, `Skipping agent file ${path}: ${reason}`);
350
+ return undefined;
351
+ }
352
+ function readAgentFileSync(path, strict, warnings) {
353
+ let content;
354
+ try {
355
+ syncReads++;
356
+ content = readFileSync(path, "utf-8");
357
+ }
358
+ catch (err) {
359
+ return agentFileFailure(path, err, strict, warnings);
360
+ }
361
+ try {
362
+ return parseCached(path, content);
363
+ }
364
+ catch (err) {
365
+ return agentFileFailure(path, err, strict, warnings);
366
+ }
367
+ }
368
+ async function readAgentFileAsync(path, strict, warnings) {
369
+ let content;
370
+ try {
371
+ asyncReads++;
372
+ content = await readFile(path, "utf-8");
373
+ }
374
+ catch (err) {
375
+ return agentFileFailure(path, err, strict, warnings);
376
+ }
377
+ try {
378
+ return parseCached(path, content);
379
+ }
380
+ catch (err) {
381
+ return agentFileFailure(path, err, strict, warnings);
382
+ }
383
+ }
384
+ /**
385
+ * A skipped file that was overriding an already-loaded agent leaves the name
386
+ * pointing at a *different* file — its own prompt, model and tools. Nothing
387
+ * downstream can flag that: unlike an unknown type, the `Agent` call succeeds.
388
+ */
389
+ function warnSkippedOverride(name, agents, warnings) {
390
+ const surviving = agents.get(name);
391
+ // Nothing shadowed, or what it shadowed is disabled: dispatch refuses the type
392
+ // either way (see resolveEnabledTypeIn), so there is no substitution to report.
393
+ if (!surviving?.sourcePath || surviving.enabled === false)
394
+ return;
395
+ warnIfNew(warnings, `Agent "${name}" now loads from ${surviving.sourcePath} instead`);
396
+ }
397
+ let warnedLastLoad = new Set();
398
+ function beginLoadWarnings() {
399
+ return { previous: warnedLastLoad, current: new Set() };
400
+ }
401
+ function commitLoadWarnings(warnings) {
402
+ warnedLastLoad = warnings.current;
403
+ }
404
+ /**
405
+ * Agents reload on activation and again on every `Agent` call, so an unchanged
406
+ * problem would re-warn all session — over a painted TUI, since pi does not
407
+ * redirect console output. Compare against the previous load rather than every
408
+ * load ever, so a file that is fixed and then broken again still reports.
409
+ *
410
+ * The set is per load, not module-wide: an async load may interleave with
411
+ * another refresh or with a synchronous fallback between reads, and sharing
412
+ * one accumulator would let one load suppress another's diagnostics.
413
+ */
414
+ function warnIfNew(warnings, message) {
415
+ warnings.current.add(message);
416
+ if (warnings.previous.has(message))
417
+ return;
418
+ console.warn(`[pi-subagents] ${message}`);
419
+ }
420
+ // ---- Field parsers ----
421
+ /** Validate every explicit alias before resolving precedence; a bad value must not inherit. */
422
+ function parseAliasedString(fm, path, fields, allowedValues, warnings) {
423
+ const entries = fields.filter(field => Object.hasOwn(fm, field)).map(field => {
424
+ const value = fm[field];
425
+ if (typeof value !== "string" || !value.trim() || (allowedValues && !allowedValues.includes(value))) {
426
+ const hint = allowedValues
427
+ ? `Use one of: ${allowedValues.join(", ")}; omit all thinking fields to inherit.`
428
+ : `Use a nonempty string, or omit ${fields.join(" and ")}.`;
429
+ throw new Error(`Invalid ${field}: ${inspect(value, { depth: 1, maxStringLength: 120, maxArrayLength: 10 })}. ${hint}`);
430
+ }
431
+ return { field, value };
432
+ });
433
+ const selected = entries[0];
434
+ if (!selected)
435
+ return undefined;
436
+ if (entries.some(entry => entry.value !== selected.value)) {
437
+ warnIfNew(warnings, `Agent file ${path} has conflicting ${fields[0]} aliases: `
438
+ + `${entries.map(entry => `${entry.field}: ${entry.value}`).join(", ")}. `
439
+ + `Using ${selected.field}: ${selected.value}; precedence: ${fields.join(" > ")}.`);
440
+ }
441
+ return selected.value;
442
+ }
443
+ /**
444
+ * Boolean twin of parseAliasedString, for fields whose values are YAML
445
+ * booleans rather than one of a level list — `advisor` today. Validation is
446
+ * the same shape on purpose: every present alias is checked BEFORE precedence
447
+ * (an invalid `advisor` cannot hide behind a valid `advisors` or fall through
448
+ * to it), and a genuine boolean `true`/`false` is the only accepted value —
449
+ * pi's frontmatter parser leaves `on`/`off`/`yes` as strings, so accepting
450
+ * only real booleans turns those misspellings into a skip-the-file diagnostic
451
+ * instead of a silently inherited default.
452
+ */
453
+ function parseAliasedBoolean(fm, path, fields, warnings) {
454
+ const entries = fields.filter(field => Object.hasOwn(fm, field)).map(field => {
455
+ const value = fm[field];
456
+ if (typeof value !== "boolean") {
457
+ throw new Error(`Invalid ${field}: ${inspect(value, { depth: 1, maxStringLength: 120, maxArrayLength: 10 })}. `
458
+ + `Use a bare YAML boolean (${fields[0]}: true or ${fields[0]}: false); omit ${fields.join(" and ")} to inherit pi-advisor's own subagent default.`);
459
+ }
460
+ return { field, value };
461
+ });
462
+ const selected = entries[0];
463
+ if (!selected)
464
+ return undefined;
465
+ if (entries.some(entry => entry.value !== selected.value)) {
466
+ warnIfNew(warnings, `Agent file ${path} has conflicting ${fields[0]} aliases: `
467
+ + `${entries.map(entry => `${entry.field}: ${entry.value}`).join(", ")}. `
468
+ + `Using ${selected.field}: ${selected.value}; precedence: ${fields.join(" > ")}.`);
469
+ }
470
+ return selected.value;
471
+ }
472
+ // Remaining parsers: omitted → default, "none"/empty → nothing, value → exact.
473
+ /** Extract a string or undefined. */
474
+ function str(val) {
475
+ return typeof val === "string" ? val : undefined;
476
+ }
477
+ /** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
478
+ function nonNegativeInt(val) {
479
+ return typeof val === "number" && val >= 0 ? val : undefined;
480
+ }
481
+ /**
482
+ * Parse a raw CSV field value into items, or undefined if absent/empty/"none".
483
+ */
484
+ function parseCsvField(val) {
485
+ if (val === undefined || val === null)
486
+ return undefined;
487
+ const s = String(val).trim();
488
+ if (!s || s === "none")
489
+ return undefined;
490
+ const items = s.split(",").map(t => t.trim()).filter(Boolean);
491
+ return items.length > 0 ? items : undefined;
492
+ }
493
+ /**
494
+ * Parse the nested-delegation allowlist. Single field, default-off:
495
+ * omitted/empty/"none"/`false` → undefined (no nested tools); "all"/"*"/`true`
496
+ * → "all" (any enabled agent); csv → only the listed types.
497
+ *
498
+ * Booleans are accepted because `extensions:`/`skills:` take them and users
499
+ * generalize: without this, YAML's `true` stringifies into an agent type
500
+ * literally named "true", so the tools appear and every spawn is refused.
501
+ */
502
+ function parseAllowedSubagents(val) {
503
+ if (typeof val === "boolean")
504
+ return val ? "all" : undefined;
505
+ const items = parseCsvField(val);
506
+ if (!items)
507
+ return undefined;
508
+ return items.some(i => i === "*" || i.toLowerCase() === "all") ? "all" : items;
509
+ }
510
+ /**
511
+ * Parse a comma-separated list field with defaults.
512
+ * omitted → defaults; "none"/empty → []; csv → listed items.
513
+ */
514
+ function csvList(val, defaults) {
515
+ if (val === undefined || val === null)
516
+ return defaults;
517
+ return parseCsvField(val) ?? [];
518
+ }
519
+ /**
520
+ * Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
521
+ * `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
522
+ * built-ins; plain entries are built-in names; `ext:` entries are extension-tool
523
+ * selectors parsed later by the runner. omitted → all built-ins, no selectors.
524
+ * `tools:` present with only `ext:` entries → zero built-ins (use `*`).
525
+ */
526
+ function parseToolsField(val) {
527
+ const entries = csvList(val, BUILTIN_TOOL_NAMES);
528
+ const isWildcard = (e) => e === "*" || e.toLowerCase() === "all";
529
+ const hasWildcard = entries.some(isWildcard);
530
+ const plain = entries.filter(e => !isWildcard(e) && !e.startsWith("ext:"));
531
+ const extEntries = entries.filter(e => e.startsWith("ext:"));
532
+ return {
533
+ builtinToolNames: hasWildcard ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain,
534
+ extSelectors: extEntries.length > 0 ? extEntries : undefined,
535
+ };
536
+ }
537
+ /**
538
+ * Parse an optional comma-separated list field.
539
+ * omitted → undefined; "none"/empty → undefined; csv → listed items.
540
+ */
541
+ function csvListOptional(val) {
542
+ return parseCsvField(val);
543
+ }
544
+ /**
545
+ * Parse a memory scope field.
546
+ * omitted → undefined; "user"/"project"/"local" → MemoryScope.
547
+ */
548
+ function parseMemory(val) {
549
+ if (val === "user" || val === "project" || val === "local")
550
+ return val;
551
+ return undefined;
552
+ }
553
+ /**
554
+ * Parse the `isolation` frontmatter field.
555
+ *
556
+ * `off` is kept as a value rather than folded into `undefined` because the two
557
+ * do not mean the same thing here: agent config outranks tool-call params, so
558
+ * `off` vetoes a caller's `worktree` while an absent field lets it through.
559
+ *
560
+ * pi's frontmatter parser is not YAML 1.1 — bare `off` and `no` arrive as
561
+ * strings and only `false` becomes a boolean — so all three spellings are
562
+ * accepted rather than leaving an author's intent silently dropped. Anything
563
+ * else stays `undefined`, as before.
564
+ */
565
+ function parseIsolation(val) {
566
+ if (val === "worktree")
567
+ return "worktree";
568
+ if (val === "off" || val === "none" || val === "no" || val === false)
569
+ return "off";
570
+ return undefined;
571
+ }
572
+ /**
573
+ * Parse an inherit field (extensions, skills).
574
+ * omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
575
+ */
576
+ function inheritField(val) {
577
+ if (val === undefined || val === null || val === true)
578
+ return true;
579
+ if (val === false || val === "none")
580
+ return false;
581
+ const items = csvList(val, []);
582
+ return items.length > 0 ? items : false;
583
+ }
@@ -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.ts";
7
+ export declare const DEFAULT_AGENTS: Map<string, AgentConfig>;