xonecas.io
64875
Mc

mini-coder / commit 821fe71

feat: stream parallel subagent activity with labeled lanes

Sean2026-02-28 821fe71b9d6b07e5df0af9facca9a45a977a4bf6 parent 15ca66b

5 files changed

src/agent/agent.ts+17−24
@@ -12,10 +12,12 @@ import { readline, type InputResult } from "../cli/input.ts";
1212 import {
1313 PREFIX,
1414 Spinner,
15+ formatSubagentLabel,
1516 renderError,
1617 renderHook,
1718 renderInfo,
1819 renderStatusBar,
20+ renderSubagentEvent,
1921 renderTurn,
2022 restoreTerminal,
2123 tildePath,
@@ -32,7 +34,7 @@ import {
3234 restoreSnapshot,
3335 takeSnapshot,
3436 } from "../tools/snapshot.ts";
35-import type { SubagentOutput, SubagentToolEntry } from "../tools/subagent.ts";
37+import type { SubagentOutput } from "../tools/subagent.ts";
3638
3739 import {
3840 deleteAllSnapshots,
@@ -184,6 +186,9 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
184186 // so we can trim or rebuild without mutating the in-memory DB copy.
185187 const coreHistory: CoreMessage[] = [...session.messages];
186188
189+ let nextLaneId = 1;
190+ const activeLanes = new Set<number>();
191+
187192 // Subagent runner (recursive) — depth prevents infinite recursion.
188193 // agentName: optional custom agent to run (looks up .agents/agents/<name>.md).
189194 // modelOverride: explicit model to use (for /review and custom commands).
@@ -192,6 +197,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
192197 depth = 0,
193198 agentName?: string,
194199 modelOverride?: string,
200+ parentLabel?: string,
195201 ): Promise<SubagentOutput> => {
196202 // Resolve custom agent config if an agentName was specified
197203 const allAgents = loadAgents(cwd);
@@ -206,12 +212,17 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
206212 const systemPrompt = agentConfig?.systemPrompt ?? buildSystemPrompt(cwd);
207213
208214 const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
215+ const laneId = nextLaneId++;
216+ activeLanes.add(laneId);
217+ const laneLabel = formatSubagentLabel(laneId, parentLabel);
218+
209219 const subTools = buildToolSet({
210220 cwd,
211221 depth,
212222 runSubagent,
213223 onHook: renderHook,
214224 availableAgents: allAgents,
225+ parentLabel: laneLabel,
215226 });
216227
217228 const subLlm = resolveModel(model);
@@ -219,10 +230,6 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
219230 let result = "";
220231 let inputTokens = 0;
221232 let outputTokens = 0;
222- const activity: SubagentToolEntry[] = [];
223-
224- // Track pending tool call so we can pair it with its result
225- const pendingCalls = new Map<string, { toolName: string; args: unknown }>();
226233
227234 const events = runTurn({
228235 model: subLlm,
@@ -232,32 +239,18 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
232239 });
233240
234241 for await (const event of events) {
242+ spinner.stop();
243+ renderSubagentEvent(event, { laneId, parentLabel, activeLanes });
244+ spinner.start("thinking");
235245 if (event.type === "text-delta") result += event.delta;
236- if (event.type === "tool-call-start") {
237- pendingCalls.set(event.toolCallId, {
238- toolName: event.toolName,
239- args: event.args,
240- });
241- }
242- if (event.type === "tool-result") {
243- const pending = pendingCalls.get(event.toolCallId);
244- if (pending) {
245- pendingCalls.delete(event.toolCallId);
246- activity.push({
247- toolName: pending.toolName,
248- args: pending.args,
249- result: event.result,
250- isError: event.isError,
251- });
252- }
253- }
254246 if (event.type === "turn-complete") {
255247 inputTokens = event.inputTokens;
256248 outputTokens = event.outputTokens;
257249 }
258250 }
259251
260- return { result, inputTokens, outputTokens, activity };
252+ activeLanes.delete(laneId);
253+ return { result, inputTokens, outputTokens };
261254 };
262255
263256 // ── MCP: load persisted servers and connect them ───────────────────────────
src/agent/tools.ts+21−8
@@ -103,10 +103,13 @@ export function buildToolSet(opts: {
103103 prompt: string,
104104 depth?: number,
105105 agentName?: string,
106+ modelOverride?: string,
107+ parentLabel?: string,
106108 ) => Promise<SubagentOutput>;
107109
108110 onHook: (toolName: string, scriptPath: string, success: boolean) => void;
109111 availableAgents: ReadonlyMap<string, { description: string }>;
112+ parentLabel?: string;
110113 }): ToolDef[] {
111114 const { cwd, onHook } = opts;
112115 const depth = opts.depth ?? 0;
@@ -186,15 +189,25 @@ export function buildToolSet(opts: {
186189 (result, input) => hookEnvForShell(result, input, cwd),
187190 onHook,
188191 ) as ToolDef,
189- createSubagentTool(async (prompt, agentName) => {
190- if (depth >= MAX_SUBAGENT_DEPTH) {
191- throw new Error(
192- `Subagent depth limit reached (max ${MAX_SUBAGENT_DEPTH}). ` +
193- `Cannot spawn another subagent from depth ${depth}.`,
192+ createSubagentTool(
193+ async (prompt, agentName) => {
194+ if (depth >= MAX_SUBAGENT_DEPTH) {
195+ throw new Error(
196+ `Subagent depth limit reached (max ${MAX_SUBAGENT_DEPTH}). ` +
197+ `Cannot spawn another subagent from depth ${depth}.`,
198+ );
199+ }
200+ return opts.runSubagent(
201+ prompt,
202+ depth + 1,
203+ agentName,
204+ undefined,
205+ opts.parentLabel,
194206 );
195- }
196- return opts.runSubagent(prompt, depth + 1, agentName);
197- }, opts.availableAgents) as ToolDef,
207+ },
208+ opts.availableAgents,
209+ opts.parentLabel,
210+ ) as ToolDef,
198211 ];
199212 }
200213
src/cli/commands.ts+1−19
@@ -14,14 +14,7 @@ import {
1414 loadCustomCommands,
1515 } from "./custom-commands.ts";
1616 import { renderMarkdown } from "./markdown.ts";
17-import {
18- PREFIX,
19- renderError,
20- renderInfo,
21- renderSubagentActivity,
22- write,
23- writeln,
24-} from "./output.ts";
17+import { PREFIX, renderError, renderInfo, write, writeln } from "./output.ts";
2518 import { loadSkills } from "./skills.ts";
2619
2720 // ─── Types ────────────────────────────────────────────────────────────────────
@@ -297,12 +290,6 @@ async function handleReview(
297290 try {
298291 const output = await ctx.runSubagent(REVIEW_PROMPT(ctx.cwd, focus));
299292
300- // Show subagent activity tree.
301- if (output.activity.length) {
302- renderSubagentActivity(output.activity, " ", 1);
303- writeln();
304- }
305-
306293 // Show review results.
307294 write(renderMarkdown(output.result));
308295 writeln();
@@ -345,11 +332,6 @@ async function handleCustomCommand(
345332 try {
346333 const output = await ctx.runSubagent(prompt, cmd.model);
347334
348- if (output.activity.length) {
349- renderSubagentActivity(output.activity, " ", 1);
350- writeln();
351- }
352-
353335 write(renderMarkdown(output.result));
354336 writeln();
355337
src/cli/output.ts+59−44
@@ -3,7 +3,7 @@ import { homedir } from "node:os";
33 import * as c from "yoctocolors";
44 import type { CoreMessage } from "../llm-api/turn.ts";
55 import type { TurnEvent } from "../llm-api/types.ts";
6-import type { SubagentOutput, SubagentToolEntry } from "../tools/subagent.ts";
6+import type { SubagentOutput } from "../tools/subagent.ts";
77 import { renderChunk } from "./markdown.ts";
88
99 const HOME = homedir();
@@ -305,12 +305,7 @@ function renderToolResultInline(
305305 }
306306
307307 if (toolName === "subagent") {
308- const r = result as { inputTokens?: number; outputTokens?: number };
309- if (r.inputTokens || r.outputTokens) {
310- writeln(
311- `${indent}${G.ok} ${c.dim(`↑${r.inputTokens ?? 0} ↓${r.outputTokens ?? 0}`)}`,
312- );
313- }
308+ // Activity and token counts are now streamed live.
314309 return;
315310 }
316311
@@ -334,32 +329,68 @@ function renderToolResultInline(
334329 );
335330 }
336331
337-/** Render a subagent's activity tree, indented under its parent tool-call line. */
338-export function renderSubagentActivity(
339- activity: SubagentToolEntry[],
332+export function formatSubagentLabel(
333+ laneId: number,
334+ parentLabel?: string,
335+): string {
336+ const numStr = parentLabel
337+ ? `${parentLabel.replace(/[\[\]]/g, "")}.${laneId}`
338+ : `${laneId}`;
339+ return c.dim(c.cyan(`[${numStr}]`));
340+}
340341
341- indent: string,
342- maxDepth: number,
342+const laneBuffers = new Map<number, string>();
343+
344+export function renderSubagentEvent(
345+ event: TurnEvent,
346+ opts: {
347+ laneId: number;
348+ parentLabel?: string | undefined;
349+ activeLanes: Set<number>;
350+ },
343351 ): void {
344- for (const entry of activity) {
345- writeln(`${indent}${toolCallLine(entry.toolName, entry.args)}`);
346-
347- // For nested subagents, recurse one more level (capped at maxDepth)
348- if (entry.toolName === "subagent" && maxDepth > 0) {
349- const nested = entry.result as {
350- activity?: SubagentToolEntry[];
351- };
352- if (nested?.activity?.length) {
353- renderSubagentActivity(nested.activity, `${indent} `, maxDepth - 1);
352+ const { laneId, parentLabel, activeLanes } = opts;
353+
354+ const labelStr = formatSubagentLabel(laneId, parentLabel);
355+ const prefix = activeLanes.size > 1 ? `${labelStr} ` : "";
356+
357+ if (event.type === "text-delta") {
358+ const buf = (laneBuffers.get(laneId) ?? "") + event.delta;
359+ const lines = buf.split("\n");
360+ if (lines.length > 1) {
361+ for (let i = 0; i < lines.length - 1; i++) {
362+ writeln(`${prefix}${lines[i]}`);
354363 }
364+ laneBuffers.set(laneId, lines[lines.length - 1] ?? "");
365+ } else {
366+ laneBuffers.set(laneId, buf);
355367 }
356-
368+ } else if (event.type === "tool-call-start") {
369+ writeln(`${prefix}${toolCallLine(event.toolName, event.args)}`);
370+ } else if (event.type === "tool-result") {
371+ // Use inlineResultSummary logic directly here
357372 renderToolResultInline(
358- entry.toolName,
359- entry.result,
360- entry.isError,
361- `${indent} `,
373+ event.toolName,
374+ event.result,
375+ event.isError,
376+ `${prefix} `,
362377 );
378+ } else if (event.type === "turn-complete") {
379+ // Flush buffer if any
380+ const buf = laneBuffers.get(laneId);
381+ if (buf) {
382+ writeln(`${prefix}${buf}`);
383+ laneBuffers.delete(laneId);
384+ }
385+ if (event.inputTokens > 0 || event.outputTokens > 0) {
386+ writeln(
387+ `${prefix}${c.dim(`↑${event.inputTokens} ↓${event.outputTokens}`)}`,
388+ );
389+ }
390+ } else if (event.type === "turn-error") {
391+ laneBuffers.delete(laneId);
392+ const msg = event.error.message.split("\n")[0] ?? event.error.message;
393+ writeln(`${prefix}${G.err} ${c.red(msg)}`);
363394 }
364395 }
365396
@@ -517,23 +548,7 @@ export function renderToolResult(
517548 }
518549
519550 if (toolName === "subagent") {
520- const r = result as SubagentOutput;
521-
522- // Render the tool call tree before showing the result text
523- if (r.activity?.length) {
524- renderSubagentActivity(r.activity, " ", 1);
525- }
526-
527- if (r.result) {
528- const lines = r.result.split("\n");
529- const preview = lines.slice(0, 8);
530- for (const line of preview) writeln(` ${c.dim("│")} ${line}`);
531- if (lines.length > 8)
532- writeln(` ${c.dim(`│ … +${lines.length - 8} lines`)}`);
533- }
534- if (r.inputTokens || r.outputTokens) {
535- writeln(` ${c.dim(`↑${r.inputTokens ?? 0} ↓${r.outputTokens ?? 0}`)}`);
536- }
551+ // Activity and tokens are streamed live.
537552 return;
538553 }
539554
src/tools/subagent.ts+7−10
@@ -13,18 +13,10 @@ const SubagentInput = z.object({
1313
1414 type SubagentInput = z.infer<typeof SubagentInput>;
1515
16-export interface SubagentToolEntry {
17- toolName: string;
18- args: unknown;
19- result: unknown;
20- isError: boolean;
21-}
22-
2316 export interface SubagentOutput {
2417 result: string;
2518 inputTokens: number;
2619 outputTokens: number;
27- activity: SubagentToolEntry[];
2820 }
2921
3022 /**
@@ -34,8 +26,13 @@ export interface SubagentOutput {
3426 * the agent without creating a circular import.
3527 */
3628 export function createSubagentTool(
37- runSubagent: (prompt: string, agentName?: string) => Promise<SubagentOutput>,
29+ runSubagent: (
30+ prompt: string,
31+ agentName?: string,
32+ parentLabel?: string,
33+ ) => Promise<SubagentOutput>,
3834 availableAgents: ReadonlyMap<string, { description: string }>,
35+ parentLabel?: string,
3936 ): ToolDef<SubagentInput, SubagentOutput> {
4037 const agentSection =
4138 availableAgents.size > 0
@@ -46,7 +43,7 @@ export function createSubagentTool(
4643 description: `Spawn a sub-agent to handle a focused subtask. Use this for parallel exploration, specialised analysis, or tasks that benefit from a fresh context window. The subagent has access to all the same tools.${agentSection}`,
4744 schema: SubagentInput,
4845 execute: async (input) => {
49- return runSubagent(input.prompt, input.agentName);
46+ return runSubagent(input.prompt, input.agentName, parentLabel);
5047 },
5148 };
5249 }