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

subagents-advanced.md

735 lines26.3 KB

1---
2title: "Subagents: Advanced"
3id: subagents-advanced
4description: "Router plans, the agent tool input, value results, limits, middleware, sandboxes, and custom subagent cards."
5keywords:
6 - tanstack ai
7 - subagents
8 - defineAgent
9 - subagentRoute
10 - router
11 - sandbox
12---
13​
14This page covers the details of subagents that you need only for special cases. Set up the basics first with [Subagents](./subagents).
15​
16## Router picks
17​
18The router can return:
19​
20- `'main'`: the parent model answers the turn.
21- One agent name.
22- An array of names.
23- `{ names, order }`: a list with its own order for this turn.
24- `{ steps }`: groups that run one after another.
25​
26Anywhere a name goes, `{ name, input }` can go too, for example `{ name: 'pricer', input: { vendor: 'Acme' } }`. These rules apply:
27​
28- An agent with `inputSchema` needs an input.
29- No other agent takes an input.
30- If the pick breaks one of these rules, `chat()` throws.
31​
32One step holds one input for each agent. To give one agent two inputs, put each pick in its own step of `{ steps }`.
33​
34### Order
35​
36`subagents.order` is the default order for an array:
37​
38- `parallel` (default): the names start together.
39- `sequence`: the names run one after another. Each later child reads the text of the earlier child.
40​
41`{ names, order }` overrides that default for one turn. If some turns are parallel and some are serial, use it.
42​
43`{ 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. If two agents start together and a later agent must read both, use `{ steps }`:
44​
45```ts
46const plan = {
47 steps: [
48 { names: ['researcher', 'seo'], order: 'parallel' },
49 { names: ['writer'] },
50 ],
52```
53​
54A later user message can also read that child text. The assistant message keeps the name and text of each child, so the next turn still has the notes.
55​
56### Build the plan with `subagentRoute`
57​
58`subagentRoute` makes one yes/no question for each agent and 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.
59​
60```ts
61import { chat, decide, defineAgent, subagentRoute } from '@tanstack/ai'
62import { openaiText } from '@tanstack/ai-openai'
63import { typesafeDecider } from '@tanstack/ai-typesafe'
64​
65const researcher = defineAgent({
66 name: 'researcher',
67 description: 'Looks up facts',
68 run: async function* () {},
69})
70const writer = defineAgent({
71 name: 'writer',
72 description: 'Writes the post',
73 run: async function* () {},
74})
75const messages = [
76 { role: 'user' as const, content: 'Research squids and write an article' },
78​
79const stream = chat({
80 adapter: openaiText('gpt-6.1-sol'),
81 messages,
82 threadId: 'thread-1',
83 subagents: {
84 agents: [researcher, writer],
85 router: async ({ messages: turnMessages, agents }) => {
86 const state = turnMessages.at(-1)
87 if (state === undefined) {
88 throw new Error('No message')
89 }
90 const route = subagentRoute(agents)
91 const result = await decide({
92 adapter: typesafeDecider('jev-latest'),
93 state,
94 questions: route.questions,
95 })
96 return route.pick(result)
97 },
98 },
99})
100```
101​
102- Pass the `agents` argument of the router to `subagentRoute`. Each yes/no question uses the `description` of that agent.
103- If you need different question text, pass `when`. `when` must include every agent name.
104- `pick` returns `main`, one name, `{ names, order }`, or `{ steps }`. The names follow the order of that `agents` array.
105- `subagentRoute(agents, { then: ['writer'] })` puts the writer in a later step when it 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.
106​
107### Give a routed agent its input
108​
109An agent with `inputSchema` gets its input from the router:
110​
1111. `route.needsInput(result)` lists the picked agents that need an input, each with its schema.
1122. Make each input.
1133. Pass the inputs to `route.pick(result, { inputs })`.
114​
115Here the model writes each input, with the schema as `outputSchema`:
116​
117```ts
118import { chat, decide, defineAgent, subagentRoute } from '@tanstack/ai'
119import { openaiText } from '@tanstack/ai-openai'
120import { typesafeDecider } from '@tanstack/ai-typesafe'
121import { z } from 'zod'
122​
123const writer = defineAgent({
124 name: 'writer',
125 description: 'Writes the post',
126 run: async function* () {},
127})
128const pricer = defineAgent({
129 name: 'pricer',
130 description: 'Compares the plans and prices of one vendor',
131 inputSchema: z.object({ vendor: z.string() }),
132 run: (ctx) =>
133 chat({
134 adapter: openaiText('gpt-6.1-sol'),
135 messages: [{ role: 'user', content: `Compare the plans of ${ctx.input.vendor}` }],
136 threadId: ctx.threadId,
137 runId: ctx.runId,
138 parentRunId: ctx.parentRunId,
139 subagentRunId: ctx.subagentRunId,
140 resume: ctx.resume,
141 }),
142})
143const messages = [
144 { role: 'user' as const, content: 'What does Acme cost? Write a post about it.' },
146const threadId = 'thread-1'
147​
148const stream = chat({
149 adapter: openaiText('gpt-6.1-sol'),
150 messages,
151 threadId,
152 subagents: {
153 agents: [pricer, writer],
154 router: async ({ messages: turnMessages, agents }) => {
155 const route = subagentRoute(agents, { then: ['writer'] })
156 const result = await decide({
157 adapter: typesafeDecider('jev-latest'),
158 state: turnMessages,
159 questions: route.questions,
160 })
161 const inputs = Object.fromEntries(
162 await Promise.all(
163 route.needsInput(result).map(async ({ name, inputSchema }) => [
164 name,
165 await chat({
166 adapter: openaiText('gpt-6.1-sol'),
167 messages: turnMessages,
168 threadId,
169 outputSchema: inputSchema,
170 }),
171 ]),
172 ),
173 )
174 return route.pick(result, { inputs })
175 },
176 },
177})
178```
179​
180- `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 type check.
181- If a picked agent with a schema has no input, `pick` throws `Agent "pricer" needs input. Pass it in inputs.`
182- `chat()` checks each input against the schema before any child starts. If one input does not match, `chat()` throws, and no child starts.
183- The `inputSchema` must be a Standard Schema, such as a zod schema. If it is a plain JSON Schema, `chat()` throws.
184- `run` reads the input as `ctx.input`. The input stays on the server. It does not go to the client.
185​
186> [!WARNING]
187> 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.
188​
189## The tool input
190​
191Without a router, every agent tool takes the fields of the agent, plus two more:
192​
193- The fields of `inputSchema`, for an agent with one. The tool checks them against the schema.
194- `prompt`: the task as text, for an agent without `inputSchema`. The child gets it as the last user message.
195- `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()`.
196- `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.
197​
198When 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.
199​
200### Wrong calls
201​
202A wrong call goes back to the model as a tool error, and the run continues. For example:
203​
204- `Input validation failed for tool researcher: ...`: the fields do not match `inputSchema`.
205- `Unknown sessionId "..."`: no child of this thread has that id. A thread can continue only its own children.
206- `Session "..." belongs to agent "writer", not "researcher".`: the call must use the tool of the agent that ran the child.
207- `background needs a host that runs children in the background.`
208​
209## Return a value, or call any activity
210​
211A 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:
212​
213```ts group=subagent-values
214import { chat, defineAgent } from '@tanstack/ai'
215import { openaiImage, openaiText } from '@tanstack/ai-openai'
216import { z } from 'zod'
217​
218const heroImage = defineAgent({
219 name: 'heroImage',
220 description: 'Makes a hero image for a post',
221 produces: 'image',
222 inputSchema: z.object({ prompt: z.string() }),
223 run: (ctx) =>
224 ctx.generateImage({
225 adapter: openaiImage('gpt-image-2.5-sunburst'),
226 prompt: `${ctx.input.prompt}. Brand colors: blue and white.`,
227 size: '1536x1024',
228 }),
229})
230​
231const stream = chat({
232 adapter: openaiText('gpt-6.1-sol'),
233 messages: [{ role: 'user', content: 'Make a hero image about squids' }],
234 threadId: 'thread-1',
235 subagents: { agents: [heroImage] },
236})
237```
238​
239What the activities on `ctx` do:
240​
241- `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.
242- `ctx.chat` also uses the parent conversation (`ctx.messages`) when you do not pass `messages`.
243- Each `ctx.chat` call after the first one gets its own run id.
244- A child that `ctx.chat` starts gets the prompt cache retention of the parent call, unless the call sets its own `promptCache`.
245​
246What happens to the result:
247​
248- `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.
249- A string result also streams as the text of the child, so the card shows it. The parent model gets the full string.
250- The result of `ctx.chat({ stream: false })` streams like the chat stream. Its text, usage, and interrupts reach the parent.
251- 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`.
252​
253`produces` says what the agent makes (`'image'`, `'text'`, and more). It does not change how the agent runs.
254​
255When you call the plain `chat()` instead, spread `ctx.forward`. It passes the ids and the abort controller of the child in one line:
256​
257```ts group=subagent-values
258const researcher = defineAgent({
259 name: 'researcher',
260 description: 'Looks up facts',
261 run: (ctx) =>
262 chat({
263 adapter: openaiText('gpt-6.1-sol'),
264 messages: ctx.messages,
265 ...ctx.forward,
266 }),
267})
268```
269​
270## Limit details
271​
272The whole tree shares one budget. A child that calls `ctx.chat({ subagents })` passes the budget on, so a child cannot reset it.
273​
274- Set `limits` on the first `chat()`. A nested chat in a child uses that budget, so its own `limits` do not apply.
275- A child that a router picks does not count against the limits. The children it starts do count, one level deeper.
276​
277A refused start reaches the model as a tool error:
278​
279| Cause | Tool error |
280| --- | --- |
281| Too many calls | `subagent limit reached (maxCalls 12)` |
282| A child runs past `timeoutMs` | `subagent timed out after 120000 ms` |
283| The parent has no time left | `subagent limit reached (no time left)` |
284| `timeoutMs: 0` | `subagent limit reached (timeoutMs 0)` |
285​
286## Keys for agents
287​
288An agent that calls a model needs a provider key. An adapter such as `openaiText` reads its env var, for example `OPENAI_API_KEY`.
289​
290To 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).
291​
292## Middleware
293​
294A child is its own `chat()` call. Put the middleware of the child in that call. The middleware list of the parent does not reach the child.
295​
296The middleware context of a child has these fields:
297​
298- `subagentRunId`: tells a child run from a top-level run. Use it to link a child trace to its card.
299- `subagentName`: the name of the agent, when the child calls `ctx.chat`.
300- `parentSubagentRunId`: for a nested child, the id of the child that started it.
301​
302When a resume answers an interrupt from an agent tool call, the middleware context of the parent has `childResumeIds`. These are the interrupt ids in `resume` that the child answers. The parent run does not answer them. When no child resumes, `childResumeIds` is `undefined`.
303​
304On a routed turn where a child runs and main does not, the middleware of the parent does not run. Only `withPersistence` records that turn. A turn where main runs, including a handoff, runs the middleware of the parent as usual.
305​
306## Run a child from code
307​
308A server job can run an agent with no parent chat turn. If the job must read a pause or the token counts, pass a sink.
309​
310```ts
311import {
312 chat,
313 createSubagentId,
314 createSubagentSink,
315 defineAgent,
316 runAgentStream,
317} from '@tanstack/ai'
318import { openaiText } from '@tanstack/ai-openai'
319​
320const researcher = defineAgent({
321 name: 'researcher',
322 description: 'Looks up facts and sources',
323 run: (ctx) =>
324 chat({
325 adapter: openaiText('gpt-6.1-sol'),
326 messages: ctx.messages,
327 ...ctx.forward,
328 }),
329})
330​
331const subagentRunId = createSubagentId()
332const sink = createSubagentSink()
333for await (const chunk of runAgentStream(
334 researcher,
335 {
336 input: undefined,
337 messages: [{ role: 'user', content: 'Find three facts about squids' }],
338 threadId: 'thread-1',
339 runId: `job-1:${subagentRunId}`,
340 parentRunId: 'job-1',
341 subagentRunId,
342 },
343 sink,
344)) {
345 if (chunk.type === 'TEXT_MESSAGE_CONTENT') console.log(chunk.delta)
347```
348​
349The sink holds the pause and the token counts:
350​
351- `sink.interrupts` has the interrupt objects. The finished event has `interruptIds` only.
352- `sink.usage` has one entry for each model call.
353​
354After the loop, read `sink.interrupts` to show the pause.
355​
356Some things that `chat({ subagents })` does for you, `runAgentStream` does not do:
357​
358- It does not check `input`. If the agent has an `inputSchema`, check the input before the call.
359- A failure ends as `SUBAGENT_ERROR`. The stream omits `RUN_STARTED`, `MESSAGES_SNAPSHOT`, and `RUN_FINISHED`.
360​
361## Sandbox
362​
363`withSandbox` keys the workspace by `threadId`. Set `subagents.sandbox` so the child gets the right thread id. Pass `ctx.threadId` into the child `chat()`.
364​
365- `'own'` (default): the child thread id is `${parentThreadId}:${name}`. The child gets its own workspace. Parallel children each get a workspace.
366- `'inherit'`: the child thread id is the parent thread id. The child uses the parent workspace again when `lifecycle.reuse` is `'thread'`.
367​
368If `sandbox` is `'inherit'` and the router returns two or more names, `chat()` throws before the start. Otherwise two children write the same files at the same time.
369​
370```ts
371import { chat, defineAgent } from '@tanstack/ai'
372import { grokBuildText } from '@tanstack/ai-grok-build'
373import {
374 defineSandbox,
375 defineWorkspace,
376 withSandbox,
377} from '@tanstack/ai-sandbox'
378import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
379​
380const messages = [{ role: 'user' as const, content: 'Fix the tests' }]
381const threadId = 'parent-thread'
382​
383const repoSandbox = defineSandbox({
384 id: 'repo-agent',
385 provider: dockerSandbox({ image: 'node:22' }),
386 workspace: defineWorkspace({
387 source: { type: 'none' },
388 packageManager: 'pnpm',
389 }),
390 lifecycle: { reuse: 'thread' },
391})
392​
393const coder = defineAgent({
394 name: 'coder',
395 description: 'Edits the repo in a sandbox',
396 run: (ctx) =>
397 chat({
398 adapter: grokBuildText('grok-build'),
399 messages: ctx.messages,
400 threadId: ctx.threadId,
401 runId: ctx.runId,
402 parentRunId: ctx.parentRunId,
403 subagentRunId: ctx.subagentRunId,
404 resume: ctx.resume,
405 middleware: [withSandbox(repoSandbox)],
406 }),
407})
408​
409const ownStream = chat({
410 adapter: grokBuildText('grok-build'),
411 messages,
412 threadId,
413 middleware: [withSandbox(repoSandbox)],
414 subagents: {
415 agents: [coder],
416 sandbox: 'own',
417 strategy: 'exclusive',
418 router: () => 'coder',
419 },
420})
421​
422const inheritStream = chat({
423 adapter: grokBuildText('grok-build'),
424 messages,
425 threadId,
426 middleware: [withSandbox(repoSandbox)],
427 subagents: {
428 agents: [coder],
429 sandbox: 'inherit',
430 strategy: 'exclusive',
431 router: () => 'coder',
432 },
433})
434```
435​
436- `ownStream` runs the child with `threadId` `parent-thread:coder`.
437- `inheritStream` runs the child with `threadId` `parent-thread`, so `reuse: 'thread'` shares the parent workspace.
438​
439See [Sandboxes](../sandbox/overview) for `withSandbox` and `lifecycle.reuse`.
440​
441## Client details
442​
443The nested `type: 'subagent'` part and `useChat().subagents[i]` are the same live object. When you call `stop()` on either one, this happens:
444​
445- The client sets that child to error.
446- The client aborts the current parent run.
447- The client ignores later events for that id, and for its nested children.
448​
449`part.subagent.messages` holds everything the child did:
450​
451- text and reasoning
452- tool calls and tool results
453- the approval state on the tool calls of the child
454- nested children, as their own `subagent` parts
455​
456`part.subagent.status` is `'running'`, `'finished'`, `'error'`, or `'suspended'`.
457​
458### Type the child parts
459​
460Pass the agents that you give to `chat()` to `useChat` too. The hook uses them for types only. It does not call `run`.
461​
462```tsx
463import { defineAgent } from '@tanstack/ai'
464import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
465​
466const researcher = defineAgent({
467 name: 'researcher',
468 description: 'Looks up facts',
469 run: async function* () {},
470})
471const writer = defineAgent({
472 name: 'writer',
473 description: 'Drafts posts',
474 run: async function* () {},
475})
476​
477function Desk() {
478 const chat = useChat({
479 connection: fetchServerSentEvents('/api/chat'),
480 threadId: 'support-chat',
481 subagents: [researcher, writer],
482 })
483 const part = chat.messages[0]?.parts[0]
484 if (part?.type === 'subagent' && part.subagent.name === 'researcher') {
485 return part.subagent.status
486 }
487 return null
489```
490​
491`part.subagent.name` is `'researcher' | 'writer'`. After you check the name, the `messages` of that child use the tools and the output schema of that agent.
492​
493When `run` imports server code, do not import the agent into the browser. Do these steps:
494​
4951. Declare the agent once in a shared file, with its `name`, `description`, and tool definitions from `toolDefinition`.
4962. On the server, pass `defineAgent({ ...researcher, run })` to `chat()`.
4973. On the client, pass the declaration.
498​
499### Draw cards with `createChatHook`
500​
501If you want the factory to draw the cards, use `createChatHook` from `@tanstack/ai-react/ui`:
502​
503- Pass the agents that you give to `chat()` as `options.subagents`. The client reads the `name`, `tools`, `interrupts`, and `outputSchema` of each agent for types. It does not call `run`.
504- Register `subagentsComponents` for each agent name. Those components receive `SubagentProps` and `Parts`.
505- 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.
506​
507> [!WARNING]
508> If a started child has a name with no `subagentsComponents` entry, rendering that card throws.
509​
510```tsx
511import { defineAgent } from '@tanstack/ai'
512import { fetchServerSentEvents } from '@tanstack/ai-react'
513import { createChatHook } from '@tanstack/ai-react/ui'
514import type { LayoutProps, SubagentProps } from '@tanstack/ai-react/ui'
515​
516const researcher = defineAgent({
517 name: 'researcher',
518 description: 'Looks up facts',
519 run: async function* () {},
520})
521const writer = defineAgent({
522 name: 'writer',
523 description: 'Drafts posts',
524 run: async function* () {},
525})
526​
527const chatOptions = {
528 connection: fetchServerSentEvents('/api/chat'),
529 subagents: [researcher, writer],
531​
532function SubagentCard({
533 subagent,
534 Parts,
535}: SubagentProps<typeof chatOptions, 'researcher' | 'writer'>) {
536 return (
537 <section>
538 <strong>{subagent.name}</strong>
539 <span>{subagent.status}</span>
540 {subagent.status === 'running' ? (
541 <button type="button" onClick={() => subagent.stop?.()}>
542 Stop
543 </button>
544 ) : null}
545 <Parts />
546 </section>
547 )
549​
550const { useAppChat, useChatContext } = createChatHook({
551 options: chatOptions,
552 components: {
553 layout: ({ Messages, Input }: LayoutProps<typeof chatOptions>) => (
554 <main>
555 <Messages />
556 <Input />
557 </main>
558 ),
559 message: ({ Parts }) => <article><Parts /></article>,
560 input: function Input() {
561 const chat = useChatContext()
562 return (
563 <form
564 onSubmit={(event) => {
565 event.preventDefault()
566 const field = event.currentTarget.elements.namedItem('message')
567 if (!(field instanceof HTMLInputElement)) return
568 void chat.sendMessage(field.value)
569 field.value = ''
570 }}
571 >
572 <input name="message" />
573 <button type="submit">Send</button>
574 </form>
575 )
576 },
577 },
578 partsComponents: {
579 text: ({ part }) => <p>{part.content}</p>,
580 fallback: () => null,
581 },
582 subagentsComponents: {
583 researcher: SubagentCard,
584 writer: SubagentCard,
585 },
586})
587​
588export function ChatScreen() {
589 const chat = useAppChat({ threadId: 'support-chat' })
590 return <chat.AppChat />
592```
593​
594By default, the child messages use the same parts components as the parent. To change that for one card, see [Style one child's parts](#style-one-childs-parts).
595​
596### Show the brief on a card
597​
598When 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:
599​
600```typescript title="agents.ts"
601import { z } from 'zod'
602​
603export const researcher = {
604 name: 'researcher',
605 description: 'Researches one focused question and returns sourced findings',
606 inputSchema: z.object({ task: z.string() }),
607} as const
608```
609​
610```tsx title="briefs.tsx"
611import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
612import { researcher } from './agents'
613​
614export function Briefs() {
615 const { messages } = useChat({
616 connection: fetchServerSentEvents('/api/chat'),
617 threadId: 'support-chat',
618 subagents: [researcher],
619 })
620 return messages.flatMap((message) =>
621 message.parts.map((part) =>
622 part.type === 'subagent' ? (
623 <p key={part.subagent.id}>{part.subagent.input?.task}</p>
624 ) : null,
625 ),
626 )
628```
629​
630- `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`.
631- It is `undefined` for an agent without `inputSchema`.
632- A router input stays on the server, so a child that a router started has no `part.subagent.input`.
633​
634### Style one child's parts
635​
636The reasoning and tool calls of the researcher use the root widgets by default. To make them look different on the researcher card only, pass widgets to the `Parts` of that card:
637​
638```tsx
639import { toolDefinition } from '@tanstack/ai'
640import { fetchServerSentEvents } from '@tanstack/ai-react'
641import { createChatHook, ThinkingPart } from '@tanstack/ai-react/ui'
642import type { SubagentPartsProps, SubagentProps } from '@tanstack/ai-react/ui'
643import { z } from 'zod'
644​
645const lookupWikipedia = toolDefinition({
646 name: 'lookupWikipedia',
647 description: 'Get the Wikipedia summary of one topic',
648 inputSchema: z.object({ title: z.string() }),
649 outputSchema: z.object({ extract: z.string() }),
650})
651​
652// Shared with the server, which passes defineAgent({ ...researcher, run }).
653const researcher = {
654 name: 'researcher',
655 description: 'Looks up facts',
656 tools: [lookupWikipedia],
657} as const
658​
659const chatOptions = {
660 connection: fetchServerSentEvents('/api/chat'),
661 subagents: [researcher],
663​
664type ResearcherWidgets = SubagentPartsProps<typeof chatOptions, 'researcher'>
665​
666const researcherParts: ResearcherWidgets['partsComponents'] = {
667 thinking: ({ part }) => (
668 <ThinkingPart content={part.content} className="research-notes" />
669 ),
671​
672const researcherTools: ResearcherWidgets['toolsComponents'] = {
673 lookupWikipedia: ({ part }) => (
674 <details>
675 <summary>
676 {part.input?.title} ({part.state})
677 </summary>
678 {part.output?.extract}
679 </details>
680 ),
682​
683function Researcher({
684 Parts,
685}: SubagentProps<typeof chatOptions, 'researcher'>) {
686 return (
687 <section>
688 <Parts partsComponents={researcherParts} toolsComponents={researcherTools} />
689 </section>
690 )
692​
693export const { useAppChat } = createChatHook({
694 options: chatOptions,
695 components: {
696 layout: ({ Messages }) => (
697 <main>
698 <Messages />
699 </main>
700 ),
701 message: ({ Parts }) => (
702 <article>
703 <Parts />
704 </article>
705 ),
706 },
707 partsComponents: {
708 text: ({ part }) => <p>{part.content}</p>,
709 thinking: ({ part }) => <ThinkingPart content={part.content} />,
710 fallback: () => null,
711 },
712 subagentsComponents: { researcher: Researcher },
713})
714```
715​
716- An entry on `Parts` replaces the root entry with the same key, for this card and for the children nested in it.
717- A key that you do not set uses the root entry. Here, `text` still uses the root widget.
718- The keys and props of `toolsComponents` come from the `tools` of the agent. `part.input` and `part.output` are typed, and a tool name that the agent does not have is a type error.
719- A tool call with no entry at any level renders nothing.
720- An approval for a child tool arrives as `interrupt` on that tool widget, typed from the tool. The root `interruptsComponents` also accepts the approval tools of the child and the ids in the `interrupts` of the agent.
721- An approval for a tool that only a card registers also shows in the root `<Interrupts />` list.
722​
723Define these maps outside the component. A new object on each render makes every part in the card render again.
724​
725## Devtools
726​
727In the AI devtools, the Conversation tab shows each child as a card with its name and status:
728​
729- The card holds the steps of the child, drawn the same way as the steps of the parent.
730- A new step starts after each tool result.
731- The User view on the right shows the text and tool outputs of the child.
732​
733When the server events reach the devtools (the `devtools()` plugin from `@tanstack/devtools-vite`), the steps of the child 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.
734​
735See [Stream Events](./stream-events) for `SUBAGENT_*` and `subagentRunId`.