Open History to see the last commit
1import { LLMock } from '@copilotkit/aimock'
2import fs from 'fs'
3import http from 'http'
4import path from 'path'
5import { fileURLToPath } from 'url'
6import type { Mountable } from '@copilotkit/aimock'
7
8const __filename = fileURLToPath(import.meta.url)
9const __dirname = path.dirname(__filename)
10
11/**
12 * Directories to skip when loading JSON fixtures.
13 * - 'recorded' is for record-mode output
14 * - 'video-gen' uses programmatic registration (needs match.endpoint)
15 */
16const SKIP_FIXTURE_DIRS = new Set(['recorded', 'video-gen'])
17
18export default async function globalSetup() {
19 const mock = new LLMock({ port: 4010, host: '127.0.0.1', logLevel: 'info' })
20
21 // Load all JSON fixture directories (except skipped ones)
22 const fixturesDir = path.resolve(__dirname, 'fixtures')
23 const entries = fs.readdirSync(fixturesDir, { withFileTypes: true })
24 for (const entry of entries) {
25 if (entry.isDirectory() && !SKIP_FIXTURE_DIRS.has(entry.name)) {
26 await mock.loadFixtureDir(path.join(fixturesDir, entry.name))
27 }
28 }
29
30 // Register media fixtures programmatically (require match.endpoint)
31 registerMediaFixtures(mock)
32
33 // Mount xAI-shaped audio routes (/v1/tts, /v1/stt) — these are NOT
34 // OpenAI-compatible so aimock's onSpeech/onTranscription helpers don't cover
35 // them. Use mock.mount() to handle the paths directly.
36 mock.mount('/v1/tts', grokTTSMount())
37 mock.mount('/v1/stt', grokSTTMount())
38
39 // ElevenLabs TTS (/v1/text-to-speech/{voiceId}) and STT (/v1/speech-to-text)
40 // are not yet covered by aimock helpers (1.17 added /v1/sound-generation
41 // and /v1/music/* but not these). Mount them here following the grok
42 // pattern above.
43 mock.mount('/v1/text-to-speech', elevenLabsTTSMount())
44 mock.mount('/v1/speech-to-text', elevenLabsSTTMount())
45
46 await mock.start()
47 console.log(`[aimock] started on port 4010`)
48 ;(globalThis as any).__aimock = mock
49}
50
51function registerMediaFixtures(mock: LLMock) {
52 // Transcription: onTranscription sets match.endpoint = "transcription"
53 mock.onTranscription({
54 transcription: {
55 text: 'I would like to buy a Fender Stratocaster please',
56 },
57 })
58
59 // Video: onVideo sets match.endpoint = "video"
60 // id + status are required for the OpenAI SDK's videos API to work:
61 // - POST /v1/videos reads response.id for the job ID
62 // - GET /v1/videos/{id} reads response.status to determine completion
63 mock.onVideo('a guitar being played in a store', {
64 video: {
65 url: 'https://example.com/guitar-store.mp4',
66 duration: 10,
67 id: 'video-job-e2e',
68 status: 'completed',
69 },
70 })
71
72 // ElevenLabs music (/v1/music/*) and SFX (/v1/sound-generation) are
73 // covered natively by aimock 1.17 — fixtures live under
74 // fixtures/audio-gen/ and fixtures/sound-effects/ and are loaded by the
75 // generic loadFixtureDir() loop above.
76}
77
78/**
79 * Minimal MP3 bytes — just enough for the <audio> element to consider it a
80 * valid media resource in tests. The e2e specs only check visibility of the
81 * `generated-audio` element, not playback fidelity.
82 */
83const FAKE_MP3_BYTES = Buffer.from([
84 0xff, 0xfb, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
85])
86
87function grokTTSMount(): Mountable {
88 return {
89 async handleRequest(
90 req: http.IncomingMessage,
91 res: http.ServerResponse,
92 // aimock strips the mount prefix — pathname will be "/" for an exact match.
93 pathname: string,
94 ): Promise<boolean> {
95 if (pathname !== '/' || req.method !== 'POST') return false
96 // Drain the request body (we don't need to inspect it for tests).
97 await drainBody(req)
98 res.statusCode = 200
99 res.setHeader('Content-Type', 'audio/mpeg')
100 res.setHeader('Content-Length', String(FAKE_MP3_BYTES.length))
101 res.end(FAKE_MP3_BYTES)
102 return true
103 },
104 }
105}
106
107function grokSTTMount(): Mountable {
108 return {
109 async handleRequest(
110 req: http.IncomingMessage,
111 res: http.ServerResponse,
112 pathname: string,
113 ): Promise<boolean> {
114 if (pathname !== '/' || req.method !== 'POST') return false
115 await drainBody(req)
116 res.statusCode = 200
117 res.setHeader('Content-Type', 'application/json')
118 res.end(
119 JSON.stringify({
120 text: 'I would like to buy a Fender Stratocaster please',
121 language: 'en',
122 duration: 3.0,
123 words: [
124 { text: 'I', start: 0, end: 0.1, confidence: 0.99 },
125 { text: 'would', start: 0.1, end: 0.3, confidence: 0.98 },
126 { text: 'like', start: 0.3, end: 0.5, confidence: 0.97 },
127 { text: 'to', start: 0.5, end: 0.6, confidence: 0.99 },
128 { text: 'buy', start: 0.6, end: 0.8, confidence: 0.98 },
129 { text: 'a', start: 0.8, end: 0.9, confidence: 0.99 },
130 { text: 'Fender', start: 0.9, end: 1.3, confidence: 0.96 },
131 { text: 'Stratocaster', start: 1.3, end: 2.0, confidence: 0.94 },
132 { text: 'please', start: 2.0, end: 2.4, confidence: 0.97 },
133 ],
134 }),
135 )
136 return true
137 },
138 }
139}
140
141function elevenLabsTTSMount(): Mountable {
142 return {
143 async handleRequest(
144 req: http.IncomingMessage,
145 res: http.ServerResponse,
146 pathname: string,
147 ): Promise<boolean> {
148 // ElevenLabs TTS hits POST /v1/text-to-speech/{voiceId} or
149 // /v1/text-to-speech/{voiceId}/stream. After mount-prefix stripping
150 // pathname will be /{voiceId} or /{voiceId}/stream — accept any
151 // sub-path so we don't have to enumerate voice IDs.
152 if (req.method !== 'POST' || pathname === '/' || pathname === '')
153 return false
154 await drainBody(req)
155 res.statusCode = 200
156 res.setHeader('Content-Type', 'audio/mpeg')
157 res.setHeader('Content-Length', String(FAKE_MP3_BYTES.length))
158 res.end(FAKE_MP3_BYTES)
159 return true
160 },
161 }
162}
163
164function elevenLabsSTTMount(): Mountable {
165 return {
166 async handleRequest(
167 req: http.IncomingMessage,
168 res: http.ServerResponse,
169 pathname: string,
170 ): Promise<boolean> {
171 if (pathname !== '/' || req.method !== 'POST') return false
172 await drainBody(req)
173 res.statusCode = 200
174 res.setHeader('Content-Type', 'application/json')
175 // Scribe wire format is snake_case (the SDK converts to camelCase
176 // before handing the response to user code). Each word needs a
177 // `logprob` field per the SDK's runtime validation. Keep "Fender
178 // Stratocaster" so the existing transcription.spec.ts assertion
179 // passes for elevenlabs too.
180 res.end(
181 JSON.stringify({
182 language_code: 'en',
183 language_probability: 0.99,
184 text: 'I would like to buy a Fender Stratocaster please',
185 audio_duration_secs: 2.4,
186 words: [
187 { text: 'I', start: 0, end: 0.1, type: 'word', logprob: -0.01 },
188 {
189 text: 'would',
190 start: 0.1,
191 end: 0.3,
192 type: 'word',
193 logprob: -0.02,
194 },
195 {
196 text: 'like',
197 start: 0.3,
198 end: 0.5,
199 type: 'word',
200 logprob: -0.03,
201 },
202 { text: 'to', start: 0.5, end: 0.6, type: 'word', logprob: -0.01 },
203 { text: 'buy', start: 0.6, end: 0.8, type: 'word', logprob: -0.02 },
204 { text: 'a', start: 0.8, end: 0.9, type: 'word', logprob: -0.01 },
205 {
206 text: 'Fender',
207 start: 0.9,
208 end: 1.3,
209 type: 'word',
210 logprob: -0.04,
211 },
212 {
213 text: 'Stratocaster',
214 start: 1.3,
215 end: 2.0,
216 type: 'word',
217 logprob: -0.06,
218 },
219 {
220 text: 'please',
221 start: 2.0,
222 end: 2.4,
223 type: 'word',
224 logprob: -0.03,
225 },
226 ],
227 }),
228 )
229 return true
230 },
231 }
232}
233
234function drainBody(req: http.IncomingMessage): Promise<void> {
235 return new Promise((resolve, reject) => {
236 req.on('data', () => {})
237 req.on('end', () => resolve())
238 req.on('error', reject)
239 })
240}