Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, createChatOptions, maxIterations } from '@tanstack/ai'
3import { createOpenaiChat } from '@tanstack/ai-openai'
4import {
5 clearToolResults,
6 evictOldest,
7 withCompaction,
8} from '@tanstack/ai-compaction'
9import type { CompactionStrategy } from '@tanstack/ai-compaction'
10import type { ModelMessage } from '@tanstack/ai'
11import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
12
13const DUMMY_KEY = 'sk-e2e-test-dummy-key'
14
15function makeTextStream(callNumber: number): ReadableStream<Uint8Array> {
16 const encoder = new TextEncoder()
17 const responseId = `resp_compaction_${callNumber}`
18 const itemId = `msg_compaction_${callNumber}`
19 const events = [
20 {
21 type: 'response.created',
22 response: {
23 id: responseId,
24 object: 'response',
25 status: 'in_progress',
26 output: [],
27 },
28 },
29 {
30 type: 'response.output_text.delta',
31 response_id: responseId,
32 item_id: itemId,
33 output_index: 0,
34 content_index: 0,
35 delta: 'ok',
36 },
37 {
38 type: 'response.completed',
39 response: {
40 id: responseId,
41 object: 'response',
42 status: 'completed',
43 output: [
44 {
45 id: itemId,
46 type: 'message',
47 role: 'assistant',
48 status: 'completed',
49 content: [{ type: 'output_text', text: 'ok' }],
50 },
51 ],
52 usage: { input_tokens: 5, output_tokens: 2, total_tokens: 7 },
53 },
54 },
55 ]
56 return new ReadableStream<Uint8Array>({
57 start(controller) {
58 for (const event of events) {
59 controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
60 }
61 controller.enqueue(encoder.encode('data: [DONE]\n\n'))
62 controller.close()
63 },
64 })
65}
66
67const FILLER = 'x'.repeat(160)
68
69// evict: oldest message carries SECRET_ALPHA_ONE, newest carries KEEP_ME_LAST.
70const evictMessages: Array<ModelMessage> = [
71 { role: 'user', content: `SECRET_ALPHA_ONE ${FILLER}` },
72 { role: 'assistant', content: FILLER },
73 { role: 'user', content: FILLER },
74 { role: 'assistant', content: FILLER },
75 { role: 'user', content: `KEEP_ME_LAST ${FILLER}` },
76]
77
78// clear: two tool results. Oldest carries SECRET_TOOL_ALPHA (should be stubbed),
79// newest carries KEEP_TOOL_BETA (kept). All messages stay in place.
80const clearMessages: Array<ModelMessage> = [
81 { role: 'user', content: 'run the tools' },
82 {
83 role: 'assistant',
84 content: '',
85 toolCalls: [
86 { id: 'a', type: 'function', function: { name: 'f', arguments: '{}' } },
87 ],
88 },
89 { role: 'tool', content: `SECRET_TOOL_ALPHA ${FILLER}`, toolCallId: 'a' },
90 {
91 role: 'assistant',
92 content: '',
93 toolCalls: [
94 { id: 'b', type: 'function', function: { name: 'f', arguments: '{}' } },
95 ],
96 },
97 { role: 'tool', content: `KEEP_TOOL_BETA ${FILLER}`, toolCallId: 'b' },
98 { role: 'user', content: 'done?' },
99]
100
101/**
102 * Wire-format verification for `withCompaction`. A capturing `fetch` records the
103 * outgoing request body so the spec can assert what each strategy sent.
104 *
105 * `?strategy=clear` uses `clearToolResults` on a tool-heavy history; anything
106 * else uses `evictOldest` on a plain chat history.
107 */
108export const Route = createFileRoute('/api/compaction-wire')({
109 server: {
110 handlers: {
111 POST: async ({ request }) => {
112 const clear =
113 new URL(request.url).searchParams.get('strategy') === 'clear'
114
115 const requestBodies: Array<unknown> = []
116
117 const mockFetch: typeof fetch = async (input, init) => {
118 const req =
119 input instanceof Request ? input : new Request(input, init)
120 requestBodies.push(JSON.parse(await req.text()))
121 return new Response(makeTextStream(requestBodies.length), {
122 headers: { 'Content-Type': 'text/event-stream' },
123 })
124 }
125
126 const messages = clear ? clearMessages : evictMessages
127 const strategy: CompactionStrategy = clear
128 ? clearToolResults({ keepRecentToolResults: 1 })
129 : evictOldest({ keepRecentTokens: 45 })
130
131 const adapter = createOpenaiChat('gpt-5.2', DUMMY_KEY, {
132 fetch: mockFetch,
133 })
134 const persistence = memoryPersistence()
135 let compactionCount = 0
136
137 try {
138 for await (const _ of chat({
139 ...createChatOptions({ adapter }),
140 messages,
141 threadId: 'compaction-wire',
142 runId: 'compaction-wire-1',
143 middleware: [
144 withPersistence(persistence),
145 withCompaction({
146 maxTokens: 60,
147 strategy,
148 onCompact: () => compactionCount++,
149 }),
150 ],
151 agentLoopStrategy: maxIterations(1),
152 })) {
153 // Drain the stream.
154 }
155
156 for await (const _ of chat({
157 ...createChatOptions({ adapter }),
158 messages: [],
159 threadId: 'compaction-wire',
160 runId: 'compaction-wire-2',
161 middleware: [
162 withPersistence(persistence),
163 withCompaction({
164 maxTokens: 60,
165 strategy,
166 onCompact: () => compactionCount++,
167 }),
168 ],
169 agentLoopStrategy: maxIterations(1),
170 })) {
171 // Drain the restored run.
172 }
173 } catch (error) {
174 return Response.json({
175 ok: false,
176 error: error instanceof Error ? error.message : String(error),
177 })
178 }
179
180 const canonicalMessages =
181 await persistence.stores.messages.loadThread('compaction-wire')
182 return Response.json({
183 ok: true,
184 firstRequestBody: requestBodies[0],
185 secondRequestBody: requestBodies[1],
186 canonicalMessages,
187 compactionCount,
188 })
189 },
190 },
191 },
192})