mercury-agent 0.5.0 → 0.5.2

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 (125) hide show
  1. package/README.md +452 -451
  2. package/container/Dockerfile +127 -127
  3. package/container/Dockerfile.base +109 -109
  4. package/container/Dockerfile.power +17 -17
  5. package/container/agent-package.json +8 -8
  6. package/container/build.sh +54 -54
  7. package/docs/ROADMAP.md +3 -4
  8. package/docs/archive/summarization/2026-07-02-recent-dev-summary.md +71 -0
  9. package/docs/auth/dashboard.md +28 -28
  10. package/docs/auth/overview.md +109 -109
  11. package/docs/auth/whatsapp.md +173 -173
  12. package/docs/authoring-profiles.md +174 -174
  13. package/docs/configuration.md +54 -54
  14. package/docs/container-lifecycle.md +349 -349
  15. package/docs/{bugs/bwrap-privileged-linux-docker.md → debug/major/2026-07-02-bwrap-privileged-linux-docker.md} +21 -1
  16. package/docs/{bugs/e2big-prompt-delivery-fix.md → debug/major/2026-07-02-e2big-prompt-delivery-fix.md} +27 -1
  17. package/docs/{bugs/registry-pull-no-local-fallback.md → debug/major/2026-07-02-registry-pull-no-local-fallback.md} +27 -1
  18. package/docs/debug/summarization/2026-07-02-common-bug-patterns.md +72 -0
  19. package/docs/deployment.md +199 -199
  20. package/docs/extensions.md +375 -375
  21. package/docs/graceful-shutdown.md +62 -62
  22. package/docs/kb-distillation.md +77 -77
  23. package/docs/media/overview.md +140 -140
  24. package/docs/media/whatsapp.md +171 -171
  25. package/docs/memory.md +137 -137
  26. package/docs/permissions.md +217 -217
  27. package/docs/pipeline.md +228 -228
  28. package/docs/prd-chat-memory.md +76 -76
  29. package/docs/prd-config-load.md +82 -82
  30. package/docs/rate-limiting.md +229 -229
  31. package/docs/runbooks/publish-checklist.md +9 -1
  32. package/docs/scheduler.md +288 -288
  33. package/docs/setup-discord.md +100 -100
  34. package/docs/setup-slack.md +119 -119
  35. package/docs/setup-whatsapp.md +94 -94
  36. package/docs/subagents.md +166 -166
  37. package/docs/web-search.md +62 -62
  38. package/examples/extensions/README.md +12 -12
  39. package/examples/extensions/charts/index.ts +13 -13
  40. package/examples/extensions/charts/skill/SKILL.md +98 -98
  41. package/examples/extensions/gws/README.md +52 -52
  42. package/examples/extensions/gws/skill/SKILL.md +57 -57
  43. package/examples/extensions/gws/skill/references/calendar.md +101 -101
  44. package/examples/extensions/gws/skill/references/docs.md +65 -65
  45. package/examples/extensions/gws/skill/references/drive.md +79 -79
  46. package/examples/extensions/gws/skill/references/gmail.md +85 -85
  47. package/examples/extensions/gws/skill/references/sheets.md +60 -60
  48. package/examples/extensions/napkin/skill/SKILL.md +728 -728
  49. package/examples/extensions/pdf/skill/LICENSE.txt +30 -30
  50. package/examples/extensions/pdf/skill/SKILL.md +314 -314
  51. package/examples/extensions/pdf/skill/forms.md +294 -294
  52. package/examples/extensions/pdf/skill/reference.md +611 -611
  53. package/examples/extensions/pdf/skill/scripts/check_bounding_boxes.py +65 -65
  54. package/examples/extensions/pdf/skill/scripts/check_fillable_fields.py +11 -11
  55. package/examples/extensions/pdf/skill/scripts/convert_pdf_to_images.py +33 -33
  56. package/examples/extensions/pdf/skill/scripts/create_validation_image.py +37 -37
  57. package/examples/extensions/pdf/skill/scripts/extract_form_field_info.py +122 -122
  58. package/examples/extensions/pdf/skill/scripts/extract_form_structure.py +115 -115
  59. package/examples/extensions/pdf/skill/scripts/fill_fillable_fields.py +98 -98
  60. package/examples/extensions/pdf/skill/scripts/fill_pdf_form_with_annotations.py +107 -107
  61. package/examples/extensions/permission-guard/index.ts +65 -65
  62. package/examples/extensions/pinchtab/skill/SKILL.md +224 -224
  63. package/examples/extensions/pinchtab/skill/TRUST.md +69 -69
  64. package/examples/extensions/pinchtab/skill/references/api.md +297 -297
  65. package/examples/extensions/pinchtab/skill/references/env.md +45 -45
  66. package/examples/extensions/pinchtab/skill/references/profiles.md +107 -107
  67. package/examples/extensions/tradestation/host/refresh.ts +102 -102
  68. package/examples/extensions/tradestation/index.ts +153 -153
  69. package/examples/extensions/tradestation/skill/SKILL.md +67 -67
  70. package/examples/extensions/voice-synth/index.ts +94 -94
  71. package/examples/extensions/voice-synth/skill/SKILL.md +38 -38
  72. package/examples/extensions/voice-transcribe/requirements.txt +8 -8
  73. package/examples/extensions/voice-transcribe/scripts/transcribe.py +179 -179
  74. package/examples/extensions/voice-transcribe/skill/SKILL.md +53 -53
  75. package/examples/extensions/yahoo-mail/cli/package.json +13 -13
  76. package/examples/extensions/yahoo-mail/skill/SKILL.md +78 -78
  77. package/package.json +106 -106
  78. package/resources/agents/explore.md +50 -50
  79. package/resources/agents/worker.md +24 -24
  80. package/resources/connection-env-vars.json +25 -25
  81. package/resources/pi-extensions/subagent/agents.ts +126 -126
  82. package/resources/pi-extensions/subagent/index.ts +964 -964
  83. package/resources/profiles/coding/AGENTS.md +43 -43
  84. package/resources/profiles/coding/mercury-profile.yaml +15 -15
  85. package/resources/profiles/general/AGENTS.md +31 -31
  86. package/resources/profiles/general/mercury-profile.yaml +15 -15
  87. package/resources/profiles/research/AGENTS.md +40 -40
  88. package/resources/profiles/research/mercury-profile.yaml +15 -15
  89. package/resources/skills/config/SKILL.md +25 -25
  90. package/resources/skills/context/SKILL.md +33 -33
  91. package/resources/skills/conversation-recap/SKILL.md +19 -19
  92. package/resources/skills/mutes/SKILL.md +31 -31
  93. package/resources/skills/permissions/SKILL.md +19 -19
  94. package/resources/skills/preferences/SKILL.md +31 -31
  95. package/resources/skills/recall/SKILL.md +24 -24
  96. package/resources/skills/roles/SKILL.md +18 -18
  97. package/resources/skills/spaces/SKILL.md +18 -18
  98. package/resources/skills/tasks/SKILL.md +45 -45
  99. package/resources/templates/AGENTS.md +157 -157
  100. package/resources/templates/env.template +38 -38
  101. package/resources/templates/mercury.example.yaml +99 -99
  102. package/src/agent/container-entry.ts +1 -1
  103. package/src/agent/container-runner.ts +1345 -1346
  104. package/src/cli/mercury.ts +39 -7
  105. package/src/cli/mrctl.ts +636 -636
  106. package/src/config-file.ts +540 -540
  107. package/src/config.ts +339 -339
  108. package/src/core/api.ts +125 -125
  109. package/src/core/caller-token.ts +101 -101
  110. package/src/core/permissions.ts +228 -228
  111. package/src/core/profiles.ts +271 -271
  112. package/src/core/routes/capability.ts +70 -70
  113. package/src/core/routes/index.ts +15 -15
  114. package/src/core/runtime.ts +1530 -1530
  115. package/src/dashboard/index.html +729 -729
  116. package/src/extensions/api.ts +273 -273
  117. package/src/extensions/loader.ts +286 -286
  118. package/src/extensions/types.ts +517 -517
  119. package/src/main.ts +605 -605
  120. package/docs/pending-updates/applicative-profiles.md +0 -15
  121. package/docs/pending-updates/caller-bound-capability-token.md +0 -15
  122. package/docs/pending-updates/dm-auto-space.md +0 -15
  123. /package/docs/archive/{2026-07-01-applicative-profiles.md → applicative-profiles/2026-07-01-applicative-profiles.md} +0 -0
  124. /package/docs/archive/{2026-07-01-caller-bound-capability-token.md → applicative-profiles/2026-07-01-caller-bound-capability-token.md} +0 -0
  125. /package/docs/archive/{2026-07-01-dm-auto-space.md → applicative-profiles/2026-07-01-dm-auto-space.md} +0 -0
