|
| 1 | +import WebSocket from 'ws'; |
| 2 | + |
| 3 | +import { getGeminiLiveModel, getGeminiLiveWsUrl, getVoiceMaxDuration } from '../../ai/voice-model'; |
| 4 | +import logger from '../../libs/logger'; |
| 5 | + |
| 6 | +interface VoiceSession { |
| 7 | + userId: string; |
| 8 | + systemInstruction: string; |
| 9 | + voiceName: string; |
| 10 | + language: string; |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * GeminiLiveRelay — bridges a client WebSocket to the Gemini Live API. |
| 15 | + * |
| 16 | + * Protocol (client ↔ backend): |
| 17 | + * Client sends: { type: "audio", data: "<base64 PCM 16kHz>" } |
| 18 | + * { type: "end" } |
| 19 | + * Server sends: { type: "ready" } |
| 20 | + * { type: "audio", data: "<base64 PCM 24kHz>" } |
| 21 | + * { type: "turnComplete" } |
| 22 | + * { type: "error", message: "..." } |
| 23 | + * { type: "closed" } |
| 24 | + */ |
| 25 | +export class GeminiLiveRelay { |
| 26 | + private geminiWs: WebSocket | null = null; |
| 27 | + |
| 28 | + private isSetupComplete = false; |
| 29 | + |
| 30 | + private isClosed = false; |
| 31 | + |
| 32 | + private maxDurationTimer: ReturnType<typeof setTimeout> | null = null; |
| 33 | + |
| 34 | + constructor( |
| 35 | + private clientWs: WebSocket, |
| 36 | + private session: VoiceSession, |
| 37 | + ) {} |
| 38 | + |
| 39 | + /** Start the relay: connect to Gemini and wire up message handlers */ |
| 40 | + start(): void { |
| 41 | + const wsUrl = getGeminiLiveWsUrl(); |
| 42 | + if (!wsUrl || wsUrl.endsWith('key=')) { |
| 43 | + this.sendToClient({ type: 'error', message: 'Gemini API key not configured' }); |
| 44 | + this.close(); |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + logger.info('[voice-relay] connecting to Gemini Live', { userId: this.session.userId }); |
| 49 | + |
| 50 | + this.geminiWs = new WebSocket(wsUrl); |
| 51 | + |
| 52 | + this.geminiWs.on('open', () => { |
| 53 | + logger.info('[voice-relay] Gemini WS connected, sending setup'); |
| 54 | + this.sendSetup(); |
| 55 | + }); |
| 56 | + |
| 57 | + this.geminiWs.on('message', (data: WebSocket.Data) => { |
| 58 | + this.handleGeminiMessage(data); |
| 59 | + }); |
| 60 | + |
| 61 | + this.geminiWs.on('error', (error) => { |
| 62 | + logger.error('[voice-relay] Gemini WS error', error); |
| 63 | + this.sendToClient({ type: 'error', message: 'Connection to AI service failed' }); |
| 64 | + this.close(); |
| 65 | + }); |
| 66 | + |
| 67 | + this.geminiWs.on('close', (code, reason) => { |
| 68 | + logger.info('[voice-relay] Gemini WS closed', { code, reason: reason.toString() }); |
| 69 | + if (!this.isClosed) { |
| 70 | + this.sendToClient({ type: 'closed' }); |
| 71 | + this.close(); |
| 72 | + } |
| 73 | + }); |
| 74 | + |
| 75 | + // Client message handler |
| 76 | + this.clientWs.on('message', (data: WebSocket.Data) => { |
| 77 | + this.handleClientMessage(data); |
| 78 | + }); |
| 79 | + |
| 80 | + this.clientWs.on('close', () => { |
| 81 | + logger.info('[voice-relay] client disconnected', { userId: this.session.userId }); |
| 82 | + this.close(); |
| 83 | + }); |
| 84 | + |
| 85 | + this.clientWs.on('error', (error) => { |
| 86 | + logger.error('[voice-relay] client WS error', error); |
| 87 | + this.close(); |
| 88 | + }); |
| 89 | + |
| 90 | + // Max duration safety timer |
| 91 | + const maxDuration = getVoiceMaxDuration(); |
| 92 | + this.maxDurationTimer = setTimeout(() => { |
| 93 | + logger.info('[voice-relay] max duration reached', { maxDuration, userId: this.session.userId }); |
| 94 | + this.sendToClient({ type: 'closed' }); |
| 95 | + this.close(); |
| 96 | + }, maxDuration * 1000); |
| 97 | + } |
| 98 | + |
| 99 | + /** Send the Gemini Live setup message with model config + system instruction */ |
| 100 | + private sendSetup(): void { |
| 101 | + const model = getGeminiLiveModel(); |
| 102 | + const setup = { |
| 103 | + setup: { |
| 104 | + model: `models/${model}`, |
| 105 | + generationConfig: { |
| 106 | + responseModalities: ['AUDIO'], |
| 107 | + speechConfig: { |
| 108 | + voiceConfig: { |
| 109 | + prebuiltVoiceConfig: { voiceName: this.session.voiceName }, |
| 110 | + }, |
| 111 | + }, |
| 112 | + }, |
| 113 | + systemInstruction: { |
| 114 | + parts: [{ text: this.session.systemInstruction }], |
| 115 | + }, |
| 116 | + }, |
| 117 | + }; |
| 118 | + this.geminiWs?.send(JSON.stringify(setup)); |
| 119 | + } |
| 120 | + |
| 121 | + /** Handle messages from the client */ |
| 122 | + private handleClientMessage(raw: WebSocket.Data): void { |
| 123 | + try { |
| 124 | + const msg = JSON.parse(raw.toString()); |
| 125 | + |
| 126 | + if (msg.type === 'audio' && this.isSetupComplete) { |
| 127 | + // Forward audio to Gemini in realtimeInput format |
| 128 | + this.geminiWs?.send( |
| 129 | + JSON.stringify({ |
| 130 | + realtimeInput: { |
| 131 | + audio: { |
| 132 | + data: msg.data, |
| 133 | + mimeType: 'audio/pcm;rate=16000', |
| 134 | + }, |
| 135 | + }, |
| 136 | + }), |
| 137 | + ); |
| 138 | + } else if (msg.type === 'end') { |
| 139 | + this.close(); |
| 140 | + } |
| 141 | + } catch { |
| 142 | + // Ignore malformed messages |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + /** Handle messages from Gemini Live API */ |
| 147 | + private handleGeminiMessage(raw: WebSocket.Data): void { |
| 148 | + try { |
| 149 | + const msg = JSON.parse(raw.toString()); |
| 150 | + |
| 151 | + // Setup complete |
| 152 | + if (msg.setupComplete !== undefined) { |
| 153 | + this.isSetupComplete = true; |
| 154 | + logger.info('[voice-relay] setup complete', { userId: this.session.userId }); |
| 155 | + this.sendToClient({ type: 'ready' }); |
| 156 | + return; |
| 157 | + } |
| 158 | + |
| 159 | + const sc = msg.serverContent; |
| 160 | + if (!sc) return; |
| 161 | + |
| 162 | + // Forward audio data |
| 163 | + if (sc.modelTurn?.parts) { |
| 164 | + for (const part of sc.modelTurn.parts) { |
| 165 | + const inline = part.inlineData; |
| 166 | + if (inline?.data) { |
| 167 | + this.sendToClient({ type: 'audio', data: inline.data }); |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + // Turn complete |
| 173 | + if (sc.turnComplete) { |
| 174 | + this.sendToClient({ type: 'turnComplete' }); |
| 175 | + } |
| 176 | + } catch { |
| 177 | + // Ignore parse errors |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + /** Send a JSON message to the client WebSocket */ |
| 182 | + private sendToClient(msg: object): void { |
| 183 | + if (this.clientWs.readyState === WebSocket.OPEN) { |
| 184 | + this.clientWs.send(JSON.stringify(msg)); |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + /** Clean up both connections */ |
| 189 | + close(): void { |
| 190 | + if (this.isClosed) return; |
| 191 | + this.isClosed = true; |
| 192 | + |
| 193 | + if (this.maxDurationTimer) { |
| 194 | + clearTimeout(this.maxDurationTimer); |
| 195 | + this.maxDurationTimer = null; |
| 196 | + } |
| 197 | + |
| 198 | + if (this.geminiWs && this.geminiWs.readyState !== WebSocket.CLOSED) { |
| 199 | + this.geminiWs.close(); |
| 200 | + } |
| 201 | + this.geminiWs = null; |
| 202 | + |
| 203 | + if (this.clientWs.readyState !== WebSocket.CLOSED) { |
| 204 | + this.clientWs.close(); |
| 205 | + } |
| 206 | + } |
| 207 | +} |
0 commit comments