@diousk/pi-subagents-fast 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +808 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1034 -0
  5. package/SECURITY.md +95 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/agent-color.d.ts +35 -0
  9. package/dist/agent-color.js +123 -0
  10. package/dist/agent-file-toggle.d.ts +125 -0
  11. package/dist/agent-file-toggle.js +260 -0
  12. package/dist/agent-manager.d.ts +472 -0
  13. package/dist/agent-manager.js +1338 -0
  14. package/dist/agent-runner.d.ts +312 -0
  15. package/dist/agent-runner.js +1034 -0
  16. package/dist/agent-types.d.ts +119 -0
  17. package/dist/agent-types.js +286 -0
  18. package/dist/child-context.d.ts +2 -0
  19. package/dist/child-context.js +12 -0
  20. package/dist/context.d.ts +12 -0
  21. package/dist/context.js +56 -0
  22. package/dist/cross-extension-rpc.d.ts +66 -0
  23. package/dist/cross-extension-rpc.js +138 -0
  24. package/dist/custom-agents.d.ts +54 -0
  25. package/dist/custom-agents.js +316 -0
  26. package/dist/default-agents.d.ts +7 -0
  27. package/dist/default-agents.js +122 -0
  28. package/dist/enabled-models.d.ts +49 -0
  29. package/dist/enabled-models.js +145 -0
  30. package/dist/env.d.ts +6 -0
  31. package/dist/env.js +28 -0
  32. package/dist/group-join.d.ts +32 -0
  33. package/dist/group-join.js +116 -0
  34. package/dist/index.d.ts +50 -0
  35. package/dist/index.js +3682 -0
  36. package/dist/invocation-config.d.ts +107 -0
  37. package/dist/invocation-config.js +83 -0
  38. package/dist/memory.d.ts +53 -0
  39. package/dist/memory.js +165 -0
  40. package/dist/mention-clone.d.ts +87 -0
  41. package/dist/mention-clone.js +153 -0
  42. package/dist/mention.d.ts +81 -0
  43. package/dist/mention.js +131 -0
  44. package/dist/model-resolver.d.ts +36 -0
  45. package/dist/model-resolver.js +95 -0
  46. package/dist/model-scope.d.ts +49 -0
  47. package/dist/model-scope.js +48 -0
  48. package/dist/nested-tools.d.ts +55 -0
  49. package/dist/nested-tools.js +299 -0
  50. package/dist/output-file.d.ts +43 -0
  51. package/dist/output-file.js +142 -0
  52. package/dist/prompts.d.ts +55 -0
  53. package/dist/prompts.js +91 -0
  54. package/dist/schedule-store.d.ts +38 -0
  55. package/dist/schedule-store.js +155 -0
  56. package/dist/schedule.d.ts +109 -0
  57. package/dist/schedule.js +359 -0
  58. package/dist/settings.d.ts +360 -0
  59. package/dist/settings.js +251 -0
  60. package/dist/skill-loader.d.ts +24 -0
  61. package/dist/skill-loader.js +93 -0
  62. package/dist/status-note.d.ts +61 -0
  63. package/dist/status-note.js +85 -0
  64. package/dist/structured-output.d.ts +61 -0
  65. package/dist/structured-output.js +112 -0
  66. package/dist/types.d.ts +371 -0
  67. package/dist/types.js +5 -0
  68. package/dist/ui/agent-mention.d.ts +82 -0
  69. package/dist/ui/agent-mention.js +187 -0
  70. package/dist/ui/agent-widget.d.ts +219 -0
  71. package/dist/ui/agent-widget.js +592 -0
  72. package/dist/ui/conversation-viewer.d.ts +120 -0
  73. package/dist/ui/conversation-viewer.js +578 -0
  74. package/dist/ui/fleet-list.d.ts +195 -0
  75. package/dist/ui/fleet-list.js +471 -0
  76. package/dist/ui/schedule-menu.d.ts +16 -0
  77. package/dist/ui/schedule-menu.js +94 -0
  78. package/dist/ui/select-item.d.ts +27 -0
  79. package/dist/ui/select-item.js +34 -0
  80. package/dist/ui/viewer-keys.d.ts +20 -0
  81. package/dist/ui/viewer-keys.js +17 -0
  82. package/dist/ui/workflow-card.d.ts +175 -0
  83. package/dist/ui/workflow-card.js +332 -0
  84. package/dist/ui/workflow-dialog.d.ts +305 -0
  85. package/dist/ui/workflow-dialog.js +843 -0
  86. package/dist/ui/workflow-menu.d.ts +60 -0
  87. package/dist/ui/workflow-menu.js +147 -0
  88. package/dist/usage.d.ts +135 -0
  89. package/dist/usage.js +120 -0
  90. package/dist/workflow/collisions.d.ts +95 -0
  91. package/dist/workflow/collisions.js +88 -0
  92. package/dist/workflow/entry.d.ts +32 -0
  93. package/dist/workflow/entry.js +29 -0
  94. package/dist/workflow/host.d.ts +62 -0
  95. package/dist/workflow/host.js +362 -0
  96. package/dist/workflow/journal.d.ts +97 -0
  97. package/dist/workflow/journal.js +120 -0
  98. package/dist/workflow/json-schema.d.ts +51 -0
  99. package/dist/workflow/json-schema.js +111 -0
  100. package/dist/workflow/meta.d.ts +67 -0
  101. package/dist/workflow/meta.js +317 -0
  102. package/dist/workflow/progress.d.ts +224 -0
  103. package/dist/workflow/progress.js +361 -0
  104. package/dist/workflow/runtime.d.ts +334 -0
  105. package/dist/workflow/runtime.js +830 -0
  106. package/dist/workflow/saved.d.ts +90 -0
  107. package/dist/workflow/saved.js +203 -0
  108. package/dist/workflow/task.d.ts +136 -0
  109. package/dist/workflow/task.js +207 -0
  110. package/dist/workflow/tool-description.d.ts +38 -0
  111. package/dist/workflow/tool-description.js +199 -0
  112. package/dist/workflow/worker-source.d.ts +47 -0
  113. package/dist/workflow/worker-source.js +778 -0
  114. package/dist/worktree.d.ts +52 -0
  115. package/dist/worktree.js +164 -0
  116. package/dist/xml.d.ts +10 -0
  117. package/dist/xml.js +12 -0
  118. package/docs/rpc.md +183 -0
  119. package/docs/workflows.md +437 -0
  120. package/examples/agent-tool-description.md +42 -0
  121. package/examples/workflows/compose.js +51 -0
  122. package/examples/workflows/fan-out-audit.js +47 -0
  123. package/examples/workflows/gated-fix.js +60 -0
  124. package/examples/workflows/lib/count-child.js +27 -0
  125. package/examples/workflows/review-panel.js +63 -0
  126. package/examples/workflows/structured-findings.js +78 -0
  127. package/package.json +68 -0
  128. package/src/abortable.ts +43 -0
  129. package/src/agent-color.ts +161 -0
  130. package/src/agent-file-toggle.ts +270 -0
  131. package/src/agent-manager.ts +1581 -0
  132. package/src/agent-runner.ts +1286 -0
  133. package/src/agent-types.ts +346 -0
  134. package/src/child-context.ts +15 -0
  135. package/src/context.ts +58 -0
  136. package/src/cross-extension-rpc.ts +198 -0
  137. package/src/custom-agents.ts +333 -0
  138. package/src/default-agents.ts +126 -0
  139. package/src/enabled-models.ts +180 -0
  140. package/src/env.ts +33 -0
  141. package/src/group-join.ts +141 -0
  142. package/src/index.ts +3991 -0
  143. package/src/invocation-config.ts +155 -0
  144. package/src/memory.ts +179 -0
  145. package/src/mention-clone.ts +196 -0
  146. package/src/mention.ts +141 -0
  147. package/src/model-resolver.ts +118 -0
  148. package/src/model-scope.ts +70 -0
  149. package/src/nested-tools.ts +422 -0
  150. package/src/output-file.ts +155 -0
  151. package/src/prompts.ts +142 -0
  152. package/src/schedule-store.ts +153 -0
  153. package/src/schedule.ts +386 -0
  154. package/src/settings.ts +587 -0
  155. package/src/skill-loader.ts +102 -0
  156. package/src/status-note.ts +90 -0
  157. package/src/structured-output.ts +130 -0
  158. package/src/types.ts +384 -0
  159. package/src/ui/agent-mention.ts +216 -0
  160. package/src/ui/agent-widget.ts +664 -0
  161. package/src/ui/conversation-viewer.ts +589 -0
  162. package/src/ui/fleet-list.ts +543 -0
  163. package/src/ui/schedule-menu.ts +105 -0
  164. package/src/ui/select-item.ts +45 -0
  165. package/src/ui/viewer-keys.ts +39 -0
  166. package/src/ui/workflow-card.ts +470 -0
  167. package/src/ui/workflow-dialog.ts +1115 -0
  168. package/src/ui/workflow-menu.ts +193 -0
  169. package/src/usage.ts +167 -0
  170. package/src/workflow/collisions.ts +123 -0
  171. package/src/workflow/entry.ts +47 -0
  172. package/src/workflow/host.ts +403 -0
  173. package/src/workflow/journal.ts +164 -0
  174. package/src/workflow/json-schema.ts +128 -0
  175. package/src/workflow/meta.ts +325 -0
  176. package/src/workflow/progress.ts +550 -0
  177. package/src/workflow/runtime.ts +1219 -0
  178. package/src/workflow/saved.ts +217 -0
  179. package/src/workflow/task.ts +302 -0
  180. package/src/workflow/tool-description.ts +200 -0
  181. package/src/workflow/worker-source.ts +781 -0
  182. package/src/worktree.ts +205 -0
  183. package/src/xml.ts +13 -0
