@mrquake/quakecode-cli 0.64.0 → 0.64.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 (180) hide show
  1. package/dist/bun/cli.d.ts.map +1 -1
  2. package/dist/bun/cli.js +1 -1
  3. package/dist/bun/cli.js.map +1 -1
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/config.js +7 -10
  6. package/dist/config.js.map +1 -1
  7. package/dist/core/extensions/loader.d.ts.map +1 -1
  8. package/dist/core/extensions/loader.js +21 -7
  9. package/dist/core/extensions/loader.js.map +1 -1
  10. package/dist/core/settings-manager.d.ts.map +1 -1
  11. package/dist/core/settings-manager.js +2 -2
  12. package/dist/core/settings-manager.js.map +1 -1
  13. package/dist/core/slash-commands.d.ts.map +1 -1
  14. package/dist/core/slash-commands.js +1 -1
  15. package/dist/core/slash-commands.js.map +1 -1
  16. package/dist/core/system-prompt.d.ts.map +1 -1
  17. package/dist/core/system-prompt.js +5 -5
  18. package/dist/core/system-prompt.js.map +1 -1
  19. package/dist/main.d.ts.map +1 -1
  20. package/dist/main.js +7 -7
  21. package/dist/main.js.map +1 -1
  22. package/dist/migrations.d.ts.map +1 -1
  23. package/dist/migrations.js +2 -2
  24. package/dist/migrations.js.map +1 -1
  25. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  26. package/dist/modes/interactive/components/config-selector.js +1 -1
  27. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  28. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  29. package/dist/modes/interactive/components/session-selector.js +82 -105
  30. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  31. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  32. package/dist/modes/interactive/interactive-mode.js +10 -5
  33. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  34. package/dist/utils/clipboard-image.d.ts.map +1 -1
  35. package/dist/utils/clipboard-image.js +3 -3
  36. package/dist/utils/clipboard-image.js.map +1 -1
  37. package/package.json +14 -7
  38. package/docs/compaction.md +0 -394
  39. package/docs/custom-provider.md +0 -596
  40. package/docs/development.md +0 -71
  41. package/docs/extensions.md +0 -2286
  42. package/docs/images/doom-extension.png +0 -0
  43. package/docs/images/exy.png +0 -0
  44. package/docs/images/interactive-mode.png +0 -0
  45. package/docs/images/tree-view.png +0 -0
  46. package/docs/json.md +0 -82
  47. package/docs/keybindings.md +0 -175
  48. package/docs/models.md +0 -341
  49. package/docs/packages.md +0 -218
  50. package/docs/prompt-templates.md +0 -67
  51. package/docs/providers.md +0 -195
  52. package/docs/rpc.md +0 -1377
  53. package/docs/sdk.md +0 -1064
  54. package/docs/session.md +0 -412
  55. package/docs/settings.md +0 -246
  56. package/docs/shell-aliases.md +0 -13
  57. package/docs/skills.md +0 -232
  58. package/docs/terminal-setup.md +0 -106
  59. package/docs/termux.md +0 -127
  60. package/docs/themes.md +0 -295
  61. package/docs/tmux.md +0 -61
  62. package/docs/tree.md +0 -231
  63. package/docs/tui.md +0 -887
  64. package/docs/windows.md +0 -17
  65. package/examples/README.md +0 -25
  66. package/examples/extensions/README.md +0 -206
  67. package/examples/extensions/antigravity-image-gen.ts +0 -418
  68. package/examples/extensions/auto-commit-on-exit.ts +0 -49
  69. package/examples/extensions/bash-spawn-hook.ts +0 -30
  70. package/examples/extensions/bookmark.ts +0 -50
  71. package/examples/extensions/built-in-tool-renderer.ts +0 -246
  72. package/examples/extensions/claude-rules.ts +0 -86
  73. package/examples/extensions/commands.ts +0 -72
  74. package/examples/extensions/confirm-destructive.ts +0 -59
  75. package/examples/extensions/custom-compaction.ts +0 -127
  76. package/examples/extensions/custom-footer.ts +0 -64
  77. package/examples/extensions/custom-header.ts +0 -73
  78. package/examples/extensions/custom-provider-anthropic/index.ts +0 -604
  79. package/examples/extensions/custom-provider-anthropic/package-lock.json +0 -24
  80. package/examples/extensions/custom-provider-anthropic/package.json +0 -19
  81. package/examples/extensions/custom-provider-gitlab-duo/index.ts +0 -349
  82. package/examples/extensions/custom-provider-gitlab-duo/package.json +0 -16
  83. package/examples/extensions/custom-provider-gitlab-duo/test.ts +0 -82
  84. package/examples/extensions/custom-provider-qwen-cli/index.ts +0 -345
  85. package/examples/extensions/custom-provider-qwen-cli/package.json +0 -16
  86. package/examples/extensions/dirty-repo-guard.ts +0 -56
  87. package/examples/extensions/doom-overlay/README.md +0 -46
  88. package/examples/extensions/doom-overlay/doom/build/doom.js +0 -21
  89. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  90. package/examples/extensions/doom-overlay/doom/build.sh +0 -152
  91. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +0 -72
  92. package/examples/extensions/doom-overlay/doom-component.ts +0 -132
  93. package/examples/extensions/doom-overlay/doom-engine.ts +0 -173
  94. package/examples/extensions/doom-overlay/doom-keys.ts +0 -104
  95. package/examples/extensions/doom-overlay/index.ts +0 -74
  96. package/examples/extensions/doom-overlay/wad-finder.ts +0 -51
  97. package/examples/extensions/dynamic-resources/SKILL.md +0 -8
  98. package/examples/extensions/dynamic-resources/dynamic.json +0 -79
  99. package/examples/extensions/dynamic-resources/dynamic.md +0 -5
  100. package/examples/extensions/dynamic-resources/index.ts +0 -15
  101. package/examples/extensions/dynamic-tools.ts +0 -74
  102. package/examples/extensions/event-bus.ts +0 -43
  103. package/examples/extensions/file-trigger.ts +0 -41
  104. package/examples/extensions/git-checkpoint.ts +0 -53
  105. package/examples/extensions/handoff.ts +0 -153
  106. package/examples/extensions/hello.ts +0 -26
  107. package/examples/extensions/hidden-thinking-label.ts +0 -53
  108. package/examples/extensions/inline-bash.ts +0 -94
  109. package/examples/extensions/input-transform.ts +0 -43
  110. package/examples/extensions/interactive-shell.ts +0 -196
  111. package/examples/extensions/mac-system-theme.ts +0 -47
  112. package/examples/extensions/message-renderer.ts +0 -59
  113. package/examples/extensions/minimal-mode.ts +0 -426
  114. package/examples/extensions/modal-editor.ts +0 -85
  115. package/examples/extensions/model-status.ts +0 -31
  116. package/examples/extensions/notify.ts +0 -55
  117. package/examples/extensions/overlay-qa-tests.ts +0 -1348
  118. package/examples/extensions/overlay-test.ts +0 -150
  119. package/examples/extensions/permission-gate.ts +0 -34
  120. package/examples/extensions/pirate.ts +0 -47
  121. package/examples/extensions/plan-mode/README.md +0 -65
  122. package/examples/extensions/plan-mode/index.ts +0 -340
  123. package/examples/extensions/plan-mode/utils.ts +0 -168
  124. package/examples/extensions/preset.ts +0 -397
  125. package/examples/extensions/protected-paths.ts +0 -30
  126. package/examples/extensions/provider-payload.ts +0 -14
  127. package/examples/extensions/qna.ts +0 -122
  128. package/examples/extensions/question.ts +0 -264
  129. package/examples/extensions/questionnaire.ts +0 -427
  130. package/examples/extensions/rainbow-editor.ts +0 -88
  131. package/examples/extensions/reload-runtime.ts +0 -37
  132. package/examples/extensions/rpc-demo.ts +0 -118
  133. package/examples/extensions/sandbox/index.ts +0 -321
  134. package/examples/extensions/sandbox/package-lock.json +0 -92
  135. package/examples/extensions/sandbox/package.json +0 -19
  136. package/examples/extensions/send-user-message.ts +0 -97
  137. package/examples/extensions/session-name.ts +0 -27
  138. package/examples/extensions/shutdown-command.ts +0 -63
  139. package/examples/extensions/snake.ts +0 -343
  140. package/examples/extensions/space-invaders.ts +0 -560
  141. package/examples/extensions/ssh.ts +0 -220
  142. package/examples/extensions/status-line.ts +0 -32
  143. package/examples/extensions/subagent/README.md +0 -172
  144. package/examples/extensions/subagent/agents/planner.md +0 -37
  145. package/examples/extensions/subagent/agents/reviewer.md +0 -35
  146. package/examples/extensions/subagent/agents/scout.md +0 -50
  147. package/examples/extensions/subagent/agents/worker.md +0 -24
  148. package/examples/extensions/subagent/agents.ts +0 -126
  149. package/examples/extensions/subagent/index.ts +0 -986
  150. package/examples/extensions/subagent/prompts/implement-and-review.md +0 -10
  151. package/examples/extensions/subagent/prompts/implement.md +0 -10
  152. package/examples/extensions/subagent/prompts/scout-and-plan.md +0 -9
  153. package/examples/extensions/summarize.ts +0 -206
  154. package/examples/extensions/system-prompt-header.ts +0 -17
  155. package/examples/extensions/timed-confirm.ts +0 -70
  156. package/examples/extensions/titlebar-spinner.ts +0 -58
  157. package/examples/extensions/todo.ts +0 -297
  158. package/examples/extensions/tool-override.ts +0 -144
  159. package/examples/extensions/tools.ts +0 -141
  160. package/examples/extensions/trigger-compact.ts +0 -50
  161. package/examples/extensions/truncated-tool.ts +0 -195
  162. package/examples/extensions/widget-placement.ts +0 -9
  163. package/examples/extensions/with-deps/index.ts +0 -32
  164. package/examples/extensions/with-deps/package-lock.json +0 -31
  165. package/examples/extensions/with-deps/package.json +0 -22
  166. package/examples/rpc-extension-ui.ts +0 -632
  167. package/examples/sdk/01-minimal.ts +0 -22
  168. package/examples/sdk/02-custom-model.ts +0 -49
  169. package/examples/sdk/03-custom-prompt.ts +0 -55
  170. package/examples/sdk/04-skills.ts +0 -52
  171. package/examples/sdk/05-tools.ts +0 -56
  172. package/examples/sdk/06-extensions.ts +0 -88
  173. package/examples/sdk/07-context-files.ts +0 -40
  174. package/examples/sdk/08-prompt-templates.ts +0 -48
  175. package/examples/sdk/09-api-keys-and-oauth.ts +0 -48
  176. package/examples/sdk/10-settings.ts +0 -51
  177. package/examples/sdk/11-sessions.ts +0 -48
  178. package/examples/sdk/12-full-control.ts +0 -81
  179. package/examples/sdk/13-session-runtime.ts +0 -49
  180. package/examples/sdk/README.md +0 -145