@@ -1,964 +1,964 @@
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 { AgentToolResult } from "@earendil-works/pi-agent-core";
20
- import type { Message } from "@earendil-works/pi-ai";
21
- import { StringEnum } from "@earendil-works/pi-ai";
22
- import { type ExtensionAPI, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
23
- import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
24
- import { Type } from "@sinclair/typebox";
25
- import { type AgentConfig, type AgentScope, discoverAgents } from "./agents.js";
26
-
27
- const MAX_PARALLEL_TASKS = 8;
28
- const MAX_CONCURRENCY = 4;
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(
39
- usage: {
40
- input: number;
41
- output: number;
42
- cacheRead: number;
43
- cacheWrite: number;
44
- cost: number;
45
- contextTokens?: number;
46
- turns?: number;
47
- },
48
- model?: string,
49
- ): string {
50
- const parts: string[] = [];
51
- if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
52
- if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
53
- if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
54
- if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
55
- if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
56
- if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
57
- if (usage.contextTokens && usage.contextTokens > 0) {
58
- parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
59
- }
60
- if (model) parts.push(model);
61
- return parts.join(" ");
62
- }
63
-
64
- function formatToolCall(
65
- toolName: string,
66
- args: Record<string, unknown>,
67
- themeFg: (color: any, text: string) => string,
68
- ): string {
69
- const shortenPath = (p: string) => {
70
- const home = os.homedir();
71
- return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
72
- };
73
-
74
- switch (toolName) {
75
- case "bash": {
76
- const command = (args.command as string) || "...";
77
- const preview = command.length > 60 ? `${command.slice(0, 60)}...` : command;
78
- return themeFg("muted", "$ ") + themeFg("toolOutput", preview);
79
- }
80
- case "read": {
81
- const rawPath = (args.file_path || args.path || "...") as string;
82
- const filePath = shortenPath(rawPath);
83
- const offset = args.offset as number | undefined;
84
- const limit = args.limit as number | undefined;
85
- let text = themeFg("accent", filePath);
86
- if (offset !== undefined || limit !== undefined) {
87
- const startLine = offset ?? 1;
88
- const endLine = limit !== undefined ? startLine + limit - 1 : "";
89
- text += themeFg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`);
90
- }
91
- return themeFg("muted", "read ") + text;
92
- }
93
- case "write": {
94
- const rawPath = (args.file_path || args.path || "...") as string;
95
- const filePath = shortenPath(rawPath);
96
- const content = (args.content || "") as string;
97
- const lines = content.split("\n").length;
98
- let text = themeFg("muted", "write ") + themeFg("accent", filePath);
99
- if (lines > 1) text += themeFg("dim", ` (${lines} lines)`);
100
- return text;
101
- }
102
- case "edit": {
103
- const rawPath = (args.file_path || args.path || "...") as string;
104
- return themeFg("muted", "edit ") + themeFg("accent", shortenPath(rawPath));
105
- }
106
- case "ls": {
107
- const rawPath = (args.path || ".") as string;
108
- return themeFg("muted", "ls ") + themeFg("accent", shortenPath(rawPath));
109
- }
110
- case "find": {
111
- const pattern = (args.pattern || "*") as string;
112
- const rawPath = (args.path || ".") as string;
113
- return themeFg("muted", "find ") + themeFg("accent", pattern) + themeFg("dim", ` in ${shortenPath(rawPath)}`);
114
- }
115
- case "grep": {
116
- const pattern = (args.pattern || "") as string;
117
- const rawPath = (args.path || ".") as string;
118
- return (
119
- themeFg("muted", "grep ") +
120
- themeFg("accent", `/${pattern}/`) +
121
- themeFg("dim", ` in ${shortenPath(rawPath)}`)
122
- );
123
- }
124
- default: {
125
- const argsStr = JSON.stringify(args);
126
- const preview = argsStr.length > 50 ? `${argsStr.slice(0, 50)}...` : argsStr;
127
- return themeFg("accent", toolName) + themeFg("dim", ` ${preview}`);
128
- }
129
- }
130
- }
131
-
132
- interface UsageStats {
133
- input: number;
134
- output: number;
135
- cacheRead: number;
136
- cacheWrite: number;
137
- cost: number;
138
- contextTokens: number;
139
- turns: number;
140
- }
141
-
142
- interface SingleResult {
143
- agent: string;
144
- agentSource: "user" | "project" | "unknown";
145
- task: string;
146
- exitCode: number;
147
- messages: Message[];
148
- stderr: string;
149
- usage: UsageStats;
150
- model?: string;
151
- stopReason?: string;
152
- errorMessage?: string;
153
- step?: number;
154
- }
155
-
156
- interface SubagentDetails {
157
- mode: "single" | "parallel" | "chain";
158
- agentScope: AgentScope;
159
- projectAgentsDir: string | null;
160
- results: SingleResult[];
161
- }
162
-
163
- function getFinalOutput(messages: Message[]): string {
164
- for (let i = messages.length - 1; i >= 0; i--) {
165
- const msg = messages[i];
166
- if (msg.role === "assistant") {
167
- for (const part of msg.content) {
168
- if (part.type === "text") return part.text;
169
- }
170
- }
171
- }
172
- return "";
173
- }
174
-
175
- type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, any> };
176
-
177
- function getDisplayItems(messages: Message[]): DisplayItem[] {
178
- const items: DisplayItem[] = [];
179
- for (const msg of messages) {
180
- if (msg.role === "assistant") {
181
- for (const part of msg.content) {
182
- if (part.type === "text") items.push({ type: "text", text: part.text });
183
- else if (part.type === "toolCall") items.push({ type: "toolCall", name: part.name, args: part.arguments });
184
- }
185
- }
186
- }
187
- return items;
188
- }
189
-
190
- async function mapWithConcurrencyLimit<TIn, TOut>(
191
- items: TIn[],
192
- concurrency: number,
193
- fn: (item: TIn, index: number) => Promise<TOut>,
194
- ): Promise<TOut[]> {
195
- if (items.length === 0) return [];
196
- const limit = Math.max(1, Math.min(concurrency, items.length));
197
- const results: TOut[] = new Array(items.length);
198
- let nextIndex = 0;
199
- const workers = new Array(limit).fill(null).map(async () => {
200
- while (true) {
201
- const current = nextIndex++;
202
- if (current >= items.length) return;
203
- results[current] = await fn(items[current], current);
204
- }
205
- });
206
- await Promise.all(workers);
207
- return results;
208
- }
209
-
210
- function writePromptToTempFile(agentName: string, prompt: string): { dir: string; filePath: string } {
211
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
212
- const safeName = agentName.replace(/[^\w.-]+/g, "_");
213
- const filePath = path.join(tmpDir, `prompt-${safeName}.md`);
214
- fs.writeFileSync(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
215
- return { dir: tmpDir, filePath };
216
- }
217
-
218
- type OnUpdateCallback = (partial: AgentToolResult<SubagentDetails>) => void;
219
-
220
- async function runSingleAgent(
221
- defaultCwd: string,
222
- agents: AgentConfig[],
223
- agentName: string,
224
- task: string,
225
- cwd: string | undefined,
226
- step: number | undefined,
227
- signal: AbortSignal | undefined,
228
- onUpdate: OnUpdateCallback | undefined,
229
- makeDetails: (results: SingleResult[]) => SubagentDetails,
230
- ): Promise<SingleResult> {
231
- const agent = agents.find((a) => a.name === agentName);
232
-
233
- if (!agent) {
234
- const available = agents.map((a) => `"${a.name}"`).join(", ") || "none";
235
- return {
236
- agent: agentName,
237
- agentSource: "unknown",
238
- task,
239
- exitCode: 1,
240
- messages: [],
241
- stderr: `Unknown agent: "${agentName}". Available agents: ${available}.`,
242
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
243
- step,
244
- };
245
- }
246
-
247
- const args: string[] = ["--mode", "json", "-p", "--no-session"];
248
- if (agent.model) args.push("--model", agent.model);
249
- if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
250
-
251
- let tmpPromptDir: string | null = null;
252
- let tmpPromptPath: string | null = null;
253
-
254
- const currentResult: SingleResult = {
255
- agent: agentName,
256
- agentSource: agent.source,
257
- task,
258
- exitCode: 0,
259
- messages: [],
260
- stderr: "",
261
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
262
- model: agent.model,
263
- step,
264
- };
265
-
266
- const emitUpdate = () => {
267
- if (onUpdate) {
268
- onUpdate({
269
- content: [{ type: "text", text: getFinalOutput(currentResult.messages) || "(running...)" }],
270
- details: makeDetails([currentResult]),
271
- });
272
- }
273
- };
274
-
275
- try {
276
- if (agent.systemPrompt.trim()) {
277
- const tmp = writePromptToTempFile(agent.name, agent.systemPrompt);
278
- tmpPromptDir = tmp.dir;
279
- tmpPromptPath = tmp.filePath;
280
- args.push("--append-system-prompt", tmpPromptPath);
281
- }
282
-
283
- args.push(`Task: ${task}`);
284
- let wasAborted = false;
285
-
286
- const exitCode = await new Promise<number>((resolve) => {
287
- const proc = spawn("pi", args, { cwd: cwd ?? defaultCwd, shell: false, stdio: ["ignore", "pipe", "pipe"] });
288
- let buffer = "";
289
-
290
- const processLine = (line: string) => {
291
- if (!line.trim()) return;
292
- let event: any;
293
- try {
294
- event = JSON.parse(line);
295
- } catch {
296
- return;
297
- }
298
-
299
- if (event.type === "message_end" && event.message) {
300
- const msg = event.message as Message;
301
- currentResult.messages.push(msg);
302
-
303
- if (msg.role === "assistant") {
304
- currentResult.usage.turns++;
305
- const usage = msg.usage;
306
- if (usage) {
307
- currentResult.usage.input += usage.input || 0;
308
- currentResult.usage.output += usage.output || 0;
309
- currentResult.usage.cacheRead += usage.cacheRead || 0;
310
- currentResult.usage.cacheWrite += usage.cacheWrite || 0;
311
- currentResult.usage.cost += usage.cost?.total || 0;
312
- currentResult.usage.contextTokens = usage.totalTokens || 0;
313
- }
314
- if (!currentResult.model && msg.model) currentResult.model = msg.model;
315
- if (msg.stopReason) currentResult.stopReason = msg.stopReason;
316
- if (msg.errorMessage) currentResult.errorMessage = msg.errorMessage;
317
- }
318
- emitUpdate();
319
- }
320
-
321
- if (event.type === "tool_result_end" && event.message) {
322
- currentResult.messages.push(event.message as Message);
323
- emitUpdate();
324
- }
325
- };
326
-
327
- proc.stdout.on("data", (data) => {
328
- buffer += data.toString();
329
- const lines = buffer.split("\n");
330
- buffer = lines.pop() || "";
331
- for (const line of lines) processLine(line);
332
- });
333
-
334
- proc.stderr.on("data", (data) => {
335
- currentResult.stderr += data.toString();
336
- });
337
-
338
- proc.on("close", (code) => {
339
- if (buffer.trim()) processLine(buffer);
340
- resolve(code ?? 0);
341
- });
342
-
343
- proc.on("error", () => {
344
- resolve(1);
345
- });
346
-
347
- if (signal) {
348
- const killProc = () => {
349
- wasAborted = true;
350
- proc.kill("SIGTERM");
351
- setTimeout(() => {
352
- if (!proc.killed) proc.kill("SIGKILL");
353
- }, 5000);
354
- };
355
- if (signal.aborted) killProc();
356
- else signal.addEventListener("abort", killProc, { once: true });
357
- }
358
- });
359
-
360
- currentResult.exitCode = exitCode;
361
- if (wasAborted) throw new Error("Subagent was aborted");
362
- return currentResult;
363
- } finally {
364
- if (tmpPromptPath)
365
- try {
366
- fs.unlinkSync(tmpPromptPath);
367
- } catch {
368
- /* ignore */
369
- }
370
- if (tmpPromptDir)
371
- try {
372
- fs.rmdirSync(tmpPromptDir);
373
- } catch {
374
- /* ignore */
375
- }
376
- }
377
- }
378
-
379
- const TaskItem = Type.Object({
380
- agent: Type.String({ description: "Name of the agent to invoke" }),
381
- task: Type.String({ description: "Task to delegate to the agent" }),
382
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
383
- });
384
-
385
- const ChainItem = Type.Object({
386
- agent: Type.String({ description: "Name of the agent to invoke" }),
387
- task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
388
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
389
- });
390
-
391
- const AgentScopeSchema = StringEnum(["user", "project", "both"] as const, {
392
- description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
393
- default: "user",
394
- });
395
-
396
- const SubagentParams = Type.Object({
397
- agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })),
398
- task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })),
399
- tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
400
- chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })),
401
- agentScope: Type.Optional(AgentScopeSchema),
402
- confirmProjectAgents: Type.Optional(
403
- Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true }),
404
- ),
405
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
406
- });
407
-
408
- export default function (pi: ExtensionAPI) {
409
- pi.registerTool({
410
- name: "subagent",
411
- label: "Subagent",
412
- description: [
413
- "Delegate tasks to specialized subagents with isolated context.",
414
- "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).",
415
- 'Default agent scope is "user" (from ~/.pi/agent/agents).',
416
- 'To enable project-local agents in .pi/agents, set agentScope: "both" (or "project").',
417
- ].join(" "),
418
- parameters: SubagentParams,
419
-
420
- async execute(_toolCallId, params, signal, onUpdate, ctx) {
421
- const agentScope: AgentScope = params.agentScope ?? "user";
422
- const discovery = discoverAgents(ctx.cwd, agentScope);
423
- const agents = discovery.agents;
424
- const confirmProjectAgents = params.confirmProjectAgents ?? true;
425
-
426
- const hasChain = (params.chain?.length ?? 0) > 0;
427
- const hasTasks = (params.tasks?.length ?? 0) > 0;
428
- const hasSingle = Boolean(params.agent && params.task);
429
- const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle);
430
-
431
- const makeDetails =
432
- (mode: "single" | "parallel" | "chain") =>
433
- (results: SingleResult[]): SubagentDetails => ({
434
- mode,
435
- agentScope,
436
- projectAgentsDir: discovery.projectAgentsDir,
437
- results,
438
- });
439
-
440
- if (modeCount !== 1) {
441
- const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
442
- return {
443
- content: [
444
- {
445
- type: "text",
446
- text: `Invalid parameters. Provide exactly one mode.\nAvailable agents: ${available}`,
447
- },
448
- ],
449
- details: makeDetails("single")([]),
450
- };
451
- }
452
-
453
- if ((agentScope === "project" || agentScope === "both") && confirmProjectAgents && ctx.hasUI) {
454
- const requestedAgentNames = new Set<string>();
455
- if (params.chain) for (const step of params.chain) requestedAgentNames.add(step.agent);
456
- if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent);
457
- if (params.agent) requestedAgentNames.add(params.agent);
458
-
459
- const projectAgentsRequested = Array.from(requestedAgentNames)
460
- .map((name) => agents.find((a) => a.name === name))
461
- .filter((a): a is AgentConfig => a?.source === "project");
462
-
463
- if (projectAgentsRequested.length > 0) {
464
- const names = projectAgentsRequested.map((a) => a.name).join(", ");
465
- const dir = discovery.projectAgentsDir ?? "(unknown)";
466
- const ok = await ctx.ui.confirm(
467
- "Run project-local agents?",
468
- `Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
469
- );
470
- if (!ok)
471
- return {
472
- content: [{ type: "text", text: "Canceled: project-local agents not approved." }],
473
- details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]),
474
- };
475
- }
476
- }
477
-
478
- if (params.chain && params.chain.length > 0) {
479
- const results: SingleResult[] = [];
480
- let previousOutput = "";
481
-
482
- for (let i = 0; i < params.chain.length; i++) {
483
- const step = params.chain[i];
484
- const taskWithContext = step.task.replace(/\{previous\}/g, previousOutput);
485
-
486
- // Create update callback that includes all previous results
487
- const chainUpdate: OnUpdateCallback | undefined = onUpdate
488
- ? (partial) => {
489
- // Combine completed results with current streaming result
490
- const currentResult = partial.details?.results[0];
491
- if (currentResult) {
492
- const allResults = [...results, currentResult];
493
- onUpdate({
494
- content: partial.content,
495
- details: makeDetails("chain")(allResults),
496
- });
497
- }
498
- }
499
- : undefined;
500
-
501
- const result = await runSingleAgent(
502
- ctx.cwd,
503
- agents,
504
- step.agent,
505
- taskWithContext,
506
- step.cwd,
507
- i + 1,
508
- signal,
509
- chainUpdate,
510
- makeDetails("chain"),
511
- );
512
- results.push(result);
513
-
514
- const isError =
515
- result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
516
- if (isError) {
517
- const errorMsg =
518
- result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
519
- return {
520
- content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` }],
521
- details: makeDetails("chain")(results),
522
- isError: true,
523
- };
524
- }
525
- previousOutput = getFinalOutput(result.messages);
526
- }
527
- return {
528
- content: [{ type: "text", text: getFinalOutput(results[results.length - 1].messages) || "(no output)" }],
529
- details: makeDetails("chain")(results),
530
- };
531
- }
532
-
533
- if (params.tasks && params.tasks.length > 0) {
534
- if (params.tasks.length > MAX_PARALLEL_TASKS)
535
- return {
536
- content: [
537
- {
538
- type: "text",
539
- text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.`,
540
- },
541
- ],
542
- details: makeDetails("parallel")([]),
543
- };
544
-
545
- // Track all results for streaming updates
546
- const allResults: SingleResult[] = new Array(params.tasks.length);
547
-
548
- // Initialize placeholder results
549
- for (let i = 0; i < params.tasks.length; i++) {
550
- allResults[i] = {
551
- agent: params.tasks[i].agent,
552
- agentSource: "unknown",
553
- task: params.tasks[i].task,
554
- exitCode: -1, // -1 = still running
555
- messages: [],
556
- stderr: "",
557
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
558
- };
559
- }
560
-
561
- const emitParallelUpdate = () => {
562
- if (onUpdate) {
563
- const running = allResults.filter((r) => r.exitCode === -1).length;
564
- const done = allResults.filter((r) => r.exitCode !== -1).length;
565
- onUpdate({
566
- content: [
567
- { type: "text", text: `Parallel: ${done}/${allResults.length} done, ${running} running...` },
568
- ],
569
- details: makeDetails("parallel")([...allResults]),
570
- });
571
- }
572
- };
573
-
574
- const results = await mapWithConcurrencyLimit(params.tasks, MAX_CONCURRENCY, async (t, index) => {
575
- const result = await runSingleAgent(
576
- ctx.cwd,
577
- agents,
578
- t.agent,
579
- t.task,
580
- t.cwd,
581
- undefined,
582
- signal,
583
- // Per-task update callback
584
- (partial) => {
585
- if (partial.details?.results[0]) {
586
- allResults[index] = partial.details.results[0];
587
- emitParallelUpdate();
588
- }
589
- },
590
- makeDetails("parallel"),
591
- );
592
- allResults[index] = result;
593
- emitParallelUpdate();
594
- return result;
595
- });
596
-
597
- const successCount = results.filter((r) => r.exitCode === 0).length;
598
- const summaries = results.map((r) => {
599
- const output = getFinalOutput(r.messages);
600
- const preview = output.slice(0, 100) + (output.length > 100 ? "..." : "");
601
- return `[${r.agent}] ${r.exitCode === 0 ? "completed" : "failed"}: ${preview || "(no output)"}`;
602
- });
603
- return {
604
- content: [
605
- {
606
- type: "text",
607
- text: `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n")}`,
608
- },
609
- ],
610
- details: makeDetails("parallel")(results),
611
- };
612
- }
613
-
614
- if (params.agent && params.task) {
615
- const result = await runSingleAgent(
616
- ctx.cwd,
617
- agents,
618
- params.agent,
619
- params.task,
620
- params.cwd,
621
- undefined,
622
- signal,
623
- onUpdate,
624
- makeDetails("single"),
625
- );
626
- const isError = result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
627
- if (isError) {
628
- const errorMsg =
629
- result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
630
- return {
631
- content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }],
632
- details: makeDetails("single")([result]),
633
- isError: true,
634
- };
635
- }
636
- return {
637
- content: [{ type: "text", text: getFinalOutput(result.messages) || "(no output)" }],
638
- details: makeDetails("single")([result]),
639
- };
640
- }
641
-
642
- const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
643
- return {
644
- content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }],
645
- details: makeDetails("single")([]),
646
- };
647
- },
648
-
649
- renderCall(args, theme) {
650
- const scope: AgentScope = args.agentScope ?? "user";
651
- if (args.chain && args.chain.length > 0) {
652
- let text =
653
- theme.fg("toolTitle", theme.bold("subagent ")) +
654
- theme.fg("accent", `chain (${args.chain.length} steps)`) +
655
- theme.fg("muted", ` [${scope}]`);
656
- for (let i = 0; i < Math.min(args.chain.length, 3); i++) {
657
- const step = args.chain[i];
658
- // Clean up {previous} placeholder for display
659
- const cleanTask = step.task.replace(/\{previous\}/g, "").trim();
660
- const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask;
661
- text +=
662
- "\n " +
663
- theme.fg("muted", `${i + 1}.`) +
664
- " " +
665
- theme.fg("accent", step.agent) +
666
- theme.fg("dim", ` ${preview}`);
667
- }
668
- if (args.chain.length > 3) text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`;
669
- return new Text(text, 0, 0);
670
- }
671
- if (args.tasks && args.tasks.length > 0) {
672
- let text =
673
- theme.fg("toolTitle", theme.bold("subagent ")) +
674
- theme.fg("accent", `parallel (${args.tasks.length} tasks)`) +
675
- theme.fg("muted", ` [${scope}]`);
676
- for (const t of args.tasks.slice(0, 3)) {
677
- const preview = t.task.length > 40 ? `${t.task.slice(0, 40)}...` : t.task;
678
- text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", ` ${preview}`)}`;
679
- }
680
- if (args.tasks.length > 3) text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`;
681
- return new Text(text, 0, 0);
682
- }
683
- const agentName = args.agent || "...";
684
- const preview = args.task ? (args.task.length > 60 ? `${args.task.slice(0, 60)}...` : args.task) : "...";
685
- let text =
686
- theme.fg("toolTitle", theme.bold("subagent ")) +
687
- theme.fg("accent", agentName) +
688
- theme.fg("muted", ` [${scope}]`);
689
- text += `\n ${theme.fg("dim", preview)}`;
690
- return new Text(text, 0, 0);
691
- },
692
-
693
- renderResult(result, { expanded }, theme) {
694
- const details = result.details as SubagentDetails | undefined;
695
- if (!details || details.results.length === 0) {
696
- const text = result.content[0];
697
- return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
698
- }
699
-
700
- const mdTheme = getMarkdownTheme();
701
-
702
- const renderDisplayItems = (items: DisplayItem[], limit?: number) => {
703
- const toShow = limit ? items.slice(-limit) : items;
704
- const skipped = limit && items.length > limit ? items.length - limit : 0;
705
- let text = "";
706
- if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`);
707
- for (const item of toShow) {
708
- if (item.type === "text") {
709
- const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n");
710
- text += `${theme.fg("toolOutput", preview)}\n`;
711
- } else {
712
- text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme))}\n`;
713
- }
714
- }
715
- return text.trimEnd();
716
- };
717
-
718
- if (details.mode === "single" && details.results.length === 1) {
719
- const r = details.results[0];
720
- const isError = r.exitCode !== 0 || r.stopReason === "error" || r.stopReason === "aborted";
721
- const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
722
- const displayItems = getDisplayItems(r.messages);
723
- const finalOutput = getFinalOutput(r.messages);
724
-
725
- if (expanded) {
726
- const container = new Container();
727
- let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
728
- if (isError && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
729
- container.addChild(new Text(header, 0, 0));
730
- if (isError && r.errorMessage)
731
- container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
732
- container.addChild(new Spacer(1));
733
- container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
734
- container.addChild(new Text(theme.fg("dim", r.task), 0, 0));
735
- container.addChild(new Spacer(1));
736
- container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
737
- if (displayItems.length === 0 && !finalOutput) {
738
- container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
739
- } else {
740
- for (const item of displayItems) {
741
- if (item.type === "toolCall")
742
- container.addChild(
743
- new Text(
744
- theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
745
- 0,
746
- 0,
747
- ),
748
- );
749
- }
750
- if (finalOutput) {
751
- container.addChild(new Spacer(1));
752
- container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
753
- }
754
- }
755
- const usageStr = formatUsageStats(r.usage, r.model);
756
- if (usageStr) {
757
- container.addChild(new Spacer(1));
758
- container.addChild(new Text(theme.fg("dim", usageStr), 0, 0));
759
- }
760
- return container;
761
- }
762
-
763
- let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
764
- if (isError && r.stopReason) text += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
765
- if (isError && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`;
766
- else if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
767
- else {
768
- text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`;
769
- if (displayItems.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
770
- }
771
- const usageStr = formatUsageStats(r.usage, r.model);
772
- if (usageStr) text += `\n${theme.fg("dim", usageStr)}`;
773
- return new Text(text, 0, 0);
774
- }
775
-
776
- const aggregateUsage = (results: SingleResult[]) => {
777
- const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
778
- for (const r of results) {
779
- total.input += r.usage.input;
780
- total.output += r.usage.output;
781
- total.cacheRead += r.usage.cacheRead;
782
- total.cacheWrite += r.usage.cacheWrite;
783
- total.cost += r.usage.cost;
784
- total.turns += r.usage.turns;
785
- }
786
- return total;
787
- };
788
-
789
- if (details.mode === "chain") {
790
- const successCount = details.results.filter((r) => r.exitCode === 0).length;
791
- const icon = successCount === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
792
-
793
- if (expanded) {
794
- const container = new Container();
795
- container.addChild(
796
- new Text(
797
- icon +
798
- " " +
799
- theme.fg("toolTitle", theme.bold("chain ")) +
800
- theme.fg("accent", `${successCount}/${details.results.length} steps`),
801
- 0,
802
- 0,
803
- ),
804
- );
805
-
806
- for (const r of details.results) {
807
- const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
808
- const displayItems = getDisplayItems(r.messages);
809
- const finalOutput = getFinalOutput(r.messages);
810
-
811
- container.addChild(new Spacer(1));
812
- container.addChild(
813
- new Text(
814
- `${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`,
815
- 0,
816
- 0,
817
- ),
818
- );
819
- container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
820
-
821
- // Show tool calls
822
- for (const item of displayItems) {
823
- if (item.type === "toolCall") {
824
- container.addChild(
825
- new Text(
826
- theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
827
- 0,
828
- 0,
829
- ),
830
- );
831
- }
832
- }
833
-
834
- // Show final output as markdown
835
- if (finalOutput) {
836
- container.addChild(new Spacer(1));
837
- container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
838
- }
839
-
840
- const stepUsage = formatUsageStats(r.usage, r.model);
841
- if (stepUsage) container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0));
842
- }
843
-
844
- const usageStr = formatUsageStats(aggregateUsage(details.results));
845
- if (usageStr) {
846
- container.addChild(new Spacer(1));
847
- container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
848
- }
849
- return container;
850
- }
851
-
852
- // Collapsed view
853
- let text =
854
- icon +
855
- " " +
856
- theme.fg("toolTitle", theme.bold("chain ")) +
857
- theme.fg("accent", `${successCount}/${details.results.length} steps`);
858
- for (const r of details.results) {
859
- const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
860
- const displayItems = getDisplayItems(r.messages);
861
- text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`;
862
- if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
863
- else text += `\n${renderDisplayItems(displayItems, 5)}`;
864
- }
865
- const usageStr = formatUsageStats(aggregateUsage(details.results));
866
- if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
867
- text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
868
- return new Text(text, 0, 0);
869
- }
870
-
871
- if (details.mode === "parallel") {
872
- const running = details.results.filter((r) => r.exitCode === -1).length;
873
- const successCount = details.results.filter((r) => r.exitCode === 0).length;
874
- const failCount = details.results.filter((r) => r.exitCode > 0).length;
875
- const isRunning = running > 0;
876
- const icon = isRunning
877
- ? theme.fg("warning", "⏳")
878
- : failCount > 0
879
- ? theme.fg("warning", "◐")
880
- : theme.fg("success", "✓");
881
- const status = isRunning
882
- ? `${successCount + failCount}/${details.results.length} done, ${running} running`
883
- : `${successCount}/${details.results.length} tasks`;
884
-
885
- if (expanded && !isRunning) {
886
- const container = new Container();
887
- container.addChild(
888
- new Text(
889
- `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`,
890
- 0,
891
- 0,
892
- ),
893
- );
894
-
895
- for (const r of details.results) {
896
- const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
897
- const displayItems = getDisplayItems(r.messages);
898
- const finalOutput = getFinalOutput(r.messages);
899
-
900
- container.addChild(new Spacer(1));
901
- container.addChild(
902
- new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0),
903
- );
904
- container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
905
-
906
- // Show tool calls
907
- for (const item of displayItems) {
908
- if (item.type === "toolCall") {
909
- container.addChild(
910
- new Text(
911
- theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
912
- 0,
913
- 0,
914
- ),
915
- );
916
- }
917
- }
918
-
919
- // Show final output as markdown
920
- if (finalOutput) {
921
- container.addChild(new Spacer(1));
922
- container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
923
- }
924
-
925
- const taskUsage = formatUsageStats(r.usage, r.model);
926
- if (taskUsage) container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0));
927
- }
928
-
929
- const usageStr = formatUsageStats(aggregateUsage(details.results));
930
- if (usageStr) {
931
- container.addChild(new Spacer(1));
932
- container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
933
- }
934
- return container;
935
- }
936
-
937
- // Collapsed view (or still running)
938
- let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`;
939
- for (const r of details.results) {
940
- const rIcon =
941
- r.exitCode === -1
942
- ? theme.fg("warning", "⏳")
943
- : r.exitCode === 0
944
- ? theme.fg("success", "✓")
945
- : theme.fg("error", "✗");
946
- const displayItems = getDisplayItems(r.messages);
947
- text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
948
- if (displayItems.length === 0)
949
- text += `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}`;
950
- else text += `\n${renderDisplayItems(displayItems, 5)}`;
951
- }
952
- if (!isRunning) {
953
- const usageStr = formatUsageStats(aggregateUsage(details.results));
954
- if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
955
- }
956
- if (!expanded) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
957
- return new Text(text, 0, 0);
958
- }
959
-
960
- const text = result.content[0];
961
- return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
962
- },
963
- });
964
- }
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 { AgentToolResult } from "@earendil-works/pi-agent-core";
20
+ import type { Message } from "@earendil-works/pi-ai";
21
+ import { StringEnum } from "@earendil-works/pi-ai";
22
+ import { type ExtensionAPI, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
23
+ import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
24
+ import { Type } from "@sinclair/typebox";
25
+ import { type AgentConfig, type AgentScope, discoverAgents } from "./agents.js";
26
+
27
+ const MAX_PARALLEL_TASKS = 8;
28
+ const MAX_CONCURRENCY = 4;
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(
39
+ usage: {
40
+ input: number;
41
+ output: number;
42
+ cacheRead: number;
43
+ cacheWrite: number;
44
+ cost: number;
45
+ contextTokens?: number;
46
+ turns?: number;
47
+ },
48
+ model?: string,
49
+ ): string {
50
+ const parts: string[] = [];
51
+ if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
52
+ if (usage.input) parts.push(`↑${formatTokens(usage.input)}`);
53
+ if (usage.output) parts.push(`↓${formatTokens(usage.output)}`);
54
+ if (usage.cacheRead) parts.push(`R${formatTokens(usage.cacheRead)}`);
55
+ if (usage.cacheWrite) parts.push(`W${formatTokens(usage.cacheWrite)}`);
56
+ if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`);
57
+ if (usage.contextTokens && usage.contextTokens > 0) {
58
+ parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
59
+ }
60
+ if (model) parts.push(model);
61
+ return parts.join(" ");
62
+ }
63
+
64
+ function formatToolCall(
65
+ toolName: string,
66
+ args: Record<string, unknown>,
67
+ themeFg: (color: any, text: string) => string,
68
+ ): string {
69
+ const shortenPath = (p: string) => {
70
+ const home = os.homedir();
71
+ return p.startsWith(home) ? `~${p.slice(home.length)}` : p;
72
+ };
73
+
74
+ switch (toolName) {
75
+ case "bash": {
76
+ const command = (args.command as string) || "...";
77
+ const preview = command.length > 60 ? `${command.slice(0, 60)}...` : command;
78
+ return themeFg("muted", "$ ") + themeFg("toolOutput", preview);
79
+ }
80
+ case "read": {
81
+ const rawPath = (args.file_path || args.path || "...") as string;
82
+ const filePath = shortenPath(rawPath);
83
+ const offset = args.offset as number | undefined;
84
+ const limit = args.limit as number | undefined;
85
+ let text = themeFg("accent", filePath);
86
+ if (offset !== undefined || limit !== undefined) {
87
+ const startLine = offset ?? 1;
88
+ const endLine = limit !== undefined ? startLine + limit - 1 : "";
89
+ text += themeFg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`);
90
+ }
91
+ return themeFg("muted", "read ") + text;
92
+ }
93
+ case "write": {
94
+ const rawPath = (args.file_path || args.path || "...") as string;
95
+ const filePath = shortenPath(rawPath);
96
+ const content = (args.content || "") as string;
97
+ const lines = content.split("\n").length;
98
+ let text = themeFg("muted", "write ") + themeFg("accent", filePath);
99
+ if (lines > 1) text += themeFg("dim", ` (${lines} lines)`);
100
+ return text;
101
+ }
102
+ case "edit": {
103
+ const rawPath = (args.file_path || args.path || "...") as string;
104
+ return themeFg("muted", "edit ") + themeFg("accent", shortenPath(rawPath));
105
+ }
106
+ case "ls": {
107
+ const rawPath = (args.path || ".") as string;
108
+ return themeFg("muted", "ls ") + themeFg("accent", shortenPath(rawPath));
109
+ }
110
+ case "find": {
111
+ const pattern = (args.pattern || "*") as string;
112
+ const rawPath = (args.path || ".") as string;
113
+ return themeFg("muted", "find ") + themeFg("accent", pattern) + themeFg("dim", ` in ${shortenPath(rawPath)}`);
114
+ }
115
+ case "grep": {
116
+ const pattern = (args.pattern || "") as string;
117
+ const rawPath = (args.path || ".") as string;
118
+ return (
119
+ themeFg("muted", "grep ") +
120
+ themeFg("accent", `/${pattern}/`) +
121
+ themeFg("dim", ` in ${shortenPath(rawPath)}`)
122
+ );
123
+ }
124
+ default: {
125
+ const argsStr = JSON.stringify(args);
126
+ const preview = argsStr.length > 50 ? `${argsStr.slice(0, 50)}...` : argsStr;
127
+ return themeFg("accent", toolName) + themeFg("dim", ` ${preview}`);
128
+ }
129
+ }
130
+ }
131
+
132
+ interface UsageStats {
133
+ input: number;
134
+ output: number;
135
+ cacheRead: number;
136
+ cacheWrite: number;
137
+ cost: number;
138
+ contextTokens: number;
139
+ turns: number;
140
+ }
141
+
142
+ interface SingleResult {
143
+ agent: string;
144
+ agentSource: "user" | "project" | "unknown";
145
+ task: string;
146
+ exitCode: number;
147
+ messages: Message[];
148
+ stderr: string;
149
+ usage: UsageStats;
150
+ model?: string;
151
+ stopReason?: string;
152
+ errorMessage?: string;
153
+ step?: number;
154
+ }
155
+
156
+ interface SubagentDetails {
157
+ mode: "single" | "parallel" | "chain";
158
+ agentScope: AgentScope;
159
+ projectAgentsDir: string | null;
160
+ results: SingleResult[];
161
+ }
162
+
163
+ function getFinalOutput(messages: Message[]): string {
164
+ for (let i = messages.length - 1; i >= 0; i--) {
165
+ const msg = messages[i];
166
+ if (msg.role === "assistant") {
167
+ for (const part of msg.content) {
168
+ if (part.type === "text") return part.text;
169
+ }
170
+ }
171
+ }
172
+ return "";
173
+ }
174
+
175
+ type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record<string, any> };
176
+
177
+ function getDisplayItems(messages: Message[]): DisplayItem[] {
178
+ const items: DisplayItem[] = [];
179
+ for (const msg of messages) {
180
+ if (msg.role === "assistant") {
181
+ for (const part of msg.content) {
182
+ if (part.type === "text") items.push({ type: "text", text: part.text });
183
+ else if (part.type === "toolCall") items.push({ type: "toolCall", name: part.name, args: part.arguments });
184
+ }
185
+ }
186
+ }
187
+ return items;
188
+ }
189
+
190
+ async function mapWithConcurrencyLimit<TIn, TOut>(
191
+ items: TIn[],
192
+ concurrency: number,
193
+ fn: (item: TIn, index: number) => Promise<TOut>,
194
+ ): Promise<TOut[]> {
195
+ if (items.length === 0) return [];
196
+ const limit = Math.max(1, Math.min(concurrency, items.length));
197
+ const results: TOut[] = new Array(items.length);
198
+ let nextIndex = 0;
199
+ const workers = new Array(limit).fill(null).map(async () => {
200
+ while (true) {
201
+ const current = nextIndex++;
202
+ if (current >= items.length) return;
203
+ results[current] = await fn(items[current], current);
204
+ }
205
+ });
206
+ await Promise.all(workers);
207
+ return results;
208
+ }
209
+
210
+ function writePromptToTempFile(agentName: string, prompt: string): { dir: string; filePath: string } {
211
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
212
+ const safeName = agentName.replace(/[^\w.-]+/g, "_");
213
+ const filePath = path.join(tmpDir, `prompt-${safeName}.md`);
214
+ fs.writeFileSync(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
215
+ return { dir: tmpDir, filePath };
216
+ }
217
+
218
+ type OnUpdateCallback = (partial: AgentToolResult<SubagentDetails>) => void;
219
+
220
+ async function runSingleAgent(
221
+ defaultCwd: string,
222
+ agents: AgentConfig[],
223
+ agentName: string,
224
+ task: string,
225
+ cwd: string | undefined,
226
+ step: number | undefined,
227
+ signal: AbortSignal | undefined,
228
+ onUpdate: OnUpdateCallback | undefined,
229
+ makeDetails: (results: SingleResult[]) => SubagentDetails,
230
+ ): Promise<SingleResult> {
231
+ const agent = agents.find((a) => a.name === agentName);
232
+
233
+ if (!agent) {
234
+ const available = agents.map((a) => `"${a.name}"`).join(", ") || "none";
235
+ return {
236
+ agent: agentName,
237
+ agentSource: "unknown",
238
+ task,
239
+ exitCode: 1,
240
+ messages: [],
241
+ stderr: `Unknown agent: "${agentName}". Available agents: ${available}.`,
242
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
243
+ step,
244
+ };
245
+ }
246
+
247
+ const args: string[] = ["--mode", "json", "-p", "--no-session"];
248
+ if (agent.model) args.push("--model", agent.model);
249
+ if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
250
+
251
+ let tmpPromptDir: string | null = null;
252
+ let tmpPromptPath: string | null = null;
253
+
254
+ const currentResult: SingleResult = {
255
+ agent: agentName,
256
+ agentSource: agent.source,
257
+ task,
258
+ exitCode: 0,
259
+ messages: [],
260
+ stderr: "",
261
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
262
+ model: agent.model,
263
+ step,
264
+ };
265
+
266
+ const emitUpdate = () => {
267
+ if (onUpdate) {
268
+ onUpdate({
269
+ content: [{ type: "text", text: getFinalOutput(currentResult.messages) || "(running...)" }],
270
+ details: makeDetails([currentResult]),
271
+ });
272
+ }
273
+ };
274
+
275
+ try {
276
+ if (agent.systemPrompt.trim()) {
277
+ const tmp = writePromptToTempFile(agent.name, agent.systemPrompt);
278
+ tmpPromptDir = tmp.dir;
279
+ tmpPromptPath = tmp.filePath;
280
+ args.push("--append-system-prompt", tmpPromptPath);
281
+ }
282
+
283
+ args.push(`Task: ${task}`);
284
+ let wasAborted = false;
285
+
286
+ const exitCode = await new Promise<number>((resolve) => {
287
+ const proc = spawn("pi", args, { cwd: cwd ?? defaultCwd, shell: false, stdio: ["ignore", "pipe", "pipe"] });
288
+ let buffer = "";
289
+
290
+ const processLine = (line: string) => {
291
+ if (!line.trim()) return;
292
+ let event: any;
293
+ try {
294
+ event = JSON.parse(line);
295
+ } catch {
296
+ return;
297
+ }
298
+
299
+ if (event.type === "message_end" && event.message) {
300
+ const msg = event.message as Message;
301
+ currentResult.messages.push(msg);
302
+
303
+ if (msg.role === "assistant") {
304
+ currentResult.usage.turns++;
305
+ const usage = msg.usage;
306
+ if (usage) {
307
+ currentResult.usage.input += usage.input || 0;
308
+ currentResult.usage.output += usage.output || 0;
309
+ currentResult.usage.cacheRead += usage.cacheRead || 0;
310
+ currentResult.usage.cacheWrite += usage.cacheWrite || 0;
311
+ currentResult.usage.cost += usage.cost?.total || 0;
312
+ currentResult.usage.contextTokens = usage.totalTokens || 0;
313
+ }
314
+ if (!currentResult.model && msg.model) currentResult.model = msg.model;
315
+ if (msg.stopReason) currentResult.stopReason = msg.stopReason;
316
+ if (msg.errorMessage) currentResult.errorMessage = msg.errorMessage;
317
+ }
318
+ emitUpdate();
319
+ }
320
+
321
+ if (event.type === "tool_result_end" && event.message) {
322
+ currentResult.messages.push(event.message as Message);
323
+ emitUpdate();
324
+ }
325
+ };
326
+
327
+ proc.stdout.on("data", (data) => {
328
+ buffer += data.toString();
329
+ const lines = buffer.split("\n");
330
+ buffer = lines.pop() || "";
331
+ for (const line of lines) processLine(line);
332
+ });
333
+
334
+ proc.stderr.on("data", (data) => {
335
+ currentResult.stderr += data.toString();
336
+ });
337
+
338
+ proc.on("close", (code) => {
339
+ if (buffer.trim()) processLine(buffer);
340
+ resolve(code ?? 0);
341
+ });
342
+
343
+ proc.on("error", () => {
344
+ resolve(1);
345
+ });
346
+
347
+ if (signal) {
348
+ const killProc = () => {
349
+ wasAborted = true;
350
+ proc.kill("SIGTERM");
351
+ setTimeout(() => {
352
+ if (!proc.killed) proc.kill("SIGKILL");
353
+ }, 5000);
354
+ };
355
+ if (signal.aborted) killProc();
356
+ else signal.addEventListener("abort", killProc, { once: true });
357
+ }
358
+ });
359
+
360
+ currentResult.exitCode = exitCode;
361
+ if (wasAborted) throw new Error("Subagent was aborted");
362
+ return currentResult;
363
+ } finally {
364
+ if (tmpPromptPath)
365
+ try {
366
+ fs.unlinkSync(tmpPromptPath);
367
+ } catch {
368
+ /* ignore */
369
+ }
370
+ if (tmpPromptDir)
371
+ try {
372
+ fs.rmdirSync(tmpPromptDir);
373
+ } catch {
374
+ /* ignore */
375
+ }
376
+ }
377
+ }
378
+
379
+ const TaskItem = Type.Object({
380
+ agent: Type.String({ description: "Name of the agent to invoke" }),
381
+ task: Type.String({ description: "Task to delegate to the agent" }),
382
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
383
+ });
384
+
385
+ const ChainItem = Type.Object({
386
+ agent: Type.String({ description: "Name of the agent to invoke" }),
387
+ task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
388
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
389
+ });
390
+
391
+ const AgentScopeSchema = StringEnum(["user", "project", "both"] as const, {
392
+ description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
393
+ default: "user",
394
+ });
395
+
396
+ const SubagentParams = Type.Object({
397
+ agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })),
398
+ task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })),
399
+ tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
400
+ chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })),
401
+ agentScope: Type.Optional(AgentScopeSchema),
402
+ confirmProjectAgents: Type.Optional(
403
+ Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true }),
404
+ ),
405
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
406
+ });
407
+
408
+ export default function (pi: ExtensionAPI) {
409
+ pi.registerTool({
410
+ name: "subagent",
411
+ label: "Subagent",
412
+ description: [
413
+ "Delegate tasks to specialized subagents with isolated context.",
414
+ "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).",
415
+ 'Default agent scope is "user" (from ~/.pi/agent/agents).',
416
+ 'To enable project-local agents in .pi/agents, set agentScope: "both" (or "project").',
417
+ ].join(" "),
418
+ parameters: SubagentParams,
419
+
420
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
421
+ const agentScope: AgentScope = params.agentScope ?? "user";
422
+ const discovery = discoverAgents(ctx.cwd, agentScope);
423
+ const agents = discovery.agents;
424
+ const confirmProjectAgents = params.confirmProjectAgents ?? true;
425
+
426
+ const hasChain = (params.chain?.length ?? 0) > 0;
427
+ const hasTasks = (params.tasks?.length ?? 0) > 0;
428
+ const hasSingle = Boolean(params.agent && params.task);
429
+ const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle);
430
+
431
+ const makeDetails =
432
+ (mode: "single" | "parallel" | "chain") =>
433
+ (results: SingleResult[]): SubagentDetails => ({
434
+ mode,
435
+ agentScope,
436
+ projectAgentsDir: discovery.projectAgentsDir,
437
+ results,
438
+ });
439
+
440
+ if (modeCount !== 1) {
441
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
442
+ return {
443
+ content: [
444
+ {
445
+ type: "text",
446
+ text: `Invalid parameters. Provide exactly one mode.\nAvailable agents: ${available}`,
447
+ },
448
+ ],
449
+ details: makeDetails("single")([]),
450
+ };
451
+ }
452
+
453
+ if ((agentScope === "project" || agentScope === "both") && confirmProjectAgents && ctx.hasUI) {
454
+ const requestedAgentNames = new Set<string>();
455
+ if (params.chain) for (const step of params.chain) requestedAgentNames.add(step.agent);
456
+ if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent);
457
+ if (params.agent) requestedAgentNames.add(params.agent);
458
+
459
+ const projectAgentsRequested = Array.from(requestedAgentNames)
460
+ .map((name) => agents.find((a) => a.name === name))
461
+ .filter((a): a is AgentConfig => a?.source === "project");
462
+
463
+ if (projectAgentsRequested.length > 0) {
464
+ const names = projectAgentsRequested.map((a) => a.name).join(", ");
465
+ const dir = discovery.projectAgentsDir ?? "(unknown)";
466
+ const ok = await ctx.ui.confirm(
467
+ "Run project-local agents?",
468
+ `Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
469
+ );
470
+ if (!ok)
471
+ return {
472
+ content: [{ type: "text", text: "Canceled: project-local agents not approved." }],
473
+ details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]),
474
+ };
475
+ }
476
+ }
477
+
478
+ if (params.chain && params.chain.length > 0) {
479
+ const results: SingleResult[] = [];
480
+ let previousOutput = "";
481
+
482
+ for (let i = 0; i < params.chain.length; i++) {
483
+ const step = params.chain[i];
484
+ const taskWithContext = step.task.replace(/\{previous\}/g, previousOutput);
485
+
486
+ // Create update callback that includes all previous results
487
+ const chainUpdate: OnUpdateCallback | undefined = onUpdate
488
+ ? (partial) => {
489
+ // Combine completed results with current streaming result
490
+ const currentResult = partial.details?.results[0];
491
+ if (currentResult) {
492
+ const allResults = [...results, currentResult];
493
+ onUpdate({
494
+ content: partial.content,
495
+ details: makeDetails("chain")(allResults),
496
+ });
497
+ }
498
+ }
499
+ : undefined;
500
+
501
+ const result = await runSingleAgent(
502
+ ctx.cwd,
503
+ agents,
504
+ step.agent,
505
+ taskWithContext,
506
+ step.cwd,
507
+ i + 1,
508
+ signal,
509
+ chainUpdate,
510
+ makeDetails("chain"),
511
+ );
512
+ results.push(result);
513
+
514
+ const isError =
515
+ result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
516
+ if (isError) {
517
+ const errorMsg =
518
+ result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
519
+ return {
520
+ content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` }],
521
+ details: makeDetails("chain")(results),
522
+ isError: true,
523
+ };
524
+ }
525
+ previousOutput = getFinalOutput(result.messages);
526
+ }
527
+ return {
528
+ content: [{ type: "text", text: getFinalOutput(results[results.length - 1].messages) || "(no output)" }],
529
+ details: makeDetails("chain")(results),
530
+ };
531
+ }
532
+
533
+ if (params.tasks && params.tasks.length > 0) {
534
+ if (params.tasks.length > MAX_PARALLEL_TASKS)
535
+ return {
536
+ content: [
537
+ {
538
+ type: "text",
539
+ text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.`,
540
+ },
541
+ ],
542
+ details: makeDetails("parallel")([]),
543
+ };
544
+
545
+ // Track all results for streaming updates
546
+ const allResults: SingleResult[] = new Array(params.tasks.length);
547
+
548
+ // Initialize placeholder results
549
+ for (let i = 0; i < params.tasks.length; i++) {
550
+ allResults[i] = {
551
+ agent: params.tasks[i].agent,
552
+ agentSource: "unknown",
553
+ task: params.tasks[i].task,
554
+ exitCode: -1, // -1 = still running
555
+ messages: [],
556
+ stderr: "",
557
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
558
+ };
559
+ }
560
+
561
+ const emitParallelUpdate = () => {
562
+ if (onUpdate) {
563
+ const running = allResults.filter((r) => r.exitCode === -1).length;
564
+ const done = allResults.filter((r) => r.exitCode !== -1).length;
565
+ onUpdate({
566
+ content: [
567
+ { type: "text", text: `Parallel: ${done}/${allResults.length} done, ${running} running...` },
568
+ ],
569
+ details: makeDetails("parallel")([...allResults]),
570
+ });
571
+ }
572
+ };
573
+
574
+ const results = await mapWithConcurrencyLimit(params.tasks, MAX_CONCURRENCY, async (t, index) => {
575
+ const result = await runSingleAgent(
576
+ ctx.cwd,
577
+ agents,
578
+ t.agent,
579
+ t.task,
580
+ t.cwd,
581
+ undefined,
582
+ signal,
583
+ // Per-task update callback
584
+ (partial) => {
585
+ if (partial.details?.results[0]) {
586
+ allResults[index] = partial.details.results[0];
587
+ emitParallelUpdate();
588
+ }
589
+ },
590
+ makeDetails("parallel"),
591
+ );
592
+ allResults[index] = result;
593
+ emitParallelUpdate();
594
+ return result;
595
+ });
596
+
597
+ const successCount = results.filter((r) => r.exitCode === 0).length;
598
+ const summaries = results.map((r) => {
599
+ const output = getFinalOutput(r.messages);
600
+ const preview = output.slice(0, 100) + (output.length > 100 ? "..." : "");
601
+ return `[${r.agent}] ${r.exitCode === 0 ? "completed" : "failed"}: ${preview || "(no output)"}`;
602
+ });
603
+ return {
604
+ content: [
605
+ {
606
+ type: "text",
607
+ text: `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n")}`,
608
+ },
609
+ ],
610
+ details: makeDetails("parallel")(results),
611
+ };
612
+ }
613
+
614
+ if (params.agent && params.task) {
615
+ const result = await runSingleAgent(
616
+ ctx.cwd,
617
+ agents,
618
+ params.agent,
619
+ params.task,
620
+ params.cwd,
621
+ undefined,
622
+ signal,
623
+ onUpdate,
624
+ makeDetails("single"),
625
+ );
626
+ const isError = result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
627
+ if (isError) {
628
+ const errorMsg =
629
+ result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
630
+ return {
631
+ content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }],
632
+ details: makeDetails("single")([result]),
633
+ isError: true,
634
+ };
635
+ }
636
+ return {
637
+ content: [{ type: "text", text: getFinalOutput(result.messages) || "(no output)" }],
638
+ details: makeDetails("single")([result]),
639
+ };
640
+ }
641
+
642
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
643
+ return {
644
+ content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }],
645
+ details: makeDetails("single")([]),
646
+ };
647
+ },
648
+
649
+ renderCall(args, theme) {
650
+ const scope: AgentScope = args.agentScope ?? "user";
651
+ if (args.chain && args.chain.length > 0) {
652
+ let text =
653
+ theme.fg("toolTitle", theme.bold("subagent ")) +
654
+ theme.fg("accent", `chain (${args.chain.length} steps)`) +
655
+ theme.fg("muted", ` [${scope}]`);
656
+ for (let i = 0; i < Math.min(args.chain.length, 3); i++) {
657
+ const step = args.chain[i];
658
+ // Clean up {previous} placeholder for display
659
+ const cleanTask = step.task.replace(/\{previous\}/g, "").trim();
660
+ const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask;
661
+ text +=
662
+ "\n " +
663
+ theme.fg("muted", `${i + 1}.`) +
664
+ " " +
665
+ theme.fg("accent", step.agent) +
666
+ theme.fg("dim", ` ${preview}`);
667
+ }
668
+ if (args.chain.length > 3) text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`;
669
+ return new Text(text, 0, 0);
670
+ }
671
+ if (args.tasks && args.tasks.length > 0) {
672
+ let text =
673
+ theme.fg("toolTitle", theme.bold("subagent ")) +
674
+ theme.fg("accent", `parallel (${args.tasks.length} tasks)`) +
675
+ theme.fg("muted", ` [${scope}]`);
676
+ for (const t of args.tasks.slice(0, 3)) {
677
+ const preview = t.task.length > 40 ? `${t.task.slice(0, 40)}...` : t.task;
678
+ text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", ` ${preview}`)}`;
679
+ }
680
+ if (args.tasks.length > 3) text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`;
681
+ return new Text(text, 0, 0);
682
+ }
683
+ const agentName = args.agent || "...";
684
+ const preview = args.task ? (args.task.length > 60 ? `${args.task.slice(0, 60)}...` : args.task) : "...";
685
+ let text =
686
+ theme.fg("toolTitle", theme.bold("subagent ")) +
687
+ theme.fg("accent", agentName) +
688
+ theme.fg("muted", ` [${scope}]`);
689
+ text += `\n ${theme.fg("dim", preview)}`;
690
+ return new Text(text, 0, 0);
691
+ },
692
+
693
+ renderResult(result, { expanded }, theme) {
694
+ const details = result.details as SubagentDetails | undefined;
695
+ if (!details || details.results.length === 0) {
696
+ const text = result.content[0];
697
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
698
+ }
699
+
700
+ const mdTheme = getMarkdownTheme();
701
+
702
+ const renderDisplayItems = (items: DisplayItem[], limit?: number) => {
703
+ const toShow = limit ? items.slice(-limit) : items;
704
+ const skipped = limit && items.length > limit ? items.length - limit : 0;
705
+ let text = "";
706
+ if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`);
707
+ for (const item of toShow) {
708
+ if (item.type === "text") {
709
+ const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n");
710
+ text += `${theme.fg("toolOutput", preview)}\n`;
711
+ } else {
712
+ text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme))}\n`;
713
+ }
714
+ }
715
+ return text.trimEnd();
716
+ };
717
+
718
+ if (details.mode === "single" && details.results.length === 1) {
719
+ const r = details.results[0];
720
+ const isError = r.exitCode !== 0 || r.stopReason === "error" || r.stopReason === "aborted";
721
+ const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
722
+ const displayItems = getDisplayItems(r.messages);
723
+ const finalOutput = getFinalOutput(r.messages);
724
+
725
+ if (expanded) {
726
+ const container = new Container();
727
+ let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
728
+ if (isError && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
729
+ container.addChild(new Text(header, 0, 0));
730
+ if (isError && r.errorMessage)
731
+ container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
732
+ container.addChild(new Spacer(1));
733
+ container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
734
+ container.addChild(new Text(theme.fg("dim", r.task), 0, 0));
735
+ container.addChild(new Spacer(1));
736
+ container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
737
+ if (displayItems.length === 0 && !finalOutput) {
738
+ container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
739
+ } else {
740
+ for (const item of displayItems) {
741
+ if (item.type === "toolCall")
742
+ container.addChild(
743
+ new Text(
744
+ theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
745
+ 0,
746
+ 0,
747
+ ),
748
+ );
749
+ }
750
+ if (finalOutput) {
751
+ container.addChild(new Spacer(1));
752
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
753
+ }
754
+ }
755
+ const usageStr = formatUsageStats(r.usage, r.model);
756
+ if (usageStr) {
757
+ container.addChild(new Spacer(1));
758
+ container.addChild(new Text(theme.fg("dim", usageStr), 0, 0));
759
+ }
760
+ return container;
761
+ }
762
+
763
+ let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
764
+ if (isError && r.stopReason) text += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
765
+ if (isError && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`;
766
+ else if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
767
+ else {
768
+ text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`;
769
+ if (displayItems.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
770
+ }
771
+ const usageStr = formatUsageStats(r.usage, r.model);
772
+ if (usageStr) text += `\n${theme.fg("dim", usageStr)}`;
773
+ return new Text(text, 0, 0);
774
+ }
775
+
776
+ const aggregateUsage = (results: SingleResult[]) => {
777
+ const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
778
+ for (const r of results) {
779
+ total.input += r.usage.input;
780
+ total.output += r.usage.output;
781
+ total.cacheRead += r.usage.cacheRead;
782
+ total.cacheWrite += r.usage.cacheWrite;
783
+ total.cost += r.usage.cost;
784
+ total.turns += r.usage.turns;
785
+ }
786
+ return total;
787
+ };
788
+
789
+ if (details.mode === "chain") {
790
+ const successCount = details.results.filter((r) => r.exitCode === 0).length;
791
+ const icon = successCount === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
792
+
793
+ if (expanded) {
794
+ const container = new Container();
795
+ container.addChild(
796
+ new Text(
797
+ icon +
798
+ " " +
799
+ theme.fg("toolTitle", theme.bold("chain ")) +
800
+ theme.fg("accent", `${successCount}/${details.results.length} steps`),
801
+ 0,
802
+ 0,
803
+ ),
804
+ );
805
+
806
+ for (const r of details.results) {
807
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
808
+ const displayItems = getDisplayItems(r.messages);
809
+ const finalOutput = getFinalOutput(r.messages);
810
+
811
+ container.addChild(new Spacer(1));
812
+ container.addChild(
813
+ new Text(
814
+ `${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`,
815
+ 0,
816
+ 0,
817
+ ),
818
+ );
819
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
820
+
821
+ // Show tool calls
822
+ for (const item of displayItems) {
823
+ if (item.type === "toolCall") {
824
+ container.addChild(
825
+ new Text(
826
+ theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
827
+ 0,
828
+ 0,
829
+ ),
830
+ );
831
+ }
832
+ }
833
+
834
+ // Show final output as markdown
835
+ if (finalOutput) {
836
+ container.addChild(new Spacer(1));
837
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
838
+ }
839
+
840
+ const stepUsage = formatUsageStats(r.usage, r.model);
841
+ if (stepUsage) container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0));
842
+ }
843
+
844
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
845
+ if (usageStr) {
846
+ container.addChild(new Spacer(1));
847
+ container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
848
+ }
849
+ return container;
850
+ }
851
+
852
+ // Collapsed view
853
+ let text =
854
+ icon +
855
+ " " +
856
+ theme.fg("toolTitle", theme.bold("chain ")) +
857
+ theme.fg("accent", `${successCount}/${details.results.length} steps`);
858
+ for (const r of details.results) {
859
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
860
+ const displayItems = getDisplayItems(r.messages);
861
+ text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`;
862
+ if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
863
+ else text += `\n${renderDisplayItems(displayItems, 5)}`;
864
+ }
865
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
866
+ if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
867
+ text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
868
+ return new Text(text, 0, 0);
869
+ }
870
+
871
+ if (details.mode === "parallel") {
872
+ const running = details.results.filter((r) => r.exitCode === -1).length;
873
+ const successCount = details.results.filter((r) => r.exitCode === 0).length;
874
+ const failCount = details.results.filter((r) => r.exitCode > 0).length;
875
+ const isRunning = running > 0;
876
+ const icon = isRunning
877
+ ? theme.fg("warning", "⏳")
878
+ : failCount > 0
879
+ ? theme.fg("warning", "◐")
880
+ : theme.fg("success", "✓");
881
+ const status = isRunning
882
+ ? `${successCount + failCount}/${details.results.length} done, ${running} running`
883
+ : `${successCount}/${details.results.length} tasks`;
884
+
885
+ if (expanded && !isRunning) {
886
+ const container = new Container();
887
+ container.addChild(
888
+ new Text(
889
+ `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`,
890
+ 0,
891
+ 0,
892
+ ),
893
+ );
894
+
895
+ for (const r of details.results) {
896
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
897
+ const displayItems = getDisplayItems(r.messages);
898
+ const finalOutput = getFinalOutput(r.messages);
899
+
900
+ container.addChild(new Spacer(1));
901
+ container.addChild(
902
+ new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0),
903
+ );
904
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
905
+
906
+ // Show tool calls
907
+ for (const item of displayItems) {
908
+ if (item.type === "toolCall") {
909
+ container.addChild(
910
+ new Text(
911
+ theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
912
+ 0,
913
+ 0,
914
+ ),
915
+ );
916
+ }
917
+ }
918
+
919
+ // Show final output as markdown
920
+ if (finalOutput) {
921
+ container.addChild(new Spacer(1));
922
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
923
+ }
924
+
925
+ const taskUsage = formatUsageStats(r.usage, r.model);
926
+ if (taskUsage) container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0));
927
+ }
928
+
929
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
930
+ if (usageStr) {
931
+ container.addChild(new Spacer(1));
932
+ container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
933
+ }
934
+ return container;
935
+ }
936
+
937
+ // Collapsed view (or still running)
938
+ let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`;
939
+ for (const r of details.results) {
940
+ const rIcon =
941
+ r.exitCode === -1
942
+ ? theme.fg("warning", "⏳")
943
+ : r.exitCode === 0
944
+ ? theme.fg("success", "✓")
945
+ : theme.fg("error", "✗");
946
+ const displayItems = getDisplayItems(r.messages);
947
+ text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
948
+ if (displayItems.length === 0)
949
+ text += `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}`;
950
+ else text += `\n${renderDisplayItems(displayItems, 5)}`;
951
+ }
952
+ if (!isRunning) {
953
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
954
+ if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
955
+ }
956
+ if (!expanded) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
957
+ return new Text(text, 0, 0);
958
+ }
959
+
960
+ const text = result.content[0];
961
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
962
+ },
963
+ });
964
+ }