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

api.run.ts

234 lines8.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { createMiddleware } from '@tanstack/react-start'
3import { z } from 'zod'
4import {
5 memoryStream,
6 resolveResumeRunId,
7 resumeServerSentEventsResponse,
8 toServerSentEventsResponse,
9} from '@tanstack/ai'
10import {
11 buildRunStream,
12 driving,
13 ensureReaper,
14 runs,
15 takeoverDriver,
16} from '../run-durable'
17import { missingEnv } from '../sandbox-agent'
18import type { ModelMessage } from '@tanstack/ai'
19​
20/**
21 * The run route, DURABLE (the journal-only tier — see
22 * docs/sandbox/durable-runs):
23 *
24 * - `POST` starts a run. `withSandbox` gets `runs` + `durability`, so a
25 * dropped connection DETACHES the run (agent keeps working, sandbox stays
26 * up) instead of destroying it. Stop is an explicit cancel via
27 * `/api/run/cancel`.
28 * - `GET` is the resume/attach handler `joinRun` calls after a reload: it
29 * replays the delivery log from the requested offset AND (via
30 * `sandboxRunDriver`) takes the detached run over — claims it, re-tails the
31 * journal, aligns against what was already delivered, and streams the rest.
32 *
33 * Unlike the Cloudflare example (which proxies to a Durable Object), the agent
34 * loop runs right here, and every store is in-process memory: zero infra, at
35 * the documented cost that log durability equals this process's lifetime.
36 */
37​
38/** The layers `useChat` may nest forwarded props in, depending on the adapter. */
39function bodyLayers(value: object): Array<object> {
40 const layers: Array<object> = [value]
41 if (
42 'data' in value &&
43 value.data !== null &&
44 typeof value.data === 'object'
45 ) {
46 layers.push(value.data)
47 }
48 if (
49 'forwardedProps' in value &&
50 value.forwardedProps !== null &&
51 typeof value.forwardedProps === 'object'
52 ) {
53 layers.push(value.forwardedProps)
54 }
55 return layers
57​
58/** First non-empty string for `key` across any body layer (top layer wins). */
59function readForwarded(value: object, key: string): string | undefined {
60 for (const layer of bodyLayers(value)) {
61 const candidate: unknown = Reflect.get(layer, key)
62 if (typeof candidate === 'string' && candidate !== '') return candidate
63 }
64 return undefined
66​
67/** Flatten the nested `data`/`forwardedProps` layers into one object to validate. */
68function flattenRunBody(value: unknown): unknown {
69 if (value === null || typeof value !== 'object') return value
70 const flat: Record<string, unknown> = {}
71 if ('messages' in value) flat.messages = value.messages
72 for (const key of ['threadId', 'sessionId'] as const) {
73 const found = readForwarded(value, key)
74 if (found !== undefined) flat[key] = found
75 }
76 return flat
78​
79const runBodySchema = z.preprocess(
80 flattenRunBody,
81 z.object({
82 messages: z
83 .array(z.custom<ModelMessage>())
84 .min(1, 'body.messages must be a non-empty array'),
85 threadId: z.string().optional(),
86 sessionId: z.string().optional(),
87 }),
89​
90function jsonError(status: number, error: string): Response {
91 return new Response(JSON.stringify({ error }), {
92 status,
93 headers: { 'content-type': 'application/json' },
94 })
96​
97/**
98 * Request middleware: parse + validate the body once and hand the typed result
99 * to the POST handler via context, short-circuiting with a 4xx on a bad request
100 * so the handler only ever sees a valid `runBody`.
101 */
102const runBodyMiddleware = createMiddleware().server(
103 async ({ next, request }) => {
104 if (request.signal.aborted) {
105 return new Response(null, { status: 499 })
106 }
107 let raw: unknown
108 try {
109 raw = await request.json()
110 } catch {
111 return jsonError(400, 'invalid JSON body')
112 }
113 const parsed = runBodySchema.safeParse(raw)
114 if (!parsed.success) {
115 return jsonError(400, parsed.error.issues[0]?.message ?? 'invalid body')
116 }
117 return next({ context: { runBody: parsed.data } })
118 },
120​
121export const Route = createFileRoute('/api/run')({
122 server: {
123 handlers: ({ createHandlers }) =>
124 createHandlers({
125 POST: {
126 middleware: [runBodyMiddleware],
127 handler: async ({ request, context }) => {
128 ensureReaper()
129 const {
130 messages,
131 threadId: threadIdInput,
132 sessionId,
133 } = context.runBody
134​
135 const missing = missingEnv()
136 if (missing.length > 0) {
137 return jsonError(
138 500,
139 `Missing required env: ${missing.join(', ')}. Set it and restart the dev server.`,
140 )
141 }
142​
143 const threadId = threadIdInput ?? crypto.randomUUID()
144 // Forwarded from the client (`X-Run-Id`), not generated, whenever
145 // possible: the journal path, the deterministic message ids, and
146 // the delivery-log stream are all keyed by it, and the client can
147 // only rejoin a run whose id it knows.
148 const runId = resolveResumeRunId(request) ?? crypto.randomUUID()
149​
150 const abortController = new AbortController()
151 // A dropped request ABORTS the stream — with `runs` + `durability`
152 // wired below, `withSandbox` treats that abort as a DETACH (keeps
153 // the sandbox and the agent), not a cancel. Explicit cancel is
154 // /api/run/cancel, which aborts with `RUN_CANCEL_REASON`.
155 request.signal.addEventListener('abort', () =>
156 abortController.abort(),
157 )
158​
159 try {
160 driving.set(runId, abortController)
161​
162 // Create the run record at ACCEPT time, for the same reason the
163 // durable producer appends its run-accepted marker: the record
164 // otherwise appears only when the stream starts — AFTER sandbox
165 // boot — and a takeover GET that lands in that window finds no
166 // record, declines to drive (by design), and nobody ever
167 // retries. `withPersistence`'s own createOrResume later is
168 // idempotent against this one.
169 await runs.createOrResume({
170 runId,
171 threadId,
172 startedAt: Date.now(),
173 })
174​
175 // ONE durability adapter instance for the middleware and the
176 // response, so the journal path and the delivery log describe
177 // the same run. `Last-Event-ID` makes a mid-stream SSE reconnect
178 // to this route resume instead of restarting.
179 const adapter = memoryStream({
180 runId,
181 offset: request.headers.get('Last-Event-ID'),
182 })
183​
184 const stream = buildRunStream({
185 threadId,
186 messages,
187 runId,
188 abortController,
189 attach: false,
190 durability: adapter,
191 ...(sessionId !== undefined ? { sessionId } : {}),
192 })
193​
194 return toServerSentEventsResponse(stream, {
195 abortController,
196 durability: { adapter },
197 })
198 } catch (error) {
199 driving.delete(runId)
200 if (abortController.signal.aborted) {
201 return new Response(null, { status: 499 })
202 }
203 console.error('[api/run] error:', error)
204 return jsonError(
205 502,
206 error instanceof Error ? error.message : 'run error',
207 )
208 }
209 },
210 },
211 // The resume/attach handler `joinRun` GETs (`?offset=-1&runId=…`) after
212 // a reload, and an SSE reconnect falls back to. The response replays
213 // the delivery log either way; `driver` additionally claims a detached
214 // run and keeps driving it (serving the log untouched when the run is
215 // unknown, terminal, or claimed by another request).
216 GET: {
217 handler: ({ request }) => {
218 ensureReaper()
219 return resumeServerSentEventsResponse({
220 // The raised deadline covers the sliver between a run being
221 // accepted and its `run.accepted` marker landing in the log — a
222 // join in that sliver parks briefly instead of failing as "run
223 // gone" (the default 100ms is tuned for plain chat, where an
224 // empty log really does mean the run is gone).
225 adapter: memoryStream(request, { firstChunkDeadlineMs: 10_000 }),
226 // `sandboxRunDriver` with a retrying claim — see run-durable.ts
227 // for why one attempt is not enough on a refresh-during-boot.
228 driver: takeoverDriver(request),
229 })
230 },
231 },
232 }),
233 },
234})