@humain/terminal 0.0.3-beta.2 → 0.0.4-beta.1

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 (136) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/bun/cli.d.ts.map +1 -1
  3. package/dist/bun/cli.js +0 -1
  4. package/dist/bun/cli.js.map +1 -1
  5. package/dist/core/agent-session.d.ts.map +1 -1
  6. package/dist/core/agent-session.js +7 -1
  7. package/dist/core/agent-session.js.map +1 -1
  8. package/dist/core/sdk.d.ts.map +1 -1
  9. package/dist/core/sdk.js +1 -1
  10. package/dist/core/sdk.js.map +1 -1
  11. package/dist/core/session-manager.d.ts +4 -0
  12. package/dist/core/session-manager.d.ts.map +1 -1
  13. package/dist/core/session-manager.js +46 -22
  14. package/dist/core/session-manager.js.map +1 -1
  15. package/dist/core/tools/index.d.ts +2 -1
  16. package/dist/core/tools/index.d.ts.map +1 -1
  17. package/dist/core/tools/index.js +9 -1
  18. package/dist/core/tools/index.js.map +1 -1
  19. package/dist/core/tools/subagent.d.ts +82 -0
  20. package/dist/core/tools/subagent.d.ts.map +1 -0
  21. package/dist/core/tools/subagent.js +980 -0
  22. package/dist/core/tools/subagent.js.map +1 -0
  23. package/dist/humain/bedrock-provider/vendor/index.bundle.d.mts +3 -0
  24. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +1509 -0
  25. package/dist/humain/index.d.ts.map +1 -1
  26. package/dist/humain/index.js +3 -0
  27. package/dist/humain/index.js.map +1 -1
  28. package/dist/humain/mcp-adapter/vendor/CHANGELOG.md +36 -0
  29. package/dist/humain/mcp-adapter/vendor/README.md +47 -5
  30. package/dist/humain/mcp-adapter/vendor/cli.js +163 -1
  31. package/dist/humain/mcp-adapter/vendor/commands.ts +128 -22
  32. package/dist/humain/mcp-adapter/vendor/config.ts +25 -7
  33. package/dist/humain/mcp-adapter/vendor/direct-tools.ts +5 -4
  34. package/dist/humain/mcp-adapter/vendor/index.bundle.mjs +1663 -458
  35. package/dist/humain/mcp-adapter/vendor/index.ts +219 -32
  36. package/dist/humain/mcp-adapter/vendor/init.ts +36 -4
  37. package/dist/humain/mcp-adapter/vendor/lifecycle.ts +315 -24
  38. package/dist/humain/mcp-adapter/vendor/mcp-auth-flow.ts +39 -6
  39. package/dist/humain/mcp-adapter/vendor/mcp-bearer-store.ts +387 -0
  40. package/dist/humain/mcp-adapter/vendor/mcp-callback-server.ts +27 -3
  41. package/dist/humain/mcp-adapter/vendor/mcp-code.ts +4 -0
  42. package/dist/humain/mcp-adapter/vendor/mcp-panel.ts +42 -13
  43. package/dist/humain/mcp-adapter/vendor/metadata-cache.ts +32 -21
  44. package/dist/humain/mcp-adapter/vendor/package-mcp-loader.ts +168 -0
  45. package/dist/humain/mcp-adapter/vendor/package.json +179 -177
  46. package/dist/humain/mcp-adapter/vendor/proxy-modes.ts +5 -4
  47. package/dist/humain/mcp-adapter/vendor/request-headers-command.ts +31 -37
  48. package/dist/humain/mcp-adapter/vendor/search-ranking.ts +92 -22
  49. package/dist/humain/mcp-adapter/vendor/server-manager.ts +140 -2
  50. package/dist/humain/mcp-adapter/vendor/session-recovery.ts +7 -0
  51. package/dist/humain/mcp-adapter/vendor/tool-approval.ts +15 -2
  52. package/dist/humain/mcp-adapter/vendor/tool-result-renderer.ts +44 -4
  53. package/dist/humain/mcp-adapter/vendor/types.ts +2 -0
  54. package/dist/humain/mcp-adapter/vendor/ui-server.ts +18 -16
  55. package/dist/humain/mcp-adapter/vendor/utils.ts +70 -0
  56. package/dist/humain/web-access/vendor/anysearch.d.ts.map +1 -1
  57. package/dist/humain/web-access/vendor/anysearch.js +3 -2
  58. package/dist/humain/web-access/vendor/anysearch.js.map +1 -1
  59. package/dist/humain/web-access/vendor/brave.d.ts.map +1 -1
  60. package/dist/humain/web-access/vendor/brave.js +14 -4
  61. package/dist/humain/web-access/vendor/brave.js.map +1 -1
  62. package/dist/humain/web-access/vendor/curator-page.d.ts +3 -0
  63. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  64. package/dist/humain/web-access/vendor/curator-page.js +4 -1
  65. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  66. package/dist/humain/web-access/vendor/curator-server.d.ts +3 -0
  67. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  68. package/dist/humain/web-access/vendor/curator-server.js +6 -0
  69. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  70. package/dist/humain/web-access/vendor/exa.d.ts.map +1 -1
  71. package/dist/humain/web-access/vendor/exa.js +16 -7
  72. package/dist/humain/web-access/vendor/exa.js.map +1 -1
  73. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  74. package/dist/humain/web-access/vendor/extract.js +31 -3
  75. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  76. package/dist/humain/web-access/vendor/gemini-search.d.ts +2 -2
  77. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  78. package/dist/humain/web-access/vendor/gemini-search.js +25 -4
  79. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  80. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  81. package/dist/humain/web-access/vendor/index.js +36 -49
  82. package/dist/humain/web-access/vendor/index.js.map +1 -1
  83. package/dist/humain/web-access/vendor/page-query.d.ts +1 -2
  84. package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
  85. package/dist/humain/web-access/vendor/page-query.js +5 -2
  86. package/dist/humain/web-access/vendor/page-query.js.map +1 -1
  87. package/dist/humain/web-access/vendor/parallel-mcp.d.ts +10 -0
  88. package/dist/humain/web-access/vendor/parallel-mcp.d.ts.map +1 -0
  89. package/dist/humain/web-access/vendor/parallel-mcp.js +224 -0
  90. package/dist/humain/web-access/vendor/parallel-mcp.js.map +1 -0
  91. package/dist/humain/web-access/vendor/parallel.d.ts +1 -0
  92. package/dist/humain/web-access/vendor/parallel.d.ts.map +1 -1
  93. package/dist/humain/web-access/vendor/parallel.js +2 -2
  94. package/dist/humain/web-access/vendor/parallel.js.map +1 -1
  95. package/dist/humain/web-access/vendor/query-rewrite.d.ts +3 -0
  96. package/dist/humain/web-access/vendor/query-rewrite.d.ts.map +1 -0
  97. package/dist/humain/web-access/vendor/query-rewrite.js +42 -0
  98. package/dist/humain/web-access/vendor/query-rewrite.js.map +1 -0
  99. package/dist/humain/web-access/vendor/serper.d.ts +4 -0
  100. package/dist/humain/web-access/vendor/serper.d.ts.map +1 -0
  101. package/dist/humain/web-access/vendor/serper.js +206 -0
  102. package/dist/humain/web-access/vendor/serper.js.map +1 -0
  103. package/dist/humain/web-access/vendor/summary-model-scope.d.ts +5 -0
  104. package/dist/humain/web-access/vendor/summary-model-scope.d.ts.map +1 -1
  105. package/dist/humain/web-access/vendor/summary-model-scope.js +10 -5
  106. package/dist/humain/web-access/vendor/summary-model-scope.js.map +1 -1
  107. package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -1
  108. package/dist/humain/web-access/vendor/summary-review.js +40 -14
  109. package/dist/humain/web-access/vendor/summary-review.js.map +1 -1
  110. package/dist/humain/web-access/vendor/tavily.d.ts.map +1 -1
  111. package/dist/humain/web-access/vendor/tavily.js +14 -4
  112. package/dist/humain/web-access/vendor/tavily.js.map +1 -1
  113. package/dist/humain/web-access/vendor/utils.d.ts +10 -0
  114. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  115. package/dist/humain/web-access/vendor/utils.js +70 -0
  116. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  117. package/dist/humain/web-access/vendor/valyu.d.ts +6 -0
  118. package/dist/humain/web-access/vendor/valyu.d.ts.map +1 -0
  119. package/dist/humain/web-access/vendor/valyu.js +194 -0
  120. package/dist/humain/web-access/vendor/valyu.js.map +1 -0
  121. package/docs/extensions.md +1 -1
  122. package/examples/extensions/README.md +1 -1
  123. package/examples/extensions/subagent/README.md +24 -147
  124. package/npm-shrinkwrap.json +7 -2
  125. package/package.json +7 -2
  126. package/src/humain/mcp-adapter/UPSTREAM.md +1 -1
  127. package/src/humain/mcp-adapter/upstream.json +3 -3
  128. package/src/humain/mcp-adapter/vendor/CHANGELOG.md +36 -0
  129. package/src/humain/web-access/UPSTREAM.md +1 -1
  130. package/src/humain/web-access/upstream.json +4 -4
  131. package/dist/bun/register-bedrock.d.ts +0 -2
  132. package/dist/bun/register-bedrock.d.ts.map +0 -1
  133. package/dist/bun/register-bedrock.js +0 -4
  134. package/dist/bun/register-bedrock.js.map +0 -1
  135. package/examples/extensions/subagent/agents.ts +0 -126
  136. package/examples/extensions/subagent/index.ts +0 -1015
