@johnnywu/pi-subagents 1.0.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # 1.0.0 (2026-05-30)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * simplify subagent tool log rendering ([aea9cfe](https://github.com/jwu/pi-subagents/commit/aea9cfea9c53ea62273a5be41bd923b20522c833))
7
+ * **subagent:** move usage summary after markdown output in expanded mode ([8fecce0](https://github.com/jwu/pi-subagents/commit/8fecce0ae2d318e101e75e3484b7d3010fddcdb5))
8
+
9
+
10
+ ### Features
11
+
12
+ * add subagent extension core ([b524b4e](https://github.com/jwu/pi-subagents/commit/b524b4e1f8acb175360e526e99b4f52ca43ee460))
13
+ * improve subagent progress rendering ([92f40b6](https://github.com/jwu/pi-subagents/commit/92f40b60730d44b459970580ba675c1d020303dd))
14
+ * improve subagent result rendering ([699587f](https://github.com/jwu/pi-subagents/commit/699587fd9aed6cd5f59780e1d2ee21aeb8d1a304))
15
+ * **render:** 折叠态输出摘要改为原始文本截断,与 builtin 工具一致 ([18de536](https://github.com/jwu/pi-subagents/commit/18de5367b25f70035404911d31446bbabb340d1b))
16
+
17
+ # Changelog
18
+
19
+ ## [1.0.0] - 2026-05-29
20
+
21
+ ### Added
22
+ - Initial project scaffolding
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jwu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # pi-subagents
2
+
3
+ Sub-agents extension for [pi](https://github.com/badlogic/pi-mono) coding agent.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pi install npm:@johnnywu/pi-subagents
9
+ ```
10
+
11
+ ## Development
12
+
13
+ ```bash
14
+ # Install dependencies
15
+ bun install
16
+
17
+ # Run tests
18
+ bun test
19
+
20
+ # Type-check
21
+ bun run typecheck
22
+
23
+ # Format
24
+ bun run format
25
+
26
+ # Release (local, requires GH_TOKEN and NPM_TOKEN)
27
+ bun run release
28
+ ```
29
+
30
+ This project uses [semantic-release](https://semantic-release.gitbook.io) with [conventional commits](https://www.conventionalcommits.org/).
31
+
32
+ ## License
33
+
34
+ MIT
@@ -0,0 +1,180 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as os from 'node:os';
3
+ import * as path from 'node:path';
4
+
5
+ export type ThinkingLevel = 'off' | 'low' | 'medium' | 'high';
6
+ export type SystemPromptMode = 'replace' | 'append';
7
+ export type AgentSource = 'global' | 'project';
8
+
9
+ export interface AgentConfig {
10
+ name: string;
11
+ description?: string;
12
+ tools: string[];
13
+ model?: string;
14
+ thinking: ThinkingLevel;
15
+ systemPromptMode: SystemPromptMode;
16
+ allowedAgents?: string[];
17
+ maxDepth: number;
18
+ prompt: string;
19
+ source: AgentSource;
20
+ filePath: string;
21
+ }
22
+
23
+ export interface AgentDefinitionWarning {
24
+ filePath: string;
25
+ message: string;
26
+ }
27
+
28
+ export interface AgentDefinitionResult {
29
+ agents: AgentConfig[];
30
+ warnings: AgentDefinitionWarning[];
31
+ }
32
+
33
+ export interface AgentDefinitionFs {
34
+ listFiles(dir: string): Promise<string[]>;
35
+ readFile(filePath: string): Promise<string>;
36
+ }
37
+
38
+ export interface LoadAgentDefinitionsOptions {
39
+ cwd?: string;
40
+ globalDir?: string;
41
+ projectDir?: string;
42
+ fs?: AgentDefinitionFs;
43
+ }
44
+
45
+ const defaultFs: AgentDefinitionFs = {
46
+ async listFiles(dir) {
47
+ try {
48
+ const entries = await fs.readdir(dir, { withFileTypes: true });
49
+ return entries
50
+ .filter((entry) => entry.isFile() || entry.isSymbolicLink())
51
+ .map((entry) => path.join(dir, entry.name))
52
+ .sort();
53
+ } catch {
54
+ return [];
55
+ }
56
+ },
57
+ readFile(filePath) {
58
+ return fs.readFile(filePath, 'utf8');
59
+ },
60
+ };
61
+
62
+ export function defaultGlobalAgentsDir(): string {
63
+ return path.join(os.homedir(), '.pi', 'agent', 'agents');
64
+ }
65
+
66
+ export function defaultProjectAgentsDir(cwd = process.cwd()): string {
67
+ return path.join(cwd, '.pi', 'agents');
68
+ }
69
+
70
+ function splitCsv(value: string | undefined): string[] {
71
+ return (value ?? '')
72
+ .split(',')
73
+ .map((item) => item.trim())
74
+ .filter(Boolean);
75
+ }
76
+
77
+ function parseFrontmatter(content: string): { data: Record<string, string>; body: string } {
78
+ if (!content.startsWith('---\n')) throw new Error('missing frontmatter');
79
+ const end = content.indexOf('\n---', 4);
80
+ if (end === -1) throw new Error('missing frontmatter terminator');
81
+
82
+ const rawFrontmatter = content.slice(4, end);
83
+ const body = content.slice(end + '\n---'.length).replace(/^\n/, '');
84
+ const data: Record<string, string> = {};
85
+
86
+ for (const line of rawFrontmatter.split('\n')) {
87
+ const trimmed = line.trim();
88
+ if (!trimmed || trimmed.startsWith('#')) continue;
89
+ const separator = trimmed.indexOf(':');
90
+ if (separator === -1) throw new Error(`invalid frontmatter line: ${line}`);
91
+ const key = trimmed.slice(0, separator).trim();
92
+ const value = trimmed.slice(separator + 1).trim();
93
+ if (!key) throw new Error(`invalid frontmatter key: ${line}`);
94
+ data[key] = value.replace(/^['"]|['"]$/g, '');
95
+ }
96
+
97
+ return { data, body };
98
+ }
99
+
100
+ function parseAgentFile(content: string, filePath: string, source: AgentSource): AgentConfig {
101
+ const { data, body } = parseFrontmatter(content);
102
+ if (!data.name) throw new Error('missing required field: name');
103
+
104
+ const thinking = (data.thinking ?? 'off') as ThinkingLevel;
105
+ if (!['off', 'low', 'medium', 'high'].includes(thinking)) {
106
+ throw new Error(`invalid thinking: ${data.thinking}`);
107
+ }
108
+
109
+ const systemPromptMode = (data.systemPrompt ?? 'replace') as SystemPromptMode;
110
+ if (!['replace', 'append'].includes(systemPromptMode)) {
111
+ throw new Error(`invalid systemPrompt: ${data.systemPrompt}`);
112
+ }
113
+
114
+ const maxDepth = data.maxDepth === undefined ? 10 : Number(data.maxDepth);
115
+ if (!Number.isInteger(maxDepth) || maxDepth < 0) {
116
+ throw new Error(`invalid maxDepth: ${data.maxDepth}`);
117
+ }
118
+
119
+ const allowedAgents = splitCsv(data.allowedAgents);
120
+
121
+ return {
122
+ name: data.name,
123
+ description: data.description,
124
+ tools: splitCsv(data.tools),
125
+ model: data.model || undefined,
126
+ thinking,
127
+ systemPromptMode,
128
+ allowedAgents: allowedAgents.length > 0 ? allowedAgents : undefined,
129
+ maxDepth,
130
+ prompt: body,
131
+ source,
132
+ filePath,
133
+ };
134
+ }
135
+
136
+ async function loadDirectory(
137
+ dir: string,
138
+ source: AgentSource,
139
+ fileSystem: AgentDefinitionFs,
140
+ warnings: AgentDefinitionWarning[],
141
+ ): Promise<AgentConfig[]> {
142
+ const agents: AgentConfig[] = [];
143
+ const seen = new Set<string>();
144
+
145
+ for (const filePath of await fileSystem.listFiles(dir)) {
146
+ if (!filePath.endsWith('.md')) continue;
147
+
148
+ try {
149
+ const agent = parseAgentFile(await fileSystem.readFile(filePath), filePath, source);
150
+ if (seen.has(agent.name)) continue;
151
+ seen.add(agent.name);
152
+ agents.push(agent);
153
+ } catch (error) {
154
+ warnings.push({
155
+ filePath,
156
+ message: error instanceof Error ? error.message : String(error),
157
+ });
158
+ }
159
+ }
160
+
161
+ return agents;
162
+ }
163
+
164
+ export async function loadAgentDefinitions(
165
+ options: LoadAgentDefinitionsOptions = {},
166
+ ): Promise<AgentDefinitionResult> {
167
+ const fileSystem = options.fs ?? defaultFs;
168
+ const globalDir = options.globalDir ?? defaultGlobalAgentsDir();
169
+ const projectDir = options.projectDir ?? defaultProjectAgentsDir(options.cwd);
170
+ const warnings: AgentDefinitionWarning[] = [];
171
+
172
+ const globalAgents = await loadDirectory(globalDir, 'global', fileSystem, warnings);
173
+ const projectAgents = await loadDirectory(projectDir, 'project', fileSystem, warnings);
174
+
175
+ const byName = new Map<string, AgentConfig>();
176
+ for (const agent of globalAgents) byName.set(agent.name, agent);
177
+ for (const agent of projectAgents) byName.set(agent.name, agent);
178
+
179
+ return { agents: [...byName.values()], warnings };
180
+ }
@@ -0,0 +1,13 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { loadAgentDefinitions } from './agent-loader.ts';
3
+ import { registerSubagentTool } from './subagent-tool.ts';
4
+
5
+ export default async function (pi: ExtensionAPI) {
6
+ const result = await loadAgentDefinitions({ cwd: process.cwd() });
7
+
8
+ for (const warning of result.warnings) {
9
+ console.warn(`[pi-subagents] skipped ${warning.filePath}: ${warning.message}`);
10
+ }
11
+
12
+ registerSubagentTool(pi, { agents: result.agents });
13
+ }