Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

subagents.md

945 lines36.3 KB

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​
93Anywhere a name goes, `{ name, input }` can go too, for example `{ name: 'pricer', input: { vendor: 'Acme' } }`. An agent with `inputSchema` needs it. No other agent takes an input. `chat()` throws when the pick breaks either rule.
94​
95One step holds one input for each agent. To give one agent two inputs, put each pick in its own step of `{ steps }`.
96​
97`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`.
98​
99`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.
100​
101`{ names, order }` overrides that default for one turn. Use it when some turns are parallel and some are serial.
102​
103`{ 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.
104​
105A 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.
106​
107```ts
108const plan = {
109 steps: [
110 { names: ['researcher', 'seo'], order: 'parallel' },
111 { names: ['writer'] },
112 ],
114```
115​
116`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.
117​
118Pass 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.
119​
120```ts
121import { chat, decide, defineAgent, subagentRoute } from '@tanstack/ai'
122import { openaiText } from '@tanstack/ai-openai'
123import { typesafeDecider } from '@tanstack/ai-typesafe'
124​
125const researcher = defineAgent({
126 name: 'researcher',
127 description: 'Looks up facts',
128 run: async function* () {},
129})
130const writer = defineAgent({
131 name: 'writer',
132 description: 'Writes the post',
133 run: async function* () {},
134})
135const messages = [
136 { role: 'user' as const, content: 'Research squids and write an article' },
138​
139const stream = chat({
140 adapter: openaiText('gpt-5.6'),
141 messages,
142 subagents: {
143 agents: [researcher, writer],
144 router: async ({ messages: turnMessages, agents }) => {
145 const state = turnMessages.at(-1)
146 if (state === undefined) {
147 throw new Error('No message')
148 }
149 const route = subagentRoute(agents)
150 const result = await decide({
151 adapter: typesafeDecider('jev-latest'),
152 state,
153 questions: route.questions,
154 })
155 return route.pick(result)
156 },
157 },
158})
159```
160​
161**Give a routed agent its input.** An agent with `inputSchema` gets its input from the router. `route.needsInput(result)` lists the picked agents that need one, each with its schema. Make each input. Then pass them to `route.pick(result, { inputs })`. Here the model writes each input, with the schema as `outputSchema`:
162​
163```ts
164import { chat, decide, defineAgent, subagentRoute } from '@tanstack/ai'
165import { openaiText } from '@tanstack/ai-openai'
166import { typesafeDecider } from '@tanstack/ai-typesafe'
167import { z } from 'zod'
168​
169const writer = defineAgent({
170 name: 'writer',
171 description: 'Writes the post',
172 run: async function* () {},
173})
174const pricer = defineAgent({
175 name: 'pricer',
176 description: 'Compares the plans and prices of one vendor',
177 inputSchema: z.object({ vendor: z.string() }),
178 run: (ctx) =>
179 chat({
180 adapter: openaiText('gpt-6.1-sol'),
181 messages: [{ role: 'user', content: `Compare the plans of ${ctx.input.vendor}` }],
182 threadId: ctx.threadId,
183 runId: ctx.runId,
184 parentRunId: ctx.parentRunId,
185 subagentRunId: ctx.subagentRunId,
186 resume: ctx.resume,
187 }),
188})
189const messages = [
190 { role: 'user' as const, content: 'What does Acme cost? Write a post about it.' },
192​
193const stream = chat({
194 adapter: openaiText('gpt-6.1-sol'),
195 messages,
196 subagents: {
197 agents: [pricer, writer],
198 router: async ({ messages: turnMessages, agents }) => {
199 const route = subagentRoute(agents, { then: ['writer'] })
200 const result = await decide({
201 adapter: typesafeDecider('jev-latest'),
202 state: turnMessages,
203 questions: route.questions,
204 })
205 const inputs = Object.fromEntries(
206 await Promise.all(
207 route.needsInput(result).map(async ({ name, inputSchema }) => [
208 name,
209 await chat({
210 adapter: openaiText('gpt-6.1-sol'),
211 messages: turnMessages,
212 outputSchema: inputSchema,
213 }),
214 ]),
215 ),
216 )
217 return route.pick(result, { inputs })
218 },
219 },
220})
221```
222​
223- `pick` types `inputs` when you write it as an object, such as `{ pricer: { vendor: 'Acme' } }`. Each key is the name of an agent with `inputSchema`, and the value has the type of that schema. `Object.fromEntries` returns `any`, so the sample above has no such check.
224- If a picked agent with a schema has no input, `pick` throws `Agent "pricer" needs input. Pass it in inputs.`
225- `chat()` checks each input against the schema before any child starts. If one input does not match, `chat()` throws, and no child starts. The `inputSchema` must be a Standard Schema, such as a zod schema. If it is a plain JSON Schema, `chat()` throws.
226- `run` reads the input as `ctx.input`. The input stays on the server. It does not go to the client.
227- A turn with a router input cannot resume after an interrupt. Do not give a tool that needs approval, or a client tool, to an agent in such a turn.
228​
229**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. The model can also pass the task as `prompt`. The child gets it as the last user message. For all fields of the tool input, see [The tool input](#the-tool-input).
230​
231## Let the model write the brief
232​
233In 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.
234​
235Add `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`:
236​
237```ts
238import { chat, defineAgent } from '@tanstack/ai'
239import { openaiText } from '@tanstack/ai-openai'
240import { z } from 'zod'
241​
242const messages = [
243 { role: 'user' as const, content: 'Compare pricing for the vendors we picked' },
245​
246const researcher = defineAgent({
247 name: 'researcher',
248 description: 'Researches one focused question and returns sourced findings',
249 inputSchema: z.object({
250 task: z
251 .string()
252 .describe('What to find and what to return. The researcher sees only this text.'),
253 }),
254 run: (ctx) =>
255 chat({
256 adapter: openaiText('gpt-5.6'),
257 messages: [{ role: 'user', content: ctx.input.task }],
258 threadId: ctx.threadId,
259 runId: ctx.runId,
260 parentRunId: ctx.parentRunId,
261 subagentRunId: ctx.subagentRunId,
262 resume: ctx.resume,
263 }),
264})
265​
266const stream = chat({
267 adapter: openaiText('gpt-5.6'),
268 messages,
269 subagents: { agents: [researcher] },
270})
271```
272​
273- `ctx.input` has the type of the schema. Here it is `{ task: string }`.
274- 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.
275- `ctx.messages` still holds the parent conversation. Add parts of it when the child needs more context.
276- A resumed child gets the same `ctx.input` as the first run.
277- With `subagents.router`, the router gives the input. See [Route, or let the model pick](#route-or-let-the-model-pick).
278​
279To show the brief in the UI, see [Show the brief on a card](#show-the-brief-on-a-card).
280​
281## Continue a child
282​
283Each tool call starts a new child. Sometimes the model must send a follow-up to a child that already answered, like "make it shorter". Add `withPersistence` to the parent `chat()`. Each result then gives the model the `subagentRunId` of the child, and the model continues that child with `sessionId`.
284​
285```ts
286import {
287 chat,
288 chatParamsFromRequest,
289 defineAgent,
290 toServerSentEventsResponse,
291} from '@tanstack/ai'
292import { openaiText } from '@tanstack/ai-openai'
293import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
294​
295const writer = defineAgent({
296 name: 'writer',
297 description: 'Writes and edits drafts',
298 run: (ctx) => ctx.chat({ adapter: openaiText('gpt-6.1-sol') }),
299})
300​
301// A continued child loads from this store. Use a durable backend in production.
302const persistence = memoryPersistence()
303​
304export async function POST(request: Request) {
305 const params = await chatParamsFromRequest(request)
306 const stream = chat({
307 adapter: openaiText('gpt-6.1-sol'),
308 messages: params.messages,
309 threadId: params.threadId,
310 runId: params.runId,
311 middleware: [withPersistence(persistence)],
312 subagents: { agents: [writer] },
313 })
314 return toServerSentEventsResponse(stream)
316```
317​
318The model continues the writer like this:
319​
3201. The model calls `writer` with `{ "prompt": "Draft a post about tides" }`.
3212. It gets `{ "subagentRunId": "subagent-1767225600000-x7k2m9q", "result": "Tides rise twice a day..." }`.
3223. In a later turn, it calls `writer` with `{ "sessionId": "subagent-1767225600000-x7k2m9q", "prompt": "Make it shorter" }`.
323​
324The writer gets the task of its first call, its stored transcript, then `Make it shorter` as the last user message. The stream uses the same `subagentRunId`, so the client shows the new work on the same card.
325​
326### The tool input
327​
328Every agent tool takes the agent's own fields, plus two more:
329​
330- The fields of `inputSchema`, for an agent with one. The tool checks them against the schema.
331- `prompt`: the task as text, for an agent without `inputSchema`. The child gets it as the last user message.
332- `sessionId`: the `subagentRunId` of an earlier result. The call continues that child. The tool has this field only when `withPersistence` is on the parent `chat()`.
333- `background`: `true` starts the child and returns its `subagentRunId` at once. The tool has this field only when the host sets `subagents.binding.start`. The host returns `done`. `maxConcurrent` counts that child until `done` settles.
334​
335When the run uses `sessionId` or `background`, that name is reserved. If an `inputSchema` has a field with that name, `chat()` throws before the run starts.
336​
337### Wrong calls
338​
339A wrong call goes back to the model as a tool error, and the run continues. For example:
340​
341- `Input validation failed for tool researcher: ...`: the fields do not match `inputSchema`.
342- `Unknown sessionId "..."`: no child of this thread has that id. A thread can continue only its own children.
343- `Session "..." belongs to agent "writer", not "researcher".`: the call must use the tool of the agent that ran the child.
344- `background needs a host that runs children in the background.`
345​
346## Return a value, or call any activity
347​
348A child does not have to be a chat. It can make an image, or return a plain value that the parent model reads as the tool result. Call the activity on `ctx` and return what it gives you:
349​
350```ts group=subagent-values
351import { chat, defineAgent } from '@tanstack/ai'
352import { openaiImage, openaiText } from '@tanstack/ai-openai'
353import { z } from 'zod'
354​
355const heroImage = defineAgent({
356 name: 'heroImage',
357 description: 'Makes a hero image for a post',
358 produces: 'image',
359 inputSchema: z.object({ prompt: z.string() }),
360 run: (ctx) =>
361 ctx.generateImage({
362 adapter: openaiImage('gpt-image-2.5-sunburst'),
363 prompt: `${ctx.input.prompt}. Brand colors: blue and white.`,
364 size: '1536x1024',
365 }),
366})
367​
368const stream = chat({
369 adapter: openaiText('gpt-6.1-sol'),
370 messages: [{ role: 'user', content: 'Make a hero image about squids' }],
371 subagents: { agents: [heroImage] },
372})
373```
374​
375- `ctx.chat`, `ctx.generateImage`, `ctx.generateVideo`, `ctx.generateSpeech`, and the other activities on `ctx` take the same options as the plain functions. They fill in the thread id, a run id, and the abort signal.
376- `ctx.chat` also uses the parent conversation (`ctx.messages`) when you do not pass `messages`.
377- `run` can return a promise of any value. The value arrives on `SUBAGENT_FINISHED.result`, and the parent model gets it as the tool result.
378- A string result also streams as the child's text, so the card shows it. The parent model gets the full string.
379- The result of `ctx.chat({ stream: false })` streams like the chat stream: its text, usage, and interrupts reach the parent.
380- Each `ctx.chat` call after the first one gets its own run id.
381- A very long string in the result (for example a base64 image) reaches the parent model as a short note, `[omitted 5000 characters]`. The full value stays on `SUBAGENT_FINISHED.result`.
382- `produces` says what the agent makes (`'image'`, `'text'`, and so on). It does not change how the agent runs.
383​
384When you call the plain `chat()` instead, spread `ctx.forward` to pass the child's ids and abort controller in one line:
385​
386```ts group=subagent-values
387const researcher = defineAgent({
388 name: 'researcher',
389 description: 'Looks up facts',
390 run: (ctx) =>
391 chat({
392 adapter: openaiText('gpt-6.1-sol'),
393 messages: ctx.messages,
394 ...ctx.forward,
395 }),
396})
397```
398​
399A child that `ctx.chat` starts gets the prompt cache retention of the parent call, unless the call sets its own `promptCache`.
400​
401## Limit the tree
402​
403A child can have children of its own, and a model can call a child many times. Set `limits` so one request cannot start an unbounded tree:
404​
405```ts group=subagent-values
406const limited = chat({
407 adapter: openaiText('gpt-6.1-sol'),
408 messages: [{ role: 'user', content: 'Research squids in depth' }],
409 subagents: {
410 agents: [researcher],
411 limits: { maxDepth: 2, maxConcurrent: 3, maxCalls: 12, timeoutMs: 120_000 },
412 },
413})
414```
415​
416- `maxDepth`: how deep the tree can grow. The first chat is depth 0.
417- `maxCalls`: how many children the whole tree can start.
418- `maxConcurrent`: how many children one run can have running at once.
419- `timeoutMs`: how long one child can run. A child never gets more time than its parent has left.
420​
421The whole tree shares one budget. A child that calls `ctx.chat({ subagents })` passes it on, so a child cannot reset it. A refused start reaches the model as a tool error, for example `subagent limit reached (maxCalls 12)`.
422​
423- Set `limits` on the first `chat()`. A nested chat in a child uses that budget, so its own `limits` do not apply.
424- A child that a router picks does not count against the limits. The children it starts do count, one level deeper.
425- A child that runs past `timeoutMs` stops, and the model gets `subagent timed out after 120000 ms`.
426- When the parent has no time left, the model gets `subagent limit reached (no time left)`.
427- A limit of `timeoutMs: 0` gets `subagent limit reached (timeoutMs 0)`.
428​
429## Keys for agents
430​
431An agent that calls a model needs a provider key. An adapter such as `openaiText` reads its env var, for example `OPENAI_API_KEY`.
432​
433To use the key of the user, pass it on `subagents.keys`. The agent then builds its adapter with `ctx.keys`. See [Keys inside agents](../advanced/byok#keys-inside-agents).
434​
435## Strategy
436​
437- `exclusive` (default): the chosen child owns the turn. Main does not answer after it.
438- `handoff`: the child streams first. Then main runs with the new child text in the messages.
439​
440The parent `RUN_FINISHED.usage` includes the token usage of every child.
441​
442## Interrupts in a child
443​
444Some 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.
445​
4461. Share one tool definition between the server and the client:
447​
448```typescript title="tools.ts"
449import { toolDefinition } from '@tanstack/ai'
450import { z } from 'zod'
451​
452export const deleteFile = toolDefinition({
453 name: 'deleteFile',
454 description: 'Delete a file',
455 needsApproval: true,
456 inputSchema: z.object({ path: z.string() }),
457})
458```
459​
4602. Give the child the server tool. Pass the resume fields from the request to the parent `chat()`:
461​
462```typescript title="route.ts"
463import {
464 chat,
465 chatParamsFromRequest,
466 defineAgent,
467 toServerSentEventsResponse,
468} from '@tanstack/ai'
469import { openaiText } from '@tanstack/ai-openai'
470import { deleteFile } from './tools'
471​
472const cleaner = defineAgent({
473 name: 'cleaner',
474 description: 'Deletes old files',
475 run: (ctx) =>
476 chat({
477 adapter: openaiText('gpt-5.6'),
478 messages: ctx.messages,
479 threadId: ctx.threadId,
480 runId: ctx.runId,
481 parentRunId: ctx.parentRunId,
482 subagentRunId: ctx.subagentRunId,
483 resume: ctx.resume,
484 tools: [deleteFile.server(({ path }: { path: string }) => ({ deleted: path }))],
485 }),
486})
487​
488export async function POST(request: Request) {
489 const params = await chatParamsFromRequest(request)
490 const stream = chat({
491 adapter: openaiText('gpt-5.6'),
492 messages: params.messages,
493 threadId: params.threadId,
494 runId: params.runId,
495 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
496 ...(params.resume ? { resume: params.resume } : {}),
497 subagents: { agents: [cleaner], router: () => 'cleaner' },
498 })
499​
500 return toServerSentEventsResponse(stream)
502```
503​
5043. Register the same definition on the client, and answer the interrupt:
505​
506```tsx title="cleanup-panel.tsx"
507import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
508import { deleteFile } from './tools'
509​
510export function CleanupPanel() {
511 const chat = useChat({
512 connection: fetchServerSentEvents('/api/chat'),
513 tools: [deleteFile.client()],
514 })
515​
516 return (
517 <section>
518 <button onClick={() => chat.sendMessage('Clean up old files')}>
519 Clean up
520 </button>
521 {chat.interrupts.map((interrupt) =>
522 interrupt.kind === 'tool-approval' ? (
523 <button key={interrupt.id} onClick={() => interrupt.resolveInterrupt(true)}>
524 Approve delete
525 </button>
526 ) : null,
527 )}
528 </section>
529 )
531```
532​
533The resume uses the plan that the router picked in the first run. It does not call the router again. If the router gave an agent of that plan an input, the resume fails. 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.
534​
535The 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. The result content carries the child's output or error. It carries `subagentRunId` only when the model can continue the child: with a persistence store, or for a background child. Else the id stays in the subagent events.
536​
537## Middleware
538​
539A child is its own `chat()` call. Put the child's middleware in that call. The parent's middleware list does not reach the child.
540​
541Inside 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.
542​
543When the child calls `ctx.chat`, the context also has `subagentName`, the name of the agent. For a nested child, `parentSubagentRunId` is the id of the child that started it.
544​
545On 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.
546​
547## Run a child from code
548​
549A server job can run an agent with no parent chat turn. Pass a sink when the job must read a pause or the token counts.
550​
551```ts group=subagents
552import {
553 createSubagentId,
554 createSubagentSink,
555 runAgentStream,
556} from '@tanstack/ai'
557​
558const subagentRunId = createSubagentId()
559const sink = createSubagentSink()
560for await (const chunk of runAgentStream(
561 researcher,
562 {
563 input: undefined,
564 messages: [{ role: 'user', content: 'Find three facts about squids' }],
565 threadId: 'thread-1',
566 runId: `job-1:${subagentRunId}`,
567 parentRunId: 'job-1',
568 subagentRunId,
569 },
570 sink,
571)) {
572 if (chunk.type === 'TEXT_MESSAGE_CONTENT') console.log(chunk.delta)
574```
575​
576The sink holds the pause and the token counts:
577​
578- `sink.interrupts` has the interrupt objects. The finished event has `interruptIds` only.
579- `sink.usage` has one entry per model call.
580- `runAgentStream` does not check `input`. If the agent has an `inputSchema`, check the input before the call.
581- A failure ends as `SUBAGENT_ERROR`. The stream omits `RUN_STARTED`, `MESSAGES_SNAPSHOT`, and `RUN_FINISHED`.
582​
583After the loop, read `sink.interrupts` to show the pause.
584​
585## Persistence
586​
587Put `withPersistence` on the parent `chat()` only. The parent stores each child:
588​
589- the child run, linked to the parent run
590- the full child transcript
591- the child's pending interrupts
592- the card status
593​
594A reload then shows every card, and a resume continues a waiting child. See [Subagent cards on reload](../persistence/chat-persistence#subagent-cards-on-reload).
595​
596Do 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.
597​
598## Sandbox
599​
600`withSandbox` keys the workspace by `threadId`. Set `subagents.sandbox` so the child gets the right thread id. Pass `ctx.threadId` into the child `chat()`.
601​
602Options:
603​
604- `'own'` (default): the child thread id is `${parentThreadId}:${name}`. The child gets its own workspace.
605- `'inherit'`: the child thread id is the parent thread id. The child reuses the parent workspace when `lifecycle.reuse` is `'thread'`.
606​
607If `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.
608​
609**Own workspace (default).** Each child works in isolation. Parallel children each get a workspace.
610​
611```ts
612import { chat, defineAgent } from '@tanstack/ai'
613import { grokBuildText } from '@tanstack/ai-grok-build'
614import {
615 defineSandbox,
616 defineWorkspace,
617 withSandbox,
618} from '@tanstack/ai-sandbox'
619import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
620​
621const messages = [{ role: 'user' as const, content: 'Fix the tests' }]
622const threadId = 'parent-thread'
623​
624const repoSandbox = defineSandbox({
625 id: 'repo-agent',
626 provider: dockerSandbox({ image: 'node:22' }),
627 workspace: defineWorkspace({
628 source: { type: 'none' },
629 packageManager: 'pnpm',
630 }),
631 lifecycle: { reuse: 'thread' },
632})
633​
634const coder = defineAgent({
635 name: 'coder',
636 description: 'Edits the repo in a sandbox',
637 run: (ctx) =>
638 chat({
639 adapter: grokBuildText('grok-build'),
640 messages: ctx.messages,
641 threadId: ctx.threadId,
642 runId: ctx.runId,
643 parentRunId: ctx.parentRunId,
644 subagentRunId: ctx.subagentRunId,
645 resume: ctx.resume,
646 middleware: [withSandbox(repoSandbox)],
647 }),
648})
649​
650const ownStream = chat({
651 adapter: grokBuildText('grok-build'),
652 messages,
653 threadId,
654 middleware: [withSandbox(repoSandbox)],
655 subagents: {
656 agents: [coder],
657 sandbox: 'own',
658 strategy: 'exclusive',
659 router: () => 'coder',
660 },
661})
662​
663const inheritStream = chat({
664 adapter: grokBuildText('grok-build'),
665 messages,
666 threadId,
667 middleware: [withSandbox(repoSandbox)],
668 subagents: {
669 agents: [coder],
670 sandbox: 'inherit',
671 strategy: 'exclusive',
672 router: () => 'coder',
673 },
674})
675```
676​
677`ownStream` runs the child with `threadId` `parent-thread:coder`. `inheritStream` runs the child with `threadId` `parent-thread`, so `reuse: 'thread'` shares the parent workspace.
678​
679See [Sandboxes](../sandbox/overview) for `withSandbox` and `lifecycle.reuse`.
680​
681## Client
682​
683The 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.
684​
685`part.subagent.messages` holds everything the child did:
686​
687- text and reasoning
688- tool calls and tool results
689- approval state on the child's tool calls
690- nested children, as their own `subagent` parts
691​
692`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).
693​
694Use `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.
695​
696When you render the parts yourself, pass the same agents to `useChat`. The hook uses them for types only. It does not call `run`.
697​
698```tsx
699import { defineAgent } from '@tanstack/ai'
700import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
701​
702const researcher = defineAgent({
703 name: 'researcher',
704 description: 'Looks up facts',
705 run: async function* () {},
706})
707const writer = defineAgent({
708 name: 'writer',
709 description: 'Drafts posts',
710 run: async function* () {},
711})
712​
713function Desk() {
714 const chat = useChat({
715 connection: fetchServerSentEvents('/api/chat'),
716 subagents: [researcher, writer],
717 })
718 const part = chat.messages[0]?.parts[0]
719 if (part?.type === 'subagent' && part.subagent.name === 'researcher') {
720 return part.subagent.status
721 }
722 return null
724```
725​
726`part.subagent.name` is `'researcher' | 'writer'`. After you check the name, that child's `messages` use the tools and output schema from that agent.
727​
728```tsx
729import { defineAgent } from '@tanstack/ai'
730import { fetchServerSentEvents } from '@tanstack/ai-react'
731import { createChatHook } from '@tanstack/ai-react/ui'
732import type { LayoutProps, SubagentProps } from '@tanstack/ai-react/ui'
733​
734const researcher = defineAgent({
735 name: 'researcher',
736 description: 'Looks up facts',
737 run: async function* () {},
738})
739const writer = defineAgent({
740 name: 'writer',
741 description: 'Drafts posts',
742 run: async function* () {},
743})
744​
745const chatOptions = {
746 connection: fetchServerSentEvents('/api/chat'),
747 subagents: [researcher, writer],
749​
750function SubagentCard({
751 subagent,
752 Parts,
753}: SubagentProps<typeof chatOptions, 'researcher' | 'writer'>) {
754 return (
755 <section>
756 <strong>{subagent.name}</strong>
757 <span>{subagent.status}</span>
758 {subagent.status === 'running' ? (
759 <button type="button" onClick={() => subagent.stop?.()}>
760 Stop
761 </button>
762 ) : null}
763 <Parts />
764 </section>
765 )
767​
768const { useAppChat, useChatContext } = createChatHook({
769 options: chatOptions,
770 components: {
771 layout: ({ Messages, Input }: LayoutProps<typeof chatOptions>) => (
772 <main>
773 <Messages />
774 <Input />
775 </main>
776 ),
777 message: ({ Parts }) => <article><Parts /></article>,
778 input: function Input() {
779 const chat = useChatContext()
780 return (
781 <form
782 onSubmit={(event) => {
783 event.preventDefault()
784 const field = event.currentTarget.elements.namedItem('message')
785 if (!(field instanceof HTMLInputElement)) return
786 void chat.sendMessage(field.value)
787 field.value = ''
788 }}
789 >
790 <input name="message" />
791 <button type="submit">Send</button>
792 </form>
793 )
794 },
795 },
796 partsComponents: {
797 text: ({ part }) => <p>{part.content}</p>,
798 fallback: () => null,
799 },
800 subagentsComponents: {
801 researcher: SubagentCard,
802 writer: SubagentCard,
803 },
804})
805​
806export function ChatScreen() {
807 const chat = useAppChat()
808 return <chat.AppChat />
810```
811​
812`part.subagent` is the same object as `useChat().subagents[i]` for that id. `stop()` on either one aborts the current parent run.
813​
814When `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.
815​
816### Show the brief on a card
817​
818When an agent has `inputSchema`, the card keeps the checked input that the parent model wrote, as `part.subagent.input`. Put `inputSchema` in the shared declaration, and pass the declaration to `useChat` to type it:
819​
820```typescript title="agents.ts"
821import { z } from 'zod'
822​
823export const researcher = {
824 name: 'researcher',
825 description: 'Researches one focused question and returns sourced findings',
826 inputSchema: z.object({ task: z.string() }),
827} as const
828```
829​
830```tsx title="briefs.tsx"
831import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
832import { researcher } from './agents'
833​
834export function Briefs() {
835 const { messages } = useChat({
836 connection: fetchServerSentEvents('/api/chat'),
837 subagents: [researcher],
838 })
839 return messages.flatMap((message) =>
840 message.parts.map((part) =>
841 part.type === 'subagent' ? (
842 <p key={part.subagent.id}>{part.subagent.input?.task}</p>
843 ) : null,
844 ),
845 )
847```
848​
849- `part.subagent.input` is the same value as `ctx.input` in `run`, with the output type of the schema. Here it is `{ task: string } | undefined`.
850- It is `undefined` for an agent without `inputSchema`. A router input stays on the server, so a child that a router started has no `part.subagent.input`.
851​
852### Style one child's parts
853​
854The 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`:
855​
856```tsx
857import { toolDefinition } from '@tanstack/ai'
858import { fetchServerSentEvents } from '@tanstack/ai-react'
859import { createChatHook, ThinkingPart } from '@tanstack/ai-react/ui'
860import type { SubagentPartsProps, SubagentProps } from '@tanstack/ai-react/ui'
861import { z } from 'zod'
862​
863const lookupWikipedia = toolDefinition({
864 name: 'lookupWikipedia',
865 description: 'Get the Wikipedia summary of one topic',
866 inputSchema: z.object({ title: z.string() }),
867 outputSchema: z.object({ extract: z.string() }),
868})
869​
870// Shared with the server, which passes defineAgent({ ...researcher, run }).
871const researcher = {
872 name: 'researcher',
873 description: 'Looks up facts',
874 tools: [lookupWikipedia],
875} as const
876​
877const chatOptions = {
878 connection: fetchServerSentEvents('/api/chat'),
879 subagents: [researcher],
881​
882type ResearcherWidgets = SubagentPartsProps<typeof chatOptions, 'researcher'>
883​
884const researcherParts: ResearcherWidgets['partsComponents'] = {
885 thinking: ({ part }) => (
886 <ThinkingPart content={part.content} className="research-notes" />
887 ),
889​
890const researcherTools: ResearcherWidgets['toolsComponents'] = {
891 lookupWikipedia: ({ part }) => (
892 <details>
893 <summary>
894 {part.input?.title} ({part.state})
895 </summary>
896 {part.output?.extract}
897 </details>
898 ),
900​
901function Researcher({
902 Parts,
903}: SubagentProps<typeof chatOptions, 'researcher'>) {
904 return (
905 <section>
906 <Parts partsComponents={researcherParts} toolsComponents={researcherTools} />
907 </section>
908 )
910​
911export const { useAppChat } = createChatHook({
912 options: chatOptions,
913 components: {
914 layout: ({ Messages }) => (
915 <main>
916 <Messages />
917 </main>
918 ),
919 message: ({ Parts }) => (
920 <article>
921 <Parts />
922 </article>
923 ),
924 },
925 partsComponents: {
926 text: ({ part }) => <p>{part.content}</p>,
927 thinking: ({ part }) => <ThinkingPart content={part.content} />,
928 fallback: () => null,
929 },
930 subagentsComponents: { researcher: Researcher },
931})
932```
933​
934- An entry on `Parts` replaces the root entry with the same key, for this card and for the children nested in it.
935- A key that you do not set uses the root entry. Here, `text` still uses the root widget.
936- `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.
937- 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`.
938​
939Define 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.
940​
941In 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.
942​
943When 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.
944​
945See [Stream Events](./stream-events) for `SUBAGENT_*` and `subagentRunId`.