Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2
3/**
4 * A provider-free AG-UI producer that sends only the *_CHUNK shorthand
5 * (issue #1531). It writes the SSE bytes itself. A continuation chunk
6 * carries no id, as the spec allows.
7 *
8 * `?case=turn` streams reasoning, a tool call with its result, and text.
9 * `?case=error` is the issue repro: one text chunk with error metadata, then
10 * RUN_ERROR.
11 */
12function sse(events: Array<Record<string, unknown>>): Response {
13 const body = events.map((event) => `data: ${JSON.stringify(event)}\n\n`)
14 return new Response(body.join(''), {
15 headers: { 'Content-Type': 'text/event-stream' },
16 })
17}
18
19const threadId = 'foreign-chunk-events'
20const runId = 'run-1'
21
22const turn = [
23 { type: 'RUN_STARTED', threadId, runId },
24 {
25 type: 'REASONING_MESSAGE_CHUNK',
26 messageId: 'think-1',
27 delta: 'Look up ',
28 },
29 { type: 'REASONING_MESSAGE_CHUNK', delta: 'the weather.' },
30 {
31 type: 'TOOL_CALL_CHUNK',
32 toolCallId: 'call-weather',
33 toolCallName: 'get_weather',
34 parentMessageId: 'msg-chunked',
35 delta: '{"city":',
36 },
37 { type: 'TOOL_CALL_CHUNK', delta: '"Kyiv"}' },
38 {
39 type: 'TOOL_CALL_RESULT',
40 messageId: 'result-1',
41 toolCallId: 'call-weather',
42 content: '"sunny"',
43 },
44 { type: 'TEXT_MESSAGE_CHUNK', messageId: 'msg-chunked', delta: 'It is ' },
45 { type: 'TEXT_MESSAGE_CHUNK', delta: 'sunny in Kyiv.' },
46 { type: 'RUN_FINISHED', threadId, runId },
47]
48
49const error = [
50 { type: 'RUN_STARTED', threadId, runId },
51 {
52 type: 'TEXT_MESSAGE_CHUNK',
53 messageId: 'msg-error',
54 delta: 'the run failed',
55 metadata: { error: 'upstream timeout' },
56 },
57 { type: 'RUN_ERROR', message: 'upstream timeout' },
58]
59
60export const Route = createFileRoute('/api/foreign-chunk-events')({
61 server: {
62 handlers: {
63 POST: ({ request }) => {
64 const scenario = new URL(request.url).searchParams.get('case')
65 return sse(scenario === 'error' ? error : turn)
66 },
67 },
68 },
69})