@mariozechner/pi-coding-agent 0.23.4 → 0.24.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 (104) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +20 -13
  3. package/dist/core/custom-tools/loader.d.ts.map +1 -1
  4. package/dist/core/custom-tools/loader.js +56 -6
  5. package/dist/core/custom-tools/loader.js.map +1 -1
  6. package/dist/core/custom-tools/types.d.ts +9 -1
  7. package/dist/core/custom-tools/types.d.ts.map +1 -1
  8. package/dist/core/custom-tools/types.js.map +1 -1
  9. package/dist/core/hooks/index.d.ts +2 -1
  10. package/dist/core/hooks/index.d.ts.map +1 -1
  11. package/dist/core/hooks/index.js +1 -0
  12. package/dist/core/hooks/index.js.map +1 -1
  13. package/dist/core/hooks/runner.d.ts.map +1 -1
  14. package/dist/core/hooks/runner.js +44 -4
  15. package/dist/core/hooks/runner.js.map +1 -1
  16. package/dist/core/hooks/tool-wrapper.d.ts.map +1 -1
  17. package/dist/core/hooks/tool-wrapper.js +5 -9
  18. package/dist/core/hooks/tool-wrapper.js.map +1 -1
  19. package/dist/core/hooks/types.d.ts +73 -11
  20. package/dist/core/hooks/types.d.ts.map +1 -1
  21. package/dist/core/hooks/types.js +22 -1
  22. package/dist/core/hooks/types.js.map +1 -1
  23. package/dist/core/skills.d.ts +18 -5
  24. package/dist/core/skills.d.ts.map +1 -1
  25. package/dist/core/skills.js +183 -72
  26. package/dist/core/skills.js.map +1 -1
  27. package/dist/core/slash-commands.d.ts.map +1 -1
  28. package/dist/core/slash-commands.js +2 -2
  29. package/dist/core/slash-commands.js.map +1 -1
  30. package/dist/core/system-prompt.d.ts.map +1 -1
  31. package/dist/core/system-prompt.js +2 -2
  32. package/dist/core/system-prompt.js.map +1 -1
  33. package/dist/core/tools/bash.d.ts +5 -0
  34. package/dist/core/tools/bash.d.ts.map +1 -1
  35. package/dist/core/tools/bash.js.map +1 -1
  36. package/dist/core/tools/find.d.ts +5 -0
  37. package/dist/core/tools/find.d.ts.map +1 -1
  38. package/dist/core/tools/find.js.map +1 -1
  39. package/dist/core/tools/grep.d.ts +6 -0
  40. package/dist/core/tools/grep.d.ts.map +1 -1
  41. package/dist/core/tools/grep.js.map +1 -1
  42. package/dist/core/tools/index.d.ts +6 -5
  43. package/dist/core/tools/index.d.ts.map +1 -1
  44. package/dist/core/tools/index.js.map +1 -1
  45. package/dist/core/tools/ls.d.ts +5 -0
  46. package/dist/core/tools/ls.d.ts.map +1 -1
  47. package/dist/core/tools/ls.js.map +1 -1
  48. package/dist/core/tools/read.d.ts +4 -0
  49. package/dist/core/tools/read.d.ts.map +1 -1
  50. package/dist/core/tools/read.js.map +1 -1
  51. package/dist/index.d.ts +5 -3
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +5 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/main.d.ts.map +1 -1
  56. package/dist/main.js +4 -0
  57. package/dist/main.js.map +1 -1
  58. package/dist/modes/interactive/components/custom-editor.d.ts +1 -0
  59. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  60. package/dist/modes/interactive/components/custom-editor.js +16 -7
  61. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  62. package/dist/modes/interactive/components/hook-input.d.ts.map +1 -1
  63. package/dist/modes/interactive/components/hook-input.js +2 -2
  64. package/dist/modes/interactive/components/hook-input.js.map +1 -1
  65. package/dist/modes/interactive/components/hook-selector.d.ts.map +1 -1
  66. package/dist/modes/interactive/components/hook-selector.js +2 -2
  67. package/dist/modes/interactive/components/hook-selector.js.map +1 -1
  68. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  69. package/dist/modes/interactive/components/model-selector.js +2 -2
  70. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  71. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  72. package/dist/modes/interactive/components/oauth-selector.js +2 -2
  73. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  74. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  75. package/dist/modes/interactive/components/session-selector.js +3 -3
  76. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  77. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  78. package/dist/modes/interactive/components/user-message-selector.js +3 -3
  79. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  80. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  81. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  82. package/dist/modes/interactive/interactive-mode.js +63 -1
  83. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  84. package/dist/modes/print-mode.d.ts.map +1 -1
  85. package/dist/modes/print-mode.js +10 -0
  86. package/dist/modes/print-mode.js.map +1 -1
  87. package/docs/custom-tools.md +43 -4
  88. package/docs/hooks.md +104 -5
  89. package/docs/skills.md +65 -24
  90. package/examples/custom-tools/README.md +18 -7
  91. package/examples/custom-tools/subagent/README.md +172 -0
  92. package/examples/custom-tools/subagent/agents/planner.md +37 -0
  93. package/examples/custom-tools/subagent/agents/reviewer.md +35 -0
  94. package/examples/custom-tools/subagent/agents/scout.md +50 -0
  95. package/examples/custom-tools/subagent/agents/worker.md +24 -0
  96. package/examples/custom-tools/subagent/agents.ts +157 -0
  97. package/examples/custom-tools/subagent/commands/implement-and-review.md +10 -0
  98. package/examples/custom-tools/subagent/commands/implement.md +10 -0
  99. package/examples/custom-tools/subagent/commands/scout-and-plan.md +9 -0
  100. package/examples/custom-tools/subagent/index.ts +772 -0
  101. package/package.json +4 -4
  102. /package/examples/custom-tools/{hello.ts → hello/index.ts} +0 -0
  103. /package/examples/custom-tools/{question.ts → question/index.ts} +0 -0
  104. /package/examples/custom-tools/{todo.ts → todo/index.ts} +0 -0
