@selesai/code 0.9.5 → 0.9.8

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