Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 defineAgent,
6 keyedAdapter,
7 maxIterations,
8 toServerSentEventsResponse,
9} from '@tanstack/ai'
10import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
11import { z } from 'zod'
12import type {
13 ChatMiddleware,
14 DefinedAgent,
15 ReasoningRequest,
16 Tool,
17} from '@tanstack/ai'
18import { createOpenaiChat } from '@tanstack/ai-openai'
19import { openaiByok } from '@tanstack/ai-openai/byok'
20import { getByokKey } from '@tanstack/ai/byok/server'
21import type { ByokProvider } from '@tanstack/ai/byok'
22import { LLMOCK_DEFAULT_BASE, createTextAdapter } from '@/lib/providers'
23import {
24 deleteLogs,
25 isSubagentScenario,
26 lookupFacts,
27} from '@/lib/subagents-test'
28import type { SubagentScenario } from '@/lib/subagents-test'
29
30/**
31 * Subagent harness. Every child is a real `chat()` on the OpenAI adapter
32 * against aimock, so the child's reasoning, tool calls, and approval go
33 * through the same path as an app.
34 *
35 * - `route`: a router picks `researcher`. The child thinks, calls a server
36 * tool, then answers.
37 * - `approval`: a router picks `cleaner`. The child's tool needs approval,
38 * so the parent run ends with the child's interrupt. The resume continues
39 * the same child.
40 * - `tool`: no router. The parent model calls the `researcher` tool, the
41 * child answers, and the parent reads its result.
42 * - `brief`: no router. The parent model writes a `task` for `researcher`,
43 * and the child's only message is that task.
44 * - `limits`: like `brief`, with `limits: { maxCalls: 1 }`. The parent model
45 * calls `researcher` twice in one turn. The second call gets a tool error.
46 * - `keys`: like `result`, but the page sends an `x-byok-openai` header.
47 * `subagents.keys` reads it with `getByokKey`, and `writer` builds its
48 * adapter with `ctx.keys.adapter(...)`. The child request carries that
49 * key. aimock hides `Authorization` in its journal, so the request also
50 * sends it as `x-e2e-authorization`.
51 * - `result`: no router. `pricer` calls the bound `ctx.chat` with
52 * `stream: false`, so its `run` resolves to a string. The string streams as
53 * the child's text and goes back to the parent model as the result.
54 * - `session`: no router. The parent model starts `researcher`, then a
55 * second `researcher` call continues it by its `sessionId`.
56 * `withPersistence` stores the child, so that call loads its transcript.
57 * - `routed-brief`: a router picks `researcher` and gives it the `task` as
58 * `{ name, input }`. The child's only message is that task.
59 */
60/** Send `Authorization` again as `x-e2e-authorization`, which aimock keeps. */
61const echoAuthorization: typeof fetch = (input, init) => {
62 const headers = new Headers(init?.headers)
63 headers.set('x-e2e-authorization', headers.get('authorization') ?? '')
64 return fetch(input, { ...init, headers })
65}
66
67function subagentsFor(
68 request: Request,
69 scenario: SubagentScenario,
70 aimockPort: number | undefined,
71 testId: string | undefined,
72) {
73 const child = (
74 name: string,
75 tools: Array<Tool>,
76 model?: string,
77 reasoning?: ReasoningRequest,
78 ) =>
79 defineAgent({
80 name,
81 description: `${name} agent`,
82 run: (ctx) =>
83 chat({
84 ...createTextAdapter('openai', model, aimockPort, testId),
85 messages: ctx.messages,
86 threadId: ctx.threadId,
87 runId: ctx.runId,
88 parentRunId: ctx.parentRunId,
89 subagentRunId: ctx.subagentRunId,
90 resume: ctx.resume,
91 tools,
92 ...(reasoning ? { reasoning } : {}),
93 agentLoopStrategy: maxIterations(4),
94 }),
95 })
96
97 if (scenario === 'route') {
98 const researcher = child(
99 'researcher',
100 [lookupFacts.server(({ topic }) => ({ topic, facts: ['three hearts'] }))],
101 'o3',
102 { level: 'high', summary: true },
103 )
104 return { agents: [researcher], router: () => 'researcher' }
105 }
106 if (scenario === 'approval') {
107 const cleaner = child('cleaner', [
108 deleteLogs.server(({ folder }) => ({ deleted: folder })),
109 ])
110 return { agents: [cleaner], router: () => 'cleaner' }
111 }
112 if (
113 scenario === 'brief' ||
114 scenario === 'limits' ||
115 scenario === 'routed-brief'
116 ) {
117 const researcher = defineAgent({
118 name: 'researcher',
119 description: 'Researches one focused task',
120 inputSchema: z.object({ task: z.string() }),
121 run: (ctx) =>
122 chat({
123 ...createTextAdapter('openai', undefined, aimockPort, testId),
124 messages: [{ role: 'user', content: ctx.input.task }],
125 threadId: ctx.threadId,
126 runId: ctx.runId,
127 parentRunId: ctx.parentRunId,
128 subagentRunId: ctx.subagentRunId,
129 resume: ctx.resume,
130 }),
131 })
132 // Each branch returns its own bag, so give them one agent type.
133 const agents: Array<DefinedAgent> = [researcher]
134 if (scenario === 'limits') {
135 return { agents, limits: { maxCalls: 1 } }
136 }
137 if (scenario === 'brief') return { agents }
138 return {
139 agents,
140 router: () => ({
141 name: 'researcher',
142 input: { task: '[subagent-brief-task] List two squid facts.' },
143 }),
144 }
145 }
146 if (scenario === 'result') {
147 const pricer = defineAgent({
148 name: 'pricer',
149 description: 'Prices one vendor',
150 inputSchema: z.object({ task: z.string() }),
151 run: (ctx) =>
152 ctx.chat({
153 ...createTextAdapter('openai', undefined, aimockPort, testId),
154 messages: [{ role: 'user', content: ctx.input.task }],
155 stream: false,
156 }),
157 })
158 const agents: Array<DefinedAgent> = [pricer]
159 return { agents }
160 }
161 if (scenario === 'keys') {
162 const gpt = keyedAdapter(openaiByok, (key) =>
163 createOpenaiChat('gpt-4o', key, {
164 baseURL: `${LLMOCK_DEFAULT_BASE}/v1`,
165 fetch: echoAuthorization,
166 ...(testId ? { defaultHeaders: { 'X-Test-Id': testId } } : {}),
167 }),
168 )
169 const writer = defineAgent({
170 name: 'writer',
171 description: 'Writes a short draft',
172 inputSchema: z.object({ task: z.string() }),
173 run: async (ctx) =>
174 ctx.chat({
175 adapter: await ctx.keys.adapter(gpt),
176 messages: [{ role: 'user', content: ctx.input.task }],
177 stream: false,
178 }),
179 })
180 const agents: Array<DefinedAgent> = [writer]
181 return {
182 agents,
183 keys: (provider: ByokProvider | string) => getByokKey(request, provider),
184 }
185 }
186 return { agents: [child('researcher', [])] }
187}
188
189/**
190 * aimock replies are fixed, so the second `researcher` call in
191 * `fixtures/subagents/session.json` cannot hold the random id of the
192 * first child. It sends `sessionId: 'first-child'`. This middleware does what
193 * a real model does: it copies the `subagentRunId` of the first result.
194 */
195function fillSessionId(): ChatMiddleware {
196 let first: string | undefined
197 return {
198 name: 'fill-session-id',
199 onAfterToolCall(_ctx, { result }) {
200 if (
201 first === undefined &&
202 typeof result === 'object' &&
203 result !== null &&
204 'subagentRunId' in result &&
205 typeof result.subagentRunId === 'string'
206 ) {
207 first = result.subagentRunId
208 }
209 },
210 onBeforeToolCall(_ctx, { args }) {
211 if (
212 first === undefined ||
213 typeof args !== 'object' ||
214 args === null ||
215 !('sessionId' in args) ||
216 args.sessionId !== 'first-child'
217 ) {
218 return undefined
219 }
220 return { type: 'transformArgs', args: { ...args, sessionId: first } }
221 },
222 }
223}
224
225export const Route = createFileRoute('/api/subagents-test')({
226 server: {
227 handlers: {
228 POST: async ({ request }) => {
229 if (request.signal?.aborted) return new Response(null, { status: 499 })
230 let params
231 try {
232 params = await chatParamsFromRequestBody(await request.json())
233 } catch (error) {
234 return new Response(
235 error instanceof Error ? error.message : 'Bad request',
236 { status: 400 },
237 )
238 }
239
240 const fp = params.forwardedProps
241 const scenario = isSubagentScenario(fp.scenario) ? fp.scenario : 'route'
242 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
243 const aimockPort =
244 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
245 const abortController = new AbortController()
246
247 try {
248 const stream = chat({
249 ...createTextAdapter('openai', undefined, aimockPort, testId),
250 messages: params.messages,
251 threadId: params.threadId,
252 runId: params.runId,
253 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
254 ...(params.resume ? { resume: params.resume } : {}),
255 subagents: subagentsFor(request, scenario, aimockPort, testId),
256 // One run holds both calls, so a store per request is enough.
257 ...(scenario === 'session'
258 ? {
259 middleware: [
260 withPersistence(memoryPersistence()),
261 fillSessionId(),
262 ],
263 }
264 : {}),
265 agentLoopStrategy: maxIterations(4),
266 abortController,
267 })
268 return toServerSentEventsResponse(stream, { abortController })
269 } catch (error) {
270 if (
271 (error instanceof Error && error.name === 'AbortError') ||
272 abortController.signal.aborted
273 ) {
274 return new Response(null, { status: 499 })
275 }
276 const message =
277 error instanceof Error ? error.message : 'An error occurred'
278 return new Response(JSON.stringify({ error: message }), {
279 status: 500,
280 headers: { 'Content-Type': 'application/json' },
281 })
282 }
283 },
284 },
285 },
286})