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 summarizeOldest,
8 withCompaction,
9} from '@tanstack/ai-compaction'
10import type {
11 CompactionInfo,
12 CompactionStrategy,
13} from '@tanstack/ai-compaction'
14import type { ModelMessage } from '@tanstack/ai'
15import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
16
17const DUMMY_KEY = 'sk-e2e-test-dummy-key'
18
19function makeTextStream(callNumber: number): ReadableStream<Uint8Array> {
20 const encoder = new TextEncoder()
21 const responseId = `resp_compaction_${callNumber}`
22 const itemId = `msg_compaction_${callNumber}`
23 const events = [
24 {
25 type: 'response.created',
26 response: {
27 id: responseId,
28 object: 'response',
29 status: 'in_progress',
30 output: [],
31 },
32 },
33 {
34 type: 'response.output_text.delta',
35 response_id: responseId,
36 item_id: itemId,
37 output_index: 0,
38 content_index: 0,
39 delta: 'ok',
40 },
41 {
42 type: 'response.completed',
43 response: {
44 id: responseId,
45 object: 'response',
46 status: 'completed',
47 output: [
48 {
49 id: itemId,
50 type: 'message',
51 role: 'assistant',
52 status: 'completed',
53 content: [{ type: 'output_text', text: 'ok' }],
54 },
55 ],
56 usage: { input_tokens: 5, output_tokens: 2, total_tokens: 7 },
57 },
58 },
59 ]
60 return new ReadableStream<Uint8Array>({
61 start(controller) {
62 for (const event of events) {
63 controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`))
64 }
65 controller.enqueue(encoder.encode('data: [DONE]\n\n'))
66 controller.close()
67 },
68 })
69}
70
71const FILLER = 'x'.repeat(160)
72
73// evict: oldest message carries SECRET_ALPHA_ONE, newest carries KEEP_ME_LAST.
74const evictMessages: Array<ModelMessage> = [
75 { role: 'user', content: `SECRET_ALPHA_ONE ${FILLER}` },
76 { role: 'assistant', content: FILLER },
77 { role: 'user', content: FILLER },
78 { role: 'assistant', content: FILLER },
79 { role: 'user', content: `KEEP_ME_LAST ${FILLER}` },
80]
81
82// clear: two tool results. Oldest carries SECRET_TOOL_ALPHA (should be stubbed),
83// newest carries KEEP_TOOL_BETA (kept). All messages stay in place.
84const clearMessages: Array<ModelMessage> = [
85 { role: 'user', content: 'run the tools' },
86 {
87 role: 'assistant',
88 content: '',
89 toolCalls: [
90 { id: 'a', type: 'function', function: { name: 'f', arguments: '{}' } },
91 ],
92 },
93 { role: 'tool', content: `SECRET_TOOL_ALPHA ${FILLER}`, toolCallId: 'a' },
94 {
95 role: 'assistant',
96 content: '',
97 toolCalls: [
98 { id: 'b', type: 'function', function: { name: 'f', arguments: '{}' } },
99 ],
100 },
101 { role: 'tool', content: `KEEP_TOOL_BETA ${FILLER}`, toolCallId: 'b' },
102 { role: 'user', content: 'done?' },
103]
104
105// native: what `/responses/compact` returns. aimock has no route for it, so
106// the capturing fetch serves it.
107const compactedResponse = {
108 id: 'resp_compact_e2e',
109 created_at: 1,
110 object: 'response.compaction',
111 output: [
112 {
113 type: 'message',
114 id: 'msg_kept_e2e',
115 role: 'user',
116 status: 'completed',
117 content: [{ type: 'input_text', text: 'KEEP_ME_LAST' }],
118 },
119 { type: 'compaction', id: 'cmp_e2e', encrypted_content: 'SEALED_E2E' },
120 ],
121 usage: { input_tokens: 50, output_tokens: 5, total_tokens: 55 },
122}
123
124/**
125 * Wire-format verification for `withCompaction`. A capturing `fetch` records the
126 * outgoing request body so the spec can assert what each strategy sent.
127 *
128 * `?strategy=clear` uses `clearToolResults` on a tool-heavy history.
129 * `?strategy=empty-summary` uses `summarizeOldest` with a summarizer that
130 * returns an empty summary, so the compaction fails before any model call.
131 * `?strategy=native` turns on the adapter's own compaction.
132 * `?strategy=native-empty` does too, but the compact result has no compaction
133 * item, so `evictOldest` runs in its place.
134 * Anything else uses `evictOldest` on a plain chat history.
135 */
136export const Route = createFileRoute('/api/compaction-wire')({
137 server: {
138 handlers: {
139 POST: async ({ request }) => {
140 const strategyParam = new URL(request.url).searchParams.get('strategy')
141 const clear = strategyParam === 'clear'
142
143 const requestBodies: Array<unknown> = []
144 const compactRequestBodies: Array<unknown> = []
145
146 const mockFetch: typeof fetch = async (input, init) => {
147 const req =
148 input instanceof Request ? input : new Request(input, init)
149 if (req.url.endsWith('/responses/compact')) {
150 compactRequestBodies.push(JSON.parse(await req.text()))
151 return Response.json(
152 strategyParam === 'native-empty'
153 ? {
154 ...compactedResponse,
155 output: compactedResponse.output.filter(
156 (item) => item.type !== 'compaction',
157 ),
158 }
159 : compactedResponse,
160 )
161 }
162 requestBodies.push(JSON.parse(await req.text()))
163 return new Response(makeTextStream(requestBodies.length), {
164 headers: { 'Content-Type': 'text/event-stream' },
165 })
166 }
167
168 const messages = clear ? clearMessages : evictMessages
169 const strategy: CompactionStrategy = clear
170 ? clearToolResults({ keepRecentToolResults: 1 })
171 : strategyParam === 'empty-summary'
172 ? summarizeOldest({
173 summarize: async () => '',
174 keepRecentTokens: 45,
175 })
176 : evictOldest({ keepRecentTokens: 45 })
177
178 const adapter = createOpenaiChat('gpt-5.2', DUMMY_KEY, {
179 fetch: mockFetch,
180 })
181 const persistence = memoryPersistence()
182 let compactionCount = 0
183 const compactionErrors: Array<string> = []
184 const onCompact = (info: CompactionInfo) => {
185 compactionCount++
186 if (info.error) compactionErrors.push(info.error.message)
187 }
188 const native = strategyParam?.startsWith('native') ? adapter : undefined
189
190 try {
191 for await (const _ of chat({
192 ...createChatOptions({ adapter }),
193 messages,
194 threadId: 'compaction-wire',
195 runId: 'compaction-wire-1',
196 middleware: [
197 withPersistence(persistence),
198 withCompaction({
199 maxTokens: 60,
200 strategy,
201 native,
202 onCompact,
203 }),
204 ],
205 agentLoopStrategy: maxIterations(1),
206 })) {
207 // Drain the stream.
208 }
209
210 for await (const _ of chat({
211 ...createChatOptions({ adapter }),
212 messages: [],
213 threadId: 'compaction-wire',
214 runId: 'compaction-wire-2',
215 middleware: [
216 withPersistence(persistence),
217 withCompaction({
218 maxTokens: 60,
219 strategy,
220 native,
221 onCompact,
222 }),
223 ],
224 agentLoopStrategy: maxIterations(1),
225 })) {
226 // Drain the restored run.
227 }
228 } catch (error) {
229 return Response.json({
230 ok: false,
231 error: error instanceof Error ? error.message : String(error),
232 requestCount: requestBodies.length,
233 })
234 }
235
236 const canonicalMessages =
237 await persistence.stores.messages.loadThread('compaction-wire')
238 return Response.json({
239 ok: true,
240 firstRequestBody: requestBodies[0],
241 secondRequestBody: requestBodies[1],
242 compactRequestBodies,
243 canonicalMessages,
244 compactionCount,
245 compactionErrors,
246 })
247 },
248 },
249 },
250})