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

api.run.ts

345 lines11.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { createMiddleware } from '@tanstack/react-start'
3import { toServerSentEventsStream } from '@tanstack/ai'
4import { z } from 'zod'
5import {
6 isGrokModel,
7 isGrokProtocol,
8 isGrokTransport,
9 isHarness,
10} from '../sandbox-options'
11import type {
12 GrokBuildModel,
13 GrokBuildProtocol,
14 GrokTransport,
15 HarnessName,
16} from '../sandbox-options'
17import type { ModelMessage, StreamChunk } from '@tanstack/ai'
18import type { StartRunInput } from '@tanstack/ai-sandbox-cloudflare/agent'
19​
20/**
21 * Proxy route: bridge the browser's `useChat` SSE expectation to the sandbox
22 * agent's POST-then-WebSocket run protocol — same Worker, no self-subrequest.
23 *
24 * The run coordinator (the `RunCoordinator` Durable Object wired by `src/server.ts`)
25 * speaks:
26 *
27 * 1. `startRun({ threadId, messages, … })` → `{ runId }` (returns immediately;
28 * the DO drives the run in the background under its own `ctx.waitUntil`).
29 * 2. `fetch('/runs/:runId/stream?threadId=…')` over a **WebSocket** → a resumable
30 * tail of `{ seq, chunk }` events, each `chunk` a standard chat `StreamChunk`,
31 * terminated by a `{ type: 'status', record }` frame.
32 *
33 * `useChat` only speaks "POST a body, read back an SSE stream of StreamChunks", so
34 * this handler does the handshake + WS tail and re-emits the chunks as SSE.
35 *
36 * IMPORTANT — why we talk to the DO directly instead of `fetch('/runs')`:
37 * the agent's HTTP surface (`POST /runs`, `/runs/:id/stream`) lives in THIS SAME
38 * Worker. A Worker `fetch()` to its own hostname is a same-zone self-subrequest,
39 * which Cloudflare blocks in production (`error code 1042` → a 404) unless the
40 * `global_fetch_strictly_public` flag is set — even though it resolves fine in the
41 * local `workerd` dev runtime. So rather than loop back over HTTP, we address the
42 * coordinator DO over its binding (an in-process RPC + a DO `fetch`, the exact same
43 * hops the agent Worker would make) — no public round-trip, no 1042.
44 */
45​
46/** The layers `useChat` may nest forwarded props in, depending on the adapter. */
47function bodyLayers(value: object): Array<object> {
48 const layers: Array<object> = [value]
49 if (
50 'forwardedProps' in value &&
51 value.forwardedProps !== null &&
52 typeof value.forwardedProps === 'object'
53 ) {
54 layers.push(value.forwardedProps)
55 }
56 return layers
58​
59/** First non-empty string for `key` across any body layer (top layer wins). */
60function readForwarded(value: object, key: string): string | undefined {
61 for (const layer of bodyLayers(value)) {
62 const candidate: unknown = Reflect.get(layer, key)
63 if (typeof candidate === 'string' && candidate !== '') return candidate
64 }
65 return undefined
67​
68const FORWARDED_KEYS = [
69 'threadId',
70 'harness',
71 'sessionId',
72 'grokModel',
73 'grokProtocol',
74 'grokTransport',
75] as const
76​
77/** Flatten the body and its `forwardedProps` layer into one object to validate. */
78function flattenRunBody(value: unknown): unknown {
79 if (value === null || typeof value !== 'object') return value
80 const flat: Record<string, unknown> = {}
81 if ('messages' in value) flat.messages = value.messages
82 for (const key of FORWARDED_KEYS) {
83 const found = readForwarded(value, key)
84 if (found !== undefined) flat[key] = found
85 }
86 return flat
88​
89/**
90 * Validates the proxy body. Harness/grok fields reuse the same type guards as the
91 * picker UI (`sandbox-options.ts`). Harness is optional — absent values fall back
92 * to the deploy-time `HARNESS` var in `resolveHarness`.
93 */
94const runBodySchema = z.preprocess(
95 flattenRunBody,
96 z.object({
97 messages: z
98 .array(z.custom<ModelMessage>())
99 .min(1, 'body.messages must be a non-empty array'),
100 threadId: z.string().optional(),
101 harness: z.custom<HarnessName>(isHarness, 'Unknown harness').optional(),
102 sessionId: z.string().optional(),
103 grokModel: z
104 .custom<GrokBuildModel>(isGrokModel, 'Unknown grokModel')
105 .optional(),
106 grokProtocol: z
107 .custom<GrokBuildProtocol>(isGrokProtocol, 'Unknown grokProtocol')
108 .optional(),
109 grokTransport: z
110 .custom<GrokTransport>(isGrokTransport, 'Unknown grokTransport')
111 .optional(),
112 }),
114​
115function jsonError(status: number, error: string): Response {
116 return new Response(JSON.stringify({ error }), {
117 status,
118 headers: { 'content-type': 'application/json' },
119 })
121​
122/**
123 * Request middleware: parse + validate the body once and hand the typed result
124 * to the POST handler via context, short-circuiting with a 4xx on a bad request
125 * so the handler only ever sees a valid `runBody`.
126 */
127const runBodyMiddleware = createMiddleware().server(
128 async ({ next, request }) => {
129 if (request.signal.aborted) {
130 return new Response(null, { status: 499 })
131 }
132 let raw: unknown
133 try {
134 raw = await request.json()
135 } catch {
136 return jsonError(400, 'invalid JSON body')
137 }
138 const parsed = runBodySchema.safeParse(raw)
139 if (!parsed.success) {
140 return jsonError(400, parsed.error.issues[0]?.message ?? 'invalid body')
141 }
142 return next({ context: { runBody: parsed.data } })
143 },
145​
146/** The run coordinator DO for a thread, addressed over the `RUN_COORDINATOR` binding. */
147async function getCoordinator(threadId: string) {
148 // Dynamic import keeps the Workers-only `cloudflare:workers` virtual module out
149 // of the client bundle (this handler only ever runs on the server).
150 const { env } = await import('cloudflare:workers')
151 return env.RUN_COORDINATOR.get(env.RUN_COORDINATOR.idFromName(threadId))
153​
154type Coordinator = Awaited<ReturnType<typeof getCoordinator>>
155​
156/** Trigger a run on the coordinator; resolve once it has a `runId`. */
157async function triggerRun(
158 coordinator: Coordinator,
159 input: StartRunInput,
160): Promise<string> {
161 const { runId } = await coordinator.startRun(input)
162 return runId
164​
165/**
166 * Open the run's WebSocket tail (the coordinator's `fetch` returns a `101` with a
167 * `webSocket`) and yield each chat `StreamChunk` as it arrives. Resolves when the
168 * coordinator sends its terminal `status` frame (or the socket closes / the client
169 * disconnects).
170 */
171async function* tailRun(
172 coordinator: Coordinator,
173 runId: string,
174 threadId: string,
175 signal: AbortSignal,
176): AsyncGenerator<StreamChunk> {
177 // The host is irrelevant — the DO routes on the pathname; this is an in-process
178 // DO `fetch`, not a public request.
179 const streamUrl = `https://do/runs/${runId}/stream?threadId=${encodeURIComponent(threadId)}&lastSeq=-1`
180 const res = await coordinator.fetch(streamUrl, {
181 headers: { Upgrade: 'websocket' },
182 })
183 const socket = res.webSocket
184 if (!socket) {
185 throw new Error(
186 `agent stream did not upgrade to a WebSocket (status ${res.status})`,
187 )
188 }
189 socket.accept()
190​
191 const queue: Array<StreamChunk> = []
192 // Mutated from the socket/abort callbacks below. Held on an object (rather than
193 // bare `let`s) so the generator loop's checks aren't flagged as constant.
194 const state: { finished: boolean; failure: Error | null } = {
195 finished: false,
196 failure: null,
197 }
198 let wake: (() => void) | null = null
199 const signalReady = () => {
200 wake?.()
201 wake = null
202 }
203​
204 socket.addEventListener('message', (event: MessageEvent) => {
205 let parsed: unknown
206 try {
207 parsed = JSON.parse(typeof event.data === 'string' ? event.data : '')
208 } catch {
209 return
210 }
211 if (parsed === null || typeof parsed !== 'object') return
212 if ('type' in parsed && parsed.type === 'status') {
213 state.finished = true
214 } else if ('chunk' in parsed) {
215 queue.push(parsed.chunk as StreamChunk)
216 }
217 signalReady()
218 })
219 socket.addEventListener('close', () => {
220 state.finished = true
221 signalReady()
222 })
223 socket.addEventListener('error', () => {
224 state.failure = new Error('agent stream socket error')
225 state.finished = true
226 signalReady()
227 })
228 const onAbort = () => {
229 state.finished = true
230 try {
231 socket.close()
232 } catch {
233 // already closing
234 }
235 signalReady()
236 }
237 signal.addEventListener('abort', onAbort)
238​
239 try {
240 while (!state.finished || queue.length > 0) {
241 const next = queue.shift()
242 if (next !== undefined) {
243 yield next
244 continue
245 }
246 await new Promise<void>((resolve) => {
247 wake = resolve
248 })
249 }
250 if (state.failure) throw state.failure
251 } finally {
252 signal.removeEventListener('abort', onAbort)
253 try {
254 socket.close()
255 } catch {
256 // already closed
257 }
258 }
260​
261export const Route = createFileRoute('/api/run')({
262 server: {
263 handlers: ({ createHandlers }) =>
264 createHandlers({
265 POST: {
266 middleware: [runBodyMiddleware],
267 handler: async ({ request, context }) => {
268 const {
269 messages,
270 threadId: threadIdInput,
271 harness,
272 sessionId,
273 grokModel,
274 grokProtocol,
275 grokTransport,
276 } = context.runBody
277​
278 const threadId = threadIdInput ?? crypto.randomUUID()
279​
280 const abortController = new AbortController()
281 request.signal.addEventListener('abort', () =>
282 abortController.abort(),
283 )
284​
285 try {
286 const coordinator = await getCoordinator(threadId)
287 const runId = await triggerRun(coordinator, {
288 runId: crypto.randomUUID(),
289 threadId,
290 messages,
291 // The host this user request arrived on — the coordinators derive the
292 // container's bridge + preview hosts from it when PUBLIC_HOSTNAME /
293 // PREVIEW_HOSTNAME are unset (local dev → host.docker.internal +
294 // localhost). Safe to trust on Cloudflare (the edge only routes hosts
295 // you own to this Worker). See resolveBridgeOrigin / resolvePreviewHost.
296 publicHost: new URL(request.url).host,
297 // The UI's chosen coding agent. `resolveHarness` in src/agent.ts reads
298 // it; absent → the HARNESS deploy default. Omitted entirely when unset.
299 metadata:
300 harness ||
301 sessionId ||
302 grokModel ||
303 grokProtocol ||
304 grokTransport
305 ? {
306 ...(harness ? { harness } : {}),
307 ...(sessionId ? { sessionId } : {}),
308 ...(grokModel ? { grokModel } : {}),
309 ...(grokProtocol ? { grokProtocol } : {}),
310 ...(grokTransport ? { grokTransport } : {}),
311 }
312 : undefined,
313 })
314 const chunks = tailRun(
315 coordinator,
316 runId,
317 threadId,
318 abortController.signal,
319 )
320 const sseStream = toServerSentEventsStream(
321 chunks,
322 abortController,
323 )
324 return new Response(sseStream, {
325 headers: {
326 'Content-Type': 'text/event-stream',
327 'Cache-Control': 'no-cache',
328 Connection: 'keep-alive',
329 },
330 })
331 } catch (error) {
332 if (abortController.signal.aborted) {
333 return new Response(null, { status: 499 })
334 }
335 console.error('[api/run] proxy error:', error)
336 return jsonError(
337 502,
338 error instanceof Error ? error.message : 'proxy error',
339 )
340 }
341 },
342 },
343 }),
344 },
345})