@leing2021/super-pi 0.22.1 → 0.23.1

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 (117) hide show
  1. package/README.md +66 -293
  2. package/extensions/ce-core/index.ts +276 -48
  3. package/extensions/ce-core/tools/parallel-subagent.ts +3 -3
  4. package/extensions/ce-core/tools/subagent.ts +2 -2
  5. package/package.json +4 -20
  6. package/rules/common/naming.md +154 -0
  7. package/skills/01-brainstorm/SKILL.md +42 -79
  8. package/skills/01-brainstorm/references/ce-brainstorm-mode.md +47 -0
  9. package/skills/02-plan/SKILL.md +43 -61
  10. package/skills/02-plan/references/solution-search.md +46 -0
  11. package/skills/03-work/SKILL.md +34 -52
  12. package/skills/03-work/references/completion-report.md +51 -0
  13. package/skills/04-review/SKILL.md +44 -51
  14. package/skills/04-review/references/solution-search.md +46 -0
  15. package/skills/06-next/SKILL.md +35 -20
  16. package/skills/06-next/references/recommendation-logic.md +47 -2
  17. package/skills/07-worktree/SKILL.md +21 -20
  18. package/skills/08-help/SKILL.md +46 -0
  19. package/skills/08-help/references/workflow-sequence.md +135 -0
  20. package/skills/references/language-detection.md +44 -0
  21. package/LICENSE +0 -21
  22. package/THIRD-PARTY-NOTICES.md +0 -35
  23. package/extensions/subagent/__tests__/async-job-tracker.test.ts +0 -21
  24. package/extensions/subagent/__tests__/execution-activity.test.ts +0 -15
  25. package/extensions/subagent/__tests__/parallel-render-stress.test.ts +0 -82
  26. package/extensions/subagent/__tests__/render-dedup.test.ts +0 -98
  27. package/extensions/subagent/__tests__/render-widget.test.ts +0 -28
  28. package/extensions/subagent/__tests__/throttle.test.ts +0 -90
  29. package/extensions/subagent/agent-management.ts +0 -596
  30. package/extensions/subagent/agent-manager-chain-detail.ts +0 -163
  31. package/extensions/subagent/agent-manager-detail.ts +0 -232
  32. package/extensions/subagent/agent-manager-edit.ts +0 -391
  33. package/extensions/subagent/agent-manager-list.ts +0 -279
  34. package/extensions/subagent/agent-manager-parallel.ts +0 -305
  35. package/extensions/subagent/agent-manager.ts +0 -706
  36. package/extensions/subagent/agent-scope.ts +0 -9
  37. package/extensions/subagent/agent-selection.ts +0 -26
  38. package/extensions/subagent/agent-serializer.ts +0 -124
  39. package/extensions/subagent/agent-templates.ts +0 -63
  40. package/extensions/subagent/agents/context-builder.md +0 -37
  41. package/extensions/subagent/agents/delegate.md +0 -9
  42. package/extensions/subagent/agents/oracle.md +0 -73
  43. package/extensions/subagent/agents/planner.md +0 -52
  44. package/extensions/subagent/agents/researcher.md +0 -50
  45. package/extensions/subagent/agents/reviewer.md +0 -38
  46. package/extensions/subagent/agents/scout.md +0 -48
  47. package/extensions/subagent/agents/worker.md +0 -52
  48. package/extensions/subagent/agents.ts +0 -762
  49. package/extensions/subagent/artifacts.ts +0 -101
  50. package/extensions/subagent/async-execution.ts +0 -521
  51. package/extensions/subagent/async-job-tracker.ts +0 -240
  52. package/extensions/subagent/async-status.ts +0 -242
  53. package/extensions/subagent/chain-clarify.ts +0 -1365
  54. package/extensions/subagent/chain-execution.ts +0 -854
  55. package/extensions/subagent/chain-serializer.ts +0 -127
  56. package/extensions/subagent/completion-dedupe.ts +0 -66
  57. package/extensions/subagent/doctor.ts +0 -201
  58. package/extensions/subagent/execution.ts +0 -748
  59. package/extensions/subagent/file-coalescer.ts +0 -43
  60. package/extensions/subagent/fork-context.ts +0 -64
  61. package/extensions/subagent/formatters.ts +0 -123
  62. package/extensions/subagent/frontmatter.ts +0 -32
  63. package/extensions/subagent/index.ts +0 -586
  64. package/extensions/subagent/intercom-bridge.ts +0 -241
  65. package/extensions/subagent/jsonl-writer.ts +0 -84
  66. package/extensions/subagent/model-fallback.ts +0 -109
  67. package/extensions/subagent/notify.ts +0 -111
  68. package/extensions/subagent/parallel-utils.ts +0 -109
  69. package/extensions/subagent/pi-args.ts +0 -139
  70. package/extensions/subagent/pi-spawn.ts +0 -101
  71. package/extensions/subagent/post-exit-stdio-guard.ts +0 -88
  72. package/extensions/subagent/prompt-template-bridge.ts +0 -400
  73. package/extensions/subagent/prompts/gather-context-and-clarify.md +0 -13
  74. package/extensions/subagent/prompts/parallel-cleanup.md +0 -42
  75. package/extensions/subagent/prompts/parallel-research.md +0 -50
  76. package/extensions/subagent/prompts/parallel-review.md +0 -40
  77. package/extensions/subagent/render-helpers.ts +0 -83
  78. package/extensions/subagent/render.ts +0 -908
  79. package/extensions/subagent/result-intercom.ts +0 -238
  80. package/extensions/subagent/result-watcher.ts +0 -172
  81. package/extensions/subagent/run-history.ts +0 -58
  82. package/extensions/subagent/run-status.ts +0 -137
  83. package/extensions/subagent/schemas.ts +0 -165
  84. package/extensions/subagent/session-tokens.ts +0 -51
  85. package/extensions/subagent/settings.ts +0 -368
  86. package/extensions/subagent/single-output.ts +0 -98
  87. package/extensions/subagent/skills.ts +0 -627
  88. package/extensions/subagent/slash-bridge.ts +0 -177
  89. package/extensions/subagent/slash-commands.ts +0 -304
  90. package/extensions/subagent/slash-live-state.ts +0 -295
  91. package/extensions/subagent/subagent-control.ts +0 -151
  92. package/extensions/subagent/subagent-executor.ts +0 -1915
  93. package/extensions/subagent/subagent-prompt-runtime.ts +0 -76
  94. package/extensions/subagent/subagent-runner.ts +0 -1471
  95. package/extensions/subagent/subagents-status.ts +0 -473
  96. package/extensions/subagent/text-editor.ts +0 -273
  97. package/extensions/subagent/throttle.ts +0 -77
  98. package/extensions/subagent/top-level-async.ts +0 -16
  99. package/extensions/subagent/types.ts +0 -624
  100. package/extensions/subagent/utils.ts +0 -457
  101. package/extensions/subagent/worktree.ts +0 -580
  102. package/extensions/super-pi-extension/agents/ce-oracle.md +0 -109
  103. package/extensions/super-pi-extension/agents/ce-planner.md +0 -116
  104. package/extensions/super-pi-extension/agents/ce-reviewer.md +0 -99
  105. package/extensions/super-pi-extension/agents/ce-scout.md +0 -80
  106. package/extensions/super-pi-extension/agents/ce-worker.md +0 -78
  107. package/extensions/super-pi-extension/chains/ce-parallel-review.chain.md +0 -34
  108. package/extensions/super-pi-extension/chains/ce-review-only.chain.md +0 -12
  109. package/extensions/super-pi-extension/chains/ce-standard.chain.md +0 -28
  110. package/extensions/super-pi-extension/index.ts +0 -129
  111. package/extensions/super-pi-extension/model-sync.ts +0 -204
  112. package/skills/08-status/SKILL.md +0 -41
  113. package/skills/08-status/references/artifact-locations.md +0 -10
  114. package/skills/09-help/SKILL.md +0 -37
  115. package/skills/09-help/references/workflow-sequence.md +0 -9
  116. package/skills/10-rules/SKILL.md +0 -76
  117. package/skills/pi-subagents/SKILL.md +0 -566
