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