@fabric-harness/channels 0.21.1 → 0.24.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.
@@ -0,0 +1,1005 @@
1
+ /**
2
+ * Twilio Programmable Voice → governed Harness voice.
3
+ *
4
+ * Runtime-neutral pieces for answering a phone call with `session.voice()`:
5
+ *
6
+ * 1. {@link verifyTwilioVoiceWebhook} authenticates the TwiML webhook (form POST).
7
+ * 2. The application resolves the tenant, case and session for the verified
8
+ * `CallSid` from its own state, then mints a short-lived
9
+ * {@link createTwilioStreamToken | stream token} bound to that `CallSid`.
10
+ * 3. {@link twilioConnectStreamTwiml} answers with `<Connect><Stream>`, carrying
11
+ * the token in a `<Parameter>` (Twilio forbids query strings on stream URLs).
12
+ * 4. The Media Streams WebSocket is attached with {@link attachTwilioMediaStream}.
13
+ * The bridge verifies the token from the `start` message against the
14
+ * stream's `CallSid`, atomically claims its nonce through the application's
15
+ * mandatory `claimStream` (so a replayed token is refused), then calls the
16
+ * application's `resolveCall`, which opens `session.voice()` with
17
+ * server-owned instructions and tools.
18
+ *
19
+ * Identity never comes from unauthenticated stream parameters, and the bridge
20
+ * never forwards stream parameters, DTMF or Twilio metadata to the model.
21
+ * The bridge speaks μ-law 8 kHz mono end to end: configure the voice session
22
+ * with `audioFormat: 'g711_ulaw'` and `sampleRate: 8000`.
23
+ */
24
+ import { readRequestBody } from '@fabric-harness/sdk/channel';
25
+ import { verifyTwilioSignature } from './twilio.js';
26
+ /** `<Parameter>` name that carries the stream token by default. */
27
+ export const TWILIO_STREAM_TOKEN_PARAMETER = 'fabricStreamToken';
28
+ /**
29
+ * Longest stream token {@link createTwilioStreamToken} mints and
30
+ * {@link verifyTwilioStreamToken} accepts. Twilio requires each `<Parameter>`
31
+ * name plus value to be under 500 characters, so this bound leaves room for a
32
+ * parameter name of up to 39 characters, including the default
33
+ * {@link TWILIO_STREAM_TOKEN_PARAMETER}.
34
+ */
35
+ export const TWILIO_STREAM_TOKEN_MAX_LENGTH = 460;
36
+ const CALL_SID = /^CA[0-9a-fA-F]{32}$/;
37
+ const STREAM_SID = /^MZ[0-9a-fA-F]{32}$/;
38
+ const ACCOUNT_SID = /^AC[0-9a-fA-F]{32}$/;
39
+ const PARAMETER_NAME = /^[A-Za-z0-9_.-]{1,64}$/;
40
+ const DTMF_DIGIT = /^[0-9*#A-Da-dw]$/;
41
+ const TOKEN_CONTEXT = 'fabric-twilio-stream-v1.';
42
+ const MIN_SECRET_BYTES = 32;
43
+ const encoder = new TextEncoder();
44
+ const decoder = new TextDecoder();
45
+ /**
46
+ * Build a `<Response><Connect><Stream>` TwiML document. All attribute and text
47
+ * values are XML-escaped; invalid URLs or oversize parameters throw.
48
+ */
49
+ export function twilioConnectStreamTwiml(options) {
50
+ const url = parseUrl(options.streamUrl, 'streamUrl');
51
+ if (url.protocol !== 'wss:')
52
+ throw new Error('Twilio Media Streams require a wss:// stream URL');
53
+ if (url.search || url.hash || url.username || url.password)
54
+ throw new Error('Twilio stream URLs must not contain query strings, fragments or credentials; use parameters');
55
+ const parameters = Object.entries(options.parameters ?? {});
56
+ if (parameters.length > 32)
57
+ throw new Error('Too many Twilio stream parameters');
58
+ for (const [name, value] of parameters) {
59
+ if (!PARAMETER_NAME.test(name))
60
+ throw new Error('Invalid Twilio stream parameter name');
61
+ if (typeof value !== 'string' || name.length + value.length >= 500)
62
+ throw new Error('Twilio stream parameter name and value must be under 500 characters');
63
+ }
64
+ let streamAttributes = ` url="${xml(url.toString())}"`;
65
+ if (options.statusCallback !== undefined) {
66
+ const callback = parseUrl(options.statusCallback, 'statusCallback');
67
+ if (callback.protocol !== 'https:')
68
+ throw new Error('Twilio statusCallback must use https://');
69
+ streamAttributes += ` statusCallback="${xml(callback.toString())}"`;
70
+ if (options.statusCallbackMethod)
71
+ streamAttributes += ` statusCallbackMethod="${options.statusCallbackMethod === 'GET' ? 'GET' : 'POST'}"`;
72
+ }
73
+ const say = options.say ? `<Say>${xml(options.say)}</Say>` : '';
74
+ const body = parameters.map(([name, value]) => `<Parameter name="${xml(name)}" value="${xml(value)}"/>`).join('');
75
+ return `<?xml version="1.0" encoding="UTF-8"?><Response>${say}<Connect><Stream${streamAttributes}>${body}</Stream></Connect></Response>`;
76
+ }
77
+ /** A TwiML response with the XML content type Twilio expects. */
78
+ export function twimlResponse(twiml, init = {}) {
79
+ const headers = new Headers(init.headers);
80
+ headers.set('content-type', 'text/xml; charset=utf-8');
81
+ headers.set('cache-control', 'no-store');
82
+ return new Response(twiml, { ...init, headers });
83
+ }
84
+ function xml(value) {
85
+ return value.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[char] ?? char)
86
+ // Control characters other than tab/newline are not valid XML 1.0.
87
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: stripping invalid XML characters
88
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '');
89
+ }
90
+ function parseUrl(value, name) {
91
+ try {
92
+ return new URL(value);
93
+ }
94
+ catch {
95
+ throw new Error(`Invalid Twilio ${name}`);
96
+ }
97
+ }
98
+ /**
99
+ * Mint an HMAC-SHA256 token binding a Twilio `CallSid` to a tenant, resource
100
+ * and optional session/actor. The token is compact enough for a `<Parameter>`:
101
+ * a binding whose token would exceed {@link TWILIO_STREAM_TOKEN_MAX_LENGTH}
102
+ * characters throws instead of minting a token that could not verify.
103
+ */
104
+ export async function createTwilioStreamToken(options) {
105
+ if (!CALL_SID.test(options.callSid))
106
+ throw new Error('Invalid Twilio CallSid');
107
+ for (const [name, value] of [['tenantId', options.tenantId], ['resourceId', options.resourceId], ['sessionId', options.sessionId], ['actorId', options.actorId]]) {
108
+ if (value === undefined && (name === 'sessionId' || name === 'actorId'))
109
+ continue;
110
+ if (!validBindingValue(value))
111
+ throw new Error(`Invalid Twilio stream binding ${name}`);
112
+ }
113
+ if (!Number.isFinite(options.expiresAt))
114
+ throw new Error('Invalid Twilio stream token expiry');
115
+ const nonceBytes = new Uint8Array(16);
116
+ crypto.getRandomValues(nonceBytes);
117
+ const claims = [options.callSid, options.tenantId, options.resourceId, options.sessionId ?? null, options.actorId ?? null, Math.floor(options.expiresAt / 1000), base64Url(nonceBytes)];
118
+ const payload = base64Url(encoder.encode(JSON.stringify(claims)));
119
+ const key = await hmacKey(options.secret);
120
+ const signature = new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(TOKEN_CONTEXT + payload)));
121
+ const token = `v1.${payload}.${base64Url(signature)}`;
122
+ // Minting and verification share one bound, so every minted token verifies.
123
+ if (token.length > TWILIO_STREAM_TOKEN_MAX_LENGTH) {
124
+ throw new Error(`Twilio stream binding is too large: the token would exceed ${TWILIO_STREAM_TOKEN_MAX_LENGTH} characters; shorten tenantId, resourceId, sessionId or actorId`);
125
+ }
126
+ return token;
127
+ }
128
+ /**
129
+ * Verify a stream token. Returns the claims, or `undefined` for any malformed,
130
+ * tampered, expired, over-long-lived or wrong-call token. Never throws on
131
+ * attacker-controlled input and never reports why verification failed.
132
+ */
133
+ export async function verifyTwilioStreamToken(token, options) {
134
+ if (typeof token !== 'string' || token.length > TWILIO_STREAM_TOKEN_MAX_LENGTH)
135
+ return undefined;
136
+ const parts = token.split('.');
137
+ if (parts.length !== 3 || parts[0] !== 'v1')
138
+ return undefined;
139
+ const [, payload, signature] = parts;
140
+ const signatureBytes = fromBase64Url(signature);
141
+ if (!signatureBytes || signatureBytes.byteLength !== 32)
142
+ return undefined;
143
+ const key = await hmacKey(options.secret);
144
+ // WebCrypto HMAC verification is constant-time.
145
+ if (!(await crypto.subtle.verify('HMAC', key, signatureBytes, encoder.encode(TOKEN_CONTEXT + payload))))
146
+ return undefined;
147
+ const payloadBytes = fromBase64Url(payload);
148
+ if (!payloadBytes)
149
+ return undefined;
150
+ let claims;
151
+ try {
152
+ claims = JSON.parse(decoder.decode(payloadBytes));
153
+ }
154
+ catch {
155
+ return undefined;
156
+ }
157
+ if (!Array.isArray(claims) || claims.length !== 7)
158
+ return undefined;
159
+ const [callSid, tenantId, resourceId, sessionId, actorId, expiresAtSeconds, nonce] = claims;
160
+ if (typeof callSid !== 'string' || callSid !== options.callSid || !CALL_SID.test(callSid))
161
+ return undefined;
162
+ if (!validBindingValue(tenantId) || !validBindingValue(resourceId))
163
+ return undefined;
164
+ if (sessionId !== null && !validBindingValue(sessionId))
165
+ return undefined;
166
+ if (actorId !== null && !validBindingValue(actorId))
167
+ return undefined;
168
+ if (typeof expiresAtSeconds !== 'number' || !Number.isSafeInteger(expiresAtSeconds) || typeof nonce !== 'string' || !nonce)
169
+ return undefined;
170
+ const expiresAt = expiresAtSeconds * 1000;
171
+ const now = options.now ?? Date.now();
172
+ if (expiresAt <= now || expiresAt - now > (options.maxLifetimeMs ?? 15 * 60_000))
173
+ return undefined;
174
+ return {
175
+ callSid, tenantId, resourceId, expiresAt, nonce,
176
+ ...(typeof sessionId === 'string' ? { sessionId } : {}),
177
+ ...(typeof actorId === 'string' ? { actorId } : {}),
178
+ };
179
+ }
180
+ function validBindingValue(value) {
181
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: binding values must be printable
182
+ return typeof value === 'string' && value.length > 0 && value.length <= 128 && !/[\u0000-\u001F\u007F]/.test(value);
183
+ }
184
+ async function hmacKey(secret) {
185
+ const bytes = typeof secret === 'string' ? encoder.encode(secret) : secret;
186
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < MIN_SECRET_BYTES)
187
+ throw new Error('Twilio stream token secret must be at least 32 bytes');
188
+ return crypto.subtle.importKey('raw', bytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
189
+ }
190
+ /**
191
+ * Authenticate a Twilio Voice webhook (`application/x-www-form-urlencoded`
192
+ * POST signed with `X-Twilio-Signature`). Returns `undefined` when the
193
+ * signature, method, size, account or `CallSid` is invalid — answer 403.
194
+ */
195
+ export async function verifyTwilioVoiceWebhook(request, options) {
196
+ if (request.method !== 'POST')
197
+ return undefined;
198
+ const signature = request.headers.get('x-twilio-signature');
199
+ if (!signature || !options.authToken)
200
+ return undefined;
201
+ const body = await readRequestBody(request, options.maxBodyBytes ?? 65_536);
202
+ if (!body)
203
+ return undefined;
204
+ const params = new URLSearchParams(decoder.decode(body));
205
+ if (!(await verifyTwilioSignature(options.authToken, options.url ?? request.url, params, signature)))
206
+ return undefined;
207
+ const callSid = params.get('CallSid') ?? '';
208
+ const accountSid = params.get('AccountSid') ?? '';
209
+ if (!CALL_SID.test(callSid) || !ACCOUNT_SID.test(accountSid))
210
+ return undefined;
211
+ if (options.accountSid !== undefined && accountSid !== options.accountSid)
212
+ return undefined;
213
+ const from = params.get('From');
214
+ const to = params.get('To');
215
+ const direction = params.get('Direction');
216
+ return { callSid, accountSid, params, ...(from ? { from } : {}), ...(to ? { to } : {}), ...(direction ? { direction } : {}) };
217
+ }
218
+ /**
219
+ * Verify the `X-Twilio-Signature` Twilio sends on the Media Streams WebSocket
220
+ * handshake: HMAC-SHA1 over the exact `wss://` URL with no parameters. Twilio
221
+ * documents that the handshake is signed but not the exact URL canonicalisation,
222
+ * so both the URL and its trailing-slash variant are accepted. Treat this as
223
+ * defence in depth; the stream token remains the mandatory call binding.
224
+ */
225
+ export async function verifyTwilioMediaStreamUpgrade(request, options) {
226
+ if (request.method !== 'GET' || request.headers.get('upgrade')?.toLowerCase() !== 'websocket')
227
+ return false;
228
+ const signature = request.headers.get('x-twilio-signature');
229
+ if (!signature || !options.authToken)
230
+ return false;
231
+ const url = options.url ?? request.url.replace(/^https:/i, 'wss:').replace(/^http:/i, 'ws:');
232
+ const variants = [url, url.endsWith('/') ? url.slice(0, -1) : `${url}/`];
233
+ const empty = new URLSearchParams();
234
+ for (const candidate of variants) {
235
+ if (await verifyTwilioSignature(options.authToken, candidate, empty, signature))
236
+ return true;
237
+ }
238
+ return false;
239
+ }
240
+ /** Extract a routable `CallSid` path segment (for per-call Durable Object routing), or `undefined`. */
241
+ export function twilioCallSidFromPath(pathname, prefix) {
242
+ const normalized = prefix.endsWith('/') ? prefix : `${prefix}/`;
243
+ if (!pathname.startsWith(normalized))
244
+ return undefined;
245
+ const rest = pathname.slice(normalized.length).replace(/\/$/, '');
246
+ return CALL_SID.test(rest) ? rest : undefined;
247
+ }
248
+ const BRIDGE_VOICE_OPTIONS = Object.freeze({ audioFormat: 'g711_ulaw', sampleRate: 8000, emitSpeechStopped: true });
249
+ const DEFAULT_LIMITS = {
250
+ startTimeoutMs: 10_000,
251
+ resolveTimeoutMs: 10_000,
252
+ idleTimeoutMs: 15_000,
253
+ maxCallDurationMs: 3_600_000,
254
+ maxMessageBytes: 65_536,
255
+ maxInboundFrameBytes: 1_600,
256
+ maxInboundQueueFrames: 250,
257
+ maxPrerollFrames: 50,
258
+ maxOutboundBufferedBytes: 2 * 1024 * 1024,
259
+ maxUnplayedAudioMs: 180_000,
260
+ outboundFrameBytes: 160,
261
+ maxPendingMarks: 256,
262
+ clearAckTimeoutMs: 5_000,
263
+ maxPendingDtmf: 32,
264
+ dtmfTimeoutMs: 5_000,
265
+ maxPendingTranscripts: 32,
266
+ transcriptTimeoutMs: 5_000,
267
+ closeTimeoutMs: 2_000,
268
+ };
269
+ /** μ-law at 8 kHz: 8 bytes per millisecond. */
270
+ const ULAW_BYTES_PER_MS = 8;
271
+ const MAX_INBOUND_BATCH_BYTES = 3_200;
272
+ /**
273
+ * Bridges one Twilio Media Streams WebSocket to one governed voice session.
274
+ * Create it with {@link attachTwilioMediaStream}.
275
+ */
276
+ export class TwilioMediaStreamBridge {
277
+ socket;
278
+ options;
279
+ /** Resolves once with the close summary. */
280
+ closed;
281
+ resolveClosed;
282
+ limits;
283
+ now;
284
+ abort = new AbortController();
285
+ startedAt;
286
+ state = 'awaiting_start';
287
+ closing = false;
288
+ voice;
289
+ context;
290
+ callSid;
291
+ streamSid;
292
+ startTimer;
293
+ idleTimer;
294
+ durationTimer;
295
+ inbound = [];
296
+ pumping = false;
297
+ inboundFrames = 0;
298
+ outboundFrames = 0;
299
+ // Playback tracking.
300
+ streamAcceptedAt = 0;
301
+ sentAnyAudio = false;
302
+ responseSeq = 0;
303
+ responseActive = false;
304
+ responseSentBytes = 0;
305
+ responsePlayedMs = 0;
306
+ dropAssistantAudio = false;
307
+ speechStoppedAt;
308
+ /**
309
+ * Outstanding playback marks → the cumulative assistant audio bytes and the
310
+ * response-relative milliseconds each acknowledges. Mark names carry a
311
+ * per-call monotonic counter so no two outstanding marks can share a name.
312
+ */
313
+ pendingMarks = new Map();
314
+ markCounter = 0;
315
+ /** Assistant audio bytes sent to Twilio, and those Twilio acknowledged as played. */
316
+ outboundAudioBytes = 0;
317
+ playedAudioBytes = 0;
318
+ /**
319
+ * Assistant audio bytes covered by the latest mark sent. When the mark budget
320
+ * is exhausted, audio past this point waits for a slot: the next echo sends
321
+ * one mark covering the whole untracked tail.
322
+ */
323
+ markedAudioBytes = 0;
324
+ /**
325
+ * Assistant audio bytes a `clear` discarded from Twilio's buffer. They no
326
+ * longer count as playing, but stay unacknowledged (against the unplayed
327
+ * budget) until the fence mark sent after the clear is echoed.
328
+ */
329
+ clearedAudioBytes = 0;
330
+ /** Acknowledgement the latest fence mark stands for, and its deadline. */
331
+ clearFenceBytes = 0;
332
+ clearAckTimer;
333
+ /** Caller DTMF digits, delivered to one `onDtmf` callback at a time. */
334
+ dtmf;
335
+ /** Final transcripts, delivered to one `onTranscript` callback at a time, off the voice event loop. */
336
+ transcripts;
337
+ onAbort = () => { void this.close('aborted'); };
338
+ constructor(socket, options) {
339
+ this.socket = socket;
340
+ this.options = options;
341
+ this.limits = { ...DEFAULT_LIMITS, ...definedOnly(options.limits ?? {}) };
342
+ for (const [name, value] of Object.entries(this.limits)) {
343
+ if (!Number.isSafeInteger(value) || value <= 0)
344
+ throw new Error(`Invalid Twilio media stream limit ${name}`);
345
+ }
346
+ if (this.limits.maxCallDurationMs > 2_147_483_647)
347
+ throw new Error('Twilio call duration exceeds timer range');
348
+ // Fail closed: without an atomic claim a replayed stream token could open a second stream.
349
+ if (typeof options.claimStream !== 'function')
350
+ throw new Error('attachTwilioMediaStream requires claimStream: an atomic single-use claim of the stream token nonce');
351
+ this.now = options.now ?? Date.now;
352
+ this.startedAt = this.now();
353
+ const fail = (reason) => { void this.close(reason); };
354
+ this.dtmf = new BridgeCallbackQueue((item, signal) => options.onDtmf?.(item.digit, item.context, signal), this.limits.maxPendingDtmf, this.limits.dtmfTimeoutMs, this.abort.signal, fail);
355
+ this.transcripts = new BridgeCallbackQueue((item, signal) => options.onTranscript?.(item.event, item.context, signal), this.limits.maxPendingTranscripts, this.limits.transcriptTimeoutMs, this.abort.signal, fail);
356
+ this.closed = new Promise(resolve => { this.resolveClosed = resolve; });
357
+ socket.addEventListener('message', event => this.onMessage(event.data));
358
+ socket.addEventListener('close', () => { void this.close('remote_closed'); });
359
+ socket.addEventListener('error', () => { void this.close('socket_error'); });
360
+ this.startTimer = setTimeout(() => { void this.close('start_timeout'); }, this.limits.startTimeoutMs);
361
+ this.durationTimer = setTimeout(() => { void this.close('duration_limit'); }, this.limits.maxCallDurationMs);
362
+ if (options.signal?.aborted)
363
+ queueMicrotask(this.onAbort);
364
+ else
365
+ options.signal?.addEventListener('abort', this.onAbort, { once: true });
366
+ }
367
+ /** Close the call's stream and voice session. Idempotent. */
368
+ async close(reason = 'closed_by_host') {
369
+ if (this.closing)
370
+ return this.closed;
371
+ this.closing = true;
372
+ this.state = 'closed';
373
+ clearTimeout(this.startTimer);
374
+ clearTimeout(this.idleTimer);
375
+ clearTimeout(this.durationTimer);
376
+ clearTimeout(this.clearAckTimer);
377
+ this.options.signal?.removeEventListener('abort', this.onAbort);
378
+ this.abort.abort();
379
+ this.inbound.length = 0;
380
+ this.dtmf.clear();
381
+ this.transcripts.clear();
382
+ this.pendingMarks.clear();
383
+ try {
384
+ this.socket.close(closeCode(reason), reason);
385
+ }
386
+ catch { }
387
+ const voice = this.voice;
388
+ this.voice = undefined;
389
+ if (voice)
390
+ await closeVoice(voice, this.limits.closeTimeoutMs);
391
+ const summary = {
392
+ reason,
393
+ ...(this.callSid ? { callSid: this.callSid } : {}),
394
+ ...(this.streamSid ? { streamSid: this.streamSid } : {}),
395
+ durationMs: Math.max(0, this.now() - this.startedAt),
396
+ inboundFrames: this.inboundFrames,
397
+ outboundFrames: this.outboundFrames,
398
+ };
399
+ try {
400
+ this.options.onClose?.(summary);
401
+ }
402
+ catch { }
403
+ this.resolveClosed(summary);
404
+ return summary;
405
+ }
406
+ onMessage(data) {
407
+ if (this.closing)
408
+ return;
409
+ const text = messageText(data);
410
+ if (text === undefined) {
411
+ void this.close('protocol_error');
412
+ return;
413
+ }
414
+ if (text.length > this.limits.maxMessageBytes) {
415
+ void this.close('message_too_large');
416
+ return;
417
+ }
418
+ let message;
419
+ try {
420
+ const parsed = JSON.parse(text);
421
+ if (!isRecord(parsed))
422
+ throw new Error('not an object');
423
+ message = parsed;
424
+ }
425
+ catch {
426
+ void this.close('protocol_error');
427
+ return;
428
+ }
429
+ switch (message.event) {
430
+ case 'connected':
431
+ return;
432
+ case 'start':
433
+ if (this.state !== 'awaiting_start') {
434
+ void this.close('protocol_error');
435
+ return;
436
+ }
437
+ void this.handleStart(message);
438
+ return;
439
+ case 'media':
440
+ this.handleMedia(message);
441
+ return;
442
+ case 'mark':
443
+ this.handleMark(message);
444
+ return;
445
+ case 'dtmf':
446
+ this.handleDtmf(message);
447
+ return;
448
+ case 'stop':
449
+ void this.close('stopped');
450
+ return;
451
+ default:
452
+ // Unknown events are ignored for forward compatibility.
453
+ return;
454
+ }
455
+ }
456
+ async handleStart(message) {
457
+ this.state = 'starting';
458
+ clearTimeout(this.startTimer);
459
+ const start = parseStart(message);
460
+ if (start === 'unsupported_media_format' || start === undefined) {
461
+ void this.close(start ?? 'protocol_error');
462
+ return;
463
+ }
464
+ this.callSid = start.callSid;
465
+ this.streamSid = start.streamSid;
466
+ if ((this.options.expectedCallSid !== undefined && start.callSid !== this.options.expectedCallSid)
467
+ || (this.options.accountSid !== undefined && start.accountSid !== this.options.accountSid)) {
468
+ void this.close('unauthorized');
469
+ return;
470
+ }
471
+ this.streamAcceptedAt = this.now();
472
+ this.resetIdle();
473
+ const parameterName = this.options.tokenParameter ?? TWILIO_STREAM_TOKEN_PARAMETER;
474
+ const token = start.customParameters[parameterName];
475
+ delete start.customParameters[parameterName];
476
+ const signal = this.abort.signal;
477
+ const resolveTimer = setTimeout(() => { void this.close('resolve_failed'); }, this.limits.resolveTimeoutMs);
478
+ let binding;
479
+ try {
480
+ binding = await verifyTwilioStreamToken(token, {
481
+ secret: this.options.tokenSecret,
482
+ callSid: start.callSid,
483
+ now: this.now(),
484
+ ...(this.options.maxTokenLifetimeMs !== undefined ? { maxLifetimeMs: this.options.maxTokenLifetimeMs } : {}),
485
+ });
486
+ if (!binding || (await raceAbort(Promise.resolve(this.options.claimStream(binding, start, signal)), signal)) !== true) {
487
+ clearTimeout(resolveTimer);
488
+ void this.close('unauthorized');
489
+ return;
490
+ }
491
+ }
492
+ catch {
493
+ clearTimeout(resolveTimer);
494
+ void this.close('unauthorized');
495
+ return;
496
+ }
497
+ if (this.closing) {
498
+ clearTimeout(resolveTimer);
499
+ return;
500
+ }
501
+ let voice;
502
+ try {
503
+ voice = await this.options.resolveCall({ start, binding, signal, voiceOptions: BRIDGE_VOICE_OPTIONS });
504
+ }
505
+ catch {
506
+ clearTimeout(resolveTimer);
507
+ void this.close('resolve_failed');
508
+ return;
509
+ }
510
+ clearTimeout(resolveTimer);
511
+ if (this.closing) {
512
+ await closeVoice(voice, this.limits.closeTimeoutMs);
513
+ return;
514
+ }
515
+ if (!voice || voice.governed !== true) {
516
+ // Only sessions opened through session.voice() carry server-owned policy.
517
+ if (voice)
518
+ await closeVoice(voice, this.limits.closeTimeoutMs);
519
+ void this.close('resolve_failed');
520
+ return;
521
+ }
522
+ this.voice = voice;
523
+ this.context = { callSid: start.callSid, streamSid: start.streamSid, binding };
524
+ this.state = 'active';
525
+ if (this.inbound.length > 0)
526
+ this.pumpInbound(voice);
527
+ void this.pumpVoice(voice);
528
+ }
529
+ handleMedia(message) {
530
+ if (this.state === 'awaiting_start') {
531
+ void this.close('protocol_error');
532
+ return;
533
+ }
534
+ if (message.streamSid !== undefined && message.streamSid !== this.streamSid) {
535
+ void this.close('protocol_error');
536
+ return;
537
+ }
538
+ const media = message.media;
539
+ if (!isRecord(media) || typeof media.payload !== 'string') {
540
+ void this.close('protocol_error');
541
+ return;
542
+ }
543
+ // Bidirectional streams carry the caller's audio on the inbound track only.
544
+ if (media.track !== undefined && media.track !== 'inbound')
545
+ return;
546
+ if (media.payload.length > Math.ceil(this.limits.maxInboundFrameBytes / 3) * 4) {
547
+ void this.close('message_too_large');
548
+ return;
549
+ }
550
+ const frame = fromBase64(media.payload);
551
+ if (!frame) {
552
+ void this.close('protocol_error');
553
+ return;
554
+ }
555
+ if (frame.byteLength === 0)
556
+ return;
557
+ this.inboundFrames++;
558
+ this.resetIdle();
559
+ if (this.state === 'starting') {
560
+ this.inbound.push(frame);
561
+ if (this.inbound.length > this.limits.maxPrerollFrames)
562
+ this.inbound.shift();
563
+ return;
564
+ }
565
+ if (this.inbound.length >= this.limits.maxInboundQueueFrames) {
566
+ void this.close('backpressure');
567
+ return;
568
+ }
569
+ this.inbound.push(frame);
570
+ const voice = this.voice;
571
+ if (voice)
572
+ this.pumpInbound(voice);
573
+ }
574
+ pumpInbound(voice) {
575
+ if (this.pumping)
576
+ return;
577
+ this.pumping = true;
578
+ void (async () => {
579
+ try {
580
+ while (this.inbound.length > 0 && !this.closing) {
581
+ // Coalesce a backlog into one governed send; a single frame goes out immediately.
582
+ let size = 0;
583
+ let count = 0;
584
+ while (count < this.inbound.length && size + (this.inbound[count]?.byteLength ?? 0) <= MAX_INBOUND_BATCH_BYTES) {
585
+ size += this.inbound[count]?.byteLength ?? 0;
586
+ count++;
587
+ }
588
+ const frames = this.inbound.splice(0, Math.max(1, count));
589
+ await voice.sendAudio(frames.length === 1 ? frames[0] : concat(frames));
590
+ }
591
+ }
592
+ catch (error) {
593
+ // A provider that cannot keep up (VoiceBackpressureError) is backpressure, not a voice fault.
594
+ void this.close(error?.code === 'VOICE_BACKPRESSURE' ? 'backpressure' : 'voice_error');
595
+ }
596
+ finally {
597
+ this.pumping = false;
598
+ }
599
+ })();
600
+ }
601
+ handleMark(message) {
602
+ const mark = message.mark;
603
+ if (!isRecord(mark) || typeof mark.name !== 'string')
604
+ return;
605
+ const pending = this.pendingMarks.get(mark.name);
606
+ if (pending === undefined)
607
+ return;
608
+ this.pendingMarks.delete(mark.name);
609
+ // Twilio echoes a mark once playback reaches it: everything before it was played.
610
+ this.playedAudioBytes = Math.max(this.playedAudioBytes, pending.audioBytes);
611
+ if (pending.seq === this.responseSeq)
612
+ this.responsePlayedMs = Math.max(this.responsePlayedMs, pending.responseMs);
613
+ // The fence after the latest clear (or a later mark) is echoed: the cleared audio left Twilio.
614
+ if (this.clearAckTimer !== undefined && this.playedAudioBytes >= this.clearFenceBytes) {
615
+ clearTimeout(this.clearAckTimer);
616
+ this.clearAckTimer = undefined;
617
+ }
618
+ // A slot freed up: cover any audio sent while the mark budget was exhausted.
619
+ this.markPlayback();
620
+ }
621
+ handleDtmf(message) {
622
+ const context = this.context;
623
+ const dtmf = message.dtmf;
624
+ if (this.state !== 'active' || !context || !isRecord(dtmf) || typeof dtmf.digit !== 'string' || !DTMF_DIGIT.test(dtmf.digit))
625
+ return;
626
+ if (!this.options.onDtmf)
627
+ return;
628
+ // Bounded, ordered, one callback at a time: a flood of digits cannot fan out callbacks.
629
+ this.dtmf.push({ digit: dtmf.digit, context });
630
+ }
631
+ async pumpVoice(voice) {
632
+ try {
633
+ // resolveCall opens the session with emitSpeechStopped, so speech_stopped may arrive.
634
+ // Opened with emitSpeechStopped (BRIDGE_VOICE_OPTIONS), so speech_stopped may arrive.
635
+ for await (const event of voice.events()) {
636
+ if (this.closing)
637
+ return;
638
+ await this.handleVoiceEvent(voice, event);
639
+ if (this.closing)
640
+ return;
641
+ }
642
+ void this.close('voice_ended');
643
+ }
644
+ catch {
645
+ void this.close('voice_error');
646
+ }
647
+ }
648
+ async handleVoiceEvent(voice, event) {
649
+ switch (event.type) {
650
+ case 'audio_delta':
651
+ this.sendAssistantAudio(event.audio);
652
+ return;
653
+ case 'speech_started':
654
+ this.bargeIn(voice, event);
655
+ return;
656
+ case 'speech_stopped':
657
+ this.speechStoppedAt = this.now();
658
+ return;
659
+ case 'response_done':
660
+ if (this.responseActive)
661
+ this.responseActive = false;
662
+ this.dropAssistantAudio = false;
663
+ return;
664
+ case 'transcript': {
665
+ // Queued, never awaited here: a slow transcript consumer must not hold
666
+ // up a following speech_started (clear + cancel) or assistant audio.
667
+ const context = this.context;
668
+ if (context && this.options.onTranscript)
669
+ this.transcripts.push({ event: { role: event.role, text: event.text }, context });
670
+ return;
671
+ }
672
+ case 'error':
673
+ // Governed voice already sanitized and audited the failure.
674
+ void this.close('voice_error');
675
+ return;
676
+ default:
677
+ return;
678
+ }
679
+ }
680
+ sendAssistantAudio(audio) {
681
+ if (this.dropAssistantAudio || audio.byteLength === 0 || !this.streamSid)
682
+ return;
683
+ // Application-level bound on unplayed audio: works even where the socket
684
+ // reports no bufferedAmount (Workers), since only Twilio's mark echoes advance it.
685
+ if ((this.outboundAudioBytes - this.playedAudioBytes + audio.byteLength) / ULAW_BYTES_PER_MS > this.limits.maxUnplayedAudioMs) {
686
+ void this.close('backpressure');
687
+ return;
688
+ }
689
+ const now = this.now();
690
+ if (!this.responseActive) {
691
+ this.responseActive = true;
692
+ this.responseSeq++;
693
+ this.responseSentBytes = 0;
694
+ this.responsePlayedMs = 0;
695
+ if (this.speechStoppedAt !== undefined) {
696
+ this.metric('response_first_audio_ms', now - this.speechStoppedAt);
697
+ this.speechStoppedAt = undefined;
698
+ }
699
+ }
700
+ if (!this.sentAnyAudio) {
701
+ this.sentAnyAudio = true;
702
+ this.metric('call_first_audio_ms', now - this.streamAcceptedAt);
703
+ }
704
+ const frameBytes = this.limits.outboundFrameBytes;
705
+ for (let offset = 0; offset < audio.byteLength; offset += frameBytes) {
706
+ const frame = audio.subarray(offset, offset + frameBytes);
707
+ if (!this.send({ event: 'media', streamSid: this.streamSid, media: { payload: toBase64(frame) } }))
708
+ return;
709
+ this.outboundFrames++;
710
+ this.outboundAudioBytes += frame.byteLength;
711
+ }
712
+ this.responseSentBytes += audio.byteLength;
713
+ this.markPlayback();
714
+ }
715
+ /**
716
+ * Send a playback mark covering all assistant audio sent so far, when some
717
+ * is not yet covered and the mark budget allows. Twilio echoes a mark once
718
+ * playback reaches it, so a mark sent now covers every earlier byte.
719
+ */
720
+ markPlayback() {
721
+ if (!this.streamSid || this.outboundAudioBytes <= this.markedAudioBytes || this.pendingMarks.size >= this.limits.maxPendingMarks)
722
+ return;
723
+ const name = `fh:${this.responseSeq}:${++this.markCounter}`;
724
+ const pending = { seq: this.responseSeq, audioBytes: this.outboundAudioBytes, responseMs: Math.floor(this.responseSentBytes / ULAW_BYTES_PER_MS) };
725
+ if (!this.send({ event: 'mark', streamSid: this.streamSid, mark: { name } }))
726
+ return;
727
+ this.pendingMarks.set(name, pending);
728
+ this.markedAudioBytes = this.outboundAudioBytes;
729
+ }
730
+ bargeIn(voice, interruption) {
731
+ // Unplayed bytes, not the mark count, decide whether playback is outstanding:
732
+ // audio sent past an exhausted mark budget is still queued at Twilio.
733
+ const outstanding = this.responseActive || this.outboundAudioBytes > Math.max(this.playedAudioBytes, this.clearedAudioBytes);
734
+ if (!outstanding || !this.streamSid)
735
+ return;
736
+ const startedAt = this.now();
737
+ const playedMs = this.responsePlayedMs;
738
+ // Stop playback first: Twilio drops buffered audio and echoes pending marks.
739
+ if (!this.send({ event: 'clear', streamSid: this.streamSid }))
740
+ return;
741
+ this.metric('barge_in_clear_ms', this.now() - startedAt);
742
+ if (this.responseActive)
743
+ this.dropAssistantAudio = true;
744
+ // Echoed marks belong to the interrupted response; a new sequence ignores them.
745
+ this.responseSeq++;
746
+ this.responseActive = false;
747
+ // Twilio discards its unplayed buffer on clear and echoes the pending marks,
748
+ // then echoes a mark sent after the clear once its (now empty) buffer drains.
749
+ // Only that echo proves the discarded audio left Twilio, so the cleared bytes
750
+ // stay against the unplayed budget until the fence mark comes back.
751
+ this.pendingMarks.clear();
752
+ this.clearedAudioBytes = this.outboundAudioBytes;
753
+ this.markedAudioBytes = this.outboundAudioBytes;
754
+ this.clearFenceBytes = this.outboundAudioBytes;
755
+ const fence = `fh:${this.responseSeq}:${++this.markCounter}`;
756
+ if (!this.send({ event: 'mark', streamSid: this.streamSid, mark: { name: fence } }))
757
+ return;
758
+ this.pendingMarks.set(fence, { seq: -1, audioBytes: this.outboundAudioBytes, responseMs: 0 });
759
+ // Keep the earliest deadline: repeated clears cannot postpone the acknowledgement.
760
+ this.clearAckTimer ??= setTimeout(() => { void this.close('backpressure'); }, this.limits.clearAckTimeoutMs);
761
+ // Hand the interruption itself to governed voice: it carries the provider
762
+ // reply that was playing when it arrived, so a newer reply is never cancelled.
763
+ void voice.cancelResponse({ playedMs, interruption }).then(() => this.metric('barge_in_cancel_ms', this.now() - startedAt), () => { void this.close('voice_error'); });
764
+ }
765
+ send(message) {
766
+ if (this.closing)
767
+ return false;
768
+ try {
769
+ this.socket.send(JSON.stringify(message));
770
+ }
771
+ catch {
772
+ void this.close('socket_error');
773
+ return false;
774
+ }
775
+ const buffered = this.socket.bufferedAmount;
776
+ if (typeof buffered === 'number' && buffered > this.limits.maxOutboundBufferedBytes) {
777
+ void this.close('backpressure');
778
+ return false;
779
+ }
780
+ return true;
781
+ }
782
+ resetIdle() {
783
+ if (this.closing)
784
+ return;
785
+ clearTimeout(this.idleTimer);
786
+ this.idleTimer = setTimeout(() => { void this.close('idle_timeout'); }, this.limits.idleTimeoutMs);
787
+ }
788
+ metric(name, valueMs) {
789
+ if (!this.options.onMetric || !this.callSid)
790
+ return;
791
+ try {
792
+ this.options.onMetric({ name, valueMs: Math.max(0, valueMs), callSid: this.callSid });
793
+ }
794
+ catch { }
795
+ }
796
+ }
797
+ /**
798
+ * Attach a governed voice bridge to an accepted Twilio Media Streams socket.
799
+ * Works with Node `ws` sockets and Cloudflare Workers sockets alike.
800
+ */
801
+ export function attachTwilioMediaStream(socket, options) {
802
+ return new TwilioMediaStreamBridge(socket, options);
803
+ }
804
+ function parseStart(message) {
805
+ const start = message.start;
806
+ if (!isRecord(start))
807
+ return undefined;
808
+ const { streamSid, callSid, accountSid, tracks, mediaFormat, customParameters } = start;
809
+ if (typeof streamSid !== 'string' || !STREAM_SID.test(streamSid))
810
+ return undefined;
811
+ if (message.streamSid !== undefined && message.streamSid !== streamSid)
812
+ return undefined;
813
+ if (typeof callSid !== 'string' || !CALL_SID.test(callSid))
814
+ return undefined;
815
+ if (typeof accountSid !== 'string' || !ACCOUNT_SID.test(accountSid))
816
+ return undefined;
817
+ if (!Array.isArray(tracks) || !tracks.every(track => typeof track === 'string') || !tracks.includes('inbound'))
818
+ return undefined;
819
+ if (!isRecord(mediaFormat))
820
+ return undefined;
821
+ // Governed telephony runs μ-law 8 kHz mono end to end; anything else fails closed.
822
+ if (mediaFormat.encoding !== 'audio/x-mulaw' || Number(mediaFormat.sampleRate) !== 8000 || Number(mediaFormat.channels) !== 1)
823
+ return 'unsupported_media_format';
824
+ const parameters = {};
825
+ if (customParameters !== undefined) {
826
+ if (!isRecord(customParameters))
827
+ return undefined;
828
+ const entries = Object.entries(customParameters);
829
+ if (entries.length > 32)
830
+ return undefined;
831
+ for (const [name, value] of entries) {
832
+ if (typeof value !== 'string' || !PARAMETER_NAME.test(name) || name.length + value.length >= 500)
833
+ return undefined;
834
+ parameters[name] = value;
835
+ }
836
+ }
837
+ return { streamSid, callSid, accountSid, tracks: [...tracks], mediaFormat: { encoding: 'audio/x-mulaw', sampleRate: 8000, channels: 1 }, customParameters: parameters };
838
+ }
839
+ function closeCode(reason) {
840
+ switch (reason) {
841
+ case 'stopped':
842
+ case 'remote_closed':
843
+ case 'aborted':
844
+ case 'closed_by_host':
845
+ case 'voice_ended': return 1000;
846
+ case 'unauthorized':
847
+ case 'protocol_error':
848
+ case 'unsupported_media_format': return 1008;
849
+ case 'message_too_large': return 1009;
850
+ case 'backpressure': return 1013;
851
+ default: return 1011;
852
+ }
853
+ }
854
+ async function closeVoice(voice, timeoutMs) {
855
+ let timer;
856
+ await Promise.race([
857
+ Promise.resolve().then(() => voice.close()).catch(() => { }),
858
+ new Promise(resolve => { timer = setTimeout(resolve, timeoutMs); }),
859
+ ]);
860
+ clearTimeout(timer);
861
+ }
862
+ function messageText(data) {
863
+ if (typeof data === 'string')
864
+ return data;
865
+ if (data instanceof ArrayBuffer)
866
+ return decoder.decode(new Uint8Array(data));
867
+ if (ArrayBuffer.isView(data))
868
+ return decoder.decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
869
+ return undefined;
870
+ }
871
+ function isRecord(value) {
872
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
873
+ }
874
+ function definedOnly(value) {
875
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
876
+ }
877
+ function concat(frames) {
878
+ const out = new Uint8Array(frames.reduce((sum, frame) => sum + frame.byteLength, 0));
879
+ let offset = 0;
880
+ for (const frame of frames) {
881
+ out.set(frame, offset);
882
+ offset += frame.byteLength;
883
+ }
884
+ return out;
885
+ }
886
+ function toBase64(bytes) {
887
+ let binary = '';
888
+ for (let i = 0; i < bytes.byteLength; i += 0x8000)
889
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
890
+ return btoa(binary);
891
+ }
892
+ function fromBase64(value) {
893
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(value))
894
+ return undefined;
895
+ try {
896
+ const binary = atob(value);
897
+ const out = new Uint8Array(binary.length);
898
+ for (let i = 0; i < binary.length; i++)
899
+ out[i] = binary.charCodeAt(i);
900
+ return out;
901
+ }
902
+ catch {
903
+ return undefined;
904
+ }
905
+ }
906
+ function base64Url(bytes) {
907
+ return toBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
908
+ }
909
+ function fromBase64Url(value) {
910
+ if (!/^[A-Za-z0-9_-]*$/.test(value))
911
+ return undefined;
912
+ const padded = value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (value.length % 4)) % 4);
913
+ return fromBase64(padded);
914
+ }
915
+ /**
916
+ * Settle with `promise`, or reject as soon as `signal` aborts, so a wedged
917
+ * application callback cannot pin the bridge's continuation after close.
918
+ */
919
+ function raceAbort(promise, signal) {
920
+ if (signal.aborted)
921
+ return Promise.reject(signal.reason);
922
+ return new Promise((resolve, reject) => {
923
+ const onAbort = () => reject(signal.reason);
924
+ signal.addEventListener('abort', onAbort, { once: true });
925
+ promise.then((value) => { signal.removeEventListener('abort', onAbort); resolve(value); }, (error) => { signal.removeEventListener('abort', onAbort); reject(error); });
926
+ });
927
+ }
928
+ /**
929
+ * A bounded, ordered application callback queue: one callback runs at a time,
930
+ * at most `maxPending` items wait behind it (overflow fails the call with
931
+ * `backpressure`), each callback is bounded by `timeoutMs` (then
932
+ * `callback_error`), and every callback receives the bridge's abort signal.
933
+ * Items still queued when the signal aborts are dropped.
934
+ */
935
+ class BridgeCallbackQueue {
936
+ deliver;
937
+ maxPending;
938
+ timeoutMs;
939
+ signal;
940
+ fail;
941
+ items = [];
942
+ running = false;
943
+ constructor(deliver, maxPending, timeoutMs, signal, fail) {
944
+ this.deliver = deliver;
945
+ this.maxPending = maxPending;
946
+ this.timeoutMs = timeoutMs;
947
+ this.signal = signal;
948
+ this.fail = fail;
949
+ }
950
+ push(item) {
951
+ if (this.signal.aborted)
952
+ return;
953
+ if (this.items.length >= this.maxPending) {
954
+ this.fail('backpressure');
955
+ return;
956
+ }
957
+ this.items.push(item);
958
+ if (!this.running)
959
+ void this.drain();
960
+ }
961
+ clear() {
962
+ this.items.length = 0;
963
+ }
964
+ async drain() {
965
+ this.running = true;
966
+ const signal = this.signal;
967
+ try {
968
+ while (this.items.length > 0 && !signal.aborted) {
969
+ const item = this.items.shift();
970
+ let timer;
971
+ let onAbort;
972
+ let outcome;
973
+ try {
974
+ outcome = await Promise.race([
975
+ Promise.resolve().then(() => this.deliver(item, signal)).then(() => 'ok', () => 'error'),
976
+ new Promise(resolve => { timer = setTimeout(() => resolve('timeout'), this.timeoutMs); }),
977
+ new Promise(resolve => {
978
+ onAbort = () => resolve('closed');
979
+ if (signal.aborted)
980
+ resolve('closed');
981
+ else
982
+ signal.addEventListener('abort', onAbort, { once: true });
983
+ }),
984
+ ]);
985
+ }
986
+ finally {
987
+ // The call-lifetime signal outlives each item: detach this race's listener.
988
+ clearTimeout(timer);
989
+ if (onAbort)
990
+ signal.removeEventListener('abort', onAbort);
991
+ }
992
+ if (outcome === 'closed')
993
+ return;
994
+ if (outcome !== 'ok') {
995
+ this.fail('callback_error');
996
+ return;
997
+ }
998
+ }
999
+ }
1000
+ finally {
1001
+ this.running = false;
1002
+ }
1003
+ }
1004
+ }
1005
+ //# sourceMappingURL=twilio-voice.js.map