@timmyjl12/pi-subagents 0.0.0-stage → 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 (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  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 +18 -0
  9. package/dist/active-agents-prompt.js +34 -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 +123 -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 +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -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 +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -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/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,386 @@
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 { inspect } from "node:util";
7
+ import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
+ import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
9
+ /**
10
+ * The one thing a declared `name:` may not contain, matching Claude Code
11
+ * exactly: it reserves `:` for plugin-scoped identifiers (`my-plugin:reviewer`)
12
+ * and refuses to load a file whose name uses one.
13
+ *
14
+ * Nothing else is rejected. Claude Code's docs describe names as "lowercase
15
+ * letters and hyphens", but that is guidance — the only stated load failure is
16
+ * the colon, so `name: Code Reviewer` must work here too. (The stricter
17
+ * letters/digits/underscore/hyphen regex in Claude Code applies to the Agent
18
+ * tool's spawn-time `name` parameter, which is a different field.) Mixed case
19
+ * has to be allowed regardless: the built-in types `Explore` and `Plan` use it,
20
+ * and a file must be able to override one.
21
+ */
22
+ const RESERVED_IN_TYPE = ":";
23
+ const THINKING_FIELDS = ["thinking", "thinkingLevel", "thinking-level", "thinking_level", "effort"];
24
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
25
+ const FALLBACK_MODEL_FIELDS = ["fallback_model", "fallbackModel"];
26
+ // `advisors` is a tolerated spelling for the same per-agent advisor on/off pin;
27
+ // canonical `advisor` wins a conflict, same shape as the alias groups above.
28
+ const ADVISOR_FIELDS = ["advisor", "advisors"];
29
+ /**
30
+ * Scan for custom agent .md files from multiple locations.
31
+ * Discovery hierarchy (higher priority wins):
32
+ * 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
33
+ * 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
34
+ * 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
35
+ *
36
+ * Project-level agents override global ones with the same name. On a name clash
37
+ * between the two project locations, .pi/agents wins — .pi stays the project
38
+ * authority; .agents/agents is an additional read location.
39
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
40
+ *
41
+ * An agent's type comes from its frontmatter `name:`, falling back to the
42
+ * filename — Claude Code's rule, where "the filename doesn't have to match".
43
+ * Because the type is now declared rather than derived from a unique path, two
44
+ * files can claim the same one; the later load wins, as it always has for a
45
+ * filename clash, and `warnSkippedOverride` reports the substitution.
46
+ */
47
+ export function loadCustomAgents(cwd, strict = false) {
48
+ const globalDir = join(getAgentDir(), "agents");
49
+ const workspaceProjectDir = join(cwd, ".agents", "agents");
50
+ const projectDir = join(cwd, ".pi", "agents");
51
+ const agents = new Map();
52
+ loadFromDir(globalDir, agents, "global", strict); // lowest priority
53
+ loadFromDir(workspaceProjectDir, agents, "project", strict); // shared workspace
54
+ loadFromDir(projectDir, agents, "project", strict); // highest priority (overwrites)
55
+ warnedLastLoad = warnedThisLoad;
56
+ warnedThisLoad = new Set();
57
+ return agents;
58
+ }
59
+ /** Load agent configs from a directory into the map. */
60
+ function loadFromDir(dir, agents, source, strict) {
61
+ if (!existsSync(dir))
62
+ return;
63
+ let files;
64
+ try {
65
+ files = readdirSync(dir).filter(f => f.endsWith(".md"));
66
+ }
67
+ catch {
68
+ return;
69
+ }
70
+ for (const file of files) {
71
+ const filenameType = basename(file, ".md");
72
+ const path = join(dir, file);
73
+ const parsed = readAgentFile(path, strict);
74
+ if (!parsed) {
75
+ warnSkippedOverride(filenameType, agents);
76
+ continue;
77
+ }
78
+ const { frontmatter: fm, body } = parsed;
79
+ // Claude Code's rule: `name:` IS the agent type, and the filename need not
80
+ // match. Absent, the filename stands in — Claude Code requires the field,
81
+ // but most files here predate it and must keep loading.
82
+ const declared = str(fm.name)?.trim();
83
+ if (declared?.includes(RESERVED_IN_TYPE)) {
84
+ // Refusing beats silently substituting: the file would otherwise load
85
+ // under its filename, so `Agent({subagent_type})` would succeed against
86
+ // an agent whose declared identity nothing honoured.
87
+ warnIfNew(`Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
88
+ + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.");
89
+ // No `warnSkippedOverride`: this file would have registered under its
90
+ // *declared* name, which nothing else can hold (a colon keeps it out of
91
+ // the registry), so it shadowed nothing. Passing the filename instead
92
+ // would report a substitution of an unrelated agent that never happened.
93
+ continue;
94
+ }
95
+ // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
96
+ // register the agent under the empty type — unspawnable, and it takes the
97
+ // filename-derived one down with it.
98
+ const name = declared || filenameType;
99
+ let thinking;
100
+ let fallbackModel;
101
+ let advisor;
102
+ try {
103
+ // AgentConfig uses pi-ai's streaming type (which omits "off"), while
104
+ // session settings accept it. Cast only AFTER validating the seven levels.
105
+ thinking = parseAliasedString(fm, path, THINKING_FIELDS, THINKING_LEVELS);
106
+ fallbackModel = parseAliasedString(fm, path, FALLBACK_MODEL_FIELDS);
107
+ advisor = parseAliasedBoolean(fm, path, ADVISOR_FIELDS);
108
+ }
109
+ catch (err) {
110
+ const reason = err instanceof Error ? err.message : String(err);
111
+ if (strict)
112
+ throw new Error(`${path}: ${reason}`);
113
+ warnIfNew(`Skipping agent file ${path}: ${reason}`);
114
+ warnSkippedOverride(name, agents);
115
+ continue;
116
+ }
117
+ const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
118
+ agents.set(name, {
119
+ name,
120
+ // Only `display_name` now: `name` is the type, and `getConfig` already
121
+ // falls back to the type when no label is set — so a Claude Code file
122
+ // with `name: code-reviewer` still badges as "code-reviewer".
123
+ displayName: str(fm.display_name),
124
+ color: str(fm.color),
125
+ description: str(fm.description) ?? name,
126
+ builtinToolNames,
127
+ extSelectors,
128
+ disallowedTools: csvListOptional(fm.disallowed_tools),
129
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
130
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
131
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
132
+ model: str(fm.model),
133
+ fallbackModel,
134
+ thinking,
135
+ advisor,
136
+ maxTurns: nonNegativeInt(fm.max_turns),
137
+ persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
138
+ outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
139
+ sessionDir: str(fm.session_dir),
140
+ allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
141
+ systemPrompt: body.trim(),
142
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
143
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
144
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
145
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
146
+ memory: parseMemory(fm.memory),
147
+ isolation: parseIsolation(fm.isolation),
148
+ enabled: fm.enabled !== false, // default true; explicitly false disables
149
+ source,
150
+ sourcePath: path,
151
+ });
152
+ }
153
+ }
154
+ /**
155
+ * Read and parse one agent file, or warn and return undefined for the caller to
156
+ * skip. One bad file must not take the whole extension down with it — an
157
+ * unparseable `.md` used to abort activation, so pi exited before the TUI.
158
+ *
159
+ * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
160
+ * column 14") is unactionable when agents come from three directories at once,
161
+ * and the only other symptom is `Unknown agent type`, which reads like a typo.
162
+ *
163
+ * Under `strict` the same failure rethrows, still naming the path, so callers
164
+ * that opted into failing closed stop rather than run a substituted agent.
165
+ */
166
+ /**
167
+ * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
168
+ *
169
+ * Editors across the Windows/CJK world write UTF-8 with a BOM by default, and
170
+ * pi's parser did not look past one before 0.84.3: the fence never matched, so
171
+ * the frontmatter came back empty and the *whole file* — YAML and all — became
172
+ * the body. An agent authored that way silently lost every field. `tools: none`
173
+ * going missing is the sharp edge: the agent registers with the default
174
+ * toolset rather than none, which is a wider grant than its author wrote.
175
+ *
176
+ * Stripped here rather than detected per pi version, because this is the only
177
+ * place agent files are read and the BOM is a file-encoding artifact, not
178
+ * content — normalising it at the boundary keeps one behaviour across the whole
179
+ * supported peer range instead of forking on what happens to be installed.
180
+ */
181
+ export function parseAgentFrontmatter(content) {
182
+ return parseFrontmatter(content.startsWith("\uFEFF") ? content.slice(1) : content);
183
+ }
184
+ function readAgentFile(path, strict) {
185
+ try {
186
+ return parseAgentFrontmatter(readFileSync(path, "utf-8"));
187
+ }
188
+ catch (err) {
189
+ const reason = err instanceof Error ? err.message : String(err);
190
+ if (strict)
191
+ throw new Error(`${path}: ${reason}`);
192
+ warnIfNew(`Skipping agent file ${path}: ${reason}`);
193
+ return undefined;
194
+ }
195
+ }
196
+ /**
197
+ * A skipped file that was overriding an already-loaded agent leaves the name
198
+ * pointing at a *different* file — its own prompt, model and tools. Nothing
199
+ * downstream can flag that: unlike an unknown type, the `Agent` call succeeds.
200
+ */
201
+ function warnSkippedOverride(name, agents) {
202
+ const surviving = agents.get(name);
203
+ // Nothing shadowed, or what it shadowed is disabled: dispatch refuses the type
204
+ // either way (see resolveEnabledTypeIn), so there is no substitution to report.
205
+ if (!surviving?.sourcePath || surviving.enabled === false)
206
+ return;
207
+ warnIfNew(`Agent "${name}" now loads from ${surviving.sourcePath} instead`);
208
+ }
209
+ let warnedLastLoad = new Set();
210
+ let warnedThisLoad = new Set();
211
+ /**
212
+ * Agents reload on activation and again on every `Agent` call, so an unchanged
213
+ * problem would re-warn all session — over a painted TUI, since pi does not
214
+ * redirect console output. Compare against the previous load rather than every
215
+ * load ever, so a file that is fixed and then broken again still reports.
216
+ */
217
+ function warnIfNew(message) {
218
+ warnedThisLoad.add(message);
219
+ if (warnedLastLoad.has(message))
220
+ return;
221
+ console.warn(`[pi-subagents] ${message}`);
222
+ }
223
+ // ---- Field parsers ----
224
+ /** Validate every explicit alias before resolving precedence; a bad value must not inherit. */
225
+ function parseAliasedString(fm, path, fields, allowedValues) {
226
+ const entries = fields.filter(field => Object.hasOwn(fm, field)).map(field => {
227
+ const value = fm[field];
228
+ if (typeof value !== "string" || !value.trim() || (allowedValues && !allowedValues.includes(value))) {
229
+ const hint = allowedValues
230
+ ? `Use one of: ${allowedValues.join(", ")}; omit all thinking fields to inherit.`
231
+ : `Use a nonempty string, or omit ${fields.join(" and ")}.`;
232
+ throw new Error(`Invalid ${field}: ${inspect(value, { depth: 1, maxStringLength: 120, maxArrayLength: 10 })}. ${hint}`);
233
+ }
234
+ return { field, value };
235
+ });
236
+ const selected = entries[0];
237
+ if (!selected)
238
+ return undefined;
239
+ if (entries.some(entry => entry.value !== selected.value)) {
240
+ warnIfNew(`Agent file ${path} has conflicting ${fields[0]} aliases: `
241
+ + `${entries.map(entry => `${entry.field}: ${entry.value}`).join(", ")}. `
242
+ + `Using ${selected.field}: ${selected.value}; precedence: ${fields.join(" > ")}.`);
243
+ }
244
+ return selected.value;
245
+ }
246
+ /**
247
+ * Boolean twin of parseAliasedString, for fields whose values are YAML
248
+ * booleans rather than one of a level list — `advisor` today. Validation is
249
+ * the same shape on purpose: every present alias is checked BEFORE precedence
250
+ * (an invalid `advisor` cannot hide behind a valid `advisors` or fall through
251
+ * to it), and a genuine boolean `true`/`false` is the only accepted value —
252
+ * pi's frontmatter parser leaves `on`/`off`/`yes` as strings, so accepting
253
+ * only real booleans turns those misspellings into a skip-the-file diagnostic
254
+ * instead of a silently inherited default.
255
+ */
256
+ function parseAliasedBoolean(fm, path, fields) {
257
+ const entries = fields.filter(field => Object.hasOwn(fm, field)).map(field => {
258
+ const value = fm[field];
259
+ if (typeof value !== "boolean") {
260
+ throw new Error(`Invalid ${field}: ${inspect(value, { depth: 1, maxStringLength: 120, maxArrayLength: 10 })}. `
261
+ + `Use a bare YAML boolean (${fields[0]}: true or ${fields[0]}: false); omit ${fields.join(" and ")} to inherit pi-advisor's own subagent default.`);
262
+ }
263
+ return { field, value };
264
+ });
265
+ const selected = entries[0];
266
+ if (!selected)
267
+ return undefined;
268
+ if (entries.some(entry => entry.value !== selected.value)) {
269
+ warnIfNew(`Agent file ${path} has conflicting ${fields[0]} aliases: `
270
+ + `${entries.map(entry => `${entry.field}: ${entry.value}`).join(", ")}. `
271
+ + `Using ${selected.field}: ${selected.value}; precedence: ${fields.join(" > ")}.`);
272
+ }
273
+ return selected.value;
274
+ }
275
+ // Remaining parsers: omitted → default, "none"/empty → nothing, value → exact.
276
+ /** Extract a string or undefined. */
277
+ function str(val) {
278
+ return typeof val === "string" ? val : undefined;
279
+ }
280
+ /** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
281
+ function nonNegativeInt(val) {
282
+ return typeof val === "number" && val >= 0 ? val : undefined;
283
+ }
284
+ /**
285
+ * Parse a raw CSV field value into items, or undefined if absent/empty/"none".
286
+ */
287
+ function parseCsvField(val) {
288
+ if (val === undefined || val === null)
289
+ return undefined;
290
+ const s = String(val).trim();
291
+ if (!s || s === "none")
292
+ return undefined;
293
+ const items = s.split(",").map(t => t.trim()).filter(Boolean);
294
+ return items.length > 0 ? items : undefined;
295
+ }
296
+ /**
297
+ * Parse the nested-delegation allowlist. Single field, default-off:
298
+ * omitted/empty/"none"/`false` → undefined (no nested tools); "all"/"*"/`true`
299
+ * → "all" (any enabled agent); csv → only the listed types.
300
+ *
301
+ * Booleans are accepted because `extensions:`/`skills:` take them and users
302
+ * generalize: without this, YAML's `true` stringifies into an agent type
303
+ * literally named "true", so the tools appear and every spawn is refused.
304
+ */
305
+ function parseAllowedSubagents(val) {
306
+ if (typeof val === "boolean")
307
+ return val ? "all" : undefined;
308
+ const items = parseCsvField(val);
309
+ if (!items)
310
+ return undefined;
311
+ return items.some(i => i === "*" || i.toLowerCase() === "all") ? "all" : items;
312
+ }
313
+ /**
314
+ * Parse a comma-separated list field with defaults.
315
+ * omitted → defaults; "none"/empty → []; csv → listed items.
316
+ */
317
+ function csvList(val, defaults) {
318
+ if (val === undefined || val === null)
319
+ return defaults;
320
+ return parseCsvField(val) ?? [];
321
+ }
322
+ /**
323
+ * Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
324
+ * `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
325
+ * built-ins; plain entries are built-in names; `ext:` entries are extension-tool
326
+ * selectors parsed later by the runner. omitted → all built-ins, no selectors.
327
+ * `tools:` present with only `ext:` entries → zero built-ins (use `*`).
328
+ */
329
+ function parseToolsField(val) {
330
+ const entries = csvList(val, BUILTIN_TOOL_NAMES);
331
+ const isWildcard = (e) => e === "*" || e.toLowerCase() === "all";
332
+ const hasWildcard = entries.some(isWildcard);
333
+ const plain = entries.filter(e => !isWildcard(e) && !e.startsWith("ext:"));
334
+ const extEntries = entries.filter(e => e.startsWith("ext:"));
335
+ return {
336
+ builtinToolNames: hasWildcard ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain,
337
+ extSelectors: extEntries.length > 0 ? extEntries : undefined,
338
+ };
339
+ }
340
+ /**
341
+ * Parse an optional comma-separated list field.
342
+ * omitted → undefined; "none"/empty → undefined; csv → listed items.
343
+ */
344
+ function csvListOptional(val) {
345
+ return parseCsvField(val);
346
+ }
347
+ /**
348
+ * Parse a memory scope field.
349
+ * omitted → undefined; "user"/"project"/"local" → MemoryScope.
350
+ */
351
+ function parseMemory(val) {
352
+ if (val === "user" || val === "project" || val === "local")
353
+ return val;
354
+ return undefined;
355
+ }
356
+ /**
357
+ * Parse the `isolation` frontmatter field.
358
+ *
359
+ * `off` is kept as a value rather than folded into `undefined` because the two
360
+ * do not mean the same thing here: agent config outranks tool-call params, so
361
+ * `off` vetoes a caller's `worktree` while an absent field lets it through.
362
+ *
363
+ * pi's frontmatter parser is not YAML 1.1 — bare `off` and `no` arrive as
364
+ * strings and only `false` becomes a boolean — so all three spellings are
365
+ * accepted rather than leaving an author's intent silently dropped. Anything
366
+ * else stays `undefined`, as before.
367
+ */
368
+ function parseIsolation(val) {
369
+ if (val === "worktree")
370
+ return "worktree";
371
+ if (val === "off" || val === "none" || val === "no" || val === false)
372
+ return "off";
373
+ return undefined;
374
+ }
375
+ /**
376
+ * Parse an inherit field (extensions, skills).
377
+ * omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
378
+ */
379
+ function inheritField(val) {
380
+ if (val === undefined || val === null || val === true)
381
+ return true;
382
+ if (val === false || val === "none")
383
+ return false;
384
+ const items = csvList(val, []);
385
+ return items.length > 0 ? items : false;
386
+ }
@@ -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,125 @@
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
+ // an exact provider/id match wins; otherwise the same model id resolves
35
+ // on another available provider (date-suffix/dot-dash tolerant). Only as
36
+ // a last resort — and only because this is a built-in default, never for
37
+ // a user-authored .md pin — the parent model is used with a visible
38
+ // notice. See resolvePinnedModel in invocation-config.ts.
39
+ model: "anthropic/claude-haiku-4-5",
40
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
41
+ You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
42
+ Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
43
+
44
+ You are STRICTLY PROHIBITED from:
45
+ - Creating new files
46
+ - Modifying existing files
47
+ - Deleting files
48
+ - Moving or copying files
49
+ - Creating temporary files anywhere, including /tmp
50
+ - Using redirect operators (>, >>, |) or heredocs to write to files
51
+ - Running ANY commands that change system state
52
+
53
+ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
54
+
55
+ # Tool Usage
56
+ - Use the find tool for file pattern matching (NOT the bash find command)
57
+ - Use the grep tool for content search (NOT bash grep/rg command)
58
+ - Use the read tool for reading files (NOT bash cat/head/tail)
59
+ - Use Bash ONLY for read-only operations
60
+ - Make independent tool calls in parallel for efficiency
61
+ - Adapt search approach based on thoroughness level specified
62
+
63
+ # Output
64
+ - Use absolute file paths in all references
65
+ - Report findings as regular messages
66
+ - Do not use emojis
67
+ - Be thorough and precise`,
68
+ promptMode: "replace",
69
+ isDefault: true,
70
+ },
71
+ ],
72
+ [
73
+ "Plan",
74
+ {
75
+ name: "Plan",
76
+ displayName: "Plan",
77
+ 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.",
78
+ builtinToolNames: READ_ONLY_TOOLS,
79
+ extensions: true,
80
+ skills: true,
81
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
82
+ You are a software architect and planning specialist.
83
+ Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
84
+ You do NOT have access to file editing tools — attempting to edit files will fail.
85
+
86
+ You are STRICTLY PROHIBITED from:
87
+ - Creating new files
88
+ - Modifying existing files
89
+ - Deleting files
90
+ - Moving or copying files
91
+ - Creating temporary files anywhere, including /tmp
92
+ - Using redirect operators (>, >>, |) or heredocs to write to files
93
+ - Running ANY commands that change system state
94
+
95
+ # Planning Process
96
+ 1. Understand requirements
97
+ 2. Explore thoroughly (read files, find patterns, understand architecture)
98
+ 3. Design solution based on your assigned perspective
99
+ 4. Detail the plan with step-by-step implementation strategy
100
+
101
+ # Requirements
102
+ - Consider trade-offs and architectural decisions
103
+ - Identify dependencies and sequencing
104
+ - Anticipate potential challenges
105
+ - Follow existing patterns where appropriate
106
+
107
+ # Tool Usage
108
+ - Use the find tool for file pattern matching (NOT the bash find command)
109
+ - Use the grep tool for content search (NOT bash grep/rg command)
110
+ - Use the read tool for reading files (NOT bash cat/head/tail)
111
+ - Use Bash ONLY for read-only operations
112
+
113
+ # Output Format
114
+ - Use absolute file paths
115
+ - Do not use emojis
116
+ - End your response with:
117
+
118
+ ### Critical Files for Implementation
119
+ List 3-5 files most critical for implementing this plan:
120
+ - /absolute/path/to/file.ts - [Brief reason]`,
121
+ promptMode: "replace",
122
+ isDefault: true,
123
+ },
124
+ ],
125
+ ]);
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Reads `enabledModels` from pi's settings (global `<agentDir>/settings.json`
3
+ * + project-local `<cwd>/.pi/settings.json`, project wins) and resolves
4
+ * entries to concrete `provider/modelId` keys for scope validation.
5
+ *
6
+ * **Project overrides global**, mirroring pi's own `SettingsManager`
7
+ * deep-merge behavior and matching the precedence we use for our own
8
+ * `subagents.json` settings (see `src/settings.ts:loadSettings`). If
9
+ * project file has `enabledModels` set, it wholly replaces global's
10
+ * (array fields are replaced, not concatenated).
11
+ *
12
+ * **Limited subset of upstream's resolveModelScope.** We support exact
13
+ * `provider/modelId` matching only. Upstream (pi-coding-agent's
14
+ * `core/model-resolver.ts`) additionally supports glob patterns
15
+ * (`*sonnet*`, `anthropic/*`), bare model IDs without provider, and
16
+ * thinking-level suffixes (`provider/*:high`). Those forms are silently
17
+ * ignored here.
18
+ *
19
+ * In practice, pi's `/scoped-models` picker writes exact `provider/modelId`
20
+ * entries, so the limitation is invisible for users who configure scope
21
+ * through pi's UI. Hand-edited settings using globs or bare IDs will
22
+ * produce an empty allowed set (scope check becomes a no-op).
23
+ *
24
+ * Example:
25
+ * enabledModels = ["anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6"]
26
+ * → resolves to { "anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6" }
27
+ */
28
+ /** Minimal registry shape — only the methods resolveEnabledModels actually calls. */
29
+ export interface ModelRegistryRef {
30
+ getAll(): unknown[];
31
+ getAvailable?(): unknown[];
32
+ }
33
+ /**
34
+ * Read enabledModels from pi's settings — project-local overrides global.
35
+ * Mirrors pi's SettingsManager deep-merge for the `enabledModels` field
36
+ * (and matches our own loadSettings precedence in src/settings.ts).
37
+ * Returns undefined when neither file has the field.
38
+ */
39
+ export declare function readEnabledModels(cwd: string): string[] | undefined;
40
+ export declare function resolveEnabledModels(patterns: string[] | undefined, registry: ModelRegistryRef, cwd?: string): Set<string> | undefined;
41
+ /**
42
+ * True when `model` is in the allowed set. Centralizes the key format
43
+ * (`provider/id` lowercase) so callers don't have to reproduce it —
44
+ * both set-building (resolveExact) and lookup go through `modelKey`.
45
+ */
46
+ export declare function isModelInScope(model: {
47
+ provider: string;
48
+ id: string;
49
+ }, allowed: Set<string>): boolean;