Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { EventType, defineAgent } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4import {
5 createHarnessHost,
6 defineHarness,
7 harnessAgent,
8 logIdOf,
9} from '@tanstack/ai-harness'
10import { memoryPersistence } from '@tanstack/ai-persistence'
11import { z } from 'zod'
12import type { StreamChunk } from '@tanstack/ai'
13import type { HarnessSession } from '@tanstack/ai-harness'
14
15/**
16 * The agent tree of a harness session: agents that start agents.
17 *
18 * `POST` with `{ scenario }` starts a scenario and returns its id. `GET
19 * ?runId=` returns `{ done: false }` until the scenario ends, then `{ done:
20 * true, result }` with what the test checks. Each scenario opens its own host, and closes it at the end.
21 *
22 * - `group`: a lead agent runs the agents `a`, `b`, and `c` in a group with
23 * `concurrency: 2`. Each agent records when it starts and ends.
24 * - `budget`: a lead agent runs a worker with `budget: { maxTokens: 50 }`.
25 * The model call of the worker uses 80 tokens.
26 * - `state`: a lead agent runs two agents that add to the shared state
27 * `count`, then reads it.
28 * - `harness-agent`: the model of a lead harness calls a child harness
29 * (`harnessAgent`) as a tool.
30 *
31 * A custom `fetch` answers with canned Anthropic streams, so no aimock
32 * fixture is needed.
33 */
34
35const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
36const MODEL = 'claude-sonnet-5-5'
37
38type AnthropicEvent = { type: string } & Record<string, unknown>
39
40const sseOf = (events: Array<AnthropicEvent>) =>
41 events
42 .map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
43 .join('')
44
45/** The first event of an answer. The call uses `inputTokens` + 1 tokens. */
46const messageStart = (id: string, inputTokens: number): AnthropicEvent => ({
47 type: 'message_start',
48 message: {
49 id,
50 type: 'message',
51 role: 'assistant',
52 content: [],
53 model: MODEL,
54 stop_reason: null,
55 stop_sequence: null,
56 usage: { input_tokens: inputTokens, output_tokens: 0 },
57 },
58})
59
60const ending = (stopReason: string): Array<AnthropicEvent> => [
61 { type: 'content_block_stop', index: 0 },
62 {
63 type: 'message_delta',
64 delta: { stop_reason: stopReason, stop_sequence: null },
65 usage: { output_tokens: 1 },
66 },
67 { type: 'message_stop' },
68]
69
70/** An answer with the text `text`. */
71const reply =
72 (text: string, inputTokens = 5) =>
73 (id: string) =>
74 sseOf([
75 messageStart(id, inputTokens),
76 {
77 type: 'content_block_start',
78 index: 0,
79 content_block: { type: 'text', text: '' },
80 },
81 {
82 type: 'content_block_delta',
83 index: 0,
84 delta: { type: 'text_delta', text },
85 },
86 ...ending('end_turn'),
87 ])
88
89/** An answer that calls the tool `name` with `input`. */
90const callTool =
91 (name: string, input: Record<string, unknown>) => (id: string) =>
92 sseOf([
93 messageStart(id, 5),
94 {
95 type: 'content_block_start',
96 index: 0,
97 content_block: { type: 'tool_use', id: 'toolu_child', name, input: {} },
98 },
99 {
100 type: 'content_block_delta',
101 index: 0,
102 delta: {
103 type: 'input_json_delta',
104 partial_json: JSON.stringify(input),
105 },
106 },
107 ...ending('tool_use'),
108 ])
109
110/** A model that answers with `answers`, in order. */
111function scripted(answers: Array<(id: string) => string>) {
112 let calls = 0
113 const scriptedFetch: typeof fetch = async () => {
114 calls += 1
115 const answer = answers[calls - 1] ?? reply('No more answers.')
116 return new Response(answer(`msg_agent_tree_${calls}`), {
117 headers: { 'Content-Type': 'text/event-stream' },
118 })
119 }
120 return createAnthropicChat(MODEL, DUMMY_KEY, { fetch: scriptedFetch })
121}
122
123const sleep = (ms: number) =>
124 new Promise<void>((resolve) => setTimeout(resolve, ms))
125
126const errorOf = (error: unknown) =>
127 error instanceof Error ? error.message : String(error)
128
129/** The fields of an agent run that the test checks. */
130const runsOf = (session: HarnessSession) =>
131 session.agentRuns().map((run) => ({
132 runId: run.runId,
133 agent: run.agent,
134 status: run.status,
135 parentRunId: run.parentRunId ?? null,
136 error: run.error ?? null,
137 }))
138
139/** Open a harness with `agents` on a new host. */
140async function openWith(
141 name: string,
142 agents: Parameters<typeof defineHarness>[0]['agents'],
143) {
144 const host = createHarnessHost({ persistence: memoryPersistence() })
145 const harness = defineHarness({
146 name: `e2e/harness-agent-tree-${name}`,
147 adapter: scripted([]),
148 agents,
149 })
150 const session = await host.open(harness, {
151 threadId: `e2e-harness-agent-tree-${name}-${crypto.randomUUID()}`,
152 })
153 return { host, session }
154}
155
156async function group() {
157 const order: Array<string> = []
158 let active = 0
159 let maxActive = 0
160 // An agent that records when it starts and ends, and works for `ms`.
161 const worker = (name: string, ms: number) =>
162 defineAgent({
163 name,
164 description: `Works on a topic for ${ms} ms`,
165 inputSchema: z.object({ topic: z.string() }),
166 run: async (ctx) => {
167 order.push(`start ${name}`)
168 active += 1
169 maxActive = Math.max(maxActive, active)
170 await sleep(ms)
171 active -= 1
172 order.push(`end ${name}`)
173 return `${name}: ${ctx.input.topic}`
174 },
175 })
176 const a = worker('a', 400)
177 const b = worker('b', 100)
178 const c = worker('c', 100)
179 const lead = defineAgent({
180 name: 'lead',
181 description: 'Runs a, b, and c, two at a time',
182 run: (ctx) => {
183 if (!ctx.harness) throw new Error('This agent must run in a harness.')
184 return ctx.harness.agents.group({ concurrency: 2 }, (g) => [
185 g.start(a, { topic: 'auth' }),
186 g.start(b, { topic: 'billing' }),
187 g.start(c, { topic: 'search' }),
188 ])
189 },
190 })
191 const { host, session } = await openWith('group', [lead, a, b, c])
192 try {
193 const run = session.agents.lead.start(undefined)
194 const results = await run
195 return {
196 results,
197 leadRunId: run.id,
198 runs: runsOf(session),
199 order,
200 maxActive,
201 }
202 } finally {
203 await host.close()
204 }
205}
206
207async function budget() {
208 const worker = defineAgent({
209 name: 'worker',
210 description: 'Answers with one model call of 80 tokens',
211 // 79 input tokens and 1 output token.
212 run: (ctx) =>
213 ctx.chat({ adapter: scripted([reply('A long answer.', 79)]) }),
214 })
215 const lead = defineAgent({
216 name: 'lead',
217 description: 'Runs the worker with a budget, and returns the error code',
218 run: async (ctx) => {
219 if (!ctx.harness) throw new Error('This agent must run in a harness.')
220 return ctx.harness.agents
221 .run(worker, undefined, { budget: { maxTokens: 50 } })
222 .then(
223 () => 'finished',
224 (error: unknown) =>
225 typeof error === 'object' &&
226 error !== null &&
227 'code' in error &&
228 typeof error.code === 'string'
229 ? error.code
230 : errorOf(error),
231 )
232 },
233 })
234 const { host, session } = await openWith('budget', [lead, worker])
235 try {
236 const run = session.agents.lead.start(undefined)
237 const leadResult = await run
238 return { leadResult, leadRunId: run.id, runs: runsOf(session) }
239 } finally {
240 await host.close()
241 }
242}
243
244async function state() {
245 const counter = () => ({ key: 'count', initial: 0 })
246 const adder = defineAgent({
247 name: 'adder',
248 description: 'Adds `by` to the shared count',
249 inputSchema: z.object({ by: z.number() }),
250 run: (ctx) => {
251 if (!ctx.harness) throw new Error('This agent must run in a harness.')
252 return ctx.harness
253 .state(counter())
254 .update((count) => count + ctx.input.by)
255 },
256 })
257 const lead = defineAgent({
258 name: 'lead',
259 description: 'Runs two adders at the same time, then reads the count',
260 run: async (ctx) => {
261 if (!ctx.harness) throw new Error('This agent must run in a harness.')
262 await ctx.harness.agents.group({}, (g) => [
263 g.start(adder, { by: 1 }),
264 g.start(adder, { by: 10 }),
265 ])
266 return ctx.harness.state(counter()).get()
267 },
268 })
269 const { host, session } = await openWith('state', [lead, adder])
270 try {
271 const count = await session.agents.lead.start(undefined)
272 return { count, runs: runsOf(session) }
273 } finally {
274 await host.close()
275 }
276}
277
278/** `metadata.tanstack.parentRunId` of `chunk`, if it has one. */
279function parentRunIdOf(chunk: StreamChunk) {
280 const metadata: unknown = 'metadata' in chunk ? chunk.metadata : undefined
281 if (typeof metadata !== 'object' || metadata === null) return null
282 if (!('tanstack' in metadata)) return null
283 const { tanstack } = metadata
284 if (typeof tanstack !== 'object' || tanstack === null) return null
285 if (!('parentRunId' in tanstack)) return null
286 return typeof tanstack.parentRunId === 'string' ? tanstack.parentRunId : null
287}
288
289async function childHarness() {
290 const child = defineHarness({
291 name: 'e2e/harness-agent-tree-child',
292 description: 'Checks a change',
293 // 40 input tokens and 1 output token.
294 adapter: scripted([reply('Child answer.', 40)]),
295 })
296 const agent = harnessAgent(child)
297 const lead = defineHarness({
298 name: 'e2e/harness-agent-tree-lead',
299 // Two model calls of 6 tokens each.
300 adapter: scripted([
301 callTool(agent.name, { prompt: 'Check the change.' }),
302 reply('Done.'),
303 ]),
304 subagents: { agents: [agent] },
305 })
306 const persistence = memoryPersistence()
307 const host = createHarnessHost({ persistence })
308 const threadId = `e2e-harness-agent-tree-lead-${crypto.randomUUID()}`
309 try {
310 const session = await host.open(lead, { threadId })
311 const turn = session.send('[harness-agent-tree] check it')
312 const chunks: Array<StreamChunk> = []
313 for await (const chunk of turn.stream()) chunks.push(chunk)
314 const result = await turn
315 const childText = chunks.find(
316 (chunk) =>
317 chunk.type === EventType.TEXT_MESSAGE_CONTENT &&
318 chunk.delta.includes('Child answer.'),
319 )
320 // The thread of the child, from the log of the root thread.
321 const records = await persistence.stores.log.read({
322 logId: logIdOf({ logId: threadId }),
323 })
324 const childThread =
325 records
326 .map((entry) => entry.record.thread)
327 .find(
328 (thread): thread is string =>
329 typeof thread === 'string' &&
330 thread.startsWith(`${threadId}/agent/`),
331 ) ?? null
332 let openError: string | null = null
333 if (childThread) {
334 await host.open(child, { threadId: childThread }).then(
335 () => {
336 openError = 'host.open did not throw.'
337 },
338 (error: unknown) => {
339 openError = errorOf(error)
340 },
341 )
342 }
343 return {
344 text: result.text,
345 turnId: turn.id,
346 childTextParentRunId: childText ? parentRunIdOf(childText) : null,
347 totalTokens: session.usage().total.totalTokens,
348 threadId,
349 childThread,
350 openError,
351 }
352 } finally {
353 await host.close()
354 }
355}
356
357const scenarios = {
358 group,
359 budget,
360 state,
361 'harness-agent': childHarness,
362}
363
364type Scenario = keyof typeof scenarios
365
366interface Run {
367 done: boolean
368 result?: unknown
369 error?: string
370}
371
372// ponytail: the result of each scenario, kept in memory by run id.
373const runs = new Map<string, Run>()
374/** A result that nobody reads goes away after this time. */
375const RUN_TTL_MS = 60_000
376
377export const Route = createFileRoute('/api/harness-agent-tree')({
378 server: {
379 handlers: {
380 POST: async ({ request }) => {
381 const { scenario } = (await request.json()) as { scenario: Scenario }
382 if (!(scenario in scenarios)) {
383 return Response.json({ error: `No scenario ${scenario}.` })
384 }
385 const runId = crypto.randomUUID()
386 const run: Run = { done: false }
387 runs.set(runId, run)
388 setTimeout(() => runs.delete(runId), RUN_TTL_MS)
389 scenarios[scenario]().then(
390 (result) => {
391 run.result = result
392 run.done = true
393 },
394 (error: unknown) => {
395 run.error = errorOf(error)
396 run.done = true
397 },
398 )
399 return Response.json({ runId })
400 },
401 GET: ({ request }) => {
402 const runId = new URL(request.url).searchParams.get('runId') ?? ''
403 const run = runs.get(runId)
404 if (!run) return Response.json({ error: `No run ${runId}.` })
405 if (run.error !== undefined) return Response.json({ error: run.error })
406 return Response.json({ done: run.done, result: run.result ?? null })
407 },
408 },
409 },
410})