@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/index.d.ts ADDED
@@ -0,0 +1,519 @@
1
+ export type Awaitable<T> = T | Promise<T>;
2
+ export interface Clock {
3
+ now(): number;
4
+ setTimeout(fn: () => void, ms: number): unknown;
5
+ clearTimeout(id: unknown): void;
6
+ setInterval(fn: () => void, ms: number): unknown;
7
+ clearInterval(id: unknown): void;
8
+ }
9
+ export interface CallContext {
10
+ userId: string;
11
+ role: string;
12
+ plan?: string;
13
+ groupId?: string;
14
+ callId?: string;
15
+ language?: string;
16
+ mode?: string;
17
+ conversationId?: string | null;
18
+ allowCloudFallback?: boolean;
19
+ memoryWhere?: unknown;
20
+ }
21
+ export interface CallMessage {
22
+ type: string;
23
+ [key: string]: unknown;
24
+ }
25
+ export interface Socket {
26
+ readyState: number;
27
+ send(data: string): void;
28
+ close(code?: number): void;
29
+ on?(event: string, listener: (...args: unknown[]) => void): void;
30
+ }
31
+ export interface ProviderLine {
32
+ sendAudio(data: string, mimeType?: string): void;
33
+ sendText(text: string): void;
34
+ sendImage?(data: string): void;
35
+ mute?(): void;
36
+ interrupt?(): void;
37
+ close(): void;
38
+ readonly model?: string | null;
39
+ }
40
+ export interface ProviderAdapter {
41
+ connect(options: {
42
+ instructions: string;
43
+ tools?: unknown;
44
+ earlier?: unknown[];
45
+ getHistory?: () => unknown[];
46
+ mode?: string;
47
+ onEvent?: (event: CallMessage) => void;
48
+ onClose?: (reason: string) => void;
49
+ }): Promise<ProviderLine>;
50
+ }
51
+ export declare const PHASES: Set<string>;
52
+ export declare function encodeMessage(message: CallMessage): string;
53
+ export declare function decodeMessage(raw: unknown, options?: {
54
+ maxBytes?: number;
55
+ }): CallMessage | null;
56
+ export declare function nextCallState(state: {
57
+ phase: string;
58
+ reason: string | null;
59
+ muted: boolean;
60
+ }, event: CallMessage): {
61
+ phase: string;
62
+ reason: string | null;
63
+ muted: boolean;
64
+ };
65
+ export declare function floatToPcm16(samples: Float32Array): Uint8Array;
66
+ export declare function pcm16ToFloat(bytes: Uint8Array): Float32Array;
67
+ export declare function bytesToBase64(bytes: Uint8Array): string;
68
+ export declare function base64ToBytes(value: string): Uint8Array;
69
+ export declare function resample(samples: Float32Array, from: number, to: number): Float32Array;
70
+ export declare function audioLevel(samples: Float32Array): number;
71
+ export declare function encodeMicroChunk(samples: Float32Array, inputRate: number, outputRate?: number): string;
72
+ export declare function decodeVoiceChunk(data: string): Float32Array;
73
+ export declare function shouldInterrupt(input: {
74
+ level: number;
75
+ playing: boolean;
76
+ threshold?: number;
77
+ mode?: string;
78
+ }): boolean;
79
+ export declare function createAudioPacer(options: {
80
+ sampleRate?: number;
81
+ framesPerSecond?: number;
82
+ maxQueuedMs?: number;
83
+ send(data: string): void;
84
+ clock?: Pick<Clock, 'setTimeout' | 'clearTimeout'>;
85
+ }): {
86
+ push(samples: Float32Array, inputRate?: number): number;
87
+ clear(): void;
88
+ stop(): void;
89
+ readonly queued: number;
90
+ };
91
+ export declare function serverReason(reason: unknown): string | null;
92
+ export declare function closeOutcome(code: number, options?: {
93
+ reason?: string | null;
94
+ refreshed?: boolean;
95
+ }): {
96
+ kind: string;
97
+ code?: string;
98
+ };
99
+ export declare function nextSubtitle(state: {
100
+ text: string;
101
+ fresh: boolean;
102
+ }, event: CallMessage): {
103
+ text: string;
104
+ fresh: boolean;
105
+ };
106
+ export declare function subtitleTail(text: string, max?: number): string;
107
+ export declare function nextConsent(state: {
108
+ actionId: string;
109
+ readback: string;
110
+ } | null, event: CallMessage): {
111
+ actionId: string;
112
+ readback: string;
113
+ } | null;
114
+ export declare function nextTranscript(turns: Array<{
115
+ role: string;
116
+ text: string;
117
+ }>, event: CallMessage): Array<{
118
+ role: string;
119
+ text: string;
120
+ }>;
121
+ export declare function cleanTranscript(turns: Array<{
122
+ role: string;
123
+ text: string;
124
+ }>): Array<{
125
+ role: string;
126
+ text: string;
127
+ }>;
128
+ export declare function nextHeard(state: {
129
+ text: string;
130
+ fresh: boolean;
131
+ uncertain: boolean;
132
+ }, event: CallMessage): {
133
+ text: string;
134
+ fresh: boolean;
135
+ uncertain: boolean;
136
+ };
137
+ export declare function callUrl(baseUrl: string, options?: {
138
+ path?: string;
139
+ language?: string;
140
+ conversationId?: string | null;
141
+ mode?: string | null;
142
+ }): string;
143
+ export declare function languageCode(value: unknown, supported?: string[], fallback?: string): string;
144
+ export declare function resumeConversation(options: {
145
+ store?: {
146
+ get(id: string, userId: string): Awaitable<unknown>;
147
+ latest(userId: string): Awaitable<unknown>;
148
+ };
149
+ userId: string;
150
+ requestedId?: string | null;
151
+ now(): number;
152
+ windowMs?: number;
153
+ maxTurns?: number;
154
+ }): Promise<{
155
+ id: string;
156
+ turns: unknown[];
157
+ } | null>;
158
+ export declare function createTranscriptRecorder(options: {
159
+ store?: unknown;
160
+ userId: string;
161
+ conversationId?: string | null;
162
+ now(): number;
163
+ onSaved?(id: string): void;
164
+ maxChars?: number;
165
+ completeOnly?: boolean;
166
+ deferLatestExchange?: boolean;
167
+ }): {
168
+ record(turns: Array<{
169
+ who: string;
170
+ text: string;
171
+ annotations?: unknown[];
172
+ }>, options?: {
173
+ final?: boolean;
174
+ }): Promise<void>;
175
+ kept(): Promise<string | null>;
176
+ };
177
+ export declare function consolidateAfterCall(memory: {
178
+ consolidate(where: unknown, input: unknown): Awaitable<unknown>;
179
+ } | null, where: unknown, transcript: unknown[], id: string | null, logger?: unknown): Promise<unknown>;
180
+ export declare function createMemoryMinuteStore(options: {
181
+ now(): number;
182
+ }): {
183
+ usedMs(userId: string, plan?: string, role?: string): Promise<number>;
184
+ addMs(userId: string, plan: string | undefined, role: string | undefined, ms: number): Promise<void>;
185
+ usedGroupMs(groupId: string, plan?: string): Promise<number>;
186
+ addGroupMs(groupId: string, plan: string | undefined, ms: number): Promise<void>;
187
+ };
188
+ export declare function createMinuteQuota(options: {
189
+ store?: {
190
+ usedMs?(userId: string, plan?: string, role?: string): Awaitable<number>;
191
+ addMs?(userId: string, plan: string | undefined, role: string | undefined, ms: number): Awaitable<unknown>;
192
+ usedGroupMs?(groupId: string, plan?: string): Awaitable<number>;
193
+ addGroupMs?(groupId: string, plan: string | undefined, ms: number): Awaitable<unknown>;
194
+ };
195
+ limits?: Record<string, unknown>;
196
+ now(): number;
197
+ warningBeforeMs?: number;
198
+ maxCallMs?: number;
199
+ countGroup?(ctx: CallContext): boolean;
200
+ }): {
201
+ check(ctx: CallContext, startedAt: number, chargedMs?: number): Promise<{
202
+ remainingMs: number;
203
+ code: string;
204
+ reason: string;
205
+ }>;
206
+ debit(ctx: CallContext, ms: number): Promise<number>;
207
+ charge(ctx: CallContext, startedAt: number, chargedMs?: number): Promise<number>;
208
+ limitFor(ctx: CallContext): number;
209
+ groupLimitFor(ctx: CallContext): number;
210
+ };
211
+ export declare function createDailyCounter(options: {
212
+ store?: {
213
+ get(key: string): Awaitable<number>;
214
+ add(key: string, amount: number, ttlMs: number): Awaitable<unknown>;
215
+ };
216
+ now(): number;
217
+ }): {
218
+ used(id: string): Promise<number>;
219
+ add(id: string, amount?: number): Promise<number>;
220
+ };
221
+ export declare function createCallLease(options: {
222
+ store: {
223
+ get(userId: string): Awaitable<string | null>;
224
+ set(userId: string, callId: string, ttlMs: number): Awaitable<unknown>;
225
+ delete(userId: string): Awaitable<unknown>;
226
+ };
227
+ ttlMs?: number;
228
+ }): {
229
+ acquire(userId: string, callId: string): Promise<void>;
230
+ isOwner(userId: string, callId: string): Promise<boolean>;
231
+ release(userId: string, callId: string): Promise<void>;
232
+ };
233
+ export declare function normalizeSpeech(value: unknown): string;
234
+ export declare function createSpokenConfirmation(options: {
235
+ now(): number;
236
+ timeoutMs?: number;
237
+ affirmative?: Record<string, string[]>;
238
+ negative?: Record<string, string[]>;
239
+ }): {
240
+ propose(id: string): void;
241
+ heard(turn: {
242
+ who: string;
243
+ text: string;
244
+ }): void;
245
+ verify(id: string, language: string): string;
246
+ clear(id: string): void;
247
+ readonly pendingId: string | null;
248
+ };
249
+ export declare function toolDeclarations(registry: unknown, role: string, catalog?: Record<string, string>): unknown[];
250
+ export declare function createCallTools(options: {
251
+ registry?: unknown;
252
+ context: CallContext;
253
+ confirmation: ReturnType<typeof createSpokenConfirmation>;
254
+ actions?: unknown;
255
+ shield?: unknown;
256
+ clock: Pick<Clock, 'setTimeout' | 'clearTimeout'>;
257
+ timeoutMs?: number;
258
+ maxResultChars?: number;
259
+ send?(message: CallMessage): void;
260
+ onResult?(name: string, result: unknown): void;
261
+ catalog?: Record<string, string>;
262
+ }): {
263
+ declarations: unknown[];
264
+ call(request: {
265
+ name: string;
266
+ args?: Record<string, unknown>;
267
+ }): Promise<unknown>;
268
+ confirmByClient(actionId: string): Promise<unknown>;
269
+ cancelByClient(actionId: string): Promise<unknown>;
270
+ };
271
+ export declare function buildInstructions(options: {
272
+ persona?: string;
273
+ language?: string;
274
+ role?: string;
275
+ now?(): string;
276
+ catalog?: Record<string, unknown>;
277
+ shield?: unknown;
278
+ }): string;
279
+ export declare function createLiveShield(options?: {
280
+ omitKey?(key: string, path: string[], value: unknown): boolean;
281
+ redactText?(text: string): string;
282
+ maskText?(text: string): string;
283
+ unmaskText?(text: string): string;
284
+ maxDepth?: number;
285
+ }): {
286
+ input(text: string): string;
287
+ output(text: string): string;
288
+ args(value: unknown): unknown;
289
+ result(value: unknown): unknown;
290
+ external(value: unknown): unknown;
291
+ history(value: unknown): unknown;
292
+ };
293
+ export declare function geminiSetup(options: {
294
+ model: string;
295
+ voice?: string;
296
+ instructions: string;
297
+ declarations?: unknown[];
298
+ handle?: string | null;
299
+ mode?: string;
300
+ }): unknown;
301
+ export declare function geminiEvents(message: Record<string, unknown>): CallMessage[];
302
+ export declare function createGeminiLiveAdapter(options: {
303
+ websocketFactory(url: string): unknown;
304
+ candidates: Array<{
305
+ model: string;
306
+ key: string;
307
+ }>;
308
+ endpoint?: string;
309
+ voice?: string;
310
+ clock: Clock;
311
+ openTimeoutMs?: number;
312
+ cooldownMs?: number;
313
+ maxHeld?: number;
314
+ maxImageBytes?: number;
315
+ imageEveryMs?: number;
316
+ logger?: unknown;
317
+ }): ProviderAdapter;
318
+ export declare function parseSse(stream: AsyncIterable<Uint8Array>): AsyncIterable<unknown>;
319
+ export declare function createGeminiTextModel(options: {
320
+ fetch(url: string, options: unknown): Promise<unknown>;
321
+ candidates: Array<{
322
+ model: string;
323
+ key: string;
324
+ }>;
325
+ endpoint?: string;
326
+ clock: Clock;
327
+ timeoutMs?: number;
328
+ cooldownMs?: number;
329
+ generationConfig?: Record<string, unknown>;
330
+ logger?: unknown;
331
+ }): {
332
+ generate(input: unknown): Promise<{
333
+ parts: unknown[];
334
+ interrupted: boolean;
335
+ }>;
336
+ };
337
+ export declare function createTextThinker(options: {
338
+ model: {
339
+ generate(input: unknown): Promise<unknown>;
340
+ };
341
+ instructions: string;
342
+ declarations?: unknown[];
343
+ tools: {
344
+ call(input: unknown): Promise<unknown>;
345
+ };
346
+ earlier?: unknown[];
347
+ maxTurns?: number;
348
+ maxHistory?: number;
349
+ onTool?(name: string, state: string): void;
350
+ }): {
351
+ respond(question: string, options?: {
352
+ onText?(text: string): void;
353
+ signal?: AbortSignal;
354
+ }): Promise<{
355
+ text: string;
356
+ interrupted: boolean;
357
+ limitReached?: boolean;
358
+ }>;
359
+ undoLast(): void;
360
+ readonly history: unknown[];
361
+ };
362
+ export declare function createLiveReader(options?: {
363
+ primary?: {
364
+ id?: string;
365
+ synthesize(input: unknown): Promise<unknown>;
366
+ interrupt?(): void;
367
+ close?(): void;
368
+ };
369
+ providers?: Array<{
370
+ id?: string;
371
+ synthesize(input: unknown): Promise<unknown>;
372
+ }>;
373
+ maxConcurrent?: number;
374
+ drift?: Record<string, unknown>;
375
+ logger?: unknown;
376
+ }): {
377
+ synthesize(input: {
378
+ text: string;
379
+ language?: string;
380
+ signal?: AbortSignal;
381
+ onPiece?(piece: unknown): void;
382
+ onReset?(): void;
383
+ }): Promise<{
384
+ pieces: unknown[];
385
+ code?: string;
386
+ provider?: string;
387
+ fallback?: boolean;
388
+ streamed?: boolean;
389
+ }>;
390
+ interrupt(): void;
391
+ close(): void;
392
+ };
393
+ export declare function createGeminiLiveReader(options: {
394
+ adapter?: ProviderAdapter;
395
+ websocketFactory?: (url: string) => unknown;
396
+ candidates?: Array<{
397
+ model: string;
398
+ key: string;
399
+ }>;
400
+ clock: Clock;
401
+ voice?: string;
402
+ providers?: Array<{
403
+ id?: string;
404
+ synthesize(input: unknown): Promise<unknown>;
405
+ }>;
406
+ timeoutMs?: number;
407
+ instructions?: string;
408
+ logger?: unknown;
409
+ }): ReturnType<typeof createLiveReader>;
410
+ export declare function createConfidentialCall(options: {
411
+ voiceOptions?: unknown;
412
+ transcribe(samples: Float32Array): Awaitable<unknown>;
413
+ thinker(input: unknown): Awaitable<unknown>;
414
+ reader: {
415
+ synthesize(input: unknown): Awaitable<unknown>;
416
+ interrupt?(): void;
417
+ close?(): void;
418
+ };
419
+ policy?: unknown;
420
+ session: CallContext;
421
+ shield?: unknown;
422
+ tools?: unknown;
423
+ send(message: CallMessage): void;
424
+ onFallback?(reason: string, audio?: Float32Array): void;
425
+ onTurn?(turn: {
426
+ who: string;
427
+ text: string;
428
+ }): void;
429
+ clock: Clock;
430
+ repeatText?: string | null;
431
+ earlier?: Array<{
432
+ who?: string;
433
+ role?: string;
434
+ text: string;
435
+ }>;
436
+ }): {
437
+ receive(message: CallMessage): Promise<void> | void;
438
+ end(): void;
439
+ flush(): Promise<void>;
440
+ snapshot(): unknown;
441
+ readonly history: unknown[];
442
+ readonly busy: boolean;
443
+ };
444
+ export declare const CLOSE: Readonly<{
445
+ AUTH: number;
446
+ DENIED: number;
447
+ REPLACED: number;
448
+ BUSY: number;
449
+ UNAVAILABLE: number;
450
+ NORMAL: number;
451
+ }>;
452
+ export declare function createLiveSession(options: {
453
+ socket: Socket;
454
+ context: CallContext;
455
+ provider?: ProviderAdapter;
456
+ local?: unknown;
457
+ policy?: unknown;
458
+ registry?: unknown;
459
+ actions?: unknown;
460
+ quota?: unknown;
461
+ lease?: ReturnType<typeof createCallLease>;
462
+ transcripts?: unknown;
463
+ memory?: unknown;
464
+ clock: Clock;
465
+ logger?: unknown;
466
+ catalog?: Record<string, unknown>;
467
+ persona?: string;
468
+ resumeWindowMs?: number;
469
+ resumeTurns?: number;
470
+ transcriptCompleteOnly?: boolean;
471
+ deferLatestExchange?: boolean;
472
+ idleMs?: number;
473
+ checkMs?: number;
474
+ maxCallMs?: number;
475
+ shield?: unknown;
476
+ annotateToolResult?(name: string, result: unknown): unknown;
477
+ directAudio?: {
478
+ vad?: unknown;
479
+ echo?: unknown;
480
+ outputRate?: number;
481
+ } | null;
482
+ }): {
483
+ start(): Promise<void>;
484
+ receive(raw: unknown): Promise<void>;
485
+ close(reason?: string, code?: number): Promise<void>;
486
+ tick(): Promise<void>;
487
+ readonly mode: string | null;
488
+ readonly ended: boolean;
489
+ readonly turns: unknown[];
490
+ };
491
+ export declare function attachLive(options: {
492
+ httpServer: {
493
+ on(event: string, listener: (...args: unknown[]) => void): void;
494
+ off?(event: string, listener: (...args: unknown[]) => void): void;
495
+ };
496
+ websocketServer: {
497
+ handleUpgrade(request: unknown, socket: unknown, head: unknown, callback: (client: Socket) => void): void;
498
+ close?(): void;
499
+ };
500
+ authenticate(request: unknown): Awaitable<CallContext | null>;
501
+ authorize?(request: unknown, context: CallContext): Awaitable<boolean | {
502
+ allowed: boolean;
503
+ reason?: string;
504
+ code?: number;
505
+ }>;
506
+ createSession(options: {
507
+ socket: Socket;
508
+ context: CallContext;
509
+ }): ReturnType<typeof createLiveSession>;
510
+ path?: string;
511
+ maxCalls?: number;
512
+ logger?: unknown;
513
+ languages?: string[];
514
+ modes?: string[];
515
+ conversationIdPattern?: RegExp;
516
+ }): {
517
+ readonly size: number;
518
+ close(): void;
519
+ };
package/src/index.js ADDED
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ module.exports = {
4
+ ...require('./protocol'),
5
+ ...require('./client'),
6
+ ...require('./continuity'),
7
+ ...require('./quotas'),
8
+ ...require('./tools'),
9
+ ...require('./shield'),
10
+ ...require('./gemini'),
11
+ ...require('./textModel'),
12
+ ...require('./reader'),
13
+ ...require('./confidential'),
14
+ ...require('./session')
15
+ };
@@ -0,0 +1,169 @@
1
+ 'use strict';
2
+
3
+ const PHASES = new Set(['connecting', 'listening', 'thinking', 'speaking', 'confirming', 'reconnecting', 'ended']);
4
+ const MESSAGE_TYPES = new Set([
5
+ 'audio', 'text', 'image', 'mute', 'unmute', 'interrupt', 'confirm', 'cancel',
6
+ 'end', 'mode', 'ready', 'heard', 'said', 'turn', 'tool', 'tool_done', 'error',
7
+ 'idle', 'saved', 'action_done', 'action_cancelled', 'fallback', 'quota',
8
+ 'interrupted', 'switching', 'repeat'
9
+ ]);
10
+ function encodeMessage(message) {
11
+ if (!message || !MESSAGE_TYPES.has(message.type)) throw new TypeError('INVALID_MESSAGE');
12
+ return JSON.stringify(message);
13
+ }
14
+ function decodeMessage(raw, {
15
+ maxBytes = 256 * 1024
16
+ } = {}) {
17
+ const value = typeof raw === 'string' ? raw : String(raw);
18
+ if (globalThis.Buffer ? globalThis.Buffer.byteLength(value) > maxBytes : new globalThis.TextEncoder().encode(value).length > maxBytes) return null;
19
+ try {
20
+ const message = JSON.parse(value);
21
+ return message && !Array.isArray(message) && MESSAGE_TYPES.has(message.type) ? message : null;
22
+ } catch (_error) {
23
+ return null;
24
+ }
25
+ }
26
+ function nextCallState(state = {
27
+ phase: 'connecting',
28
+ reason: null,
29
+ muted: false
30
+ }, event = {}) {
31
+ if (state.phase === 'ended') return state;
32
+ const phase = {
33
+ ready: 'listening',
34
+ audio: 'speaking',
35
+ heard: 'thinking',
36
+ text: 'thinking',
37
+ said: 'speaking',
38
+ confirm: 'confirming',
39
+ switching: 'reconnecting',
40
+ turn: 'listening',
41
+ interrupted: 'listening',
42
+ end: 'ended',
43
+ error: 'ended',
44
+ idle: 'ended'
45
+ }[event.type] || state.phase;
46
+ return {
47
+ ...state,
48
+ phase: PHASES.has(phase) ? phase : state.phase,
49
+ muted: event.type === 'mute' ? true : event.type === 'unmute' ? false : state.muted,
50
+ reason: phase === 'ended' ? event.reason || event.type.toUpperCase() : null
51
+ };
52
+ }
53
+ function floatToPcm16(samples) {
54
+ const bytes = new Uint8Array(samples.length * 2);
55
+ const view = new DataView(bytes.buffer);
56
+ for (let i = 0; i < samples.length; i += 1) {
57
+ const value = Math.max(-1, Math.min(1, Number(samples[i]) || 0));
58
+ view.setInt16(i * 2, value < 0 ? Math.round(value * 32768) : Math.round(value * 32767), true);
59
+ }
60
+ return bytes;
61
+ }
62
+ function pcm16ToFloat(bytes) {
63
+ if (bytes.length % 2) throw new RangeError('INVALID_PCM16');
64
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
65
+ return Float32Array.from({
66
+ length: bytes.length / 2
67
+ }, (_, i) => view.getInt16(i * 2, true) / 32768);
68
+ }
69
+ function bytesToBase64(bytes) {
70
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64');
71
+ let binary = '';
72
+ for (const byte of bytes) binary += String.fromCharCode(byte);
73
+ return globalThis.btoa(binary);
74
+ }
75
+ function base64ToBytes(value) {
76
+ if (typeof Buffer !== 'undefined') return Uint8Array.from(Buffer.from(value, 'base64'));
77
+ return Uint8Array.from(globalThis.atob(value), char => char.charCodeAt(0));
78
+ }
79
+ function resample(samples, from, to) {
80
+ if (!(from > 0 && to > 0)) throw new RangeError('INVALID_AUDIO_RATE');
81
+ if (from === to) return Float32Array.from(samples);
82
+ const out = new Float32Array(Math.round(samples.length * to / from));
83
+ for (let i = 0; i < out.length; i += 1) {
84
+ const position = i * from / to;
85
+ const left = Math.floor(position);
86
+ const fraction = position - left;
87
+ out[i] = (samples[left] || 0) * (1 - fraction) + (samples[Math.min(left + 1, samples.length - 1)] || 0) * fraction;
88
+ }
89
+ return out;
90
+ }
91
+ function audioLevel(samples) {
92
+ if (!samples.length) return 0;
93
+ return Math.min(1, Math.sqrt(samples.reduce((sum, sample) => sum + sample * sample, 0) / samples.length) * 5);
94
+ }
95
+ function encodeMicroChunk(samples, inputRate, outputRate = 16000) {
96
+ return bytesToBase64(floatToPcm16(resample(samples, inputRate, outputRate)));
97
+ }
98
+ function decodeVoiceChunk(data) {
99
+ return pcm16ToFloat(base64ToBytes(data));
100
+ }
101
+ function shouldInterrupt({
102
+ level,
103
+ playing,
104
+ threshold = 0.55,
105
+ mode = 'normal'
106
+ }) {
107
+ return Boolean(playing && mode === 'confidential' && level >= threshold);
108
+ }
109
+ function createAudioPacer({
110
+ sampleRate = 16000,
111
+ framesPerSecond = 25,
112
+ maxQueuedMs = 400,
113
+ send,
114
+ clock = {
115
+ setTimeout,
116
+ clearTimeout
117
+ }
118
+ }) {
119
+ if (typeof send !== 'function' || !(sampleRate > 0 && framesPerSecond > 0 && maxQueuedMs > 0)) throw new TypeError('INVALID_PACER');
120
+ const frame = Math.round(sampleRate / framesPerSecond);
121
+ const queue = [];
122
+ let timer = null;
123
+ let stopped = false;
124
+ function tick() {
125
+ timer = null;
126
+ if (stopped || !queue.length) return;
127
+ send(bytesToBase64(floatToPcm16(queue.shift())));
128
+ if (queue.length) timer = clock.setTimeout(tick, 1000 / framesPerSecond);
129
+ }
130
+ return {
131
+ push(samples, inputRate = sampleRate) {
132
+ if (stopped) return 0;
133
+ const converted = resample(samples, inputRate, sampleRate);
134
+ for (let at = 0; at < converted.length; at += frame) queue.push(converted.slice(at, at + frame));
135
+ const max = Math.ceil(maxQueuedMs * framesPerSecond / 1000);
136
+ while (queue.length > max) queue.shift();
137
+ if (timer === null && queue.length) tick();
138
+ return queue.length;
139
+ },
140
+ clear() {
141
+ queue.length = 0;
142
+ if (timer !== null) clock.clearTimeout(timer);
143
+ timer = null;
144
+ },
145
+ stop() {
146
+ stopped = true;
147
+ this.clear();
148
+ },
149
+ get queued() {
150
+ return queue.length;
151
+ }
152
+ };
153
+ }
154
+ module.exports = {
155
+ PHASES,
156
+ encodeMessage,
157
+ decodeMessage,
158
+ nextCallState,
159
+ floatToPcm16,
160
+ pcm16ToFloat,
161
+ bytesToBase64,
162
+ base64ToBytes,
163
+ resample,
164
+ audioLevel,
165
+ encodeMicroChunk,
166
+ decodeVoiceChunk,
167
+ shouldInterrupt,
168
+ createAudioPacer
169
+ };