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

api.run.ts

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