@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.d.mts CHANGED
@@ -1,6 +1,22 @@
1
- import { MicdropTransport, MicdropServerMessage } from '@micdrop/server';
1
+ import { MicdropTransport, MicdropTransportEvents, StandardWebSocket, MicdropServerMessage, Tool, MicdropServer } from '@micdrop/server';
2
2
  import { WebSocket } from 'ws';
3
3
 
4
+ /** Keys a phone keypad sends, and the pauses providers accept between them */
5
+ declare const DTMF_DIGITS: RegExp;
6
+ /**
7
+ * Checks keys to send, and fails loudly on anything a keypad cannot send
8
+ * @param digits - Keys, with `w` for a pause of 0.5 s and `W` for 1 s
9
+ */
10
+ declare function checkDtmfDigits(digits: string): string;
11
+ /**
12
+ * Synthesizes keys as the dual tones of a keypad, for a line that carries
13
+ * them in its audio
14
+ * @param digits - Keys, with `w` for a pause of 0.5 s and `W` for 1 s
15
+ * @param sampleRate - Rate of the audio, in Hz
16
+ * @returns PCM16 mono
17
+ */
18
+ declare function dtmfTones(digits: string, sampleRate: number): Buffer;
19
+
4
20
  /**
5
21
  * G.711, the codec of the phone network: one byte per sample at 8 kHz, with a
6
22
  * logarithmic scale that keeps quiet speech as precise as loud speech.
@@ -33,6 +49,26 @@ declare function alawToPcm16(bytes: Uint8Array): Buffer;
33
49
  */
34
50
  declare function pcm16ToAlaw(pcm: Buffer): Buffer;
35
51
 
52
+ /** A request to the API of a provider that did not succeed */
53
+ declare class TelephonyApiError extends Error {
54
+ readonly status: number;
55
+ readonly body: string;
56
+ constructor(message: string, status: number, body: string);
57
+ }
58
+ /**
59
+ * Calls the API of a provider, and throws with what it answered when the
60
+ * request fails
61
+ * @param what - What the request does, for the error message
62
+ * @returns The JSON body of the answer, or undefined when there is none
63
+ */
64
+ declare function callApi(what: string, url: string, init: RequestInit): Promise<any>;
65
+ /** Encodes fields as a form, for the APIs that read one */
66
+ declare function formBody(fields: Record<string, unknown>): URLSearchParams;
67
+ /** Waits for a while */
68
+ declare function sleep(ms: number): Promise<void>;
69
+ /** Fails loudly when a credential the action needs is missing */
70
+ declare function requireOption<T>(value: T | undefined | null | '', message: string): T;
71
+
36
72
  /** What the provider says about the call, once its stream has started */
