Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 canonicalInterruptJson,
5 chat,
6 chatParamsFromRequestBody,
7 digestInterruptJson,
8 maxIterations,
9 toServerSentEventsResponse,
10} from '@tanstack/ai'
11import { z } from 'zod'
12import type { ChatMiddleware } from '@tanstack/ai'
13import { createTextAdapter } from '@/lib/providers'
14import {
15 feedingScheduleResponseSchema,
16 getServerToolsForScenario,
17} from '@/lib/interrupt-scenario-tools'
18
19/** The generic feeding interrupt id is derived from the run it pauses. */
20export const feedingInterruptId = (runId: string): string => `feeding_${runId}`
21
22// Constant continuation prompts keep aimock's userMessage matching stable
23// (the payload is validated but not interpolated into the prompt text).
24const FEEDING_CONFIRM_PROMPT =
25 'The keeper set a feeding schedule. Confirm it briefly.'
26const FEEDING_CANCEL_PROMPT =
27 'The keeper cancelled the feeding schedule. Acknowledge briefly.'
28
29/**
30 * Emits the generic "feeding schedule" interrupt: a non-tool application
31 * pause. On the first turn the plain success terminal is replaced with an
32 * interrupt outcome carrying a wire responseSchema; on the continuation the
33 * keeper's answer is validated here (the library does not validate generic
34 * values) and a fixed confirmation prompt is appended.
35 */
36export function createFeedingMiddleware(): ChatMiddleware {
37 const responseSchemaHash = digestInterruptJson(
38 canonicalInterruptJson(feedingScheduleResponseSchema),
39 )
40 const validate = z.fromJSONSchema(
41 feedingScheduleResponseSchema as unknown as Parameters<
42 typeof z.fromJSONSchema
43 >[0],
44 )
45 let isContinuation = false
46
47 return {
48 name: 'feeding-schedule',
49 onConfig(ctx, config) {
50 if (ctx.phase !== 'init' || (config.resume?.length ?? 0) === 0) return
51 isContinuation = true
52 const interruptedRunId = ctx.parentRunId
53 if (!interruptedRunId) {
54 throw new Error('Feeding continuation requires parentRunId.')
55 }
56 const expectedId = feedingInterruptId(interruptedRunId)
57 const resolution = config.resume?.[0]
58 if (
59 config.resume?.length !== 1 ||
60 resolution?.interruptId !== expectedId
61 ) {
62 throw new Error(`Feeding continuation must resolve only ${expectedId}.`)
63 }
64
65 let prompt: string
66 if (resolution.status === 'cancelled') {
67 prompt = FEEDING_CANCEL_PROMPT
68 } else {
69 const parsed = validate.safeParse(resolution.payload)
70 if (!parsed.success) {
71 throw new Error(
72 `Invalid feeding schedule: ${parsed.error.issues
73 .map((issue) => issue.message)
74 .join('; ')}`,
75 )
76 }
77 prompt = FEEDING_CONFIRM_PROMPT
78 }
79
80 return {
81 messages: [...config.messages, { role: 'user', content: prompt }],
82 resume: undefined,
83 }
84 },
85 onChunk(ctx, chunk) {
86 if (
87 isContinuation ||
88 chunk.type !== EventType.RUN_FINISHED ||
89 (chunk.outcome !== undefined && chunk.outcome.type !== 'success')
90 ) {
91 return
92 }
93 // Correlate on the client's request run id (`ctx.runId`), which is what
94 // the client sends back as `parentRunId` on the continuation.
95 const interruptedRunId = ctx.runId
96 const interruptId = feedingInterruptId(interruptedRunId)
97 return {
98 ...chunk,
99 outcome: {
100 type: 'interrupt',
101 interrupts: [
102 {
103 id: interruptId,
104 reason: 'sanctuary:feeding_schedule',
105 message: 'Choose a feeding schedule for this animal.',
106 responseSchema: feedingScheduleResponseSchema,
107 metadata: {
108 kind: 'generic',
109 'tanstack:interruptBinding': {
110 kind: 'generic',
111 interruptId,
112 interruptedRunId,
113 generation: 0,
114 responseSchemaHash,
115 },
116 },
117 },
118 ],
119 },
120 }
121 },
122 }
123}
124
125export const Route = createFileRoute('/api/interrupts-test')({
126 server: {
127 handlers: {
128 POST: async ({ request }) => {
129 if (request.signal?.aborted) {
130 return new Response(null, { status: 499 })
131 }
132
133 let params
134 try {
135 params = await chatParamsFromRequestBody(await request.json())
136 } catch (error) {
137 return new Response(
138 error instanceof Error ? error.message : 'Bad request',
139 { status: 400 },
140 )
141 }
142
143 const fp = params.forwardedProps
144 const scenario = typeof fp.scenario === 'string' ? fp.scenario : 'admit'
145 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
146 const aimockPort =
147 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
148 const isGeneric = scenario === 'feeding'
149 const scenarioTools = getServerToolsForScenario(scenario)
150 // The admit cancellation reproduces a stale approval after its schema changed.
151 const tools =
152 scenario === 'admit' &&
153 params.resume?.some((entry) => entry.status === 'cancelled')
154 ? scenarioTools.map((tool) => ({
155 ...tool,
156 inputSchema: z.object({
157 species: z.string(),
158 name: z.string(),
159 source: z.string().optional(),
160 }),
161 }))
162 : scenarioTools
163
164 const abortController = new AbortController()
165
166 try {
167 const stream = chat({
168 ...createTextAdapter('openai', undefined, aimockPort, testId),
169 messages: params.messages,
170 tools,
171 agentLoopStrategy: maxIterations(8),
172 threadId: params.threadId,
173 runId: params.runId,
174 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
175 ...(params.resume ? { resume: params.resume } : {}),
176 ...(isGeneric ? { middleware: [createFeedingMiddleware()] } : {}),
177 abortController,
178 })
179
180 return toServerSentEventsResponse(stream, { abortController })
181 } catch (error) {
182 if (
183 (error instanceof Error && error.name === 'AbortError') ||
184 abortController.signal.aborted
185 ) {
186 return new Response(null, { status: 499 })
187 }
188 const message =
189 error instanceof Error ? error.message : 'An error occurred'
190 return new Response(JSON.stringify({ error: message }), {
191 status: 500,
192 headers: { 'Content-Type': 'application/json' },
193 })
194 }
195 },
196 },
197 },
198})