Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import { z } from 'zod'
3
4/**
5 * Willowbrook Wildlife Sanctuary interrupt scenarios, ported from the
6 * ts-react-chat example into deterministic e2e coverage.
7 *
8 * Each tool isolates one interrupt behavior. The bare definitions are exported
9 * so the client (route) can build stubs/executors whose schemas — including
10 * `approvalSchema` — hash-match the server side; without a matching client
11 * registration the InterruptManager won't hydrate the pause as
12 * `kind: 'tool-approval'` and Approve/Deny silently no-op. The server binds
13 * `.server()` executors via {@link getServerToolsForScenario}.
14 *
15 * Every server executor echoes its (possibly edited) input into the output so
16 * a spec can prove the tool ran with the arguments the keeper approved — which
17 * is how the edited-args scenarios are observed.
18 */
19
20// --- Bare tool definitions -------------------------------------------------
21
22// Server, plain boolean approve / reject.
23export const admitRescue = toolDefinition({
24 name: 'admitRescue',
25 description: 'Admit a rescued animal into the sanctuary intake ward.',
26 inputSchema: z.object({ species: z.string(), name: z.string() }),
27 outputSchema: z.object({ intakeId: z.string(), status: z.string() }),
28 needsApproval: true,
29})
30
31// Server, one shared payload schema for the decision.
32export const scheduleVetCheck = toolDefinition({
33 name: 'scheduleVetCheck',
34 description: 'Schedule a veterinary check for an animal in care.',
35 inputSchema: z.object({
36 animal: z.string(),
37 urgency: z.enum(['routine', 'urgent']),
38 }),
39 outputSchema: z.object({ visitId: z.string() }),
40 needsApproval: true,
41 approvalSchema: z.object({ note: z.string().min(1) }),
42})
43
44// Server, separate approve / reject payload schemas.
45export const finalizeAdoption = toolDefinition({
46 name: 'finalizeAdoption',
47 description: 'Finalize the adoption of an animal to a new home.',
48 inputSchema: z.object({ animal: z.string(), adopter: z.string() }),
49 outputSchema: z.object({ certificateId: z.string() }),
50 needsApproval: true,
51 approvalSchema: {
52 approve: z.object({
53 adopterName: z.string().min(1),
54 homeCheckPassed: z.boolean(),
55 }),
56 reject: z.object({ reason: z.string().min(1) }),
57 },
58})
59
60// Server, approval with edited arguments (change the plan before it runs).
61export const assignEnclosure = toolDefinition({
62 name: 'assignEnclosure',
63 description: 'Assign an animal to an enclosure.',
64 inputSchema: z.object({
65 animal: z.string(),
66 enclosure: z.string(),
67 sizeSqm: z.number().positive(),
68 }),
69 outputSchema: z.object({
70 assignmentId: z.string(),
71 enclosure: z.string(),
72 sizeSqm: z.number(),
73 }),
74 needsApproval: true,
75})
76
77// Client, plain boolean approve / reject.
78export const printIntakeTag = toolDefinition({
79 name: 'printIntakeTag',
80 description: "Print an intake tag on this device's label printer.",
81 inputSchema: z.object({ animal: z.string() }),
82 outputSchema: z.object({ tag: z.string() }),
83 needsApproval: true,
84})
85
86// Client, one shared payload schema.
87export const logFieldSighting = toolDefinition({
88 name: 'logFieldSighting',
89 description: 'Log a field sighting captured from this device.',
90 inputSchema: z.object({ species: z.string(), location: z.string() }),
91 outputSchema: z.object({ sightingId: z.string() }),
92 needsApproval: true,
93 approvalSchema: z.object({ note: z.string().min(1) }),
94})
95
96// Client, separate approve / reject payload schemas.
97export const shareAdoptionStory = toolDefinition({
98 name: 'shareAdoptionStory',
99 description: 'Share an adoption story to a social channel from this device.',
100 inputSchema: z.object({ animal: z.string() }),
101 outputSchema: z.object({ url: z.string() }),
102 needsApproval: true,
103 approvalSchema: {
104 approve: z.object({ channel: z.enum(['instagram', 'newsletter']) }),
105 reject: z.object({ reason: z.string().min(1) }),
106 },
107})
108
109// Client, approval with edited arguments.
110export const printCertificate = toolDefinition({
111 name: 'printCertificate',
112 description: 'Print an adoption certificate on this device.',
113 inputSchema: z.object({
114 animal: z.string(),
115 adopter: z.string(),
116 date: z.string(),
117 }),
118 outputSchema: z.object({ certificate: z.string() }),
119 needsApproval: true,
120})
121
122/** The generic interrupt's response schema (a non-tool application pause). */
123export const feedingScheduleResponseSchema = {
124 $schema: 'https://json-schema.org/draft/2020-12/schema',
125 type: 'object',
126 properties: {
127 mealsPerDay: { type: 'integer', minimum: 1, maximum: 6 },
128 diet: { type: 'string', minLength: 2 },
129 },
130 required: ['mealsPerDay', 'diet'],
131 additionalProperties: false,
132} as const
133
134/** Names of the tools whose executors run on the server (need `.server()`). */
135export const SERVER_TOOL_NAMES = [
136 admitRescue.name,
137 scheduleVetCheck.name,
138 finalizeAdoption.name,
139 assignEnclosure.name,
140] as const
141
142// --- Server-bound tools (executors live on the server) ---------------------
143
144const admitRescueServer = admitRescue.server(async ({ name }) => ({
145 intakeId: `intake_${name.toLowerCase()}`,
146 status: 'admitted',
147}))
148const scheduleVetCheckServer = scheduleVetCheck.server(
149 async ({ animal, urgency }) => ({
150 visitId: `visit_${animal.toLowerCase()}_${urgency}`,
151 }),
152)
153const finalizeAdoptionServer = finalizeAdoption.server(async ({ animal }) => ({
154 certificateId: `cert_${animal.toLowerCase()}`,
155}))
156const assignEnclosureServer = assignEnclosure.server(
157 async ({ animal, enclosure, sizeSqm }, context) => {
158 // Server tool results aren't surfaced to the client as message parts, so
159 // echo the (possibly edited) args via a custom event the spec can observe.
160 // This is how server-side edited-args application is verified.
161 context?.emitCustomEvent('enclosure:assigned', { enclosure, sizeSqm })
162 return {
163 assignmentId: `${enclosure.toLowerCase()}_${animal.toLowerCase()}`,
164 enclosure,
165 sizeSqm,
166 }
167 },
168)
169
170// --- Scenario registry -----------------------------------------------------
171
172export type ScenarioGroup = 'server' | 'client' | 'generic' | 'batch'
173
174/**
175 * How a scenario's interrupt(s) are resolved. All interrupts within a single
176 * scenario share this shape (except `batch-mixed`, which resolves per tool
177 * name via `resolutionByTool`).
178 */
179export interface ResolutionConfig {
180 /** Payload sent with an approve decision (shared/branch approve schemas). */
181 approvePayload?: Record<string, unknown>
182 /** Payload sent with a deny decision (branch reject schema). */
183 denyPayload?: Record<string, unknown>
184 /** Edited arguments applied on approve. */
185 editedArgs?: Record<string, unknown>
186}
187
188export interface Scenario {
189 id: string
190 group: ScenarioGroup
191 label: string
192 /** Resolution for a single-interrupt scenario. */
193 resolution?: ResolutionConfig
194 /** For batch-mixed: resolution keyed by tool name. */
195 resolutionByTool?: Record<string, ResolutionConfig>
196}
197
198export const SCENARIO_LIST: ReadonlyArray<Scenario> = [
199 {
200 id: 'admit',
201 group: 'server',
202 label: 'Admit a rescue (server, boolean)',
203 resolution: {},
204 },
205 {
206 id: 'vet',
207 group: 'server',
208 label: 'Vet check (server, shared payload)',
209 resolution: {
210 approvePayload: { note: 'Check the injured paw' },
211 denyPayload: { note: 'No vet check needed right now' },
212 },
213 },
214 {
215 id: 'adopt',
216 group: 'server',
217 label: 'Finalize adoption (server, branch payload)',
218 resolution: {
219 approvePayload: { adopterName: 'Dana Rivers', homeCheckPassed: true },
220 denyPayload: { reason: 'Home check still pending' },
221 },
222 },
223 {
224 id: 'enclosure',
225 group: 'server',
226 label: 'Assign enclosure (server, edited args)',
227 resolution: {
228 editedArgs: { animal: 'Rusty', enclosure: 'Birch', sizeSqm: 24 },
229 },
230 },
231 {
232 id: 'tag',
233 group: 'client',
234 label: 'Print intake tag (client, boolean)',
235 resolution: {},
236 },
237 {
238 id: 'sighting',
239 group: 'client',
240 label: 'Log field sighting (client, shared payload)',
241 resolution: {
242 approvePayload: { note: 'Seen near the North Meadow' },
243 denyPayload: { note: 'Sighting not confirmed' },
244 },
245 },
246 {
247 id: 'story',
248 group: 'client',
249 label: 'Share adoption story (client, branch payload)',
250 resolution: {
251 approvePayload: { channel: 'newsletter' },
252 denyPayload: { reason: 'Adopter has not consented yet' },
253 },
254 },
255 {
256 id: 'certificate',
257 group: 'client',
258 label: 'Print certificate (client, edited args)',
259 resolution: {
260 editedArgs: {
261 animal: 'Luna',
262 adopter: 'Dana Rivers',
263 date: '2026-07-22',
264 },
265 },
266 },
267 {
268 id: 'feeding',
269 group: 'generic',
270 label: 'Set a feeding schedule (generic interrupt)',
271 resolution: { approvePayload: { mealsPerDay: 3, diet: 'insectivore' } },
272 },
273 {
274 id: 'batch',
275 group: 'batch',
276 label: 'Admit three rescues (batch, boolean)',
277 resolution: {},
278 },
279 {
280 id: 'batch-mixed',
281 group: 'batch',
282 label: 'Mixed batch (boolean + payload + client)',
283 resolutionByTool: {
284 admitRescue: {},
285 scheduleVetCheck: { approvePayload: { note: 'Priority intake' } },
286 printIntakeTag: {},
287 },
288 },
289]
290
291export function getScenario(id: string): Scenario | undefined {
292 return SCENARIO_LIST.find((s) => s.id === id)
293}
294
295/**
296 * Server-side tool set for a scenario: server tools carry their `.server()`
297 * executor, client tools are passed as bare definitions so the run pauses on
298 * them (`client-tool-execution`) and the browser runs them after approval.
299 */
300export function getServerToolsForScenario(scenario: string) {
301 switch (scenario) {
302 case 'admit':
303 case 'batch':
304 return [admitRescueServer]
305 case 'vet':
306 return [scheduleVetCheckServer]
307 case 'adopt':
308 return [finalizeAdoptionServer]
309 case 'enclosure':
310 return [assignEnclosureServer]
311 case 'tag':
312 return [printIntakeTag]
313 case 'sighting':
314 return [logFieldSighting]
315 case 'story':
316 return [shareAdoptionStory]
317 case 'certificate':
318 return [printCertificate]
319 case 'batch-mixed':
320 return [admitRescueServer, scheduleVetCheckServer, printIntakeTag]
321 case 'feeding':
322 default:
323 return []
324 }
325}