@astratra/live 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/gemini.js ADDED
@@ -0,0 +1,374 @@
1
+ 'use strict';
2
+
3
+ const DEFAULT_ENDPOINT = 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent';
4
+ function geminiSetup({
5
+ model,
6
+ voice,
7
+ instructions,
8
+ declarations = [],
9
+ handle = null,
10
+ mode = 'normal'
11
+ }) {
12
+ return {
13
+ setup: {
14
+ model: `models/${model}`,
15
+ ...(declarations.length ? {
16
+ tools: [{
17
+ functionDeclarations: declarations
18
+ }]
19
+ } : {}),
20
+ generationConfig: mode === 'confidential' ? {
21
+ responseModalities: ['TEXT']
22
+ } : {
23
+ responseModalities: ['AUDIO'],
24
+ speechConfig: {
25
+ voiceConfig: {
26
+ prebuiltVoiceConfig: {
27
+ voiceName: voice
28
+ }
29
+ }
30
+ }
31
+ },
32
+ systemInstruction: {
33
+ parts: [{
34
+ text: instructions
35
+ }]
36
+ },
37
+ inputAudioTranscription: {},
38
+ outputAudioTranscription: {},
39
+ sessionResumption: handle ? {
40
+ handle
41
+ } : {},
42
+ contextWindowCompression: {
43
+ slidingWindow: {}
44
+ },
45
+ realtimeInputConfig: {
46
+ automaticActivityDetection: {
47
+ startOfSpeechSensitivity: 'START_SENSITIVITY_LOW',
48
+ prefixPaddingMs: 300
49
+ }
50
+ }
51
+ }
52
+ };
53
+ }
54
+ function geminiEvents(message) {
55
+ const events = [];
56
+ if (message.sessionResumptionUpdate?.newHandle) events.push({
57
+ type: 'handle',
58
+ handle: message.sessionResumptionUpdate.newHandle
59
+ });
60
+ if (message.goAway) events.push({
61
+ type: 'goAway'
62
+ });
63
+ if (message.toolCall?.functionCalls) events.push({
64
+ type: 'tools',
65
+ calls: message.toolCall.functionCalls
66
+ });
67
+ if (message.toolCallCancellation?.ids) events.push({
68
+ type: 'toolCancel',
69
+ ids: message.toolCallCancellation.ids
70
+ });
71
+ const content = message.serverContent;
72
+ if (content?.inputTranscription?.text) events.push({
73
+ type: 'heard',
74
+ text: content.inputTranscription.text
75
+ });
76
+ if (content?.outputTranscription?.text) events.push({
77
+ type: 'said',
78
+ text: content.outputTranscription.text
79
+ });
80
+ for (const part of content?.modelTurn?.parts || []) {
81
+ if (part.inlineData?.data) events.push({
82
+ type: 'audio',
83
+ data: part.inlineData.data,
84
+ mimeType: part.inlineData.mimeType
85
+ });
86
+ if (part.text) events.push({
87
+ type: 'text',
88
+ text: part.text
89
+ });
90
+ }
91
+ if (content?.interrupted) events.push({
92
+ type: 'interrupted'
93
+ });
94
+ if (content?.turnComplete) events.push({
95
+ type: 'turn'
96
+ });
97
+ if (message.error) events.push({
98
+ type: 'error',
99
+ code: message.error.code || 'PROVIDER_ERROR'
100
+ });
101
+ return events;
102
+ }
103
+ function createGeminiLiveAdapter({
104
+ websocketFactory,
105
+ candidates = [],
106
+ endpoint = DEFAULT_ENDPOINT,
107
+ voice,
108
+ clock,
109
+ openTimeoutMs = 10000,
110
+ cooldownMs = 600000,
111
+ maxHeld = 200,
112
+ maxImageBytes = 200000,
113
+ imageEveryMs = 1000,
114
+ logger = {}
115
+ }) {
116
+ if (typeof websocketFactory !== 'function' || !clock) throw new TypeError('ADAPTER_DEPENDENCY_REQUIRED');
117
+ const resting = new Map();
118
+ function ordered() {
119
+ const available = candidates.filter(candidate => candidate?.key && candidate?.model);
120
+ return [...available.filter(item => (resting.get(item.key) || 0) <= clock.now()), ...available.filter(item => (resting.get(item.key) || 0) > clock.now())];
121
+ }
122
+ return {
123
+ async connect({
124
+ instructions,
125
+ tools = {
126
+ declarations: [],
127
+ call: async () => ({})
128
+ },
129
+ earlier = [],
130
+ getHistory,
131
+ mode = 'normal',
132
+ onEvent = () => {},
133
+ onClose = () => {}
134
+ }) {
135
+ let socket = null;
136
+ let current = null;
137
+ let handle = null;
138
+ let ended = false;
139
+ let moving = false;
140
+ let generation = 0;
141
+ let lastImageAt = -Infinity;
142
+ const held = [];
143
+ const tried = new Set();
144
+ const cancelled = new Set();
145
+ const send = value => {
146
+ if (socket?.readyState === 1) socket.send(JSON.stringify(value));
147
+ };
148
+ const tell = () => {
149
+ const history = typeof getHistory === 'function' ? getHistory() : earlier;
150
+ const text = history.map(turn => `${turn.who}: ${String(turn.text).trim()}`).join('\n').slice(-6000);
151
+ if (text) send({
152
+ clientContent: {
153
+ turns: [{
154
+ role: 'user',
155
+ parts: [{
156
+ text
157
+ }]
158
+ }],
159
+ turnComplete: true
160
+ }
161
+ });
162
+ };
163
+ async function routeEvents(raw, source) {
164
+ let parsed;
165
+ try {
166
+ parsed = JSON.parse(String(raw));
167
+ } catch (_error) {
168
+ return;
169
+ }
170
+ for (const event of geminiEvents(parsed)) {
171
+ if (event.type === 'handle') handle = event.handle;else if (event.type === 'goAway') {
172
+ if (source === socket) void move(Boolean(handle));
173
+ } else if (event.type === 'toolCancel') event.ids.forEach(id => cancelled.add(id));else if (event.type === 'tools') {
174
+ for (const call of event.calls) {
175
+ onEvent({
176
+ type: 'tool',
177
+ name: call.name
178
+ });
179
+ let result;
180
+ try {
181
+ result = await tools.call({
182
+ id: call.id,
183
+ name: call.name,
184
+ args: call.args || {}
185
+ });
186
+ } catch (_error) {
187
+ result = {
188
+ code: 'TOOL_FAILED'
189
+ };
190
+ }
191
+ onEvent({
192
+ type: 'tool_done',
193
+ name: call.name
194
+ });
195
+ if (!cancelled.has(call.id) && source === socket) send({
196
+ toolResponse: {
197
+ functionResponses: [{
198
+ id: call.id,
199
+ name: call.name,
200
+ response: {
201
+ result
202
+ }
203
+ }]
204
+ }
205
+ });
206
+ }
207
+ } else onEvent(event);
208
+ }
209
+ }
210
+ function open(candidate, resume) {
211
+ return new Promise((resolve, reject) => {
212
+ const next = websocketFactory(`${endpoint}?key=${encodeURIComponent(candidate.key)}`);
213
+ let ready = false;
214
+ let settled = false;
215
+ const fail = code => {
216
+ if (settled) return;
217
+ settled = true;
218
+ clock.clearTimeout(timer);
219
+ reject(Object.assign(new Error(code), {
220
+ code
221
+ }));
222
+ };
223
+ const timer = clock.setTimeout(() => {
224
+ next.terminate?.();
225
+ fail('OPEN_TIMEOUT');
226
+ }, openTimeoutMs);
227
+ next.on('open', () => next.send(JSON.stringify(geminiSetup({
228
+ model: candidate.model,
229
+ voice,
230
+ instructions,
231
+ declarations: tools.declarations,
232
+ handle: resume ? handle : null,
233
+ mode
234
+ }))));
235
+ next.on('message', data => {
236
+ let parsed;
237
+ try {
238
+ parsed = JSON.parse(String(data));
239
+ } catch (_error) {
240
+ return;
241
+ }
242
+ if (!ready && parsed.setupComplete) {
243
+ ready = true;
244
+ settled = true;
245
+ clock.clearTimeout(timer);
246
+ resolve(next);
247
+ } else if (ready && next === socket) void routeEvents(data, next);
248
+ });
249
+ next.on('close', code => {
250
+ if (!ready) fail('OPEN_CLOSED');else if (next === socket && !ended && !moving) {
251
+ if (code === 1008) resting.set(candidate.key, clock.now() + cooldownMs);
252
+ void move(code !== 1008 && Boolean(handle));
253
+ }
254
+ });
255
+ next.on('error', () => {
256
+ if (!ready) fail('OPEN_ERROR');
257
+ });
258
+ });
259
+ }
260
+ async function move(resume) {
261
+ if (ended || moving) return;
262
+ moving = true;
263
+ const previous = socket;
264
+ socket = null;
265
+ if (previous) onEvent({
266
+ type: 'switching'
267
+ });
268
+ if (previous) previous.close?.();
269
+ const available = ordered();
270
+ for (const candidate of available) {
271
+ const id = `${candidate.model}:${candidate.key}`;
272
+ if (tried.has(id) && !(resume && handle && current && candidate.key === current.key && candidate.model === current.model)) continue;
273
+ tried.add(id);
274
+ try {
275
+ const next = await open(candidate, resume && Boolean(handle) && candidate.key === current?.key);
276
+ if (ended) {
277
+ next.close?.();
278
+ break;
279
+ }
280
+ socket = next;
281
+ const changed = Boolean(current && (candidate.key !== current.key || candidate.model !== current.model));
282
+ current = candidate;
283
+ generation += 1;
284
+ if (changed || generation > 1 && !resume) tell();
285
+ while (held.length) send(held.shift());
286
+ onEvent({
287
+ type: 'ready',
288
+ model: candidate.model,
289
+ reconnected: generation > 1
290
+ });
291
+ moving = false;
292
+ return;
293
+ } catch (error) {
294
+ logger.warn?.('PROVIDER_CONNECT_FAILED', {
295
+ code: error.code
296
+ });
297
+ resting.set(candidate.key, clock.now() + cooldownMs);
298
+ }
299
+ }
300
+ moving = false;
301
+ if (!ended) onClose('PROVIDER_UNAVAILABLE');
302
+ }
303
+ await move(false);
304
+ return {
305
+ sendAudio(data, mimeType = 'audio/pcm;rate=16000') {
306
+ const message = {
307
+ realtimeInput: {
308
+ audio: {
309
+ data,
310
+ mimeType
311
+ }
312
+ }
313
+ };
314
+ if (socket) send(message);else if (held.length < maxHeld) held.push(message);
315
+ },
316
+ sendText(text) {
317
+ const message = {
318
+ clientContent: {
319
+ turns: [{
320
+ role: 'user',
321
+ parts: [{
322
+ text
323
+ }]
324
+ }],
325
+ turnComplete: true
326
+ }
327
+ };
328
+ if (socket) send(message);else if (held.length < maxHeld) held.push(message);
329
+ },
330
+ sendImage(data) {
331
+ if (typeof data !== 'string' || data.length > maxImageBytes * 4 / 3 + 4 || clock.now() - lastImageAt < imageEveryMs) return false;
332
+ lastImageAt = clock.now();
333
+ send({
334
+ realtimeInput: {
335
+ video: {
336
+ data,
337
+ mimeType: 'image/jpeg'
338
+ }
339
+ }
340
+ });
341
+ return true;
342
+ },
343
+ mute() {
344
+ send({
345
+ realtimeInput: {
346
+ audioStreamEnd: true
347
+ }
348
+ });
349
+ },
350
+ interrupt() {
351
+ send({
352
+ clientContent: {
353
+ turnComplete: true
354
+ }
355
+ });
356
+ },
357
+ close() {
358
+ ended = true;
359
+ held.length = 0;
360
+ socket?.close?.();
361
+ socket = null;
362
+ },
363
+ get model() {
364
+ return current?.model || null;
365
+ }
366
+ };
367
+ }
368
+ };
369
+ }
370
+ module.exports = {
371
+ geminiSetup,
372
+ geminiEvents,
373
+ createGeminiLiveAdapter
374
+ };