Open History to see the last commit
1---
2title: Subagents
3id: subagents
4order: 4
5description: "Delegate a turn to a named child agent. The stream tags that work with AG-UI subagent events, and the UI shows a nested part."
6keywords:
7 - tanstack ai
8 - subagents
9 - defineAgent
10 - router
11 - sandbox
12 - AG-UI
13---
14
15You want a specialist to handle some turns (research, writing, a sandbox harness) while the parent chat stays one conversation. `chat({ subagents })` lets the parent start a child. A router can still keep the turn on the parent, and without a router the model can skip the child tool. When a child starts, the stream tags its events with `subagentRunId`, and the client stores the work in a `type: 'subagent'` part.
16
17Want a Start app with a researcher, an SEO agent, and a writer, routed by Jev? Open the [Subagents tutorial](../tutorials/subagents).
18
19## Define a child
20
21`run` is a `chat()` call. The child can use tools, MCP, interrupts, and its own nested `subagents`.
22
23```ts group=subagents
24import { chat, choice, decide, defineAgent } from '@tanstack/ai'
25import { openaiText } from '@tanstack/ai-openai'
26import { typesafeDecider } from '@tanstack/ai-typesafe'
27
28const messages = [{ role: 'user' as const, content: 'Capital of France?' }]
29
30const researcher = defineAgent({
31 name: 'researcher',
32 description: 'Looks up facts and sources',
33 run: (ctx) =>
34 chat({
35 adapter: openaiText('gpt-5.6'),
36 messages: ctx.messages,
37 threadId: ctx.threadId,
38 runId: ctx.runId,
39 parentRunId: ctx.parentRunId,
40 subagentRunId: ctx.subagentRunId,
41 resume: ctx.resume,
42 }),
43})
44```
45
46Pass every `ctx` field to the child `chat()`. A child that stops for an approval needs `parentRunId` and `resume` to continue. See [Interrupts in a child](#interrupts-in-a-child).
47
48## Route, or let the model pick
49
50All spawn options live on `subagents`. Do not put `agents` or `router` on the root of `chat()`.
51
52**With a router.** The library calls your function, then starts that agent. It does not send subagent tools to the model.
53
54```ts group=subagents
55const stream = chat({
56 adapter: openaiText('gpt-5.6'),
57 messages,
58 subagents: {
59 agents: [researcher],
60 strategy: 'exclusive',
61 router: async ({ agents }) => {
62 const result = await decide({
63 adapter: typesafeDecider('jev-latest'),
64 state: messages,
65 questions: {
66 target: choice({
67 instructions: 'Who must handle this turn?',
68 options: {
69 main: 'General chat',
70 ...Object.fromEntries(
71 agents.map((agent) => [agent.name, agent.description]),
72 ),
73 },
74 }),
75 },
76 })
77 return result.target.value
78 },
79 },
80})
81```
82
83`choice` options must include `main` plus every agent name.
84
85The router can return:
86
87- `'main'`
88- one agent name
89- an array of names
90- `{ names, order }`
91- `{ steps }`
92
93`subagents.order` is the default for an array. `parallel` starts the names together. `sequence` runs them one after another, and each later child reads the earlier child text. Omit `order` to get `parallel`.
94
95`subagentRoute` asks Jev for the order. Jev picks `parallel` when no agent must read text from another agent. The same topic is not a reason to wait. Jev picks `sequence` only when a later agent must read the earlier text, such as research notes and then a draft.
96
97`{ names, order }` overrides that default for one turn. Use it when some turns are parallel and some are serial.
98
99`{ steps }` runs one group, then the next group. Each group has `names` and an optional `order`. The next group reads the text from the earlier group. Use this when two agents start together and a later agent must read both.
100
101A later user message can also read that child text. The assistant message keeps each child's name and text, so the next turn still has the notes.
102
103```ts
104const plan = {
105 steps: [
106 { names: ['researcher', 'seo'], order: 'parallel' },
107 { names: ['writer'] },
108 ],
109}
110```
111
112`subagentRoute(agents, { then: ['writer'] })` builds that plan when the writer is selected with other agents. The other names start together. The writer runs after them and reads their text. `then` does not have to list every agent.
113
114Pass the router's `agents` argument to `subagentRoute`. Each yes/no question uses that agent's `description`. Pass `when` only when you need different question text. `when` must include every agent name. `pick` returns `main`, one name, `{ names, order }`, or `{ steps }`. Names follow that `agents` array.
115
116```ts
117import { chat, decide, defineAgent, subagentRoute } from '@tanstack/ai'
118import { openaiText } from '@tanstack/ai-openai'
119import { typesafeDecider } from '@tanstack/ai-typesafe'
120
121const researcher = defineAgent({
122 name: 'researcher',
123 description: 'Looks up facts',
124 run: async function* () {},
125})
126const writer = defineAgent({
127 name: 'writer',
128 description: 'Writes the post',
129 run: async function* () {},
130})
131const messages = [
132 { role: 'user' as const, content: 'Research squids and write an article' },
133]
134
135const stream = chat({
136 adapter: openaiText('gpt-5.6'),
137 messages,
138 subagents: {
139 agents: [researcher, writer],
140 router: async ({ messages: turnMessages, agents }) => {
141 const state = turnMessages.at(-1)
142 if (state === undefined) {
143 throw new Error('No message')
144 }
145 const route = subagentRoute(agents)
146 const result = await decide({
147 adapter: typesafeDecider('jev-latest'),
148 state,
149 questions: route.questions,
150 })
151 return route.pick(result)
152 },
153 },
154})
155```
156
157**Without a router.** The library adds one synthetic server tool per agent. The main model calls that tool. The public stream still emits `SUBAGENT_STARTED` / `SUBAGENT_FINISHED` (or `SUBAGENT_ERROR`) and nested parts. The UI does not treat spawn as a normal tool card. The child's events stream while the tool runs, and the child's text becomes the tool result. The child reads the conversation as it is at that tool call.
158
159## Let the model write the brief
160
161In a long thread, the child gets the full conversation at the tool call, with every earlier tool result. Each parallel child gets its own copy. The child must also find its task in that conversation.
162
163Add `inputSchema` to the agent. The main model then writes the child's input when it calls the tool. `run` reads that input as `ctx.input`:
164
165```ts
166import { chat, defineAgent } from '@tanstack/ai'
167import { openaiText } from '@tanstack/ai-openai'
168import { z } from 'zod'
169
170const messages = [
171 { role: 'user' as const, content: 'Compare pricing for the vendors we picked' },
172]
173
174const researcher = defineAgent({
175 name: 'researcher',
176 description: 'Researches one focused question and returns sourced findings',
177 inputSchema: z.object({
178 task: z
179 .string()
180 .describe('What to find and what to return. The researcher sees only this text.'),
181 }),
182 run: (ctx) =>
183 chat({
184 adapter: openaiText('gpt-5.6'),
185 messages: [{ role: 'user', content: ctx.input.task }],
186 threadId: ctx.threadId,
187 runId: ctx.runId,
188 parentRunId: ctx.parentRunId,
189 subagentRunId: ctx.subagentRunId,
190 resume: ctx.resume,
191 }),
192})
193
194const stream = chat({
195 adapter: openaiText('gpt-5.6'),
196 messages,
197 subagents: { agents: [researcher] },
198})
199```
200
201- `ctx.input` has the type of the schema. Here it is `{ task: string }`.
202- If the input does not match the schema, the model gets a tool error and can call the tool again. The child does not start.
203- `ctx.messages` still holds the parent conversation. Add parts of it when the child needs more context.
204- A resumed child gets the same `ctx.input` as the first run.
205- `inputSchema` needs tool mode. If `subagents.router` is set and an agent has `inputSchema`, `chat()` throws.
206
207To show the brief in the UI, see [Show the brief on a card](#show-the-brief-on-a-card).
208
209## Strategy
210
211- `exclusive` (default): the chosen child owns the turn. Main does not answer after it.
212- `handoff`: the child streams first. Then main runs with the new child text in the messages.
213
214The parent `RUN_FINISHED.usage` includes the token usage of every child.
215
216## Interrupts in a child
217
218Some child work needs a person first, for example deleting a file. Give that child tool `needsApproval: true`. The child stops, and the parent run ends with the child's interrupt. The client answers it like any other interrupt. The next run continues the same child.
219
2201. Share one tool definition between the server and the client:
221
222```typescript title="tools.ts"
223import { toolDefinition } from '@tanstack/ai'
224import { z } from 'zod'
225
226export const deleteFile = toolDefinition({
227 name: 'deleteFile',
228 description: 'Delete a file',
229 needsApproval: true,
230 inputSchema: z.object({ path: z.string() }),
231})
232```
233
2342. Give the child the server tool. Pass the resume fields from the request to the parent `chat()`:
235
236```typescript title="route.ts"
237import {
238 chat,
239 chatParamsFromRequest,
240 defineAgent,
241 toServerSentEventsResponse,
242} from '@tanstack/ai'
243import { openaiText } from '@tanstack/ai-openai'
244import { deleteFile } from './tools'
245
246const cleaner = defineAgent({
247 name: 'cleaner',
248 description: 'Deletes old files',
249 run: (ctx) =>
250 chat({
251 adapter: openaiText('gpt-5.6'),
252 messages: ctx.messages,
253 threadId: ctx.threadId,
254 runId: ctx.runId,
255 parentRunId: ctx.parentRunId,
256 subagentRunId: ctx.subagentRunId,
257 resume: ctx.resume,
258 tools: [deleteFile.server(({ path }: { path: string }) => ({ deleted: path }))],
259 }),
260})
261
262export async function POST(request: Request) {
263 const params = await chatParamsFromRequest(request)
264 const stream = chat({
265 adapter: openaiText('gpt-5.6'),
266 messages: params.messages,
267 threadId: params.threadId,
268 runId: params.runId,
269 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
270 ...(params.resume ? { resume: params.resume } : {}),
271 subagents: { agents: [cleaner], router: () => 'cleaner' },
272 })
273
274 return toServerSentEventsResponse(stream)
275}
276```
277
2783. Register the same definition on the client, and answer the interrupt:
279
280```tsx title="cleanup-panel.tsx"
281import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
282import { deleteFile } from './tools'
283
284export function CleanupPanel() {
285 const chat = useChat({
286 connection: fetchServerSentEvents('/api/chat'),
287 tools: [deleteFile.client()],
288 })
289
290 return (
291 <section>
292 <button onClick={() => chat.sendMessage('Clean up old files')}>
293 Clean up
294 </button>
295 {chat.interrupts.map((interrupt) =>
296 interrupt.kind === 'tool-approval' ? (
297 <button key={interrupt.id} onClick={() => interrupt.resolveInterrupt(true)}>
298 Approve delete
299 </button>
300 ) : null,
301 )}
302 </section>
303 )
304}
305```
306
307The resume uses the plan that the router picked in the first run. It does not call the router again. While the child waits, its card has `status: 'suspended'` and `interruptIds`. After you approve, the card shows the tool result and the child's reply. Client tools in a child work the same way.
308
309The same flow works without a router. The child's tool call stays open until the resume, then the parent model reads the child's result.
310
311## Middleware
312
313A child is its own `chat()` call. Put the child's middleware in that call. The parent's middleware list does not reach the child.
314
315Inside a child, the middleware context has `subagentRunId`. Use it to tell a child run from a top-level run, and to link a child trace to its card.
316
317On a routed turn where a child runs and main does not, the parent's middleware does not run. Only `withPersistence` records that turn. A turn where main runs, including a handoff, runs the parent's middleware as usual.
318
319## Persistence
320
321Put `withPersistence` on the parent `chat()` only. The parent stores each child:
322
323- the child run, linked to the parent run
324- the full child transcript
325- the child's pending interrupts
326- the card status
327
328A reload then shows every card, and a resume continues a waiting child. See [Subagent cards on reload](../persistence/chat-persistence#subagent-cards-on-reload).
329
330Do not add `withPersistence` to a child `chat()` too. The child does not know that it runs as a subagent, so it stores the same child again under its own run and thread ids. Its interrupt records then conflict with the parent's records, and a reload can lose the pending approval.
331
332## Sandbox
333
334`withSandbox` keys the workspace by `threadId`. Set `subagents.sandbox` so the child gets the right thread id. Pass `ctx.threadId` into the child `chat()`.
335
336Options:
337
338- `'own'` (default): the child thread id is `${parentThreadId}:${name}`. The child gets its own workspace.
339- `'inherit'`: the child thread id is the parent thread id. The child reuses the parent workspace when `lifecycle.reuse` is `'thread'`.
340
341If `sandbox` is `'inherit'` and the router returns two or more names, `chat()` throws before start. Two children write the same files at the same time.
342
343**Own workspace (default).** Each child works in isolation. Parallel children each get a workspace.
344
345```ts
346import { chat, defineAgent } from '@tanstack/ai'
347import { grokBuildText } from '@tanstack/ai-grok-build'
348import {
349 defineSandbox,
350 defineWorkspace,
351 withSandbox,
352} from '@tanstack/ai-sandbox'
353import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
354
355const messages = [{ role: 'user' as const, content: 'Fix the tests' }]
356const threadId = 'parent-thread'
357
358const repoSandbox = defineSandbox({
359 id: 'repo-agent',
360 provider: dockerSandbox({ image: 'node:22' }),
361 workspace: defineWorkspace({
362 source: { type: 'none' },
363 packageManager: 'pnpm',
364 }),
365 lifecycle: { reuse: 'thread' },
366})
367
368const coder = defineAgent({
369 name: 'coder',
370 description: 'Edits the repo in a sandbox',
371 run: (ctx) =>
372 chat({
373 adapter: grokBuildText('grok-build'),
374 messages: ctx.messages,
375 threadId: ctx.threadId,
376 runId: ctx.runId,
377 parentRunId: ctx.parentRunId,
378 subagentRunId: ctx.subagentRunId,
379 resume: ctx.resume,
380 middleware: [withSandbox(repoSandbox)],
381 }),
382})
383
384const ownStream = chat({
385 adapter: grokBuildText('grok-build'),
386 messages,
387 threadId,
388 middleware: [withSandbox(repoSandbox)],
389 subagents: {
390 agents: [coder],
391 sandbox: 'own',
392 strategy: 'exclusive',
393 router: () => 'coder',
394 },
395})
396
397const inheritStream = chat({
398 adapter: grokBuildText('grok-build'),
399 messages,
400 threadId,
401 middleware: [withSandbox(repoSandbox)],
402 subagents: {
403 agents: [coder],
404 sandbox: 'inherit',
405 strategy: 'exclusive',
406 router: () => 'coder',
407 },
408})
409```
410
411`ownStream` runs the child with `threadId` `parent-thread:coder`. `inheritStream` runs the child with `threadId` `parent-thread`, so `reuse: 'thread'` shares the parent workspace.
412
413See [Sandboxes](../sandbox/overview) for `withSandbox` and `lifecycle.reuse`.
414
415## Client
416
417The nested `type: 'subagent'` part and `useChat().subagents[i]` are the same live object. Call `stop()` on either one. The client sets that child to error and aborts the current parent run. Later events for that id, and for its nested children, are ignored.
418
419`part.subagent.messages` holds everything the child did:
420
421- text and reasoning
422- tool calls and tool results
423- approval state on the child's tool calls
424- nested children, as their own `subagent` parts
425
426`part.subagent.status` is `'running'`, `'finished'`, `'error'`, or `'suspended'`. By default, the child messages use the same parts components as the parent. A card can replace them for its child. See [Style one child's parts](#style-one-childs-parts).
427
428Use `createChatHook` from `@tanstack/ai-react/ui` when you want the factory to draw the cards. Pass the agents you give to `chat()` as `options.subagents`. The client reads each agent's `name`, `tools`, `interrupts`, and `outputSchema` for types. It does not call `run`. Register `subagentsComponents` for each agent name. Those components receive `SubagentProps` and `Parts`. Render `<Messages />`. The subagent card is a part of the assistant message. `<Subagents />` draws that same card for the live list. Pick one place for the card. If a started child has a name with no `subagentsComponents` entry, rendering that card throws.
429
430When you render the parts yourself, pass the same agents to `useChat`. The hook uses them for types only. It does not call `run`.
431
432```tsx
433import { defineAgent } from '@tanstack/ai'
434import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
435
436const researcher = defineAgent({
437 name: 'researcher',
438 description: 'Looks up facts',
439 run: async function* () {},
440})
441const writer = defineAgent({
442 name: 'writer',
443 description: 'Drafts posts',
444 run: async function* () {},
445})
446
447function Desk() {
448 const chat = useChat({
449 connection: fetchServerSentEvents('/api/chat'),
450 subagents: [researcher, writer],
451 })
452 const part = chat.messages[0]?.parts[0]
453 if (part?.type === 'subagent' && part.subagent.name === 'researcher') {
454 return part.subagent.status
455 }
456 return null
457}
458```
459
460`part.subagent.name` is `'researcher' | 'writer'`. After you check the name, that child's `messages` use the tools and output schema from that agent.
461
462```tsx
463import { defineAgent } from '@tanstack/ai'
464import { fetchServerSentEvents } from '@tanstack/ai-react'
465import { createChatHook } from '@tanstack/ai-react/ui'
466import type { LayoutProps, SubagentProps } from '@tanstack/ai-react/ui'
467
468const researcher = defineAgent({
469 name: 'researcher',
470 description: 'Looks up facts',
471 run: async function* () {},
472})
473const writer = defineAgent({
474 name: 'writer',
475 description: 'Drafts posts',
476 run: async function* () {},
477})
478
479const chatOptions = {
480 connection: fetchServerSentEvents('/api/chat'),
481 subagents: [researcher, writer],
482}
483
484function SubagentCard({
485 subagent,
486 Parts,
487}: SubagentProps<typeof chatOptions, 'researcher' | 'writer'>) {
488 return (
489 <section>
490 <strong>{subagent.name}</strong>
491 <span>{subagent.status}</span>
492 {subagent.status === 'running' ? (
493 <button type="button" onClick={() => subagent.stop?.()}>
494 Stop
495 </button>
496 ) : null}
497 <Parts />
498 </section>
499 )
500}
501
502const { useAppChat, useChatContext } = createChatHook({
503 options: chatOptions,
504 components: {
505 layout: ({ Messages, Input }: LayoutProps<typeof chatOptions>) => (
506 <main>
507 <Messages />
508 <Input />
509 </main>
510 ),
511 message: ({ Parts }) => <article><Parts /></article>,
512 input: function Input() {
513 const chat = useChatContext()
514 return (
515 <form
516 onSubmit={(event) => {
517 event.preventDefault()
518 const field = event.currentTarget.elements.namedItem('message')
519 if (!(field instanceof HTMLInputElement)) return
520 void chat.sendMessage(field.value)
521 field.value = ''
522 }}
523 >
524 <input name="message" />
525 <button type="submit">Send</button>
526 </form>
527 )
528 },
529 },
530 partsComponents: {
531 text: ({ part }) => <p>{part.content}</p>,
532 fallback: () => null,
533 },
534 subagentsComponents: {
535 researcher: SubagentCard,
536 writer: SubagentCard,
537 },
538})
539
540export function ChatScreen() {
541 const chat = useAppChat()
542 return <chat.AppChat />
543}
544```
545
546`part.subagent` is the same object as `useChat().subagents[i]` for that id. `stop()` on either one aborts the current parent run.
547
548When `run` imports server code, do not import the agent into the browser. Declare the agent once in a shared file, with its `name`, `description`, and tool definitions from `toolDefinition`. The server passes `defineAgent({ ...researcher, run })` to `chat()`. The client passes the declaration.
549
550### Show the brief on a card
551
552When an agent has `inputSchema`, the brief is the input of the tool call that started the child. That `tool-call` part is on the same assistant message as the card. `part.subagent.parentToolCallId` is its id:
553
554```tsx
555import type { UIMessage } from '@tanstack/ai-react'
556
557function briefOf(message: UIMessage, toolCallId: string) {
558 for (const part of message.parts) {
559 if (part.type !== 'tool-call' || part.id !== toolCallId) continue
560 const input = part.input
561 if (
562 typeof input === 'object' &&
563 input !== null &&
564 'task' in input &&
565 typeof input.task === 'string'
566 ) {
567 return input.task
568 }
569 }
570 return undefined
571}
572
573function Briefs({ message }: { message: UIMessage }) {
574 return message.parts.map((part) => {
575 if (part.type !== 'subagent') return null
576 const toolCallId = part.subagent.parentToolCallId
577 if (toolCallId === undefined) return null
578 return <p key={part.subagent.id}>{briefOf(message, toolCallId)}</p>
579 })
580}
581```
582
583A child that a router started has no `parentToolCallId`, so it has no brief.
584
585### Style one child's parts
586
587The researcher's reasoning and tool calls use the root widgets by default. To make them look different on the researcher card only, pass widgets to that card's `Parts`:
588
589```tsx
590import { toolDefinition } from '@tanstack/ai'
591import { fetchServerSentEvents } from '@tanstack/ai-react'
592import { createChatHook, ThinkingPart } from '@tanstack/ai-react/ui'
593import type { SubagentPartsProps, SubagentProps } from '@tanstack/ai-react/ui'
594import { z } from 'zod'
595
596const lookupWikipedia = toolDefinition({
597 name: 'lookupWikipedia',
598 description: 'Get the Wikipedia summary of one topic',
599 inputSchema: z.object({ title: z.string() }),
600 outputSchema: z.object({ extract: z.string() }),
601})
602
603// Shared with the server, which passes defineAgent({ ...researcher, run }).
604const researcher = {
605 name: 'researcher',
606 description: 'Looks up facts',
607 tools: [lookupWikipedia],
608} as const
609
610const chatOptions = {
611 connection: fetchServerSentEvents('/api/chat'),
612 subagents: [researcher],
613}
614
615type ResearcherWidgets = SubagentPartsProps<typeof chatOptions, 'researcher'>
616
617const researcherParts: ResearcherWidgets['partsComponents'] = {
618 thinking: ({ part }) => (
619 <ThinkingPart content={part.content} className="research-notes" />
620 ),
621}
622
623const researcherTools: ResearcherWidgets['toolsComponents'] = {
624 lookupWikipedia: ({ part }) => (
625 <details>
626 <summary>
627 {part.input?.title} ({part.state})
628 </summary>
629 {part.output?.extract}
630 </details>
631 ),
632}
633
634function Researcher({
635 Parts,
636}: SubagentProps<typeof chatOptions, 'researcher'>) {
637 return (
638 <section>
639 <Parts partsComponents={researcherParts} toolsComponents={researcherTools} />
640 </section>
641 )
642}
643
644export const { useAppChat } = createChatHook({
645 options: chatOptions,
646 components: {
647 layout: ({ Messages }) => (
648 <main>
649 <Messages />
650 </main>
651 ),
652 message: ({ Parts }) => (
653 <article>
654 <Parts />
655 </article>
656 ),
657 },
658 partsComponents: {
659 text: ({ part }) => <p>{part.content}</p>,
660 thinking: ({ part }) => <ThinkingPart content={part.content} />,
661 fallback: () => null,
662 },
663 subagentsComponents: { researcher: Researcher },
664})
665```
666
667- An entry on `Parts` replaces the root entry with the same key, for this card and for the children nested in it.
668- A key that you do not set uses the root entry. Here, `text` still uses the root widget.
669- `toolsComponents` keys and props come from the agent's `tools`. `part.input` and `part.output` are typed, and a tool name that the agent does not have is a type error. A tool call with no entry at any level renders nothing.
670- An approval for a child tool arrives as `interrupt` on that tool widget, typed from the tool. The root `interruptsComponents` also accepts the child's approval tools and the ids in the agent's `interrupts`.
671
672Define these maps outside the component. A new object on each render makes every part in the card render again. An approval for a tool that only a card registers also shows in the root `<Interrupts />` list.
673
674In the AI devtools, the Conversation tab shows each child as a card with its name and status. The card holds the child's steps, drawn the same way as the parent's steps. A new step starts after each tool result. The User view on the right shows the child's text and tool outputs.
675
676When the server events reach the devtools (the `devtools()` plugin from `@tanstack/devtools-vite`), the child's steps are its real server iterations, with the model, the system prompts, and the token usage. Without the plugin, the steps come from the messages in the browser.
677
678See [Stream Events](./stream-events) for `SUBAGENT_*` and `subagentRunId`.