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

api.run.ts

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