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