@@ -0,0 +1,772 @@
1
+ /**
2
+ * Subagent Tool - Delegate tasks to specialized agents
3
+ *
4
+ * Spawns a separate `pi` process for each subagent invocation,
5
+ * giving it an isolated context window.
6
+ *
7
+ * Supports three modes:
8
+ * - Single: { agent: "name", task: "..." }
9
+ * - Parallel: { tasks: [{ agent: "name", task: "..." }, ...] }
10
+ * - Chain: { chain: [{ agent: "name", task: "... {previous} ..." }, ...] }
11
+ *
12
+ * Uses JSON mode to capture structured output from subagents.
13
+ */
14
+
15
+ import { spawn } from "node:child_process";
16
+ import * as fs from "node:fs";
17
+ import * as os from "node:os";
18
+ import * as path from "node:path";
19
+ import { Type } from "@sinclair/typebox";
20
+ import type { AgentToolResult, Message } from "@mariozechner/pi-ai";
21
+ import { StringEnum } from "@mariozechner/pi-ai";
22
+ import { Container, Markdown, Spacer, Text } from "@mariozechner/pi-tui";
23
+ import { getMarkdownTheme, type CustomAgentTool, type CustomToolFactory, type ToolAPI } from "@mariozechner/pi-coding-agent";
24
+ import { type AgentConfig, type AgentScope, discoverAgents, formatAgentList } from "./agents.js";
25
+
26
+ const MAX_PARALLEL_TASKS = 8;
27
+ const MAX_CONCURRENCY = 4;
28
+ const MAX_AGENTS_IN_DESCRIPTION = 10;
29
+ const COLLAPSED_ITEM_COUNT = 10;
30
+
31
+ function formatTokens(count: number): string {
32
+ if (count < 1000) return count.toString();
33
+ if (count < 10000) return (count / 1000).toFixed(1) + "k";
34
+ if (count < 1000000) return Math.round(count / 1000) + "k";
35
+ return (count / 1000000).toFixed(1) + "M";
36
+ }
37
+
38
+ function formatUsageStats(usage: { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number; contextTokens?: number; turns?: number }, model?: string): string {
39
+ const parts: string[] = [];
40
+ if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
41
+ if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
42
+ if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
43
+ if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
44
+ if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
45
+ if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
46
+ if (usage.contextTokens && usage.contextTokens > 0) {
47
+ parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
48
+ }
49
+ if (model) parts.push(model);
50
+ return parts.join(" ");
51
+ }
52
+
53
+ function formatToolCall(toolName: string, args: Record<string, unknown>, themeFg: (color: any, text: string) => string): string {
54
+ const shortenPath = (p: string) => {
55
+ const home = os.homedir();
56
+ return p.startsWith(home) ? "~" + p.slice(home.length) : p;
57
+ };
58
+
59
+ switch (toolName) {
60
+ case "bash": {
61
+ const command = (args.command as string) || "...";
62
+ const preview = command.length > 60 ? command.slice(0, 60) + "..." : command;
63
+ return themeFg("muted", "$ ") + themeFg("toolOutput", preview);
64
+ }
65
+ case "read": {
66
+ const rawPath = (args.file_path || args.path || "...") as string;
67
+ const filePath = shortenPath(rawPath);
68
+ const offset = args.offset as number | undefined;
69
+ const limit = args.limit as number | undefined;
70
+ let text = themeFg("accent", filePath);
71
+ if (offset !== undefined || limit !== undefined) {
72
+ const startLine = offset ?? 1;
73
+ const endLine = limit !== undefined ? startLine + limit - 1 : "";
74
+ text += themeFg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`);
75
+ }
76
+ return themeFg("muted", "read ") + text;
77
+ }
78
+ case "write": {
79
+ const rawPath = (args.file_path || args.path || "...") as string;
80
+ const filePath = shortenPath(rawPath);
81
+ const content = (args.content || "") as string;
82
+ const lines = content.split("\n").length;
83
+ let text = themeFg("muted", "write ") + themeFg("accent", filePath);
84
+ if (lines > 1) text += themeFg("dim", ` (${lines} lines)`);
85
+ return text;
86
+ }
87
+ case "edit": {
88
+ const rawPath = (args.file_path || args.path || "...") as string;
89
+ return themeFg("muted", "edit ") + themeFg("accent", shortenPath(rawPath));
90
+ }
91
+ case "ls": {
92
+ const rawPath = (args.path || ".") as string;
93
+ return themeFg("muted", "ls ") + themeFg("accent", shortenPath(rawPath));
94
+ }
95
+ case "find": {
96
+ const pattern = (args.pattern || "*") as string;
97
+ const rawPath = (args.path || ".") as string;
98
+ return themeFg("muted", "find ") + themeFg("accent", pattern) + themeFg("dim", ` in ${shortenPath(rawPath)}`);
99
+ }
100
+ case "grep": {
101
+ const pattern = (args.pattern || "") as string;
102
+ const rawPath = (args.path || ".") as string;
103
+ return themeFg("muted", "grep ") + themeFg("accent", `/${pattern}/`) + themeFg("dim", ` in ${shortenPath(rawPath)}`);
104
+ }
105
+ default: {
106
+ const argsStr = JSON.stringify(args);
107
+ const preview = argsStr.length > 50 ? argsStr.slice(0, 50) + "..." : argsStr;
108
+ return themeFg("accent", toolName) + themeFg("dim", ` ${preview}`);
109
+ }
110
+ }
111
+ }
112
+
113
+ interface UsageStats {
114
+ input: number;
115
+ output: number;
116
+ cacheRead: number;
117
+ cacheWrite: number;
118
+ cost: number;
119
+ contextTokens: number;
120
+ turns: number;
121
+ }
122
+
123
+ interface SingleResult {
124
+ agent: string;
125
+ agentSource: "user" | "project" | "unknown";
126
+ task: string;
127
+ exitCode: number;
128
+ messages: Message[];
129
+ stderr: string;
130
+ usage: UsageStats;
131
+ model?: string;
132
+ stopReason?: string;
133
+ errorMessage?: string;
134
+ step?: number;
135
+ }
136
+
137
+ interface SubagentDetails {
138
+ mode: "single" | "parallel" | "chain";
139
+ agentScope: AgentScope;
140
+ projectAgentsDir: string | null;
141
+ results: SingleResult[];
142
+ }
143
+
144
+ function getFinalOutput(messages: Message[]): string {
145
+ for (let i = messages.length - 1; i >= 0; i--) {
146
+ const msg = messages[i];
147
+ if (msg.role === "assistant") {
148
+ for (const part of msg.content) {
149
+ if (part.type === "text") return part.text;
150
+ }
151
+ }
152
+ }
153
+ return "";
154
+ }
155
+
156
+ type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, any> };
157
+
158
+ function getDisplayItems(messages: Message[]): DisplayItem[] {
159
+ const items: DisplayItem[] = [];
160
+ for (const msg of messages) {
161
+ if (msg.role === "assistant") {
162
+ for (const part of msg.content) {
163
+ if (part.type === "text") items.push({ type: "text", text: part.text });
164
+ else if (part.type === "toolCall") items.push({ type: "toolCall", name: part.name, args: part.arguments });
165
+ }
166
+ }
167
+ }
168
+ return items;
169
+ }
170
+
171
+ async function mapWithConcurrencyLimit<TIn, TOut>(
172
+ items: TIn[],
173
+ concurrency: number,
174
+ fn: (item: TIn, index: number) => Promise<TOut>
175
+ ): Promise<TOut[]> {
176
+ if (items.length === 0) return [];
177
+ const limit = Math.max(1, Math.min(concurrency, items.length));
178
+ const results: TOut[] = new Array(items.length);
179
+ let nextIndex = 0;
180
+ const workers = new Array(limit).fill(null).map(async () => {
181
+ while (true) {
182
+ const current = nextIndex++;
183
+ if (current >= items.length) return;
184
+ results[current] = await fn(items[current], current);
185
+ }
186
+ });
187
+ await Promise.all(workers);
188
+ return results;
189
+ }
190
+
191
+ function writePromptToTempFile(agentName: string, prompt: string): { dir: string; filePath: string } {
192
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
193
+ const safeName = agentName.replace(/[^\w.-]+/g, "_");
194
+ const filePath = path.join(tmpDir, `prompt-${safeName}.md`);
195
+ fs.writeFileSync(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
196
+ return { dir: tmpDir, filePath };
197
+ }
198
+
199
+ type OnUpdateCallback = (partial: AgentToolResult<SubagentDetails>) => void;
200
+
201
+ async function runSingleAgent(
202
+ pi: ToolAPI,
203
+ agents: AgentConfig[],
204
+ agentName: string,
205
+ task: string,
206
+ step: number | undefined,
207
+ signal: AbortSignal | undefined,
208
+ onUpdate: OnUpdateCallback | undefined,
209
+ makeDetails: (results: SingleResult[]) => SubagentDetails
210
+ ): Promise<SingleResult> {
211
+ const agent = agents.find((a) => a.name === agentName);
212
+
213
+ if (!agent) {
214
+ return {
215
+ agent: agentName,
216
+ agentSource: "unknown",
217
+ task,
218
+ exitCode: 1,
219
+ messages: [],
220
+ stderr: `Unknown agent: ${agentName}`,
221
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
222
+ step,
223
+ };
224
+ }
225
+
226
+ const args: string[] = ["--mode", "json", "-p", "--no-session"];
227
+ if (agent.model) args.push("--model", agent.model);
228
+ if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
229
+
230
+ let tmpPromptDir: string | null = null;
231
+ let tmpPromptPath: string | null = null;
232
+
233
+ const currentResult: SingleResult = {
234
+ agent: agentName,
235
+ agentSource: agent.source,
236
+ task,
237
+ exitCode: 0,
238
+ messages: [],
239
+ stderr: "",
240
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
241
+ model: agent.model,
242
+ step,
243
+ };
244
+
245
+ const emitUpdate = () => {
246
+ if (onUpdate) {
247
+ onUpdate({
248
+ content: [{ type: "text", text: getFinalOutput(currentResult.messages) || "(running...)" }],
249
+ details: makeDetails([currentResult]),
250
+ });
251
+ }
252
+ };
253
+
254
+ try {
255
+ if (agent.systemPrompt.trim()) {
256
+ const tmp = writePromptToTempFile(agent.name, agent.systemPrompt);
257
+ tmpPromptDir = tmp.dir;
258
+ tmpPromptPath = tmp.filePath;
259
+ args.push("--append-system-prompt", tmpPromptPath);
260
+ }
261
+
262
+ args.push(`Task: ${task}`);
263
+ let wasAborted = false;
264
+
265
+ const exitCode = await new Promise<number>((resolve) => {
266
+ const proc = spawn("pi", args, { cwd: pi.cwd, shell: false, stdio: ["ignore", "pipe", "pipe"] });
267
+ let buffer = "";
268
+
269
+ const processLine = (line: string) => {
270
+ if (!line.trim()) return;
271
+ let event: any;
272
+ try { event = JSON.parse(line); } catch { return; }
273
+
274
+ if (event.type === "message_end" && event.message) {
275
+ const msg = event.message as Message;
276
+ currentResult.messages.push(msg);
277
+
278
+ if (msg.role === "assistant") {
279
+ currentResult.usage.turns++;
280
+ const usage = msg.usage;
281
+ if (usage) {
282
+ currentResult.usage.input += usage.input || 0;
283
+ currentResult.usage.output += usage.output || 0;
284
+ currentResult.usage.cacheRead += usage.cacheRead || 0;
285
+ currentResult.usage.cacheWrite += usage.cacheWrite || 0;
286
+ currentResult.usage.cost += usage.cost?.total || 0;
287
+ currentResult.usage.contextTokens = usage.totalTokens || 0;
288
+ }
289
+ if (!currentResult.model && msg.model) currentResult.model = msg.model;
290
+ if (msg.stopReason) currentResult.stopReason = msg.stopReason;
291
+ if (msg.errorMessage) currentResult.errorMessage = msg.errorMessage;
292
+ }
293
+ emitUpdate();
294
+ }
295
+
296
+ if (event.type === "tool_result_end" && event.message) {
297
+ currentResult.messages.push(event.message as Message);
298
+ emitUpdate();
299
+ }
300
+ };
301
+
302
+ proc.stdout.on("data", (data) => {
303
+ buffer += data.toString();
304
+ const lines = buffer.split("\n");
305
+ buffer = lines.pop() || "";
306
+ for (const line of lines) processLine(line);
307
+ });
308
+
309
+ proc.stderr.on("data", (data) => { currentResult.stderr += data.toString(); });
310
+
311
+ proc.on("close", (code) => {
312
+ if (buffer.trim()) processLine(buffer);
313
+ resolve(code ?? 0);
314
+ });
315
+
316
+ proc.on("error", () => { resolve(1); });
317
+
318
+ if (signal) {
319
+ const killProc = () => {
320
+ wasAborted = true;
321
+ proc.kill("SIGTERM");
322
+ setTimeout(() => { if (!proc.killed) proc.kill("SIGKILL"); }, 5000);
323
+ };
324
+ if (signal.aborted) killProc();
325
+ else signal.addEventListener("abort", killProc, { once: true });
326
+ }
327
+ });
328
+
329
+ currentResult.exitCode = exitCode;
330
+ if (wasAborted) throw new Error("Subagent was aborted");
331
+ return currentResult;
332
+ } finally {
333
+ if (tmpPromptPath) try { fs.unlinkSync(tmpPromptPath); } catch { /* ignore */ }
334
+ if (tmpPromptDir) try { fs.rmdirSync(tmpPromptDir); } catch { /* ignore */ }
335
+ }
336
+ }
337
+
338
+ const TaskItem = Type.Object({
339
+ agent: Type.String({ description: "Name of the agent to invoke" }),
340
+ task: Type.String({ description: "Task to delegate to the agent" }),
341
+ });
342
+
343
+ const ChainItem = Type.Object({
344
+ agent: Type.String({ description: "Name of the agent to invoke" }),
345
+ task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
346
+ });
347
+
348
+ const AgentScopeSchema = StringEnum(["user", "project", "both"] as const, {
349
+ description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
350
+ default: "user",
351
+ });
352
+
353
+ const SubagentParams = Type.Object({
354
+ agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })),
355
+ task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })),
356
+ tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
357
+ chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })),
358
+ agentScope: Type.Optional(AgentScopeSchema),
359
+ confirmProjectAgents: Type.Optional(Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true })),
360
+ });
361
+
362
+ const factory: CustomToolFactory = (pi) => {
363
+ const tool: CustomAgentTool<typeof SubagentParams, SubagentDetails> = {
364
+ name: "subagent",
365
+ label: "Subagent",
366
+ get description() {
367
+ const user = discoverAgents(pi.cwd, "user");
368
+ const project = discoverAgents(pi.cwd, "project");
369
+ const userList = formatAgentList(user.agents, MAX_AGENTS_IN_DESCRIPTION);
370
+ const projectList = formatAgentList(project.agents, MAX_AGENTS_IN_DESCRIPTION);
371
+ const userSuffix = userList.remaining > 0 ? `; ... and ${userList.remaining} more` : "";
372
+ const projectSuffix = projectList.remaining > 0 ? `; ... and ${projectList.remaining} more` : "";
373
+ const projectDirNote = project.projectAgentsDir ? ` (from ${project.projectAgentsDir})` : "";
374
+ return [
375
+ "Delegate tasks to specialized subagents with isolated context.",
376
+ "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).",
377
+ 'Default agent scope is "user" (from ~/.pi/agent/agents).',
378
+ 'To enable project-local agents in .pi/agents, set agentScope: "both" (or "project").',
379
+ `User agents: ${userList.text}${userSuffix}.`,
380
+ `Project agents${projectDirNote}: ${projectList.text}${projectSuffix}.`,
381
+ ].join(" ");
382
+ },
383
+ parameters: SubagentParams,
384
+
385
+ async execute(_toolCallId, params, signal, onUpdate) {
386
+ const agentScope: AgentScope = params.agentScope ?? "user";
387
+ const discovery = discoverAgents(pi.cwd, agentScope);
388
+ const agents = discovery.agents;
389
+ const confirmProjectAgents = params.confirmProjectAgents ?? true;
390
+
391
+ const hasChain = (params.chain?.length ?? 0) > 0;
392
+ const hasTasks = (params.tasks?.length ?? 0) > 0;
393
+ const hasSingle = Boolean(params.agent && params.task);
394
+ const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle);
395
+
396
+ const makeDetails = (mode: "single" | "parallel" | "chain") => (results: SingleResult[]): SubagentDetails => ({
397
+ mode, agentScope, projectAgentsDir: discovery.projectAgentsDir, results,
398
+ });
399
+
400
+ if (modeCount !== 1) {
401
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
402
+ return { content: [{ type: "text", text: `Invalid parameters. Provide exactly one mode.\nAvailable agents: ${available}` }], details: makeDetails("single")([]) };
403
+ }
404
+
405
+ if ((agentScope === "project" || agentScope === "both") && confirmProjectAgents && pi.hasUI) {
406
+ const requestedAgentNames = new Set<string>();
407
+ if (params.chain) for (const step of params.chain) requestedAgentNames.add(step.agent);
408
+ if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent);
409
+ if (params.agent) requestedAgentNames.add(params.agent);
410
+
411
+ const projectAgentsRequested = Array.from(requestedAgentNames)
412
+ .map((name) => agents.find((a) => a.name === name))
413
+ .filter((a): a is AgentConfig => a?.source === "project");
414
+
415
+ if (projectAgentsRequested.length > 0) {
416
+ const names = projectAgentsRequested.map((a) => a.name).join(", ");
417
+ const dir = discovery.projectAgentsDir ?? "(unknown)";
418
+ const ok = await pi.ui.confirm("Run project-local agents?", `Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`);
419
+ if (!ok) return { content: [{ type: "text", text: "Canceled: project-local agents not approved." }], details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]) };
420
+ }
421
+ }
422
+
423
+ if (params.chain && params.chain.length > 0) {
424
+ const results: SingleResult[] = [];
425
+ let previousOutput = "";
426
+
427
+ for (let i = 0; i < params.chain.length; i++) {
428
+ const step = params.chain[i];
429
+ const taskWithContext = step.task.replace(/\{previous\}/g, previousOutput);
430
+
431
+ // Create update callback that includes all previous results
432
+ const chainUpdate: OnUpdateCallback | undefined = onUpdate ? (partial) => {
433
+ // Combine completed results with current streaming result
434
+ const currentResult = partial.details?.results[0];
435
+ if (currentResult) {
436
+ const allResults = [...results, currentResult];
437
+ onUpdate({
438
+ content: partial.content,
439
+ details: makeDetails("chain")(allResults),
440
+ });
441
+ }
442
+ } : undefined;
443
+
444
+ const result = await runSingleAgent(pi, agents, step.agent, taskWithContext, i + 1, signal, chainUpdate, makeDetails("chain"));
445
+ results.push(result);
446
+
447
+ const isError = result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
448
+ if (isError) {
449
+ const errorMsg = result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
450
+ return { content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` }], details: makeDetails("chain")(results), isError: true };
451
+ }
452
+ previousOutput = getFinalOutput(result.messages);
453
+ }
454
+ return { content: [{ type: "text", text: getFinalOutput(results[results.length - 1].messages) || "(no output)" }], details: makeDetails("chain")(results) };
455
+ }
456
+
457
+ if (params.tasks && params.tasks.length > 0) {
458
+ if (params.tasks.length > MAX_PARALLEL_TASKS) return { content: [{ type: "text", text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.` }], details: makeDetails("parallel")([]) };
459
+
460
+ // Track all results for streaming updates
461
+ const allResults: SingleResult[] = new Array(params.tasks.length);
462
+
463
+ // Initialize placeholder results
464
+ for (let i = 0; i < params.tasks.length; i++) {
465
+ allResults[i] = {
466
+ agent: params.tasks[i].agent,
467
+ agentSource: "unknown",
468
+ task: params.tasks[i].task,
469
+ exitCode: -1, // -1 = still running
470
+ messages: [],
471
+ stderr: "",
472
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
473
+ };
474
+ }
475
+
476
+ const emitParallelUpdate = () => {
477
+ if (onUpdate) {
478
+ const running = allResults.filter(r => r.exitCode === -1).length;
479
+ const done = allResults.filter(r => r.exitCode !== -1).length;
480
+ onUpdate({
481
+ content: [{ type: "text", text: `Parallel: ${done}/${allResults.length} done, ${running} running...` }],
482
+ details: makeDetails("parallel")([...allResults]),
483
+ });
484
+ }
485
+ };
486
+
487
+ const results = await mapWithConcurrencyLimit(params.tasks, MAX_CONCURRENCY, async (t, index) => {
488
+ const result = await runSingleAgent(
489
+ pi, agents, t.agent, t.task, undefined, signal,
490
+ // Per-task update callback
491
+ (partial) => {
492
+ if (partial.details?.results[0]) {
493
+ allResults[index] = partial.details.results[0];
494
+ emitParallelUpdate();
495
+ }
496
+ },
497
+ makeDetails("parallel")
498
+ );
499
+ allResults[index] = result;
500
+ emitParallelUpdate();
501
+ return result;
502
+ });
503
+
504
+ const successCount = results.filter((r) => r.exitCode === 0).length;
505
+ const summaries = results.map((r) => {
506
+ const output = getFinalOutput(r.messages);
507
+ const preview = output.slice(0, 100) + (output.length > 100 ? "..." : "");
508
+ return `[${r.agent}] ${r.exitCode === 0 ? "completed" : "failed"}: ${preview || "(no output)"}`;
509
+ });
510
+ return { content: [{ type: "text", text: `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n")}` }], details: makeDetails("parallel")(results) };
511
+ }
512
+
513
+ if (params.agent && params.task) {
514
+ const result = await runSingleAgent(pi, agents, params.agent, params.task, undefined, signal, onUpdate, makeDetails("single"));
515
+ const isError = result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
516
+ if (isError) {
517
+ const errorMsg = result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
518
+ return { content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }], details: makeDetails("single")([result]), isError: true };
519
+ }
520
+ return { content: [{ type: "text", text: getFinalOutput(result.messages) || "(no output)" }], details: makeDetails("single")([result]) };
521
+ }
522
+
523
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
524
+ return { content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }], details: makeDetails("single")([]) };
525
+ },
526
+
527
+ renderCall(args, theme) {
528
+ const scope: AgentScope = args.agentScope ?? "user";
529
+ if (args.chain && args.chain.length > 0) {
530
+ let text = theme.fg("toolTitle", theme.bold("subagent ")) + theme.fg("accent", `chain (${args.chain.length} steps)`) + theme.fg("muted", ` [${scope}]`);
531
+ for (let i = 0; i < Math.min(args.chain.length, 3); i++) {
532
+ const step = args.chain[i];
533
+ // Clean up {previous} placeholder for display
534
+ const cleanTask = step.task.replace(/\{previous\}/g, "").trim();
535
+ const preview = cleanTask.length > 40 ? cleanTask.slice(0, 40) + "..." : cleanTask;
536
+ text += "\n " + theme.fg("muted", `${i + 1}.`) + " " + theme.fg("accent", step.agent) + theme.fg("dim", ` ${preview}`);
537
+ }
538
+ if (args.chain.length > 3) text += "\n " + theme.fg("muted", `... +${args.chain.length - 3} more`);
539
+ return new Text(text, 0, 0);
540
+ }
541
+ if (args.tasks && args.tasks.length > 0) {
542
+ let text = theme.fg("toolTitle", theme.bold("subagent ")) + theme.fg("accent", `parallel (${args.tasks.length} tasks)`) + theme.fg("muted", ` [${scope}]`);
543
+ for (const t of args.tasks.slice(0, 3)) {
544
+ const preview = t.task.length > 40 ? t.task.slice(0, 40) + "..." : t.task;
545
+ text += "\n " + theme.fg("accent", t.agent) + theme.fg("dim", ` ${preview}`);
546
+ }
547
+ if (args.tasks.length > 3) text += "\n " + theme.fg("muted", `... +${args.tasks.length - 3} more`);
548
+ return new Text(text, 0, 0);
549
+ }
550
+ const agentName = args.agent || "...";
551
+ const preview = args.task ? (args.task.length > 60 ? args.task.slice(0, 60) + "..." : args.task) : "...";
552
+ let text = theme.fg("toolTitle", theme.bold("subagent ")) + theme.fg("accent", agentName) + theme.fg("muted", ` [${scope}]`);
553
+ text += "\n " + theme.fg("dim", preview);
554
+ return new Text(text, 0, 0);
555
+ },
556
+
557
+ renderResult(result, { expanded }, theme) {
558
+ const { details } = result;
559
+ if (!details || details.results.length === 0) {
560
+ const text = result.content[0];
561
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
562
+ }
563
+
564
+ const mdTheme = getMarkdownTheme();
565
+
566
+ const renderDisplayItems = (items: DisplayItem[], limit?: number) => {
567
+ const toShow = limit ? items.slice(-limit) : items;
568
+ const skipped = limit && items.length > limit ? items.length - limit : 0;
569
+ let text = "";
570
+ if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`);
571
+ for (const item of toShow) {
572
+ if (item.type === "text") {
573
+ const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n");
574
+ text += theme.fg("toolOutput", preview) + "\n";
575
+ } else {
576
+ text += theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)) + "\n";
577
+ }
578
+ }
579
+ return text.trimEnd();
580
+ };
581
+
582
+ if (details.mode === "single" && details.results.length === 1) {
583
+ const r = details.results[0];
584
+ const isError = r.exitCode !== 0 || r.stopReason === "error" || r.stopReason === "aborted";
585
+ const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
586
+ const displayItems = getDisplayItems(r.messages);
587
+ const finalOutput = getFinalOutput(r.messages);
588
+
589
+ if (expanded) {
590
+ const container = new Container();
591
+ let header = icon + " " + theme.fg("toolTitle", theme.bold(r.agent)) + theme.fg("muted", ` (${r.agentSource})`);
592
+ if (isError && r.stopReason) header += " " + theme.fg("error", `[${r.stopReason}]`);
593
+ container.addChild(new Text(header, 0, 0));
594
+ if (isError && r.errorMessage) container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
595
+ container.addChild(new Spacer(1));
596
+ container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
597
+ container.addChild(new Text(theme.fg("dim", r.task), 0, 0));
598
+ container.addChild(new Spacer(1));
599
+ container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
600
+ if (displayItems.length === 0 && !finalOutput) {
601
+ container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
602
+ } else {
603
+ for (const item of displayItems) {
604
+ if (item.type === "toolCall") container.addChild(new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), 0, 0));
605
+ }
606
+ if (finalOutput) {
607
+ container.addChild(new Spacer(1));
608
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
609
+ }
610
+ }
611
+ const usageStr = formatUsageStats(r.usage, r.model);
612
+ if (usageStr) { container.addChild(new Spacer(1)); container.addChild(new Text(theme.fg("dim", usageStr), 0, 0)); }
613
+ return container;
614
+ }
615
+
616
+ let text = icon + " " + theme.fg("toolTitle", theme.bold(r.agent)) + theme.fg("muted", ` (${r.agentSource})`);
617
+ if (isError && r.stopReason) text += " " + theme.fg("error", `[${r.stopReason}]`);
618
+ if (isError && r.errorMessage) text += "\n" + theme.fg("error", `Error: ${r.errorMessage}`);
619
+ else if (displayItems.length === 0) text += "\n" + theme.fg("muted", "(no output)");
620
+ else {
621
+ text += "\n" + renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT);
622
+ if (displayItems.length > COLLAPSED_ITEM_COUNT) text += "\n" + theme.fg("muted", "(Ctrl+O to expand)");
623
+ }
624
+ const usageStr = formatUsageStats(r.usage, r.model);
625
+ if (usageStr) text += "\n" + theme.fg("dim", usageStr);
626
+ return new Text(text, 0, 0);
627
+ }
628
+
629
+ const aggregateUsage = (results: SingleResult[]) => {
630
+ const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
631
+ for (const r of results) {
632
+ total.input += r.usage.input;
633
+ total.output += r.usage.output;
634
+ total.cacheRead += r.usage.cacheRead;
635
+ total.cacheWrite += r.usage.cacheWrite;
636
+ total.cost += r.usage.cost;
637
+ total.turns += r.usage.turns;
638
+ }
639
+ return total;
640
+ };
641
+
642
+ if (details.mode === "chain") {
643
+ const successCount = details.results.filter((r) => r.exitCode === 0).length;
644
+ const icon = successCount === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
645
+
646
+ if (expanded) {
647
+ const container = new Container();
648
+ container.addChild(new Text(icon + " " + theme.fg("toolTitle", theme.bold("chain ")) + theme.fg("accent", `${successCount}/${details.results.length} steps`), 0, 0));
649
+
650
+ for (const r of details.results) {
651
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
652
+ const displayItems = getDisplayItems(r.messages);
653
+ const finalOutput = getFinalOutput(r.messages);
654
+
655
+ container.addChild(new Spacer(1));
656
+ container.addChild(new Text(theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent) + " " + rIcon, 0, 0));
657
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
658
+
659
+ // Show tool calls
660
+ for (const item of displayItems) {
661
+ if (item.type === "toolCall") {
662
+ container.addChild(new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), 0, 0));
663
+ }
664
+ }
665
+
666
+ // Show final output as markdown
667
+ if (finalOutput) {
668
+ container.addChild(new Spacer(1));
669
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
670
+ }
671
+
672
+ const stepUsage = formatUsageStats(r.usage, r.model);
673
+ if (stepUsage) container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0));
674
+ }
675
+
676
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
677
+ if (usageStr) {
678
+ container.addChild(new Spacer(1));
679
+ container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
680
+ }
681
+ return container;
682
+ }
683
+
684
+ // Collapsed view
685
+ let text = icon + " " + theme.fg("toolTitle", theme.bold("chain ")) + theme.fg("accent", `${successCount}/${details.results.length} steps`);
686
+ for (const r of details.results) {
687
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
688
+ const displayItems = getDisplayItems(r.messages);
689
+ text += "\n\n" + theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent) + " " + rIcon;
690
+ if (displayItems.length === 0) text += "\n" + theme.fg("muted", "(no output)");
691
+ else text += "\n" + renderDisplayItems(displayItems, 5);
692
+ }
693
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
694
+ if (usageStr) text += "\n\n" + theme.fg("dim", `Total: ${usageStr}`);
695
+ text += "\n" + theme.fg("muted", "(Ctrl+O to expand)");
696
+ return new Text(text, 0, 0);
697
+ }
698
+
699
+ if (details.mode === "parallel") {
700
+ const running = details.results.filter((r) => r.exitCode === -1).length;
701
+ const successCount = details.results.filter((r) => r.exitCode === 0).length;
702
+ const failCount = details.results.filter((r) => r.exitCode > 0).length;
703
+ const isRunning = running > 0;
704
+ const icon = isRunning ? theme.fg("warning", "⏳") : (failCount > 0 ? theme.fg("warning", "◐") : theme.fg("success", "✓"));
705
+ const status = isRunning
706
+ ? `${successCount + failCount}/${details.results.length} done, ${running} running`
707
+ : `${successCount}/${details.results.length} tasks`;
708
+
709
+ if (expanded && !isRunning) {
710
+ const container = new Container();
711
+ container.addChild(new Text(icon + " " + theme.fg("toolTitle", theme.bold("parallel ")) + theme.fg("accent", status), 0, 0));
712
+
713
+ for (const r of details.results) {
714
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
715
+ const displayItems = getDisplayItems(r.messages);
716
+ const finalOutput = getFinalOutput(r.messages);
717
+
718
+ container.addChild(new Spacer(1));
719
+ container.addChild(new Text(theme.fg("muted", "─── ") + theme.fg("accent", r.agent) + " " + rIcon, 0, 0));
720
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
721
+
722
+ // Show tool calls
723
+ for (const item of displayItems) {
724
+ if (item.type === "toolCall") {
725
+ container.addChild(new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), 0, 0));
726
+ }
727
+ }
728
+
729
+ // Show final output as markdown
730
+ if (finalOutput) {
731
+ container.addChild(new Spacer(1));
732
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
733
+ }
734
+
735
+ const taskUsage = formatUsageStats(r.usage, r.model);
736
+ if (taskUsage) container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0));
737
+ }
738
+
739
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
740
+ if (usageStr) {
741
+ container.addChild(new Spacer(1));
742
+ container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
743
+ }
744
+ return container;
745
+ }
746
+
747
+ // Collapsed view (or still running)
748
+ let text = icon + " " + theme.fg("toolTitle", theme.bold("parallel ")) + theme.fg("accent", status);
749
+ for (const r of details.results) {
750
+ const rIcon = r.exitCode === -1 ? theme.fg("warning", "⏳") : (r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗"));
751
+ const displayItems = getDisplayItems(r.messages);
752
+ text += "\n\n" + theme.fg("muted", "─── ") + theme.fg("accent", r.agent) + " " + rIcon;
753
+ if (displayItems.length === 0) text += "\n" + theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)");
754
+ else text += "\n" + renderDisplayItems(displayItems, 5);
755
+ }
756
+ if (!isRunning) {
757
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
758
+ if (usageStr) text += "\n\n" + theme.fg("dim", `Total: ${usageStr}`);
759
+ }
760
+ if (!expanded) text += "\n" + theme.fg("muted", "(Ctrl+O to expand)");
761
+ return new Text(text, 0, 0);
762
+ }
763
+
764
+ const text = result.content[0];
765
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
766
+ },
767
+ };
768
+
769
+ return tool;
770
+ };
771
+
772
+ export default factory;