index.ts 34 KB

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