Subagent
Shows another agent working on a sub-task, with its own steps and a report.
Installation
pnpm dlx shadcn@latest add @silkware/ai-subagentTo copy the pattern by hand, install the components it composes:
pnpm dlx shadcn@latest add @silkware/bubble @silkware/button @silkware/code-block @silkware/message @silkware/traceThen the packages:
pnpm add ai @ai-sdk/react @shadcn/helpers lucide-reactCopy the source into components/ai-elements/subagent.tsx. The file also needs @/lib/ai:
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"import type { UIDataTypes, UIMessage } from "ai"import { CircleAlertIcon, CircleCheckIcon, LoaderCircleIcon,} from "lucide-react"
import { createChat, getMessageText } from "@/lib/ai"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"import { Message, MessageContent } from "@/components/ui/message"import { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceIcon, TraceLine, TraceTitle,} from "@/components/ui/trace"
type SubagentMessage = UIMessage< unknown, UIDataTypes, { runCommand: { input: { command: string } output: { stdout: string } } }>
type SubagentPart = SubagentMessage["parts"][number]
type ChatMessage = UIMessage< unknown, UIDataTypes, { researchAgent: { input: { task: string } output: SubagentMessage } }>
type Part = ChatMessage["parts"][number]
const steps = [ { command: "grep -rn cacheKey scripts", stdout: "scripts/optimize-images.ts:14: const cacheKey = process.env.COMMIT_SHA", }, { command: "sed -n 13,15p scripts/optimize-images.ts", stdout: 'const cacheDir = ".next/cache/images"\nconst cacheKey = process.env.COMMIT_SHA\nconst cached = await restoreCache(cacheDir, cacheKey)', }, { command: "ls public/images | wc -l", stdout: "1240", },]
function getSubagentMessage(done: number, report?: string): SubagentMessage { const parts = steps.slice(0, done).map((step, index): SubagentPart => ({ type: "tool-runCommand", toolCallId: `step-${index}`, state: "output-available", input: { command: step.command }, output: { stdout: step.stdout }, }))
if (done < steps.length) { parts.push({ type: "tool-runCommand", toolCallId: `step-${done}`, state: "input-available", input: { command: steps[done].command }, }) }
if (report) { parts.push({ type: "text", text: report }) }
return { id: "research-agent", role: "assistant", parts }}
const chat = createChat<ChatMessage>() .user("Why does image optimization rerun on every deploy?") .assistant(({ writer }) => { const subagent = writer .tool("researchAgent", { input: { task: "Find out why image optimization reruns on every deploy.", }, }) .sleep(600) steps.forEach((_, index) => { subagent .output(getSubagentMessage(index), { preliminary: true }) .sleep(1000) }) subagent .output( getSubagentMessage( steps.length, "The cache is keyed on the commit SHA, so every deploy misses it and optimizes all 1,240 images again." ) ) .sleep(400) writer.text( "Image optimization reruns because its cache is keyed on the commit SHA, which changes on every deploy. Key the cache on a hash of public/images instead, and unchanged images will be skipped." ) })
const transcript = chat.get()const [question] = chat.get(1)const transport = chat.transport({ delayMs: 20 })
function StepRow({ part, running,}: { part: Extract<SubagentPart, { type: "tool-runCommand" }> running: boolean}) { const command = part.input?.command
if (part.state === "output-available") { return ( <TraceCollapsible> <TraceCollapsibleTrigger> <TraceLine> <TraceIcon> <CircleCheckIcon /> </TraceIcon> <TraceTitle>Ran {command}</TraceTitle> </TraceLine> </TraceCollapsibleTrigger> <TraceCollapsibleContent> <CodeBlock size="sm"> <CodeBlockContent wrap className="max-h-64"> {part.output.stdout} </CodeBlockContent> </CodeBlock> </TraceCollapsibleContent> </TraceCollapsible> ) }
return ( <TraceLine status={running ? "running" : "error"}> <TraceIcon> {running ? ( <LoaderCircleIcon className="animate-spin" /> ) : ( <CircleAlertIcon /> )} </TraceIcon> <TraceTitle> {running ? "Running" : "Failed to run"} {command} </TraceTitle> </TraceLine> )}
function SubagentRow({ part, streaming,}: { part: Extract<Part, { type: "tool-researchAgent" }> streaming: boolean}) { const done = part.state === "output-available" && !part.preliminary const running = !done && part.state !== "output-error" && streaming const parts = part.state === "output-available" ? part.output.parts : [] const report = parts .map((agentPart) => (agentPart.type === "text" ? agentPart.text : "")) .join("")
const line = ( <TraceLine status={done ? undefined : running ? "running" : "error"}> <TraceIcon> {done ? ( <CircleCheckIcon /> ) : running ? ( <LoaderCircleIcon className="animate-spin" /> ) : ( <CircleAlertIcon /> )} </TraceIcon> <TraceTitle> {done ? "Ran" : running ? "Running" : "Failed to run"} the research subagent </TraceTitle> </TraceLine> )
if (parts.length === 0) { return line }
return ( <TraceCollapsible defaultExpanded> <TraceCollapsibleTrigger>{line}</TraceCollapsibleTrigger> <TraceCollapsibleContent className="flex flex-col gap-3"> <Trace> {parts.map((agentPart) => agentPart.type === "tool-runCommand" ? ( <StepRow key={agentPart.toolCallId} part={agentPart} running={running} /> ) : null )} </Trace> {report && <p>{report}</p>} </TraceCollapsibleContent> </TraceCollapsible> )}
export function SubagentDemo() { const { messages, sendMessage, setMessages, status } = useChat({ messages: transcript, transport, }) const busy = status === "submitted" || status === "streaming"
return ( <div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm"> {messages.map((message) => { if (message.role === "user") { return ( <Message key={message.id} align="end"> <MessageContent> <Bubble align="end" variant="muted"> <BubbleContent>{getMessageText(message)}</BubbleContent> </Bubble> </MessageContent> </Message> ) }
const streaming = busy && message === messages.at(-1) const agents = message.parts.filter( (part) => part.type === "tool-researchAgent" ) const text = getMessageText(message)
return ( <Message key={message.id}> <MessageContent className="gap-4"> {agents.length > 0 && ( <Trace> {agents.map((part) => ( <SubagentRow key={part.toolCallId} part={part} streaming={streaming} /> ))} </Trace> )} {text && <p>{text}</p>} </MessageContent> </Message> ) })} {!busy && ( <Button variant="outline" size="sm" className="mt-auto self-start" onPress={() => { setMessages([]) sendMessage(question) }} > Replay </Button> )} </div> )}Usage
A subagent is a tool call whose output is itself a message. The line names the agent and its state, and the content shows the steps it took and the report it wrote.
import { CircleAlertIcon, CircleCheckIcon, LoaderCircleIcon } from "lucide-react"
import { Trace, TraceCollapsible, TraceCollapsibleContent, TraceCollapsibleTrigger, TraceIcon, TraceLine, TraceTitle,} from "@/components/ui/trace"<TraceCollapsible defaultExpanded> <TraceCollapsibleTrigger> <TraceLine status={done ? undefined : running ? "running" : "error"}> <TraceIcon>{icon}</TraceIcon> <TraceTitle>Running the research subagent</TraceTitle> </TraceLine> </TraceCollapsibleTrigger> <TraceCollapsibleContent className="flex flex-col gap-3"> <Trace>{steps}</Trace> {report && <p>{report}</p>} </TraceCollapsibleContent></TraceCollapsible>The steps are the subagent's own tool calls, drawn as lines like the ones in Tool. Show the report as text under the steps, so the person reads the result without opening each step.
Examples
Running
While the subagent works, its line shimmers and each step shows as it starts. The last step is still running.
With details
A finished subagent can show how long it took, which model it used and which tools it had, as badges and a description next to the title. Show these when the person audits agents; leave them out otherwise.
Find out why image optimization reruns on every deploy.
The cache is keyed on the commit SHA.
Failed
When a step fails, the subagent stops and its line says so. The steps that finished stay, and the message says that nothing was changed.
The agent stopped before it compared prices. No supplier data was changed.
AI SDK
A subagent is a tool whose output is a UIMessage. The output can be streamed in pieces: each call to output with { preliminary: true } replaces the last one, and the final call, without it, ends the tool. On the client, the part is in output-available for both, so check part.preliminary to tell a running subagent from a finished one.
import type { UIDataTypes, UIMessage } from "ai"
type SubagentMessage = UIMessage< unknown, UIDataTypes, { runCommand: { input: { command: string }; output: { stdout: string } } }>
type ChatMessage = UIMessage< unknown, UIDataTypes, { researchAgent: { input: { task: string }; output: SubagentMessage } }>const done = part.state === "output-available" && !part.preliminaryconst parts = part.state === "output-available" ? part.output.parts : []const report = parts.map((agentPart) => (agentPart.type === "text" ? agentPart.text : "")).join("")On the server, run the subagent from the tool's execute. It is an async generator: each yield replaces the previous output, so yield the whole message each time. readUIMessageStream builds that growing message from the subagent's stream:
import { readUIMessageStream, toUIMessageStream, tool } from "ai"import { z } from "zod"
const researchAgent = tool({ description: "Research a question in the codebase.", inputSchema: z.object({ task: z.string() }), execute: async function* ({ task }, { abortSignal }) { const result = await researchSubagent.stream({ prompt: task, abortSignal })
for await (const message of readUIMessageStream({ stream: toUIMessageStream({ stream: result.stream }), })) { yield message } },})researchSubagent is a ToolLoopAgent of your own.
Scripted streams in development
output(message, { preliminary: true }) in createChat streams each state of the subagent, and a final output without the flag finishes it:
const subagent = writer.tool("researchAgent", { input: { task } }).sleep(600)
steps.forEach((_, index) => { subagent.output(getSubagentMessage(index), { preliminary: true }).sleep(1000)})
subagent.output(getSubagentMessage(steps.length, report))Accessibility
| Key | Action |
|---|---|
| Enter | Opens or closes the subagent's steps, or a step's output. |
| Space | Opens or closes the subagent's steps, or a step's output. |
| Tab | Moves focus to the next line that can open, or into the output block of an open step: the block is focusable so it can be scrolled. |
The composed components provide:
- Real buttons with
aria-expandedfor the subagent and for each step with output. - A visible focus ring on every trigger.
- A code block for command output.
You provide:
- The state in the title: "Running the research subagent", "Ran the research subagent", "Failed to run the research subagent". The spinner and the crimson are not the only signal.
- Text for the badges. A badge that holds a model name is read as it is written; do not use a badge as the only place the state appears.
- A way to learn that the subagent finished or failed. The line updates in place and is not announced. Say it in the answer text.
Guidelines
When to use
- When the agent hands a sub-task to another agent and the person should see that it did.
- For research or checks that take several steps and end in a report.
When not to use
- For a single call. Use a Tool line.
- For steps the agent takes itself. Use Task.
- For a plan the agent will follow. Use Plan.
Content
- Name the subagent by its job: "the research agent", "the supplier agent".
- State the brief it was given, in one sentence, so the person can compare it with the report.
- Show the subagent's report as text. A subagent that ran and shows only its steps leaves the person to guess the result.
- Report what it could not do. A failure line should say which step failed and what was left untouched.
Name the subagent by its job, show its brief and put its report under the steps.
Don’t show only "Agent finished". The person cannot check what it was asked or what it found.
Human in the loop
A subagent acts for the agent, and so for the person. The person's control must reach it.
- Give the subagent the same limits as its parent: the same tools, the same approvals. A subagent that can send an order must ask before it sends one, the same as the main agent. Show that prompt in the subagent's steps, or lift it into the conversation.
- Show what the subagent changed, not only what it found. If it edited anything, list the edits in its report.
- Let the person stop it. Stopping the turn stops the subagent too; say so in the interface.
- Keep the steps in the transcript after it finishes, so a person can audit what it did.
Composition
| Component | What it does here |
|---|---|
| Trace | Lays out the subagent line, its steps and the collapsibles, and carries the running and error status. |
| Code Block | Shows the output of each step. |
| Badge | Shows the model and tools in the details example. |
| Message | Places the conversation in turns. |
| Bubble | Wraps the person's own message. |
| Button | The replay control of the demo. |
components/ai-elements/subagent.tsx exports SubagentDemo, a scripted chat that streams a researchAgent call with three preliminary outputs and a final one. Copy SubagentRow and StepRow into your app and replace the scripted chat with useChat against your route.