Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { createAnthropicChat } from '@tanstack/ai-anthropic'
3import {
4 createHarnessHost,
5 createHarnessWorker,
6 defineHarness,
7} from '@tanstack/ai-harness'
8import { memoryLogState, memoryLogStore } from '@tanstack/ai-persistence'
9import type { HarnessHost } from '@tanstack/ai-harness'
10
11/**
12 * A background agent that one server stores and a worker on another server
13 * runs. Two hosts on one log backend are two servers on one database. Host A
14 * runs nothing. The worker runs on host B. Host A reads the thread.
15 *
16 * `POST` starts a run and returns its id. The `submit` scenario stores an
17 * input with `host.submit` on host A. The `schedule` scenario opens the
18 * thread on a third host, schedules an input for a short time later, and
19 * closes that host. Then a worker starts on host B.
20 *
21 * `GET ?runId=` reads the thread from host A. When the answer is there, it
22 * stops the worker and closes the hosts.
23 *
24 * A custom `fetch` answers with canned Anthropic streams, so no aimock
25 * fixture is needed.
26 */
27
28const DUMMY_KEY = 'sk-ant-e2e-test-dummy-key'
29const MODEL = 'claude-sonnet-5-5'
30const NAME = 'e2e/harness-worker'
31
32const reply = (id: string, text: string) =>
33 [
34 {
35 type: 'message_start',
36 message: {
37 id,
38 type: 'message',
39 role: 'assistant',
40 content: [],
41 model: MODEL,
42 stop_reason: null,
43 stop_sequence: null,
44 usage: { input_tokens: 5, output_tokens: 0 },
45 },
46 },
47 {
48 type: 'content_block_start',
49 index: 0,
50 content_block: { type: 'text', text: '' },
51 },
52 {
53 type: 'content_block_delta',
54 index: 0,
55 delta: { type: 'text_delta', text },
56 },
57 { type: 'content_block_stop', index: 0 },
58 {
59 type: 'message_delta',
60 delta: { stop_reason: 'end_turn', stop_sequence: null },
61 usage: { output_tokens: 1 },
62 },
63 { type: 'message_stop' },
64 ]
65 .map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)
66 .join('')
67
68/** A harness whose model always answers `text`. `calls` counts its requests. */
69function harnessWith(text: string) {
70 const counter = { calls: 0 }
71 const scriptedFetch: typeof fetch = async () => {
72 counter.calls += 1
73 return new Response(reply(`msg_worker_${counter.calls}`, text), {
74 headers: { 'Content-Type': 'text/event-stream' },
75 })
76 }
77 const harness = defineHarness({
78 name: NAME,
79 adapter: createAnthropicChat(MODEL, DUMMY_KEY, { fetch: scriptedFetch }),
80 })
81 return { harness, counter }
82}
83
84/** The text of each message of the transcript. */
85const textsOf = (messages: Array<{ role: string; content: unknown }>) =>
86 messages.map((message) => ({
87 role: message.role,
88 text: typeof message.content === 'string' ? message.content : '',
89 }))
90
91interface Run {
92 threadId: string
93 hostA: HarnessHost
94 a: ReturnType<typeof harnessWith>
95 b: ReturnType<typeof harnessWith>
96 stop: () => Promise<void>
97}
98
99// ponytail: the runs that did not end yet, kept in memory by run id.
100const runs = new Map<string, Run>()
101/** A run that nobody reads ends after this time. */
102const RUN_TTL_MS = 60_000
103
104export const Route = createFileRoute('/api/harness-worker')({
105 server: {
106 handlers: {
107 POST: async ({ request }) => {
108 const { scenario } = (await request.json()) as {
109 scenario: 'submit' | 'schedule'
110 }
111 const runId = crypto.randomUUID()
112 const threadId = `e2e-harness-worker-${scenario}-${runId}`
113 const logState = memoryLogState()
114 const hostOn = () =>
115 createHarnessHost({
116 persistence: {
117 stores: { log: memoryLogStore({ state: logState }) },
118 },
119 })
120 // Host A must not run the thread, so its model has another answer.
121 const a = harnessWith('Not on host A.')
122 const b = harnessWith('Done by the worker.')
123 const hostA = hostOn()
124 const hostB = hostOn()
125 try {
126 let receipt: { status: string } | undefined
127 if (scenario === 'submit') {
128 receipt = await hostA.submit({
129 harness: a.harness,
130 threadId,
131 input: { op: 'prompt', message: '[harness-worker] submitted' },
132 })
133 } else {
134 // The planner opens the thread, schedules the input, and stops.
135 const planner = hostOn()
136 const p = harnessWith('Not on the planner.')
137 const session = await planner.open(p.harness, { threadId })
138 await session.schedule({
139 at: Date.now() + 300,
140 input: { op: 'prompt', message: '[harness-worker] scheduled' },
141 })
142 await session.close()
143 await planner.close()
144 }
145 const worker = createHarnessWorker({
146 host: hostB,
147 harnesses: [b.harness],
148 pollMs: 50,
149 })
150 const stop = async () => {
151 if (!runs.delete(runId)) return
152 await worker.stop()
153 await hostB.close()
154 await hostA.close()
155 }
156 runs.set(runId, { threadId, hostA, a, b, stop })
157 setTimeout(() => void stop(), RUN_TTL_MS)
158 return Response.json({ runId, receipt })
159 } catch (error) {
160 await hostA.close()
161 await hostB.close()
162 return Response.json({
163 error: error instanceof Error ? error.message : String(error),
164 })
165 }
166 },
167 GET: async ({ request }) => {
168 const runId = new URL(request.url).searchParams.get('runId') ?? ''
169 const run = runs.get(runId)
170 if (!run) return Response.json({ error: `No run ${runId}.` })
171 try {
172 const view = await run.hostA.observe(run.a.harness, {
173 threadId: run.threadId,
174 })
175 const transcript = textsOf(await view.transcript())
176 const answered = transcript.some(
177 (message) => message.role === 'assistant',
178 )
179 const result = {
180 answered,
181 transcript,
182 hostACalls: run.a.counter.calls,
183 workerCalls: run.b.counter.calls,
184 }
185 if (answered) await run.stop()
186 return Response.json(result)
187 } catch (error) {
188 return Response.json({
189 error: error instanceof Error ? error.message : String(error),
190 })
191 }
192 },
193 },
194 },
195})