37
73
  interface TelephonyCall {
38
74
  /** Identifier of the call at the provider, to act on it with its API */
@@ -43,6 +79,59 @@ interface TelephonyCall {
43
79
  from?: string;
44
80
  /** Number called, when the provider passes it */
45
81
  to?: string;
82
+ /**
83
+ * Whether the call came in or went out, when known: the outbound helpers
84
+ * of this package mark the calls they make
85
+ */
86
+ direction?: 'inbound' | 'outbound';
87
+ }
88
+ /** Who picked up an outbound call, as the provider detected it */
89
+ type AnsweredBy = 'human' | 'machine' | 'fax' | 'unknown';
90
+ /** What the answering machine detection of the provider found */
91
+ interface MachineDetection {
92
+ /** Who picked up */
93
+ answeredBy: AnsweredBy;
94
+ /**
95
+ * Whether the greeting of the machine is over, the beep heard or the line
96
+ * silent, so a message left now is recorded whole
97
+ */
98
+ greetingEnded: boolean;
99
+ /** What the provider sent, as it sent it */
100
+ raw?: unknown;
101
+ }
102
+ /** Where to send a call, and how */
103
+ interface TransferOptions {
104
+ /** Phone number in E.164 format, such as `+14155550100`, or a SIP URI */
105
+ to: string;
106
+ /**
107
+ * Number the person reached sees, one of your account. Each provider has
108
+ * its own default, read on the page of its transport.
109
+ */
110
+ from?: string;
111
+ /** How long to let the phone ring, in seconds, 30 by default */
112
+ timeout?: number;
113
+ }
114
+ /** A transfer where the assistant reaches the person before the caller */
115
+ interface WarmTransferOptions extends TransferOptions {
116
+ /**
117
+ * What the person reached hears before the caller joins them: who calls,
118
+ * and what for. The voice of the provider speaks it.
119
+ */
120
+ briefing?: string;
121
+ }
122
+ /** Why a warm transfer did not reach anybody */
123
+ type WarmTransferFailure = 'busy' | 'no-answer' | 'voicemail' | 'failed' | 'hung-up';
124
+ type WarmTransferResult = {
125
+ transferred: true;
126
+ } | {
127
+ transferred: false;
128
+ reason: WarmTransferFailure;
129
+ };
130
+ interface TelephonyTransportEvents extends MicdropTransportEvents {
131
+ /** The answering machine detection of the provider found who picked up */
132
+ MachineDetection: [MachineDetection];
133
+ /** The call left the assistant for another destination */
134
+ Transferred: [to: string];
46
135
  }
47
136
  /**
48
137
  * A phone call carried over the media stream WebSocket of a telephony
@@ -55,14 +144,21 @@ interface TelephonyCall {
55
144
  * provider wants them, playback confirmed by marks, and a hang up once the
56
145
  * goodbye is played. Each provider writes and reads its own messages.
57
146
  *
58
- * A phone line has no client to find the turns: the server needs `vad`.
147
+ * A phone line has no client to find the turns: the server needs `turns.vad`.
59
148
  */
60
- declare abstract class TelephonyTransport extends MicdropTransport {
61
- readonly socket: WebSocket;
149
+ declare abstract class TelephonyTransport extends MicdropTransport<TelephonyTransportEvents> {
150
+ readonly socket: WebSocket | StandardWebSocket;
62
151
  readonly clientTurns = false;
63
152
  readonly hangsUp = true;
64
153
  /** What the provider said about the call */
65
154
  call: TelephonyCall;
155
+ /**
156
+ * What the answering machine detection of the provider found, once it
157
+ * reported, for the outbound calls that asked for it
158
+ */
159
+ machineDetection?: MachineDetection;
160
+ /** Where the call was transferred, once it left the assistant */
161
+ transferredTo?: string;
66
162
  /**
67
163
  * Duration of the frames the provider wants, in ms. 0 sends the audio as it
68
164
  * comes, for the providers that take any size.
@@ -76,13 +172,17 @@ declare abstract class TelephonyTransport extends MicdropTransport {
76
172
  private outputRate;
77
173
  private frameRemainder;
78
174
  private frameTimer?;
175
+ private playoutEnd;
79
176
  private markCounter;
80
177
  private playbackWaiters;
81
178
  private closed;
179
+ private handedOff;
82
180
  /**
83
- * @param socket - The socket the provider opened, as the `ws` server hands it
181
+ * @param socket - The socket the provider opened, as the `ws` server hands
182
+ * it, or a standard WebSocket, the server half of a Cloudflare
183
+ * `WebSocketPair` for instance
84
184
  */
85
- constructor(socket: WebSocket);
185
+ constructor(socket: WebSocket | StandardWebSocket);
86
186
  /** Rate of the audio on the line, in Hz */
87
187
  protected abstract get lineRate(): number;
88
188
  /**
@@ -112,11 +212,70 @@ declare abstract class TelephonyTransport extends MicdropTransport {
112
212
  /**
113
213
  * Ends the stream, and the call with it: closing the socket is enough for
114
214
  * the providers that end the call when nothing follows the stream, the
115
- * others hang up through their API in `hangUp()`
215
+ * others hang up through their API in `hangUp()`. A call transferred
216
+ * elsewhere goes on without the assistant.
116
217
  */
117
218
  close(code?: number, reason?: string): void;
219
+ /**
220
+ * Sends keys on the line, to navigate the menu of the phone system the
221
+ * assistant called. Resolves once they have been sent.
222
+ *
223
+ * Providers that send keys through their API or their stream do it there.
224
+ * The others carry them in the audio, as the dual tones of a keypad.
225
+ *
226
+ * @param digits - Keys among 0-9, *, # and A-D, with `w` for a pause of
227
+ * 0.5 s and `W` for 1 s
228
+ */
229
+ sendDtmf(digits: string): Promise<void>;
230
+ /**
231
+ * Sends keys a piece at a time, waiting where they ask for a pause, for the
232
+ * providers that take no pause in the keys they send
233
+ * @param send - Sends keys without pauses
234
+ */
235
+ protected sendDtmfWithPauses(digits: string, send: (keys: string) => Promise<void>): Promise<void>;
236
+ /** The number of the account on the call, to call from in a transfer */
237
+ protected get ownNumber(): string | undefined;
238
+ /**
239
+ * Sends the call to another number, and leaves it: the assistant is no
240
+ * longer on the line once it resolves. Rejects when the provider refuses.
241
+ *
242
+ * @param options - Where to send the call
243
+ */
244
+ transfer(options: TransferOptions): Promise<void>;
245
+ /**
246
+ * Reaches a person first, tells them about the call, then connects the
247
+ * caller to them and leaves. The assistant stays on the line with the
248
+ * caller while the phone rings, and keeps it when nobody takes the call.
249
+ *
250
+ * @param options - Who to reach, and what to tell them
251
+ * @returns Whether the caller was connected, or why not
252
+ */
253
+ warmTransfer(options: WarmTransferOptions): Promise<WarmTransferResult>;
254
+ /**
255
+ * Takes the result of the answering machine detection of the provider,
256
+ * which reaches the server through a webhook for most of them.
257
+ * `TelephonyCalls` routes the webhooks of a server to the right transport.
258
+ */
259
+ receiveMachineDetection(detection: MachineDetection): void;
260
+ /**
261
+ * Resolves with the result of the answering machine detection, as soon as
262
+ * there is one, or undefined once `timeout` ms passed without any
263
+ */
264
+ waitForMachineDetection(timeout?: number): Promise<MachineDetection | undefined>;
118
265
  /** Hangs up through the API of the provider, for those that need it */
119
266
  protected hangUp(): Promise<void>;
267
+ /**
268
+ * The call now goes on without the assistant: ends the stream without
269
+ * hanging up
270
+ * @param to - Where the call went
271
+ */
272
+ protected handOff(to: string): void;
273
+ /**
274
+ * Ends the call on a misconfiguration that would leave it garbled or
275
+ * silent, and says why where it cannot be missed
276
+ * @param reason - What is wrong, and how to fix it
277
+ */
278
+ protected fail(reason: string): void;
120
279
  /**
121
280
  * The stream has started: keeps what the provider said about the call and
122
281
  * sends the audio that waited for it
@@ -132,13 +291,19 @@ declare abstract class TelephonyTransport extends MicdropTransport {
132
291
  /** The provider played the audio sent before a mark */
133
292
  protected markPlayed(name: string): void;
134
293
  /** A key was pressed on the keypad of the phone */
135
- protected receiveDtmf(digit: string): void;
294
+ protected receiveDtmf(digit: unknown): void;
295
+ /** Writes audio, keeping track of when the provider will be done playing it */
296
+ private writePacedAudio;
136
297
  /** Bytes in one outgoing frame */
137
298
  protected get frameBytes(): number;
138
299
  private toLineRate;
139
300
  private whenReady;
140
301
  /** Sends the incomplete frame left, padded with silence */
141
302
  private flushFrame;
303
+ /**
304
+ * Sends the incomplete frame left once the provider is about to run out of
305
+ * audio, if the rest of the answer has not come by then
306
+ */
142
307
  private scheduleFrameFlush;
143
308
  private cancelFrameFlush;
144
309
  private resolvePlayback;
@@ -148,13 +313,19 @@ declare abstract class TelephonyTransport extends MicdropTransport {
148
313
  /** Reads a JSON text message, or nothing when it is not one */
149
314
  declare function parseJson(data: Buffer): any;
150
315
 
151
- interface PlivoTransportOptions {
316
+ /** Credentials of a Plivo account, to act on calls through its API */
317
+ interface PlivoCredentials {
318
+ authId: string;
319
+ authToken: string;
320
+ }
321
+ interface PlivoTransportOptions extends Partial<PlivoCredentials> {
152
322
  /**
153
- * Credentials of the account, to hang up through the API when the assistant
154
- * ends the call, whatever the XML says after the stream
323
+ * Address of the XML that dials the destination of a transfer, as Plivo
324
+ * only transfers a call to an XML it fetches. Given the transfer, it
325
+ * returns the address of a route of your server that answers with
326
+ * {@link plivoTransferXml}.
155
327
  */
156
- authId?: string;
157
- authToken?: string;
328
+ transferUrl?: (options: TransferOptions) => string;
158
329
  }
159
330
  /**
160
331
  * A call from Plivo, over a bidirectional audio stream.
@@ -170,7 +341,7 @@ declare class PlivoTransport extends TelephonyTransport {
170
341
  private options;
171
342
  /**
172
343
  * @param socket - The socket Plivo opened
173
- * @param options - Credentials to hang up with
344
+ * @param options - Credentials to hang up and transfer with
174
345
  */
175
346
  constructor(socket: ConstructorParameters<typeof TelephonyTransport>[0], options?: PlivoTransportOptions);
176
347
  protected get lineRate(): number;
@@ -178,6 +349,13 @@ declare class PlivoTransport extends TelephonyTransport {
178
349
  protected writeAudio(pcm: Buffer): void;
179
350
  protected writeClear(): void;
180
351
  protected writeMark(name: string): void;
352
+ /** Sends the keys over the stream, which Plivo plays on the call */
353
+ sendDtmf(digits: string): Promise<void>;
354
+ /**
355
+ * Transfers the call to the XML at `transferUrl`, which dials the
356
+ * destination and ends the stream
357
+ */
358
+ transfer(options: TransferOptions): Promise<void>;
181
359
  protected hangUp(): Promise<void>;
182
360
  private sendJson;
183
361
  }
@@ -196,6 +374,213 @@ interface PlivoStreamOptions {
196
374
  * @returns The XML document
197
375
  */
198
376
  declare function plivoStreamXml({ url, parameters }: PlivoStreamOptions): string;
377
+ /**
378
+ * Writes the XML that dials the destination of a transfer, for the route
379
+ * `transferUrl` points to
380
+ * @returns The XML document
381
+ */
382
+ declare function plivoTransferXml({ to, from, timeout }: TransferOptions): string;
383
+ interface PlivoCallOptions extends PlivoCredentials {
384
+ /** Number to call, in E.164 format */
385
+ to: string;
386
+ /** Number of your account that calls */
387
+ from: string;
388
+ /**
389
+ * Address of the XML of the call once picked up, a route of your server
390
+ * that answers with {@link plivoStreamXml}
391
+ */
392
+ answerUrl: string;
393
+ /** How long to let the phone ring, in seconds */
394
+ timeout?: number;
395
+ /**
396
+ * Detects whether a machine picked up, without holding the call: Plivo
397
+ * posts the result to `machineDetectionUrl`. Hand the request to
398
+ * `TelephonyCalls.plivoMachineDetection()`.
399
+ */
400
+ machineDetection?: boolean;
401
+ /** Where Plivo posts the result of the machine detection */
402
+ machineDetectionUrl?: string;
403
+ }
404
+ /**
405
+ * Calls a number, and runs the XML of `answerUrl` once picked up
406
+ * @returns The request UUID of the call, Plivo gives the call UUID to the
407
+ * answer URL and to the stream
408
+ * @see https://www.plivo.com/docs/voice/api/call/make-a-call
409
+ */
410
+ declare function plivoCall(options: PlivoCallOptions): Promise<{
411
+ requestId: string;
412
+ }>;
413
+ /**
414
+ * Reads the result of the machine detection of Plivo, as it posts it to the
415
+ * `machine_detection_url`
416
+ * @param params - The fields of the request, parsed from its form body
417
+ */
418
+ declare function plivoMachineDetection(params: Record<string, any> | URLSearchParams): {
419
+ callId: string;
420
+ detection: MachineDetection;
421
+ } | undefined;
422
+
423
+ /**
424
+ * Checks of the signatures each provider puts on the requests it sends, so a
425
+ * server only acts on webhooks that came from its provider. Each one takes
426
+ * the request as the server received it: the address the provider called,
427
+ * the raw body and the headers.
428
+ */
429
+ /** The fields of a form body, or of a query string */
430
+ type SignedParams = Record<string, string | string[]> | URLSearchParams;
431
+ interface TwilioSignatureOptions {
432
+ /** Auth token of the account */
433
+ authToken: string;
434
+ /** The `X-Twilio-Signature` header */
435
+ signature: string | null | undefined;
436
+ /**
437
+ * The address Twilio called, query string included, as configured at
438
+ * Twilio: `https://`, or `wss://` for the stream of a call
439
+ */
440
+ url: string;
441
+ /** The fields of the form body of a POST, none for a GET or a stream */
442
+ params?: SignedParams;
443
+ }
444
+ /**
445
+ * Checks the `X-Twilio-Signature` of a request of Twilio: its voice webhooks,
446
+ * status callbacks and the opening of a Media Stream.
447
+ *
448
+ * Tries the address with and without its default port, as the Twilio SDK
449
+ * does, and with a trailing slash for a stream, as Twilio advises.
450
+ *
451
+ * @returns Whether Twilio signed the request
452
+ * @see https://www.twilio.com/docs/usage/security#validating-requests
453
+ */
454
+ declare function validateTwilioSignature({ authToken, signature, url, params, }: TwilioSignatureOptions): boolean;
455
+ interface TelnyxSignatureOptions {
456
+ /** Public key of the account, in base64, as the portal shows it */
457
+ publicKey: string;
458
+ /** The `telnyx-signature-ed25519` header */
459
+ signature: string | null | undefined;
460
+ /** The `telnyx-timestamp` header */
461
+ timestamp: string | null | undefined;
462
+ /** The raw body of the request, as received */
463
+ body: string;
464
+ /** How old or early the timestamp may be, in seconds, 300 by default */
465
+ tolerance?: number;
466
+ }
467
+ /**
468
+ * Checks the Ed25519 signature of a webhook of Telnyx, and that it is recent
469
+ *
470
+ * @returns Whether Telnyx signed the request in the last five minutes
471
+ * @see https://developers.telnyx.com/docs/messaging/messages/receiving-webhooks
472
+ */
473
+ declare function validateTelnyxSignature({ publicKey, signature, timestamp, body, tolerance, }: TelnyxSignatureOptions): boolean;
474
+ interface VonageSignatureOptions {
475
+ /** Signature secret of the account, in the settings of the dashboard */
476
+ signatureSecret: string;
477
+ /** The `Authorization` header, `Bearer <JWT>` */
478
+ authorization: string | null | undefined;
479
+ /**
480
+ * The raw body of the request, to check against the hash the token carries.
481
+ * Left out or empty, only the token is checked.
482
+ */
483
+ body?: string;
484
+ /** How old the token may be, in seconds, 300 by default */
485
+ tolerance?: number;
486
+ }
487
+ /**
488
+ * Checks the signed JWT Vonage puts on the webhooks of a Voice application:
489
+ * HS256 with the signature secret of the account, and the SHA-256 of the
490
+ * body in its `payload_hash` claim.
491
+ *
492
+ * Signed webhooks are on by default for the applications created since
493
+ * Vonage introduced them, and turn on in the Voice settings of the others.
494
+ *
495
+ * @returns Whether Vonage signed the request
496
+ * @see https://developer.vonage.com/en/getting-started/concepts/webhooks#decoding-signed-webhooks
497
+ */
498
+ declare function validateVonageSignature({ signatureSecret, authorization, body, tolerance, }: VonageSignatureOptions): boolean;
499
+ interface PlivoSignatureOptions {
500
+ /** Auth token of the account, or of the subaccount owning the number */
501
+ authToken: string;
502
+ /** The `X-Plivo-Signature-V3` header, one signature per active token */
503
+ signature: string | null | undefined;
504
+ /** The `X-Plivo-Signature-V3-Nonce` header */
505
+ nonce: string | null | undefined;
506
+ /** The address Plivo called, query string included */
507
+ url: string;
508
+ /** Method of the request */
509
+ method: string;
510
+ /** The fields of the form body of a POST */
511
+ params?: SignedParams;
512
+ }
513
+ /**
514
+ * Checks the V3 signature of a request of Plivo: its answer, hangup and
515
+ * machine detection callbacks
516
+ *
517
+ * @returns Whether Plivo signed the request
518
+ * @see https://www.plivo.com/docs/voice/concepts/signature-validation
519
+ */
520
+ declare function validatePlivoSignature({ authToken, signature, nonce, url, method, params, }: PlivoSignatureOptions): boolean;
521
+
522
+ /**
523
+ * The calls a server runs, by the identifier the provider gave them, to hand
524
+ * them what the provider reports to a webhook rather than to the stream: the
525
+ * answering machine detection, and the steps of a warm transfer on Telnyx.
526
+ *
527
+ * One instance per server. Each transport joins it once created, and leaves
528
+ * it when its call ends.
529
+ *
530
+ * ```ts
531
+ * const calls = new TelephonyCalls()
532
+ * // The stream
533
+ * calls.add(new TwilioTransport(socket, credentials))
534
+ * // The webhook
535
+ * app.post('/twilio/amd', (request) => {
536
+ * calls.twilioMachineDetection(request.body)
537
+ * })
538
+ * ```
539
+ */
540
+ declare class TelephonyCalls {
541
+ private transports;
542
+ private early;
543
+ /**
544
+ * Adds a call, known by its identifier once its stream started
545
+ * @returns The transport, to chain on
546
+ */
547
+ add<Transport extends TelephonyTransport>(transport: Transport): Transport;
548
+ /** The call with this identifier at the provider, while its stream runs */
549
+ get(callId: string): TelephonyTransport | undefined;
550
+ /** Number of calls under way */
551
+ get size(): number;
552
+ /**
553
+ * Hands a result of machine detection to its call, or keeps it a while
554
+ * for a stream that has not started yet
555
+ * @returns Whether the call was found
556
+ */
557
+ machineDetected(callId: string, detection: MachineDetection): boolean;
558
+ /**
559
+ * Reads the request Twilio posts to the `AsyncAmdStatusCallback` of a call
560
+ * @param params - The fields of its form body
561
+ * @returns Whether it carried a result
562
+ */
563
+ twilioMachineDetection(params: Record<string, any> | URLSearchParams): boolean;
564
+ /**
565
+ * Reads a webhook event of a Telnyx Call Control application: the machine
566
+ * detection of a call, and the steps of its warm transfer
567
+ * @param body - The JSON body of the webhook
568
+ * @returns Whether a call of this server had a use for it
569
+ */
570
+ telnyxWebhook(body: unknown): boolean;
571
+ /**
572
+ * Reads an event Vonage posts to the event URL of a call
573
+ * @param body - Its JSON body
574
+ * @returns Whether it carried a result of machine detection
575
+ */
576
+ vonageEvent(body: unknown): boolean;
577
+ /**
578
+ * Reads the request Plivo posts to the `machine_detection_url` of a call
579
+ * @param params - The fields of its form body
580
+ * @returns Whether it carried a result
581
+ */
582
+ plivoMachineDetection(params: Record<string, any> | URLSearchParams): boolean;
583
+ }
199
584
 
200
585
  type TelnyxCodec = 'PCMU' | 'PCMA';
201
586
  interface TelnyxTransportOptions {
@@ -205,11 +590,34 @@ interface TelnyxTransportOptions {
205
590
  */
206
591
  codec?: TelnyxCodec;
207
592
  /**
208
- * API key, to hang up when the assistant ends the call. Telnyx keeps a
209
- * call going when its stream closes, so without it the call stays on the
210
- * line until the caller hangs up.
593
+ * API key, to hang up when the assistant ends the call, transfer it and
594
+ * send keys. Telnyx keeps a call going when its stream closes, so without
595
+ * it the call stays on the line until the caller hangs up.
211
596
  */
212
597
  apiKey?: string;
598
+ /**
599
+ * Call Control application that dials the person of a warm transfer. Its
600
+ * webhooks have to reach `TelephonyCalls.telnyxWebhook()`.
601
+ */
602
+ connectionId?: string;
603
+ /**
604
+ * Voice that speaks the briefing of a warm transfer, as Telnyx names it,
605
+ * `AWS.Polly.Joanna-Neural` by default
606
+ */
607
+ briefingVoice?: string;
608
+ /** Language of the briefing, such as `en-US` */
609
+ briefingLanguage?: string;
610
+ }
611
+ /** A Call Control event, as Telnyx posts it to the webhook of an application */
612
+ interface TelnyxEvent {
613
+ event_type: string;
614
+ payload: {
615
+ call_control_id: string;
616
+ client_state?: string;
617
+ result?: string;
618
+ hangup_cause?: string;
619
+ [key: string]: any;
620
+ };
213
621
  }
214
622
  /**
215
623
  * A call from Telnyx, streamed with bidirectional RTP media streaming.
@@ -224,9 +632,11 @@ interface TelnyxTransportOptions {
224
632
  declare class TelnyxTransport extends TelephonyTransport {
225
633
  private options;
226
634
  private codec;
635
+ private pendingTransfer?;
636
+ private earlyTransferEvents;
227
637
  /**
228
638
  * @param socket - The socket Telnyx opened
229
- * @param options - Codec of the stream and key to hang up with
639
+ * @param options - Codec of the stream, and what Call Control needs
230
640
  */
231
641
  constructor(socket: ConstructorParameters<typeof TelephonyTransport>[0], options?: TelnyxTransportOptions);
232
642
  protected get lineRate(): number;
@@ -235,8 +645,36 @@ declare class TelnyxTransport extends TelephonyTransport {
235
645
  protected writeClear(): void;
236
646
  protected writeMark(name: string): void;
237
647
  protected hangUp(): Promise<void>;
648
+ /** Sends the keys with Call Control, or in the audio without an API key */
649
+ sendDtmf(digits: string): Promise<void>;
650
+ /**
651
+ * Transfers the call with Call Control, then stops the stream. `from`
652
+ * defaults to the number the call was made to.
653
+ */
654
+ transfer({ to, from, timeout }: TransferOptions): Promise<void>;
655
+ /**
656
+ * Dials the person, speaks the briefing to them once they pick up, then
657
+ * bridges the caller to them. Telnyx reports each step to the webhook of
658
+ * the application only, so its events have to reach
659
+ * `TelephonyCalls.telnyxWebhook()`.
660
+ *
661
+ * `from` defaults to the number of your account on the call.
662
+ */
663
+ warmTransfer({ to, from, timeout, briefing, }: WarmTransferOptions): Promise<WarmTransferResult>;
664
+ /**
665
+ * Takes a Call Control event about the person of a warm transfer, which
666
+ * `TelephonyCalls.telnyxWebhook()` routes here
667
+ */
668
+ receiveTelnyxEvent(event: TelnyxEvent): void;
669
+ private bridgeTo;
670
+ private stopStreaming;
671
+ private requireCallId;
672
+ private action;
673
+ private request;
238
674
  private sendJson;
239
675
  }
676
+ /** Reads a client state this package or the application wrote */
677
+ declare function decodeTelnyxState(state: unknown): Record<string, any>;
240
678
  interface TelnyxStreamOptions {
241
679
  /** Address of the WebSocket that runs the call */
242
680
  url: string;
@@ -258,7 +696,149 @@ declare function telnyxStreamOptions({ url, parameters, codec, }: TelnyxStreamOp
258
696
  stream_bidirectional_mode: string;
259
697
  stream_bidirectional_codec: TelnyxCodec;
260
698
  };
699
+ interface TelnyxCallOptions extends TelnyxStreamOptions {
700
+ /** API key of the account */
701
+ apiKey: string;
702
+ /** Call Control application that places the call */
703
+ connectionId: string;
704
+ /** Number to call, in E.164 format, or a SIP URI */
705
+ to: string;
706
+ /** Number of your account that calls */
707
+ from: string;
708
+ /** How long to let the phone ring, in seconds, 30 by default */
709
+ timeout?: number;
710
+ /**
711
+ * Detects whether a person or a machine picked up, `greeting_end` to also
712
+ * hear when the greeting of a machine ends. Telnyx posts the result to the
713
+ * webhook of the application: hand it to `TelephonyCalls.telnyxWebhook()`.
714
+ */
715
+ machineDetection?: boolean | 'detect' | 'greeting_end' | 'premium';
716
+ }
717
+ /**
718
+ * Calls a number, and streams the call to a Micdrop server once picked up
719
+ * @returns The Call Control ID of the call, which the transport gets as
720
+ * `call.callId`
721
+ * @see https://developers.telnyx.com/api-reference/call-commands/dial
722
+ */
723
+ declare function telnyxCall(options: TelnyxCallOptions): Promise<{
724
+ callId: string;
725
+ }>;
726
+ /**
727
+ * Reads a result of the machine detection of Telnyx from a webhook event
728
+ * @param body - The JSON body of the webhook
729
+ */
730
+ declare function telnyxMachineDetection(body: any): {
731
+ callId: string;
732
+ detection: MachineDetection;
733
+ } | undefined;
734
+ /**
735
+ * Reads the call a webhook event belongs to: the call itself, or the call a
736
+ * warm transfer was dialing the person for
737
+ * @param body - The JSON body of the webhook
738
+ */
739
+ declare function telnyxEventTarget(body: any): {
740
+ callId: string;
741
+ event: TelnyxEvent;
742
+ transfer: boolean;
743
+ } | undefined;
261
744
 
745
+ /** A number or SIP address the agent can send the call to */
746
+ interface TransferDestination {
747
+ /** Name the model picks it by, such as `sales` */
748
+ name: string;
749
+ /** Phone number in E.164 format, such as `+14155550100`, or a SIP URI */
750
+ to: string;
751
+ /** When to choose it, for the model */
752
+ description?: string;
753
+ }
754
+ interface TransferCallToolOptions {
755
+ /** The one destination, when there is only one */
756
+ to?: string;
757
+ /** Destinations the model picks from, by name */
758
+ destinations?: TransferDestination[];
759
+ /**
760
+ * `cold` hands the call over at once. `warm` reaches the person first and
761
+ * briefs them with a summary the model writes, the caller staying with
762
+ * the assistant until they pick up. `cold` by default.
763
+ */
764
+ mode?: 'cold' | 'warm';
765
+ /** Number the person reached sees, one of your account */
766
+ from?: string;
767
+ /** How long to let the phone ring, in seconds, 30 by default */
768
+ timeout?: number;
769
+ /** Name of the tool, `transfer_call` by default */
770
+ name?: string;
771
+ /** Tells the model when to transfer, in place of the default wording */
772
+ description?: string;
773
+ }
774
+ /**
775
+ * Lets the model send the call to a person or another line: once the words
776
+ * that announce it have been played, the transport transfers the call
777
+ * through the API of its provider, and the assistant leaves.
778
+ *
779
+ * In `warm` mode, the model writes a summary for the person, the provider
780
+ * speaks it to them once they pick up, and the caller joins after. When
781
+ * nobody picks up, the assistant stays on the line and the model hears why.
782
+ *
783
+ * The transport needs the credentials of its provider to transfer.
784
+ */
785
+ declare function transferCallTool(options: TransferCallToolOptions): Tool;
786
+ interface SendDtmfToolOptions {
787
+ /** Name of the tool, `send_dtmf` by default */
788
+ name?: string;
789
+ /** Tells the model when to press keys, in place of the default wording */
790
+ description?: string;
791
+ }
792
+ /**
793
+ * Lets the model press keys on the phone, to find its way through the menu of
794
+ * the phone system it called. The keys go once the answer under way has been
795
+ * played, and the model stays quiet meanwhile.
796
+ */
797
+ declare function sendDtmfTool(options?: SendDtmfToolOptions): Tool;
798
+ interface VoicemailToolOptions {
799
+ /**
800
+ * Message to leave, the same for every call. Without it, the model words
801
+ * it from the conversation.
802
+ */
803
+ message?: string;
804
+ /** Name of the tool, `leave_voicemail` by default */
805
+ name?: string;
806
+ /** Tells the model when it reached a voicemail, in place of the default */
807
+ description?: string;
808
+ }
809
+ /**
810
+ * Lets the model tell a voicemail from a person: once it hears a greeting,
811
+ * it calls the tool, and the assistant waits for the greeting to end, leaves
812
+ * the message and hangs up.
813
+ *
814
+ * It works on every provider, with or without their own detection, on what
815
+ * the speech to text heard.
816
+ */
817
+ declare function voicemailTool(options?: VoicemailToolOptions): Tool;
818
+
819
+ /** Credentials of a Twilio account, to act on calls through its API */
820
+ interface TwilioCredentials {
821
+ /** SID of the account, `AC...` */
822
+ accountSid: string;
823
+ /** Auth token of the account, or the secret of `apiKey` */
824
+ authToken: string;
825
+ /** SID of an API key, `SK...`, to authenticate with it instead */
826
+ apiKey?: string;
827
+ }
828
+ interface TwilioTransportOptions extends Partial<TwilioCredentials> {
829
+ /**
830
+ * Plays to the caller while the person reached in a warm transfer hears
831
+ * the briefing: the address of an audio file or TwiML, as the `waitUrl` of
832
+ * a conference. Twilio plays its own hold music by default, `''` keeps the
833
+ * line silent.
834
+ */
835
+ holdMusicUrl?: string;
836
+ /**
837
+ * Said to the caller when the person reached in a warm transfer hangs up
838
+ * before joining, as TwiML. An apology and a hang up by default.
839
+ */
840
+ transferFallbackTwiml?: string;
841
+ }
262
842
  /**
263
843
  * A call from Twilio, over a bidirectional Media Stream.
264
844
  *
@@ -267,17 +847,49 @@ declare function telnyxStreamOptions({ url, parameters, codec, }: TelnyxStreamOp
267
847
  * μ-law at 8 kHz, and the assistant goes back the same way. Closing the
268
848
  * socket ends the `<Connect>`, and the call with it when nothing follows.
269
849
  *
850
+ * Transfers go through the API of Twilio, and need the credentials of the
851
+ * account. Keys go in the audio, as the stream carries no other way to send
852
+ * them.
853
+ *
270
854
  * SignalWire speaks the same protocol, with its default `PCMU` codec.
271
855
  *
272
856
  * @see https://www.twilio.com/docs/voice/media-streams/websocket-messages
273
857
  */
274
858
  declare class TwilioTransport extends TelephonyTransport {
859
+ private options;
275
860
  protected frameDuration: number;
861
+ /**
862
+ * @param socket - The socket Twilio opened
863
+ * @param options - Credentials of the account, for the transfers
864
+ */
865
+ constructor(socket: ConstructorParameters<typeof TelephonyTransport>[0], options?: TwilioTransportOptions);
276
866
  protected get lineRate(): number;
277
867
  protected onProviderMessage(data: Buffer): void;
278
868
  protected writeAudio(pcm: Buffer): void;
279
869
  protected writeClear(): void;
280
870
  protected writeMark(name: string): void;
871
+ /**
872
+ * Sends the call to another number with a `<Dial>`, which ends the stream.
873
+ * The caller ID stays that of the caller, unless `from` says otherwise.
874
+ */
875
+ transfer({ to, from, timeout }: TransferOptions): Promise<void>;
876
+ /**
877
+ * Calls the person with the briefing and a conference, then moves the
878
+ * caller into that conference once they picked up. The caller hears the
879
+ * hold music while the briefing plays, and the person joins right after.
880
+ *
881
+ * `from` defaults to the number of your account on the call.
882
+ */
883
+ warmTransfer({ to, from, timeout, briefing, }: WarmTransferOptions): Promise<WarmTransferResult>;
884
+ /**
885
+ * Sends the caller the fallback when the person hangs up during the
886
+ * briefing, before the conference started, so the caller does not wait for
887
+ * nobody
888
+ */
889
+ private rescueIfAbandoned;
890
+ private isTransferOver;
891
+ private requireCallId;
892
+ private api;
281
893
  private sendJson;
282
894
  }
283
895
  interface TwilioStreamOptions {
@@ -297,7 +909,118 @@ interface TwilioStreamOptions {
297
909
  * @returns The TwiML document
298
910
  */
299
911
  declare function twilioStreamTwiml({ url, parameters, before, }: TwilioStreamOptions): string;
912
+ interface TwilioCallOptions extends TwilioCredentials, TwilioStreamOptions {
913
+ /** Number to call, in E.164 format, or a SIP URI */
914
+ to: string;
915
+ /** Number of your account that calls */
916
+ from: string;
917
+ /** How long to let the phone ring, in seconds, 30 by default */
918
+ timeout?: number;
919
+ /**
920
+ * Detects whether a person or a machine picked up, without holding the
921
+ * call: the stream starts at once, and Twilio posts the result to
922
+ * `machineDetectionUrl` when it has it, at the end of the greeting of a
923
+ * machine. Hand the request to `TelephonyCalls.twilioMachineDetection()`.
924
+ */
925
+ machineDetection?: boolean;
926
+ /** Where Twilio posts the result of the machine detection */
927
+ machineDetectionUrl?: string;
928
+ /** Where Twilio posts the status of the call as it goes */
929
+ statusCallback?: string;
930
+ }
931
+ /**
932
+ * Calls a number, and streams the call to a Micdrop server once picked up
933
+ * @returns The SID of the call, which the transport gets as `call.callId`
934
+ * @see https://www.twilio.com/docs/voice/api/call-resource#create-a-call-resource
935
+ */
936
+ declare function twilioCall(options: TwilioCallOptions): Promise<{
937
+ callId: string;
938
+ }>;
939
+ /**
940
+ * Reads the result of the machine detection of Twilio, as it posts it to the
941
+ * `AsyncAmdStatusCallback` or to the voice webhook
942
+ * @param params - The fields of the request, parsed from its form body
943
+ */
944
+ declare function twilioMachineDetection(params: Record<string, any> | URLSearchParams): {
945
+ callId: string;
946
+ detection: MachineDetection;
947
+ } | undefined;
948
+
949
+ interface LeaveVoicemailOptions {
950
+ /**
951
+ * Message to leave. Without it, the agent words it from the conversation,
952
+ * told it reached a voicemail.
953
+ */
954
+ message?: string;
955
+ /**
956
+ * How long the line has to stay quiet for the greeting to count as over,
957
+ * in ms, when the provider does not say when it ends. 1500 by default.
958
+ */
959
+ silence?: number;
960
+ /** How long to wait for the greeting to end at most, in ms, 20000 by default */
961
+ maxWait?: number;
962
+ }
963
+ /**
964
+ * Leaves a message on the voicemail that picked up, then hangs up.
965
+ *
966
+ * The assistant stops talking over the greeting, waits for its end, then
967
+ * speaks the message and ends the call once it has been played. The end of
968
+ * the greeting comes from the provider when its detection reports it (the
969
+ * beep), from a pause of the line otherwise.
970
+ *
971
+ * @param server - The call
972
+ * @param options - The message, and how to find the end of the greeting
973
+ */
974
+ declare function leaveVoicemail(server: MicdropServer, options?: LeaveVoicemailOptions): Promise<void>;
975
+ interface AnsweringMachineOptions {
976
+ /**
977
+ * Message to leave on a voicemail, worded by the agent when left out, or
978
+ * `false` to hang up without one
979
+ */
980
+ message?: string | false;
981
+ /** Options of {@link leaveVoicemail} */
982
+ silence?: number;
983
+ maxWait?: number;
984
+ /** Called when the provider found a person on the line */
985
+ onHuman?: (detection: MachineDetection) => void;
986
+ /**
987
+ * Called when it found a machine or a fax, before anything is done.
988
+ * Returning `false` leaves the call to the application.
989
+ */
990
+ onMachine?: (detection: MachineDetection) => void | boolean;
991
+ }
992
+ /**
993
+ * Acts on the answering machine detection of the provider, for an outbound
994
+ * call placed with it: leaves a message on a voicemail and hangs up, hangs
995
+ * up on a fax, and lets the conversation go on with a person.
996
+ *
997
+ * @param server - The call, over a telephony transport
998
+ * @param options - What to do with a machine
999
+ * @returns A function that stops listening
1000
+ */
1001
+ declare function answeringMachine(server: MicdropServer, options?: AnsweringMachineOptions): () => void;
300
1002
 
1003
+ /** Credentials of a Vonage application, to act on calls through its API */
1004
+ interface VonageCredentials {
1005
+ /** ID of the Vonage application */
1006
+ applicationId: string;
1007
+ /** Private key of the application, in PEM format */
1008
+ privateKey: string;
1009
+ }
1010
+ interface VonageTransportOptions extends Partial<VonageCredentials> {
1011
+ /** The rate of the NCCO, read again from the first message */
1012
+ sampleRate?: number;
1013
+ /**
1014
+ * Plays to the caller while the person reached in a warm transfer hears
1015
+ * the briefing, the address of an audio file. Silence by default.
1016
+ */
1017
+ holdMusicUrl?: string;
1018
+ /**
1019
+ * Said to the caller when the person reached in a warm transfer hangs up
1020
+ * before joining
1021
+ */
1022
+ transferFallback?: string;
1023
+ }
301
1024
  /**
302
1025
  * A call from the Vonage Voice API, connected to a WebSocket by the
303
1026
  * `connect` action of its NCCO, which {@link vonageConnectNcco} writes.
@@ -307,24 +1030,54 @@ declare function twilioStreamTwiml({ url, parameters, before, }: TwilioStreamOpt
307
1030
  * twice the quality of a regular phone line. The NCCO headers are the
308
1031
  * parameters of the call.
309
1032
  *
1033
+ * Transfers and keys go through the Voice API, and need the credentials of
1034
+ * the application.
1035
+ *
310
1036
  * @see https://developer.vonage.com/en/voice/voice-api/concepts/websockets
311
1037
  */
312
1038
  declare class VonageTransport extends TelephonyTransport {
1039
+ private options;
313
1040
  private rate;
314
1041
  /**
315
1042
  * @param socket - The socket Vonage opened
316
- * @param options - The rate of the NCCO, read again from the first message
1043
+ * @param options - The rate of the NCCO, and the credentials of the
1044
+ * application for the transfers and keys
317
1045
  */
318
- constructor(socket: ConstructorParameters<typeof TelephonyTransport>[0], options?: {
319
- sampleRate?: number;
320
- });
1046
+ constructor(socket: ConstructorParameters<typeof TelephonyTransport>[0], options?: VonageTransportOptions);
321
1047
  protected get lineRate(): number;
322
1048
  protected onProviderMessage(data: Buffer, isBinary: boolean): void;
323
1049
  protected writeAudio(pcm: Buffer): void;
324
1050
  protected writeClear(): void;
325
1051
  protected writeMark(name: string): void;
1052
+ /** Sends the keys with the Voice API, or in the audio without credentials */
1053
+ sendDtmf(digits: string): Promise<void>;
1054
+ /**
1055
+ * Moves the call to an NCCO that connects it to the number. `from`
1056
+ * defaults to the number of your account on the call.
1057
+ */
1058
+ transfer({ to, from, timeout }: TransferOptions): Promise<void>;
1059
+ /**
1060
+ * Calls the person with the briefing and a named conversation, then moves
1061
+ * the caller into it once they picked up. The person joins right after the
1062
+ * briefing.
1063
+ *
1064
+ * `from` defaults to the number of your account on the call.
1065
+ */
1066
+ warmTransfer({ to, from, timeout, briefing, }: WarmTransferOptions): Promise<WarmTransferResult>;
1067
+ /**
1068
+ * Tells the caller nobody is there when the person hangs up during the
1069
+ * briefing: had they joined, their leaving would have ended the call
1070
+ */
1071
+ private rescueIfAbandoned;
1072
+ private requireCallId;
1073
+ private api;
326
1074
  private sendJson;
327
1075
  }
1076
+ /**
1077
+ * Signs the token the Voice API takes, valid 5 minutes
1078
+ * @see https://developer.vonage.com/en/getting-started/concepts/authentication
1079
+ */
1080
+ declare function vonageJwt({ applicationId, privateKey }: VonageCredentials): string;
328
1081
  interface VonageConnectOptions {
329
1082
  /** Address of the WebSocket that runs the call */
330
1083
  url: string;
@@ -350,5 +1103,39 @@ interface VonageConnectOptions {
350
1103
  * @returns The NCCO, to send as JSON
351
1104
  */
352
1105
  declare function vonageConnectNcco({ url, parameters, call, sampleRate, eventUrl, }: VonageConnectOptions): object[];
1106
+ interface VonageCallOptions extends VonageCredentials, Omit<VonageConnectOptions, 'call'> {
1107
+ /** Number to call, in E.164 format, or a SIP URI */
1108
+ to: string;
1109
+ /** Number of your application that calls */
1110
+ from: string;
1111
+ /** How long to let the phone ring, in seconds, 30 by default */
1112
+ timeout?: number;
1113
+ /**
1114
+ * Detects whether a person or a machine picked up, and when the beep of a
1115
+ * machine sounds. Vonage posts the result to `eventUrl`: hand it to
1116
+ * `TelephonyCalls.vonageEvent()`.
1117
+ */
1118
+ machineDetection?: boolean;
1119
+ }
1120
+ /**
1121
+ * Calls a number, and streams the call to a Micdrop server once picked up.
1122
+ *
1123
+ * The transport learns the identifier of the call from this function, so the
1124
+ * WebSocket has to land on the same process.
1125
+ *
1126
+ * @returns The UUID of the call, which the transport gets as `call.callId`
1127
+ * @see https://developer.vonage.com/en/api/voice#createCall
1128
+ */
1129
+ declare function vonageCall(options: VonageCallOptions): Promise<{
1130
+ callId: string;
1131
+ }>;
1132
+ /**
1133
+ * Reads a result of the machine detection of Vonage from an event
1134
+ * @param body - The JSON body Vonage posted to the event URL
1135
+ */
1136
+ declare function vonageMachineDetection(body: any): {
1137
+ callId: string;
1138
+ detection: MachineDetection;
1139
+ } | undefined;
353
1140
 
354
- export { type PlivoStreamOptions, PlivoTransport, type PlivoTransportOptions, type TelephonyCall, TelephonyTransport, type TelnyxCodec, type TelnyxStreamOptions, TelnyxTransport, type TelnyxTransportOptions, type TwilioStreamOptions, TwilioTransport, type VonageConnectOptions, VonageTransport, alawToPcm16, mulawToPcm16, parseJson, pcm16ToAlaw, pcm16ToMulaw, plivoStreamXml, telnyxStreamOptions, twilioStreamTwiml, vonageConnectNcco };
1141
+ export { type AnsweredBy, type AnsweringMachineOptions, DTMF_DIGITS, type LeaveVoicemailOptions, type MachineDetection, type PlivoCallOptions, type PlivoCredentials, type PlivoSignatureOptions, type PlivoStreamOptions, PlivoTransport, type PlivoTransportOptions, type SendDtmfToolOptions, type SignedParams, TelephonyApiError, type TelephonyCall, TelephonyCalls, TelephonyTransport, type TelephonyTransportEvents, type TelnyxCallOptions, type TelnyxCodec, type TelnyxEvent, type TelnyxSignatureOptions, type TelnyxStreamOptions, TelnyxTransport, type TelnyxTransportOptions, type TransferCallToolOptions, type TransferDestination, type TransferOptions, type TwilioCallOptions, type TwilioCredentials, type TwilioSignatureOptions, type TwilioStreamOptions, TwilioTransport, type TwilioTransportOptions, type VoicemailToolOptions, type VonageCallOptions, type VonageConnectOptions, type VonageCredentials, type VonageSignatureOptions, VonageTransport, type VonageTransportOptions, type WarmTransferFailure, type WarmTransferOptions, type WarmTransferResult, alawToPcm16, answeringMachine, callApi, checkDtmfDigits, decodeTelnyxState, dtmfTones, formBody, leaveVoicemail, mulawToPcm16, parseJson, pcm16ToAlaw, pcm16ToMulaw, plivoCall, plivoMachineDetection, plivoStreamXml, plivoTransferXml, requireOption, sendDtmfTool, sleep, telnyxCall, telnyxEventTarget, telnyxMachineDetection, telnyxStreamOptions, transferCallTool, twilioCall, twilioMachineDetection, twilioStreamTwiml, validatePlivoSignature, validateTelnyxSignature, validateTwilioSignature, validateVonageSignature, voicemailTool, vonageCall, vonageConnectNcco, vonageJwt, vonageMachineDetection };