@@ -0,0 +1,980 @@
1
+ /**
2
+ * Subagent Tool - Delegate tasks to specialized agents
3
+ *
4
+ * Spawns a separate humain-terminal 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
+ import { spawn } from "node:child_process";
15
+ import * as fs from "node:fs";
16
+ import * as os from "node:os";
17
+ import * as path from "node:path";
18
+ import { StringEnum } from "@earendil-works/pi-ai";
19
+ import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
20
+ import { Type } from "typebox";
21
+ import { CONFIG_DIR_NAME, getAgentDir } from "../../config.js";
22
+ import { getMarkdownTheme } from "../../modes/interactive/theme/theme.js";
23
+ import { parseFrontmatter } from "../../utils/frontmatter.js";
24
+ import { withFileMutationQueue } from "./file-mutation-queue.js";
25
+ import { shortenPath } from "./render-utils.js";
26
+ import { wrapToolDefinition } from "./tool-definition-wrapper.js";
27
+ const MAX_PARALLEL_TASKS = 8;
28
+ const MAX_CONCURRENCY = 4;
29
+ const COLLAPSED_ITEM_COUNT = 10;
30
+ const PER_TASK_OUTPUT_CAP = 50 * 1024;
31
+ /** Children must not delegate further: depth 0 = top-level agent, depth >= 1 = subagent. */
32
+ export const SUBAGENT_DEPTH_ENV = "HUMAIN_TERMINAL_SUBAGENT_DEPTH";
33
+ const MAX_SUBAGENT_DEPTH = 1;
34
+ function currentSubagentDepth() {
35
+ const raw = Number(process.env[SUBAGENT_DEPTH_ENV] ?? "0");
36
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;
37
+ }
38
+ function loadAgentsFromDir(dir, source) {
39
+ const agents = [];
40
+ if (!fs.existsSync(dir)) {
41
+ return agents;
42
+ }
43
+ let entries;
44
+ try {
45
+ entries = fs.readdirSync(dir, { withFileTypes: true });
46
+ }
47
+ catch {
48
+ return agents;
49
+ }
50
+ for (const entry of entries) {
51
+ if (!entry.name.endsWith(".md"))
52
+ continue;
53
+ if (!entry.isFile() && !entry.isSymbolicLink())
54
+ continue;
55
+ const filePath = path.join(dir, entry.name);
56
+ let content;
57
+ try {
58
+ content = fs.readFileSync(filePath, "utf-8");
59
+ }
60
+ catch {
61
+ continue;
62
+ }
63
+ const { frontmatter, body } = parseFrontmatter(content);
64
+ if (!frontmatter.name || !frontmatter.description) {
65
+ continue;
66
+ }
67
+ const tools = frontmatter.tools
68
+ ?.split(",")
69
+ .map((t) => t.trim())
70
+ .filter(Boolean);
71
+ agents.push({
72
+ name: frontmatter.name,
73
+ description: frontmatter.description,
74
+ tools: tools && tools.length > 0 ? tools : undefined,
75
+ model: frontmatter.model,
76
+ systemPrompt: body,
77
+ source,
78
+ filePath,
79
+ });
80
+ }
81
+ return agents;
82
+ }
83
+ function isDirectory(p) {
84
+ try {
85
+ return fs.statSync(p).isDirectory();
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ function findNearestProjectAgentsDir(cwd) {
92
+ let currentDir = cwd;
93
+ while (true) {
94
+ const candidate = path.join(currentDir, CONFIG_DIR_NAME, "agents");
95
+ if (isDirectory(candidate))
96
+ return candidate;
97
+ const parentDir = path.dirname(currentDir);
98
+ if (parentDir === currentDir)
99
+ return null;
100
+ currentDir = parentDir;
101
+ }
102
+ }
103
+ export function discoverAgents(cwd, scope) {
104
+ const userDir = path.join(getAgentDir(), "agents");
105
+ const projectAgentsDir = findNearestProjectAgentsDir(cwd);
106
+ const userAgents = scope === "project" ? [] : loadAgentsFromDir(userDir, "user");
107
+ const projectAgents = scope === "user" || !projectAgentsDir ? [] : loadAgentsFromDir(projectAgentsDir, "project");
108
+ const agentMap = new Map();
109
+ if (scope === "both") {
110
+ for (const agent of userAgents)
111
+ agentMap.set(agent.name, agent);
112
+ for (const agent of projectAgents)
113
+ agentMap.set(agent.name, agent);
114
+ }
115
+ else if (scope === "user") {
116
+ for (const agent of userAgents)
117
+ agentMap.set(agent.name, agent);
118
+ }
119
+ else {
120
+ for (const agent of projectAgents)
121
+ agentMap.set(agent.name, agent);
122
+ }
123
+ return { agents: Array.from(agentMap.values()), projectAgentsDir };
124
+ }
125
+ // --- Formatting helpers ---
126
+ function formatTokens(count) {
127
+ if (count < 1000)
128
+ return count.toString();
129
+ if (count < 10000)
130
+ return `${(count / 1000).toFixed(1)}k`;
131
+ if (count < 1000000)
132
+ return `${Math.round(count / 1000)}k`;
133
+ return `${(count / 1000000).toFixed(1)}M`;
134
+ }
135
+ function formatUsageStats(usage, model) {
136
+ const parts = [];
137
+ if (usage.turns)
138
+ parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`);
139
+ if (usage.input)
140
+ parts.push(`↑${formatTokens(usage.input)}`);
141
+ if (usage.output)
142
+ parts.push(`↓${formatTokens(usage.output)}`);
143
+ if (usage.cacheRead)
144
+ parts.push(`R${formatTokens(usage.cacheRead)}`);
145
+ if (usage.cacheWrite)
146
+ parts.push(`W${formatTokens(usage.cacheWrite)}`);
147
+ if (usage.cost)
148
+ parts.push(`$${usage.cost.toFixed(4)}`);
149
+ if (usage.contextTokens && usage.contextTokens > 0) {
150
+ parts.push(`ctx:${formatTokens(usage.contextTokens)}`);
151
+ }
152
+ if (model)
153
+ parts.push(model);
154
+ return parts.join(" ");
155
+ }
156
+ function formatToolCall(toolName, args, themeFg) {
157
+ switch (toolName) {
158
+ case "bash": {
159
+ const command = args.command || "...";
160
+ const preview = command.length > 60 ? `${command.slice(0, 60)}...` : command;
161
+ return themeFg("muted", "$ ") + themeFg("toolOutput", preview);
162
+ }
163
+ case "read": {
164
+ const rawPath = (args.file_path || args.path || "...");
165
+ const filePath = shortenPath(rawPath);
166
+ const offset = args.offset;
167
+ const limit = args.limit;
168
+ let text = themeFg("accent", filePath);
169
+ if (offset !== undefined || limit !== undefined) {
170
+ const startLine = offset ?? 1;
171
+ const endLine = limit !== undefined ? startLine + limit - 1 : "";
172
+ text += themeFg("warning", `:${startLine}${endLine ? `-${endLine}` : ""}`);
173
+ }
174
+ return themeFg("muted", "read ") + text;
175
+ }
176
+ case "write": {
177
+ const rawPath = (args.file_path || args.path || "...");
178
+ const filePath = shortenPath(rawPath);
179
+ const content = (args.content || "");
180
+ const lines = content.split("\n").length;
181
+ let text = themeFg("muted", "write ") + themeFg("accent", filePath);
182
+ if (lines > 1)
183
+ text += themeFg("dim", ` (${lines} lines)`);
184
+ return text;
185
+ }
186
+ case "edit": {
187
+ const rawPath = (args.file_path || args.path || "...");
188
+ return themeFg("muted", "edit ") + themeFg("accent", shortenPath(rawPath));
189
+ }
190
+ case "ls": {
191
+ const rawPath = (args.path || ".");
192
+ return themeFg("muted", "ls ") + themeFg("accent", shortenPath(rawPath));
193
+ }
194
+ case "find": {
195
+ const pattern = (args.pattern || "*");
196
+ const rawPath = (args.path || ".");
197
+ return themeFg("muted", "find ") + themeFg("accent", pattern) + themeFg("dim", ` in ${shortenPath(rawPath)}`);
198
+ }
199
+ case "grep": {
200
+ const pattern = (args.pattern || "");
201
+ const rawPath = (args.path || ".");
202
+ return (themeFg("muted", "grep ") +
203
+ themeFg("accent", `/${pattern}/`) +
204
+ themeFg("dim", ` in ${shortenPath(rawPath)}`));
205
+ }
206
+ default: {
207
+ const argsStr = JSON.stringify(args);
208
+ const preview = argsStr.length > 50 ? `${argsStr.slice(0, 50)}...` : argsStr;
209
+ return themeFg("accent", toolName) + themeFg("dim", ` ${preview}`);
210
+ }
211
+ }
212
+ }
213
+ function getFinalOutput(messages) {
214
+ for (let i = messages.length - 1; i >= 0; i--) {
215
+ const msg = messages[i];
216
+ if (msg.role === "assistant") {
217
+ for (const part of msg.content) {
218
+ if (part.type === "text")
219
+ return part.text;
220
+ }
221
+ }
222
+ }
223
+ return "";
224
+ }
225
+ function isFailedResult(result) {
226
+ return result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted";
227
+ }
228
+ function getResultOutput(result) {
229
+ if (isFailedResult(result)) {
230
+ return result.errorMessage || result.stderr || getFinalOutput(result.messages) || "(no output)";
231
+ }
232
+ return getFinalOutput(result.messages) || "(no output)";
233
+ }
234
+ function truncateParallelOutput(output) {
235
+ const byteLength = Buffer.byteLength(output, "utf8");
236
+ if (byteLength <= PER_TASK_OUTPUT_CAP)
237
+ return output;
238
+ let truncated = output.slice(0, PER_TASK_OUTPUT_CAP);
239
+ while (Buffer.byteLength(truncated, "utf8") > PER_TASK_OUTPUT_CAP) {
240
+ truncated = truncated.slice(0, -1);
241
+ }
242
+ return `${truncated}\n\n[Output truncated: ${byteLength - Buffer.byteLength(truncated, "utf8")} bytes omitted. Full output preserved in tool details.]`;
243
+ }
244
+ function getDisplayItems(messages) {
245
+ const items = [];
246
+ for (const msg of messages) {
247
+ if (msg.role === "assistant") {
248
+ for (const part of msg.content) {
249
+ if (part.type === "text")
250
+ items.push({ type: "text", text: part.text });
251
+ else if (part.type === "toolCall")
252
+ items.push({ type: "toolCall", name: part.name, args: part.arguments });
253
+ }
254
+ }
255
+ }
256
+ return items;
257
+ }
258
+ async function mapWithConcurrencyLimit(items, concurrency, fn, signal) {
259
+ if (items.length === 0)
260
+ return [];
261
+ const limit = Math.max(1, Math.min(concurrency, items.length));
262
+ const results = new Array(items.length);
263
+ let nextIndex = 0;
264
+ const workers = new Array(limit).fill(null).map(async () => {
265
+ while (true) {
266
+ // Don't spawn doomed children for tasks still queued after an abort.
267
+ if (signal?.aborted)
268
+ throw new Error("Subagent was aborted");
269
+ const current = nextIndex++;
270
+ if (current >= items.length)
271
+ return;
272
+ results[current] = await fn(items[current], current);
273
+ }
274
+ });
275
+ await Promise.all(workers);
276
+ return results;
277
+ }
278
+ async function writePromptToTempFile(agentName, prompt) {
279
+ const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "humain-subagent-"));
280
+ const safeName = agentName.replace(/[^\w.-]+/g, "_");
281
+ const filePath = path.join(tmpDir, `prompt-${safeName}.md`);
282
+ await withFileMutationQueue(filePath, async () => {
283
+ await fs.promises.writeFile(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
284
+ });
285
+ return { dir: tmpDir, filePath };
286
+ }
287
+ function getCliInvocation(args) {
288
+ const currentScript = process.argv[1];
289
+ const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
290
+ if (currentScript && !isBunVirtualScript && fs.existsSync(currentScript)) {
291
+ return { command: process.execPath, args: [currentScript, ...args] };
292
+ }
293
+ const execName = path.basename(process.execPath).toLowerCase();
294
+ const isGenericRuntime = /^(node|bun)(\.exe)?$/.test(execName);
295
+ if (!isGenericRuntime) {
296
+ return { command: process.execPath, args };
297
+ }
298
+ return { command: "humain-terminal", args };
299
+ }
300
+ async function runSingleAgent(defaultCwd, agents, agentName, task, cwd, step, signal, onUpdate, makeDetails) {
301
+ const agent = agents.find((a) => a.name === agentName);
302
+ if (!agent) {
303
+ const available = agents.map((a) => `"${a.name}"`).join(", ") || "none";
304
+ return {
305
+ agent: agentName,
306
+ agentSource: "unknown",
307
+ task,
308
+ exitCode: 1,
309
+ messages: [],
310
+ stderr: `Unknown agent: "${agentName}". Available agents: ${available}.`,
311
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
312
+ step,
313
+ };
314
+ }
315
+ const args = ["--mode", "json", "-p", "--no-session"];
316
+ if (agent.model)
317
+ args.push("--model", agent.model);
318
+ if (agent.tools && agent.tools.length > 0)
319
+ args.push("--tools", agent.tools.join(","));
320
+ let tmpPromptDir = null;
321
+ let tmpPromptPath = null;
322
+ const currentResult = {
323
+ agent: agentName,
324
+ agentSource: agent.source,
325
+ task,
326
+ exitCode: 0,
327
+ messages: [],
328
+ stderr: "",
329
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
330
+ model: agent.model,
331
+ step,
332
+ };
333
+ const emitUpdate = () => {
334
+ if (onUpdate) {
335
+ onUpdate({
336
+ content: [{ type: "text", text: getFinalOutput(currentResult.messages) || "(running...)" }],
337
+ details: makeDetails([currentResult]),
338
+ });
339
+ }
340
+ };
341
+ try {
342
+ if (agent.systemPrompt.trim()) {
343
+ const tmp = await writePromptToTempFile(agent.name, agent.systemPrompt);
344
+ tmpPromptDir = tmp.dir;
345
+ tmpPromptPath = tmp.filePath;
346
+ args.push("--append-system-prompt", tmpPromptPath);
347
+ }
348
+ args.push(`Task: ${task}`);
349
+ let wasAborted = false;
350
+ const exitCode = await new Promise((resolve) => {
351
+ const invocation = getCliInvocation(args);
352
+ const proc = spawn(invocation.command, invocation.args, {
353
+ cwd: cwd ?? defaultCwd,
354
+ shell: false,
355
+ stdio: ["ignore", "pipe", "pipe"],
356
+ env: { ...process.env, [SUBAGENT_DEPTH_ENV]: String(currentSubagentDepth() + 1) },
357
+ });
358
+ let buffer = "";
359
+ const processLine = (line) => {
360
+ if (!line.trim())
361
+ return;
362
+ let event;
363
+ try {
364
+ event = JSON.parse(line);
365
+ }
366
+ catch {
367
+ return;
368
+ }
369
+ if (event.type === "message_end" && event.message) {
370
+ const msg = event.message;
371
+ currentResult.messages.push(msg);
372
+ if (msg.role === "assistant") {
373
+ currentResult.usage.turns++;
374
+ const usage = msg.usage;
375
+ if (usage) {
376
+ currentResult.usage.input += usage.input || 0;
377
+ currentResult.usage.output += usage.output || 0;
378
+ currentResult.usage.cacheRead += usage.cacheRead || 0;
379
+ currentResult.usage.cacheWrite += usage.cacheWrite || 0;
380
+ currentResult.usage.cost += usage.cost?.total || 0;
381
+ currentResult.usage.contextTokens = usage.totalTokens || 0;
382
+ }
383
+ if (!currentResult.model && msg.model)
384
+ currentResult.model = msg.model;
385
+ if (msg.stopReason)
386
+ currentResult.stopReason = msg.stopReason;
387
+ if (msg.errorMessage)
388
+ currentResult.errorMessage = msg.errorMessage;
389
+ }
390
+ emitUpdate();
391
+ }
392
+ if (event.type === "tool_result_end" && event.message) {
393
+ currentResult.messages.push(event.message);
394
+ emitUpdate();
395
+ }
396
+ };
397
+ proc.stdout.on("data", (data) => {
398
+ buffer += data.toString();
399
+ const lines = buffer.split("\n");
400
+ buffer = lines.pop() || "";
401
+ for (const line of lines)
402
+ processLine(line);
403
+ });
404
+ proc.stderr.on("data", (data) => {
405
+ currentResult.stderr += data.toString();
406
+ });
407
+ proc.on("close", (code) => {
408
+ if (buffer.trim())
409
+ processLine(buffer);
410
+ resolve(code ?? 0);
411
+ });
412
+ proc.on("error", () => {
413
+ resolve(1);
414
+ });
415
+ if (signal) {
416
+ const killProc = () => {
417
+ wasAborted = true;
418
+ proc.kill("SIGTERM");
419
+ setTimeout(() => {
420
+ if (!proc.killed)
421
+ proc.kill("SIGKILL");
422
+ }, 5000);
423
+ };
424
+ if (signal.aborted)
425
+ killProc();
426
+ else
427
+ signal.addEventListener("abort", killProc, { once: true });
428
+ }
429
+ });
430
+ currentResult.exitCode = exitCode;
431
+ if (wasAborted)
432
+ throw new Error("Subagent was aborted");
433
+ return currentResult;
434
+ }
435
+ finally {
436
+ if (tmpPromptPath)
437
+ try {
438
+ fs.unlinkSync(tmpPromptPath);
439
+ }
440
+ catch {
441
+ /* ignore */
442
+ }
443
+ if (tmpPromptDir)
444
+ try {
445
+ fs.rmdirSync(tmpPromptDir);
446
+ }
447
+ catch {
448
+ /* ignore */
449
+ }
450
+ }
451
+ }
452
+ const TaskItem = Type.Object({
453
+ agent: Type.String({ description: "Name of the agent to invoke" }),
454
+ task: Type.String({ description: "Task to delegate to the agent" }),
455
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
456
+ });
457
+ const ChainItem = Type.Object({
458
+ agent: Type.String({ description: "Name of the agent to invoke" }),
459
+ task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
460
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process" })),
461
+ });
462
+ const AgentScopeSchema = StringEnum(["user", "project", "both"], {
463
+ description: 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
464
+ default: "user",
465
+ });
466
+ const SubagentParams = Type.Object({
467
+ agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (for single mode)" })),
468
+ task: Type.Optional(Type.String({ description: "Task to delegate (for single mode)" })),
469
+ tasks: Type.Optional(Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" })),
470
+ chain: Type.Optional(Type.Array(ChainItem, { description: "Array of {agent, task} for sequential execution" })),
471
+ agentScope: Type.Optional(AgentScopeSchema),
472
+ confirmProjectAgents: Type.Optional(Type.Boolean({ description: "Prompt before running project-local agents. Default: true.", default: true })),
473
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent process (single mode)" })),
474
+ });
475
+ export function createSubagentToolDefinition(cwd) {
476
+ return {
477
+ name: "subagent",
478
+ label: "Subagent",
479
+ description: [
480
+ "Delegate tasks to specialized subagents with isolated context.",
481
+ "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder).",
482
+ `Default agent scope is "user" (from ${path.join(getAgentDir(), "agents")}).`,
483
+ `To enable project-local agents in ${CONFIG_DIR_NAME}/agents, set agentScope: "both" (or "project").`,
484
+ ].join(" "),
485
+ promptSnippet: "subagent: delegate work to isolated subagents — single task, parallel batch (tasks array), or sequential chain with {previous} placeholder",
486
+ promptGuidelines: [
487
+ "Use subagent to fan out independent work in parallel (tasks array) or run multi-step pipelines (chain). Subagents run with isolated context and cannot delegate further.",
488
+ ],
489
+ parameters: SubagentParams,
490
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
491
+ const agentScope = params.agentScope ?? "user";
492
+ const defaultCwd = ctx?.cwd ?? cwd;
493
+ const discovery = discoverAgents(defaultCwd, agentScope);
494
+ const agents = discovery.agents;
495
+ const confirmProjectAgents = params.confirmProjectAgents ?? true;
496
+ // Every requested child must appear in details.results, even when
497
+ // nothing ran: external consumers fan out per-child bookkeeping from
498
+ // the tool args and reconcile it against results by index.
499
+ const requestedChildren = () => {
500
+ if (params.tasks && params.tasks.length > 0)
501
+ return params.tasks.map((t) => ({ agent: t.agent, task: t.task }));
502
+ if (params.chain && params.chain.length > 0)
503
+ return params.chain.map((s, i) => ({ agent: s.agent, task: s.task, step: i + 1 }));
504
+ if (params.agent)
505
+ return [{ agent: params.agent, task: params.task }];
506
+ return [];
507
+ };
508
+ const stubResult = (child, errorMessage) => ({
509
+ agent: child.agent,
510
+ agentSource: "unknown",
511
+ task: child.task ?? "",
512
+ exitCode: 1,
513
+ messages: [],
514
+ stderr: "",
515
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
516
+ errorMessage,
517
+ step: child.step,
518
+ });
519
+ const stubAllChildren = (errorMessage) => requestedChildren().map((child) => stubResult(child, errorMessage));
520
+ const makeDetails = (mode) => (results) => ({
521
+ mode,
522
+ agentScope,
523
+ projectAgentsDir: discovery.projectAgentsDir,
524
+ results,
525
+ });
526
+ if (currentSubagentDepth() >= MAX_SUBAGENT_DEPTH) {
527
+ return {
528
+ content: [
529
+ {
530
+ type: "text",
531
+ text: "Nested delegation is not allowed: this process is already a subagent. Complete the task directly.",
532
+ },
533
+ ],
534
+ details: makeDetails("single")([]),
535
+ isError: true,
536
+ };
537
+ }
538
+ const hasChain = (params.chain?.length ?? 0) > 0;
539
+ const hasTasks = (params.tasks?.length ?? 0) > 0;
540
+ const hasSingle = Boolean(params.agent && params.task);
541
+ const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle);
542
+ if (modeCount !== 1) {
543
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
544
+ return {
545
+ content: [
546
+ {
547
+ type: "text",
548
+ text: `Invalid parameters. Provide exactly one mode.\nAvailable agents: ${available}`,
549
+ },
550
+ ],
551
+ details: makeDetails("single")(stubAllChildren("not run: invalid parameters (provide exactly one mode)")),
552
+ };
553
+ }
554
+ if ((agentScope === "project" || agentScope === "both") && confirmProjectAgents && ctx?.hasUI) {
555
+ const requestedAgentNames = new Set();
556
+ if (params.chain)
557
+ for (const step of params.chain)
558
+ requestedAgentNames.add(step.agent);
559
+ if (params.tasks)
560
+ for (const t of params.tasks)
561
+ requestedAgentNames.add(t.agent);
562
+ if (params.agent)
563
+ requestedAgentNames.add(params.agent);
564
+ const projectAgentsRequested = Array.from(requestedAgentNames)
565
+ .map((name) => agents.find((a) => a.name === name))
566
+ .filter((a) => a?.source === "project");
567
+ if (projectAgentsRequested.length > 0) {
568
+ const names = projectAgentsRequested.map((a) => a.name).join(", ");
569
+ const dir = discovery.projectAgentsDir ?? "(unknown)";
570
+ const ok = await ctx.ui.confirm("Run project-local agents?", `Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`);
571
+ if (!ok)
572
+ return {
573
+ content: [{ type: "text", text: "Canceled: project-local agents not approved." }],
574
+ details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")(stubAllChildren("canceled: project-local agents not approved")),
575
+ isError: true,
576
+ };
577
+ }
578
+ }
579
+ if (params.chain && params.chain.length > 0) {
580
+ const results = [];
581
+ let previousOutput = "";
582
+ for (let i = 0; i < params.chain.length; i++) {
583
+ const step = params.chain[i];
584
+ const taskWithContext = step.task.replace(/\{previous\}/g, previousOutput);
585
+ // Create update callback that includes all previous results
586
+ const chainUpdate = onUpdate
587
+ ? (partial) => {
588
+ // Combine completed results with current streaming result
589
+ const currentResult = partial.details?.results[0];
590
+ if (currentResult) {
591
+ const allResults = [...results, currentResult];
592
+ onUpdate({
593
+ content: partial.content,
594
+ details: makeDetails("chain")(allResults),
595
+ });
596
+ }
597
+ }
598
+ : undefined;
599
+ const result = await runSingleAgent(defaultCwd, agents, step.agent, taskWithContext, step.cwd, i + 1, signal, chainUpdate, makeDetails("chain"));
600
+ results.push(result);
601
+ const isError = isFailedResult(result);
602
+ if (isError) {
603
+ const errorMsg = getResultOutput(result);
604
+ const skipped = params.chain
605
+ .slice(i + 1)
606
+ .map((s, offset) => stubResult({ agent: s.agent, task: s.task, step: i + 2 + offset }, `not run: chain stopped at step ${i + 1}`));
607
+ return {
608
+ content: [{ type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` }],
609
+ details: makeDetails("chain")([...results, ...skipped]),
610
+ isError: true,
611
+ };
612
+ }
613
+ previousOutput = getFinalOutput(result.messages);
614
+ }
615
+ return {
616
+ content: [{ type: "text", text: getFinalOutput(results[results.length - 1].messages) || "(no output)" }],
617
+ details: makeDetails("chain")(results),
618
+ };
619
+ }
620
+ if (params.tasks && params.tasks.length > 0) {
621
+ if (params.tasks.length > MAX_PARALLEL_TASKS)
622
+ return {
623
+ content: [
624
+ {
625
+ type: "text",
626
+ text: `Too many parallel tasks (${params.tasks.length}). Max is ${MAX_PARALLEL_TASKS}.`,
627
+ },
628
+ ],
629
+ details: makeDetails("parallel")(stubAllChildren(`not run: too many parallel tasks (max ${MAX_PARALLEL_TASKS})`)),
630
+ isError: true,
631
+ };
632
+ // Track all results for streaming updates
633
+ const allResults = new Array(params.tasks.length);
634
+ // Initialize placeholder results
635
+ for (let i = 0; i < params.tasks.length; i++) {
636
+ allResults[i] = {
637
+ agent: params.tasks[i].agent,
638
+ agentSource: "unknown",
639
+ task: params.tasks[i].task,
640
+ exitCode: -1, // -1 = still running
641
+ messages: [],
642
+ stderr: "",
643
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
644
+ };
645
+ }
646
+ const emitParallelUpdate = () => {
647
+ if (onUpdate) {
648
+ const running = allResults.filter((r) => r.exitCode === -1).length;
649
+ const done = allResults.filter((r) => r.exitCode !== -1).length;
650
+ onUpdate({
651
+ content: [
652
+ { type: "text", text: `Parallel: ${done}/${allResults.length} done, ${running} running...` },
653
+ ],
654
+ details: makeDetails("parallel")([...allResults]),
655
+ });
656
+ }
657
+ };
658
+ const results = await mapWithConcurrencyLimit(params.tasks, MAX_CONCURRENCY, async (t, index) => {
659
+ const result = await runSingleAgent(defaultCwd, agents, t.agent, t.task, t.cwd, undefined, signal,
660
+ // Per-task update callback
661
+ (partial) => {
662
+ if (partial.details?.results[0]) {
663
+ allResults[index] = partial.details.results[0];
664
+ emitParallelUpdate();
665
+ }
666
+ }, makeDetails("parallel"));
667
+ allResults[index] = result;
668
+ emitParallelUpdate();
669
+ return result;
670
+ }, signal);
671
+ const successCount = results.filter((r) => !isFailedResult(r)).length;
672
+ const summaries = results.map((r) => {
673
+ const output = truncateParallelOutput(getResultOutput(r));
674
+ const status = isFailedResult(r)
675
+ ? `failed${r.stopReason && r.stopReason !== "end" ? ` (${r.stopReason})` : ""}`
676
+ : "completed";
677
+ return `### [${r.agent}] ${status}\n\n${output}`;
678
+ });
679
+ return {
680
+ content: [
681
+ {
682
+ type: "text",
683
+ text: `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n---\n\n")}`,
684
+ },
685
+ ],
686
+ details: makeDetails("parallel")(results),
687
+ };
688
+ }
689
+ if (params.agent && params.task) {
690
+ const result = await runSingleAgent(defaultCwd, agents, params.agent, params.task, params.cwd, undefined, signal, onUpdate, makeDetails("single"));
691
+ const isError = isFailedResult(result);
692
+ if (isError) {
693
+ const errorMsg = getResultOutput(result);
694
+ return {
695
+ content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }],
696
+ details: makeDetails("single")([result]),
697
+ isError: true,
698
+ };
699
+ }
700
+ return {
701
+ content: [{ type: "text", text: getFinalOutput(result.messages) || "(no output)" }],
702
+ details: makeDetails("single")([result]),
703
+ };
704
+ }
705
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
706
+ return {
707
+ content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }],
708
+ details: makeDetails("single")([]),
709
+ };
710
+ },
711
+ renderCall(args, theme, _context) {
712
+ const scope = args.agentScope ?? "user";
713
+ if (args.chain && args.chain.length > 0) {
714
+ let text = theme.fg("toolTitle", theme.bold("subagent ")) +
715
+ theme.fg("accent", `chain (${args.chain.length} steps)`) +
716
+ theme.fg("muted", ` [${scope}]`);
717
+ for (let i = 0; i < Math.min(args.chain.length, 3); i++) {
718
+ const step = args.chain[i];
719
+ // Clean up {previous} placeholder for display
720
+ const cleanTask = step.task.replace(/\{previous\}/g, "").trim();
721
+ const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask;
722
+ text +=
723
+ "\n " +
724
+ theme.fg("muted", `${i + 1}.`) +
725
+ " " +
726
+ theme.fg("accent", step.agent) +
727
+ theme.fg("dim", ` ${preview}`);
728
+ }
729
+ if (args.chain.length > 3)
730
+ text += `\n ${theme.fg("muted", `... +${args.chain.length - 3} more`)}`;
731
+ return new Text(text, 0, 0);
732
+ }
733
+ if (args.tasks && args.tasks.length > 0) {
734
+ let text = theme.fg("toolTitle", theme.bold("subagent ")) +
735
+ theme.fg("accent", `parallel (${args.tasks.length} tasks)`) +
736
+ theme.fg("muted", ` [${scope}]`);
737
+ for (const t of args.tasks.slice(0, 3)) {
738
+ const preview = t.task.length > 40 ? `${t.task.slice(0, 40)}...` : t.task;
739
+ text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", ` ${preview}`)}`;
740
+ }
741
+ if (args.tasks.length > 3)
742
+ text += `\n ${theme.fg("muted", `... +${args.tasks.length - 3} more`)}`;
743
+ return new Text(text, 0, 0);
744
+ }
745
+ const agentName = args.agent || "...";
746
+ const preview = args.task ? (args.task.length > 60 ? `${args.task.slice(0, 60)}...` : args.task) : "...";
747
+ let text = theme.fg("toolTitle", theme.bold("subagent ")) +
748
+ theme.fg("accent", agentName) +
749
+ theme.fg("muted", ` [${scope}]`);
750
+ text += `\n ${theme.fg("dim", preview)}`;
751
+ return new Text(text, 0, 0);
752
+ },
753
+ renderResult(result, { expanded }, theme, _context) {
754
+ const details = result.details;
755
+ if (!details || details.results.length === 0) {
756
+ const text = result.content[0];
757
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
758
+ }
759
+ const mdTheme = getMarkdownTheme();
760
+ const renderDisplayItems = (items, limit) => {
761
+ const toShow = limit ? items.slice(-limit) : items;
762
+ const skipped = limit && items.length > limit ? items.length - limit : 0;
763
+ let text = "";
764
+ if (skipped > 0)
765
+ text += theme.fg("muted", `... ${skipped} earlier items\n`);
766
+ for (const item of toShow) {
767
+ if (item.type === "text") {
768
+ const preview = expanded ? item.text : item.text.split("\n").slice(0, 3).join("\n");
769
+ text += `${theme.fg("toolOutput", preview)}\n`;
770
+ }
771
+ else {
772
+ text += `${theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme))}\n`;
773
+ }
774
+ }
775
+ return text.trimEnd();
776
+ };
777
+ if (details.mode === "single" && details.results.length === 1) {
778
+ const r = details.results[0];
779
+ const isError = isFailedResult(r);
780
+ const icon = isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
781
+ const displayItems = getDisplayItems(r.messages);
782
+ const finalOutput = getFinalOutput(r.messages);
783
+ if (expanded) {
784
+ const container = new Container();
785
+ let header = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
786
+ if (isError && r.stopReason)
787
+ header += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
788
+ container.addChild(new Text(header, 0, 0));
789
+ if (isError && r.errorMessage)
790
+ container.addChild(new Text(theme.fg("error", `Error: ${r.errorMessage}`), 0, 0));
791
+ container.addChild(new Spacer(1));
792
+ container.addChild(new Text(theme.fg("muted", "─── Task ───"), 0, 0));
793
+ container.addChild(new Text(theme.fg("dim", r.task), 0, 0));
794
+ container.addChild(new Spacer(1));
795
+ container.addChild(new Text(theme.fg("muted", "─── Output ───"), 0, 0));
796
+ if (displayItems.length === 0 && !finalOutput) {
797
+ container.addChild(new Text(theme.fg("muted", "(no output)"), 0, 0));
798
+ }
799
+ else {
800
+ for (const item of displayItems) {
801
+ if (item.type === "toolCall")
802
+ container.addChild(new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), 0, 0));
803
+ }
804
+ if (finalOutput) {
805
+ container.addChild(new Spacer(1));
806
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
807
+ }
808
+ }
809
+ const usageStr = formatUsageStats(r.usage, r.model);
810
+ if (usageStr) {
811
+ container.addChild(new Spacer(1));
812
+ container.addChild(new Text(theme.fg("dim", usageStr), 0, 0));
813
+ }
814
+ return container;
815
+ }
816
+ let text = `${icon} ${theme.fg("toolTitle", theme.bold(r.agent))}${theme.fg("muted", ` (${r.agentSource})`)}`;
817
+ if (isError && r.stopReason)
818
+ text += ` ${theme.fg("error", `[${r.stopReason}]`)}`;
819
+ if (isError && r.errorMessage)
820
+ text += `\n${theme.fg("error", `Error: ${r.errorMessage}`)}`;
821
+ else if (displayItems.length === 0)
822
+ text += `\n${theme.fg("muted", "(no output)")}`;
823
+ else {
824
+ text += `\n${renderDisplayItems(displayItems, COLLAPSED_ITEM_COUNT)}`;
825
+ if (displayItems.length > COLLAPSED_ITEM_COUNT)
826
+ text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
827
+ }
828
+ const usageStr = formatUsageStats(r.usage, r.model);
829
+ if (usageStr)
830
+ text += `\n${theme.fg("dim", usageStr)}`;
831
+ return new Text(text, 0, 0);
832
+ }
833
+ const aggregateUsage = (results) => {
834
+ const total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
835
+ for (const r of results) {
836
+ total.input += r.usage.input;
837
+ total.output += r.usage.output;
838
+ total.cacheRead += r.usage.cacheRead;
839
+ total.cacheWrite += r.usage.cacheWrite;
840
+ total.cost += r.usage.cost;
841
+ total.turns += r.usage.turns;
842
+ }
843
+ return total;
844
+ };
845
+ if (details.mode === "chain") {
846
+ const successCount = details.results.filter((r) => r.exitCode === 0).length;
847
+ const icon = successCount === details.results.length ? theme.fg("success", "✓") : theme.fg("error", "✗");
848
+ if (expanded) {
849
+ const container = new Container();
850
+ container.addChild(new Text(icon +
851
+ " " +
852
+ theme.fg("toolTitle", theme.bold("chain ")) +
853
+ theme.fg("accent", `${successCount}/${details.results.length} steps`), 0, 0));
854
+ for (const r of details.results) {
855
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
856
+ const displayItems = getDisplayItems(r.messages);
857
+ const finalOutput = getFinalOutput(r.messages);
858
+ container.addChild(new Spacer(1));
859
+ container.addChild(new Text(`${theme.fg("muted", `─── Step ${r.step}: `) + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0));
860
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
861
+ // Show tool calls
862
+ for (const item of displayItems) {
863
+ if (item.type === "toolCall") {
864
+ container.addChild(new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), 0, 0));
865
+ }
866
+ }
867
+ // Show final output as markdown
868
+ if (finalOutput) {
869
+ container.addChild(new Spacer(1));
870
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
871
+ }
872
+ const stepUsage = formatUsageStats(r.usage, r.model);
873
+ if (stepUsage)
874
+ container.addChild(new Text(theme.fg("dim", stepUsage), 0, 0));
875
+ }
876
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
877
+ if (usageStr) {
878
+ container.addChild(new Spacer(1));
879
+ container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
880
+ }
881
+ return container;
882
+ }
883
+ // Collapsed view
884
+ let text = icon +
885
+ " " +
886
+ theme.fg("toolTitle", theme.bold("chain ")) +
887
+ theme.fg("accent", `${successCount}/${details.results.length} steps`);
888
+ for (const r of details.results) {
889
+ const rIcon = r.exitCode === 0 ? theme.fg("success", "✓") : theme.fg("error", "✗");
890
+ const displayItems = getDisplayItems(r.messages);
891
+ text += `\n\n${theme.fg("muted", `─── Step ${r.step}: `)}${theme.fg("accent", r.agent)} ${rIcon}`;
892
+ if (displayItems.length === 0)
893
+ text += `\n${theme.fg("muted", "(no output)")}`;
894
+ else
895
+ text += `\n${renderDisplayItems(displayItems, 5)}`;
896
+ }
897
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
898
+ if (usageStr)
899
+ text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
900
+ text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
901
+ return new Text(text, 0, 0);
902
+ }
903
+ if (details.mode === "parallel") {
904
+ const running = details.results.filter((r) => r.exitCode === -1).length;
905
+ const successCount = details.results.filter((r) => r.exitCode !== -1 && !isFailedResult(r)).length;
906
+ const failCount = details.results.filter((r) => r.exitCode !== -1 && isFailedResult(r)).length;
907
+ const isRunning = running > 0;
908
+ const icon = isRunning
909
+ ? theme.fg("warning", "⏳")
910
+ : failCount > 0
911
+ ? theme.fg("warning", "◐")
912
+ : theme.fg("success", "✓");
913
+ const status = isRunning
914
+ ? `${successCount + failCount}/${details.results.length} done, ${running} running`
915
+ : `${successCount}/${details.results.length} tasks`;
916
+ if (expanded && !isRunning) {
917
+ const container = new Container();
918
+ container.addChild(new Text(`${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`, 0, 0));
919
+ for (const r of details.results) {
920
+ const rIcon = isFailedResult(r) ? theme.fg("error", "✗") : theme.fg("success", "✓");
921
+ const displayItems = getDisplayItems(r.messages);
922
+ const finalOutput = getFinalOutput(r.messages);
923
+ container.addChild(new Spacer(1));
924
+ container.addChild(new Text(`${theme.fg("muted", "─── ") + theme.fg("accent", r.agent)} ${rIcon}`, 0, 0));
925
+ container.addChild(new Text(theme.fg("muted", "Task: ") + theme.fg("dim", r.task), 0, 0));
926
+ // Show tool calls
927
+ for (const item of displayItems) {
928
+ if (item.type === "toolCall") {
929
+ container.addChild(new Text(theme.fg("muted", "→ ") + formatToolCall(item.name, item.args, theme.fg.bind(theme)), 0, 0));
930
+ }
931
+ }
932
+ // Show final output as markdown
933
+ if (finalOutput) {
934
+ container.addChild(new Spacer(1));
935
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
936
+ }
937
+ const taskUsage = formatUsageStats(r.usage, r.model);
938
+ if (taskUsage)
939
+ container.addChild(new Text(theme.fg("dim", taskUsage), 0, 0));
940
+ }
941
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
942
+ if (usageStr) {
943
+ container.addChild(new Spacer(1));
944
+ container.addChild(new Text(theme.fg("dim", `Total: ${usageStr}`), 0, 0));
945
+ }
946
+ return container;
947
+ }
948
+ // Collapsed view (or still running)
949
+ let text = `${icon} ${theme.fg("toolTitle", theme.bold("parallel "))}${theme.fg("accent", status)}`;
950
+ for (const r of details.results) {
951
+ const rIcon = r.exitCode === -1
952
+ ? theme.fg("warning", "⏳")
953
+ : isFailedResult(r)
954
+ ? theme.fg("error", "✗")
955
+ : theme.fg("success", "✓");
956
+ const displayItems = getDisplayItems(r.messages);
957
+ text += `\n\n${theme.fg("muted", "─── ")}${theme.fg("accent", r.agent)} ${rIcon}`;
958
+ if (displayItems.length === 0)
959
+ text += `\n${theme.fg("muted", r.exitCode === -1 ? "(running...)" : "(no output)")}`;
960
+ else
961
+ text += `\n${renderDisplayItems(displayItems, 5)}`;
962
+ }
963
+ if (!isRunning) {
964
+ const usageStr = formatUsageStats(aggregateUsage(details.results));
965
+ if (usageStr)
966
+ text += `\n\n${theme.fg("dim", `Total: ${usageStr}`)}`;
967
+ }
968
+ if (!expanded)
969
+ text += `\n${theme.fg("muted", "(Ctrl+O to expand)")}`;
970
+ return new Text(text, 0, 0);
971
+ }
972
+ const text = result.content[0];
973
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
974
+ },
975
+ };
976
+ }
977
+ export function createSubagentTool(cwd) {
978
+ return wrapToolDefinition(createSubagentToolDefinition(cwd));
979
+ }
980
+ //# sourceMappingURL=subagent.js.map