@@ -0,0 +1,333 @@
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
+
5
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
6
+ import { basename, join } from "node:path";
7
+ import { getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
+ import { BUILTIN_TOOL_NAMES } from "./agent-types.js";
9
+ import type { AgentConfig, IsolationMode, MemoryScope, ServiceTier, ThinkingLevel } from "./types.js";
10
+
11
+ /**
12
+ * The one thing a declared `name:` may not contain, matching Claude Code
13
+ * exactly: it reserves `:` for plugin-scoped identifiers (`my-plugin:reviewer`)
14
+ * and refuses to load a file whose name uses one.
15
+ *
16
+ * Nothing else is rejected. Claude Code's docs describe names as "lowercase
17
+ * letters and hyphens", but that is guidance — the only stated load failure is
18
+ * the colon, so `name: Code Reviewer` must work here too. (The stricter
19
+ * letters/digits/underscore/hyphen regex in Claude Code applies to the Agent
20
+ * tool's spawn-time `name` parameter, which is a different field.) Mixed case
21
+ * has to be allowed regardless: the built-in types `Explore` and `Plan` use it,
22
+ * and a file must be able to override one.
23
+ */
24
+ const RESERVED_IN_TYPE = ":";
25
+
26
+ /**
27
+ * Scan for custom agent .md files from multiple locations.
28
+ * Discovery hierarchy (higher priority wins):
29
+ * 1. Project: <cwd>/.pi/agents/*.md (authoritative — also where /agents writes)
30
+ * 2. Workspace: <cwd>/.agents/agents/*.md (shared cross-tool .agents workspace, read-only)
31
+ * 3. Global: $PI_CODING_AGENT_DIR/agents/*.md (default: ~/.pi/agent/agents/*.md)
32
+ *
33
+ * Project-level agents override global ones with the same name. On a name clash
34
+ * between the two project locations, .pi/agents wins — .pi stays the project
35
+ * authority; .agents/agents is an additional read location.
36
+ * Any name is allowed — names matching defaults (e.g. "Explore") override them.
37
+ *
38
+ * An agent's type comes from its frontmatter `name:`, falling back to the
39
+ * filename — Claude Code's rule, where "the filename doesn't have to match".
40
+ * Because the type is now declared rather than derived from a unique path, two
41
+ * files can claim the same one; the later load wins, as it always has for a
42
+ * filename clash, and `warnSkippedOverride` reports the substitution.
43
+ */
44
+ export function loadCustomAgents(cwd: string, strict = false): Map<string, AgentConfig> {
45
+ const globalDir = join(getAgentDir(), "agents");
46
+ const workspaceProjectDir = join(cwd, ".agents", "agents");
47
+ const projectDir = join(cwd, ".pi", "agents");
48
+
49
+ const agents = new Map<string, AgentConfig>();
50
+ loadFromDir(globalDir, agents, "global", strict); // lowest priority
51
+ loadFromDir(workspaceProjectDir, agents, "project", strict); // shared workspace
52
+ loadFromDir(projectDir, agents, "project", strict); // highest priority (overwrites)
53
+
54
+ warnedLastLoad = warnedThisLoad;
55
+ warnedThisLoad = new Set();
56
+ return agents;
57
+ }
58
+
59
+ /** Load agent configs from a directory into the map. */
60
+ function loadFromDir(dir: string, agents: Map<string, AgentConfig>, source: "project" | "global", strict: boolean): void {
61
+ if (!existsSync(dir)) return;
62
+
63
+ let files: string[];
64
+ try {
65
+ files = readdirSync(dir).filter(f => f.endsWith(".md"));
66
+ } catch {
67
+ return;
68
+ }
69
+
70
+ for (const file of files) {
71
+ const filenameType = basename(file, ".md");
72
+
73
+ const path = join(dir, file);
74
+
75
+ const parsed = readAgentFile(path, strict);
76
+ if (!parsed) {
77
+ warnSkippedOverride(filenameType, agents);
78
+ continue;
79
+ }
80
+ const { frontmatter: fm, body } = parsed;
81
+
82
+ // Claude Code's rule: `name:` IS the agent type, and the filename need not
83
+ // match. Absent, the filename stands in — Claude Code requires the field,
84
+ // but most files here predate it and must keep loading.
85
+ const declared = str(fm.name)?.trim();
86
+ if (declared?.includes(RESERVED_IN_TYPE)) {
87
+ // Refusing beats silently substituting: the file would otherwise load
88
+ // under its filename, so `Agent({subagent_type})` would succeed against
89
+ // an agent whose declared identity nothing honoured.
90
+ warnIfNew(
91
+ `Agent file ${path} declares name "${declared}", which contains "${RESERVED_IN_TYPE}" — reserved for `
92
+ + "plugin-scoped identifiers. Rename it, or move the label to `display_name:`. Skipping.",
93
+ );
94
+ // No `warnSkippedOverride`: this file would have registered under its
95
+ // *declared* name, which nothing else can hold (a colon keeps it out of
96
+ // the registry), so it shadowed nothing. Passing the filename instead
97
+ // would report a substitution of an unrelated agent that never happened.
98
+ continue;
99
+ }
100
+ // `||`, not `??`: a quoted empty or all-whitespace `name:` would otherwise
101
+ // register the agent under the empty type — unspawnable, and it takes the
102
+ // filename-derived one down with it.
103
+ const name = declared || filenameType;
104
+
105
+ const { builtinToolNames, extSelectors } = parseToolsField(fm.tools);
106
+
107
+ agents.set(name, {
108
+ name,
109
+ // Only `display_name` now: `name` is the type, and `getConfig` already
110
+ // falls back to the type when no label is set — so a Claude Code file
111
+ // with `name: code-reviewer` still badges as "code-reviewer".
112
+ displayName: str(fm.display_name),
113
+ color: str(fm.color),
114
+ description: str(fm.description) ?? name,
115
+ builtinToolNames,
116
+ extSelectors,
117
+ disallowedTools: csvListOptional(fm.disallowed_tools),
118
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
119
+ excludeExtensions: csvListOptional(fm.exclude_extensions),
120
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
121
+ model: str(fm.model),
122
+ thinking: str(fm.thinking) as ThinkingLevel | undefined,
123
+ serviceTier: parseServiceTier(fm.service_tier),
124
+ maxTurns: nonNegativeInt(fm.max_turns),
125
+ persistSession: fm.persist_session != null ? fm.persist_session === true : undefined,
126
+ outputTranscript: fm.output_transcript != null ? fm.output_transcript !== false : undefined,
127
+ sessionDir: str(fm.session_dir),
128
+ allowedSubagents: parseAllowedSubagents(fm.allowed_subagents),
129
+ systemPrompt: body.trim(),
130
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
131
+ inheritContext: fm.inherit_context != null ? fm.inherit_context === true : undefined,
132
+ runInBackground: fm.run_in_background != null ? fm.run_in_background === true : undefined,
133
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
134
+ memory: parseMemory(fm.memory),
135
+ isolation: parseIsolation(fm.isolation),
136
+ enabled: fm.enabled !== false, // default true; explicitly false disables
137
+ source,
138
+ sourcePath: path,
139
+ });
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Read and parse one agent file, or warn and return undefined for the caller to
145
+ * skip. One bad file must not take the whole extension down with it — an
146
+ * unparseable `.md` used to abort activation, so pi exited before the TUI.
147
+ *
148
+ * The path is as much of the fix as the recovery: a bare YAML error ("line 2,
149
+ * column 14") is unactionable when agents come from three directories at once,
150
+ * and the only other symptom is `Unknown agent type`, which reads like a typo.
151
+ *
152
+ * Under `strict` the same failure rethrows, still naming the path, so callers
153
+ * that opted into failing closed stop rather than run a substituted agent.
154
+ */
155
+ /**
156
+ * Parse an agent file's frontmatter, tolerating a leading UTF-8 BOM.
157
+ *
158
+ * Editors across the Windows/CJK world write UTF-8 with a BOM by default, and
159
+ * pi's parser did not look past one before 0.84.3: the fence never matched, so
160
+ * the frontmatter came back empty and the *whole file* — YAML and all — became
161
+ * the body. An agent authored that way silently lost every field. `tools: none`
162
+ * going missing is the sharp edge: the agent registers with the default
163
+ * toolset rather than none, which is a wider grant than its author wrote.
164
+ *
165
+ * Stripped here rather than detected per pi version, because this is the only
166
+ * place agent files are read and the BOM is a file-encoding artifact, not
167
+ * content — normalising it at the boundary keeps one behaviour across the whole
168
+ * supported peer range instead of forking on what happens to be installed.
169
+ */
170
+ export function parseAgentFrontmatter<T extends Record<string, unknown>>(content: string): { frontmatter: T; body: string } {
171
+ return parseFrontmatter<T>(content.startsWith("\uFEFF") ? content.slice(1) : content);
172
+ }
173
+
174
+ function readAgentFile(path: string, strict: boolean): { frontmatter: Record<string, unknown>; body: string } | undefined {
175
+ try {
176
+ return parseAgentFrontmatter<Record<string, unknown>>(readFileSync(path, "utf-8"));
177
+ } catch (err) {
178
+ const reason = err instanceof Error ? err.message : String(err);
179
+ if (strict) throw new Error(`${path}: ${reason}`);
180
+ warnIfNew(`Skipping agent file ${path}: ${reason}`);
181
+ return undefined;
182
+ }
183
+ }
184
+
185
+ /**
186
+ * A skipped file that was overriding an already-loaded agent leaves the name
187
+ * pointing at a *different* file — its own prompt, model and tools. Nothing
188
+ * downstream can flag that: unlike an unknown type, the `Agent` call succeeds.
189
+ */
190
+ function warnSkippedOverride(name: string, agents: Map<string, AgentConfig>): void {
191
+ const surviving = agents.get(name);
192
+ // Nothing shadowed, or what it shadowed is disabled: dispatch refuses the type
193
+ // either way (see resolveEnabledTypeIn), so there is no substitution to report.
194
+ if (!surviving?.sourcePath || surviving.enabled === false) return;
195
+ warnIfNew(`Agent "${name}" now loads from ${surviving.sourcePath} instead`);
196
+ }
197
+
198
+ let warnedLastLoad = new Set<string>();
199
+ let warnedThisLoad = new Set<string>();
200
+
201
+ /**
202
+ * Agents reload on activation and again on every `Agent` call, so an unchanged
203
+ * problem would re-warn all session — over a painted TUI, since pi does not
204
+ * redirect console output. Compare against the previous load rather than every
205
+ * load ever, so a file that is fixed and then broken again still reports.
206
+ */
207
+ function warnIfNew(message: string): void {
208
+ warnedThisLoad.add(message);
209
+ if (warnedLastLoad.has(message)) return;
210
+ console.warn(`[pi-subagents] ${message}`);
211
+ }
212
+
213
+ // ---- Field parsers ----
214
+ // All follow the same convention: omitted → default, "none"/empty → nothing, value → exact.
215
+
216
+ /** Extract a string or undefined. */
217
+ function str(val: unknown): string | undefined {
218
+ return typeof val === "string" ? val : undefined;
219
+ }
220
+
221
+ /** Extract a non-negative integer or undefined. 0 means unlimited for max_turns. */
222
+ function nonNegativeInt(val: unknown): number | undefined {
223
+ return typeof val === "number" && val >= 0 ? val : undefined;
224
+ }
225
+
226
+ /**
227
+ * Parse a raw CSV field value into items, or undefined if absent/empty/"none".
228
+ */
229
+ function parseCsvField(val: unknown): string[] | undefined {
230
+ if (val === undefined || val === null) return undefined;
231
+ const s = String(val).trim();
232
+ if (!s || s === "none") return undefined;
233
+ const items = s.split(",").map(t => t.trim()).filter(Boolean);
234
+ return items.length > 0 ? items : undefined;
235
+ }
236
+
237
+ /**
238
+ * Parse the nested-delegation allowlist. Single field, default-off:
239
+ * omitted/empty/"none"/`false` → undefined (no nested tools); "all"/"*"/`true`
240
+ * → "all" (any enabled agent); csv → only the listed types.
241
+ *
242
+ * Booleans are accepted because `extensions:`/`skills:` take them and users
243
+ * generalize: without this, YAML's `true` stringifies into an agent type
244
+ * literally named "true", so the tools appear and every spawn is refused.
245
+ */
246
+ function parseAllowedSubagents(val: unknown): "all" | string[] | undefined {
247
+ if (typeof val === "boolean") return val ? "all" : undefined;
248
+ const items = parseCsvField(val);
249
+ if (!items) return undefined;
250
+ return items.some(i => i === "*" || i.toLowerCase() === "all") ? "all" : items;
251
+ }
252
+
253
+ /**
254
+ * Parse a comma-separated list field with defaults.
255
+ * omitted → defaults; "none"/empty → []; csv → listed items.
256
+ */
257
+ function csvList(val: unknown, defaults: string[]): string[] {
258
+ if (val === undefined || val === null) return defaults;
259
+ return parseCsvField(val) ?? [];
260
+ }
261
+
262
+ /**
263
+ * Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
264
+ * `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
265
+ * built-ins; plain entries are built-in names; `ext:` entries are extension-tool
266
+ * selectors parsed later by the runner. omitted → all built-ins, no selectors.
267
+ * `tools:` present with only `ext:` entries → zero built-ins (use `*`).
268
+ */
269
+ function parseToolsField(val: unknown): { builtinToolNames: string[]; extSelectors: string[] | undefined } {
270
+ const entries = csvList(val, BUILTIN_TOOL_NAMES);
271
+ const isWildcard = (e: string) => e === "*" || e.toLowerCase() === "all";
272
+ const hasWildcard = entries.some(isWildcard);
273
+ const plain = entries.filter(e => !isWildcard(e) && !e.startsWith("ext:"));
274
+ const extEntries = entries.filter(e => e.startsWith("ext:"));
275
+ return {
276
+ builtinToolNames: hasWildcard ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])] : plain,
277
+ extSelectors: extEntries.length > 0 ? extEntries : undefined,
278
+ };
279
+ }
280
+
281
+ /**
282
+ * Parse an optional comma-separated list field.
283
+ * omitted → undefined; "none"/empty → undefined; csv → listed items.
284
+ */
285
+ function csvListOptional(val: unknown): string[] | undefined {
286
+ return parseCsvField(val);
287
+ }
288
+
289
+ /**
290
+ * Parse a memory scope field.
291
+ * omitted → undefined; "user"/"project"/"local" → MemoryScope.
292
+ */
293
+ function parseMemory(val: unknown): MemoryScope | undefined {
294
+ if (val === "user" || val === "project" || val === "local") return val;
295
+ return undefined;
296
+ }
297
+
298
+ /** Parse the OpenAI Responses/Codex `service_tier` frontmatter field. */
299
+ function parseServiceTier(val: unknown): ServiceTier | undefined {
300
+ if (val === "auto" || val === "default" || val === "flex" || val === "priority" || val === "scale") {
301
+ return val;
302
+ }
303
+ return undefined;
304
+ }
305
+
306
+ /**
307
+ * Parse the `isolation` frontmatter field.
308
+ *
309
+ * `off` is kept as a value rather than folded into `undefined` because the two
310
+ * do not mean the same thing here: agent config outranks tool-call params, so
311
+ * `off` vetoes a caller's `worktree` while an absent field lets it through.
312
+ *
313
+ * pi's frontmatter parser is not YAML 1.1 — bare `off` and `no` arrive as
314
+ * strings and only `false` becomes a boolean — so all three spellings are
315
+ * accepted rather than leaving an author's intent silently dropped. Anything
316
+ * else stays `undefined`, as before.
317
+ */
318
+ function parseIsolation(val: unknown): IsolationMode | undefined {
319
+ if (val === "worktree") return "worktree";
320
+ if (val === "off" || val === "none" || val === "no" || val === false) return "off";
321
+ return undefined;
322
+ }
323
+
324
+ /**
325
+ * Parse an inherit field (extensions, skills).
326
+ * omitted/true → true (inherit all); false/"none"/empty → false; csv → listed names.
327
+ */
328
+ function inheritField(val: unknown): true | string[] | false {
329
+ if (val === undefined || val === null || val === true) return true;
330
+ if (val === false || val === "none") return false;
331
+ const items = csvList(val, []);
332
+ return items.length > 0 ? items : false;
333
+ }
@@ -0,0 +1,126 @@
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
+
7
+ import type { AgentConfig } from "./types.js";
8
+
9
+ const READ_ONLY_TOOLS = ["read", "bash", "grep", "find", "ls"];
10
+
11
+ export const DEFAULT_AGENTS: Map<string, AgentConfig> = new Map([
12
+ [
13
+ "general-purpose",
14
+ {
15
+ name: "general-purpose",
16
+ displayName: "Agent",
17
+ 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.",
18
+ // builtinToolNames omitted — means "all available tools" (resolved at lookup time)
19
+ // inheritContext / runInBackground / isolated omitted — strategy fields, callers decide per-call.
20
+ // Setting them to false would lock callsite intent (see resolveAgentInvocationConfig in invocation-config.ts).
21
+ extensions: true,
22
+ skills: true,
23
+ systemPrompt: "",
24
+ promptMode: "append",
25
+ isDefault: true,
26
+ },
27
+ ],
28
+ [
29
+ "Explore",
30
+ {
31
+ name: "Explore",
32
+ displayName: "Explore",
33
+ 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.",
34
+ builtinToolNames: READ_ONLY_TOOLS,
35
+ extensions: true,
36
+ skills: true,
37
+ // Fast/cheap model for read-only search. Provider-preferred but resilient:
38
+ // resolveModel matches this fuzzily (date-stamp optional) and falls back to
39
+ // the same model under another provider if anthropic doesn't expose it.
40
+ model: "anthropic/claude-haiku-4-5",
41
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
42
+ You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
43
+ Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
44
+
45
+ You are STRICTLY PROHIBITED from:
46
+ - Creating new files
47
+ - Modifying existing files
48
+ - Deleting files
49
+ - Moving or copying files
50
+ - Creating temporary files anywhere, including /tmp
51
+ - Using redirect operators (>, >>, |) or heredocs to write to files
52
+ - Running ANY commands that change system state
53
+
54
+ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
55
+
56
+ # Tool Usage
57
+ - Use the find tool for file pattern matching (NOT the bash find command)
58
+ - Use the grep tool for content search (NOT bash grep/rg command)
59
+ - Use the read tool for reading files (NOT bash cat/head/tail)
60
+ - Use Bash ONLY for read-only operations
61
+ - Make independent tool calls in parallel for efficiency
62
+ - Adapt search approach based on thoroughness level specified
63
+
64
+ # Output
65
+ - Use absolute file paths in all references
66
+ - Report findings as regular messages
67
+ - Do not use emojis
68
+ - Be thorough and precise`,
69
+ promptMode: "replace",
70
+ isDefault: true,
71
+ },
72
+ ],
73
+ [
74
+ "Plan",
75
+ {
76
+ name: "Plan",
77
+ displayName: "Plan",
78
+ 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.",
79
+ builtinToolNames: READ_ONLY_TOOLS,
80
+ extensions: true,
81
+ skills: true,
82
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
83
+ You are a software architect and planning specialist.
84
+ Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
85
+ You do NOT have access to file editing tools — attempting to edit files will fail.
86
+
87
+ You are STRICTLY PROHIBITED from:
88
+ - Creating new files
89
+ - Modifying existing files
90
+ - Deleting files
91
+ - Moving or copying files
92
+ - Creating temporary files anywhere, including /tmp
93
+ - Using redirect operators (>, >>, |) or heredocs to write to files
94
+ - Running ANY commands that change system state
95
+
96
+ # Planning Process
97
+ 1. Understand requirements
98
+ 2. Explore thoroughly (read files, find patterns, understand architecture)
99
+ 3. Design solution based on your assigned perspective
100
+ 4. Detail the plan with step-by-step implementation strategy
101
+
102
+ # Requirements
103
+ - Consider trade-offs and architectural decisions
104
+ - Identify dependencies and sequencing
105
+ - Anticipate potential challenges
106
+ - Follow existing patterns where appropriate
107
+
108
+ # Tool Usage
109
+ - Use the find tool for file pattern matching (NOT the bash find command)
110
+ - Use the grep tool for content search (NOT bash grep/rg command)
111
+ - Use the read tool for reading files (NOT bash cat/head/tail)
112
+ - Use Bash ONLY for read-only operations
113
+
114
+ # Output Format
115
+ - Use absolute file paths
116
+ - Do not use emojis
117
+ - End your response with:
118
+
119
+ ### Critical Files for Implementation
120
+ List 3-5 files most critical for implementing this plan:
121
+ - /absolute/path/to/file.ts - [Brief reason]`,
122
+ promptMode: "replace",
123
+ isDefault: true,
124
+ },
125
+ ],
126
+ ]);
@@ -0,0 +1,180 @@
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
+
29
+ import { existsSync, readFileSync, statSync } from "node:fs";
30
+ import { join } from "node:path";
31
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
32
+ import type { ModelEntry } from "./model-resolver.js";
33
+
34
+ /** Minimal registry shape — only the methods resolveEnabledModels actually calls. */
35
+ export interface ModelRegistryRef {
36
+ getAll(): unknown[];
37
+ getAvailable?(): unknown[];
38
+ }
39
+
40
+ /** Paths to pi's settings.json files: [project, global] (project takes precedence). */
41
+ function settingsPaths(cwd: string): [project: string, global: string] {
42
+ return [
43
+ join(cwd, ".pi", "settings.json"),
44
+ join(getAgentDir(), "settings.json"),
45
+ ];
46
+ }
47
+
48
+ /** Read `enabledModels` from a single settings.json file. Undefined when missing or absent. */
49
+ function readField(path: string): string[] | undefined {
50
+ if (!existsSync(path)) return undefined;
51
+ try {
52
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
53
+ if (Array.isArray(raw?.enabledModels)) return raw.enabledModels as string[];
54
+ } catch {
55
+ /* corrupt file — silent */
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ /**
61
+ * Read enabledModels from pi's settings — project-local overrides global.
62
+ * Mirrors pi's SettingsManager deep-merge for the `enabledModels` field
63
+ * (and matches our own loadSettings precedence in src/settings.ts).
64
+ * Returns undefined when neither file has the field.
65
+ */
66
+ export function readEnabledModels(cwd: string): string[] | undefined {
67
+ const [project, global] = settingsPaths(cwd);
68
+ return readField(project) ?? readField(global);
69
+ }
70
+
71
+ /**
72
+ * Resolve enabledModels patterns → Set<"provider/modelId"> (lowercase keys).
73
+ *
74
+ * Only exact `provider/modelId` patterns are matched (case-insensitive).
75
+ * Patterns without a slash, with glob characters, or with a `:thinking`
76
+ * suffix are silently dropped. See module-level docstring for rationale.
77
+ *
78
+ * Cache: keyed on JSON.stringify(patterns) + mtime/size of *both*
79
+ * project and global settings.json files. Re-resolves when either file
80
+ * changes or the patterns argument differs.
81
+ *
82
+ * Returns undefined when no patterns are provided or no patterns match
83
+ * (scope check becomes a no-op at the call site).
84
+ */
85
+
86
+ // Module-level cache — invalidated when either settings.json changes or patterns differ.
87
+ let cachedAllowed: Set<string> | undefined;
88
+ let cachedHash = "";
89
+ let cachedPatternsKey = "";
90
+
91
+ /** mtime+size hash of one file, or "missing" if absent. */
92
+ function hashOf(path: string): string {
93
+ try {
94
+ const s = statSync(path);
95
+ return `${s.mtimeMs}-${s.size}`;
96
+ } catch {
97
+ return "missing";
98
+ }
99
+ }
100
+
101
+ export function resolveEnabledModels(
102
+ patterns: string[] | undefined,
103
+ registry: ModelRegistryRef,
104
+ cwd: string = process.cwd(),
105
+ ): Set<string> | undefined {
106
+ // Fast path: check cache (stat both project and global settings.json files)
107
+ const patternsKey = JSON.stringify(patterns);
108
+ const [project, global] = settingsPaths(cwd);
109
+ const fileHash = `${hashOf(project)};${hashOf(global)}`;
110
+
111
+ if (fileHash === cachedHash && patternsKey === cachedPatternsKey) {
112
+ return cachedAllowed;
113
+ }
114
+
115
+ // Cache miss — resolve
116
+ if (!patterns || patterns.length === 0) {
117
+ cachedHash = fileHash;
118
+ cachedPatternsKey = patternsKey;
119
+ cachedAllowed = undefined;
120
+ return undefined;
121
+ }
122
+
123
+ const available = (registry.getAvailable?.() ?? registry.getAll()) as ModelEntry[];
124
+ const allowed = new Set<string>();
125
+
126
+ for (const pattern of patterns) {
127
+ const trimmed = pattern.trim();
128
+ if (!trimmed) continue; // skip empty/whitespace
129
+ resolveExact(trimmed, available, allowed);
130
+ }
131
+
132
+ const result = allowed.size > 0 ? allowed : undefined;
133
+ cachedHash = fileHash;
134
+ cachedPatternsKey = patternsKey;
135
+ cachedAllowed = result;
136
+ return result;
137
+ }
138
+
139
+
140
+
141
+ /**
142
+ * True when `model` is in the allowed set. Centralizes the key format
143
+ * (`provider/id` lowercase) so callers don't have to reproduce it —
144
+ * both set-building (resolveExact) and lookup go through `modelKey`.
145
+ */
146
+ export function isModelInScope(
147
+ model: { provider: string; id: string },
148
+ allowed: Set<string>,
149
+ ): boolean {
150
+ return allowed.has(modelKey(model));
151
+ }
152
+
153
+ /** Canonical lowercase `provider/id` key for the allowed set. */
154
+ function modelKey(model: { provider: string; id: string }): string {
155
+ return `${model.provider}/${model.id}`.toLowerCase();
156
+ }
157
+
158
+ /**
159
+ * Resolve exact model pattern. Example: "google/gemma-4-31b-it".
160
+ */
161
+ function resolveExact(
162
+ pattern: string,
163
+ available: ModelEntry[],
164
+ allowed: Set<string>,
165
+ ): void {
166
+ // "provider/modelId" — exact (colon is part of id, not split)
167
+ const slashIdx = pattern.indexOf("/");
168
+ if (slashIdx === -1) return; // bare modelId not supported
169
+
170
+ const provider = pattern.slice(0, slashIdx).toLowerCase();
171
+ const modelId = pattern.slice(slashIdx + 1).toLowerCase();
172
+ const exact = available.find(
173
+ m => m.provider.toLowerCase() === provider && m.id.toLowerCase() === modelId,
174
+ );
175
+ if (exact) {
176
+ allowed.add(modelKey(exact));
177
+ }
178
+ }
179
+
180
+
package/src/env.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * env.ts — Detect environment info (git, platform) for subagent system prompts.
3
+ */
4
+
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import type { EnvInfo } from "./types.js";
7
+
8
+ export async function detectEnv(pi: ExtensionAPI, cwd: string): Promise<EnvInfo> {
9
+ let isGitRepo = false;
10
+ let branch = "";
11
+
12
+ try {
13
+ const result = await pi.exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 5000 });
14
+ isGitRepo = result.code === 0 && result.stdout.trim() === "true";
15
+ } catch {
16
+ // Not a git repo or git not installed
17
+ }
18
+
19
+ if (isGitRepo) {
20
+ try {
21
+ const result = await pi.exec("git", ["branch", "--show-current"], { cwd, timeout: 5000 });
22
+ branch = result.code === 0 ? result.stdout.trim() : "unknown";
23
+ } catch {
24
+ branch = "unknown";
25
+ }
26
+ }
27
+
28
+ return {
29
+ isGitRepo,
30
+ branch,
31
+ platform: process.platform,
32
+ };
33
+ }