-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent.js
More file actions
3159 lines (2998 loc) · 145 KB
/
agent.js
File metadata and controls
3159 lines (2998 loc) · 145 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// didww-voice-agent — SIP → Gemini Live voice agent.
//
// DIDWW DID → drachtio (SIP) → this process bridges RTP both ways → Gemini Live
// WebSocket. rtpengine handles transcoding, WhatsApp/WABA media and conference
// bridging. See docs/ARCHITECTURE.md.
import 'dotenv/config';
import Srf from 'drachtio-srf';
import sdpTransform from 'sdp-transform';
import dgram from 'node:dgram';
import crypto from 'node:crypto';
import { monitorEventLoopDelay } from 'node:perf_hooks';
import { GoogleGenAI, Modality } from '@google/genai';
import libsamplerate from '@alexanderolsen/libsamplerate-js';
import WebSocket from 'ws';
import express from 'express';
import { rtpNg, parseAudioMedia } from './rtpengine.js';
import { makeG722Codec } from './g722.js';
import { startTrunkRegistration } from './trunk-register.js';
import { getDemoVoiceConfig, execDemoTool } from './demo-config.js';
const { create: createResampler, ConverterType } = libsamplerate;
const {
PUBLIC_IP,
DRACHTIO_HOST = '127.0.0.1',
DRACHTIO_PORT = '9022',
DRACHTIO_SECRET = 'cymru',
GEMINI_API_KEY,
GEMINI_MODEL = 'gemini-3.1-flash-live-preview',
RTP_PORT_MIN = '10000',
RTP_PORT_MAX = '20000',
INTERNAL_VOICE_URL = '', // optional external config service; unset → built-in demo agent
INTERNAL_VOICE_TOKEN = '',
VOICE_VPS_ANNOUNCE_SECRET = '', // HMAC secret for app→VPS /v1/calls/* requests
MAX_CONCURRENT_CALLS = '20',
MAX_CALL_SECONDS = '600', // hard cap per call to prevent runaway Gemini cost
VAD_RMS_THRESHOLD = '500', // caller-mic energy gate (RMS, Int16 PCM)
ANNOUNCE_QUEUE_MAX = '3', // max queued announcements per call
// --- outbound calling (carrier-agnostic SIP trunk; set in .env) ---
SIP_DOMAIN = '', // outbound SIP trunk host/IP — required for outbound calls
SIP_USER = '', // trunk digest username — blank → IP auth only
SIP_PASSWORD = '',
CLI = '', // caller ID: a trunk-owned DID, E.164 digits
// Native-audio model for the 3-leg conference (Proactive Audio). Kept separate
// from GEMINI_MODEL: inbound 1:1 calls stay on gemini-3.1-flash-live-preview,
// which does not support proactivity.
GEMINI_CONFERENCE_MODEL = 'gemini-2.5-flash-native-audio-preview-12-2025',
// Deepgram streaming STT — live transcription for outbound conference calls.
DEEPGRAM_TOKEN = '',
} = process.env;
const MAX_CONCURRENT = parseInt(MAX_CONCURRENT_CALLS);
const MAX_CALL_MS = parseInt(MAX_CALL_SECONDS) * 1000;
const VAD_RMS = parseInt(VAD_RMS_THRESHOLD);
const ANN_QMAX = parseInt(ANNOUNCE_QUEUE_MAX);
// Conference media-path instrumentation — per-leg RTP/jitter-buffer counters
// logged every ~2s. Off by default; set DEBUG_MEDIA=1 in .env to enable.
const DBG_MEDIA = process.env.DEBUG_MEDIA === '1';
// Fetch the system prompt + tool declarations for a specific caller.
//
// When INTERNAL_VOICE_URL is set, this calls an external config service, so each
// caller can get a different prompt and tools (see docs/ADVANCED.md). When it is
// not set, it returns the built-in demo agent from demo-config.js — so a fresh
// clone answers calls with no extra infrastructure.
//
// Returns { systemPrompt, tools, contact, conversationId, locale } or null.
async function fetchVoiceConfig(waId, name) {
if (!INTERNAL_VOICE_URL || !INTERNAL_VOICE_TOKEN) return getDemoVoiceConfig();
try {
const r = await fetch(`${INTERNAL_VOICE_URL.replace(/\/$/, '')}/api/v1/voice/config`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'authorization': `Bearer ${INTERNAL_VOICE_TOKEN}`,
},
body: JSON.stringify({ waId, name }),
signal: AbortSignal.timeout(5000),
});
if (!r.ok) { console.warn(`[voice-config] HTTP ${r.status}`); return null; }
return await r.json();
} catch (e) { console.warn('[voice-config] fetch failed:', e?.message || e); return null; }
}
async function execToolRemote(callId, waId, conversationId, name, args) {
// No external config service → run the built-in demo tools locally.
if (!INTERNAL_VOICE_URL || !INTERNAL_VOICE_TOKEN) return execDemoTool(name, args);
try {
const r = await fetch(`${INTERNAL_VOICE_URL.replace(/\/$/, '')}/api/v1/voice/tool`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'authorization': `Bearer ${INTERNAL_VOICE_TOKEN}`,
},
// callId is required so the app can attach voice_tasks rows to the live
// call and fire mid-call announcements via /v1/calls/:callId/announce.
body: JSON.stringify({ callId, waId, conversationId, name, args }),
signal: AbortSignal.timeout(20000),
});
const j = await r.json().catch(() => ({}));
return String(j.result ?? j.error ?? 'Error: no result');
} catch (e) { return `Error: tool proxy failed — ${e?.message || e}`; }
}
// Ask the control app to hang up a WABA call on Meta's side. This agent owns
// the Gemini + RTP legs, but only the control app holds the Meta access token
// to terminate the WhatsApp call. Returns true on success, false otherwise —
// the caller still does local teardown either way.
async function wabaHangupRemote(callId, waId, reason) {
if (!INTERNAL_VOICE_URL || !INTERNAL_VOICE_TOKEN) return false;
try {
const r = await fetch(`${INTERNAL_VOICE_URL.replace(/\/$/, '')}/api/v1/voice/hangup`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'authorization': `Bearer ${INTERNAL_VOICE_TOKEN}`,
},
body: JSON.stringify({ callId, waId, reason, channel: 'waba' }),
signal: AbortSignal.timeout(8000),
});
if (!r.ok) { console.warn(`[${callId}] control-app hangup HTTP ${r.status}`); return false; }
return true;
} catch (e) { console.warn(`[${callId}] control-app hangup failed: ${e?.message || e}`); return false; }
}
// Normalize an inbound PSTN CLI to E.164 digits-only for use as the caller key.
// DIDWW's "Raw" CLI format preserves whatever the originating carrier sent, which
// is sometimes the national format (e.g. "07700900123") without a country code.
// Rule:
// - leading "+" → strip it (already E.164)
// - leading "00" → international prefix, strip (e.g. "0044770…" → "44770…")
// - leading "0" → national format → strip the "0", prepend the default CC
// - everything else → assume already in E.164 digits, leave as-is
const DIDWW_DEFAULT_CC = process.env.DIDWW_DEFAULT_COUNTRY_CODE || '1';
function normalizeToE164Digits(raw) {
let d = String(raw || '').replace(/[^\d+]/g, '');
if (d.startsWith('+')) d = d.slice(1);
if (d.startsWith('00')) return d.slice(2) || null;
if (d.startsWith('0')) return DIDWW_DEFAULT_CC + d.slice(1);
return d || null;
}
// Convert a caller-supplied number to the digit string the SIP trunk dials with.
// DIDWW two-way trunks route on E.164, so the default is an E.164 digit string
// (no "+", no "00"). Carriers that route on national format instead — some ITSPs
// reject E.164 with a 404 — need a carrier-specific rewrite here, for example an
// Israeli national trunk: `if (d.startsWith('972')) d = '0' + d.slice(3);`.
function toCarrierNumber(raw) {
let d = String(raw || '').replace(/[^\d]/g, '');
if (d.startsWith('00')) d = d.slice(2); // drop 00 international prefix
return d || null;
}
function extractCallerWaId(fromHeader) {
// fromHeader like '<sip:441234567890@203.0.113.5>;tag=...'
const m = String(fromHeader || '').match(/sip:(\+?\d{4,15})@/i);
if (!m) return null;
return normalizeToE164Digits(m[1]);
}
// Generic retry-posting helper. Fire-and-forget with exponential backoff 0→1→3→9s,
// then give up. Never throws; errors logged.
async function postWithBackoff(path, body, tag) {
if (!INTERNAL_VOICE_URL || !INTERNAL_VOICE_TOKEN) return;
const url = `${INTERNAL_VOICE_URL.replace(/\/$/, '')}${path}`;
const delays = [0, 1000, 3000, 9000];
for (let i = 0; i < delays.length; i++) {
if (delays[i]) await new Promise((r) => setTimeout(r, delays[i]));
try {
const r = await fetch(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${INTERNAL_VOICE_TOKEN}`,
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(8000),
});
if (r.ok) { return r.json().catch(() => ({})); }
console.warn(`[${tag}] POST ${path} ${r.status} — retry ${i+1}/${delays.length-1}`);
} catch (e) {
console.warn(`[${tag}] POST ${path} err: ${e?.message || e} — retry ${i+1}/${delays.length-1}`);
}
}
console.error(`[${tag}] POST ${path} gave up after ${delays.length} tries`);
}
// Summary hook — idempotent on callId (server dedupes).
const summaryPosted = new Set();
async function postVoiceSummary(meta) {
if (!meta?.callId || summaryPosted.has(meta.callId)) return;
summaryPosted.add(meta.callId);
if (meta.status === 'COMPLETED' && meta.durationSec < 2 && meta.transcript.length === 0) {
meta.status = 'FAILED';
if (!meta.endReason) meta.endReason = 'no media';
}
const j = await postWithBackoff('/api/v1/voice/summary', meta, meta.callId);
if (j?.messageId !== undefined) console.log(`[${meta.callId}] summary posted (messageId=${j.messageId})`);
}
// Live per-turn hook — fires on each turnComplete / interrupted so the support UI
// gets transcript updates in realtime. Shares callId with the /summary POST.
function postVoiceTurn({ callId, waId, callerName, channel, turnIndex, role, text, ts, staffName }) {
if (!text) return;
postWithBackoff(
'/api/v1/voice/turn',
{ waId, callerName: callerName || null, channel, callId, turnIndex, role, text, ts: ts || new Date().toISOString(), staffName: staffName || null },
`${callId}#t${turnIndex}`,
);
}
// Outbound call-state hook — ringing / answered / failed / ended for conference
// legs, so the control app's UI can show live call progress. Best-effort; the
// /api/v1/voice/call-state endpoint may not exist yet (added in a later stage).
function postCallState(callId, state, extra = {}) {
postWithBackoff(
'/api/v1/voice/call-state',
{ callId, state, ...extra, ts: new Date().toISOString() },
`${callId}#${state}`,
);
}
// Round-robin even-port allocator inside UFW-allowed range.
const PORT_LO = parseInt(RTP_PORT_MIN) & ~1;
const PORT_HI = parseInt(RTP_PORT_MAX) & ~1;
let nextRtpPort = PORT_LO + ((Math.floor(Math.random() * (PORT_HI - PORT_LO)) >> 1) << 1);
async function allocRtpSocket() {
for (let tries = 0; tries < 200; tries++) {
const port = nextRtpPort;
nextRtpPort += 2;
if (nextRtpPort >= PORT_HI) nextRtpPort = PORT_LO;
const s = dgram.createSocket('udp4');
const ok = await new Promise((resolve) => {
s.once('error', () => resolve(false));
s.bind(port, '0.0.0.0', () => resolve(true));
});
if (ok) return { socket: s, port };
try { s.close(); } catch {}
}
throw new Error('no free RTP port in allowed range');
}
if (!PUBLIC_IP) throw new Error('PUBLIC_IP env required');
if (!GEMINI_API_KEY) throw new Error('GEMINI_API_KEY env required');
// --- G.711 µ-law codec (ITU-T G.711) ---
const MULAW_DECODE = new Int16Array(256);
for (let i = 0; i < 256; i++) {
const u = ~i & 0xff;
let t = ((u & 0x0f) << 3) + 0x84;
t <<= (u & 0x70) >> 4;
MULAW_DECODE[i] = (u & 0x80) ? (0x84 - t) : (t - 0x84);
}
function mulawEncodeSample(s) {
const sign = s < 0 ? 0x80 : 0;
if (sign) s = -s;
if (s > 32635) s = 32635;
s += 0x84;
let exp = 7, m = 0x4000;
while ((s & m) === 0 && exp > 0) { exp--; m >>= 1; }
const mant = (s >> (exp + 3)) & 0x0f;
return ~(sign | (exp << 4) | mant) & 0xff;
}
// --- codec adapters (PCMU narrowband, L16 wideband) ---
// Selects best codec from SDP offer; exposes uniform encode/decode + metadata
// so runCallSession is codec-agnostic.
const CODEC_PCMU = {
name: 'PCMU', rate: 8000, pt: 0, frameSamples: 160, frameBytes: 160,
silence: Buffer.alloc(160, 0xff),
encodeFrame(pcm16) {
const b = Buffer.allocUnsafe(pcm16.length);
for (let i = 0; i < pcm16.length; i++) b[i] = mulawEncodeSample(pcm16[i]);
return b;
},
decodePayload(payload) {
const pcm = new Int16Array(payload.length);
for (let i = 0; i < payload.length; i++) pcm[i] = MULAW_DECODE[payload[i]];
return pcm;
},
sdp(pt) {
return `a=rtpmap:${pt} PCMU/8000\r\n`;
},
};
function makeL16Codec(pt) {
return {
name: 'L16', rate: 16000, pt, frameSamples: 320, frameBytes: 640,
silence: Buffer.alloc(640, 0x00), // Int16 big-endian zero
encodeFrame(pcm16) {
const b = Buffer.allocUnsafe(pcm16.length * 2);
for (let i = 0; i < pcm16.length; i++) b.writeInt16BE(pcm16[i], i * 2);
return b;
},
decodePayload(payload) {
const n = payload.length >> 1;
const pcm = new Int16Array(n);
for (let i = 0; i < n; i++) pcm[i] = payload.readInt16BE(i * 2);
return pcm;
},
sdp(p) {
return `a=rtpmap:${p} L16/16000\r\n`;
},
};
}
// Pick best supported codec from a sdp-transform `media` entry. Returns null if none usable.
function chooseCodec(sdpMedia) {
const rtps = sdpMedia?.rtp || [];
// Prefer L16/16000 (wideband)
const l16 = rtps.find(r => String(r.codec).toUpperCase() === 'L16' && (r.rate === 16000 || !r.rate));
if (l16) return makeL16Codec(l16.payload);
const pcmu = rtps.find(r => String(r.codec).toUpperCase() === 'PCMU' && (r.rate === 8000 || !r.rate));
if (pcmu) return { ...CODEC_PCMU, pt: pcmu.payload };
return null;
}
// --- libsamplerate-based resampler (sinc interpolation, VoIP-grade) ---
// Single instance per (inRate,outRate) per call — stateful streaming.
//
// Quality choice: SRC_SINC_MEDIUM_QUALITY. ~5x cheaper than BEST_QUALITY
// (≈100-tap kernel vs 512), 132 dB SNR — still ≫ 90 dB above G.711's
// inherent ~37 dB SNR floor, so the difference is inaudible on the wire.
// The CPU savings buy back event-loop headroom, which is what actually
// causes audible jitter under concurrent calls — not converter precision.
async function makeResampler(inRate, outRate) {
const src = await createResampler(1, inRate, outRate, {
converterType: ConverterType.SRC_SINC_MEDIUM_QUALITY,
});
return {
process(pcm16) {
const f32in = new Float32Array(pcm16.length);
for (let i = 0; i < pcm16.length; i++) f32in[i] = pcm16[i] / 32768;
const f32out = src.full(f32in);
const out = new Int16Array(f32out.length);
for (let i = 0; i < f32out.length; i++) {
const v = Math.max(-1, Math.min(1, f32out[i])) * 32767;
out[i] = v | 0;
}
return out;
},
destroy() { try { src.destroy(); } catch {} }
};
}
// --- RTP packet builder ---
function buildRtpPacket({ seq, ts, ssrc, payload, payloadType = 0, marker = false }) {
const pkt = Buffer.alloc(12 + payload.length);
pkt[0] = 0x80; // V=2, P=0, X=0, CC=0
pkt[1] = (marker ? 0x80 : 0) | (payloadType & 0x7f);
pkt.writeUInt16BE(seq & 0xffff, 2);
pkt.writeUInt32BE(ts >>> 0, 4);
pkt.writeUInt32BE(ssrc >>> 0, 8);
payload.copy ? payload.copy(pkt, 12) : pkt.set(payload, 12);
return pkt;
}
// --- RTP payload extractor ---
// Honours the CSRC count and the optional header extension (X bit) instead of
// assuming a fixed 12-byte header. rtpengine sets the X bit on transcoded
// WhatsApp/WABA legs; a fixed offset would feed 4 extension bytes to the
// decoder as audio (an audible ~50 Hz buzz over the caller's voice).
function rtpPayload(pkt) {
if (pkt.length < 12) return pkt.subarray(pkt.length);
let off = 12 + (pkt[0] & 0x0f) * 4; // skip CSRC list
if ((pkt[0] & 0x10) && pkt.length >= off + 4) { // X bit → header extension
off += 4 + pkt.readUInt16BE(off + 2) * 4; // 4-byte ext header + words
}
return off <= pkt.length ? pkt.subarray(off) : pkt.subarray(pkt.length);
}
// --- main ---
const srf = new Srf();
let trunkReg = null;
srf.connect({ host: DRACHTIO_HOST, port: parseInt(DRACHTIO_PORT), secret: DRACHTIO_SECRET });
srf.on('connect', (err, hp) => {
if (err) { drachtioConnected = false; return console.error('drachtio', err); }
drachtioConnected = true;
console.log('drachtio connected', hp);
// Register to the carrier so it delivers inbound calls to this server.
if (!trunkReg) trunkReg = startTrunkRegistration(srf, {
domain: SIP_DOMAIN, user: SIP_USER, pass: SIP_PASSWORD,
publicIp: PUBLIC_IP, sipPort: 5060,
});
});
srf.on('error', (err) => { drachtioConnected = false; console.error('drachtio error', err); });
const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
// Separate client pinned to the v1alpha API — required for the conference's
// Proactive Audio (proactivity.proactiveAudio). Inbound 1:1 calls use `ai`.
const aiAlpha = new GoogleGenAI({ apiKey: GEMINI_API_KEY, httpOptions: { apiVersion: 'v1alpha' } });
// Active sessions by callId — allows external (HTTP) control for WABA teardown.
const sessions = new Map();
// Recently-ended sessions — kept ~90s so /v1/calls/:callId/status can return
// `active=false` for late polls instead of 404. (Spec open question 6 / 7.)
const endedSessions = new Map(); // callId → { ended_at: unix-seconds }
const ENDED_SESSION_TTL_MS = 90_000;
let shuttingDown = false;
let drachtioConnected = false;
// Shared session runner — used by both SIP (drachtio) and WABA (HTTP control) paths.
// Takes an already-bound RTP socket + the peer's RTP address, plus caller identity.
// Returns { terminate }.
async function runCallSession({ callId, waId, rtp, localPort, remoteHost, remotePort, codec = CODEC_PCMU, channel = 'pstn', direction = 'inbound', callerName = null, endCall = null, voiceConfig }) {
console.log(`[${callId}] session start waId=${waId || '?'} channel=${channel} codec=${codec.name}/${codec.rate} RTP :${localPort} ↔ ${remoteHost}:${remotePort}`);
// Call metadata → posted as a voice-call summary to the control app on terminate.
const meta = {
waId, callerName, channel, callId,
direction,
status: 'COMPLETED',
endReason: null,
startedAt: new Date().toISOString(),
endedAt: null,
durationSec: 0,
transcript: [],
toolCalls: [],
};
const _startMs = Date.now();
// Caller turns are sourced from Deepgram STT (see DG_ENABLED below) — Gemini's
// own ASR misroutes speakers and skips short bursts. The assistant's turns
// still come from Gemini's `outputTranscription` (the model's literal text —
// exact, and it streams cleanly, unlike re-transcribing its TTS audio).
// Gemini Live owns the conversation and tools throughout.
let assistantBuf = '';
let turnIndex = 0;
// Caller VAD: simple RMS gate on inbound PCM frames; updated in rtp.on('message').
// Used by /v1/calls/:callId/announce to decide when to inject a mid-call announcement.
let lastCallerActivityAt = Date.now();
function emitUserTurn(text) {
const u = String(text || '').trim();
if (!u) return;
const now = new Date().toISOString();
meta.transcript.push({ role: 'user', text: u, ts: now });
postVoiceTurn({ callId, waId, callerName, channel, turnIndex: turnIndex++, role: 'user', text: u, ts: now });
}
// Posts an 'assistant' chat turn from the accumulated Gemini transcript.
function emitAssistantTurn(text) {
const a = String(text || '').trim();
if (!a) return;
const now = new Date().toISOString();
const transcriptText = speakingAnnouncement ? `[announcement] ${a}` : a;
meta.transcript.push({ role: 'assistant', text: transcriptText, ts: now });
postVoiceTurn({ callId, waId, callerName, channel, turnIndex: turnIndex++, role: 'assistant', text: transcriptText, ts: now });
}
function flushAssistantTurn() {
const a = assistantBuf.trim();
assistantBuf = '';
if (!a) {
// Empty turn but an announcement was injected → treat as internal_error so
// the app doesn't wait forever for the ack.
if (speakingAnnouncement) finalizeAnnouncement('dropped', { dropped_reason: 'internal_error' });
return;
}
emitAssistantTurn(a);
// If an announcement drove this turn, ack it as spoken.
if (speakingAnnouncement) finalizeAnnouncement('spoken', { actual_speak_text: a });
}
function pushTurnIfAny() { flushAssistantTurn(); } // kept for terminate path
// Assistant config (system prompt + tools). The inbound-SIP path pre-fetches
// it and passes it in; other paths fetch here. fetchVoiceConfig returns the
// built-in demo agent when no external config service is set, so voiceCfg is
// normally present — a null here means an external service was configured
// but unreachable, so decline the call rather than answer prompt-less.
const voiceCfg = voiceConfig !== undefined
? voiceConfig
: (waId ? await fetchVoiceConfig(waId) : null);
if (!voiceCfg?.systemPrompt) {
console.warn(`[${callId}] no voice config (waId=${waId || 'unknown'}) — declining call, no static fallback`);
try { rtp.close(); } catch {}
try { await endCall?.('no voice config'); } catch {}
meta.status = 'FAILED';
meta.endReason = 'no_voice_config';
meta.endedAt = new Date().toISOString();
meta.durationSec = 0;
postVoiceSummary(meta).catch(() => {});
throw new Error('no_voice_config');
}
console.log(`[${callId}] config loaded waId=${waId} contact=#${voiceCfg.contact?.id ?? '?'} tools=${voiceCfg.tools?.length ?? 0}`);
// Resamplers depend on codec rate. Skip creation when ratio is 1:1.
const rsUp = codec.rate === 16000 ? null : await makeResampler(codec.rate, 16000);
const rsDown = await makeResampler(24000, codec.rate);
// Deepgram STT transcribes the caller leg (16k caller audio) → 'user' turns.
// Aria's turns come from Gemini's outputTranscription. Falls back to Gemini
// ASR for the caller too only if DEEPGRAM_TOKEN is unset.
const DG_ENABLED = !!DEEPGRAM_TOKEN;
let callerDg = null;
if (DG_ENABLED) {
callerDg = startDeepgramStreamAuto({ callId, role: 'caller',
onTurn: (t) => { console.log(`[${callId}] caller(dg): ${t}`); emitUserTurn(t); } });
} else {
console.warn(`[${callId}] DEEPGRAM_TOKEN not set — caller transcript falls back to Gemini ASR`);
}
// RTP send state
const ssrc = (Math.random() * 0xffffffff) >>> 0;
let seq = (Math.random() * 0xffff) & 0xffff;
let ts = (Math.random() * 0xffffffff) >>> 0;
// outbound audio queue (Int16Array at codec rate; 20ms frames = codec.frameSamples)
let outQueue = new Int16Array(0);
let wasSilent = true;
function sendOneRtp() {
let payload, marker = false;
if (outQueue.length >= codec.frameSamples) {
const frame = outQueue.subarray(0, codec.frameSamples);
outQueue = outQueue.subarray(codec.frameSamples);
payload = codec.encodeFrame(frame);
if (wasSilent) { marker = true; wasSilent = false; }
} else {
payload = codec.silence;
wasSilent = true;
}
const pkt = buildRtpPacket({ seq, ts, ssrc, payload, marker, payloadType: codec.pt });
rtp.send(pkt, remotePort, remoteHost);
seq = (seq + 1) & 0xffff;
ts = (ts + codec.frameSamples) >>> 0;
}
// Drift-corrected 20ms pacer — setInterval has 1–10ms Node.js event-loop jitter which
// translates to audible underruns/overruns at the receiver's jitter buffer. This loop
// tracks absolute wall-clock and emits catch-up packets if the loop stalled.
// Gemini output accumulator — flushed on 80ms timer / turnComplete / barge-in.
let pendingOut24 = [];
let pendingOut24Len = 0;
let pendingFlushTimer = null;
function flushOut24() {
if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; }
if (pendingOut24Len === 0) return;
const concat24 = new Int16Array(pendingOut24Len);
let off = 0;
for (const s of pendingOut24) { concat24.set(s, off); off += s.length; }
pendingOut24 = []; pendingOut24Len = 0;
const pcm8 = rsDown.process(concat24);
const merged = new Int16Array(outQueue.length + pcm8.length);
merged.set(outQueue); merged.set(pcm8, outQueue.length);
outQueue = merged;
}
let pacerStopped = false;
let nextSendAt = Date.now();
const PACE_MS = 20;
let pacerTimer = null;
function pace() {
if (pacerStopped) return;
const now = Date.now();
let emitted = 0;
while (nextSendAt <= now && emitted < 10) { // safety cap per tick
sendOneRtp();
nextSendAt += PACE_MS;
emitted++;
}
pacerTimer = setTimeout(pace, Math.max(1, nextSendAt - Date.now()));
}
pace();
const pacer = { clear() { pacerStopped = true; if (pacerTimer) clearTimeout(pacerTimer); } };
// Gemini Live session
let session;
try {
// Prefer the caller-specific locale from the voice config, then the env
// default, then en-US. Pinning the language stops STT from flipping
// mid-call on short or noisy frames.
const GEMINI_LANG = voiceCfg?.locale?.languageCode || process.env.GEMINI_LANGUAGE_CODE || 'en-US';
console.log(`[${callId}] lang=${GEMINI_LANG}`);
// Inject the current wall-clock time so the model can reason about "now" —
// opening hours, today/tomorrow, ETAs. Without it the model falls back to
// training-data time. Timezone is set by AGENT_TIMEZONE (default UTC).
const now = new Date();
const tz = process.env.AGENT_TIMEZONE || 'UTC';
const fmtEn = new Intl.DateTimeFormat('en-US', { timeZone: tz, weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false });
const iso = now.toLocaleString('sv-SE', { timeZone: tz }).replace(' ', 'T') + ` (${tz})`;
const timeBlock =
`\n\n---\n\nCURRENT TIME (use this as "now" when answering about hours, dates, today/tomorrow):\n` +
`- ${fmtEn.format(now)}\n` +
`- ISO: ${iso}\n`;
const endCallGuide =
`\n\n---\n\nENDING THE CALL:\n` +
`You have a tool called \`end_call\` that hangs up the phone. ` +
`Use it when the customer has clearly finished — they say goodbye, thank you and sign off, or explicitly ask to hang up. ` +
`Before calling \`end_call\`, say a short, warm goodbye in voice in the same turn — the line stays open just long enough for it to play. ` +
`Do NOT use \`end_call\` to interrupt the customer, and do NOT mention the tool to them.\n`;
const gemConfig = {
responseModalities: [Modality.AUDIO],
// TTS language + voice for Aria's output. Aoede = warm, natural female voice.
speechConfig: {
languageCode: GEMINI_LANG,
voiceConfig: { prebuiltVoiceConfig: { voiceName: process.env.GEMINI_VOICE || 'Aoede' } },
},
// Transcribe caller speech + model speech — drives the live transcript.
// The transcription config takes no language field (the Gemini API
// rejects `languageCodes`); `{}` simply enables it.
inputAudioTranscription: {},
outputAudioTranscription: {},
// VAD tuning. Production-grade VoIP runs into background noise constantly
// (kitchens, traffic, kids). The previous config (START_HIGH + END_LOW)
// was exactly backwards: any background noise registered as "caller is
// speaking" and the LOW end-sensitivity then waited forever to commit
// turn-end → Aria would sit silent until the noise cleared.
//
// Inversion + tighter windows per:
// - Vertex Live API enum docs (HIGH = trigger more often)
// - sipfront 2026-01 baresip/Gemini Live deep-dive (400–600ms silence)
// - Google ai.google.dev best-practices (20–40ms input chunks, pin language)
//
// Note: silenceDurationMs is silently ignored on gemini-3.1-flash-live-preview
// (js-genai #1467, Apr 2026). Kept for forward-compat — value is what we
// want when the bug is fixed or we move models.
realtimeInputConfig: {
automaticActivityDetection: {
disabled: false,
startOfSpeechSensitivity: 'START_SENSITIVITY_LOW', // ignore background noise
endOfSpeechSensitivity: 'END_SENSITIVITY_HIGH', // commit turn-end faster
prefixPaddingMs: 300, // 200 sometimes clips first phoneme
silenceDurationMs: 600, // 0.6s silence → end-of-turn (when honored)
},
activityHandling: 'START_OF_ACTIVITY_INTERRUPTS', // keep barge-in working
},
// Enable session resumption → Gemini keeps context across WS drops and
// lifts the default hard session cap. We track handles via sessionResumptionUpdate.
sessionResumption: { handle: null },
// Sliding-window compression prevents token-limit truncation on long calls.
contextWindowCompression: { slidingWindow: {} },
systemInstruction: { parts: [{ text: voiceCfg.systemPrompt + timeBlock + endCallGuide }] },
};
// Local tools — always available, regardless of the voice config source.
// `end_call` lets Aria hang up after a goodbye. Local names take precedence over remote
// ones (defensive — prod should never re-declare `end_call`).
const localTools = [
{
name: 'end_call',
description:
'End the current phone call (sends SIP BYE on PSTN, asks Meta to terminate on WABA). ' +
'Use ONLY after you have said a short goodbye in voice. Never use it to interrupt the caller.',
parameters: {
type: 'object',
properties: {
reason: {
type: 'string',
description:
'Short reason for ending the call (e.g. "caller said goodbye", "caller asked for human", "caller abusive").',
},
},
required: ['reason'],
},
},
];
const localToolNames = new Set(localTools.map((t) => t.name));
const remoteTools = (voiceCfg?.tools || []).filter((t) => !localToolNames.has(t.name));
gemConfig.tools = [{ functionDeclarations: [...localTools, ...remoteTools] }];
session = await ai.live.connect({
model: GEMINI_MODEL,
config: gemConfig,
callbacks: {
onopen: () => console.log(`[${callId}] gemini open`),
onmessage: (msg) => {
if (process.env.DEBUG_GEMINI === '1') {
try {
const trace = JSON.stringify(msg, (k, v) => k === 'data' && typeof v === 'string' && v.length > 40 ? `<${v.length}B audio>` : v).slice(0, 400);
console.log(`[${callId}] gemini msg:`, trace);
} catch {}
}
if (msg?.sessionResumptionUpdate?.newHandle) {
// Save latest handle so we could auto-reconnect on drop (future work).
console.log(`[${callId}] gemini resumption handle updated (resumable=${!!msg.sessionResumptionUpdate.resumable})`);
}
if (msg?.goAway) {
console.warn(`[${callId}] gemini goAway: time left ${msg.goAway?.timeLeft || '?'}`);
}
if (msg?.setupComplete) {
console.log(`[${callId}] gemini setupComplete → sending kickoff`);
try {
// Nudge the model to speak first so the caller hears a greeting.
session.sendRealtimeInput({ text: `The caller is now connected. Greet them out loud in ${GEMINI_LANG}.` });
} catch (e) { console.error(`[${callId}] kickoff failed`, e); }
return;
}
// Gemini requested one or more tools — execute each and respond.
if (msg?.toolCall?.functionCalls?.length) {
const calls = msg.toolCall.functionCalls;
console.log(`[${callId}] tools requested: ${calls.map(c => c.name).join(', ')}`);
Promise.all(calls.map(async (fc) => {
const tsIso = new Date().toISOString();
let result;
if (fc.name === 'end_call') {
// Handled locally — schedule hangup after the current speaking turn drains.
const reason = String(fc.args?.reason || 'unspecified').slice(0, 200);
scheduleEndCallAfterTurn(reason);
result = 'ok — call ending. Say a brief goodbye now if you have not already.';
} else {
result = waId
? await execToolRemote(callId, waId, voiceCfg?.conversationId, fc.name, fc.args || {})
: `Error: no caller identity — cannot execute ${fc.name}`;
}
console.log(`[${callId}] ${fc.name} → ${String(result).slice(0, 120)}`);
// Record for call-summary hook.
meta.toolCalls.push({ name: fc.name, args: fc.args || {}, result: String(result), ts: tsIso });
return { id: fc.id, name: fc.name, response: { result } };
})).then((functionResponses) => {
try { session.sendToolResponse({ functionResponses }); }
catch (e) { console.error(`[${callId}] sendToolResponse failed`, e); }
});
return;
}
if (msg?.serverContent?.inputTranscription?.text) {
// Gemini ASR — only used as the chat source when Deepgram is off.
console.log(`[${callId}] caller said: ${msg.serverContent.inputTranscription.text}`);
if (!DG_ENABLED) emitUserTurn(msg.serverContent.inputTranscription.text);
}
if (msg?.serverContent?.outputTranscription?.text) {
assistantBuf += msg.serverContent.outputTranscription.text;
console.log(`[${callId}] gemini said: ${msg.serverContent.outputTranscription.text}`);
}
// Accumulate Gemini audio across multiple WS messages into a single buffer,
// then resample in one batch every ~80ms. Cuts sinc-edge transients by ~10×
// vs per-message resampling. Adds ≤80ms to first-syllable latency.
const parts = msg?.serverContent?.modelTurn?.parts || [];
for (const p of parts) {
const data = p.inlineData?.data;
if (!data) continue;
const buf = Buffer.from(data, 'base64');
const pcm24 = new Int16Array(buf.buffer, buf.byteOffset, buf.byteLength / 2);
pendingOut24.push(pcm24);
pendingOut24Len += pcm24.length;
}
if (pendingOut24Len > 0 && !pendingFlushTimer) {
// 40ms accumulator (was 80ms). Halves first-syllable latency to
// the caller. Edge transients between batches are bounded by
// libsamplerate's internal sinc kernel state — fine at MEDIUM.
pendingFlushTimer = setTimeout(flushOut24, 40);
}
if (msg?.serverContent?.interrupted) {
console.log(`[${callId}] caller barged in — flushing outbound audio`);
outQueue = new Int16Array(0);
pendingOut24 = []; pendingOut24Len = 0;
if (pendingFlushTimer) { clearTimeout(pendingFlushTimer); pendingFlushTimer = null; }
flushAssistantTurn(); // snapshot Aria's partial utterance at barge-in
}
if (msg?.serverContent?.turnComplete) {
console.log(`[${callId}] turn done`);
flushOut24(); // push any last samples immediately so we don't trail off
flushAssistantTurn();
if (endCallPending) executePendingEndCall();
}
},
onerror: (e) => {
console.error(`[${callId}] gemini err`, e?.message || e);
meta.status = 'FAILED'; terminatedReason = `gemini error: ${e?.message || e}`;
},
onclose: (e) => {
console.log(`[${callId}] gemini closed`, e?.reason || '');
if (e?.reason && !terminatedReason) terminatedReason = `gemini closed: ${e.reason}`;
},
}
});
} catch (e) {
console.error(`[${callId}] gemini connect failed`, e);
try { pacer.clear(); } catch {}
try { rtp.close(); } catch {}
meta.status = 'FAILED';
meta.endedAt = new Date().toISOString();
meta.durationSec = Math.max(0, Math.round((Date.now() - _startMs) / 1000));
meta.endReason = `gemini connect failed: ${e?.message || e}`;
postVoiceSummary(meta).catch(() => {});
throw e;
}
// Inbound RTP from caller (or rtpengine for WABA) — buffer 2 packets (40ms) before
// resampling + sending to Gemini. Google's Live API best-practices recommend
// 20–40ms chunks for VAD responsiveness; 60ms (the previous value) lagged the
// VAD enough to feel sluggish under noise.
let inBuf = [];
let inLen = 0;
const IN_BATCH_PACKETS = 2;
rtp.on('message', (pkt) => {
if (pkt.length < 12) return;
const pt = pkt[1] & 0x7f;
if (pt === 101) return; // DTMF – ignore for now
if (pt !== codec.pt) return; // only the negotiated codec
const payload = rtpPayload(pkt);
const pcm = codec.decodePayload(payload);
// Cheap RMS VAD on the just-decoded frame (still at codec rate). Updates
// lastCallerActivityAt whenever energy crosses VAD_RMS, which the announce
// worker uses to gauge "caller silent for N ms".
let sumSq = 0;
for (let i = 0; i < pcm.length; i++) { const s = pcm[i]; sumSq += s * s; }
if (Math.sqrt(sumSq / pcm.length) > VAD_RMS) lastCallerActivityAt = Date.now();
inBuf.push(pcm); inLen += pcm.length;
if (inBuf.length < IN_BATCH_PACKETS) return;
const merged = new Int16Array(inLen);
let off = 0;
for (const s of inBuf) { merged.set(s, off); off += s.length; }
inBuf = []; inLen = 0;
const pcm16 = rsUp ? rsUp.process(merged) : merged; // no-op when codec is already 16k
callerDg?.send(pcm16); // → Deepgram live STT (chat source)
const buf = Buffer.from(pcm16.buffer, pcm16.byteOffset, pcm16.byteLength);
try {
session.sendRealtimeInput({ audio: { data: buf.toString('base64'), mimeType: 'audio/pcm;rate=16000' } });
} catch (e) { /* session may have closed */ }
});
let terminated = false;
const terminate = () => {
if (terminated) return;
terminated = true;
pacer.clear();
// Drain announcement queue + in-flight, ack each as call_ended so the app
// doesn't wait the full 60s grace for missing acks.
if (announcePumpTimer) { clearInterval(announcePumpTimer); announcePumpTimer = null; }
for (const entry of announceQueue) {
if (entry.ttlTimer) clearTimeout(entry.ttlTimer);
ackAnnounce(entry, { status: 'dropped', dropped_reason: 'call_ended' });
}
announceQueue.length = 0;
if (speakingAnnouncement) {
ackAnnounce(speakingAnnouncement, { status: 'dropped', dropped_reason: 'call_ended' });
speakingAnnouncement = null;
}
try { rtp.close(); } catch {}
try { session?.close?.(); } catch {}
// Close Deepgram first: close() flushes any buffered final turn into
// meta.transcript synchronously, before the summary POST below.
try { callerDg?.close(); } catch {}
try { rsUp?.destroy(); } catch {}
try { rsDown.destroy(); } catch {}
sessions.delete(callId);
// Finalize metadata + post summary (non-blocking, idempotent).
pushTurnIfAny();
meta.endedAt = new Date().toISOString();
meta.durationSec = Math.max(0, Math.round((Date.now() - _startMs) / 1000));
if (!meta.endReason) meta.endReason = terminatedReason || 'COMPLETED';
// Stash for /v1/calls/:callId/status late polls (~90s window).
endedSessions.set(callId, { ended_at: Math.floor(new Date(meta.endedAt).getTime() / 1000) });
setTimeout(() => endedSessions.delete(callId), ENDED_SESSION_TTL_MS).unref();
postVoiceSummary(meta).catch((e) => console.error(`[${callId}] summary post failed`, e?.message || e));
console.log(`[${callId}] ended — ${meta.durationSec}s, ${meta.transcript.length} turns, ${meta.toolCalls.length} tool calls`);
};
let terminatedReason = null;
// Hard cap per-call duration to prevent runaway Gemini spend.
const hardCapTimer = setTimeout(() => {
if (sessions.has(callId)) {
console.warn(`[${callId}] hard cap ${MAX_CALL_SECONDS}s reached — terminating`);
terminate();
}
}, MAX_CALL_MS);
const origTerminate = terminate;
const wrapTerminate = () => {
clearTimeout(hardCapTimer);
if (endCallSafetyTimer) { clearTimeout(endCallSafetyTimer); endCallSafetyTimer = null; }
origTerminate();
};
// Agent-initiated hangup ('end_call' tool). On call: stash reason; on next
// turnComplete, wait for outQueue to drain (so the goodbye plays out), then
// run the channel-specific endCall callback (SIP BYE / Meta terminate) and
// finally local teardown.
let endCallPending = null;
let endCallSafetyTimer = null;
function scheduleEndCallAfterTurn(reason) {
if (endCallPending || terminated) return;
endCallPending = { reason };
// Safety: if turnComplete never arrives, hang up after 10s anyway.
endCallSafetyTimer = setTimeout(() => {
if (endCallPending) {
console.warn(`[${callId}] end_call: turnComplete timeout — forcing hangup`);
executePendingEndCall();
}
}, 10_000);
}
function executePendingEndCall() {
if (!endCallPending || terminated) return;
const { reason } = endCallPending;
endCallPending = null;
if (endCallSafetyTimer) { clearTimeout(endCallSafetyTimer); endCallSafetyTimer = null; }
// outQueue is at codec.rate (8k or 16k); estimate playout time + 500ms safety.
const drainMs = Math.ceil((outQueue.length / codec.rate) * 1000) + 500;
console.log(`[${callId}] end_call: draining ${drainMs}ms then hanging up (reason=${reason})`);
setTimeout(async () => {
if (terminated) return;
terminatedReason = `agent ended call: ${reason}`;
meta.endReason = terminatedReason;
try { if (endCall) await endCall(reason); }
catch (e) { console.error(`[${callId}] endCall callback failed:`, e?.message || e); }
wrapTerminate();
}, drainMs);
}
// ── Mid-call announcements (POST /v1/calls/:callId/announce) ─────────────
// Worker pattern: enqueueAnnounce stashes a payload + TTL timer; pumpAnnounceQueue
// polls every 100ms while non-empty and injects when caller is silent and the
// model isn't speaking. flushAssistantTurn detects the spoken result and acks.
// Per-session cap = ANN_QMAX (default 3). One announcement spoken at a time;
// 500ms gap between consecutive ones.
const announceQueue = [];
let speakingAnnouncement = null;
let announcePumpTimer = null;
function modelSpeaking() {
return outQueue.length > 0 || pendingOut24Len > 0 || assistantBuf.length > 0;
}
function announceLang() {
return voiceCfg?.locale?.languageCode || process.env.GEMINI_LANGUAGE_CODE || 'en-US';
}
// Fire ack callback to the app. Best-effort, fire-and-forget.
function ackAnnounce(entry, result) {
if (!entry.ack_callback_url) return;
const body = {
task_id: entry.task_id,
call_id: callId,
status: result.status,
actual_speak_text: result.actual_speak_text || entry.speak_text,
};
if (result.status === 'spoken') body.spoken_at = result.spoken_at || Math.floor(Date.now() / 1000);
if (result.status === 'dropped') body.dropped_reason = result.dropped_reason;
fetch(entry.ack_callback_url, {
method: 'POST',
headers: {
'content-type': 'application/json',
'authorization': `Bearer ${INTERNAL_VOICE_TOKEN}`,
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(5000),
}).then((r) => {
if (!r.ok) console.warn(`[${callId}] announce ack ${result.status} HTTP ${r.status}`);
}).catch((e) => {
console.warn(`[${callId}] announce ack ${result.status} failed: ${e?.message || e}`);
});
}
// Called from flushAssistantTurn when the announcement-driven turn ends, or
// from the queue worker on dropped paths. Clears speakingAnnouncement and
// schedules the next pump after the inter-announcement gap.
function finalizeAnnouncement(status, extra) {
if (!speakingAnnouncement) return;
const entry = speakingAnnouncement;
speakingAnnouncement = null;
ackAnnounce(entry, { status, ...(extra || {}) });
// 500ms gap before next announcement may be considered.
setTimeout(() => { if (!terminated) pumpAnnounceQueue(); }, 500);
}
function pumpAnnounceQueue() {
if (announcePumpTimer || terminated) return;
if (!announceQueue.length && !speakingAnnouncement) return;
announcePumpTimer = setInterval(() => {
if (terminated) {
clearInterval(announcePumpTimer); announcePumpTimer = null;
return;
}
if (speakingAnnouncement) return;
const entry = announceQueue[0];
if (!entry) {
clearInterval(announcePumpTimer); announcePumpTimer = null;
return;
}
// Block injection while the model is speaking, the caller is talking,
// or an end_call hangup is already pending — never speak over a goodbye.
if (modelSpeaking()) return;
if (endCallPending) return;
const silentMs = Date.now() - lastCallerActivityAt;
if (silentMs < entry.wait_for_silence_ms) return;
// Inject.
announceQueue.shift();
if (entry.ttlTimer) { clearTimeout(entry.ttlTimer); entry.ttlTimer = null; }
speakingAnnouncement = entry;
injectAnnouncement(entry);
// Pump pauses until finalizeAnnouncement re-arms it 500ms after speech end.
clearInterval(announcePumpTimer); announcePumpTimer = null;
}, 100);
}
function injectAnnouncement(entry) {
// Option B from the spec: prefixed user turn. The Live SDK's stable surface
// is sendRealtimeInput({text}) which is treated as a user-side turn; works
// on every Live version we've seen. If/when Option A (synthetic system turn)
// is verified for this SDK, swap here.
const wrapped =
`[SYSTEM ANNOUNCEMENT — speak the following verbatim in ${entry.language || announceLang()}, ` +
`then return naturally to the conversation]: ${entry.speak_text}`;
console.log(`[${callId}] announce inject task_id=${entry.task_id} kind=${entry.kind} text="${entry.speak_text.slice(0, 80)}"`);
try {
session.sendRealtimeInput({ text: wrapped });
} catch (e) {
console.error(`[${callId}] announce inject failed`, e?.message || e);
finalizeAnnouncement('dropped', { dropped_reason: 'internal_error' });
}
}
// Public entry from /v1/calls/:callId/announce.
function enqueueAnnounce(payload) {
const speakText = String(payload?.speak_text || '').trim().slice(0, 500);
if (!speakText) return { error: 'invalid_payload', details: 'speak_text required' };
if (announceQueue.length >= ANN_QMAX) {
return { error: 'max_queue_depth', current_depth: announceQueue.length };
}
const waitMs = Math.max(0, parseInt(payload?.wait_for_silence_ms ?? 1500, 10) || 1500);