@@ -1,762 +0,0 @@
1
- // SPDX-FileCopyrightText: 2025 Nico Bailon
2
- // SPDX-License-Identifier: MIT
3
- // Source: https://github.com/nicobailon/pi-subagents
4
- /**
5
- * Agent discovery and configuration
6
- */
7
-
8
- import * as fs from "node:fs";
9
- import * as os from "node:os";
10
- import * as path from "node:path";
11
- import { fileURLToPath } from "node:url";
12
- import { KNOWN_FIELDS } from "./agent-serializer.ts";
13
- import { parseChain } from "./chain-serializer.ts";
14
- import { mergeAgentsForScope } from "./agent-selection.ts";
15
- import { parseFrontmatter } from "./frontmatter.ts";
16
-
17
- export type AgentScope = "user" | "project" | "both";
18
-
19
- export type AgentSource = "builtin" | "user" | "project";
20
- export type SystemPromptMode = "append" | "replace";
21
-
22
- export function defaultSystemPromptMode(name: string): SystemPromptMode {
23
- return name === "delegate" ? "append" : "replace";
24
- }
25
-
26
- export function defaultInheritProjectContext(name: string): boolean {
27
- return name === "delegate";
28
- }
29
-
30
- export function defaultInheritSkills(): boolean {
31
- return false;
32
- }
33
-
34
- export interface BuiltinAgentOverrideBase {
35
- model?: string;
36
- fallbackModels?: string[];
37
- thinking?: string;
38
- systemPromptMode: SystemPromptMode;
39
- inheritProjectContext: boolean;
40
- inheritSkills: boolean;
41
- disabled?: boolean;
42
- systemPrompt: string;
43
- skills?: string[];
44
- tools?: string[];
45
- mcpDirectTools?: string[];
46
- }
47
-
48
- export interface BuiltinAgentOverrideConfig {
49
- model?: string | false;
50
- fallbackModels?: string[] | false;
51
- thinking?: string | false;
52
- systemPromptMode?: SystemPromptMode;
53
- inheritProjectContext?: boolean;
54
- inheritSkills?: boolean;
55
- disabled?: boolean;
56
- systemPrompt?: string;
57
- skills?: string[] | false;
58
- tools?: string[] | false;
59
- }
60
-
61
- export interface BuiltinAgentOverrideInfo {
62
- scope: "user" | "project";
63
- path: string;
64
- base: BuiltinAgentOverrideBase;
65
- }
66
-
67
- export interface AgentConfig {
68
- name: string;
69
- description: string;
70
- tools?: string[];
71
- mcpDirectTools?: string[];
72
- model?: string;
73
- fallbackModels?: string[];
74
- thinking?: string;
75
- systemPromptMode: SystemPromptMode;
76
- inheritProjectContext: boolean;
77
- inheritSkills: boolean;
78
- systemPrompt: string;
79
- source: AgentSource;
80
- filePath: string;
81
- skills?: string[];
82
- extensions?: string[];
83
- output?: string;
84
- defaultReads?: string[];
85
- defaultProgress?: boolean;
86
- interactive?: boolean;
87
- maxSubagentDepth?: number;
88
- disabled?: boolean;
89
- extraFields?: Record<string, string>;
90
- override?: BuiltinAgentOverrideInfo;
91
- }
92
-
93
- interface SubagentSettings {
94
- overrides: Record<string, BuiltinAgentOverrideConfig>;
95
- disableBuiltins?: boolean;
96
- }
97
-
98
- const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {} };
99
-
100
- export interface ChainStepConfig {
101
- agent: string;
102
- task: string;
103
- output?: string | false;
104
- reads?: string[] | false;
105
- model?: string;
106
- skills?: string[] | false;
107
- progress?: boolean;
108
- }
109
-
110
- export interface ChainConfig {
111
- name: string;
112
- description: string;
113
- source: AgentSource;
114
- filePath: string;
115
- steps: ChainStepConfig[];
116
- extraFields?: Record<string, string>;
117
- }
118
-
119
- export interface AgentDiscoveryResult {
120
- agents: AgentConfig[];
121
- projectAgentsDir: string | null;
122
- }
123
-
124
- function splitToolList(rawTools: string[] | undefined): { tools?: string[]; mcpDirectTools?: string[] } {
125
- const mcpDirectTools: string[] = [];
126
- const tools: string[] = [];
127
- for (const tool of rawTools ?? []) {
128
- if (tool.startsWith("mcp:")) {
129
- mcpDirectTools.push(tool.slice(4));
130
- } else {
131
- tools.push(tool);
132
- }
133
- }
134
- return {
135
- ...(tools.length > 0 ? { tools } : {}),
136
- ...(mcpDirectTools.length > 0 ? { mcpDirectTools } : {}),
137
- };
138
- }
139
-
140
- function joinToolList(config: Pick<AgentConfig, "tools" | "mcpDirectTools">): string[] | undefined {
141
- const joined = [
142
- ...(config.tools ?? []),
143
- ...(config.mcpDirectTools ?? []).map((tool) => `mcp:${tool}`),
144
- ];
145
- return joined.length > 0 ? joined : undefined;
146
- }
147
-
148
- function arraysEqual(a: string[] | undefined, b: string[] | undefined): boolean {
149
- if (!a && !b) return true;
150
- if (!a || !b) return false;
151
- if (a.length !== b.length) return false;
152
- for (let i = 0; i < a.length; i++) {
153
- if (a[i] !== b[i]) return false;
154
- }
155
- return true;
156
- }
157
-
158
- function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
159
- return {
160
- model: agent.model,
161
- fallbackModels: agent.fallbackModels ? [...agent.fallbackModels] : undefined,
162
- thinking: agent.thinking,
163
- systemPromptMode: agent.systemPromptMode,
164
- inheritProjectContext: agent.inheritProjectContext,
165
- inheritSkills: agent.inheritSkills,
166
- disabled: agent.disabled,
167
- systemPrompt: agent.systemPrompt,
168
- skills: agent.skills ? [...agent.skills] : undefined,
169
- tools: agent.tools ? [...agent.tools] : undefined,
170
- mcpDirectTools: agent.mcpDirectTools ? [...agent.mcpDirectTools] : undefined,
171
- };
172
- }
173
-
174
- function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentOverrideConfig {
175
- return {
176
- ...(override.model !== undefined ? { model: override.model } : {}),
177
- ...(override.fallbackModels !== undefined
178
- ? { fallbackModels: override.fallbackModels === false ? false : [...override.fallbackModels] }
179
- : {}),
180
- ...(override.thinking !== undefined ? { thinking: override.thinking } : {}),
181
- ...(override.systemPromptMode !== undefined ? { systemPromptMode: override.systemPromptMode } : {}),
182
- ...(override.inheritProjectContext !== undefined ? { inheritProjectContext: override.inheritProjectContext } : {}),
183
- ...(override.inheritSkills !== undefined ? { inheritSkills: override.inheritSkills } : {}),
184
- ...(override.disabled !== undefined ? { disabled: override.disabled } : {}),
185
- ...(override.systemPrompt !== undefined ? { systemPrompt: override.systemPrompt } : {}),
186
- ...(override.skills !== undefined ? { skills: override.skills === false ? false : [...override.skills] } : {}),
187
- ...(override.tools !== undefined ? { tools: override.tools === false ? false : [...override.tools] } : {}),
188
- };
189
- }
190
-
191
- function findNearestProjectRoot(cwd: string): string | null {
192
- let currentDir = cwd;
193
- while (true) {
194
- if (isDirectory(path.join(currentDir, ".pi")) || isDirectory(path.join(currentDir, ".agents"))) {
195
- return currentDir;
196
- }
197
-
198
- const parentDir = path.dirname(currentDir);
199
- if (parentDir === currentDir) return null;
200
- currentDir = parentDir;
201
- }
202
- }
203
-
204
- export function getUserAgentSettingsPath(): string {
205
- return path.join(os.homedir(), ".pi", "agent", "settings.json");
206
- }
207
-
208
- export function getProjectAgentSettingsPath(cwd: string): string | null {
209
- const projectRoot = findNearestProjectRoot(cwd);
210
- return projectRoot ? path.join(projectRoot, ".pi", "settings.json") : null;
211
- }
212
-
213
- function readSettingsFileStrict(filePath: string): Record<string, unknown> {
214
- if (!fs.existsSync(filePath)) return {};
215
- let raw: string;
216
- try {
217
- raw = fs.readFileSync(filePath, "utf-8");
218
- } catch (error) {
219
- const message = error instanceof Error ? error.message : String(error);
220
- throw new Error(`Failed to read settings file '${filePath}': ${message}`, { cause: error });
221
- }
222
-
223
- let parsed: unknown;
224
- try {
225
- parsed = JSON.parse(raw);
226
- } catch (error) {
227
- const message = error instanceof Error ? error.message : String(error);
228
- throw new Error(`Failed to parse settings file '${filePath}': ${message}`, { cause: error });
229
- }
230
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
231
- throw new Error(`Settings file '${filePath}' must contain a JSON object.`);
232
- }
233
- return parsed as Record<string, unknown>;
234
- }
235
-
236
- function writeSettingsFile(filePath: string, settings: Record<string, unknown>): void {
237
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
238
- fs.writeFileSync(filePath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
239
- }
240
-
241
- function parseOverrideStringArrayOrFalse(
242
- value: unknown,
243
- meta: { filePath: string; name: string; field: string },
244
- ): string[] | false | undefined {
245
- if (value === undefined) return undefined;
246
- if (value === false) return false;
247
- if (!Array.isArray(value)) {
248
- throw new Error(`Builtin override '${meta.name}' in '${meta.filePath}' has invalid '${meta.field}'; expected an array of strings or false.`);
249
- }
250
-
251
- const items: string[] = [];
252
- for (const item of value) {
253
- if (typeof item !== "string") {
254
- throw new Error(`Builtin override '${meta.name}' in '${meta.filePath}' has invalid '${meta.field}'; expected an array of strings or false.`);
255
- }
256
- const trimmed = item.trim();
257
- if (trimmed) items.push(trimmed);
258
- }
259
- return items;
260
- }
261
-
262
- function parseBuiltinOverrideEntry(
263
- name: string,
264
- value: unknown,
265
- filePath: string,
266
- ): BuiltinAgentOverrideConfig | undefined {
267
- if (!value || typeof value !== "object" || Array.isArray(value)) {
268
- throw new Error(`Builtin override '${name}' in '${filePath}' must be an object.`);
269
- }
270
-
271
- const input = value as Record<string, unknown>;
272
- const override: BuiltinAgentOverrideConfig = {};
273
-
274
- if ("model" in input) {
275
- if (typeof input.model === "string" || input.model === false) override.model = input.model;
276
- else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'model'; expected a string or false.`);
277
- }
278
-
279
- if ("thinking" in input) {
280
- if (typeof input.thinking === "string" || input.thinking === false) override.thinking = input.thinking;
281
- else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'thinking'; expected a string or false.`);
282
- }
283
-
284
- if ("systemPromptMode" in input) {
285
- if (input.systemPromptMode === "append" || input.systemPromptMode === "replace") {
286
- override.systemPromptMode = input.systemPromptMode;
287
- } else {
288
- throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'systemPromptMode'; expected 'append' or 'replace'.`);
289
- }
290
- }
291
-
292
- if ("inheritProjectContext" in input) {
293
- if (typeof input.inheritProjectContext === "boolean") {
294
- override.inheritProjectContext = input.inheritProjectContext;
295
- } else {
296
- throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'inheritProjectContext'; expected a boolean.`);
297
- }
298
- }
299
-
300
- if ("inheritSkills" in input) {
301
- if (typeof input.inheritSkills === "boolean") {
302
- override.inheritSkills = input.inheritSkills;
303
- } else {
304
- throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'inheritSkills'; expected a boolean.`);
305
- }
306
- }
307
-
308
- if ("disabled" in input) {
309
- if (typeof input.disabled === "boolean") {
310
- override.disabled = input.disabled;
311
- } else {
312
- throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'disabled'; expected a boolean.`);
313
- }
314
- }
315
-
316
- if ("systemPrompt" in input) {
317
- if (typeof input.systemPrompt === "string") override.systemPrompt = input.systemPrompt;
318
- else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'systemPrompt'; expected a string.`);
319
- }
320
-
321
- const fallbackModels = parseOverrideStringArrayOrFalse(input.fallbackModels, { filePath, name, field: "fallbackModels" });
322
- if (fallbackModels !== undefined) override.fallbackModels = fallbackModels;
323
-
324
- const skills = parseOverrideStringArrayOrFalse(input.skills, { filePath, name, field: "skills" });
325
- if (skills !== undefined) override.skills = skills;
326
-
327
- const tools = parseOverrideStringArrayOrFalse(input.tools, { filePath, name, field: "tools" });
328
- if (tools !== undefined) override.tools = tools;
329
-
330
- return Object.keys(override).length > 0 ? override : undefined;
331
- }
332
-
333
- function readSubagentSettings(filePath: string | null): SubagentSettings {
334
- if (!filePath) return EMPTY_SUBAGENT_SETTINGS;
335
- const settings = readSettingsFileStrict(filePath);
336
- const subagents = settings.subagents;
337
- if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return EMPTY_SUBAGENT_SETTINGS;
338
-
339
- const subagentsObject = subagents as Record<string, unknown>;
340
- let disableBuiltins: boolean | undefined;
341
- if ("disableBuiltins" in subagentsObject) {
342
- if (typeof subagentsObject.disableBuiltins === "boolean") {
343
- disableBuiltins = subagentsObject.disableBuiltins;
344
- } else {
345
- throw new Error(`Subagent settings in '${filePath}' have invalid 'disableBuiltins'; expected a boolean.`);
346
- }
347
- }
348
-
349
- const parsed: Record<string, BuiltinAgentOverrideConfig> = {};
350
- const agentOverrides = subagentsObject.agentOverrides;
351
- if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) {
352
- return { overrides: parsed, disableBuiltins };
353
- }
354
- for (const [name, value] of Object.entries(agentOverrides)) {
355
- const override = parseBuiltinOverrideEntry(name, value, filePath);
356
- if (override) parsed[name] = override;
357
- }
358
- return { overrides: parsed, disableBuiltins };
359
- }
360
-
361
- function applyBuiltinOverride(
362
- agent: AgentConfig,
363
- override: BuiltinAgentOverrideConfig,
364
- meta: { scope: "user" | "project"; path: string },
365
- ): AgentConfig {
366
- const next: AgentConfig = {
367
- ...agent,
368
- override: { ...meta, base: cloneOverrideBase(agent) },
369
- };
370
-
371
- if (override.model !== undefined) next.model = override.model === false ? undefined : override.model;
372
- if (override.fallbackModels !== undefined) {
373
- next.fallbackModels = override.fallbackModels === false ? undefined : [...override.fallbackModels];
374
- }
375
- if (override.thinking !== undefined) next.thinking = override.thinking === false ? undefined : override.thinking;
376
- if (override.systemPromptMode !== undefined) next.systemPromptMode = override.systemPromptMode;
377
- if (override.inheritProjectContext !== undefined) next.inheritProjectContext = override.inheritProjectContext;
378
- if (override.inheritSkills !== undefined) next.inheritSkills = override.inheritSkills;
379
- if (override.disabled !== undefined) next.disabled = override.disabled;
380
- if (override.systemPrompt !== undefined) next.systemPrompt = override.systemPrompt;
381
- if (override.skills !== undefined) next.skills = override.skills === false ? undefined : [...override.skills];
382
- if (override.tools !== undefined) {
383
- const { tools, mcpDirectTools } = splitToolList(override.tools === false ? [] : override.tools);
384
- next.tools = tools;
385
- next.mcpDirectTools = mcpDirectTools;
386
- }
387
-
388
- return next;
389
- }
390
-
391
- function applyBuiltinOverrides(
392
- builtinAgents: AgentConfig[],
393
- userSettings: SubagentSettings,
394
- projectSettings: SubagentSettings,
395
- userSettingsPath: string,
396
- projectSettingsPath: string | null,
397
- ): AgentConfig[] {
398
- const projectBulkDisabled = projectSettings.disableBuiltins === true && projectSettingsPath !== null;
399
- const userBulkDisabled = projectSettings.disableBuiltins === undefined && userSettings.disableBuiltins === true;
400
-
401
- return builtinAgents.map((agent) => {
402
- const projectOverride = projectSettings.overrides[agent.name];
403
- if (projectOverride && projectSettingsPath) {
404
- return applyBuiltinOverride(agent, projectOverride, { scope: "project", path: projectSettingsPath });
405
- }
406
-
407
- if (projectBulkDisabled && projectSettingsPath) {
408
- return applyBuiltinOverride(agent, { disabled: true }, { scope: "project", path: projectSettingsPath });
409
- }
410
-
411
- const userOverride = userSettings.overrides[agent.name];
412
- if (userOverride) {
413
- return applyBuiltinOverride(agent, userOverride, { scope: "user", path: userSettingsPath });
414
- }
415
-
416
- if (userBulkDisabled) {
417
- return applyBuiltinOverride(agent, { disabled: true }, { scope: "user", path: userSettingsPath });
418
- }
419
-
420
- return agent;
421
- });
422
- }
423
-
424
- export function buildBuiltinOverrideConfig(
425
- base: BuiltinAgentOverrideBase,
426
- draft: Pick<AgentConfig, "model" | "fallbackModels" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritSkills" | "disabled" | "systemPrompt" | "skills" | "tools" | "mcpDirectTools">,
427
- ): BuiltinAgentOverrideConfig | undefined {
428
- const override: BuiltinAgentOverrideConfig = {};
429
-
430
- if (draft.model !== base.model) override.model = draft.model ?? false;
431
- if (!arraysEqual(draft.fallbackModels, base.fallbackModels)) override.fallbackModels = draft.fallbackModels ? [...draft.fallbackModels] : false;
432
- if (draft.thinking !== base.thinking) override.thinking = draft.thinking ?? false;
433
- if (draft.systemPromptMode !== base.systemPromptMode) override.systemPromptMode = draft.systemPromptMode;
434
- if (draft.inheritProjectContext !== base.inheritProjectContext) override.inheritProjectContext = draft.inheritProjectContext;
435
- if (draft.inheritSkills !== base.inheritSkills) override.inheritSkills = draft.inheritSkills;
436
- if (draft.disabled !== base.disabled) override.disabled = draft.disabled ?? false;
437
- if (draft.systemPrompt !== base.systemPrompt) override.systemPrompt = draft.systemPrompt;
438
- if (!arraysEqual(draft.skills, base.skills)) override.skills = draft.skills ? [...draft.skills] : false;
439
-
440
- const baseTools = joinToolList(base);
441
- const draftTools = joinToolList(draft);
442
- if (!arraysEqual(draftTools, baseTools)) override.tools = draftTools ? [...draftTools] : false;
443
-
444
- return Object.keys(override).length > 0 ? override : undefined;
445
- }
446
-
447
- export function saveBuiltinAgentOverride(
448
- cwd: string,
449
- name: string,
450
- scope: "user" | "project",
451
- override: BuiltinAgentOverrideConfig,
452
- ): string {
453
- const filePath = scope === "project" ? getProjectAgentSettingsPath(cwd) : getUserAgentSettingsPath();
454
- if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
455
-
456
- const settings = readSettingsFileStrict(filePath);
457
- const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
458
- ? { ...(settings.subagents as Record<string, unknown>) }
459
- : {};
460
- const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
461
- ? { ...(subagents.agentOverrides as Record<string, unknown>) }
462
- : {};
463
-
464
- agentOverrides[name] = cloneOverrideValue(override);
465
- subagents.agentOverrides = agentOverrides;
466
- settings.subagents = subagents;
467
- writeSettingsFile(filePath, settings);
468
- return filePath;
469
- }
470
-
471
- export function removeBuiltinAgentOverride(cwd: string, name: string, scope: "user" | "project"): string {
472
- const filePath = scope === "project" ? getProjectAgentSettingsPath(cwd) : getUserAgentSettingsPath();
473
- if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
474
- if (!fs.existsSync(filePath)) return filePath;
475
-
476
- const settings = readSettingsFileStrict(filePath);
477
- const subagents = settings.subagents;
478
- if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return filePath;
479
- const nextSubagents = { ...(subagents as Record<string, unknown>) };
480
- const agentOverrides = nextSubagents.agentOverrides;
481
- if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return filePath;
482
-
483
- const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
484
- delete nextOverrides[name];
485
- if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
486
- else delete nextSubagents.agentOverrides;
487
-
488
- if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
489
- else delete settings.subagents;
490
-
491
- writeSettingsFile(filePath, settings);
492
- return filePath;
493
- }
494
-
495
- function loadAgentsFromDir(dir: string, source: AgentSource): AgentConfig[] {
496
- const agents: AgentConfig[] = [];
497
-
498
- if (!fs.existsSync(dir)) {
499
- return agents;
500
- }
501
-
502
- let entries: fs.Dirent[];
503
- try {
504
- entries = fs.readdirSync(dir, { withFileTypes: true });
505
- } catch {
506
- return agents;
507
- }
508
-
509
- for (const entry of entries) {
510
- if (!entry.name.endsWith(".md")) continue;
511
- if (entry.name.endsWith(".chain.md")) continue;
512
- if (!entry.isFile() && !entry.isSymbolicLink()) continue;
513
-
514
- const filePath = path.join(dir, entry.name);
515
- let content: string;
516
- try {
517
- content = fs.readFileSync(filePath, "utf-8");
518
- } catch {
519
- continue;
520
- }
521
-
522
- const { frontmatter, body } = parseFrontmatter(content);
523
-
524
- if (!frontmatter.name || !frontmatter.description) {
525
- continue;
526
- }
527
-
528
- const rawTools = frontmatter.tools
529
- ?.split(",")
530
- .map((t) => t.trim())
531
- .filter(Boolean);
532
-
533
- const mcpDirectTools: string[] = [];
534
- const tools: string[] = [];
535
- if (rawTools) {
536
- for (const tool of rawTools) {
537
- if (tool.startsWith("mcp:")) {
538
- mcpDirectTools.push(tool.slice(4));
539
- } else {
540
- tools.push(tool);
541
- }
542
- }
543
- }
544
-
545
- const defaultReads = frontmatter.defaultReads
546
- ?.split(",")
547
- .map((f) => f.trim())
548
- .filter(Boolean);
549
-
550
- const skillStr = frontmatter.skill || frontmatter.skills;
551
- const skills = skillStr
552
- ?.split(",")
553
- .map((s) => s.trim())
554
- .filter(Boolean);
555
- const fallbackModels = frontmatter.fallbackModels
556
- ?.split(",")
557
- .map((model) => model.trim())
558
- .filter(Boolean);
559
- const systemPromptMode = frontmatter.systemPromptMode === "replace"
560
- ? "replace"
561
- : frontmatter.systemPromptMode === "append"
562
- ? "append"
563
- : defaultSystemPromptMode(frontmatter.name);
564
- const inheritProjectContext = frontmatter.inheritProjectContext === "true"
565
- ? true
566
- : frontmatter.inheritProjectContext === "false"
567
- ? false
568
- : defaultInheritProjectContext(frontmatter.name);
569
- const inheritSkills = frontmatter.inheritSkills === "true"
570
- ? true
571
- : frontmatter.inheritSkills === "false"
572
- ? false
573
- : defaultInheritSkills();
574
-
575
- let extensions: string[] | undefined;
576
- if (frontmatter.extensions !== undefined) {
577
- extensions = frontmatter.extensions
578
- .split(",")
579
- .map((e) => e.trim())
580
- .filter(Boolean);
581
- }
582
-
583
- const extraFields: Record<string, string> = {};
584
- for (const [key, value] of Object.entries(frontmatter)) {
585
- if (!KNOWN_FIELDS.has(key)) extraFields[key] = value;
586
- }
587
-
588
- const parsedMaxSubagentDepth = Number(frontmatter.maxSubagentDepth);
589
-
590
- agents.push({
591
- name: frontmatter.name,
592
- description: frontmatter.description,
593
- tools: tools.length > 0 ? tools : undefined,
594
- mcpDirectTools: mcpDirectTools.length > 0 ? mcpDirectTools : undefined,
595
- model: frontmatter.model,
596
- fallbackModels: fallbackModels && fallbackModels.length > 0 ? fallbackModels : undefined,
597
- thinking: frontmatter.thinking,
598
- systemPromptMode,
599
- inheritProjectContext,
600
- inheritSkills,
601
- systemPrompt: body,
602
- source,
603
- filePath,
604
- skills: skills && skills.length > 0 ? skills : undefined,
605
- extensions,
606
- output: frontmatter.output,
607
- defaultReads: defaultReads && defaultReads.length > 0 ? defaultReads : undefined,
608
- defaultProgress: frontmatter.defaultProgress === "true",
609
- interactive: frontmatter.interactive === "true",
610
- maxSubagentDepth:
611
- Number.isInteger(parsedMaxSubagentDepth) && parsedMaxSubagentDepth >= 0
612
- ? parsedMaxSubagentDepth
613
- : undefined,
614
- extraFields: Object.keys(extraFields).length > 0 ? extraFields : undefined,
615
- });
616
- }
617
-
618
- return agents;
619
- }
620
-
621
- function loadChainsFromDir(dir: string, source: AgentSource): ChainConfig[] {
622
- const chains: ChainConfig[] = [];
623
-
624
- if (!fs.existsSync(dir)) {
625
- return chains;
626
- }
627
-
628
- let entries: fs.Dirent[];
629
- try {
630
- entries = fs.readdirSync(dir, { withFileTypes: true });
631
- } catch {
632
- return chains;
633
- }
634
-
635
- for (const entry of entries) {
636
- if (!entry.name.endsWith(".chain.md")) continue;
637
- if (!entry.isFile() && !entry.isSymbolicLink()) continue;
638
-
639
- const filePath = path.join(dir, entry.name);
640
- let content: string;
641
- try {
642
- content = fs.readFileSync(filePath, "utf-8");
643
- } catch {
644
- continue;
645
- }
646
-
647
- try {
648
- chains.push(parseChain(content, source, filePath));
649
- } catch {
650
- continue;
651
- }
652
- }
653
-
654
- return chains;
655
- }
656
-
657
- function isDirectory(p: string): boolean {
658
- try {
659
- return fs.statSync(p).isDirectory();
660
- } catch {
661
- return false;
662
- }
663
- }
664
-
665
- function resolveNearestProjectAgentDirs(cwd: string): { readDirs: string[]; preferredDir: string | null } {
666
- const projectRoot = findNearestProjectRoot(cwd);
667
- if (!projectRoot) return { readDirs: [], preferredDir: null };
668
-
669
- const legacyDir = path.join(projectRoot, ".agents");
670
- const preferredDir = path.join(projectRoot, ".pi", "agents");
671
- const readDirs: string[] = [];
672
- if (isDirectory(legacyDir)) readDirs.push(legacyDir);
673
- if (isDirectory(preferredDir)) readDirs.push(preferredDir);
674
-
675
- return {
676
- readDirs,
677
- preferredDir,
678
- };
679
- }
680
- const BUILTIN_AGENTS_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "agents");
681
-
682
- export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryResult {
683
- const userDirOld = path.join(os.homedir(), ".pi", "agent", "agents");
684
- const userDirNew = path.join(os.homedir(), ".agents");
685
- const { readDirs: projectAgentDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(cwd);
686
- const userSettingsPath = getUserAgentSettingsPath();
687
- const projectSettingsPath = getProjectAgentSettingsPath(cwd);
688
- const userSettings = scope === "project" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(userSettingsPath);
689
- const projectSettings = scope === "user" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(projectSettingsPath);
690
-
691
- const builtinAgents = applyBuiltinOverrides(
692
- loadAgentsFromDir(BUILTIN_AGENTS_DIR, "builtin"),
693
- userSettings,
694
- projectSettings,
695
- userSettingsPath,
696
- projectSettingsPath,
697
- );
698
-
699
- const userAgentsOld = scope === "project" ? [] : loadAgentsFromDir(userDirOld, "user");
700
- const userAgentsNew = scope === "project" ? [] : loadAgentsFromDir(userDirNew, "user");
701
- const userAgents = [...userAgentsOld, ...userAgentsNew];
702
-
703
- const projectAgents = scope === "user" ? [] : projectAgentDirs.flatMap((dir) => loadAgentsFromDir(dir, "project"));
704
- const agents = mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents)
705
- .filter((agent) => agent.disabled !== true);
706
-
707
- return { agents, projectAgentsDir };
708
- }
709
-
710
- export function discoverAgentsAll(cwd: string): {
711
- builtin: AgentConfig[];
712
- user: AgentConfig[];
713
- project: AgentConfig[];
714
- chains: ChainConfig[];
715
- userDir: string;
716
- projectDir: string | null;
717
- userSettingsPath: string;
718
- projectSettingsPath: string | null;
719
- } {
720
- const userDirOld = path.join(os.homedir(), ".pi", "agent", "agents");
721
- const userDirNew = path.join(os.homedir(), ".agents");
722
- const { readDirs: projectDirs, preferredDir: projectDir } = resolveNearestProjectAgentDirs(cwd);
723
- const userSettingsPath = getUserAgentSettingsPath();
724
- const projectSettingsPath = getProjectAgentSettingsPath(cwd);
725
- const userSettings = readSubagentSettings(userSettingsPath);
726
- const projectSettings = readSubagentSettings(projectSettingsPath);
727
-
728
- const builtin = applyBuiltinOverrides(
729
- loadAgentsFromDir(BUILTIN_AGENTS_DIR, "builtin"),
730
- userSettings,
731
- projectSettings,
732
- userSettingsPath,
733
- projectSettingsPath,
734
- );
735
- const user = [
736
- ...loadAgentsFromDir(userDirOld, "user"),
737
- ...loadAgentsFromDir(userDirNew, "user"),
738
- ];
739
- const projectMap = new Map<string, AgentConfig>();
740
- for (const dir of projectDirs) {
741
- for (const agent of loadAgentsFromDir(dir, "project")) {
742
- projectMap.set(agent.name, agent);
743
- }
744
- }
745
- const project = Array.from(projectMap.values());
746
-
747
- const chainMap = new Map<string, ChainConfig>();
748
- for (const dir of projectDirs) {
749
- for (const chain of loadChainsFromDir(dir, "project")) {
750
- chainMap.set(chain.name, chain);
751
- }
752
- }
753
- const chains = [
754
- ...loadChainsFromDir(userDirOld, "user"),
755
- ...loadChainsFromDir(userDirNew, "user"),
756
- ...Array.from(chainMap.values()),
757
- ];
758
-
759
- const userDir = fs.existsSync(userDirNew) ? userDirNew : userDirOld;
760
-
761
- return { builtin, user, project, chains, userDir, projectDir, userSettingsPath, projectSettingsPath };
762
- }