@micdrop/telephony 0.1.0 → 0.2.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/dist/index.mjs CHANGED
@@ -1,3 +1,44 @@
1
+ // src/dtmf.ts
2
+ var DTMF_DIGITS = /^[0-9A-D*#wW]+$/;
3
+ var ROWS = [697, 770, 852, 941];
4
+ var COLUMNS = [1209, 1336, 1477, 1633];
5
+ var KEYPAD = ["123A", "456B", "789C", "*0#D"];
6
+ var TONE = 120;
7
+ var GAP = 80;
8
+ var AMPLITUDE = 0.25 * 32767;
9
+ function checkDtmfDigits(digits) {
10
+ if (typeof digits !== "string" || !DTMF_DIGITS.test(digits)) {
11
+ throw new Error(
12
+ `Invalid DTMF digits "${digits}": use 0-9, *, #, A-D, and w or W to pause`
13
+ );
14
+ }
15
+ return digits;
16
+ }
17
+ function dtmfTones(digits, sampleRate) {
18
+ checkDtmfDigits(digits);
19
+ const parts = [];
20
+ const samples = (ms) => Math.round(sampleRate * ms / 1e3);
21
+ for (const digit of digits) {
22
+ if (digit === "w" || digit === "W") {
23
+ parts.push(Buffer.alloc(samples(digit === "w" ? 500 : 1e3) * 2));
24
+ continue;
25
+ }
26
+ const row = KEYPAD.findIndex((keys) => keys.includes(digit));
27
+ const column = KEYPAD[row].indexOf(digit);
28
+ const low = ROWS[row];
29
+ const high = COLUMNS[column];
30
+ const count = samples(TONE);
31
+ const tone = Buffer.alloc(count * 2);
32
+ for (let i = 0; i < count; i++) {
33
+ const t = i / sampleRate;
34
+ const value = AMPLITUDE * (Math.sin(2 * Math.PI * low * t) + Math.sin(2 * Math.PI * high * t));
35
+ tone.writeInt16LE(Math.round(value), i * 2);
36
+ }
37
+ parts.push(tone, Buffer.alloc(samples(GAP) * 2));
38
+ }
39
+ return Buffer.concat(parts);
40
+ }
41
+
1
42
  // src/g711.ts
2
43
  var MULAW_BIAS = 132;
3
44
  var MULAW_CLIP = 32635;
@@ -78,22 +119,69 @@ function pcm16ToAlaw(pcm) {
78
119
  return bytes;
79
120
  }
80
121
 
81
- // src/xml.ts
82
- function escapeXml(value) {
83
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
122
+ // src/http.ts
123
+ var TelephonyApiError = class extends Error {
124
+ constructor(message, status, body) {
125
+ super(message);
126
+ this.status = status;
127
+ this.body = body;
128
+ this.name = "TelephonyApiError";
129
+ }
130
+ };
131
+ async function callApi(what, url, init) {
132
+ const response = await fetch(url, init);
133
+ const text = await response.text().catch(() => "");
134
+ if (!response.ok) {
135
+ throw new TelephonyApiError(
136
+ `${what} failed: ${response.status} ${text.slice(0, 500)}`.trim(),
137
+ response.status,
138
+ text
139
+ );
140
+ }
141
+ if (!text) return void 0;
142
+ try {
143
+ return JSON.parse(text);
144
+ } catch {
145
+ return text;
146
+ }
147
+ }
148
+ function formBody(fields) {
149
+ const body = new URLSearchParams();
150
+ for (const [key, value] of Object.entries(fields)) {
151
+ if (value === void 0 || value === null) continue;
152
+ if (Array.isArray(value)) {
153
+ for (const item of value) body.append(key, String(item));
154
+ } else {
155
+ body.append(key, String(value));
156
+ }
157
+ }
158
+ return body;
159
+ }
160
+ function sleep(ms) {
161
+ return new Promise((resolve) => setTimeout(resolve, ms));
162
+ }
163
+ function requireOption(value, message) {
164
+ if (value === void 0 || value === null || value === "") {
165
+ throw new Error(message);
166
+ }
167
+ return value;
84
168
  }
85
169
 
86
170
  // src/TelephonyTransport.ts
87
171
  import {
88
172
  DEFAULT_SAMPLE_RATE,
173
+ listenToWebSocket,
89
174
  MicdropTransport,
90
175
  Pcm16Resampler
91
176
  } from "@micdrop/server";
92
177
  var PLAYBACK_MAX_WAIT = 2e4;
93
- var FRAME_IDLE_FLUSH = 80;
178
+ var FRAME_FLUSH_MARGIN = 40;
179
+ var FRAME_MIN_WAIT = 20;
94
180
  var TelephonyTransport = class extends MicdropTransport {
95
181
  /**
96
- * @param socket - The socket the provider opened, as the `ws` server hands it
182
+ * @param socket - The socket the provider opened, as the `ws` server hands
183
+ * it, or a standard WebSocket, the server half of a Cloudflare
184
+ * `WebSocketPair` for instance
97
185
  */
98
186
  constructor(socket) {
99
187
  super();
@@ -113,48 +201,57 @@ var TelephonyTransport = class extends MicdropTransport {
113
201
  this.inputRate = 0;
114
202
  this.outputRate = 0;
115
203
  this.frameRemainder = Buffer.alloc(0);
204
+ // When the audio sent so far will be done playing, at the pace of the line
205
+ this.playoutEnd = 0;
116
206
  this.markCounter = 0;
117
207
  this.playbackWaiters = /* @__PURE__ */ new Map();
118
208
  this.closed = false;
119
- this.onSocketMessage = (data, isBinary) => {
120
- const buffer = Buffer.isBuffer(data) ? data : Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
209
+ this.handedOff = false;
210
+ this.onSocketMessage = (buffer, isBinary) => {
121
211
  try {
122
- this.onProviderMessage(buffer, isBinary);
212
+ this.onProviderMessage(buffer, isBinary ?? false);
123
213
  } catch (error) {
124
- this.log("Unreadable message from the provider:", error);
214
+ this.logger.warn("Unreadable message from the provider", { error });
125
215
  }
126
216
  };
127
217
  this.onSocketClose = (code, reason) => {
128
218
  this.closed = true;
129
219
  this.cancelFrameFlush();
130
220
  this.resolvePlayback();
131
- this.socket.off("message", this.onSocketMessage);
132
- this.socket.off("close", this.onSocketClose);
133
- this.emit("Close", code, reason?.toString() || void 0);
221
+ this.emit("Close", code, reason);
134
222
  };
135
- socket.on("message", this.onSocketMessage);
136
- socket.on("close", this.onSocketClose);
223
+ listenToWebSocket(socket, {
224
+ message: this.onSocketMessage,
225
+ close: this.onSocketClose
226
+ });
137
227
  }
138
228
  get isOpen() {
139
229
  return !this.closed && (this.socket.readyState ?? 1) === 1;
140
230
  }
141
231
  // A phone line has nobody to read the messages of the server
142
232
  send(message) {
143
- if (message.type === "EndCall") this.log("The assistant ends the call");
233
+ if (message.type === "EndCall") {
234
+ this.logger.debug("The assistant ends the call");
235
+ }
144
236
  }
145
237
  sendAudio(audio, sampleRate) {
238
+ if (!(sampleRate > 0) || !Number.isFinite(sampleRate)) {
239
+ throw new Error(
240
+ `${this.constructor.name}: invalid sample rate ${sampleRate} for the assistant voice`
241
+ );
242
+ }
146
243
  if (!this.isOpen) return;
147
244
  const pcm = this.toLineRate(audio, sampleRate);
148
245
  if (pcm.length === 0) return;
149
246
  if (!this.frameDuration) {
150
- this.whenReady(() => this.writeAudio(pcm));
247
+ this.whenReady(() => this.writePacedAudio(pcm));
151
248
  return;
152
249
  }
153
250
  const frameBytes = this.frameBytes;
154
251
  let data = Buffer.concat([this.frameRemainder, pcm]);
155
252
  while (data.length >= frameBytes) {
156
253
  const frame = data.subarray(0, frameBytes);
157
- this.whenReady(() => this.writeAudio(frame));
254
+ this.whenReady(() => this.writePacedAudio(frame));
158
255
  data = data.subarray(frameBytes);
159
256
  }
160
257
  this.frameRemainder = data;
@@ -163,6 +260,7 @@ var TelephonyTransport = class extends MicdropTransport {
163
260
  clearAudio() {
164
261
  this.cancelFrameFlush();
165
262
  this.frameRemainder = Buffer.alloc(0);
263
+ this.playoutEnd = 0;
166
264
  this.pendingWrites = [];
167
265
  if (this.ready && this.isOpen) this.writeClear();
168
266
  this.resolvePlayback();
@@ -173,7 +271,7 @@ var TelephonyTransport = class extends MicdropTransport {
173
271
  const name = `micdrop-${++this.markCounter}`;
174
272
  return new Promise((resolve) => {
175
273
  const timer = setTimeout(() => {
176
- this.log("The provider never confirmed the playback");
274
+ this.logger.warn("The provider never confirmed the playback");
177
275
  done();
178
276
  }, PLAYBACK_MAX_WAIT);
179
277
  const done = () => {
@@ -188,17 +286,136 @@ var TelephonyTransport = class extends MicdropTransport {
188
286
  /**
189
287
  * Ends the stream, and the call with it: closing the socket is enough for
190
288
  * the providers that end the call when nothing follows the stream, the
191
- * others hang up through their API in `hangUp()`
289
+ * others hang up through their API in `hangUp()`. A call transferred
290
+ * elsewhere goes on without the assistant.
192
291
  */
193
292
  close(code = 1e3, reason) {
194
293
  if (this.closed) return;
195
294
  this.cancelFrameFlush();
196
- this.hangUp().catch((error) => this.log("Hang up failed:", error));
295
+ if (!this.handedOff) {
296
+ this.hangUp().catch(
297
+ (error) => this.logger.error("Hang up failed", { error })
298
+ );
299
+ }
197
300
  if ((this.socket.readyState ?? 1) <= 1) this.socket.close(code, reason);
198
301
  }
302
+ /**
303
+ * Sends keys on the line, to navigate the menu of the phone system the
304
+ * assistant called. Resolves once they have been sent.
305
+ *
306
+ * Providers that send keys through their API or their stream do it there.
307
+ * The others carry them in the audio, as the dual tones of a keypad.
308
+ *
309
+ * @param digits - Keys among 0-9, *, # and A-D, with `w` for a pause of
310
+ * 0.5 s and `W` for 1 s
311
+ */
312
+ async sendDtmf(digits) {
313
+ checkDtmfDigits(digits);
314
+ this.logger.debug("Sending DTMF in the audio", { digits });
315
+ this.sendAudio(dtmfTones(digits, this.lineRate), this.lineRate);
316
+ await this.waitForPlayback();
317
+ }
318
+ /**
319
+ * Sends keys a piece at a time, waiting where they ask for a pause, for the
320
+ * providers that take no pause in the keys they send
321
+ * @param send - Sends keys without pauses
322
+ */
323
+ async sendDtmfWithPauses(digits, send) {
324
+ checkDtmfDigits(digits);
325
+ for (const part of digits.split(/([wW]+)/)) {
326
+ if (!part) continue;
327
+ if (/^[wW]+$/.test(part)) {
328
+ let pause = 0;
329
+ for (const char of part) pause += char === "w" ? 500 : 1e3;
330
+ await new Promise((resolve) => setTimeout(resolve, pause));
331
+ } else {
332
+ await send(part);
333
+ }
334
+ }
335
+ }
336
+ /** The number of the account on the call, to call from in a transfer */
337
+ get ownNumber() {
338
+ return this.call.direction === "outbound" ? this.call.from : this.call.to;
339
+ }
340
+ /**
341
+ * Sends the call to another number, and leaves it: the assistant is no
342
+ * longer on the line once it resolves. Rejects when the provider refuses.
343
+ *
344
+ * @param options - Where to send the call
345
+ */
346
+ async transfer(options) {
347
+ throw new Error(
348
+ `${this.constructor.name} cannot transfer calls (to ${options.to})`
349
+ );
350
+ }
351
+ /**
352
+ * Reaches a person first, tells them about the call, then connects the
353
+ * caller to them and leaves. The assistant stays on the line with the
354
+ * caller while the phone rings, and keeps it when nobody takes the call.
355
+ *
356
+ * @param options - Who to reach, and what to tell them
357
+ * @returns Whether the caller was connected, or why not
358
+ */
359
+ async warmTransfer(options) {
360
+ throw new Error(
361
+ `${this.constructor.name} cannot make warm transfers (to ${options.to})`
362
+ );
363
+ }
364
+ /**
365
+ * Takes the result of the answering machine detection of the provider,
366
+ * which reaches the server through a webhook for most of them.
367
+ * `TelephonyCalls` routes the webhooks of a server to the right transport.
368
+ */
369
+ receiveMachineDetection(detection) {
370
+ const answeredBy = detection.answeredBy === "unknown" && this.machineDetection ? this.machineDetection.answeredBy : detection.answeredBy;
371
+ this.machineDetection = { ...detection, answeredBy };
372
+ this.logger.info("Machine detection", { ...this.machineDetection });
373
+ this.emit("MachineDetection", this.machineDetection);
374
+ }
375
+ /**
376
+ * Resolves with the result of the answering machine detection, as soon as
377
+ * there is one, or undefined once `timeout` ms passed without any
378
+ */
379
+ waitForMachineDetection(timeout = 1e4) {
380
+ if (this.machineDetection) return Promise.resolve(this.machineDetection);
381
+ return new Promise((resolve) => {
382
+ const done = (detection) => {
383
+ clearTimeout(timer);
384
+ this.off("MachineDetection", done);
385
+ this.off("Close", onClose);
386
+ resolve(detection);
387
+ };
388
+ const onClose = () => done();
389
+ const timer = setTimeout(done, timeout);
390
+ this.on("MachineDetection", done);
391
+ this.on("Close", onClose);
392
+ });
393
+ }
199
394
  /** Hangs up through the API of the provider, for those that need it */
200
395
  async hangUp() {
201
396
  }
397
+ /**
398
+ * The call now goes on without the assistant: ends the stream without
399
+ * hanging up
400
+ * @param to - Where the call went
401
+ */
402
+ handOff(to) {
403
+ this.logger.info("Call transferred", { to });
404
+ this.handedOff = true;
405
+ this.transferredTo = to;
406
+ this.clearAudio();
407
+ this.emit("Transferred", to);
408
+ this.close(1e3, "Transferred");
409
+ }
410
+ /**
411
+ * Ends the call on a misconfiguration that would leave it garbled or
412
+ * silent, and says why where it cannot be missed
413
+ * @param reason - What is wrong, and how to fix it
414
+ */
415
+ fail(reason) {
416
+ this.logger.error("Misconfigured call", { reason });
417
+ this.close(1011, reason.slice(0, 120));
418
+ }
202
419
  /**
203
420
  * The stream has started: keeps what the provider said about the call and
204
421
  * sends the audio that waited for it
@@ -207,7 +424,7 @@ var TelephonyTransport = class extends MicdropTransport {
207
424
  */
208
425
  startStream(call, params) {
209
426
  this.call = { ...this.call, ...call };
210
- this.log("Stream started", this.call);
427
+ this.logger.info("Stream started", { ...this.call });
211
428
  this.ready = true;
212
429
  const writes = this.pendingWrites;
213
430
  this.pendingWrites = [];
@@ -234,8 +451,19 @@ var TelephonyTransport = class extends MicdropTransport {
234
451
  }
235
452
  /** A key was pressed on the keypad of the phone */
236
453
  receiveDtmf(digit) {
237
- this.log(`DTMF ${digit}`);
238
- this.emit("Dtmf", digit);
454
+ const key = String(digit ?? "");
455
+ if (!/^[0-9A-D*#]$/i.test(key)) {
456
+ this.logger.warn("Unreadable DTMF digit ignored", { key });
457
+ return;
458
+ }
459
+ this.logger.debug("DTMF", { key });
460
+ this.emit("Dtmf", key.toUpperCase());
461
+ }
462
+ /** Writes audio, keeping track of when the provider will be done playing it */
463
+ writePacedAudio(pcm) {
464
+ const duration = pcm.length / 2 / this.lineRate * 1e3;
465
+ this.playoutEnd = Math.max(this.playoutEnd, Date.now()) + duration;
466
+ this.writeAudio(pcm);
239
467
  }
240
468
  /** Bytes in one outgoing frame */
241
469
  get frameBytes() {
@@ -261,12 +489,20 @@ var TelephonyTransport = class extends MicdropTransport {
261
489
  const frame = Buffer.alloc(this.frameBytes);
262
490
  this.frameRemainder.copy(frame);
263
491
  this.frameRemainder = Buffer.alloc(0);
264
- this.whenReady(() => this.writeAudio(frame));
492
+ this.whenReady(() => this.writePacedAudio(frame));
265
493
  }
494
+ /**
495
+ * Sends the incomplete frame left once the provider is about to run out of
496
+ * audio, if the rest of the answer has not come by then
497
+ */
266
498
  scheduleFrameFlush() {
267
499
  this.cancelFrameFlush();
268
500
  if (this.frameRemainder.length === 0) return;
269
- this.frameTimer = setTimeout(() => this.flushFrame(), FRAME_IDLE_FLUSH);
501
+ const delay = Math.max(
502
+ this.playoutEnd - Date.now() - FRAME_FLUSH_MARGIN,
503
+ FRAME_MIN_WAIT
504
+ );
505
+ this.frameTimer = setTimeout(() => this.flushFrame(), delay);
270
506
  }
271
507
  cancelFrameFlush() {
272
508
  if (!this.frameTimer) return;
@@ -285,11 +521,18 @@ function parseJson(data) {
285
521
  }
286
522
  }
287
523
 
524
+ // src/xml.ts
525
+ function escapeXml(value) {
526
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
527
+ }
528
+
288
529
  // src/plivo.ts
530
+ var API = "https://api.plivo.com/v1";
531
+ var DTMF_KEY_DURATION = 250;
289
532
  var PlivoTransport = class extends TelephonyTransport {
290
533
  /**
291
534
  * @param socket - The socket Plivo opened
292
- * @param options - Credentials to hang up with
535
+ * @param options - Credentials to hang up and transfer with
293
536
  */
294
537
  constructor(socket, options = {}) {
295
538
  super(socket);
@@ -303,6 +546,13 @@ var PlivoTransport = class extends TelephonyTransport {
303
546
  switch (message?.event) {
304
547
  case "start": {
305
548
  const start = message.start ?? {};
549
+ const format = start.mediaFormat;
550
+ if (format && (format.encoding !== "audio/x-mulaw" || Number(format.sampleRate) !== 8e3)) {
551
+ this.fail(
552
+ `Plivo streams ${format.encoding} at ${format.sampleRate} Hz, PlivoTransport reads audio/x-mulaw at 8000 Hz: set the contentType of the <Stream>, as plivoStreamXml() does`
553
+ );
554
+ return;
555
+ }
306
556
  this.startStream(
307
557
  {
308
558
  callId: start.callId,
@@ -324,7 +574,7 @@ var PlivoTransport = class extends TelephonyTransport {
324
574
  this.markPlayed(message.name);
325
575
  break;
326
576
  case "dtmf":
327
- this.receiveDtmf(String(message.dtmf?.digit));
577
+ this.receiveDtmf(message.dtmf?.digit);
328
578
  break;
329
579
  }
330
580
  }
@@ -344,23 +594,80 @@ var PlivoTransport = class extends TelephonyTransport {
344
594
  writeMark(name) {
345
595
  this.sendJson({ event: "checkpoint", streamId: this.call.streamId, name });
346
596
  }
597
+ /** Sends the keys over the stream, which Plivo plays on the call */
598
+ async sendDtmf(digits) {
599
+ await this.sendDtmfWithPauses(digits, async (keys) => {
600
+ this.sendJson({ event: "sendDTMF", dtmf: keys });
601
+ await new Promise(
602
+ (resolve) => setTimeout(resolve, keys.length * DTMF_KEY_DURATION)
603
+ );
604
+ });
605
+ }
606
+ /**
607
+ * Transfers the call to the XML at `transferUrl`, which dials the
608
+ * destination and ends the stream
609
+ */
610
+ async transfer(options) {
611
+ const { authId, authToken, transferUrl } = this.options;
612
+ const callId = requireOption(
613
+ this.call.callId,
614
+ "PlivoTransport: the stream has not started, the call is unknown"
615
+ );
616
+ const url = requireOption(
617
+ transferUrl?.(options),
618
+ "PlivoTransport needs transferUrl, a route that answers with plivoTransferXml(), to transfer a call"
619
+ );
620
+ const api = plivoApi({
621
+ authId: requireOption(
622
+ authId,
623
+ "PlivoTransport needs authId and authToken to transfer a call"
624
+ ),
625
+ authToken: requireOption(
626
+ authToken,
627
+ "PlivoTransport needs authId and authToken to transfer a call"
628
+ )
629
+ });
630
+ await api(
631
+ "Plivo transfer",
632
+ "POST",
633
+ `/Call/${encodeURIComponent(callId)}/`,
634
+ {
635
+ legs: "aleg",
636
+ aleg_url: url,
637
+ aleg_method: "POST"
638
+ }
639
+ );
640
+ this.handOff(options.to);
641
+ }
347
642
  async hangUp() {
348
643
  const { authId, authToken } = this.options;
349
644
  const callId = this.call.callId;
350
645
  if (!authId || !authToken || !callId) return;
351
- const credentials = Buffer.from(`${authId}:${authToken}`).toString("base64");
352
- const response = await fetch(
353
- `https://api.plivo.com/v1/Account/${encodeURIComponent(authId)}/Call/${encodeURIComponent(callId)}/`,
354
- { method: "DELETE", headers: { Authorization: `Basic ${credentials}` } }
355
- );
356
- if (!response.ok && response.status !== 404) {
357
- throw new Error(`Plivo answered ${response.status} to the hang up`);
646
+ try {
647
+ await plivoApi({ authId, authToken })(
648
+ "Plivo hang up",
649
+ "DELETE",
650
+ `/Call/${encodeURIComponent(callId)}/`
651
+ );
652
+ } catch (error) {
653
+ if (error?.status !== 404) throw error;
358
654
  }
359
655
  }
360
656
  sendJson(message) {
361
657
  if (this.isOpen) this.socket.send(JSON.stringify(message));
362
658
  }
363
659
  };
660
+ function plivoApi({ authId, authToken }) {
661
+ const authorization = `Basic ${Buffer.from(`${authId}:${authToken}`).toString("base64")}`;
662
+ return (what, method, path, body) => callApi(what, `${API}/Account/${encodeURIComponent(authId)}${path}`, {
663
+ method,
664
+ headers: {
665
+ Authorization: authorization,
666
+ ...body ? { "Content-Type": "application/json" } : {}
667
+ },
668
+ ...body ? { body: JSON.stringify(body) } : {}
669
+ });
670
+ }
364
671
  function parseExtraHeaders(headers) {
365
672
  const params = {};
366
673
  if (typeof headers !== "string") return params;
@@ -376,16 +683,223 @@ function plivoStreamXml({ url, parameters = {} }) {
376
683
  const extra = extraHeaders ? ` extraHeaders="${escapeXml(extraHeaders)}"` : "";
377
684
  return `<?xml version="1.0" encoding="UTF-8"?><Response><Stream bidirectional="true" keepCallAlive="true" contentType="audio/x-mulaw;rate=8000"${extra}>${escapeXml(url)}</Stream></Response>`;
378
685
  }
686
+ function plivoTransferXml({ to, from, timeout }) {
687
+ const attributes = [
688
+ from ? ` callerId="${escapeXml(from)}"` : "",
689
+ timeout ? ` timeout="${Math.round(timeout)}"` : ""
690
+ ].join("");
691
+ const target = /^sips?:/i.test(to) ? `<User>${escapeXml(to)}</User>` : `<Number>${escapeXml(to.replace(/^\+/, ""))}</Number>`;
692
+ return `<?xml version="1.0" encoding="UTF-8"?><Response><Dial${attributes}>${target}</Dial></Response>`;
693
+ }
694
+ async function plivoCall(options) {
695
+ const { to, from, answerUrl, timeout, machineDetection } = options;
696
+ if (machineDetection && !options.machineDetectionUrl) {
697
+ throw new Error(
698
+ "plivoCall: machineDetection needs machineDetectionUrl, where Plivo posts the result"
699
+ );
700
+ }
701
+ const result = await plivoApi(options)(
702
+ "Plivo call creation",
703
+ "POST",
704
+ "/Call/",
705
+ {
706
+ to: to.replace(/^\+/, ""),
707
+ from: from.replace(/^\+/, ""),
708
+ answer_url: answerUrl,
709
+ answer_method: "POST",
710
+ ...timeout ? { ring_timeout: Math.round(timeout) } : {},
711
+ ...machineDetection ? {
712
+ machine_detection: "true",
713
+ machine_detection_url: options.machineDetectionUrl,
714
+ machine_detection_method: "POST"
715
+ } : {}
716
+ }
717
+ );
718
+ return { requestId: result?.request_uuid };
719
+ }
720
+ function plivoMachineDetection(params) {
721
+ const get = (key) => params instanceof URLSearchParams ? params.get(key) : params[key];
722
+ const callId = get("CallUUID");
723
+ const machine = get("Machine");
724
+ if (!callId || machine === void 0 || machine === null) return void 0;
725
+ const raw = Object.fromEntries(
726
+ params instanceof URLSearchParams ? params : Object.entries(params)
727
+ );
728
+ return {
729
+ callId,
730
+ detection: {
731
+ answeredBy: String(machine) === "true" ? "machine" : "human",
732
+ greetingEnded: false,
733
+ raw
734
+ }
735
+ };
736
+ }
737
+
738
+ // src/signatures.ts
739
+ import {
740
+ createHash,
741
+ createHmac,
742
+ createPublicKey,
743
+ timingSafeEqual,
744
+ verify
745
+ } from "crypto";
746
+ function validateTwilioSignature({
747
+ authToken,
748
+ signature,
749
+ url,
750
+ params
751
+ }) {
752
+ if (!authToken || !signature) return false;
753
+ const fields = entries(params);
754
+ const data = [...new Set(fields.map(([key]) => key))].sort().map(
755
+ (key) => [...new Set(fields.filter(([k]) => k === key).map(([, value]) => value))].sort().map((value) => key + value).join("")
756
+ ).join("");
757
+ const urls = urlVariants(url);
758
+ if (/^wss?:/i.test(url) && !new URL(url).pathname.endsWith("/")) {
759
+ urls.push(...urlVariants(url.replace(/(\?|$)/, "/$1")));
760
+ }
761
+ return urls.some(
762
+ (candidate) => safeEqual(
763
+ createHmac("sha1", authToken).update(candidate + data).digest("base64"),
764
+ signature
765
+ )
766
+ );
767
+ }
768
+ var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
769
+ function validateTelnyxSignature({
770
+ publicKey,
771
+ signature,
772
+ timestamp,
773
+ body,
774
+ tolerance = 300
775
+ }) {
776
+ if (!publicKey || !signature || !timestamp) return false;
777
+ if (!/^\d+$/.test(timestamp)) return false;
778
+ if (Math.abs(Date.now() / 1e3 - Number(timestamp)) > tolerance) return false;
779
+ const raw = Buffer.from(publicKey, "base64");
780
+ if (raw.length !== 32) {
781
+ throw new Error(
782
+ "validateTelnyxSignature: the public key must be the 32 bytes in base64 the Telnyx portal shows"
783
+ );
784
+ }
785
+ const sig = Buffer.from(signature, "base64");
786
+ if (sig.length !== 64) return false;
787
+ try {
788
+ const key = createPublicKey({
789
+ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]),
790
+ format: "der",
791
+ type: "spki"
792
+ });
793
+ return verify(null, Buffer.from(`${timestamp}|${body}`), key, sig);
794
+ } catch {
795
+ return false;
796
+ }
797
+ }
798
+ function validateVonageSignature({
799
+ signatureSecret,
800
+ authorization,
801
+ body,
802
+ tolerance = 300
803
+ }) {
804
+ if (!signatureSecret || !authorization) return false;
805
+ const token = authorization.replace(/^Bearer\s+/i, "");
806
+ const parts = token.split(".");
807
+ if (parts.length !== 3) return false;
808
+ const [header, payload, signature] = parts;
809
+ const decode = (part) => {
810
+ try {
811
+ return JSON.parse(Buffer.from(part, "base64url").toString());
812
+ } catch {
813
+ return void 0;
814
+ }
815
+ };
816
+ if (decode(header)?.alg !== "HS256") return false;
817
+ const expected = createHmac("sha256", signatureSecret).update(`${header}.${payload}`).digest("base64url");
818
+ if (!safeEqual(expected, signature)) return false;
819
+ const claims = decode(payload);
820
+ if (!claims) return false;
821
+ const now = Date.now() / 1e3;
822
+ if (typeof claims.exp === "number" && claims.exp < now) return false;
823
+ if (typeof claims.iat === "number" && now - claims.iat > tolerance) {
824
+ return false;
825
+ }
826
+ if (body && claims.payload_hash) {
827
+ const hash = createHash("sha256").update(body).digest("hex");
828
+ if (!safeEqual(hash, String(claims.payload_hash).toLowerCase())) {
829
+ return false;
830
+ }
831
+ }
832
+ return true;
833
+ }
834
+ function validatePlivoSignature({
835
+ authToken,
836
+ signature,
837
+ nonce,
838
+ url,
839
+ method,
840
+ params
841
+ }) {
842
+ if (!authToken || !signature || !nonce) return false;
843
+ const parsed = new URL(url);
844
+ const base = `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
845
+ const post = method.toUpperCase() === "POST";
846
+ const query = sortedGroups([
847
+ ...entries(parsed.searchParams),
848
+ ...post ? [] : entries(params)
849
+ ]).flatMap(([key, values]) => values.map((value) => `${key}=${value}`)).join("&");
850
+ const fields = post ? entries(params) : [];
851
+ let data = query ? `${base}?${query}` : base;
852
+ if (fields.length) {
853
+ data = `${base}?${query}${query ? "." : ""}`;
854
+ data += sortedGroups(fields).map(([key, values]) => values.map((value) => key + value).join("")).join("");
855
+ }
856
+ const expected = createHmac("sha256", authToken).update(`${data}.${nonce}`).digest("base64");
857
+ return signature.split(",").some((candidate) => safeEqual(expected, candidate));
858
+ }
859
+ function entries(params) {
860
+ if (!params) return [];
861
+ if (params instanceof URLSearchParams) return [...params.entries()];
862
+ return Object.entries(params).flatMap(
863
+ ([key, value]) => Array.isArray(value) ? value.map((item) => [key, String(item)]) : [[key, String(value ?? "")]]
864
+ );
865
+ }
866
+ function sortedGroups(fields) {
867
+ const groups = /* @__PURE__ */ new Map();
868
+ for (const [key, value] of fields) {
869
+ groups.set(key, [...groups.get(key) ?? [], value]);
870
+ }
871
+ return [...groups.keys()].sort().map((key) => [key, groups.get(key).sort()]);
872
+ }
873
+ function urlVariants(url) {
874
+ const parsed = new URL(url);
875
+ const secure = /^(https|wss):$/.test(parsed.protocol);
876
+ const port = parsed.port || (secure ? "443" : "80");
877
+ const authority = (withPort) => `${parsed.protocol}//${parsed.hostname}${withPort ? `:${port}` : ""}`;
878
+ const rest = url.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i, "");
879
+ return [.../* @__PURE__ */ new Set([url, authority(false) + rest, authority(true) + rest])];
880
+ }
881
+ function safeEqual(a, b) {
882
+ const left = Buffer.from(a);
883
+ const right = Buffer.from(b);
884
+ return left.length === right.length && timingSafeEqual(left, right);
885
+ }
379
886
 
380
887
  // src/telnyx.ts
888
+ var API2 = "https://api.telnyx.com/v2";
889
+ var DEFAULT_VOICE = "AWS.Polly.Joanna-Neural";
890
+ var DEFAULT_RING_TIMEOUT = 30;
891
+ var OUTBOUND_KEY = "micdropOutbound";
892
+ var TRANSFER_KEY = "micdropTransferOf";
381
893
  var TelnyxTransport = class extends TelephonyTransport {
382
894
  /**
383
895
  * @param socket - The socket Telnyx opened
384
- * @param options - Codec of the stream and key to hang up with
896
+ * @param options - Codec of the stream, and what Call Control needs
385
897
  */
386
898
  constructor(socket, options = {}) {
387
899
  super(socket);
388
900
  this.options = options;
901
+ // Events of a transfer that came before Telnyx answered the dial
902
+ this.earlyTransferEvents = [];
389
903
  this.codec = options.codec ?? "PCMU";
390
904
  }
391
905
  get lineRate() {
@@ -396,16 +910,32 @@ var TelnyxTransport = class extends TelephonyTransport {
396
910
  switch (message?.event) {
397
911
  case "start": {
398
912
  const start = message.start ?? {};
399
- const encoding = start.media_format?.encoding;
400
- if (encoding === "PCMU" || encoding === "PCMA") this.codec = encoding;
913
+ const format = start.media_format ?? {};
914
+ const { encoding } = format;
915
+ if (encoding === "PCMU" || encoding === "PCMA") {
916
+ this.codec = encoding;
917
+ } else if (encoding) {
918
+ this.fail(
919
+ `Telnyx streams ${encoding}, TelnyxTransport reads PCMU or PCMA: set stream_codec and stream_bidirectional_codec, as telnyxStreamOptions() does`
920
+ );
921
+ return;
922
+ }
923
+ if (format.sample_rate && Number(format.sample_rate) !== 8e3) {
924
+ this.fail(
925
+ `Telnyx streams at ${format.sample_rate} Hz, TelnyxTransport reads 8000 Hz: leave stream_bidirectional_sampling_rate at 8000`
926
+ );
927
+ return;
928
+ }
929
+ const { params, outbound } = readParams(start);
401
930
  this.startStream(
402
931
  {
403
932
  callId: start.call_control_id,
404
933
  streamId: message.stream_id,
405
934
  from: start.from,
406
- to: start.to
935
+ to: start.to,
936
+ ...outbound ? { direction: "outbound" } : {}
407
937
  },
408
- readParams(start)
938
+ params
409
939
  );
410
940
  break;
411
941
  }
@@ -421,16 +951,19 @@ var TelnyxTransport = class extends TelephonyTransport {
421
951
  this.markPlayed(message.mark?.name);
422
952
  break;
423
953
  case "dtmf":
424
- this.receiveDtmf(String(message.dtmf?.digit));
954
+ this.receiveDtmf(message.dtmf?.digit);
425
955
  break;
426
956
  case "error":
427
- this.log("Telnyx error:", message.payload);
957
+ this.logger.error("Telnyx error", { payload: message.payload });
428
958
  break;
429
959
  }
430
960
  }
431
961
  writeAudio(pcm) {
432
962
  const bytes = this.codec === "PCMA" ? pcm16ToAlaw(pcm) : pcm16ToMulaw(pcm);
433
- this.sendJson({ event: "media", media: { payload: bytes.toString("base64") } });
963
+ this.sendJson({
964
+ event: "media",
965
+ media: { payload: bytes.toString("base64") }
966
+ });
434
967
  }
435
968
  writeClear() {
436
969
  this.sendJson({ event: "clear" });
@@ -442,25 +975,221 @@ var TelnyxTransport = class extends TelephonyTransport {
442
975
  const { apiKey } = this.options;
443
976
  const callId = this.call.callId;
444
977
  if (!apiKey || !callId) return;
445
- const response = await fetch(
446
- `https://api.telnyx.com/v2/calls/${encodeURIComponent(callId)}/actions/hangup`,
447
- {
448
- method: "POST",
449
- headers: {
450
- Authorization: `Bearer ${apiKey}`,
451
- "Content-Type": "application/json"
978
+ await this.action("hang up", callId, "hangup", {});
979
+ }
980
+ /** Sends the keys with Call Control, or in the audio without an API key */
981
+ async sendDtmf(digits) {
982
+ if (!this.options.apiKey) return super.sendDtmf(digits);
983
+ await this.action("send DTMF", this.requireCallId(), "send_dtmf", {
984
+ digits
985
+ });
986
+ }
987
+ /**
988
+ * Transfers the call with Call Control, then stops the stream. `from`
989
+ * defaults to the number the call was made to.
990
+ */
991
+ async transfer({ to, from, timeout }) {
992
+ const callId = this.requireCallId();
993
+ await this.action("transfer the call", callId, "transfer", {
994
+ to,
995
+ ...from ? { from } : {},
996
+ ...timeout ? { timeout_secs: Math.round(timeout) } : {}
997
+ });
998
+ await this.stopStreaming(callId);
999
+ this.handOff(to);
1000
+ }
1001
+ /**
1002
+ * Dials the person, speaks the briefing to them once they pick up, then
1003
+ * bridges the caller to them. Telnyx reports each step to the webhook of
1004
+ * the application only, so its events have to reach
1005
+ * `TelephonyCalls.telnyxWebhook()`.
1006
+ *
1007
+ * `from` defaults to the number of your account on the call.
1008
+ */
1009
+ async warmTransfer({
1010
+ to,
1011
+ from,
1012
+ timeout = DEFAULT_RING_TIMEOUT,
1013
+ briefing
1014
+ }) {
1015
+ const callId = this.requireCallId();
1016
+ const connectionId = requireOption(
1017
+ this.options.connectionId,
1018
+ "TelnyxTransport needs connectionId, the Call Control application that dials, to make a warm transfer"
1019
+ );
1020
+ const callerId = requireOption(
1021
+ from ?? this.ownNumber,
1022
+ "TelnyxTransport: set `from` to make a warm transfer"
1023
+ );
1024
+ if (this.pendingTransfer) {
1025
+ throw new Error("TelnyxTransport: a warm transfer is already under way");
1026
+ }
1027
+ this.earlyTransferEvents = [];
1028
+ const response = await callApi(
1029
+ "Telnyx dial",
1030
+ `${API2}/calls`,
1031
+ this.request({
1032
+ connection_id: connectionId,
1033
+ to,
1034
+ from: callerId,
1035
+ timeout_secs: Math.round(timeout),
1036
+ link_to: callId,
1037
+ client_state: encodeState({ [TRANSFER_KEY]: callId })
1038
+ })
1039
+ );
1040
+ const personId = response?.data?.call_control_id;
1041
+ if (!personId) throw new Error("Telnyx dial returned no call_control_id");
1042
+ const result = await new Promise((resolve, reject) => {
1043
+ const timer = setTimeout(
1044
+ () => {
1045
+ this.pendingTransfer = void 0;
1046
+ this.action("hang up", personId, "hangup", {}).catch(() => {
1047
+ });
1048
+ reject(
1049
+ new Error(
1050
+ "TelnyxTransport: no event of the transfer reached the transport. Hand the webhooks of the application to TelephonyCalls.telnyxWebhook()"
1051
+ )
1052
+ );
1053
+ },
1054
+ (timeout + 60) * 1e3
1055
+ );
1056
+ this.pendingTransfer = {
1057
+ personId,
1058
+ briefing,
1059
+ resolve: (result2) => {
1060
+ clearTimeout(timer);
1061
+ this.pendingTransfer = void 0;
1062
+ resolve(result2);
452
1063
  },
453
- body: "{}"
1064
+ reject: (error) => {
1065
+ clearTimeout(timer);
1066
+ this.pendingTransfer = void 0;
1067
+ reject(error);
1068
+ }
1069
+ };
1070
+ const early = this.earlyTransferEvents;
1071
+ this.earlyTransferEvents = [];
1072
+ for (const event of early) this.receiveTelnyxEvent(event);
1073
+ });
1074
+ if (result.transferred) this.handOff(to);
1075
+ return result;
1076
+ }
1077
+ /**
1078
+ * Takes a Call Control event about the person of a warm transfer, which
1079
+ * `TelephonyCalls.telnyxWebhook()` routes here
1080
+ */
1081
+ receiveTelnyxEvent(event) {
1082
+ const transfer = this.pendingTransfer;
1083
+ if (!transfer) {
1084
+ this.earlyTransferEvents.push(event);
1085
+ return;
1086
+ }
1087
+ if (event.payload?.call_control_id !== transfer.personId) return;
1088
+ const step = async () => {
1089
+ switch (event.event_type) {
1090
+ case "call.answered":
1091
+ if (transfer.briefing) {
1092
+ await this.action(
1093
+ "speak the briefing",
1094
+ transfer.personId,
1095
+ "speak",
1096
+ {
1097
+ payload: transfer.briefing,
1098
+ voice: this.options.briefingVoice ?? DEFAULT_VOICE,
1099
+ ...this.options.briefingLanguage ? { language: this.options.briefingLanguage } : {}
1100
+ }
1101
+ );
1102
+ } else {
1103
+ await this.bridgeTo(transfer);
1104
+ }
1105
+ break;
1106
+ case "call.speak.ended":
1107
+ await this.bridgeTo(transfer);
1108
+ break;
1109
+ case "call.hangup":
1110
+ transfer.resolve({
1111
+ transferred: false,
1112
+ reason: hangupReason(event.payload.hangup_cause)
1113
+ });
1114
+ break;
454
1115
  }
1116
+ };
1117
+ step().catch((error) => transfer.reject(error));
1118
+ }
1119
+ async bridgeTo(transfer) {
1120
+ const callId = this.requireCallId();
1121
+ await this.stopStreaming(callId);
1122
+ await this.action("bridge the transfer", callId, "bridge", {
1123
+ call_control_id: transfer.personId
1124
+ });
1125
+ transfer.resolve({ transferred: true });
1126
+ }
1127
+ async stopStreaming(callId) {
1128
+ await this.action("stop the stream", callId, "streaming_stop", {
1129
+ ...this.call.streamId ? { stream_id: this.call.streamId } : {}
1130
+ }).catch(
1131
+ (error) => this.logger.warn("Stopping the stream failed", { error })
455
1132
  );
456
- if (!response.ok) {
457
- throw new Error(`Telnyx answered ${response.status} to the hang up`);
458
- }
1133
+ }
1134
+ requireCallId() {
1135
+ return requireOption(
1136
+ this.call.callId,
1137
+ "TelnyxTransport: the stream has not started, the call is unknown"
1138
+ );
1139
+ }
1140
+ action(what, callId, name, body) {
1141
+ return callApi(
1142
+ `Telnyx ${what}`,
1143
+ `${API2}/calls/${encodeURIComponent(callId)}/actions/${name}`,
1144
+ this.request(body, what)
1145
+ );
1146
+ }
1147
+ request(body, what = "act on the call") {
1148
+ const apiKey = requireOption(
1149
+ this.options.apiKey,
1150
+ `TelnyxTransport needs apiKey to ${what}`
1151
+ );
1152
+ return {
1153
+ method: "POST",
1154
+ headers: {
1155
+ Authorization: `Bearer ${apiKey}`,
1156
+ "Content-Type": "application/json"
1157
+ },
1158
+ body: JSON.stringify(body)
1159
+ };
459
1160
  }
460
1161
  sendJson(message) {
461
1162
  if (this.isOpen) this.socket.send(JSON.stringify(message));
462
1163
  }
463
1164
  };
1165
+ function hangupReason(cause) {
1166
+ switch (cause) {
1167
+ case "user_busy":
1168
+ case "busy":
1169
+ case "call_rejected":
1170
+ return "busy";
1171
+ case "timeout":
1172
+ case "no_answer":
1173
+ case "originator_cancel":
1174
+ return "no-answer";
1175
+ case "normal_clearing":
1176
+ return "hung-up";
1177
+ default:
1178
+ return "failed";
1179
+ }
1180
+ }
1181
+ function encodeState(state) {
1182
+ return Buffer.from(JSON.stringify(state)).toString("base64");
1183
+ }
1184
+ function decodeTelnyxState(state) {
1185
+ if (typeof state !== "string") return {};
1186
+ try {
1187
+ const value = JSON.parse(Buffer.from(state, "base64").toString());
1188
+ return value && typeof value === "object" ? value : {};
1189
+ } catch {
1190
+ return {};
1191
+ }
1192
+ }
464
1193
  function readParams(start) {
465
1194
  const params = {};
466
1195
  const custom = start.custom_parameters;
@@ -469,16 +1198,10 @@ function readParams(start) {
469
1198
  } else if (custom && typeof custom === "object") {
470
1199
  Object.assign(params, custom);
471
1200
  }
472
- if (typeof start.client_state === "string") {
473
- try {
474
- const state = JSON.parse(
475
- Buffer.from(start.client_state, "base64").toString()
476
- );
477
- if (state && typeof state === "object") Object.assign(params, state);
478
- } catch {
479
- }
480
- }
481
- return params;
1201
+ Object.assign(params, decodeTelnyxState(start.client_state));
1202
+ const outbound = !!params[OUTBOUND_KEY];
1203
+ delete params[OUTBOUND_KEY];
1204
+ return { params, outbound };
482
1205
  }
483
1206
  function telnyxStreamOptions({
484
1207
  url,
@@ -491,18 +1214,82 @@ function telnyxStreamOptions({
491
1214
  stream_codec: codec,
492
1215
  stream_bidirectional_mode: "rtp",
493
1216
  stream_bidirectional_codec: codec,
494
- ...parameters ? {
495
- client_state: Buffer.from(JSON.stringify(parameters)).toString(
496
- "base64"
497
- )
498
- } : {}
1217
+ ...parameters ? { client_state: encodeState(parameters) } : {}
499
1218
  };
500
1219
  }
1220
+ async function telnyxCall(options) {
1221
+ const { apiKey, connectionId, to, from, timeout, machineDetection } = options;
1222
+ const detection = machineDetection === true ? "greeting_end" : machineDetection || void 0;
1223
+ const response = await callApi("Telnyx dial", `${API2}/calls`, {
1224
+ method: "POST",
1225
+ headers: {
1226
+ Authorization: `Bearer ${apiKey}`,
1227
+ "Content-Type": "application/json"
1228
+ },
1229
+ body: JSON.stringify({
1230
+ connection_id: connectionId,
1231
+ to,
1232
+ from,
1233
+ ...timeout ? { timeout_secs: Math.round(timeout) } : {},
1234
+ ...detection ? { answering_machine_detection: detection } : {},
1235
+ ...telnyxStreamOptions({
1236
+ ...options,
1237
+ parameters: { ...options.parameters, [OUTBOUND_KEY]: true }
1238
+ })
1239
+ })
1240
+ });
1241
+ const callId = response?.data?.call_control_id;
1242
+ if (!callId) throw new Error("Telnyx dial returned no call_control_id");
1243
+ return { callId };
1244
+ }
1245
+ function telnyxMachineDetection(body) {
1246
+ const data = body?.data ?? body;
1247
+ const type = data?.event_type;
1248
+ const payload = data?.payload;
1249
+ if (!type || !payload?.call_control_id) return void 0;
1250
+ const result = payload.result;
1251
+ const callId = payload.call_control_id;
1252
+ const detection = (answeredBy, greetingEnded = false) => ({ callId, detection: { answeredBy, greetingEnded, raw: data } });
1253
+ switch (type) {
1254
+ case "call.machine.detection.ended":
1255
+ if (result === "human") return detection("human");
1256
+ if (result === "machine") return detection("machine");
1257
+ return detection("unknown");
1258
+ case "call.machine.premium.detection.ended":
1259
+ if (result === "human_residence" || result === "human_business") {
1260
+ return detection("human");
1261
+ }
1262
+ if (result === "machine") return detection("machine");
1263
+ if (result === "fax_detected") return detection("fax");
1264
+ return detection("unknown");
1265
+ case "call.machine.greeting.ended":
1266
+ case "call.machine.premium.greeting.ended":
1267
+ return detection("unknown", true);
1268
+ default:
1269
+ return void 0;
1270
+ }
1271
+ }
1272
+ function telnyxEventTarget(body) {
1273
+ const event = body?.data ?? body;
1274
+ const callId = event?.payload?.call_control_id;
1275
+ if (!event?.event_type || !callId) return void 0;
1276
+ const transferOf = decodeTelnyxState(event.payload.client_state)[TRANSFER_KEY];
1277
+ return transferOf ? { callId: transferOf, event, transfer: true } : { callId, event, transfer: false };
1278
+ }
501
1279
 
502
1280
  // src/twilio.ts
1281
+ var API3 = "https://api.twilio.com/2010-04-01";
1282
+ var POLL_INTERVAL = 1e3;
1283
+ var DEFAULT_RING_TIMEOUT2 = 30;
1284
+ var DEFAULT_FALLBACK_TWIML = "<Response><Say>Sorry, nobody could take your call. Please call back later.</Say><Hangup/></Response>";
503
1285
  var TwilioTransport = class extends TelephonyTransport {
504
- constructor() {
505
- super(...arguments);
1286
+ /**
1287
+ * @param socket - The socket Twilio opened
1288
+ * @param options - Credentials of the account, for the transfers
1289
+ */
1290
+ constructor(socket, options = {}) {
1291
+ super(socket);
1292
+ this.options = options;
506
1293
  // Twilio takes audio of any size, and buffers it
507
1294
  this.frameDuration = 0;
508
1295
  }
@@ -514,6 +1301,13 @@ var TwilioTransport = class extends TelephonyTransport {
514
1301
  switch (message?.event) {
515
1302
  case "start": {
516
1303
  const start = message.start ?? {};
1304
+ const format = start.mediaFormat;
1305
+ if (format && (format.encoding !== "audio/x-mulaw" || format.sampleRate !== 8e3)) {
1306
+ this.fail(
1307
+ `Twilio streams ${format.encoding} at ${format.sampleRate} Hz, TwilioTransport reads audio/x-mulaw at 8000 Hz`
1308
+ );
1309
+ return;
1310
+ }
517
1311
  this.startStream(
518
1312
  {
519
1313
  callId: start.callSid,
@@ -533,10 +1327,10 @@ var TwilioTransport = class extends TelephonyTransport {
533
1327
  this.markPlayed(message.mark?.name);
534
1328
  break;
535
1329
  case "dtmf":
536
- this.receiveDtmf(String(message.dtmf?.digit));
1330
+ this.receiveDtmf(message.dtmf?.digit);
537
1331
  break;
538
1332
  case "stop":
539
- this.log("Stream stopped");
1333
+ this.logger.debug("Stream stopped");
540
1334
  break;
541
1335
  }
542
1336
  }
@@ -551,12 +1345,208 @@ var TwilioTransport = class extends TelephonyTransport {
551
1345
  this.sendJson({ event: "clear", streamSid: this.call.streamId });
552
1346
  }
553
1347
  writeMark(name) {
554
- this.sendJson({ event: "mark", streamSid: this.call.streamId, mark: { name } });
1348
+ this.sendJson({
1349
+ event: "mark",
1350
+ streamSid: this.call.streamId,
1351
+ mark: { name }
1352
+ });
1353
+ }
1354
+ /**
1355
+ * Sends the call to another number with a `<Dial>`, which ends the stream.
1356
+ * The caller ID stays that of the caller, unless `from` says otherwise.
1357
+ */
1358
+ async transfer({ to, from, timeout }) {
1359
+ const api = this.api("transfer the call");
1360
+ const callId = this.requireCallId();
1361
+ const attributes = [
1362
+ from ? ` callerId="${escapeXml(from)}"` : "",
1363
+ timeout ? ` timeout="${Math.round(timeout)}"` : ""
1364
+ ].join("");
1365
+ await api.updateCall(
1366
+ callId,
1367
+ `<Response><Dial${attributes}>${dialTarget(to)}</Dial></Response>`
1368
+ );
1369
+ this.handOff(to);
1370
+ }
1371
+ /**
1372
+ * Calls the person with the briefing and a conference, then moves the
1373
+ * caller into that conference once they picked up. The caller hears the
1374
+ * hold music while the briefing plays, and the person joins right after.
1375
+ *
1376
+ * `from` defaults to the number of your account on the call.
1377
+ */
1378
+ async warmTransfer({
1379
+ to,
1380
+ from,
1381
+ timeout = DEFAULT_RING_TIMEOUT2,
1382
+ briefing
1383
+ }) {
1384
+ const api = this.api("make a warm transfer");
1385
+ const callId = this.requireCallId();
1386
+ const room = `micdrop-${callId}`;
1387
+ const callerId = from ?? ownNumber(await api.getCall(callId));
1388
+ if (!callerId) {
1389
+ throw new Error("TwilioTransport: set `from` to make a warm transfer");
1390
+ }
1391
+ const say = briefing ? `<Say>${escapeXml(briefing)}</Say>` : "";
1392
+ const person = await api.createCall({
1393
+ To: to,
1394
+ From: callerId,
1395
+ Timeout: Math.round(timeout),
1396
+ Twiml: `<Response>${say}<Dial><Conference startConferenceOnEnter="true" endConferenceOnExit="true" beep="false">${room}</Conference></Dial></Response>`
1397
+ });
1398
+ const deadline = Date.now() + (timeout + 15) * 1e3;
1399
+ let status = person.status;
1400
+ while (Date.now() < deadline && !this.isTransferOver(status)) {
1401
+ await sleep(POLL_INTERVAL);
1402
+ status = (await api.getCall(person.sid)).status;
1403
+ }
1404
+ if (status !== "in-progress") {
1405
+ if (!this.isTransferOver(status)) {
1406
+ await api.endCall(person.sid).catch(() => {
1407
+ });
1408
+ }
1409
+ return { transferred: false, reason: transferFailure(status) };
1410
+ }
1411
+ const { holdMusicUrl } = this.options;
1412
+ const waitUrl = holdMusicUrl === void 0 ? "" : ` waitUrl="${escapeXml(holdMusicUrl)}"`;
1413
+ await api.updateCall(
1414
+ callId,
1415
+ `<Response><Dial><Conference startConferenceOnEnter="false" endConferenceOnExit="true" beep="false"${waitUrl}>${room}</Conference></Dial></Response>`
1416
+ );
1417
+ this.handOff(to);
1418
+ this.rescueIfAbandoned(api, callId, person.sid, room);
1419
+ return { transferred: true };
1420
+ }
1421
+ /**
1422
+ * Sends the caller the fallback when the person hangs up during the
1423
+ * briefing, before the conference started, so the caller does not wait for
1424
+ * nobody
1425
+ */
1426
+ async rescueIfAbandoned(api, callId, personId, room) {
1427
+ const deadline = Date.now() + 5 * 60 * 1e3;
1428
+ try {
1429
+ while (Date.now() < deadline) {
1430
+ await sleep(POLL_INTERVAL * 2);
1431
+ if (await api.isConferenceStarted(room)) return;
1432
+ const { status } = await api.getCall(personId);
1433
+ if (status === "in-progress") continue;
1434
+ if (await api.isConferenceStarted(room)) return;
1435
+ this.logger.info(
1436
+ "The person left before joining, the caller hears the fallback"
1437
+ );
1438
+ await api.updateCall(
1439
+ callId,
1440
+ this.options.transferFallbackTwiml ?? DEFAULT_FALLBACK_TWIML
1441
+ );
1442
+ return;
1443
+ }
1444
+ } catch (error) {
1445
+ this.logger.error("Watching the transfer failed", { error });
1446
+ }
1447
+ }
1448
+ isTransferOver(status) {
1449
+ return status !== "queued" && status !== "ringing" && status !== "initiated";
1450
+ }
1451
+ requireCallId() {
1452
+ return requireOption(
1453
+ this.call.callId,
1454
+ "TwilioTransport: the stream has not started, the call is unknown"
1455
+ );
1456
+ }
1457
+ api(action) {
1458
+ const { accountSid, authToken, apiKey } = this.options;
1459
+ return new TwilioApi({
1460
+ accountSid: requireOption(
1461
+ accountSid,
1462
+ `TwilioTransport needs accountSid and authToken to ${action}`
1463
+ ),
1464
+ authToken: requireOption(
1465
+ authToken,
1466
+ `TwilioTransport needs accountSid and authToken to ${action}`
1467
+ ),
1468
+ apiKey
1469
+ });
555
1470
  }
556
1471
  sendJson(message) {
557
1472
  if (this.isOpen) this.socket.send(JSON.stringify(message));
558
1473
  }
559
1474
  };
1475
+ var TwilioApi = class {
1476
+ constructor({ accountSid, authToken, apiKey }) {
1477
+ this.base = `${API3}/Accounts/${encodeURIComponent(accountSid)}`;
1478
+ this.authorization = `Basic ${Buffer.from(
1479
+ `${apiKey ?? accountSid}:${authToken}`
1480
+ ).toString("base64")}`;
1481
+ }
1482
+ createCall(fields) {
1483
+ return this.post("Twilio call creation", "/Calls.json", fields);
1484
+ }
1485
+ getCall(sid) {
1486
+ return callApi(
1487
+ "Twilio call fetch",
1488
+ `${this.base}/Calls/${encodeURIComponent(sid)}.json`,
1489
+ { headers: { Authorization: this.authorization } }
1490
+ );
1491
+ }
1492
+ updateCall(sid, twiml) {
1493
+ return this.post(
1494
+ "Twilio call update",
1495
+ `/Calls/${encodeURIComponent(sid)}.json`,
1496
+ { Twiml: twiml }
1497
+ );
1498
+ }
1499
+ endCall(sid) {
1500
+ return this.post(
1501
+ "Twilio hang up",
1502
+ `/Calls/${encodeURIComponent(sid)}.json`,
1503
+ { Status: "completed" }
1504
+ );
1505
+ }
1506
+ async isConferenceStarted(name) {
1507
+ const query = new URLSearchParams({
1508
+ FriendlyName: name,
1509
+ Status: "in-progress"
1510
+ });
1511
+ const result = await callApi(
1512
+ "Twilio conference fetch",
1513
+ `${this.base}/Conferences.json?${query}`,
1514
+ { headers: { Authorization: this.authorization } }
1515
+ );
1516
+ return (result?.conferences ?? []).length > 0;
1517
+ }
1518
+ post(what, path, fields) {
1519
+ return callApi(what, `${this.base}${path}`, {
1520
+ method: "POST",
1521
+ headers: {
1522
+ Authorization: this.authorization,
1523
+ "Content-Type": "application/x-www-form-urlencoded"
1524
+ },
1525
+ body: formBody(fields)
1526
+ });
1527
+ }
1528
+ };
1529
+ function ownNumber(call) {
1530
+ return call?.direction === "inbound" ? call?.to : call?.from;
1531
+ }
1532
+ function dialTarget(to) {
1533
+ return /^sips?:/i.test(to) ? `<Sip>${escapeXml(to)}</Sip>` : `<Number>${escapeXml(to)}</Number>`;
1534
+ }
1535
+ function transferFailure(status) {
1536
+ switch (status) {
1537
+ case "busy":
1538
+ return "busy";
1539
+ case "no-answer":
1540
+ case "queued":
1541
+ case "ringing":
1542
+ case "initiated":
1543
+ return "no-answer";
1544
+ case "completed":
1545
+ return "hung-up";
1546
+ default:
1547
+ return "failed";
1548
+ }
1549
+ }
560
1550
  function twilioStreamTwiml({
561
1551
  url,
562
1552
  parameters = {},
@@ -567,20 +1557,87 @@ function twilioStreamTwiml({
567
1557
  ).join("");
568
1558
  return `<?xml version="1.0" encoding="UTF-8"?><Response>${before}<Connect><Stream url="${escapeXml(url)}">${params}</Stream></Connect></Response>`;
569
1559
  }
1560
+ async function twilioCall(options) {
1561
+ const { to, from, timeout, machineDetection, machineDetectionUrl } = options;
1562
+ if (machineDetection && !machineDetectionUrl) {
1563
+ throw new Error(
1564
+ "twilioCall: machineDetection needs machineDetectionUrl, where Twilio posts the result"
1565
+ );
1566
+ }
1567
+ const api = new TwilioApi(options);
1568
+ const call = await api.createCall({
1569
+ To: to,
1570
+ From: from,
1571
+ Timeout: timeout === void 0 ? void 0 : Math.round(timeout),
1572
+ Twiml: twilioStreamTwiml(options),
1573
+ StatusCallback: options.statusCallback,
1574
+ ...machineDetection ? {
1575
+ MachineDetection: "DetectMessageEnd",
1576
+ AsyncAmd: "true",
1577
+ AsyncAmdStatusCallback: machineDetectionUrl
1578
+ } : {}
1579
+ });
1580
+ return { callId: call.sid };
1581
+ }
1582
+ function twilioMachineDetection(params) {
1583
+ const get = (key) => params instanceof URLSearchParams ? params.get(key) : params[key];
1584
+ const callId = get("CallSid");
1585
+ const answeredBy = get("AnsweredBy");
1586
+ if (!callId || !answeredBy) return void 0;
1587
+ const raw = Object.fromEntries(
1588
+ params instanceof URLSearchParams ? params : Object.entries(params)
1589
+ );
1590
+ if (answeredBy === "human") {
1591
+ return {
1592
+ callId,
1593
+ detection: { answeredBy: "human", greetingEnded: false, raw }
1594
+ };
1595
+ }
1596
+ if (answeredBy === "fax") {
1597
+ return {
1598
+ callId,
1599
+ detection: { answeredBy: "fax", greetingEnded: false, raw }
1600
+ };
1601
+ }
1602
+ if (String(answeredBy).startsWith("machine")) {
1603
+ return {
1604
+ callId,
1605
+ detection: {
1606
+ answeredBy: "machine",
1607
+ greetingEnded: answeredBy !== "machine_start",
1608
+ raw
1609
+ }
1610
+ };
1611
+ }
1612
+ return {
1613
+ callId,
1614
+ detection: { answeredBy: "unknown", greetingEnded: false, raw }
1615
+ };
1616
+ }
570
1617
 
571
1618
  // src/vonage.ts
1619
+ import { createSign, randomUUID } from "crypto";
572
1620
  var CALL_HEADERS = {
573
1621
  callId: "micdropCallId",
574
1622
  from: "micdropFrom",
575
- to: "micdropTo"
1623
+ to: "micdropTo",
1624
+ direction: "micdropDirection",
1625
+ ref: "micdropRef"
576
1626
  };
1627
+ var API4 = "https://api.nexmo.com/v1";
1628
+ var POLL_INTERVAL2 = 1e3;
1629
+ var DEFAULT_RING_TIMEOUT3 = 30;
1630
+ var DEFAULT_FALLBACK = "Sorry, nobody could take your call. Please call back later.";
1631
+ var outboundCalls = /* @__PURE__ */ new Map();
577
1632
  var VonageTransport = class extends TelephonyTransport {
578
1633
  /**
579
1634
  * @param socket - The socket Vonage opened
580
- * @param options - The rate of the NCCO, read again from the first message
1635
+ * @param options - The rate of the NCCO, and the credentials of the
1636
+ * application for the transfers and keys
581
1637
  */
582
1638
  constructor(socket, options = {}) {
583
1639
  super(socket);
1640
+ this.options = options;
584
1641
  this.rate = options.sampleRate ?? 16e3;
585
1642
  }
586
1643
  get lineRate() {
@@ -595,13 +1652,22 @@ var VonageTransport = class extends TelephonyTransport {
595
1652
  switch (message?.event) {
596
1653
  case "websocket:connected": {
597
1654
  const { event, "content-type": contentType, ...headers } = message;
1655
+ if (contentType && !/^audio\/l16/i.test(contentType)) {
1656
+ this.fail(
1657
+ `Vonage streams ${contentType}, VonageTransport reads audio/l16: set the content-type of the NCCO, as vonageConnectNcco() does`
1658
+ );
1659
+ return;
1660
+ }
598
1661
  const rate = /rate=(\d+)/.exec(contentType ?? "")?.[1];
599
1662
  if (rate) this.rate = Number(rate);
1663
+ const ref = headers[CALL_HEADERS.ref];
600
1664
  const call = {
601
- callId: headers[CALL_HEADERS.callId],
1665
+ callId: headers[CALL_HEADERS.callId] ?? outboundCalls.get(ref),
602
1666
  from: headers[CALL_HEADERS.from],
603
- to: headers[CALL_HEADERS.to]
1667
+ to: headers[CALL_HEADERS.to],
1668
+ direction: headers[CALL_HEADERS.direction]
604
1669
  };
1670
+ if (ref) outboundCalls.delete(ref);
605
1671
  for (const key of Object.values(CALL_HEADERS)) delete headers[key];
606
1672
  delete headers.reconnect_attempt;
607
1673
  this.startStream(call, headers);
@@ -611,7 +1677,7 @@ var VonageTransport = class extends TelephonyTransport {
611
1677
  this.markPlayed(message.payload?.micdropMark);
612
1678
  break;
613
1679
  case "websocket:dtmf":
614
- this.receiveDtmf(String(message.digit));
1680
+ this.receiveDtmf(message.digit);
615
1681
  break;
616
1682
  }
617
1683
  }
@@ -624,10 +1690,225 @@ var VonageTransport = class extends TelephonyTransport {
624
1690
  writeMark(name) {
625
1691
  this.sendJson({ action: "notify", payload: { micdropMark: name } });
626
1692
  }
1693
+ /** Sends the keys with the Voice API, or in the audio without credentials */
1694
+ async sendDtmf(digits) {
1695
+ if (!this.options.applicationId || !this.options.privateKey) {
1696
+ return super.sendDtmf(digits);
1697
+ }
1698
+ const callId = this.requireCallId();
1699
+ await this.sendDtmfWithPauses(
1700
+ digits,
1701
+ (keys) => this.api("send DTMF").request(
1702
+ "Vonage DTMF",
1703
+ "PUT",
1704
+ `/calls/${encodeURIComponent(callId)}/dtmf`,
1705
+ { digits: keys }
1706
+ )
1707
+ );
1708
+ }
1709
+ /**
1710
+ * Moves the call to an NCCO that connects it to the number. `from`
1711
+ * defaults to the number of your account on the call.
1712
+ */
1713
+ async transfer({ to, from, timeout }) {
1714
+ const api = this.api("transfer the call");
1715
+ const callId = this.requireCallId();
1716
+ const callerId = requireOption(
1717
+ from ?? this.ownNumber,
1718
+ "VonageTransport: set `from` to transfer the call"
1719
+ );
1720
+ await api.transfer(callId, [
1721
+ {
1722
+ action: "connect",
1723
+ from: vonageNumber(callerId),
1724
+ ...timeout ? { timeout: Math.round(timeout) } : {},
1725
+ endpoint: [vonageEndpoint(to)]
1726
+ }
1727
+ ]);
1728
+ this.handOff(to);
1729
+ }
1730
+ /**
1731
+ * Calls the person with the briefing and a named conversation, then moves
1732
+ * the caller into it once they picked up. The person joins right after the
1733
+ * briefing.
1734
+ *
1735
+ * `from` defaults to the number of your account on the call.
1736
+ */
1737
+ async warmTransfer({
1738
+ to,
1739
+ from,
1740
+ timeout = DEFAULT_RING_TIMEOUT3,
1741
+ briefing
1742
+ }) {
1743
+ const api = this.api("make a warm transfer");
1744
+ const callId = this.requireCallId();
1745
+ const callerId = requireOption(
1746
+ from ?? this.ownNumber,
1747
+ "VonageTransport: set `from` to make a warm transfer"
1748
+ );
1749
+ const room = `micdrop-${callId}`;
1750
+ const person = await api.request("Vonage call creation", "POST", "/calls", {
1751
+ to: [vonageEndpoint(to)],
1752
+ from: { type: "phone", number: vonageNumber(callerId) },
1753
+ ringing_timer: Math.round(timeout),
1754
+ ncco: [
1755
+ ...briefing ? [{ action: "talk", text: briefing }] : [],
1756
+ {
1757
+ action: "conversation",
1758
+ name: room,
1759
+ startOnEnter: true,
1760
+ endOnExit: true
1761
+ }
1762
+ ]
1763
+ });
1764
+ const deadline = Date.now() + (timeout + 15) * 1e3;
1765
+ let status = person?.status ?? "started";
1766
+ while (Date.now() < deadline && isRinging(status)) {
1767
+ await sleep(POLL_INTERVAL2);
1768
+ status = (await api.getCall(person.uuid)).status;
1769
+ }
1770
+ if (status !== "answered") {
1771
+ if (isRinging(status)) await api.hangUp(person.uuid).catch(() => {
1772
+ });
1773
+ return { transferred: false, reason: transferFailure2(status) };
1774
+ }
1775
+ const { holdMusicUrl } = this.options;
1776
+ await api.transfer(callId, [
1777
+ {
1778
+ action: "conversation",
1779
+ name: room,
1780
+ startOnEnter: false,
1781
+ endOnExit: true,
1782
+ ...holdMusicUrl ? { musicOnHoldUrl: [holdMusicUrl] } : {}
1783
+ }
1784
+ ]);
1785
+ this.handOff(to);
1786
+ this.rescueIfAbandoned(api, callId, person.uuid);
1787
+ return { transferred: true };
1788
+ }
1789
+ /**
1790
+ * Tells the caller nobody is there when the person hangs up during the
1791
+ * briefing: had they joined, their leaving would have ended the call
1792
+ */
1793
+ async rescueIfAbandoned(api, callId, personId) {
1794
+ const deadline = Date.now() + 5 * 60 * 1e3;
1795
+ try {
1796
+ while (Date.now() < deadline) {
1797
+ await sleep(POLL_INTERVAL2 * 2);
1798
+ if ((await api.getCall(personId)).status === "answered") continue;
1799
+ await sleep(3e3);
1800
+ if ((await api.getCall(callId)).status !== "answered") return;
1801
+ this.logger.info(
1802
+ "The person left before joining, the caller hears the fallback"
1803
+ );
1804
+ await api.transfer(callId, [
1805
+ {
1806
+ action: "talk",
1807
+ text: this.options.transferFallback ?? DEFAULT_FALLBACK
1808
+ }
1809
+ ]);
1810
+ return;
1811
+ }
1812
+ } catch (error) {
1813
+ this.logger.error("Watching the transfer failed", { error });
1814
+ }
1815
+ }
1816
+ requireCallId() {
1817
+ return requireOption(
1818
+ this.call.callId,
1819
+ "VonageTransport: the call is unknown, pass the answer webhook call to vonageConnectNcco() or place it with vonageCall()"
1820
+ );
1821
+ }
1822
+ api(action) {
1823
+ const message = `VonageTransport needs applicationId and privateKey to ${action}`;
1824
+ return new VonageApi({
1825
+ applicationId: requireOption(this.options.applicationId, message),
1826
+ privateKey: requireOption(this.options.privateKey, message)
1827
+ });
1828
+ }
627
1829
  sendJson(message) {
628
1830
  if (this.isOpen) this.socket.send(JSON.stringify(message));
629
1831
  }
630
1832
  };
1833
+ var VonageApi = class {
1834
+ constructor(credentials) {
1835
+ this.credentials = credentials;
1836
+ }
1837
+ request(what, method, path, body) {
1838
+ return callApi(what, `${API4}${path}`, {
1839
+ method,
1840
+ headers: {
1841
+ Authorization: `Bearer ${vonageJwt(this.credentials)}`,
1842
+ ...body ? { "Content-Type": "application/json" } : {}
1843
+ },
1844
+ ...body ? { body: JSON.stringify(body) } : {}
1845
+ });
1846
+ }
1847
+ getCall(uuid) {
1848
+ return this.request(
1849
+ "Vonage call fetch",
1850
+ "GET",
1851
+ `/calls/${encodeURIComponent(uuid)}`
1852
+ );
1853
+ }
1854
+ transfer(uuid, ncco) {
1855
+ return this.request(
1856
+ "Vonage transfer",
1857
+ "PUT",
1858
+ `/calls/${encodeURIComponent(uuid)}`,
1859
+ { action: "transfer", destination: { type: "ncco", ncco } }
1860
+ );
1861
+ }
1862
+ hangUp(uuid) {
1863
+ return this.request(
1864
+ "Vonage hang up",
1865
+ "PUT",
1866
+ `/calls/${encodeURIComponent(uuid)}`,
1867
+ { action: "hangup" }
1868
+ );
1869
+ }
1870
+ };
1871
+ function isRinging(status) {
1872
+ return status === "started" || status === "ringing";
1873
+ }
1874
+ function transferFailure2(status) {
1875
+ switch (status) {
1876
+ case "busy":
1877
+ case "rejected":
1878
+ return "busy";
1879
+ case "timeout":
1880
+ case "unanswered":
1881
+ case "cancelled":
1882
+ case "started":
1883
+ case "ringing":
1884
+ return "no-answer";
1885
+ case "machine":
1886
+ return "voicemail";
1887
+ case "completed":
1888
+ return "hung-up";
1889
+ default:
1890
+ return "failed";
1891
+ }
1892
+ }
1893
+ function vonageNumber(number) {
1894
+ return number.replace(/^\+/, "");
1895
+ }
1896
+ function vonageEndpoint(to) {
1897
+ return /^sips?:/i.test(to) ? { type: "sip", uri: to } : { type: "phone", number: vonageNumber(to) };
1898
+ }
1899
+ function vonageJwt({ applicationId, privateKey }) {
1900
+ const now = Math.floor(Date.now() / 1e3);
1901
+ const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
1902
+ const unsigned = `${encode({ alg: "RS256", typ: "JWT" })}.${encode({
1903
+ application_id: applicationId,
1904
+ iat: now,
1905
+ nbf: now - 10,
1906
+ exp: now + 300,
1907
+ jti: randomUUID()
1908
+ })}`;
1909
+ const signature = createSign("RSA-SHA256").update(unsigned).sign(privateKey.replace(/\\n/g, "\n")).toString("base64url");
1910
+ return `${unsigned}.${signature}`;
1911
+ }
631
1912
  function vonageConnectNcco({
632
1913
  url,
633
1914
  parameters = {},
@@ -654,20 +1935,430 @@ function vonageConnectNcco({
654
1935
  }
655
1936
  ];
656
1937
  }
1938
+ async function vonageCall(options) {
1939
+ const { to, from, timeout, machineDetection, eventUrl } = options;
1940
+ if (machineDetection && !eventUrl) {
1941
+ throw new Error(
1942
+ "vonageCall: machineDetection needs eventUrl, where Vonage posts the result"
1943
+ );
1944
+ }
1945
+ const ref = randomUUID();
1946
+ const ncco = vonageConnectNcco({ ...options, call: { from, to } });
1947
+ const headers = ncco[0].endpoint[0].headers;
1948
+ headers[CALL_HEADERS.direction] = "outbound";
1949
+ headers[CALL_HEADERS.ref] = ref;
1950
+ const call = await new VonageApi(options).request(
1951
+ "Vonage call creation",
1952
+ "POST",
1953
+ "/calls",
1954
+ {
1955
+ to: [vonageEndpoint(to)],
1956
+ from: { type: "phone", number: vonageNumber(from) },
1957
+ ncco,
1958
+ ...timeout ? { ringing_timer: Math.round(timeout) } : {},
1959
+ ...eventUrl ? { event_url: [eventUrl] } : {},
1960
+ ...machineDetection ? {
1961
+ advanced_machine_detection: {
1962
+ behavior: "continue",
1963
+ mode: "detect_beep"
1964
+ }
1965
+ } : {}
1966
+ }
1967
+ );
1968
+ const callId = call?.uuid;
1969
+ if (!callId) throw new Error("Vonage returned no uuid for the call");
1970
+ outboundCalls.set(ref, callId);
1971
+ setTimeout(() => outboundCalls.delete(ref), 10 * 60 * 1e3).unref?.();
1972
+ return { callId };
1973
+ }
1974
+ function vonageMachineDetection(body) {
1975
+ const callId = body?.call_uuid ?? body?.uuid;
1976
+ const status = body?.status;
1977
+ if (!callId || status !== "human" && status !== "machine") return void 0;
1978
+ const subState = body?.sub_state;
1979
+ if (subState === "fax") {
1980
+ return {
1981
+ callId,
1982
+ detection: { answeredBy: "fax", greetingEnded: false, raw: body }
1983
+ };
1984
+ }
1985
+ return {
1986
+ callId,
1987
+ detection: {
1988
+ answeredBy: status,
1989
+ greetingEnded: subState === "beep_start" || subState === "beep_timeout",
1990
+ raw: body
1991
+ }
1992
+ };
1993
+ }
1994
+
1995
+ // src/TelephonyCalls.ts
1996
+ var EARLY_RESULT_TTL = 2 * 60 * 1e3;
1997
+ var TelephonyCalls = class {
1998
+ constructor() {
1999
+ this.transports = /* @__PURE__ */ new Map();
2000
+ this.early = /* @__PURE__ */ new Map();
2001
+ }
2002
+ /**
2003
+ * Adds a call, known by its identifier once its stream started
2004
+ * @returns The transport, to chain on
2005
+ */
2006
+ add(transport) {
2007
+ const register = () => {
2008
+ const callId = transport.call.callId;
2009
+ if (!callId) return;
2010
+ this.transports.set(callId, transport);
2011
+ transport.once("Close", () => {
2012
+ if (this.transports.get(callId) === transport) {
2013
+ this.transports.delete(callId);
2014
+ }
2015
+ });
2016
+ const early = this.early.get(callId);
2017
+ if (early) {
2018
+ clearTimeout(early.timer);
2019
+ this.early.delete(callId);
2020
+ transport.receiveMachineDetection(early.detection);
2021
+ }
2022
+ };
2023
+ if (transport.call.callId) register();
2024
+ else transport.once("Params", register);
2025
+ return transport;
2026
+ }
2027
+ /** The call with this identifier at the provider, while its stream runs */
2028
+ get(callId) {
2029
+ return this.transports.get(callId);
2030
+ }
2031
+ /** Number of calls under way */
2032
+ get size() {
2033
+ return this.transports.size;
2034
+ }
2035
+ /**
2036
+ * Hands a result of machine detection to its call, or keeps it a while
2037
+ * for a stream that has not started yet
2038
+ * @returns Whether the call was found
2039
+ */
2040
+ machineDetected(callId, detection) {
2041
+ const transport = this.transports.get(callId);
2042
+ if (transport) {
2043
+ transport.receiveMachineDetection(detection);
2044
+ return true;
2045
+ }
2046
+ const previous = this.early.get(callId);
2047
+ if (previous) clearTimeout(previous.timer);
2048
+ const timer = setTimeout(() => this.early.delete(callId), EARLY_RESULT_TTL);
2049
+ timer.unref?.();
2050
+ this.early.set(callId, { detection, timer });
2051
+ return false;
2052
+ }
2053
+ /**
2054
+ * Reads the request Twilio posts to the `AsyncAmdStatusCallback` of a call
2055
+ * @param params - The fields of its form body
2056
+ * @returns Whether it carried a result
2057
+ */
2058
+ twilioMachineDetection(params) {
2059
+ const result = twilioMachineDetection(params);
2060
+ if (result) this.machineDetected(result.callId, result.detection);
2061
+ return !!result;
2062
+ }
2063
+ /**
2064
+ * Reads a webhook event of a Telnyx Call Control application: the machine
2065
+ * detection of a call, and the steps of its warm transfer
2066
+ * @param body - The JSON body of the webhook
2067
+ * @returns Whether a call of this server had a use for it
2068
+ */
2069
+ telnyxWebhook(body) {
2070
+ const target = telnyxEventTarget(body);
2071
+ if (!target) return false;
2072
+ if (target.transfer) {
2073
+ const transport = this.transports.get(target.callId);
2074
+ if (!(transport instanceof TelnyxTransport)) return false;
2075
+ transport.receiveTelnyxEvent(target.event);
2076
+ return true;
2077
+ }
2078
+ const result = telnyxMachineDetection(body);
2079
+ if (!result) return false;
2080
+ this.machineDetected(result.callId, result.detection);
2081
+ return true;
2082
+ }
2083
+ /**
2084
+ * Reads an event Vonage posts to the event URL of a call
2085
+ * @param body - Its JSON body
2086
+ * @returns Whether it carried a result of machine detection
2087
+ */
2088
+ vonageEvent(body) {
2089
+ const result = vonageMachineDetection(body);
2090
+ if (result) this.machineDetected(result.callId, result.detection);
2091
+ return !!result;
2092
+ }
2093
+ /**
2094
+ * Reads the request Plivo posts to the `machine_detection_url` of a call
2095
+ * @param params - The fields of its form body
2096
+ * @returns Whether it carried a result
2097
+ */
2098
+ plivoMachineDetection(params) {
2099
+ const result = plivoMachineDetection(params);
2100
+ if (result) this.machineDetected(result.callId, result.detection);
2101
+ return !!result;
2102
+ }
2103
+ };
2104
+
2105
+ // src/tools.ts
2106
+ import { z } from "zod";
2107
+
2108
+ // src/voicemail.ts
2109
+ var DEFAULT_SILENCE = 1500;
2110
+ var DEFAULT_MAX_WAIT = 2e4;
2111
+ var VOICEMAIL_NOTE = "You reached a voicemail, and the recording has started. Leave a short message now, saying who you are and why you called, then say goodbye.";
2112
+ async function leaveVoicemail(server, options = {}) {
2113
+ const transport = server.transport;
2114
+ if (!transport || server.isEnded) return;
2115
+ server.cancel();
2116
+ transport.clearAudio();
2117
+ await waitForGreetingEnd(server, options);
2118
+ if (server.isEnded) return;
2119
+ if (options.message) {
2120
+ server.say(options.message);
2121
+ } else {
2122
+ server.addSystemMessage(VOICEMAIL_NOTE);
2123
+ server.answer();
2124
+ }
2125
+ server.endCall();
2126
+ }
2127
+ function waitForGreetingEnd(server, options) {
2128
+ const transport = server.transport instanceof TelephonyTransport ? server.transport : void 0;
2129
+ const detected = transport?.machineDetection;
2130
+ if (detected?.greetingEnded) return Promise.resolve();
2131
+ const silence = (options.silence ?? DEFAULT_SILENCE) * (detected?.answeredBy === "machine" ? 2 : 1);
2132
+ const maxWait = options.maxWait ?? DEFAULT_MAX_WAIT;
2133
+ return new Promise((resolve) => {
2134
+ let speaking = false;
2135
+ let lastActivity = Date.now();
2136
+ const start = Date.now();
2137
+ const onStart = () => {
2138
+ speaking = true;
2139
+ lastActivity = Date.now();
2140
+ };
2141
+ const onStop = () => {
2142
+ speaking = false;
2143
+ lastActivity = Date.now();
2144
+ };
2145
+ const onDetection = (detection) => {
2146
+ if (detection.greetingEnded) done();
2147
+ };
2148
+ const interval = setInterval(() => {
2149
+ const now = Date.now();
2150
+ if (server.isEnded || now - start >= maxWait) return done();
2151
+ if (!speaking && now - lastActivity >= silence) done();
2152
+ }, 100);
2153
+ function done() {
2154
+ clearInterval(interval);
2155
+ server.off("UserStartSpeaking", onStart);
2156
+ server.off("UserStopSpeaking", onStop);
2157
+ transport?.off("MachineDetection", onDetection);
2158
+ resolve();
2159
+ }
2160
+ server.on("UserStartSpeaking", onStart);
2161
+ server.on("UserStopSpeaking", onStop);
2162
+ transport?.on("MachineDetection", onDetection);
2163
+ });
2164
+ }
2165
+ function answeringMachine(server, options = {}) {
2166
+ const transport = server.transport;
2167
+ if (!(transport instanceof TelephonyTransport)) {
2168
+ throw new Error(
2169
+ `answeringMachine() needs a telephony transport, the call runs on ${transport?.constructor.name ?? "nothing"}`
2170
+ );
2171
+ }
2172
+ let handled = false;
2173
+ const onDetection = (detection) => {
2174
+ if (handled || server.isEnded) return;
2175
+ if (detection.answeredBy === "human") {
2176
+ handled = true;
2177
+ options.onHuman?.(detection);
2178
+ return;
2179
+ }
2180
+ if (detection.answeredBy !== "machine" && detection.answeredBy !== "fax") {
2181
+ return;
2182
+ }
2183
+ handled = true;
2184
+ if (options.onMachine?.(detection) === false) return;
2185
+ if (detection.answeredBy === "fax" || options.message === false) {
2186
+ server.close("Answering machine");
2187
+ return;
2188
+ }
2189
+ leaveVoicemail(server, {
2190
+ message: options.message,
2191
+ silence: options.silence,
2192
+ maxWait: options.maxWait
2193
+ }).catch(
2194
+ (error) => server.logger.error("Leaving the message failed", { error })
2195
+ );
2196
+ };
2197
+ transport.on("MachineDetection", onDetection);
2198
+ if (transport.machineDetection) onDetection(transport.machineDetection);
2199
+ const stop = () => transport.off("MachineDetection", onDetection);
2200
+ server.on("End", stop);
2201
+ return stop;
2202
+ }
2203
+
2204
+ // src/tools.ts
2205
+ var PHONE_OR_SIP = /^(\+[1-9]\d{5,14}|sips?:.+)$/;
2206
+ function telephonyTransport(server) {
2207
+ const transport = server.transport;
2208
+ if (!(transport instanceof TelephonyTransport)) {
2209
+ throw new Error(
2210
+ `This tool acts on a phone call, and the call runs on ${transport?.constructor.name ?? "nothing"}`
2211
+ );
2212
+ }
2213
+ return transport;
2214
+ }
2215
+ function transferCallTool(options) {
2216
+ const destinations = options.destinations ? options.destinations : options.to ? [{ name: "default", to: options.to }] : [];
2217
+ if (destinations.length === 0) {
2218
+ throw new Error("transferCallTool needs `to` or `destinations`");
2219
+ }
2220
+ for (const destination of destinations) {
2221
+ if (!PHONE_OR_SIP.test(destination.to)) {
2222
+ throw new Error(
2223
+ `transferCallTool: "${destination.to}" is neither a phone number in E.164 format nor a SIP URI`
2224
+ );
2225
+ }
2226
+ }
2227
+ const warm = options.mode === "warm";
2228
+ const several = destinations.length > 1 || !!options.destinations;
2229
+ const shape = {};
2230
+ if (several) {
2231
+ shape.destination = z.enum(destinations.map((d) => d.name)).describe(
2232
+ "Where to send the call: " + destinations.map(
2233
+ (d) => d.description ? `${d.name} (${d.description})` : d.name
2234
+ ).join(", ")
2235
+ );
2236
+ }
2237
+ if (warm) {
2238
+ shape.summary = z.string().describe(
2239
+ "What the person taking the call needs to know, spoken to them before the caller joins: who calls and what for, in one or two sentences"
2240
+ );
2241
+ }
2242
+ return {
2243
+ name: options.name ?? "transfer_call",
2244
+ description: options.description ?? (warm ? "Call this tool when the user asks for a human, or needs help you cannot give. Tell the user you are getting someone and ask them to hold before calling it." : "Call this tool when the user asks for a human, or needs help you cannot give. Tell the user you are transferring them before calling it."),
2245
+ inputSchema: z.object(shape),
2246
+ execute: (input, agent) => {
2247
+ const destination = destinations.find((d) => d.name === input.destination) ?? destinations[0];
2248
+ const transfer = {
2249
+ to: destination.to,
2250
+ from: options.from,
2251
+ timeout: options.timeout
2252
+ };
2253
+ agent.afterAnswer(async (server) => {
2254
+ const transport = telephonyTransport(server);
2255
+ try {
2256
+ if (!warm) {
2257
+ await transport.transfer(transfer);
2258
+ return;
2259
+ }
2260
+ const result = await transport.warmTransfer({
2261
+ ...transfer,
2262
+ briefing: input.summary
2263
+ });
2264
+ if (result.transferred) return;
2265
+ server.addSystemMessage(
2266
+ `The transfer to ${destination.name} did not go through (${result.reason}). The user is still on the line with you: tell them, and offer another way to help.`
2267
+ );
2268
+ server.answer();
2269
+ } catch (error) {
2270
+ server.logger.error("Transfer failed", {
2271
+ tool: "transferCall",
2272
+ error
2273
+ });
2274
+ if (server.isEnded) return;
2275
+ server.addSystemMessage(
2276
+ `The transfer to ${destination.name} failed. The user is still on the line with you: apologize, and offer another way to help.`
2277
+ );
2278
+ server.answer();
2279
+ }
2280
+ });
2281
+ return {
2282
+ status: warm ? "calling" : "transferring",
2283
+ destination: destination.name
2284
+ };
2285
+ }
2286
+ };
2287
+ }
2288
+ function sendDtmfTool(options = {}) {
2289
+ return {
2290
+ name: options.name ?? "send_dtmf",
2291
+ description: options.description ?? "Press keys on the phone keypad, to choose in an automated phone menu or enter a number it asks for. Only call it when you hear an automated system ask for a key.",
2292
+ skipAnswer: true,
2293
+ inputSchema: z.object({
2294
+ digits: z.string().regex(DTMF_DIGITS).describe(
2295
+ "Keys to press: 0-9, * and #, with w for a half second pause"
2296
+ )
2297
+ }),
2298
+ execute: (input, agent) => {
2299
+ const digits = String(input.digits);
2300
+ agent.afterAnswer((server) => telephonyTransport(server).sendDtmf(digits));
2301
+ return { pressed: digits };
2302
+ }
2303
+ };
2304
+ }
2305
+ function voicemailTool(options = {}) {
2306
+ return {
2307
+ name: options.name ?? "leave_voicemail",
2308
+ description: options.description ?? 'Call this tool only if you hear an answering machine or a voicemail greeting instead of a person, such as "leave a message after the tone". Say nothing else.',
2309
+ skipAnswer: true,
2310
+ execute: (_input, agent) => {
2311
+ agent.afterAnswer(
2312
+ (server) => leaveVoicemail(server, { message: options.message })
2313
+ );
2314
+ return { status: "leaving a message" };
2315
+ }
2316
+ };
2317
+ }
657
2318
  export {
2319
+ DTMF_DIGITS,
658
2320
  PlivoTransport,
2321
+ TelephonyApiError,
2322
+ TelephonyCalls,
659
2323
  TelephonyTransport,
660
2324
  TelnyxTransport,
661
2325
  TwilioTransport,
662
2326
  VonageTransport,
663
2327
  alawToPcm16,
2328
+ answeringMachine,
2329
+ callApi,
2330
+ checkDtmfDigits,
2331
+ decodeTelnyxState,
2332
+ dtmfTones,
2333
+ formBody,
2334
+ leaveVoicemail,
664
2335
  mulawToPcm16,
665
2336
  parseJson,
666
2337
  pcm16ToAlaw,
667
2338
  pcm16ToMulaw,
2339
+ plivoCall,
2340
+ plivoMachineDetection,
668
2341
  plivoStreamXml,
2342
+ plivoTransferXml,
2343
+ requireOption,
2344
+ sendDtmfTool,
2345
+ sleep,
2346
+ telnyxCall,
2347
+ telnyxEventTarget,
2348
+ telnyxMachineDetection,
669
2349
  telnyxStreamOptions,
2350
+ transferCallTool,
2351
+ twilioCall,
2352
+ twilioMachineDetection,
670
2353
  twilioStreamTwiml,
671
- vonageConnectNcco
2354
+ validatePlivoSignature,
2355
+ validateTelnyxSignature,
2356
+ validateTwilioSignature,
2357
+ validateVonageSignature,
2358
+ voicemailTool,
2359
+ vonageCall,
2360
+ vonageConnectNcco,
2361
+ vonageJwt,
2362
+ vonageMachineDetection
672
2363
  };
673
2364
  //# sourceMappingURL=index.mjs.map