oira666_pi-subagent 0.1.3 → 0.1.5

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Michael Jakl
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael Jakl
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 CHANGED
@@ -62,8 +62,12 @@ Three fallback agents ship with the extension (used when no user/project agents
62
62
  Create Markdown files with YAML frontmatter:
63
63
 
64
64
  - **User agents:** `~/.pi/agent/agents/*.md`
65
+ - **Env agents:** `$PI_CODING_AGENT_DIR/agents/*.md` *(when `PI_CODING_AGENT_DIR` is set)*
65
66
  - **Project agents:** `.pi/agents/*.md` *(may prompt for confirmation — see `PI_SUBAGENT_CONFIRM_PROJECT_AGENTS`)*
66
67
 
68
+ Agent discovery priority (highest wins on name collision): project > env > user.
69
+ Built-in agents are only used as a fallback when **all three** locations are empty.
70
+
67
71
  ```markdown
68
72
  ---
69
73
  name: writer
@@ -112,6 +116,315 @@ pi --no-subagent-prevent-cycles # allow cycles (not recommended)
112
116
  | `PI_SUBAGENT_MAX_PARALLEL_TASKS` | `16` | Max tasks per single call |
113
117
  | `PI_SUBAGENT_MAX_CONCURRENCY` | `8` | Max subagents running simultaneously |
114
118
 
119
+ ## Agent Discovery
120
+
121
+ | Env Var | Description |
122
+ | ----------------------- | ------------------------------------------------------------ |
123
+ | `PI_CODING_AGENT_DIR` | Base path for an additional agents directory (`$PI_CODING_AGENT_DIR/agents/*.md`). Agents here override user agents but are overridden by project agents. Built-in agents are only used when user, env, and project locations all yield zero agents. |
124
+
125
+ ## CLI Argument Proxying
126
+
127
+ All flags passed to the parent `pi` process are forwarded to subagent child processes, so they
128
+ inherit the same provider, API key, model, and other runtime settings. Flags the extension manages
129
+ itself are blocked from being forwarded.
130
+
131
+ **Always forwarded verbatim:**
132
+
133
+ | Flag(s) | Purpose |
134
+ | --- | --- |
135
+ | `--provider` | AI provider |
136
+ | `--api-key` | API key |
137
+ | `--system-prompt` | Base system prompt override |
138
+ | `--session-dir` | Session storage directory |
139
+ | `--models` | Model cycling list |
140
+ | `--skill`, `--no-skills`/`-ns` | Skill loading |
141
+ | `--prompt-template`, `--no-prompt-templates`/`-np` | Prompt templates |
142
+ | `--theme`, `--no-themes` | Themes |
143
+ | `--verbose` | Verbose startup output |
144
+ | Unknown/custom flags | Forwarded with heuristic value detection |
145
+
146
+ **Forwarded as fallback** (agent frontmatter overrides if set):
147
+
148
+ | Flag | Overridden by |
149
+ | --- | --- |
150
+ | `--model` | `model:` in agent frontmatter |
151
+ | `--thinking` | `thinking:` in agent frontmatter |
152
+ | `--tools` / `--no-tools` | `tools:` in agent frontmatter |
153
+
154
+ **Never forwarded** (managed by the extension itself):
155
+ `--mode`, `-p`/`--print`, `--session`/`--no-session`, `--continue`, `--resume`,
156
+ `--append-system-prompt`, `--offline`, `--extension`/`-e`, `--no-extensions`/`-ne`,
157
+ `--subagent-max-depth`, `--subagent-prevent-cycles`, `--export`, `--list-models`,
158
+ `--help`, `--version`.
159
+
160
+ ---
161
+
162
+ ## Programmatic Usage (JSON RPC)
163
+
164
+ When running `pi` programmatically with `--mode rpc` (or `--mode json`), the stream contains
165
+ `tool_result_end` events whenever the agent completes a `subagent` tool call. The `details` field
166
+ of these events carries the full stats for that delegation — including recursive usage and tool
167
+ call counts from all subagents in the tree.
168
+
169
+ ### Stream event shape
170
+
171
+ ```
172
+ tool_result_end
173
+ └── message
174
+ ├── role: "toolResult"
175
+ ├── toolName: "subagent"
176
+ ├── toolCallId: string
177
+ ├── isError: boolean
178
+ ├── content: [{ type: "text", text: "<final output>" }]
179
+ └── details: SubagentDetails
180
+ ```
181
+
182
+ ### `SubagentDetails` object
183
+
184
+ ```ts
185
+ interface SubagentDetails {
186
+ // Execution metadata
187
+ mode: "single" | "parallel"; // one task vs multiple parallel tasks
188
+ delegationMode: "spawn" | "fork"; // context mode used
189
+ projectAgentsDir: string | null; // path to .pi/agents/ dir if used
190
+
191
+ // Individual agent results (one per task)
192
+ results: SingleResult[];
193
+
194
+ // ── Stats summary (own + all descendants, recursively) ──────────────────
195
+ aggregatedUsage: UsageStats; // token counts and cost, full tree
196
+ aggregatedToolCalls: ToolCallCounts; // { toolName: callCount }, full tree
197
+
198
+ // ── Per-agent breakdown ──────────────────────────────────────────────────
199
+ usageTree: UsageTreeNode[]; // one root node per result
200
+ }
201
+
202
+ interface SingleResult {
203
+ agent: string; // agent name
204
+ agentSource: "user" | "project" | "builtin" | "unknown";
205
+ task: string; // task string passed to this agent
206
+ exitCode: number; // 0 = success, >0 = error, -1 = still running
207
+ messages: Message[]; // full conversation history of the subagent
208
+ stderr: string;
209
+ usage: UsageStats; // this agent's OWN token usage only
210
+ toolCalls: ToolCallCounts; // this agent's OWN tool calls only
211
+ model?: string;
212
+ stopReason?: string; // "end_turn" | "error" | "aborted" | ...
213
+ errorMessage?: string;
214
+ }
215
+
216
+ interface UsageStats {
217
+ input: number; // input tokens
218
+ output: number; // output tokens
219
+ cacheRead: number; // cache read tokens
220
+ cacheWrite: number; // cache write tokens
221
+ cost: number; // total cost in USD
222
+ contextTokens: number; // snapshot: last context window size (not summed in aggregates)
223
+ turns: number; // number of assistant turns
224
+ }
225
+
226
+ // toolName → call count, e.g. { "bash": 5, "read": 3, "subagent": 1 }
227
+ type ToolCallCounts = Record<string, number>;
228
+
229
+ interface UsageTreeNode {
230
+ agent: string;
231
+ task: string;
232
+ ownUsage: UsageStats; // only this agent's turns
233
+ ownToolCalls: ToolCallCounts; // only this agent's tool calls
234
+ aggregatedUsage: UsageStats; // ownUsage + all children recursively
235
+ aggregatedToolCalls: ToolCallCounts; // ownToolCalls + all children recursively
236
+ children: UsageTreeNode[]; // one node per nested subagent invocation
237
+ }
238
+ ```
239
+
240
+ ### Important notes on stats
241
+
242
+ - **`SingleResult.usage`** and **`SingleResult.toolCalls`** cover **only that one agent's own work** —
243
+ not its children. Children run in separate processes; their tokens never appear in the parent's usage.
244
+ - **`aggregatedUsage`** / **`aggregatedToolCalls`** on `SubagentDetails` (and on each `UsageTreeNode`)
245
+ are the correct totals to use when you want the cost or tool call count for an entire delegation
246
+ subtree.
247
+ - **`contextTokens`** is a point-in-time snapshot of the context window size at the last turn of that
248
+ agent. It is **not** summed in aggregated stats (it would be meaningless as a cross-process sum).
249
+ - **`toolCalls`** includes **all** tool calls an agent made, including the `"subagent"` call itself.
250
+ You can use the `"subagent"` count to see how many nested delegations an agent spawned.
251
+
252
+ ### Annotated example JSON
253
+
254
+ The scenario below: main agent delegates to `code-writer`, which does some file work and then
255
+ delegates to `code-reviwer` before finishing.
256
+
257
+ ```json
258
+ {
259
+ "type": "tool_result_end",
260
+ "message": {
261
+ "role": "toolResult",
262
+ "toolName": "subagent",
263
+ "toolCallId": "toolu_01XYZ",
264
+ "isError": false,
265
+ "content": [
266
+ {
267
+ "type": "text",
268
+ "text": "Feature implemented and reviewed. Added validation logic in auth.ts and updated the test suite."
269
+ }
270
+ ],
271
+ "details": {
272
+ "mode": "single",
273
+ "delegationMode": "spawn",
274
+ "projectAgentsDir": null,
275
+
276
+ "aggregatedUsage": {
277
+ "input": 2180,
278
+ "output": 615,
279
+ "cacheRead": 940,
280
+ "cacheWrite": 120,
281
+ "cost": 0.0079,
282
+ "contextTokens": 0,
283
+ "turns": 3
284
+ },
285
+ "aggregatedToolCalls": {
286
+ "read": 3,
287
+ "bash": 2,
288
+ "edit": 1,
289
+ "subagent": 1
290
+ },
291
+
292
+ "usageTree": [
293
+ {
294
+ "agent": "code-writer",
295
+ "task": "Implement the auth feature and have it reviewed",
296
+ "ownUsage": {
297
+ "input": 1380,
298
+ "output": 365,
299
+ "cacheRead": 540,
300
+ "cacheWrite": 120,
301
+ "cost": 0.0058,
302
+ "contextTokens": 2840,
303
+ "turns": 2
304
+ },
305
+ "ownToolCalls": {
306
+ "read": 1,
307
+ "bash": 1,
308
+ "edit": 1,
309
+ "subagent": 1
310
+ },
311
+ "aggregatedUsage": {
312
+ "input": 2180,
313
+ "output": 615,
314
+ "cacheRead": 940,
315
+ "cacheWrite": 120,
316
+ "cost": 0.0079,
317
+ "contextTokens": 0,
318
+ "turns": 3
319
+ },
320
+ "aggregatedToolCalls": {
321
+ "read": 3,
322
+ "bash": 2,
323
+ "edit": 1,
324
+ "subagent": 1
325
+ },
326
+ "children": [
327
+ {
328
+ "agent": "code-reviwer",
329
+ "task": "Review the auth implementation in auth.ts",
330
+ "ownUsage": {
331
+ "input": 800,
332
+ "output": 250,
333
+ "cacheRead": 400,
334
+ "cacheWrite": 0,
335
+ "cost": 0.0021,
336
+ "contextTokens": 1450,
337
+ "turns": 1
338
+ },
339
+ "ownToolCalls": {
340
+ "read": 2,
341
+ "bash": 1
342
+ },
343
+ "aggregatedUsage": {
344
+ "input": 800,
345
+ "output": 250,
346
+ "cacheRead": 400,
347
+ "cacheWrite": 0,
348
+ "cost": 0.0021,
349
+ "contextTokens": 0,
350
+ "turns": 1
351
+ },
352
+ "aggregatedToolCalls": {
353
+ "read": 2,
354
+ "bash": 1
355
+ },
356
+ "children": []
357
+ }
358
+ ]
359
+ }
360
+ ],
361
+
362
+ "results": [
363
+ {
364
+ "agent": "code-writer",
365
+ "agentSource": "builtin",
366
+ "task": "Implement the auth feature and have it reviewed",
367
+ "exitCode": 0,
368
+ "stopReason": "end_turn",
369
+ "model": "claude-opus-4-5",
370
+ "stderr": "",
371
+ "usage": {
372
+ "input": 1380,
373
+ "output": 365,
374
+ "cacheRead": 540,
375
+ "cacheWrite": 120,
376
+ "cost": 0.0058,
377
+ "contextTokens": 2840,
378
+ "turns": 2
379
+ },
380
+ "toolCalls": {
381
+ "read": 1,
382
+ "bash": 1,
383
+ "edit": 1,
384
+ "subagent": 1
385
+ },
386
+ "messages": [
387
+ "... full conversation history of code-writer (includes the nested subagent tool_result) ..."
388
+ ]
389
+ }
390
+ ]
391
+ }
392
+ }
393
+ }
394
+ ```
395
+
396
+ ### Collecting stats across an entire session
397
+
398
+ If you are consuming the JSON stream programmatically and want to track the total cost and tool
399
+ usage across all subagent work in a session, listen for every `tool_result_end` event where
400
+ `message.toolName === "subagent"` and sum `message.details.aggregatedUsage` across them.
401
+
402
+ ```js
403
+ let totalCost = 0;
404
+ const totalToolCalls = {};
405
+
406
+ for await (const line of jsonLines) {
407
+ const event = JSON.parse(line);
408
+ if (
409
+ event.type === "tool_result_end" &&
410
+ event.message?.toolName === "subagent" &&
411
+ event.message?.details
412
+ ) {
413
+ const { aggregatedUsage, aggregatedToolCalls } = event.message.details;
414
+ totalCost += aggregatedUsage.cost;
415
+ for (const [tool, count] of Object.entries(aggregatedToolCalls)) {
416
+ totalToolCalls[tool] = (totalToolCalls[tool] ?? 0) + count;
417
+ }
418
+ }
419
+ }
420
+ ```
421
+
422
+ Note: if you also track the main agent's own usage from `message_end` events, make sure **not** to
423
+ double-count the subagent costs there — the main agent's own token usage (from its own `message_end`
424
+ events) does not include subagent work; they are always separate processes.
425
+
426
+ ---
427
+
115
428
  ## create-subagent Skill
116
429
 
117
430
  If you want the agent to **create new subagent definition files** for itself, install the [`create-subagent` skill](https://github.com/gee666/pi-subagent/tree/main/create-subagent). Once installed, the agent will know how to scaffold new `.md` agent files in the right location with correct frontmatter.
@@ -1,24 +1,24 @@
1
- ---
2
- name: code-architect
3
- description: Technical design agent for shaping implementations, APIs, module boundaries, and tradeoffs before coding. Use this agent for plans and architecture decisions.
4
- thinking: high
5
- tools: read,bash,grep,find,ls
6
- ---
7
-
8
- You are a senior software architect focused on practical design.
9
-
10
- Your job is to propose implementation approaches that balance simplicity,
11
- maintainability, extensibility, and delivery speed.
12
-
13
- Guidelines:
14
- - Start from the current codebase and constraints, not an idealized rewrite.
15
- - Prefer simple designs with clear ownership and minimal moving parts.
16
- - Call out tradeoffs, risks, migration concerns, and compatibility implications.
17
- - Recommend concrete module boundaries, data flow, and rollout steps when useful.
18
- - Avoid unnecessary abstraction.
19
-
20
- In your final response:
21
- - Present the recommended approach first.
22
- - Include 1-2 viable alternatives when relevant.
23
- - Explain why the recommendation fits this codebase.
24
- - Highlight the biggest implementation risks or unknowns.
1
+ ---
2
+ name: code-architect
3
+ description: Technical design agent for shaping implementations, APIs, module boundaries, and tradeoffs before coding. Use this agent for plans and architecture decisions.
4
+ thinking: high
5
+ tools: read,bash,grep,find,ls
6
+ ---
7
+
8
+ You are a senior software architect focused on practical design.
9
+
10
+ Your job is to propose implementation approaches that balance simplicity,
11
+ maintainability, extensibility, and delivery speed.
12
+
13
+ Guidelines:
14
+ - Start from the current codebase and constraints, not an idealized rewrite.
15
+ - Prefer simple designs with clear ownership and minimal moving parts.
16
+ - Call out tradeoffs, risks, migration concerns, and compatibility implications.
17
+ - Recommend concrete module boundaries, data flow, and rollout steps when useful.
18
+ - Avoid unnecessary abstraction.
19
+
20
+ In your final response:
21
+ - Present the recommended approach first.
22
+ - Include 1-2 viable alternatives when relevant.
23
+ - Explain why the recommendation fits this codebase.
24
+ - Highlight the biggest implementation risks or unknowns.
@@ -1,23 +1,23 @@
1
- ---
2
- name: code-reviwer
3
- description: Code review specialist for finding bugs, regressions, edge cases, and maintainability issues. Use this agent to review code, plans, or patches.
4
- thinking: high
5
- tools: read,bash,grep,find,ls
6
- ---
7
-
8
- You are a skeptical, detail-oriented code reviewer.
9
-
10
- Your goal is to identify the most important correctness, reliability, security,
11
- and maintainability issues in the provided code or plan.
12
-
13
- Guidelines:
14
- - Prioritize concrete issues over stylistic preferences.
15
- - Look for broken assumptions, missing edge-case handling, risky changes, and test gaps.
16
- - Prefer concise findings with clear reasoning and likely impact.
17
- - If the code looks good, say so explicitly instead of inventing problems.
18
- - Do not edit files; focus on analysis and recommendations.
19
-
20
- In your final response:
21
- - List findings ordered by severity.
22
- - Include file paths or symbols when possible.
23
- - If there are no meaningful issues, say "No significant issues found" and mention any residual risks briefly.
1
+ ---
2
+ name: code-reviwer
3
+ description: Code review specialist for finding bugs, regressions, edge cases, and maintainability issues. Use this agent to review code, plans, or patches.
4
+ thinking: high
5
+ tools: read,bash,grep,find,ls
6
+ ---
7
+
8
+ You are a skeptical, detail-oriented code reviewer.
9
+
10
+ Your goal is to identify the most important correctness, reliability, security,
11
+ and maintainability issues in the provided code or plan.
12
+
13
+ Guidelines:
14
+ - Prioritize concrete issues over stylistic preferences.
15
+ - Look for broken assumptions, missing edge-case handling, risky changes, and test gaps.
16
+ - Prefer concise findings with clear reasoning and likely impact.
17
+ - If the code looks good, say so explicitly instead of inventing problems.
18
+ - Do not edit files; focus on analysis and recommendations.
19
+
20
+ In your final response:
21
+ - List findings ordered by severity.
22
+ - Include file paths or symbols when possible.
23
+ - If there are no meaningful issues, say "No significant issues found" and mention any residual risks briefly.
@@ -1,18 +1,18 @@
1
- ---
2
- name: code-writer
3
- description: Focused implementation agent for writing and refactoring code with small, reliable diffs. Use this agent when you want code changes made directly.
4
- thinking: medium
5
- tools: read,bash,edit,write
6
- ---
7
-
8
- You are a pragmatic software engineer focused on implementation.
9
-
10
- Your job is to turn requirements into small, correct code changes.
11
-
12
- Guidelines:
13
- - Read the relevant files before editing.
14
- - Prefer minimal diffs that fit the existing style and architecture.
15
- - Preserve working behavior unless the task explicitly changes it.
16
- - When details are ambiguous, choose the simplest reasonable implementation and state your assumption.
17
- - If helpful, run targeted commands to inspect the codebase or validate your changes.
18
- - In your final response, summarize what you changed, note any assumptions, and mention any validation you performed.
1
+ ---
2
+ name: code-writer
3
+ description: Focused implementation agent for writing and refactoring code with small, reliable diffs. Use this agent when you want code changes made directly.
4
+ thinking: medium
5
+ tools: read,bash,edit,write
6
+ ---
7
+
8
+ You are a pragmatic software engineer focused on implementation.
9
+
10
+ Your job is to turn requirements into small, correct code changes.
11
+
12
+ Guidelines:
13
+ - Read the relevant files before editing.
14
+ - Prefer minimal diffs that fit the existing style and architecture.
15
+ - Preserve working behavior unless the task explicitly changes it.
16
+ - When details are ambiguous, choose the simplest reasonable implementation and state your assumption.
17
+ - If helpful, run targeted commands to inspect the codebase or validate your changes.
18
+ - In your final response, summarize what you changed, note any assumptions, and mention any validation you performed.