Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.copilot-wire.ts

283 lines9.4 KB

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',
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 ],
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 adapter: openaiCompatibleText('gpt-5.6', {
182 name: 'github-copilot',
183 baseURL: 'https://api.githubcopilot.com',
184 apiKey: 'copilot-token',
185 fetch: async () => sse(copilotStreams[api](turn++)),
186 ...(api === 'reasoning-text'
187 ? {}
188 : { api: 'responses' as const }),
189 }),
190 messages: [{ role: 'user', content: 'Weather in Paris?' }],
191 tools: [getWeather],
192 })
193 let text = ''
194 let thinking = ''
195 const toolCalls: Array<{ id: string; input: unknown }> = []
196 let toolCallStarts = 0
197 for await (const chunk of stream) {
198 if (chunk.type === 'TEXT_MESSAGE_CONTENT') text += chunk.delta
199 if (chunk.type === 'REASONING_MESSAGE_CONTENT')
200 thinking += chunk.delta
201 if (chunk.type === 'TOOL_CALL_START') toolCallStarts++
202 if (chunk.type === 'TOOL_CALL_END')
203 toolCalls.push({ id: chunk.toolCallId, input: chunk.input })
204 }
205 return Response.json({ text, thinking, toolCallStarts, toolCalls })
206 }
207 if (api === 'anthropic') {
208 // aimock redacts `authorization` and logs no URL query, so the
209 // route keeps the raw request.
210 let url = ''
211 let headers: Record<string, string> = {}
212 const { text } = await chat({
213 adapter: createAnthropicChat('claude-sonnet-5-5', 'copilot-token', {
214 baseURL: LLMOCK_BASE,
215 auth: 'bearer',
216 ...(testId ? { defaultHeaders: { 'X-Test-Id': testId } } : {}),
217 }),
218 messages: [
219 {
220 role: 'user',
221 content: '[oneshot] what is your most popular guitar',
222 },
223 ],
224 wrapFetch: (next) => (input, init) => {
225 const sent = new Headers(init?.headers)
226 sent.set('User-Agent', 'e2e/1.0.0')
227 sent.set('Openai-Intent', 'conversation-edits')
228 sent.set('X-GitHub-Api-Version', '2026-08-01')
229 sent.set('X-Interaction-Type', 'conversation-agent')
230 sent.set('X-Interaction-Id', 'session-1')
231 sent.set('x-initiator', 'user')
232 sent.set('anthropic-beta', 'interleaved-thinking-2025-05-14')
233 url = input instanceof Request ? input.url : String(input)
234 headers = Object.fromEntries(sent)
235 return next(input, { ...init, headers: sent })
236 },
237 stream: false,
238 })
239 return Response.json({ text, url, headers })
240 }
241 const responses = api === 'responses'
242 // aimock logs a converted body for /v1/responses, with no `store` or
243 // `include`. So the route keeps the body that the adapter sent.
244 let sent: unknown
245 const { text } = await chat({
246 adapter: openaiCompatibleText('gpt-5.6', {
247 name: 'github-copilot',
248 baseURL: `${LLMOCK_BASE}/v1`,
249 apiKey: 'copilot-token',
250 defaultHeaders: {
251 'Openai-Intent': 'conversation-edits',
252 'X-GitHub-Api-Version': '2026-08-01',
253 ...(testId ? { 'X-Test-Id': testId } : {}),
254 },
255 ...(responses ? { api: 'responses' as const } : {}),
256 }),
257 messages: [
258 {
259 role: 'user',
260 content: '[oneshot] what is your most popular guitar',
261 },
262 ],
263 ...(responses
264 ? {
265 modelOptions: {
266 store: false,
267 include: ['reasoning.encrypted_content'],
268 },
269 }
270 : {}),
271 wrapFetch: (next) => (input, init) => {
272 const headers = new Headers(init?.headers)
273 headers.set('x-initiator', 'user')
274 if (typeof init?.body === 'string') sent = JSON.parse(init.body)
275 return next(input, { ...init, headers })
276 },
277 stream: false,
278 })
279 return Response.json({ text, sent })
280 },
281 },
282 },
283})