@@ -1,986 +0,0 @@
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 "@mariozechner/pi-agent-core";
20
- import type { Message } from "@mariozechner/pi-ai";
21
- import { StringEnum } from "@mariozechner/pi-ai";
22
- import { type ExtensionAPI, getMarkdownTheme, withFileMutationQueue } from "@mariozechner/pi-coding-agent";
23
- import { Container, Markdown, Spacer, Text } from "@mariozechner/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
- async function writePromptToTempFile(agentName: string, prompt: string): Promise<{ dir: string; filePath: string }> {
211
- const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-"));
212
- const safeName = agentName.replace(/[^\w.-]+/g, "_");
213
- const filePath = path.join(tmpDir, `prompt-${safeName}.md`);
214
- await withFileMutationQueue(filePath, async () => {
215
- await fs.promises.writeFile(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
216
- });
217
- return { dir: tmpDir, filePath };
218
- }
219
-
220
- function getPiInvocation(args: string[]): { command: string; args: string[] } {
221
- const currentScript = process.argv[1];
222
- if (currentScript && fs.existsSync(currentScript)) {
223
- return { command: process.execPath, args: [currentScript, ...args] };
224
- }
225
-
226
- const execName = path.basename(process.execPath).toLowerCase();
227
- const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
228
- if (!isGenericRuntime) {
229
- return { command: process.execPath, args };
230
- }
231
-
232
- return { command: "pi", args };
233
- }
234
-
235
- type OnUpdateCallback = (partial: AgentToolResult<SubagentDetails>) => void;
236
-
237
- async function runSingleAgent(
238
- defaultCwd: string,
239
- agents: AgentConfig[],
240
- agentName: string,
241
- task: string,
242
- cwd: string | undefined,
243
- step: number | undefined,
244
- signal: AbortSignal | undefined,
245
- onUpdate: OnUpdateCallback | undefined,
246
- makeDetails: (results: SingleResult[]) => SubagentDetails,
247
- ): Promise<SingleResult> {
248
- const agent = agents.find((a) => a.name === agentName);
249
-
250
- if (!agent) {
251
- const available = agents.map((a) => `"${a.name}"`).join(", ") || "none";
252
- return {
253
- agent: agentName,
254
- agentSource: "unknown",
255
- task,
256
- exitCode: 1,
257
- messages: [],
258
- stderr: `Unknown agent: "${agentName}". Available agents: ${available}.`,
259
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
260
- step,
261
- };
262
- }
263
-
264
- const args: string[] = ["--mode", "json", "-p", "--no-session"];
265
- if (agent.model) args.push("--model", agent.model);
266
- if (agent.tools && agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
267
-
268
- let tmpPromptDir: string | null = null;
269
- let tmpPromptPath: string | null = null;
270
-
271
- const currentResult: SingleResult = {
272
- agent: agentName,
273
- agentSource: agent.source,
274
- task,
275
- exitCode: 0,
276
- messages: [],
277
- stderr: "",
278
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
279
- model: agent.model,
280
- step,
281
- };
282
-
283
- const emitUpdate = () => {
284
- if (onUpdate) {
285
- onUpdate({
286
- content: [{ type: "text", text: getFinalOutput(currentResult.messages) || "(running...)" }],
287
- details: makeDetails([currentResult]),
288
- });
289
- }
290
- };
291
-
292
- try {
293
- if (agent.systemPrompt.trim()) {
294
- const tmp = await writePromptToTempFile(agent.name, agent.systemPrompt);
295
- tmpPromptDir = tmp.dir;
296
- tmpPromptPath = tmp.filePath;
297
- args.push("--append-system-prompt", tmpPromptPath);
298
- }
299
-
300
- args.push(`Task: ${task}`);
301
- let wasAborted = false;
302
-
303
- const exitCode = await new Promise<number>((resolve) => {
304
- const invocation = getPiInvocation(args);
305
- const proc = spawn(invocation.command, invocation.args, {
306
- cwd: cwd ?? defaultCwd,
307
- shell: false,
308
- stdio: ["ignore", "pipe", "pipe"],
309
- });
310
- let buffer = "";
311
-
312
- const processLine = (line: string) => {
313
- if (!line.trim()) return;
314
- let event: any;
315
- try {
316
- event = JSON.parse(line);
317
- } catch {
318
- return;
319
- }
320
-
321
- if (event.type === "message_end" && event.message) {
322
- const msg = event.message as Message;
323
- currentResult.messages.push(msg);
324
-
325
- if (msg.role === "assistant") {
326
- currentResult.usage.turns++;
327
- const usage = msg.usage;
328
- if (usage) {
329
- currentResult.usage.input += usage.input || 0;
330
- currentResult.usage.output += usage.output || 0;
331
- currentResult.usage.cacheRead += usage.cacheRead || 0;
332
- currentResult.usage.cacheWrite += usage.cacheWrite || 0;
333
- currentResult.usage.cost += usage.cost?.total || 0;
334
- currentResult.usage.contextTokens = usage.totalTokens || 0;
335
- }
336
- if (!currentResult.model && msg.model) currentResult.model = msg.model;
337
- if (msg.stopReason) currentResult.stopReason = msg.stopReason;
338
- if (msg.errorMessage) currentResult.errorMessage = msg.errorMessage;
339
- }
340
- emitUpdate();
341
- }
342
-
343
- if (event.type === "tool_result_end" && event.message) {
344
- currentResult.messages.push(event.message as Message);
345
- emitUpdate();
346
- }
347
- };
348
-
349
- proc.stdout.on("data", (data) => {
350
- buffer += data.toString();
351
- const lines = buffer.split("\n");
352
- buffer = lines.pop() || "";
353
- for (const line of lines) processLine(line);
354
- });
355
-
356
- proc.stderr.on("data", (data) => {
357
- currentResult.stderr += data.toString();
358
- });
359
-
360
- proc.on("close", (code) => {
361
- if (buffer.trim()) processLine(buffer);
362
- resolve(code ?? 0);
363
- });
364
-
365
- proc.on("error", () => {
366
- resolve(1);
367
- });
368
-
369
- if (signal) {
370
- const killProc = () => {
371
- wasAborted = true;
372
- proc.kill("SIGTERM");
373
- setTimeout(() => {
374
- if (!proc.killed) proc.kill("SIGKILL");
375
- }, 5000);
376
- };
377
- if (signal.aborted) killProc();
378
- else signal.addEventListener("abort", killProc, { once: true });
379
- }
380
- });
381
-
382
- currentResult.exitCode = exitCode;
383
- if (wasAborted) throw new Error("Subagent was aborted");
384
- return currentResult;
385
- } finally {
386
- if (tmpPromptPath)
387
- try {
388
- fs.unlinkSync(tmpPromptPath);
389
- } catch {
390
- /* ignore */
391
- }
392
- if (tmpPromptDir)
393
- try {
394
- fs.rmdirSync(tmpPromptDir);
395
- } catch {
396
- /* ignore */
397
- }
398
- }
399
- }
400
-
401
- const TaskItem = Type.Object({
402
- agent: Type.String({ description: "Name of the agent to invoke" }),
403
- task: Type.String({ description: "Task to delegate to the agent" }),
404
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
405
- });
406
-
407
- const ChainItem = Type.Object({
408
- agent: Type.String({ description: "Name of the agent to invoke" }),
409
- task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
410
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
411
- });
412
-
413
- const AgentScopeSchema = StringEnum(["user", "project", "both"] as const, {
414
- description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
415
- default: "user",
416
- });
417
-
418
- const SubagentParams = Type.Object({
419
- agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })),
420
- task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })),
421
- tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
422
- chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })),
423
- agentScope: Type.Optional(AgentScopeSchema),
424
- confirmProjectAgents: Type.Optional(
425
- Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true }),
426
- ),
427
- cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
428
- });
429
-
430
- export default function (pi: ExtensionAPI) {
431
- pi.registerTool({
432
- name: "subagent",
433
- label: "Subagent",
434
- description: [
435
- "Delegate tasks to specialized subagents with isolated context.",
436
- "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).",
437
- 'Default agent scope is "user" (from ~/.pi/agent/agents).',
438
- 'To enable project-local agents in .pi/agents, set agentScope: "both" (or "project").',
439
- ].join(" "),
440
- parameters: SubagentParams,
441
-
442
- async execute(_toolCallId, params, signal, onUpdate, ctx) {
443
- const agentScope: AgentScope = params.agentScope ?? "user";
444
- const discovery = discoverAgents(ctx.cwd, agentScope);
445
- const agents = discovery.agents;
446
- const confirmProjectAgents = params.confirmProjectAgents ?? true;
447
-
448
- const hasChain = (params.chain?.length ?? 0) > 0;
449
- const hasTasks = (params.tasks?.length ?? 0) > 0;
450
- const hasSingle = Boolean(params.agent && params.task);
451
- const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle);
452
-
453
- const makeDetails =
454
- (mode: "single" | "parallel" | "chain") =>
455
- (results: SingleResult[]): SubagentDetails => ({
456
- mode,
457
- agentScope,
458
- projectAgentsDir: discovery.projectAgentsDir,
459
- results,
460
- });
461
-
462
- if (modeCount !== 1) {
463
- const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
464
- return {
465
- content: [
466
- {
467
- type: "text",
468
- text: `Invalid parameters. Provide exactly one mode.\nAvailable agents: ${available}`,
469
- },
470
- ],
471
- details: makeDetails("single")([]),
472
- };
473
- }
474
-
475
- if ((agentScope === "project" || agentScope === "both") && confirmProjectAgents && ctx.hasUI) {
476
- const requestedAgentNames = new Set<string>();
477
- if (params.chain) for (const step of params.chain) requestedAgentNames.add(step.agent);
478
- if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent);
479
- if (params.agent) requestedAgentNames.add(params.agent);
480
-
481
- const projectAgentsRequested = Array.from(requestedAgentNames)
482
- .map((name) => agents.find((a) => a.name === name))
483
- .filter((a): a is AgentConfig => a?.source === "project");
484
-
485
- if (projectAgentsRequested.length > 0) {
486
- const names = projectAgentsRequested.map((a) => a.name).join(", ");
487
- const dir = discovery.projectAgentsDir ?? "(unknown)";
488
- const ok = await ctx.ui.confirm(
489
- "Run project-local agents?",
490
- `Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
491
- );
492
- if (!ok)
493
- return {
494
- content: [{ type: "text", text: "Canceled: project-local agents not approved." }],
495
- details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]),
496
- };
497
- }
498
- }
499
-
500
- if (params.chain && params.chain.length > 0) {
501
- const results: SingleResult[] = [];
502
- let previousOutput = "";
503
-
504
- for (let i = 0; i < params.chain.length; i++) {
505
- const step = params.chain[i];
506
- const taskWithContext = step.task.replace(/\{previous\}/g, previousOutput);
507
-
508
- // Create update callback that includes all previous results
509
- const chainUpdate: OnUpdateCallback | undefined = onUpdate
510
- ? (partial) => {
511
- // Combine completed results with current streaming result
512
- const currentResult = partial.details?.results[0];
513
- if (currentResult) {
514
- const allResults = [...results, currentResult];
515
- onUpdate({
516
- content: partial.content,
517
- details: makeDetails("chain")(allResults),
518
- });
519
- }
520
- }
521
- : undefined;
522
-
523
- const result = await runSingleAgent(
524
- ctx.cwd,
525
- agents,
526
- step.agent,
527
- taskWithContext,
528
- step.cwd,
529
- i + 1,
530
- signal,
531
- chainUpdate,
532
- makeDetails("chain"),
533
- );
534
- results.push(result);
535
-
536
- const isError =
537
- result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
538
- if (isError) {
539
- const errorMsg =
540
- result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
541
- return {
542
- content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` }],
543
- details: makeDetails("chain")(results),
544
- isError: true,
545
- };
546
- }
547
- previousOutput = getFinalOutput(result.messages);
548
- }
549
- return {
550
- content: [{ type: "text", text: getFinalOutput(results[results.length - 1].messages) || "(no output)" }],
551
- details: makeDetails("chain")(results),
552
- };
553
- }
554
-
555
- if (params.tasks && params.tasks.length > 0) {
556
- if (params.tasks.length > MAX_PARALLEL_TASKS)
557
- return {
558
- content: [
559
- {
560
- type: "text",
561
- text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.`,
562
- },
563
- ],
564
- details: makeDetails("parallel")([]),
565
- };
566
-
567
- // Track all results for streaming updates
568
- const allResults: SingleResult[] = new Array(params.tasks.length);
569
-
570
- // Initialize placeholder results
571
- for (let i = 0; i < params.tasks.length; i++) {
572
- allResults[i] = {
573
- agent: params.tasks[i].agent,
574
- agentSource: "unknown",
575
- task: params.tasks[i].task,
576
- exitCode: -1, // -1 = still running
577
- messages: [],
578
- stderr: "",
579
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
580
- };
581
- }
582
-
583
- const emitParallelUpdate = () => {
584
- if (onUpdate) {
585
- const running = allResults.filter((r) => r.exitCode === -1).length;
586
- const done = allResults.filter((r) => r.exitCode !== -1).length;
587
- onUpdate({
588
- content: [
589
- { type: "text", text: `Parallel: ${done}/${allResults.length} done, ${running} running...` },
590
- ],
591
- details: makeDetails("parallel")([...allResults]),
592
- });
593
- }
594
- };
595
-
596
- const results = await mapWithConcurrencyLimit(params.tasks, MAX_CONCURRENCY, async (t, index) => {
597
- const result = await runSingleAgent(
598
- ctx.cwd,
599
- agents,
600
- t.agent,
601
- t.task,
602
- t.cwd,
603
- undefined,
604
- signal,
605
- // Per-task update callback
606
- (partial) => {
607
- if (partial.details?.results[0]) {
608
- allResults[index] = partial.details.results[0];
609
- emitParallelUpdate();
610
- }
611
- },
612
- makeDetails("parallel"),
613
- );
614
- allResults[index] = result;
615
- emitParallelUpdate();
616
- return result;
617
- });
618
-
619
- const successCount = results.filter((r) => r.exitCode === 0).length;
620
- const summaries = results.map((r) => {
621
- const output = getFinalOutput(r.messages);
622
- const preview = output.slice(0, 100) + (output.length > 100 ? "..." : "");
623
- return `[${r.agent}] ${r.exitCode === 0 ? "completed" : "failed"}: ${preview || "(no output)"}`;
624
- });
625
- return {
626
- content: [
627
- {
628
- type: "text",
629
- text: `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n")}`,
630
- },
631
- ],
632
- details: makeDetails("parallel")(results),
633
- };
634
- }
635
-
636
- if (params.agent && params.task) {
637
- const result = await runSingleAgent(
638
- ctx.cwd,
639
- agents,
640
- params.agent,
641
- params.task,
642
- params.cwd,
643
- undefined,
644
- signal,
645
- onUpdate,
646
- makeDetails("single"),
647
- );
648
- const isError = result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
649
- if (isError) {
650
- const errorMsg =
651
- result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
652
- return {
653
- content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }],
654
- details: makeDetails("single")([result]),
655
- isError: true,
656
- };
657
- }
658
- return {
659
- content: [{ type: "text", text: getFinalOutput(result.messages) || "(no output)" }],
660
- details: makeDetails("single")([result]),
661
- };
662
- }
663
-
664
- const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
665
- return {
666
- content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }],
667
- details: makeDetails("single")([]),
668
- };
669
- },
670
-
671
- renderCall(args, theme, _context) {
672
- const scope: AgentScope = args.agentScope ?? "user";
673
- if (args.chain && args.chain.length > 0) {
674
- let text =
675
- theme.fg("toolTitle", theme.bold("subagent ")) +
676
- theme.fg("accent", `chain (${args.chain.length} steps)`) +
677
- theme.fg("muted", ` [${scope}]`);
678
- for (let i = 0; i < Math.min(args.chain.length, 3); i++) {
679
- const step = args.chain[i];
680
- // Clean up {previous} placeholder for display
681
- const cleanTask = step.task.replace(/\{previous\}/g, "").trim();
682
- const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask;
683
- text +=
684
- "\n " +
685
- theme.fg("muted", `${i + 1}.`) +
686
- " " +
687
- theme.fg("accent", step.agent) +
688
- theme.fg("dim", ` ${preview}`);
689
- }
690
- if (args.chain.length > 3) text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`;
691
- return new Text(text, 0, 0);
692
- }
693
- if (args.tasks && args.tasks.length > 0) {
694
- let text =
695
- theme.fg("toolTitle", theme.bold("subagent ")) +
696
- theme.fg("accent", `parallel (${args.tasks.length} tasks)`) +
697
- theme.fg("muted", ` [${scope}]`);
698
- for (const t of args.tasks.slice(0, 3)) {
699
- const preview = t.task.length > 40 ? `${t.task.slice(0, 40)}...` : t.task;
700
- text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", ` ${preview}`)}`;
701
- }
702
- if (args.tasks.length > 3) text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`;
703
- return new Text(text, 0, 0);
704
- }
705
- const agentName = args.agent || "...";
706
- const preview = args.task ? (args.task.length > 60 ? `${args.task.slice(0, 60)}...` : args.task) : "...";
707
- let text =
708
- theme.fg("toolTitle", theme.bold("subagent ")) +
709
- theme.fg("accent", agentName) +
710
- theme.fg("muted", ` [${scope}]`);
711
- text += `\n ${theme.fg("dim", preview)}`;
712
- return new Text(text, 0, 0);
713
- },
714
-
715
- renderResult(result, { expanded }, theme, _context) {
716
- const details = result.details as SubagentDetails | undefined;
717
- if (!details || details.results.length === 0) {
718
- const text = result.content[0];
719
- return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
720
- }
721
-
722
- const mdTheme = getMarkdownTheme();
723
-
724
- const renderDisplayItems = (items: DisplayItem[], limit?: number) => {
725
- const toShow = limit ? items.slice(-limit) : items;
726
- const skipped = limit && items.length > limit ? items.length - limit : 0;
727
- let text = "";
728
- if (skipped > 0) text += theme.fg("muted", `... ${skipped} earlier items\n`);
729
- for (const item of toShow) {
730
- if (item.type === "text") {
731
- const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n");
732
- text += `${theme.fg("toolOutput", preview)}\n`;
733
- } else {
734
- text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme))}\n`;
735
- }
736
- }
737
- return text.trimEnd();
738
- };
739
-
740
- if (details.mode === "single" && details.results.length === 1) {
741
- const r = details.results[0];
742
- const isError = r.exitCode !== 0 || r.stopReason === "error" || r.stopReason === "aborted";
743
- const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
744
- const displayItems = getDisplayItems(r.messages);
745
- const finalOutput = getFinalOutput(r.messages);
746
-
747
- if (expanded) {
748
- const container = new Container();
749
- let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
750
- if (isError && r.stopReason) header += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
751
- container.addChild(new Text(header, 0, 0));
752
- if (isError && r.errorMessage)
753
- container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
754
- container.addChild(new Spacer(1));
755
- container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
756
- container.addChild(new Text(theme.fg("dim", r.task), 0, 0));
757
- container.addChild(new Spacer(1));
758
- container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
759
- if (displayItems.length === 0 && !finalOutput) {
760
- container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
761
- } else {
762
- for (const item of displayItems) {
763
- if (item.type === "toolCall")
764
- container.addChild(
765
- new Text(
766
- theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
767
- 0,
768
- 0,
769
- ),
770
- );
771
- }
772
- if (finalOutput) {
773
- container.addChild(new Spacer(1));
774
- container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
775
- }
776
- }
777
- const usageStr = formatUsageStats(r.usage, r.model);
778
- if (usageStr) {
779
- container.addChild(new Spacer(1));
780
- container.addChild(new Text(theme.fg("dim", usageStr), 0, 0));
781
- }
782
- return container;
783
- }
784
-
785
- let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
786
- if (isError && r.stopReason) text += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
787
- if (isError && r.errorMessage) text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`;
788
- else if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
789
- else {
790
- text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`;
791
- if (displayItems.length > COLLAPSED_ITEM_COUNT) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
792
- }
793
- const usageStr = formatUsageStats(r.usage, r.model);
794
- if (usageStr) text += `\n${theme.fg("dim", usageStr)}`;
795
- return new Text(text, 0, 0);
796
- }
797
-
798
- const aggregateUsage = (results: SingleResult[]) => {
799
- const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
800
- for (const r of results) {
801
- total.input += r.usage.input;
802
- total.output += r.usage.output;
803
- total.cacheRead += r.usage.cacheRead;
804
- total.cacheWrite += r.usage.cacheWrite;
805
- total.cost += r.usage.cost;
806
- total.turns += r.usage.turns;
807
- }
808
- return total;
809
- };
810
-
811
- if (details.mode === "chain") {
812
- const successCount = details.results.filter((r) => r.exitCode === 0).length;
813
- const icon = successCount === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
814
-
815
- if (expanded) {
816
- const container = new Container();
817
- container.addChild(
818
- new Text(
819
- icon +
820
- " " +
821
- theme.fg("toolTitle", theme.bold("chain ")) +
822
- theme.fg("accent", `${successCount}/${details.results.length} steps`),
823
- 0,
824
- 0,
825
- ),
826
- );
827
-
828
- for (const r of details.results) {
829
- const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
830
- const displayItems = getDisplayItems(r.messages);
831
- const finalOutput = getFinalOutput(r.messages);
832
-
833
- container.addChild(new Spacer(1));
834
- container.addChild(
835
- new Text(
836
- `${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`,
837
- 0,
838
- 0,
839
- ),
840
- );
841
- container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
842
-
843
- // Show tool calls
844
- for (const item of displayItems) {
845
- if (item.type === "toolCall") {
846
- container.addChild(
847
- new Text(
848
- theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
849
- 0,
850
- 0,
851
- ),
852
- );
853
- }
854
- }
855
-
856
- // Show final output as markdown
857
- if (finalOutput) {
858
- container.addChild(new Spacer(1));
859
- container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
860
- }
861
-
862
- const stepUsage = formatUsageStats(r.usage, r.model);
863
- if (stepUsage) container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0));
864
- }
865
-
866
- const usageStr = formatUsageStats(aggregateUsage(details.results));
867
- if (usageStr) {
868
- container.addChild(new Spacer(1));
869
- container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
870
- }
871
- return container;
872
- }
873
-
874
- // Collapsed view
875
- let text =
876
- icon +
877
- " " +
878
- theme.fg("toolTitle", theme.bold("chain ")) +
879
- theme.fg("accent", `${successCount}/${details.results.length} steps`);
880
- for (const r of details.results) {
881
- const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
882
- const displayItems = getDisplayItems(r.messages);
883
- text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`;
884
- if (displayItems.length === 0) text += `\n${theme.fg("muted", "(no output)")}`;
885
- else text += `\n${renderDisplayItems(displayItems, 5)}`;
886
- }
887
- const usageStr = formatUsageStats(aggregateUsage(details.results));
888
- if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
889
- text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
890
- return new Text(text, 0, 0);
891
- }
892
-
893
- if (details.mode === "parallel") {
894
- const running = details.results.filter((r) => r.exitCode === -1).length;
895
- const successCount = details.results.filter((r) => r.exitCode === 0).length;
896
- const failCount = details.results.filter((r) => r.exitCode > 0).length;
897
- const isRunning = running > 0;
898
- const icon = isRunning
899
- ? theme.fg("warning", "⏳")
900
- : failCount > 0
901
- ? theme.fg("warning", "◐")
902
- : theme.fg("success", "✓");
903
- const status = isRunning
904
- ? `${successCount + failCount}/${details.results.length} done, ${running} running`
905
- : `${successCount}/${details.results.length} tasks`;
906
-
907
- if (expanded && !isRunning) {
908
- const container = new Container();
909
- container.addChild(
910
- new Text(
911
- `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`,
912
- 0,
913
- 0,
914
- ),
915
- );
916
-
917
- for (const r of details.results) {
918
- const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
919
- const displayItems = getDisplayItems(r.messages);
920
- const finalOutput = getFinalOutput(r.messages);
921
-
922
- container.addChild(new Spacer(1));
923
- container.addChild(
924
- new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0),
925
- );
926
- container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
927
-
928
- // Show tool calls
929
- for (const item of displayItems) {
930
- if (item.type === "toolCall") {
931
- container.addChild(
932
- new Text(
933
- theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)),
934
- 0,
935
- 0,
936
- ),
937
- );
938
- }
939
- }
940
-
941
- // Show final output as markdown
942
- if (finalOutput) {
943
- container.addChild(new Spacer(1));
944
- container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
945
- }
946
-
947
- const taskUsage = formatUsageStats(r.usage, r.model);
948
- if (taskUsage) container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0));
949
- }
950
-
951
- const usageStr = formatUsageStats(aggregateUsage(details.results));
952
- if (usageStr) {
953
- container.addChild(new Spacer(1));
954
- container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
955
- }
956
- return container;
957
- }
958
-
959
- // Collapsed view (or still running)
960
- let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`;
961
- for (const r of details.results) {
962
- const rIcon =
963
- r.exitCode === -1
964
- ? theme.fg("warning", "⏳")
965
- : r.exitCode === 0
966
- ? theme.fg("success", "✓")
967
- : theme.fg("error", "✗");
968
- const displayItems = getDisplayItems(r.messages);
969
- text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
970
- if (displayItems.length === 0)
971
- text += `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}`;
972
- else text += `\n${renderDisplayItems(displayItems, 5)}`;
973
- }
974
- if (!isRunning) {
975
- const usageStr = formatUsageStats(aggregateUsage(details.results));
976
- if (usageStr) text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
977
- }
978
- if (!expanded) text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
979
- return new Text(text, 0, 0);
980
- }
981
-
982
- const text = result.content[0];
983
- return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
984
- },
985
- });
986
- }