Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 chat,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import type { ModelMessage, AdapterYieldChunk } from '@tanstack/ai'
9
10import {
11 clientServerTool,
12 clientServerToolWithApproval,
13 clientToolDef,
14 clientToolWithApprovalDef,
15 serverTool,
16 serverToolWithApproval,
17} from '@/lib/simulator-tools'
18
19/**
20 * Tool call syntax: toolName({ arg: value, arg2: value2 })
21 * Multiple calls can be separated by newlines or semicolons
22 *
23 * Examples:
24 * serverTool({ text: "hello" })
25 * clientTool({ delay: 2 })
26 * serverToolWithApproval({ text: "needs approval", delay: 1 })
27 */
28const TOOL_CALL_REGEX = /(\w+)\s*\(\s*(\{[^}]*\})\s*\)/g
29
30interface ParsedToolCall {
31 name: string
32 arguments: Record<string, any>
33}
34
35function parseToolCalls(message: string): Array<ParsedToolCall> {
36 TOOL_CALL_REGEX.lastIndex = 0
37 const toolCalls: Array<ParsedToolCall> = []
38 let match
39
40 while ((match = TOOL_CALL_REGEX.exec(message)) !== null) {
41 const name = match[1]
42 const argsString = match[2]
43
44 try {
45 // Parse the JSON-like arguments
46 // Handle simple cases like { text: "hello" } by converting to proper JSON
47 const jsonArgs = argsString.replace(/(\w+)\s*:/g, '"$1":')
48 const args = JSON.parse(jsonArgs)
49 toolCalls.push({ name, arguments: args })
50 } catch {
51 // If parsing fails, try to parse as-is
52 try {
53 const args = JSON.parse(argsString)
54 toolCalls.push({ name, arguments: args })
55 } catch {
56 console.error(`Failed to parse tool call arguments: ${argsString}`)
57 }
58 }
59 }
60
61 return toolCalls
62}
63
64// Valid tool names
65const VALID_TOOLS = new Set([
66 'serverTool',
67 'serverToolWithApproval',
68 'clientTool',
69 'clientToolWithApproval',
70 'clientServerTool',
71 'clientServerToolWithApproval',
72])
73
74const MODEL = 'simulator-v1'
75
76/**
77 * Simulated LLM adapter that:
78 * - Echoes messages back if no tool calls detected
79 * - Parses tool call syntax and generates appropriate chunks
80 *
81 * Emits the standard AG-UI lifecycle events (`RUN_STARTED`,
82 * `TEXT_MESSAGE_*` / `TOOL_CALL_*`, `RUN_FINISHED`) that the chat engine and
83 * StreamProcessor consume. The return is cast to `any` at the call site, so
84 * this only needs to be a structurally valid streaming text source.
85 */
86function createSimulatorAdapter() {
87 // Stream a text message (start -> content deltas -> end) under one run.
88 async function* streamText(
89 text: string,
90 delayMs: number,
91 ): AsyncIterable<AdapterYieldChunk> {
92 const timestamp = Date.now()
93 const messageId = `sim-msg-${timestamp}`
94
95 yield {
96 type: EventType.TEXT_MESSAGE_START,
97 messageId,
98 model: MODEL,
99 timestamp,
100 role: 'assistant',
101 }
102
103 let accumulated = ''
104 for (const char of text) {
105 accumulated += char
106 yield {
107 type: EventType.TEXT_MESSAGE_CONTENT,
108 messageId,
109 model: MODEL,
110 timestamp,
111 delta: char,
112 content: accumulated,
113 }
114 // Small delay for streaming effect
115 await new Promise((resolve) => setTimeout(resolve, delayMs))
116 }
117
118 yield {
119 type: EventType.TEXT_MESSAGE_END,
120 messageId,
121 model: MODEL,
122 timestamp: Date.now(),
123 }
124 }
125
126 return {
127 name: 'simulator',
128 model: MODEL,
129
130 async *chatStream(options: {
131 messages: Array<ModelMessage>
132 }): AsyncIterable<AdapterYieldChunk> {
133 const messages = options.messages
134 const lastMessage = messages[messages.length - 1]
135
136 const runId = `sim-run-${Date.now()}`
137 const threadId = `sim-thread-${Date.now()}`
138
139 yield {
140 type: EventType.RUN_STARTED,
141 runId,
142 threadId,
143 model: MODEL,
144 timestamp: Date.now(),
145 }
146
147 // Check if this is a tool result - if so, acknowledge it
148 if (lastMessage?.role === 'tool') {
149 const content =
150 'Tool execution completed. The result has been processed.'
151
152 yield* streamText(content, 10)
153
154 yield {
155 type: EventType.RUN_FINISHED,
156 runId,
157 threadId,
158 model: MODEL,
159 timestamp: Date.now(),
160 finishReason: 'stop',
161 usage: {
162 promptTokens: 10,
163 completionTokens: content.length,
164 totalTokens: 10 + content.length,
165 },
166 }
167 return
168 }
169
170 // Get the user's message content
171 const userContent =
172 typeof lastMessage?.content === 'string'
173 ? lastMessage.content
174 : Array.isArray(lastMessage?.content)
175 ? lastMessage.content
176 .filter((p: any) => p.type === 'text')
177 .map((p: any) => p.content)
178 .join(' ')
179 : ''
180
181 // Parse for tool calls
182 const toolCalls = parseToolCalls(userContent)
183 const validToolCalls = toolCalls.filter((tc) => VALID_TOOLS.has(tc.name))
184
185 if (validToolCalls.length === 0) {
186 // No tool calls - echo the message back
187 const echoContent = `[Echo] ${userContent}`
188
189 yield* streamText(echoContent, 15)
190
191 yield {
192 type: EventType.RUN_FINISHED,
193 runId,
194 threadId,
195 model: MODEL,
196 timestamp: Date.now(),
197 finishReason: 'stop',
198 usage: {
199 promptTokens: 10,
200 completionTokens: echoContent.length,
201 totalTokens: 10 + echoContent.length,
202 },
203 }
204 } else {
205 // Generate tool calls
206 const timestamp = Date.now()
207 for (let i = 0; i < validToolCalls.length; i++) {
208 const tc = validToolCalls[i]
209 const toolCallId = `call-${timestamp}-${i}`
210 const argsJson = JSON.stringify(tc.arguments)
211
212 yield {
213 type: EventType.TOOL_CALL_START,
214 toolCallId,
215 toolCallName: tc.name,
216 toolName: tc.name,
217 model: MODEL,
218 timestamp,
219 index: i,
220 }
221
222 // Stream tool call arguments character by character
223 let argsAccumulated = ''
224 for (const char of argsJson) {
225 argsAccumulated += char
226 yield {
227 type: EventType.TOOL_CALL_ARGS,
228 toolCallId,
229 model: MODEL,
230 timestamp,
231 delta: char,
232 args: argsAccumulated,
233 }
234 // Small delay for streaming effect
235 await new Promise((resolve) => setTimeout(resolve, 5))
236 }
237
238 yield {
239 type: EventType.TOOL_CALL_END,
240 toolCallId,
241 toolCallName: tc.name,
242 toolName: tc.name,
243 model: MODEL,
244 timestamp: Date.now(),
245 }
246 }
247
248 yield {
249 type: EventType.RUN_FINISHED,
250 runId,
251 threadId,
252 model: MODEL,
253 timestamp: Date.now(),
254 finishReason: 'tool_calls',
255 usage: { promptTokens: 10, completionTokens: 50, totalTokens: 60 },
256 }
257 }
258 },
259 }
260}
261
262export const Route = createFileRoute('/api/simulator-chat')({
263 server: {
264 handlers: {
265 POST: async ({ request }) => {
266 if (request.signal.aborted) {
267 return new Response(null, { status: 499 })
268 }
269
270 const abortController = new AbortController()
271 const body = await request.json()
272 const messages = body.messages
273
274 try {
275 const adapter = createSimulatorAdapter()
276
277 const stream = chat({
278 adapter: adapter as any,
279 tools: [
280 // Server tools with implementations
281 serverTool,
282 serverToolWithApproval,
283 clientServerTool,
284 clientServerToolWithApproval,
285 // Client-only tools (no server execute)
286 clientToolDef,
287 clientToolWithApprovalDef,
288 ],
289 systemPrompts: [],
290 agentLoopStrategy: maxIterations(10),
291 messages,
292 abortController,
293 })
294
295 return toServerSentEventsResponse(stream, { abortController })
296 } catch (error: any) {
297 console.error('[Simulator API] Error:', error)
298 if (error.name === 'AbortError' || abortController.signal.aborted) {
299 return new Response(null, { status: 499 })
300 }
301 return new Response(
302 JSON.stringify({ error: error.message || 'An error occurred' }),
303 {
304 status: 500,
305 headers: { 'Content-Type': 'application/json' },
306 },
307 )
308 }
309 },
310 },
311 },
312})