Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat, toolDefinition } from '@tanstack/ai'
3import { createAnthropicChat } from '@tanstack/ai-anthropic'
4import { openaiCompatibleText } from '@tanstack/ai-openai/compatible'
5import { z } from 'zod'
6
7const LLMOCK_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010'
8
9const sse = (events: Array<unknown>) =>
10 new Response(
11 events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(''),
12 { headers: { 'content-type': 'text/event-stream' } },
13 )
14
15const call = {
16 type: 'function_call',
17 call_id: 'call_1',
18 name: 'get_weather',
19 arguments: '{"city":"Paris"}',
20 status: 'completed',
21}
22
23/**
24 * aimock cannot send these two Copilot stream shapes, so the adapter's
25 * `fetch` answers with them: thinking on `delta.reasoning_text`, and a
26 * stateless Responses tool call with a new item id on each event.
27 */
28const copilotStreams = {
29 'reasoning-text': () => [
30 {
31 id: 'c-1',
32 choices: [{ index: 0, delta: { reasoning_text: 'Say hi back.' } }],
33 },
34 { id: 'c-1', choices: [{ index: 0, delta: { content: 'Hi' } }] },
35 { id: 'c-1', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
36 ],
37 'rotating-ids': (turn: number) =>
38 turn === 0
39 ? [
40 {
41 type: 'response.output_item.added',
42 output_index: 0,
43 item: { ...call, id: 'fc_a', arguments: '', status: 'in_progress' },
44 },
45 {
46 type: 'response.function_call_arguments.delta',
47 output_index: 0,
48 item_id: 'fc_b',
49 delta: '{"city":',
50 },
51 {
52 type: 'response.function_call_arguments.delta',
53 output_index: 0,
54 item_id: 'fc_c',
55 delta: '"Paris"}',
56 },
57 {
58 type: 'response.function_call_arguments.done',
59 output_index: 0,
60 item_id: 'fc_d',
61 arguments: '{"city":"Paris"}',
62 },
63 {
64 type: 'response.output_item.done',
65 output_index: 0,
66 item: { ...call, id: 'fc_e' },
67 },
68 {
69 type: 'response.completed',
70 response: {
71 id: 'r-1',
72 model: 'gpt-5.6',
73 status: 'completed',
74 output: [{ ...call, id: 'fc_f' }],
75 },
76 },
77 ]
78 : [
79 {
80 type: 'response.output_text.delta',
81 output_index: 0,
82 content_index: 0,
83 item_id: 'msg_1',
84 delta: 'Sunny',
85 },
86 {
87 type: 'response.completed',
88 response: {
89 id: 'r-2',
90 model: 'gpt-5.6',
91 status: 'completed',
92 output: [],
93 },
94 },
95 ],
96 // A ChatGPT plan stream: the tool call streams, then `response.completed`
97 // has an empty `output`.
98 'empty-completed-output': (turn: number) =>
99 turn === 0
100 ? [
101 {
102 type: 'response.output_item.added',
103 output_index: 0,
104 item: { ...call, id: 'fc_1', arguments: '', status: 'in_progress' },
105 },
106 {
107 type: 'response.function_call_arguments.done',
108 output_index: 0,
109 item_id: 'fc_1',
110 arguments: '{"city":"Paris"}',
111 },
112 {
113 type: 'response.output_item.done',
114 output_index: 0,
115 item: { ...call, id: 'fc_1' },
116 },
117 {
118 type: 'response.completed',
119 response: {
120 id: 'r-1',
121 model: 'gpt-5.6',
122 status: 'completed',
123 output: [],
124 },
125 },
126 ]
127 : [
128 {
129 type: 'response.output_text.delta',
130 output_index: 0,
131 content_index: 0,
132 item_id: 'msg_1',
133 delta: 'Sunny',
134 },
135 {
136 type: 'response.completed',
137 response: {
138 id: 'r-2',
139 model: 'gpt-5.6',
140 status: 'completed',
141 output: [],
142 },
143 },
144 ],
145}
146
147const getWeather = toolDefinition({
148 name: 'get_weather',
149 description: 'Get the weather for a city',
150 inputSchema: z.object({ city: z.string() }),
151}).server(({ city }) => `Sunny in ${city}`)
152
153/**
154 * Calls aimock the way a GitHub Copilot setup does: fixed headers on the
155 * adapter, and an `x-initiator` header for each request through `wrapFetch`.
156 * The Responses call is stateless, with encrypted reasoning. A Claude model
157 * goes through the Anthropic adapter, with the Copilot token as a bearer token.
158 */
159export const Route = createFileRoute('/api/copilot-wire')({
160 server: {
161 handlers: {
162 POST: async ({ request }) => {
163 await import('@/lib/llmock-server').then((m) => m.ensureLLMock())
164 const body: unknown = await request.json()
165 const field = (key: string) =>
166 typeof body === 'object' &&
167 body !== null &&
168 key in body &&
169 typeof Reflect.get(body, key) === 'string'
170 ? String(Reflect.get(body, key))
171 : undefined
172 const testId = field('testId')
173 const api = field('api')
174 if (
175 api === 'reasoning-text' ||
176 api === 'rotating-ids' ||
177 api === 'empty-completed-output'
178 ) {
179 let turn = 0
180 const stream = chat({
181 threadId: 'copilot-wire',
182 adapter: openaiCompatibleText('gpt-5.6', {
183 name: 'github-copilot',
184 baseURL: 'https://api.githubcopilot.com',
185 apiKey: 'copilot-token',
186 fetch: async () => sse(copilotStreams[api](turn++)),
187 ...(api === 'reasoning-text'
188 ? {}
189 : { api: 'responses' as const }),
190 }),
191 messages: [{ role: 'user', content: 'Weather in Paris?' }],
192 tools: [getWeather],
193 })
194 let text = ''
195 let thinking = ''
196 const toolCalls: Array<{ id: string; input: unknown }> = []
197 let toolCallStarts = 0
198 for await (const chunk of stream) {
199 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
200 if (chunk.type === 'REASONING_MESSAGE_CONTENT')
201 thinking += chunk.delta
202 if (chunk.type === 'TOOL_CALL_START') toolCallStarts++
203 if (chunk.type === 'TOOL_CALL_END')
204 toolCalls.push({ id: chunk.toolCallId, input: chunk.input })
205 }
206 return Response.json({ text, thinking, toolCallStarts, toolCalls })
207 }
208 if (api === 'anthropic') {
209 // aimock redacts `authorization` and logs no URL query, so the
210 // route keeps the raw request.
211 let url = ''
212 let headers: Record<string, string> = {}
213 const { text } = await chat({
214 threadId: 'copilot-wire',
215 adapter: createAnthropicChat('claude-sonnet-5-5', 'copilot-token', {
216 baseURL: LLMOCK_BASE,
217 auth: 'bearer',
218 ...(testId ? { defaultHeaders: { 'X-Test-Id': testId } } : {}),
219 }),
220 messages: [
221 {
222 role: 'user',
223 content: '[oneshot] what is your most popular guitar',
224 },
225 ],
226 wrapFetch: (next) => (input, init) => {
227 const sent = new Headers(init?.headers)
228 sent.set('User-Agent', 'e2e/1.0.0')
229 sent.set('Openai-Intent', 'conversation-edits')
230 sent.set('X-GitHub-Api-Version', '2026-08-01')
231 sent.set('X-Interaction-Type', 'conversation-agent')
232 sent.set('X-Interaction-Id', 'session-1')
233 sent.set('x-initiator', 'user')
234 sent.set('anthropic-beta', 'interleaved-thinking-2025-05-14')
235 url = input instanceof Request ? input.url : String(input)
236 headers = Object.fromEntries(sent)
237 return next(input, { ...init, headers: sent })
238 },
239 stream: false,
240 })
241 return Response.json({ text, url, headers })
242 }
243 const responses = api === 'responses'
244 // aimock logs a converted body for /v1/responses, with no `store` or
245 // `include`. So the route keeps the body that the adapter sent.
246 let sent: unknown
247 const { text } = await chat({
248 threadId: 'copilot-wire',
249 adapter: openaiCompatibleText('gpt-5.6', {
250 name: 'github-copilot',
251 baseURL: `${LLMOCK_BASE}/v1`,
252 apiKey: 'copilot-token',
253 defaultHeaders: {
254 'Openai-Intent': 'conversation-edits',
255 'X-GitHub-Api-Version': '2026-08-01',
256 ...(testId ? { 'X-Test-Id': testId } : {}),
257 },
258 ...(responses ? { api: 'responses' as const } : {}),
259 }),
260 messages: [
261 {
262 role: 'user',
263 content: '[oneshot] what is your most popular guitar',
264 },
265 ],
266 ...(responses
267 ? {
268 modelOptions: {
269 store: false,
270 include: ['reasoning.encrypted_content'],
271 },
272 }
273 : {}),
274 wrapFetch: (next) => (input, init) => {
275 const headers = new Headers(init?.headers)
276 headers.set('x-initiator', 'user')
277 if (typeof init?.body === 'string') sent = JSON.parse(init.body)
278 return next(input, { ...init, headers })
279 },
280 stream: false,
281 })
282 return Response.json({ text, sent })
283 },
284 },
285 },
286})