@ymy88/pi-subagents 0.0.0-stage → 0.24.0

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