@gotgenes/pi-subagents 17.5.0 → 18.0.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.
@@ -1,199 +0,0 @@
1
- /**
2
- * agent-config-editor.ts — Agent detail view with edit/delete/eject/disable/enable transitions.
3
- *
4
- * Extracted from agent-menu.ts to give each concern a single responsibility.
5
- * Receives dependencies via injection — no direct `node:fs` imports.
6
- */
7
-
8
- import { join } from "node:path";
9
-
10
- import type { AgentTypeRegistry } from "#src/config/agent-types";
11
- import type { AgentConfig } from "#src/types";
12
- import type { AgentFileOps } from "#src/ui/agent-file-ops";
13
- import { writeAgentFile } from "#src/ui/agent-file-writer";
14
- import type { MenuUI } from "#src/ui/agent-menu";
15
-
16
- // ---- Pure helpers ----
17
-
18
- /** Compute the menu option list for the agent detail view. */
19
- export function buildMenuOptions(
20
- cfg: { isDefault?: boolean; enabled?: boolean },
21
- file: string | undefined,
22
- ): string[] {
23
- const isDefault = cfg.isDefault === true;
24
- const disabled = cfg.enabled === false;
25
-
26
- if (disabled && file) {
27
- return isDefault
28
- ? ["Enable", "Edit", "Reset to default", "Delete", "Back"]
29
- : ["Enable", "Edit", "Delete", "Back"];
30
- }
31
- if (isDefault && !file) {
32
- return ["Eject (export as .md)", "Disable", "Back"];
33
- }
34
- if (isDefault && file) {
35
- return ["Edit", "Disable", "Reset to default", "Delete", "Back"];
36
- }
37
- return ["Edit", "Disable", "Delete", "Back"];
38
- }
39
-
40
- /** Build the `.md` file content (frontmatter + system prompt) for an ejected agent. */
41
- export function buildEjectContent(cfg: AgentConfig): string {
42
- const fmFields: string[] = [];
43
- fmFields.push(`description: ${cfg.description}`);
44
- if (cfg.displayName) fmFields.push(`display_name: ${cfg.displayName}`);
45
- fmFields.push(`tools: ${cfg.builtinToolNames?.join(", ") ?? "all"}`);
46
- if (cfg.model) fmFields.push(`model: ${cfg.model}`);
47
- if (cfg.thinking) fmFields.push(`thinking: ${cfg.thinking}`);
48
- if (cfg.maxTurns) fmFields.push(`max_turns: ${cfg.maxTurns}`);
49
- fmFields.push(`prompt_mode: ${cfg.promptMode}`);
50
- if (cfg.inheritContext) fmFields.push("inherit_context: true");
51
- if (cfg.runInBackground) fmFields.push("run_in_background: true");
52
- return `---\n${fmFields.join("\n")}\n---\n\n${cfg.systemPrompt}\n`;
53
- }
54
-
55
- // ---- Class ----
56
-
57
- export class AgentConfigEditor {
58
- constructor(
59
- private readonly fileOps: AgentFileOps,
60
- private readonly registry: AgentTypeRegistry,
61
- private readonly personalAgentsDir: string,
62
- private readonly projectAgentsDir: string,
63
- ) {}
64
-
65
- private agentDirs(): string[] {
66
- return [this.projectAgentsDir, this.personalAgentsDir];
67
- }
68
-
69
- async showAgentDetail(ui: MenuUI, name: string): Promise<void> {
70
- if (this.registry.resolveType(name) == null) {
71
- ui.notify(`Agent config not found for "${name}".`, "warning");
72
- return;
73
- }
74
- const cfg = this.registry.resolveAgentConfig(name);
75
- const file = this.fileOps.findAgentFile(name, this.agentDirs());
76
-
77
- const choice = await ui.select(name, buildMenuOptions(cfg, file));
78
- if (!choice || choice === "Back") return;
79
-
80
- if (choice === "Edit" && file) await this.handleEdit(ui, name, file);
81
- else if (choice === "Delete" && file) await this.handleDelete(ui, name, file);
82
- else if (choice === "Reset to default" && file)
83
- await this.handleReset(ui, name, file);
84
- else if (choice.startsWith("Eject")) await this.ejectAgent(ui, name, cfg);
85
- else if (choice === "Disable") await this.disableAgent(ui, name);
86
- else if (choice === "Enable") await this.enableAgent(ui, name);
87
- }
88
-
89
- private async handleEdit(ui: MenuUI, name: string, file: string): Promise<void> {
90
- const content = this.fileOps.read(file);
91
- if (content === undefined) return;
92
- const edited = await ui.editor(`Edit ${name}`, content);
93
- if (edited !== undefined && edited !== content) {
94
- this.fileOps.write(file, edited);
95
- this.registry.reload();
96
- ui.notify(`Updated ${file}`, "info");
97
- }
98
- }
99
-
100
- private async handleDelete(ui: MenuUI, name: string, file: string): Promise<void> {
101
- const confirmed = await ui.confirm(
102
- "Delete agent",
103
- `Delete ${name} (${file})?`,
104
- );
105
- if (confirmed) {
106
- this.fileOps.remove(file);
107
- this.registry.reload();
108
- ui.notify(`Deleted ${file}`, "info");
109
- }
110
- }
111
-
112
- private async handleReset(ui: MenuUI, name: string, file: string): Promise<void> {
113
- const confirmed = await ui.confirm(
114
- "Reset to default",
115
- `Delete override ${file} and restore embedded default?`,
116
- );
117
- if (confirmed) {
118
- this.fileOps.remove(file);
119
- this.registry.reload();
120
- ui.notify(`Restored default ${name}`, "info");
121
- }
122
- }
123
-
124
- private async ejectAgent(ui: MenuUI, name: string, cfg: AgentConfig): Promise<void> {
125
- const location = await ui.select("Choose location", [
126
- "Project (.pi/agents/)",
127
- `Personal (${this.personalAgentsDir})`,
128
- ]);
129
- if (!location) return;
130
-
131
- const targetDir = location.startsWith("Project")
132
- ? this.projectAgentsDir
133
- : this.personalAgentsDir;
134
-
135
- const targetPath = join(targetDir, `${name}.md`);
136
- await writeAgentFile(
137
- this.fileOps,
138
- ui,
139
- this.registry,
140
- targetPath,
141
- buildEjectContent(cfg),
142
- `Ejected ${name} to`,
143
- );
144
- }
145
-
146
- private async disableAgent(ui: MenuUI, name: string): Promise<void> {
147
- const file = this.fileOps.findAgentFile(name, this.agentDirs());
148
- if (file) {
149
- const content = this.fileOps.read(file);
150
- if (content?.includes("\nenabled: false\n")) {
151
- ui.notify(`${name} is already disabled.`, "info");
152
- return;
153
- }
154
- if (content) {
155
- const updated = content.replace(/^---\n/, "---\nenabled: false\n");
156
- this.fileOps.write(file, updated);
157
- this.registry.reload();
158
- ui.notify(`Disabled ${name} (${file})`, "info");
159
- }
160
- return;
161
- }
162
-
163
- const location = await ui.select("Choose location", [
164
- "Project (.pi/agents/)",
165
- `Personal (${this.personalAgentsDir})`,
166
- ]);
167
- if (!location) return;
168
-
169
- const targetDir = location.startsWith("Project")
170
- ? this.projectAgentsDir
171
- : this.personalAgentsDir;
172
-
173
- const targetPath = join(targetDir, `${name}.md`);
174
- this.fileOps.write(targetPath, "---\nenabled: false\n---\n");
175
- this.registry.reload();
176
- ui.notify(`Disabled ${name} (${targetPath})`, "info");
177
- }
178
-
179
- // eslint-disable-next-line @typescript-eslint/require-await
180
- private async enableAgent(ui: MenuUI, name: string): Promise<void> {
181
- const file = this.fileOps.findAgentFile(name, this.agentDirs());
182
- if (!file) return;
183
-
184
- const content = this.fileOps.read(file);
185
- if (!content) return;
186
-
187
- const updated = content.replace(/^(---\n)enabled: false\n/, "$1");
188
-
189
- if (updated.trim() === "---\n---" || updated.trim() === "---\n---\n") {
190
- this.fileOps.remove(file);
191
- this.registry.reload();
192
- ui.notify(`Enabled ${name} (removed ${file})`, "info");
193
- } else {
194
- this.fileOps.write(file, updated);
195
- this.registry.reload();
196
- ui.notify(`Enabled ${name} (${file})`, "info");
197
- }
198
- }
199
- }
@@ -1,233 +0,0 @@
1
- /**
2
- * agent-creation-wizard.ts — AI-generation and manual-form agent creation flows.
3
- *
4
- * Extracted from agent-menu.ts to give each concern a single responsibility.
5
- * Receives dependencies via injection — no direct `node:fs` imports.
6
- */
7
-
8
- import { join } from "node:path";
9
-
10
- import { BUILTIN_TOOL_NAMES } from "#src/config/agent-types";
11
- import type { ParentSnapshot } from "#src/lifecycle/parent-snapshot";
12
- import type { Subagent } from "#src/types";
13
- import type { AgentFileOps } from "#src/ui/agent-file-ops";
14
- import { writeAgentFile } from "#src/ui/agent-file-writer";
15
- import type { MenuUI } from "#src/ui/agent-menu";
16
-
17
- // ---- Deps interface ----
18
-
19
- /** Narrow manager interface for agent spawning (generate wizard). */
20
- export interface WizardManager {
21
- spawnAndWait: (
22
- parentSnapshot: ParentSnapshot,
23
- type: string,
24
- prompt: string,
25
- opts: { description: string; maxTurns: number },
26
- ) => Promise<Subagent>;
27
- }
28
-
29
- /** Narrow registry interface for reloading after creation. */
30
- export interface WizardRegistry {
31
- reload(): void;
32
- }
33
-
34
- // ---- Class ----
35
-
36
- export class AgentCreationWizard {
37
- constructor(
38
- private readonly fileOps: AgentFileOps,
39
- private readonly manager: WizardManager,
40
- private readonly registry: WizardRegistry,
41
- private readonly personalAgentsDir: string,
42
- private readonly projectAgentsDir: string,
43
- ) {}
44
-
45
- async showCreateWizard(ui: MenuUI, parentSnapshot: ParentSnapshot): Promise<void> {
46
- const location = await ui.select("Choose location", [
47
- "Project (.pi/agents/)",
48
- `Personal (${this.personalAgentsDir})`,
49
- ]);
50
- if (!location) return;
51
-
52
- const targetDir = location.startsWith("Project")
53
- ? this.projectAgentsDir
54
- : this.personalAgentsDir;
55
-
56
- const method = await ui.select("Creation method", [
57
- "Generate with Claude (recommended)",
58
- "Manual configuration",
59
- ]);
60
- if (!method) return;
61
-
62
- if (method.startsWith("Generate")) {
63
- await this.showGenerateWizard(ui, parentSnapshot, targetDir);
64
- } else {
65
- await this.showManualWizard(ui, targetDir);
66
- }
67
- }
68
-
69
- private async showGenerateWizard(
70
- ui: MenuUI,
71
- parentSnapshot: ParentSnapshot,
72
- targetDir: string,
73
- ): Promise<void> {
74
- const description = await ui.input("Describe what this agent should do");
75
- if (!description) return;
76
-
77
- const name = await ui.input("Agent name (filename, no spaces)");
78
- if (!name) return;
79
-
80
- this.fileOps.ensureDir(targetDir);
81
-
82
- const targetPath = join(targetDir, `${name}.md`);
83
- if (this.fileOps.exists(targetPath)) {
84
- const overwrite = await ui.confirm(
85
- "Overwrite",
86
- `${targetPath} already exists. Overwrite?`,
87
- );
88
- if (!overwrite) return;
89
- }
90
-
91
- ui.notify("Generating agent definition...", "info");
92
-
93
- const generatePrompt = `Create a custom pi sub-agent definition file based on this description: "${description}"
94
-
95
- Write a markdown file to: ${targetPath}
96
-
97
- The file format is a markdown file with YAML frontmatter and a system prompt body:
98
-
99
- \`\`\`markdown
100
- ---
101
- description: <one-line description shown in UI>
102
- tools: <comma-separated built-in tools: read, bash, edit, write, grep, find, ls. Use "none" for no tools. Omit for all tools>
103
- model: <optional model as "provider/modelId", e.g. "anthropic/claude-haiku-4-5-20251001". Omit to inherit parent model>
104
- thinking: <optional thinking level: off, minimal, low, medium, high, xhigh. Omit to inherit>
105
- max_turns: <optional max agentic turns. 0 or omit for unlimited (default)>
106
- prompt_mode: <"replace" (body IS the full system prompt) or "append" (body is appended to default prompt). Default: append>
107
- inherit_context: <true to fork parent conversation into agent so it sees chat history. Default: false>
108
- run_in_background: <true to run in background by default. Default: false>
109
- ---
110
-
111
- <system prompt body — instructions for the agent>
112
- \`\`\`
113
-
114
- Guidelines for choosing settings:
115
- - For read-only tasks (review, analysis): tools: read, bash, grep, find, ls
116
- - For code modification tasks: include edit, write
117
- - Use prompt_mode: append if the agent should keep the default system prompt and add specialization on top
118
- - Use prompt_mode: replace for fully custom agents with their own personality/instructions
119
- - Set inherit_context: true if the agent needs to know what was discussed in the parent conversation
120
- - Only include frontmatter fields that differ from defaults — omit fields where the default is fine
121
-
122
- Write the file using the write tool. Only write the file, nothing else.`;
123
-
124
- const record = await this.manager.spawnAndWait(
125
- parentSnapshot,
126
- "general-purpose",
127
- generatePrompt,
128
- {
129
- description: `Generate ${name} agent`,
130
- maxTurns: 5,
131
- },
132
- );
133
-
134
- if (record.status === "error") {
135
- ui.notify(`Generation failed: ${record.error}`, "warning");
136
- return;
137
- }
138
-
139
- this.registry.reload();
140
-
141
- if (this.fileOps.exists(targetPath)) {
142
- ui.notify(`Created ${targetPath}`, "info");
143
- } else {
144
- ui.notify(
145
- "Agent generation completed but file was not created. Check the agent output.",
146
- "warning",
147
- );
148
- }
149
- }
150
-
151
- private async showManualWizard(ui: MenuUI, targetDir: string): Promise<void> {
152
- const name = await ui.input("Agent name (filename, no spaces)");
153
- if (!name) return;
154
-
155
- const description = await ui.input("Description (one line)");
156
- if (!description) return;
157
-
158
- const toolChoice = await ui.select("Tools", [
159
- "all",
160
- "none",
161
- "read-only (read, bash, grep, find, ls)",
162
- "custom...",
163
- ]);
164
- if (!toolChoice) return;
165
-
166
- let tools: string;
167
- if (toolChoice === "all") {
168
- tools = BUILTIN_TOOL_NAMES.join(", ");
169
- } else if (toolChoice === "none") {
170
- tools = "none";
171
- } else if (toolChoice.startsWith("read-only")) {
172
- tools = "read, bash, grep, find, ls";
173
- } else {
174
- const customTools = await ui.input(
175
- "Tools (comma-separated)",
176
- BUILTIN_TOOL_NAMES.join(", "),
177
- );
178
- if (!customTools) return;
179
- tools = customTools;
180
- }
181
-
182
- const modelChoice = await ui.select("Model", [
183
- "inherit (parent model)",
184
- "haiku",
185
- "sonnet",
186
- "opus",
187
- "custom...",
188
- ]);
189
- if (!modelChoice) return;
190
-
191
- let modelLine = "";
192
- if (modelChoice === "haiku")
193
- modelLine = "\nmodel: anthropic/claude-haiku-4-5-20251001";
194
- else if (modelChoice === "sonnet")
195
- modelLine = "\nmodel: anthropic/claude-sonnet-4-6";
196
- else if (modelChoice === "opus")
197
- modelLine = "\nmodel: anthropic/claude-opus-4-6";
198
- else if (modelChoice === "custom...") {
199
- const customModel = await ui.input("Model (provider/modelId)");
200
- if (customModel) modelLine = `\nmodel: ${customModel}`;
201
- }
202
-
203
- const thinkingChoice = await ui.select("Thinking level", [
204
- "inherit",
205
- "off",
206
- "minimal",
207
- "low",
208
- "medium",
209
- "high",
210
- "xhigh",
211
- ]);
212
- if (!thinkingChoice) return;
213
-
214
- let thinkingLine = "";
215
- if (thinkingChoice !== "inherit") thinkingLine = `\nthinking: ${thinkingChoice}`;
216
-
217
- const systemPrompt = await ui.editor("System prompt", "");
218
- if (systemPrompt === undefined) return;
219
-
220
- const content = `---
221
- description: ${description}
222
- tools: ${tools}${modelLine}${thinkingLine}
223
- prompt_mode: replace
224
- ---
225
-
226
- ${systemPrompt}
227
- `;
228
-
229
- const targetPath = join(targetDir, `${name}.md`);
230
-
231
- await writeAgentFile(this.fileOps, ui, this.registry, targetPath, content, "Created");
232
- }
233
- }
@@ -1,59 +0,0 @@
1
- /**
2
- * agent-file-ops.ts — Filesystem abstraction for agent .md file operations.
3
- *
4
- * Decouples menu sub-modules from direct `node:fs` imports, making them
5
- * testable via plain stub objects without `vi.mock()`.
6
- */
7
-
8
- import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
9
- import { dirname, join } from "node:path";
10
-
11
- // ---- Interface ----
12
-
13
- /** Filesystem operations for agent `.md` files. */
14
- export interface AgentFileOps {
15
- exists(filePath: string): boolean;
16
- read(filePath: string): string | undefined;
17
- write(filePath: string, content: string): void;
18
- remove(filePath: string): void;
19
- ensureDir(dirPath: string): void;
20
- findAgentFile(name: string, dirs: string[]): string | undefined;
21
- }
22
-
23
- // ---- Production implementation ----
24
-
25
- /** Production implementation wrapping `node:fs` synchronous APIs. */
26
- export class FsAgentFileOps implements AgentFileOps {
27
- exists(filePath: string): boolean {
28
- return existsSync(filePath);
29
- }
30
-
31
- read(filePath: string): string | undefined {
32
- try {
33
- return readFileSync(filePath, "utf-8");
34
- } catch {
35
- return undefined;
36
- }
37
- }
38
-
39
- write(filePath: string, content: string): void {
40
- mkdirSync(dirname(filePath), { recursive: true });
41
- writeFileSync(filePath, content, "utf-8");
42
- }
43
-
44
- remove(filePath: string): void {
45
- unlinkSync(filePath);
46
- }
47
-
48
- ensureDir(dirPath: string): void {
49
- mkdirSync(dirPath, { recursive: true });
50
- }
51
-
52
- findAgentFile(name: string, dirs: string[]): string | undefined {
53
- for (const dir of dirs) {
54
- const p = join(dir, `${name}.md`);
55
- if (existsSync(p)) return p;
56
- }
57
- return undefined;
58
- }
59
- }
@@ -1,55 +0,0 @@
1
- /**
2
- * agent-file-writer.ts — Shared overwrite-guard + write + reload + notify helper.
3
- *
4
- * Extracted from AgentConfigEditor.ejectAgent and AgentCreationWizard.showManualWizard
5
- * to eliminate the duplicated 20-line pattern. Uses narrow interfaces (ISP) so callers
6
- * are not forced to depend on the full AgentFileOps or MenuUI shapes.
7
- */
8
-
9
- // ---- Narrow interfaces ----
10
-
11
- /** Minimal file operations needed by the overwrite-guard-and-write pattern. */
12
- export interface FileWriter {
13
- exists(filePath: string): boolean;
14
- write(filePath: string, content: string): void;
15
- }
16
-
17
- /** Minimal UI needed by the overwrite-guard-and-write pattern. */
18
- export interface WriterUI {
19
- confirm(title: string, message: string): Promise<boolean>;
20
- notify(message: string, level: "info" | "warning" | "error"): void;
21
- }
22
-
23
- /** Registry that can be reloaded after file changes. */
24
- export interface Reloadable {
25
- reload(): void;
26
- }
27
-
28
- // ---- Function ----
29
-
30
- /**
31
- * Write an agent `.md` file with an overwrite guard.
32
- *
33
- * If `targetPath` already exists, prompts the user for confirmation before writing.
34
- * On write: reloads the registry and notifies the user as `"${label} ${targetPath}"`.
35
- *
36
- * Returns `true` if the file was written, `false` if the user declined to overwrite.
37
- */
38
- export async function writeAgentFile(
39
- fileOps: FileWriter,
40
- ui: WriterUI,
41
- registry: Reloadable,
42
- targetPath: string,
43
- content: string,
44
- label: string,
45
- ): Promise<boolean> {
46
- if (fileOps.exists(targetPath)) {
47
- const overwrite = await ui.confirm("Overwrite", `${targetPath} already exists. Overwrite?`);
48
- if (!overwrite) return false;
49
- }
50
-
51
- fileOps.write(targetPath, content);
52
- registry.reload();
53
- ui.notify(`${label} ${targetPath}`, "info");
54
- return true;
55
- }