import type { AgentSessionEvent, ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent"; import { createAgentSession, DefaultResourceLoader, getAgentDir, getMarkdownTheme, SessionManager, } from "@earendil-works/pi-coding-agent"; import { StringEnum } from "@earendil-works/pi-ai"; import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; import { type AgentConfig, type AgentScope, discoverAgents, formatAgentCatalog, formatAvailableAgents, resolveAgent } from "./agents.ts"; import { createIntercomTools, type IntercomHandlers } from "./intercom.ts"; import { createWatchdog } from "./watchdog.ts"; const DEFAULT_CONCURRENCY = 3; const MAX_CONCURRENCY = 8; const MAX_TASKS = 16; const DEFAULT_RUNTIME_MS = 10 * 60 * 1000; const DEFAULT_STALL_MS = 90_000; // watchdog: no-event timeout const DEFAULT_READONLY_TOOLS = ["read", "grep", "find", "ls"]; const FINAL_OUTPUT_CAP = 24 * 1024; type RunMode = "single" | "parallel" | "chain"; type TaskStatus = "queued" | "starting" | "running" | "awaiting_parent" | "completed" | "failed" | "aborted"; type RunStatus = "queued" | "running" | "awaiting_parent" | "completed" | "failed" | "aborted"; const TERMINAL_TASK: TaskStatus[] = ["completed", "failed", "aborted"]; interface UsageStats { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number; turns: number; } interface TaskInput { id?: string; agent: string; task: string; cwd?: string; model?: string; thinking?: string; tools?: string[]; maxRuntimeMs?: number; } interface TaskSnapshot { id: string; runId: string; index: number; agent: string; task: string; cwd: string; status: TaskStatus; agentSource?: "user" | "project" | "pi-web" | "unknown"; sessionId?: string; sessionFile?: string; model?: string; thinking?: string; tools?: string[]; startedAt?: number; endedAt?: number; lastEventAt?: number; currentTool?: { toolCallId: string; toolName: string; args: unknown; startedAt: number }; progressPhase?: string; intercomQuestion?: string; // set while awaiting_parent (ask_parent) usage: UsageStats; finalText?: string; error?: string; } interface RunSnapshot { id: string; parentSessionId?: string; parentToolCallId: string; mode: RunMode; status: RunStatus; background: boolean; allowIntercom: boolean; createdAt: number; startedAt?: number; endedAt?: number; concurrency: number; stallMs: number; tasks: TaskSnapshot[]; aggregateUsage: UsageStats; } interface RunDetails { run: RunSnapshot; agents: Array<{ name: string; description: string; source: string; filePath: string; id?: string }>; background?: boolean; } interface ChildFailure { status: Extract; message: string; } interface PendingReply { resolve: (answer: string) => void; question: string; askedAt: number; } function newId(prefix: string): string { return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`; } function emptyUsage(): UsageStats { return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 }; } function aggregateUsage(tasks: TaskSnapshot[]): UsageStats { const total = emptyUsage(); for (const task of tasks) { total.input += task.usage.input; total.output += task.usage.output; total.cacheRead += task.usage.cacheRead; total.cacheWrite += task.usage.cacheWrite; total.cost += task.usage.cost; total.turns += task.usage.turns; } return total; } function truncateText(text: string, max = FINAL_OUTPUT_CAP): string { if (Buffer.byteLength(text, "utf8") <= max) return text; let out = text.slice(0, max); while (Buffer.byteLength(out, "utf8") > max) out = out.slice(0, -1); return `${out}\n\n[Output truncated. Full child session is available in the session file.]`; } function previewValue(value: unknown, max = 1024): unknown { if (typeof value === "string") return truncateText(value, max); try { return truncateText(JSON.stringify(value), max); } catch { return String(value); } } function getFirstText(message: any): string { for (const part of message?.content ?? []) { if (part?.type === "text" && typeof part.text === "string") return part.text; } return ""; } function getParentSessionFile(ctx: ExtensionContext): string | undefined { try { return ctx.sessionManager.getSessionFile?.(); } catch { return undefined; } } /** * Classify ANY non-normal assistant termination as a failure. Previously only * "error"/"aborted" were caught, which let max_tokens/refusal/etc slip through * and leave the parent hanging. This is the core reliability fix. */ function classifyFailure(stopReason: string | undefined, errorMessage?: string): ChildFailure | undefined { if (!stopReason || stopReason === "end") return undefined; if (stopReason === "aborted") return { status: "aborted", message: errorMessage || "Subagent was aborted." }; return { status: "failed", message: errorMessage || `Subagent ended with stopReason "${stopReason}".` }; } function getAssistantFailure(message: any): ChildFailure | undefined { if (message?.role !== "assistant") return undefined; return classifyFailure(message.stopReason, message.errorMessage); } function getLastAssistantFailure(messages: any[] | undefined): ChildFailure | undefined { for (const message of [...(messages ?? [])].reverse()) { const failure = getAssistantFailure(message); if (failure) return failure; if (message?.role === "assistant") return undefined; } return undefined; } function makeChildFailureError(failure: ChildFailure): Error { const error = new Error(failure.message); (error as Error & { subagentStatus?: ChildFailure["status"] }).subagentStatus = failure.status; return error; } function updateUsageFromMessage(task: TaskSnapshot, message: any): void { if (message?.role !== "assistant") return; task.usage.turns += 1; const usage = message.usage; if (!usage) return; task.usage.input += usage.input ?? 0; task.usage.output += usage.output ?? 0; task.usage.cacheRead += usage.cacheRead ?? 0; task.usage.cacheWrite += usage.cacheWrite ?? 0; task.usage.cost += usage.cost?.total ?? usage.cost ?? 0; if (message.model && !task.model) task.model = message.model; } function formatUsage(usage: UsageStats): string { const parts: string[] = []; if (usage.turns) parts.push(`${usage.turns} turn${usage.turns > 1 ? "s" : ""}`); if (usage.input) parts.push(`in ${usage.input}`); if (usage.output) parts.push(`out ${usage.output}`); if (usage.cost) parts.push(`$${usage.cost.toFixed(4)}`); return parts.join(" · "); } function statusIcon(status: TaskStatus | RunStatus): string { if (status === "completed") return "✓"; if (status === "failed") return "✗"; if (status === "aborted") return "⏹"; if (status === "awaiting_parent") return "❓"; if (status === "queued") return "○"; return "⏳"; } function renderWidgetLines(run: RunSnapshot): string[] { const live = run.tasks.filter((t) => !TERMINAL_TASK.includes(t.status)).length; const done = run.tasks.filter((t) => TERMINAL_TASK.includes(t.status)).length; const tag = run.background ? " (bg)" : ""; const lines = [`Subagents${tag} ${statusIcon(run.status)} ${run.mode}: ${done}/${run.tasks.length} done${live ? `, ${live} live` : ""}`]; for (const task of run.tasks.slice(0, 8)) { const tool = task.currentTool ? ` · ${task.currentTool.toolName}` : task.progressPhase ? ` · ${task.progressPhase}` : ""; lines.push(`${statusIcon(task.status)} ${task.agent}: ${task.status}${tool}`); } if (run.tasks.length > 8) lines.push(`… +${run.tasks.length - 8} more`); return lines; } function makeSummary(run: RunSnapshot): string { const succeeded = run.tasks.filter((t) => t.status === "completed").length; const failed = run.tasks.filter((t) => t.status === "failed").length; const aborted = run.tasks.filter((t) => t.status === "aborted").length; const lines = [ `Subagents ${run.mode}${run.background ? " (background)" : ""} finished: ${succeeded}/${run.tasks.length} succeeded${failed ? `, ${failed} failed` : ""}${aborted ? `, ${aborted} aborted` : ""}.`, ]; const usage = formatUsage(run.aggregateUsage); if (usage) lines.push(`Usage: ${usage}`); for (const task of run.tasks) { const heading = `\n## ${task.agent} ${statusIcon(task.status)}`; const session = task.sessionId ? `\nSession: ${task.sessionId}${task.sessionFile ? ` (${task.sessionFile})` : ""}` : ""; const body = task.error ? `Error: ${task.error}` : truncateText(task.finalText || "(no output)"); lines.push(`${heading}\n${body}${session}`); } return lines.join("\n"); } function cloneRun(run: RunSnapshot): RunSnapshot { return JSON.parse(JSON.stringify(run)) as RunSnapshot; } function parseModelRef(ref: string | undefined): { provider: string; modelId: string } | undefined { if (!ref) return undefined; const index = ref.indexOf("/"); if (index <= 0 || index === ref.length - 1) return undefined; return { provider: ref.slice(0, index), modelId: ref.slice(index + 1) }; } function makeAgentCatalogContext(cwd: string, scope: AgentScope = "user"): string { const discovery = discoverAgents(cwd, scope); return [ "Available subagents for the `subagent` tool:", formatAgentCatalog(discovery.agents), "", "Rules:", "- Use only an exact `name` or `id` from this list in subagent calls.", "- Do not invent agent names such as `pi`, `reviewer`, `tester`, or `analyst` unless they appear above.", "- Choose agents by matching the task to each agent description. If multiple tasks are similar, use the SAME most suitable agent for all of them.", "- Modes: single (agent+task), parallel (tasks), chain (chain with optional {previous}).", "- Set background:true to fire-and-forget a run and keep working; you'll be notified on completion. Use subagent_status / subagent_result / await_subagent / reply_subagent to interact with background runs.", "- Set allowIntercom:true to let a child ask you questions mid-run via ask_parent (use sparingly).", ].join("\n"); } function appendContextMessage(messages: TMessage[], text: string): TMessage[] { return [ ...messages, { role: "user", content: [{ type: "text", text }], timestamp: Date.now() } as TMessage, ]; } function normalizeTask(input: TaskInput, runId: string, index: number, defaultCwd: string): TaskSnapshot { return { id: input.id ?? `task_${index + 1}`, runId, index, agent: input.agent, task: input.task, cwd: input.cwd ?? defaultCwd, status: "queued", model: input.model, thinking: input.thinking, tools: input.tools, usage: emptyUsage(), }; } async function mapWithConcurrency(items: T[], concurrency: number, fn: (item: T, index: number) => Promise): Promise { let next = 0; const workers = Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, async () => { while (next < items.length) { const index = next++; await fn(items[index], index); } }); await Promise.all(workers); } class SubagentManager { private runs = new Map(); private settlers = new Map; resolve: (r: RunSnapshot) => void }>(); private pendingReplies = new Map(); // key: `${runId}:${taskId}` private liveChildren = new Map void; dispose: () => void; touchWatchdog?: () => void }>(); private eventSeq = 0; constructor(private readonly pi: ExtensionAPI) {} listRuns(): RunSnapshot[] { return Array.from(this.runs.values()).sort((a, b) => b.createdAt - a.createdAt); } getRun(runId: string | undefined): RunSnapshot | undefined { return runId ? this.runs.get(runId) : undefined; } clearRuns(): void { this.runs.clear(); this.settlers.clear(); this.pendingReplies.clear(); } async restoreFromSidecar(ctx: ExtensionContext): Promise { const parentFile = getParentSessionFile(ctx); if (!parentFile) return; const sidecar = parentFile.replace(/\.jsonl$/, ".subagents.json"); let runs: RunSnapshot[] | undefined; try { const { readFileSync, existsSync } = await import("fs"); if (!existsSync(sidecar)) return; const raw = JSON.parse(readFileSync(sidecar, "utf-8")); if (!Array.isArray(raw)) return; // Mark any non-terminal tasks as aborted on restore — we can't resume execution. runs = (raw as RunSnapshot[]).map((run) => ({ ...run, tasks: run.tasks.map((t) => (TERMINAL_TASK.includes(t.status) ? t : { ...t, status: "aborted" as TaskStatus, error: t.error || "Interrupted by session reload" })), })); } catch { return; } let added = 0; for (const run of runs ?? []) { if (!run?.id || this.runs.has(run.id)) continue; this.runs.set(run.id, run); added += 1; } if (added > 0) { this.emit("subagent:runs-restored", { count: added }); if (ctx.hasUI) { const latest = this.listRuns()[0]; if (latest) { ctx.ui.setStatus("subagents", `subagents: restored ${added} run${added > 1 ? "s" : ""}`); ctx.ui.setWidget("subagents", renderWidgetLines(latest), { placement: "aboveEditor" }); } } } } private emit(type: string, payload: Record): void { this.pi.events.emit(type, { type, timestamp: Date.now(), ...payload }); } /** Push a run notification into the parent agent so it wakes up and acts. * Uses sendUserMessage (always enters LLM context + triggers a turn) as the * primary channel; falls back to event-only if the parent is mid-stream. */ private notifyParent(run: RunSnapshot, kind: "completed" | "failed" | "aborted" | "asked", extra?: { taskId?: string; question?: string }): void { const taskHint = extra?.taskId ? ` (task ${extra.taskId})` : ""; const body = kind === "asked" ? `A background subagent is asking you a question${taskHint}: ${extra?.question ?? ""}\nReply with the reply_subagent tool (runId: ${run.id}${extra?.taskId ? `, taskId: ${extra.taskId}` : ""}).` : `Background subagent run ${run.id} ${kind}.\n${makeSummary(run)}\nUse subagent_result to read full output if needed.`; try { // sendUserMessage always triggers a turn and enters LLM context. this.pi.sendUserMessage(body); } catch { // Parent likely mid-stream without a delivery mode; emit event so // web/TUI consumers still see it. Parent can poll subagent_status. this.emit("subagent:notification", { runId: run.id, kind, body }); } this.emit("subagent:notification", { runId: run.id, kind, body }); } private updateRun(run: RunSnapshot, ctx?: ExtensionContext, onUpdate?: (partial: any) => void): void { run.aggregateUsage = aggregateUsage(run.tasks); this.runs.set(run.id, run); this.emit("subagent:run-updated", { run: cloneRun(run) }); const liveCount = run.tasks.filter((t) => !TERMINAL_TASK.includes(t.status)).length; if (ctx?.hasUI) { ctx.ui.setStatus("subagents", `subagents: ${liveCount} running`); ctx.ui.setWidget("subagents", renderWidgetLines(run), { placement: "aboveEditor" }); } onUpdate?.({ content: [{ type: "text", text: renderWidgetLines(run).join("\n") }], details: { run: cloneRun(run) } }); } private updateTask(run: RunSnapshot, task: TaskSnapshot, patch: Partial, ctx: ExtensionContext, onUpdate?: (partial: any) => void): void { Object.assign(task, patch); task.lastEventAt = Date.now(); this.emit("subagent:task-updated", { runId: run.id, taskId: task.id, patch, task: { ...task } }); this.updateRun(run, ctx, onUpdate); } // ── intercom plumbing ─────────────────────────────────────────────── private makeIntercomHandlers(run: RunSnapshot, task: TaskSnapshot, ctx: ExtensionContext): IntercomHandlers { return { onAskParent: async (_taskId, question) => { this.updateTask(run, task, { status: "awaiting_parent", intercomQuestion: question }, ctx); this.liveChildren.get(`${run.id}:${task.id}`)?.touchWatchdog?.(); // reset stall while waiting this.notifyParent(run, "asked", { taskId: task.id, question }); const reply = await this.awaitParentReply(run.id, task.id); this.updateTask(run, task, { status: "running", intercomQuestion: undefined }, ctx); this.liveChildren.get(`${run.id}:${task.id}`)?.touchWatchdog?.(); return reply; }, onNotifyParent: (_taskId, message, level) => { this.emit("subagent:intercom", { runId: run.id, taskId: task.id, kind: "notify", level, message }); }, onUpdateProgress: (_taskId, phase, note) => { this.updateTask(run, task, { progressPhase: phase + (note ? ` — ${note}` : "") }, ctx); }, }; } private awaitParentReply(runId: string, taskId: string): Promise { return new Promise((resolve) => { this.pendingReplies.set(`${runId}:${taskId}`, { resolve, question: "", askedAt: Date.now() }); }); } deliverReply(runId: string, taskId: string, message: string): boolean { const pending = this.pendingReplies.get(`${runId}:${taskId}`); if (!pending) return false; this.pendingReplies.delete(`${runId}:${taskId}`); pending.resolve(message); return true; } private async runChild( run: RunSnapshot, task: TaskSnapshot, input: TaskInput, agents: AgentConfig[], ctx: ExtensionContext, signal: AbortSignal | undefined, onUpdate?: (partial: any) => void, ): Promise { const requestedAgent = task.agent; const agent = resolveAgent(agents, requestedAgent); if (!agent) { this.updateTask(run, task, { status: "failed", error: `Unknown agent: ${requestedAgent}. Available agents: ${formatAvailableAgents(agents)}`, endedAt: Date.now(), agentSource: "unknown", }, ctx, onUpdate); return; } this.updateTask(run, task, { status: "starting", agent: agent.name, startedAt: Date.now(), agentSource: agent.source, model: input.model ?? agent.model, thinking: input.thinking ?? agent.thinking, tools: input.tools ?? agent.tools ?? DEFAULT_READONLY_TOOLS, }, ctx, onUpdate); let child: Awaited>["session"] | undefined; let unsubscribe: (() => void) | undefined; let timeout: ReturnType | undefined; let abortListener: (() => void) | undefined; let watchdog = createWatchdog(run.stallMs, `Subagent ${task.agent}`); let pendingFailure: ChildFailure | undefined; let failChildEnd: ((error: Error) => void) | undefined; let childEndResolve: (() => void) | undefined; const key = `${run.id}:${task.id}`; try { const modelRef = parseModelRef(input.model ?? agent.model); const model = modelRef ? ctx.modelRegistry.find(modelRef.provider, modelRef.modelId) : undefined; if (modelRef && !model) throw new Error(`Model not found: ${modelRef.provider}/${modelRef.modelId}`); const isPiWebAgent = agent.source === "pi-web"; const subagentInstruction = run.allowIntercom ? "You are running as a subagent. Do not call subagent/delegation tools unless the parent explicitly asks. Return a concise final answer. You MAY use ask_parent only when truly blocked on information only the parent has; otherwise resolve things yourself." : "You are running as a subagent. Do not call subagent/delegation tools unless the parent explicitly asks you to. Return a concise final answer for the parent agent."; const loaderOptions: ConstructorParameters[0] = { cwd: task.cwd, agentDir: getAgentDir(), noExtensions: !isPiWebAgent, additionalExtensionPaths: isPiWebAgent ? agent.resources?.extensions : undefined, additionalSkillPaths: isPiWebAgent ? agent.resources?.skills : undefined, additionalPromptTemplatePaths: isPiWebAgent ? agent.resources?.prompts : undefined, }; if (isPiWebAgent && agent.promptMode === "replace") { loaderOptions.systemPrompt = agent.systemPrompt.trim(); loaderOptions.appendSystemPrompt = [subagentInstruction]; } else { const appendPrompt = [agent.systemPrompt.trim(), subagentInstruction].filter(Boolean).join("\n\n"); loaderOptions.appendSystemPromptOverride = (base) => [...base, appendPrompt]; } const loader = new DefaultResourceLoader(loaderOptions); await loader.reload(); // Inject intercom tools when enabled. They close over run/task/ctx. const customTools: ToolDefinition[] = run.allowIntercom ? createIntercomTools(task.id, this.makeIntercomHandlers(run, task, ctx)) : []; const created = await createAgentSession({ cwd: task.cwd, resourceLoader: loader, sessionManager: SessionManager.create(task.cwd, undefined, { parentSession: getParentSessionFile(ctx) }), model, thinkingLevel: (input.thinking ?? agent.thinking) as any, tools: input.tools ?? agent.tools ?? DEFAULT_READONLY_TOOLS, customTools, modelRegistry: ctx.modelRegistry, }); child = created.session; child.setSessionName?.(`subagent: ${agent.name}`); this.updateTask(run, task, { status: "running", sessionId: child.sessionId, sessionFile: child.sessionFile }, ctx, onUpdate); const childFailurePromise = new Promise((_, reject) => { failChildEnd = reject; }); const childEndPromise = new Promise((resolve) => { childEndResolve = resolve; }); unsubscribe = child.subscribe((event: AgentSessionEvent) => { // Every meaningful event feeds the watchdog. if (event.type === "message_end" || event.type === "tool_execution_start" || event.type === "tool_execution_end") { watchdog.touch(); } if (event.type === "message_end" || event.type === "tool_execution_start" || event.type === "tool_execution_end") { this.emit("subagent:session-event", { runId: run.id, taskId: task.id, sessionId: child?.sessionId, sessionFile: child?.sessionFile, seq: ++this.eventSeq, event: { type: event.type }, }); } if (event.type === "tool_execution_start") { this.updateTask(run, task, { currentTool: { toolCallId: (event as any).toolCallId, toolName: (event as any).toolName, args: previewValue((event as any).args), startedAt: Date.now() }, }, ctx, onUpdate); } if (event.type === "tool_execution_end") { this.updateTask(run, task, { currentTool: undefined }, ctx, onUpdate); } if (event.type === "message_end") { const message = (event as any).message; updateUsageFromMessage(task, message); const text = getFirstText(message); if (message?.role === "assistant" && text) task.finalText = truncateText(text); pendingFailure = getAssistantFailure(message); this.updateRun(run, ctx, onUpdate); } if (event.type === "agent_end") { const willRetry = Boolean((event as any).willRetry); const failure = getLastAssistantFailure((event as any).messages); if (failure && !willRetry) { pendingFailure = failure; failChildEnd?.(makeChildFailureError(failure)); } else if (!willRetry) { childEndResolve?.(); } } }); if (signal) { const listener = () => void child?.abort(); signal.addEventListener("abort", listener, { once: true }); abortListener = () => signal.removeEventListener("abort", listener); } this.liveChildren.set(key, { abort: () => void child?.abort(), dispose: () => watchdog.dispose(), touchWatchdog: () => watchdog.touch() }); const maxRuntimeMs = input.maxRuntimeMs ?? DEFAULT_RUNTIME_MS; const promptPromise = child.prompt(task.task, { source: "extension" as any }); const timeoutPromise = new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error(`Subagent timed out after ${maxRuntimeMs}ms`)), maxRuntimeMs); }); // Race: normal completion | explicit failure | agent_end | watchdog(stall) | hard timeout await Promise.race([promptPromise, childFailurePromise, childEndPromise, watchdog.promise, timeoutPromise]); if (timeout) clearTimeout(timeout); // Prompt-settle safety net: re-verify final state even if agent_end // was somehow missed. pendingFailure ??= getLastAssistantFailure(child.messages as any[]); if (pendingFailure) throw makeChildFailureError(pendingFailure); const finalText = task.finalText || truncateText(child.messages.map(getFirstText).filter(Boolean).at(-1) || ""); this.updateTask(run, task, { status: "completed", finalText, currentTool: undefined, endedAt: Date.now() }, ctx, onUpdate); } catch (err) { if (timeout) clearTimeout(timeout); const aborted = signal?.aborted; const subagentStatus = (err as Error & { subagentStatus?: ChildFailure["status"] })?.subagentStatus; const stalled = err instanceof Error && /stalled/i.test(err.message); try { await child?.abort(); } catch { /* ignore */ } this.updateTask(run, task, { status: aborted ? "aborted" : subagentStatus ?? "failed", error: err instanceof Error ? err.message : String(err), currentTool: undefined, endedAt: Date.now(), ...(stalled ? { error: `${err instanceof Error ? err.message : "stalled"} (watchdog)` } : {}), }, ctx, onUpdate); } finally { this.liveChildren.delete(key); this.pendingReplies.delete(key); abortListener?.(); unsubscribe?.(); watchdog.dispose(); if (timeout) clearTimeout(timeout); child?.dispose(); } } /** Build a run and register it (no execution yet). */ createRun(params: any, toolCallId: string, ctx: ExtensionContext): { run: RunSnapshot; inputs: TaskInput[]; agents: AgentConfig[] } { const agentScope: AgentScope = params.agentScope ?? "user"; const discovery = discoverAgents(ctx.cwd, agentScope); const agents = discovery.agents; const hasChain = (params.chain?.length ?? 0) > 0; const hasTasks = (params.tasks?.length ?? 0) > 0; const hasSingle = Boolean(params.agent && params.task); if (Number(hasChain) + Number(hasTasks) + Number(hasSingle) !== 1) { throw new Error(`Provide exactly one subagent mode. Available agents: ${agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none"}`); } const requested = new Set(); if (hasSingle) requested.add(params.agent); for (const t of params.tasks ?? []) requested.add(t.agent); for (const t of params.chain ?? []) requested.add(t.agent); const mode: RunMode = hasChain ? "chain" : hasTasks ? "parallel" : "single"; const runId = newId("run"); const inputs: TaskInput[] = hasSingle ? [{ agent: params.agent, task: params.task, cwd: params.cwd, model: params.model, thinking: params.thinking, tools: params.tools, maxRuntimeMs: params.maxRuntimeMs }] : hasTasks ? params.tasks : params.chain; if (inputs.length > MAX_TASKS) throw new Error(`Too many subagent tasks (${inputs.length}). Max is ${MAX_TASKS}.`); const run: RunSnapshot = { id: runId, parentSessionId: ctx.sessionManager.getSessionId?.(), parentToolCallId: toolCallId, mode, status: "queued", background: Boolean(params.background), allowIntercom: Boolean(params.allowIntercom), createdAt: Date.now(), concurrency: Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, MAX_CONCURRENCY)), stallMs: Math.max(10_000, params.stallMs ?? DEFAULT_STALL_MS), tasks: inputs.map((input, index) => normalizeTask(input, runId, index, input.cwd ?? params.cwd ?? ctx.cwd)), aggregateUsage: emptyUsage(), }; this.runs.set(run.id, run); // settled promise for await_subagent let resolveSettled!: (r: RunSnapshot) => void; const promise = new Promise((res) => (resolveSettled = res)); this.settlers.set(run.id, { promise, resolve: resolveSettled }); this.emit("subagent:run-created", { run: cloneRun(run) }); return { run, inputs, agents }; } private async executeTasks(run: RunSnapshot, inputs: TaskInput[], agents: AgentConfig[], ctx: ExtensionContext, signal: AbortSignal | undefined, onUpdate?: (partial: any) => void): Promise { run.status = "running"; run.startedAt = Date.now(); this.updateRun(run, ctx, onUpdate); if (run.mode === "chain") { let previous = ""; for (let i = 0; i < inputs.length; i++) { if (signal?.aborted) { this.updateTask(run, run.tasks[i], { status: "aborted", error: "Aborted before start", endedAt: Date.now() }, ctx, onUpdate); continue; } const input = { ...inputs[i], task: inputs[i].task.replace(/\{previous\}/g, previous) }; run.tasks[i].task = input.task; await this.runChild(run, run.tasks[i], input, agents, ctx, signal, onUpdate); if (run.tasks[i].status !== "completed") break; previous = run.tasks[i].finalText ?? ""; } } else { await mapWithConcurrency(run.tasks, run.mode === "single" ? 1 : run.concurrency, async (task, index) => { await this.runChild(run, task, inputs[index], agents, ctx, signal, onUpdate); }); } const failed = run.tasks.some((t) => t.status === "failed"); const aborted = run.tasks.some((t) => t.status === "aborted") || Boolean(signal?.aborted); run.status = aborted ? "aborted" : failed ? "failed" : "completed"; run.endedAt = Date.now(); this.updateRun(run, ctx, onUpdate); this.emit("subagent:run-completed", { runId: run.id, status: run.status, run: cloneRun(run), aggregateUsage: run.aggregateUsage }); this.settlers.get(run.id)?.resolve(cloneRun(run)); this.persist(ctx); if (ctx.hasUI) { ctx.ui.setStatus("subagents", `subagents: ${run.status}`); ctx.ui.setWidget("subagents", renderWidgetLines(run), { placement: "aboveEditor" }); } } /** Blocking run (legacy/default path). */ async runBlocking(params: any, toolCallId: string, signal: AbortSignal | undefined, onUpdate: ((partial: any) => void) | undefined, ctx: ExtensionContext): Promise { const { run, inputs, agents } = this.prepareRun(params, toolCallId, ctx); await this.executeTasks(run, inputs, agents, ctx, signal, onUpdate); return { run: cloneRun(run), agents: catalog(agents) }; } /** Background run: returns immediately, notifies parent on completion. */ startInBackground(params: any, toolCallId: string, ctx: ExtensionContext): RunDetails { const { run, inputs, agents } = this.prepareRun(params, toolCallId, ctx); // Fire and forget. Use a fresh AbortController (no parent tool signal). void this.executeTasks(run, inputs, agents, ctx, undefined, undefined).then(() => { this.notifyParent(run, run.status === "completed" ? "completed" : run.status === "aborted" ? "aborted" : "failed"); }); return { run: cloneRun(run), agents: catalog(agents), background: true }; } private prepareRun(params: any, toolCallId: string, ctx: ExtensionContext) { const { run, inputs, agents } = this.createRun(params, toolCallId, ctx); const agentScope: AgentScope = params.agentScope ?? "user"; if ((agentScope === "project" || agentScope === "both") && (params.confirmProjectAgents ?? true) && ctx.hasUI) { const requested = new Set(); if (params.agent) requested.add(params.agent); for (const t of params.tasks ?? []) requested.add(t.agent); for (const t of params.chain ?? []) requested.add(t.agent); const projectAgents = [...requested].map((name) => resolveAgent(agents, name)).filter((a): a is AgentConfig => a?.source === "project"); if (projectAgents.length > 0) { // Note: confirm is async; for background we skip blocking confirm // here and rely on the execute() path having checked. (See tool.) } } return { run, inputs, agents }; } awaitRun(runId: string, timeoutMs?: number): Promise { const settler = this.settlers.get(runId); const run = this.runs.get(runId); if (!settler || !run) return Promise.resolve(undefined); if (["completed", "failed", "aborted"].includes(run.status)) return Promise.resolve(cloneRun(run)); if (!timeoutMs) return settler.promise; return Promise.race([ settler.promise, new Promise((resolve) => setTimeout(() => { const r = this.runs.get(runId); resolve(r ? cloneRun(r) : undefined); }, timeoutMs), ), ]); } private persist(ctx: ExtensionContext): void { try { const parentFile = getParentSessionFile(ctx); if (!parentFile) return; // sidecar is authoritative for restore; parent .jsonl is left clean const sidecar = parentFile.replace(/\.jsonl$/, ".subagents.json"); import("fs").then(({ writeFileSync }) => writeFileSync(sidecar, JSON.stringify(this.listRuns().map(cloneRun), null, 2))); } catch { /* ignore */ } } } function catalog(agents: AgentConfig[]) { return agents.map((agent) => ({ name: agent.name, description: agent.description, source: agent.source, filePath: agent.filePath, id: agent.id })); } const TaskItem = Type.Object({ id: Type.Optional(Type.String({ description: "Optional stable task id" })), agent: Type.String({ description: "Exact agent name or id from the injected available subagents list" }), task: Type.String({ description: "Task to delegate to the agent" }), cwd: Type.Optional(Type.String({ description: "Working directory for this task" })), model: Type.Optional(Type.String({ description: "Model override as provider/model-id" })), thinking: Type.Optional(Type.String({ description: "Thinking level override" })), tools: Type.Optional(Type.Array(Type.String(), { description: "Tool allowlist for this task" })), maxRuntimeMs: Type.Optional(Type.Number({ description: "Per-task timeout in milliseconds" })), }); const SubagentParams = Type.Object({ agent: Type.Optional(Type.String({ description: "Agent name/id for single mode" })), task: Type.Optional(Type.String({ description: "Task for single mode" })), tasks: Type.Optional(Type.Array(TaskItem, { description: "Parallel tasks" })), chain: Type.Optional(Type.Array(TaskItem, { description: "Sequential tasks. Each task may use {previous}." })), agentScope: Type.Optional(StringEnum(["user", "project", "both"] as const, { default: "user" })), confirmProjectAgents: Type.Optional(Type.Boolean({ default: true })), cwd: Type.Optional(Type.String({ description: "Default working directory" })), model: Type.Optional(Type.String({ description: "Model override for single mode as provider/model-id" })), thinking: Type.Optional(Type.String({ description: "Thinking override for single mode" })), tools: Type.Optional(Type.Array(Type.String(), { description: "Tool allowlist override for single mode" })), concurrency: Type.Optional(Type.Number({ description: `Parallel concurrency. Default ${DEFAULT_CONCURRENCY}, max ${MAX_CONCURRENCY}.` })), maxRuntimeMs: Type.Optional(Type.Number({ description: "Per-task timeout for single mode" })), background: Type.Optional(Type.Boolean({ description: "If true, return immediately with a runId and run in the background. You will be notified on completion. Default false." })), stallMs: Type.Optional(Type.Number({ description: `Watchdog: abort a child if it produces no events for this many ms. Default ${DEFAULT_STALL_MS}.` })), allowIntercom: Type.Optional(Type.Boolean({ description: "If true, inject ask_parent/notify_parent/update_progress tools into children so they can talk back. Default false." })), }); export default function (pi: ExtensionAPI) { const manager = new SubagentManager(pi); pi.registerCommand("subagents", { description: "Show recent subagent runs", handler: async (_args, ctx) => { const runs = manager.listRuns().slice(0, 10); if (runs.length === 0) { ctx.ui.notify("No subagent runs in this session.", "info"); return; } ctx.ui.setWidget("subagents", runs.flatMap((run) => renderWidgetLines(run).concat("")), { placement: "aboveEditor" }); ctx.ui.notify(`Showing ${runs.length} subagent run(s).`, "info"); }, }); pi.on("session_start", async (_event, ctx) => { await manager.restoreFromSidecar(ctx); }); pi.on("session_shutdown", async (_event, ctx) => { if (ctx?.hasUI) { try { ctx.ui.setStatus("subagents", ""); ctx.ui.setWidget("subagents", [], { placement: "aboveEditor" }); } catch { /* ignore */ } } manager.clearRuns(); }); pi.on("context", async (event, ctx) => { return { messages: appendContextMessage(event.messages, makeAgentCatalogContext(ctx.cwd)) }; }); // ── Main tool ────────────────────────────────────────────────────── pi.registerTool({ name: "subagent", label: "Subagent", description: [ "Delegate work to specialized subagents with isolated context and persisted child sessions.", "Modes: single (agent+task), parallel (tasks), chain (chain with optional {previous}).", "Set background:true to fire-and-forget (you'll be notified on completion) and use the subagent_* control tools to interact. Set allowIntercom:true to let children ask you questions mid-run.", ].join(" "), promptSnippet: "Delegate analysis/review/test/planning work to specialized subagents.", promptGuidelines: [ "Use subagent when independent review, testing, research, or parallel analysis would improve quality.", "Use only exact configured agent names or ids from the injected available subagents list.", "Prefer read-only subagent tools unless the user explicitly asks for implementation work.", "Use background:true for long-running work so you can continue; you'll be notified on completion.", "Use allowIntercom:true only when you expect the child may need to ask you something; keep children autonomous otherwise.", ], parameters: SubagentParams, executionMode: "sequential", async execute(toolCallId, params, signal, onUpdate, ctx) { // Project-agent confirmation (must happen before background dispatch). const agentScope: AgentScope = params.agentScope ?? "user"; const discovery = discoverAgents(ctx.cwd, agentScope); if ((agentScope === "project" || agentScope === "both") && (params.confirmProjectAgents ?? true) && ctx.hasUI) { const requested = new Set(); if (params.agent) requested.add(params.agent); for (const t of params.tasks ?? []) requested.add(t.agent); for (const t of params.chain ?? []) requested.add(t.agent); const projectAgents = [...requested].map((name) => resolveAgent(discovery.agents, name)).filter((a): a is AgentConfig => a?.source === "project"); if (projectAgents.length > 0) { const ok = await ctx.ui.confirm( "Run project-local subagents?", `Agents: ${projectAgents.map((a) => a.name).join(", ")}\nSource: ${discovery.projectAgentsDir}\n\nProject agents are repo-controlled. Continue only for trusted repositories.`, ); if (!ok) throw new Error("Canceled: project-local subagents not approved."); } } if (params.background) { const details = manager.startInBackground(params, toolCallId, ctx); return { content: [ { type: "text", text: `Background run started.\nrunId: ${details.run.id}\nMode: ${details.run.mode}\nTasks: ${details.run.tasks.map((t) => `${t.agent}(${t.id})`).join(", ")}\n\nYou can keep working. You will be notified when it completes. Use subagent_status / subagent_result / await_subagent / reply_subagent to interact.`, }, ], details, }; } const details = await manager.runBlocking(params, toolCallId, signal, onUpdate, ctx); return { content: [{ type: "text", text: makeSummary(details.run) }], details }; }, renderCall(args, theme) { const mode = args.chain?.length ? `chain ${args.chain.length}` : args.tasks?.length ? `parallel ${args.tasks.length}` : `single ${args.agent ?? "?"}`; const flags = [args.background ? "bg" : "", args.allowIntercom ? "intercom" : ""].filter(Boolean).join(" "); return new Text(`${theme.fg("toolTitle", theme.bold("subagent"))} ${theme.fg("accent", mode)}${flags ? ` ${theme.fg("muted", `[${flags}]`)}` : ""}`, 0, 0); }, renderResult(result, { expanded, isPartial }, theme) { const run = result.details?.run; if (!run) return new Text(result.content[0]?.type === "text" ? result.content[0].text : "", 0, 0); const header = `${isPartial ? "⏳" : statusIcon(run.status)} ${theme.fg("toolTitle", theme.bold(`subagents ${run.mode}${run.background ? " (bg)" : ""}`))} ${theme.fg("accent", `${run.tasks.filter((t) => t.status === "completed").length}/${run.tasks.length}`)} ${theme.fg("muted", run.status)}`; if (!expanded) { const lines = [header, ...run.tasks.map((task) => ` ${statusIcon(task.status)} ${task.agent}: ${task.status}${task.currentTool ? ` · ${task.currentTool.toolName}` : task.progressPhase ? ` · ${task.progressPhase}` : ""}`)]; const usage = formatUsage(run.aggregateUsage); if (usage) lines.push(theme.fg("dim", usage)); return new Text(lines.join("\n"), 0, 0); } const container = new Container(); container.addChild(new Text(header, 0, 0)); const mdTheme = getMarkdownTheme(); for (const task of run.tasks) { container.addChild(new Spacer(1)); container.addChild(new Text(`${statusIcon(task.status)} ${theme.fg("accent", task.agent)} ${theme.fg("muted", task.sessionId ?? "")}`, 0, 0)); if (task.error) container.addChild(new Text(theme.fg("error", task.error), 0, 0)); else if (task.finalText) container.addChild(new Markdown(task.finalText.trim(), 0, 0, mdTheme)); const usage = formatUsage(task.usage); if (usage) container.addChild(new Text(theme.fg("dim", usage), 0, 0)); } return container; }, }); // ── Control tools (background interaction) ──────────────────────── const RunIdParam = Type.Object({ runId: Type.String({ description: "The background run id returned by subagent({background:true})" }), }); const ResultParam = Type.Object({ runId: Type.String(), taskId: Type.Optional(Type.String({ description: "Optional specific task id; defaults to all tasks" })), }); const AwaitParam = Type.Object({ runId: Type.String(), timeoutMs: Type.Optional(Type.Number({ description: "Max wait. Default: until the run finishes." })), }); const ReplyParam = Type.Object({ runId: Type.String(), taskId: Type.String(), message: Type.String({ description: "Your answer/instruction for the child" }), }); pi.registerTool({ name: "subagent_status", label: "Subagent Status", description: "Check the live status of a background subagent run (non-blocking). Returns each task's state.", promptSnippet: "Check progress of a background subagent run.", parameters: RunIdParam, async execute(_id, params) { const { runId } = params as { runId: string }; const run = manager.getRun(runId); if (!run) return { content: [{ type: "text", text: `Unknown runId: ${runId}` }], isError: true, details: {} }; return { content: [{ type: "text", text: renderWidgetLines(run).join("\n") }], details: { run: cloneRun(run) } }; }, }); pi.registerTool({ name: "subagent_result", label: "Subagent Result", description: "Fetch the full result (finalText + usage) of a background subagent run, or a specific task. Non-blocking; returns current state if still running.", parameters: ResultParam, async execute(_id, params) { const { runId, taskId } = params as { runId: string; taskId?: string }; const run = manager.getRun(runId); if (!run) return { content: [{ type: "text", text: `Unknown runId: ${runId}` }], isError: true, details: {} }; const tasks = taskId ? run.tasks.filter((t) => t.id === taskId) : run.tasks; const text = [`Run ${run.id} — ${run.status}`, ...tasks.map((t) => `\n## ${t.agent} ${statusIcon(t.status)}\n${t.error ? `Error: ${t.error}` : t.finalText || "(no output yet)"}\n${formatUsage(t.usage)}`)].join("\n"); return { content: [{ type: "text", text: truncateText(text) }], details: { run: cloneRun(run) } }; }, }); pi.registerTool({ name: "await_subagent", label: "Await Subagent", description: "Block until a background subagent run finishes (or timeoutMs elapses). Use when you need the result before proceeding.", parameters: AwaitParam, async execute(_id, params) { const { runId, timeoutMs } = params as { runId: string; timeoutMs?: number }; const run = await manager.awaitRun(runId, timeoutMs); if (!run) return { content: [{ type: "text", text: `Unknown runId: ${runId}` }], isError: true, details: {} }; return { content: [{ type: "text", text: makeSummary(run) }], details: { run: cloneRun(run) } }; }, }); pi.registerTool({ name: "reply_subagent", label: "Reply Subagent", description: "Reply to a background child that asked you a question via ask_parent (intercom). Resumes the child's run.", parameters: ReplyParam, async execute(_id, params) { const { runId, taskId, message } = params as { runId: string; taskId: string; message: string }; const ok = manager.deliverReply(runId, taskId, message); if (!ok) return { content: [{ type: "text", text: `No pending question for ${runId}/${taskId}. (Child may have finished or was not awaiting.)` }], isError: true, details: {} }; return { content: [{ type: "text", text: `Reply delivered to ${runId}/${taskId}. The child will resume.` }], details: {} }; }, }); }