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

api.message-ids.ts

172 lines4.6 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 convertMessagesToModelMessages,
4 EventType,
5 modelMessagesToUIMessages,
6 StreamProcessor,
7 uiMessagesToWire,
8} from '@tanstack/ai'
9import { z } from 'zod'
10import type { UIMessage } from '@tanstack/ai'
11​
12const structuredOutputFields = {
13 type: z.literal('structured-output'),
14 partial: z.unknown().optional(),
15 raw: z.string(),
16 reasoning: z.string().optional(),
17 errorMessage: z.string().optional(),
19​
20const sourceSchema = z.discriminatedUnion('type', [
21 z.object({
22 type: z.literal('data'),
23 value: z.string(),
24 mimeType: z.string(),
25 }),
26 z.object({
27 type: z.literal('url'),
28 value: z.string(),
29 mimeType: z.string().optional(),
30 }),
31])
32​
33const contentPartSchema = z.discriminatedUnion('type', [
34 z.object({
35 type: z.literal('text'),
36 content: z.string(),
37 metadata: z.record(z.string(), z.unknown()).optional(),
38 }),
39 ...(['image', 'audio', 'video', 'document'] as const).map((type) =>
40 z.object({
41 type: z.literal(type),
42 source: sourceSchema,
43 metadata: z.record(z.string(), z.unknown()).optional(),
44 }),
45 ),
46])
47​
48const messagePartSchema = z.discriminatedUnion('type', [
49 ...contentPartSchema.options,
50 z.object({
51 type: z.literal('tool-call'),
52 id: z.string(),
53 name: z.string(),
54 arguments: z.string(),
55 input: z.unknown().optional(),
56 state: z.enum([
57 'awaiting-input',
58 'input-streaming',
59 'input-complete',
60 'approval-requested',
61 'approval-responded',
62 'complete',
63 'error',
64 ]),
65 approval: z
66 .object({
67 id: z.string(),
68 needsApproval: z.boolean(),
69 approved: z.boolean().optional(),
70 })
71 .optional(),
72 output: z.unknown().optional(),
73 metadata: z.record(z.string(), z.unknown()).optional(),
74 }),
75 z.object({
76 type: z.literal('tool-result'),
77 id: z.string().optional(),
78 name: z.string().optional(),
79 toolCallId: z.string(),
80 content: z.union([z.string(), z.array(contentPartSchema)]),
81 state: z.enum(['streaming', 'complete', 'error']),
82 error: z.string().optional(),
83 metadata: z.record(z.string(), z.unknown()).optional(),
84 createdAt: z.coerce.date().optional(),
85 }),
86 z.object({
87 type: z.literal('thinking'),
88 content: z.string(),
89 stepId: z.string().optional(),
90 signature: z.string().optional(),
91 }),
92 // A complete part must carry `data`. The other statuses have none.
93 z.discriminatedUnion('status', [
94 z.object({
95 ...structuredOutputFields,
96 status: z.enum(['streaming', 'error']),
97 data: z.undefined().optional(),
98 }),
99 z.object({
100 ...structuredOutputFields,
101 status: z.literal('complete'),
102 data: z.json(),
103 }),
104 ]),
105 z.object({
106 type: z.literal('ui-resource'),
107 resource: z.object({
108 uri: z.string(),
109 mimeType: z.string(),
110 text: z.string().optional(),
111 blob: z.string().optional(),
112 }),
113 serverId: z.string().optional(),
114 toolCallId: z.string(),
115 toolName: z.string(),
116 meta: z.record(z.string(), z.unknown()).optional(),
117 }),
118])
119​
120const requestBodySchema: z.ZodType<{ messages: Array<UIMessage> }> = z.object({
121 messages: z.array(
122 z.object({
123 id: z.string(),
124 role: z.enum(['system', 'user', 'assistant']),
125 parts: z.array(messagePartSchema),
126 createdAt: z.coerce.date().optional(),
127 }),
128 ),
129})
130​
131/**
132 * Provider-free harness for the UIMessage -> ModelMessage identity contract.
133 * The route keeps this regression at the public server boundary without
134 * starting a provider request or requiring an API key.
135 */
136export const Route = createFileRoute('/api/message-ids')({
137 server: {
138 handlers: {
139 POST: async ({ request }) => {
140 let body: unknown
141 try {
142 body = await request.json()
143 } catch {
144 return new Response('Invalid JSON request body', { status: 400 })
145 }
146​
147 const parsed = requestBodySchema.safeParse(body)
148 if (!parsed.success) {
149 return new Response('Invalid message data', { status: 400 })
150 }
151​
152 const modelMessages = convertMessagesToModelMessages(
153 parsed.data.messages,
154 )
155 const wireMessages = uiMessagesToWire(parsed.data.messages)
156 const processor = new StreamProcessor()
157 processor.processChunk({
158 type: EventType.MESSAGES_SNAPSHOT,
159 messages: wireMessages,
160 })
161 const snapshots = processor.getMessages()
162 const mergedSnapshots = modelMessagesToUIMessages(modelMessages)
163 return Response.json({
164 modelMessages,
165 wireMessages,
166 snapshots,
167 mergedSnapshots,
168 })
169 },
170 },
171 },
172})