@micdrop/telephony 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # 🖐️🎤 Micdrop: Real-Time Voice Conversations with AI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Micdrop website](https://micdrop.dev) | [Documentation](https://micdrop.dev/docs/transports/telephony)
4
+
5
+ Micdrop is a set of open source Typescript packages to build real-time voice conversations with AI agents. It handles all the complexities on the client and server side (microphone, speaker, VAD, network communication, etc) and provides ready-to-use implementations for various AI providers.
6
+
7
+ # @micdrop/telephony
8
+
9
+ Phone calls with a Micdrop voice agent, on your own Node.js server. The transports of this package run a call on the media stream WebSocket of a telephony provider, with the same agent, speech to text and text to speech as in the browser.
10
+
11
+ | Provider | Transport | Audio | Document that connects the call |
12
+ | --- | --- | --- | --- |
13
+ | Twilio, SignalWire | `TwilioTransport` | μ-law, 8 kHz | `twilioStreamTwiml()` |
14
+ | Vonage | `VonageTransport` | Linear PCM, 16 kHz | `vonageConnectNcco()` |
15
+ | Telnyx | `TelnyxTransport` | μ-law or A-law, 8 kHz | `telnyxStreamOptions()` |
16
+ | Plivo | `PlivoTransport` | μ-law, 8 kHz | `plivoStreamXml()` |
17
+
18
+ ```bash
19
+ npm install @micdrop/server @micdrop/telephony @micdrop/vad onnxruntime-node
20
+ ```
21
+
22
+ ## Quick start
23
+
24
+ ```typescript
25
+ import { MicdropServer, waitForParams } from '@micdrop/server'
26
+ import { TwilioTransport, twilioStreamTwiml } from '@micdrop/telephony'
27
+ import '@micdrop/vad/node'
28
+
29
+ // The voice webhook of the number
30
+ app.post('/twilio/voice', async (request, reply) => {
31
+ reply.type('text/xml')
32
+ return twilioStreamTwiml({ url: 'wss://example.com/twilio/stream' })
33
+ })
34
+
35
+ // The stream Twilio opens
36
+ app.get('/twilio/stream', { websocket: true }, async (socket) => {
37
+ const transport = new TwilioTransport(socket)
38
+ const params = await waitForParams(transport, (value) => value)
39
+
40
+ new MicdropServer(transport, {
41
+ vad: 'silero', // A phone line needs the server to find the turns
42
+ firstMessage: 'Hello, thanks for calling. How can I help?',
43
+ agent,
44
+ stt,
45
+ tts,
46
+ })
47
+ })
48
+ ```
49
+
50
+ ## What every transport does
51
+
52
+ - Brings the caller to 16 kHz for the speech to text, and the assistant voice to the rate of the line, with a low pass filter
53
+ - Drops the audio the provider still holds when the caller speaks over the assistant
54
+ - Hangs up once the goodbye has played when the agent ends the call, confirmed by the marks of the provider
55
+ - Hands the parameters of the call to `waitForParams`, and the call identifiers to `transport.call`
56
+ - Emits the keys of the keypad as `Dtmf` events
57
+
58
+ ## License
59
+
60
+ MIT
@@ -0,0 +1,354 @@
1
+ import { MicdropTransport, MicdropServerMessage } from '@micdrop/server';
2
+ import { WebSocket } from 'ws';
3
+
4
+ /**
5
+ * G.711, the codec of the phone network: one byte per sample at 8 kHz, with a
6
+ * logarithmic scale that keeps quiet speech as precise as loud speech.
7
+ *
8
+ * μ-law is the variant of North America and Japan, A-law that of the rest of
9
+ * the world. Both take and give PCM16 mono, little endian.
10
+ */
11
+ /**
12
+ * Decodes μ-law bytes
13
+ * @param bytes - One byte per sample
14
+ * @returns PCM16 mono, little endian
15
+ */
16
+ declare function mulawToPcm16(bytes: Uint8Array): Buffer;
17
+ /**
18
+ * Encodes PCM16 as μ-law
19
+ * @param pcm - PCM16 mono, little endian
20
+ * @returns One byte per sample
21
+ */
22
+ declare function pcm16ToMulaw(pcm: Buffer): Buffer;
23
+ /**
24
+ * Decodes A-law bytes
25
+ * @param bytes - One byte per sample
26
+ * @returns PCM16 mono, little endian
27
+ */
28
+ declare function alawToPcm16(bytes: Uint8Array): Buffer;
29
+ /**
30
+ * Encodes PCM16 as A-law
31
+ * @param pcm - PCM16 mono, little endian
32
+ * @returns One byte per sample
33
+ */
34
+ declare function pcm16ToAlaw(pcm: Buffer): Buffer;
35
+
36
+ /** What the provider says about the call, once its stream has started */
37
+ interface TelephonyCall {
38
+ /** Identifier of the call at the provider, to act on it with its API */
39
+ callId?: string;
40
+ /** Identifier of the media stream at the provider */
41
+ streamId?: string;
42
+ /** Number of the caller, when the provider passes it */
43
+ from?: string;
44
+ /** Number called, when the provider passes it */
45
+ to?: string;
46
+ }
47
+ /**
48
+ * A phone call carried over the media stream WebSocket of a telephony
49
+ * provider.
50
+ *
51
+ * The provider streams the caller as audio at the rate of the line, 8 kHz for
52
+ * most, and plays back what it is sent, buffering it on its side. This class
53
+ * does what all of them need: audio brought to 16 kHz for the server and to
54
+ * the rate of the line for the provider, frames of a fixed duration when the
55
+ * provider wants them, playback confirmed by marks, and a hang up once the
56
+ * goodbye is played. Each provider writes and reads its own messages.
57
+ *
58
+ * A phone line has no client to find the turns: the server needs `vad`.
59
+ */
60
+ declare abstract class TelephonyTransport extends MicdropTransport {
61
+ readonly socket: WebSocket;
62
+ readonly clientTurns = false;
63
+ readonly hangsUp = true;
64
+ /** What the provider said about the call */
65
+ call: TelephonyCall;
66
+ /**
67
+ * Duration of the frames the provider wants, in ms. 0 sends the audio as it
68
+ * comes, for the providers that take any size.
69
+ */
70
+ protected frameDuration: number;
71
+ private ready;
72
+ private pendingWrites;
73
+ private inputResampler?;
74
+ private inputRate;
75
+ private outputResampler?;
76
+ private outputRate;
77
+ private frameRemainder;
78
+ private frameTimer?;
79
+ private markCounter;
80
+ private playbackWaiters;
81
+ private closed;
82
+ /**
83
+ * @param socket - The socket the provider opened, as the `ws` server hands it
84
+ */
85
+ constructor(socket: WebSocket);
86
+ /** Rate of the audio on the line, in Hz */
87
+ protected abstract get lineRate(): number;
88
+ /**
89
+ * Reads a message of the provider
90
+ * @param data - The message, text or binary
91
+ * @param isBinary - Whether it came as a binary frame
92
+ */
93
+ protected abstract onProviderMessage(data: Buffer, isBinary: boolean): void;
94
+ /**
95
+ * Sends audio to be played
96
+ * @param pcm - PCM16 mono at the rate of the line, one frame when
97
+ * `frameDuration` is set
98
+ */
99
+ protected abstract writeAudio(pcm: Buffer): void;
100
+ /** Asks the provider to drop the audio it holds and not played yet */
101
+ protected abstract writeClear(): void;
102
+ /**
103
+ * Asks the provider to say when the audio sent so far has been played
104
+ * @param name - What the provider sends back, given to `markPlayed()`
105
+ */
106
+ protected abstract writeMark(name: string): void;
107
+ get isOpen(): boolean;
108
+ send(message: MicdropServerMessage): void;
109
+ sendAudio(audio: Buffer, sampleRate: number): void;
110
+ clearAudio(): void;
111
+ waitForPlayback(): Promise<void>;
112
+ /**
113
+ * Ends the stream, and the call with it: closing the socket is enough for
114
+ * the providers that end the call when nothing follows the stream, the
115
+ * others hang up through their API in `hangUp()`
116
+ */
117
+ close(code?: number, reason?: string): void;
118
+ /** Hangs up through the API of the provider, for those that need it */
119
+ protected hangUp(): Promise<void>;
120
+ /**
121
+ * The stream has started: keeps what the provider said about the call and
122
+ * sends the audio that waited for it
123
+ * @param call - Identifiers and numbers of the call
124
+ * @param params - Custom parameters of the call, if any
125
+ */
126
+ protected startStream(call: TelephonyCall, params?: any): void;
127
+ /**
128
+ * Hands audio of the caller to the server
129
+ * @param pcm - PCM16 mono at the rate of the line
130
+ */
131
+ protected receiveAudio(pcm: Buffer): void;
132
+ /** The provider played the audio sent before a mark */
133
+ protected markPlayed(name: string): void;
134
+ /** A key was pressed on the keypad of the phone */
135
+ protected receiveDtmf(digit: string): void;
136
+ /** Bytes in one outgoing frame */
137
+ protected get frameBytes(): number;
138
+ private toLineRate;
139
+ private whenReady;
140
+ /** Sends the incomplete frame left, padded with silence */
141
+ private flushFrame;
142
+ private scheduleFrameFlush;
143
+ private cancelFrameFlush;
144
+ private resolvePlayback;
145
+ private onSocketMessage;
146
+ private onSocketClose;
147
+ }
148
+ /** Reads a JSON text message, or nothing when it is not one */
149
+ declare function parseJson(data: Buffer): any;
150
+
151
+ interface PlivoTransportOptions {
152
+ /**
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
155
+ */
156
+ authId?: string;
157
+ authToken?: string;
158
+ }
159
+ /**
160
+ * A call from Plivo, over a bidirectional audio stream.
161
+ *
162
+ * Plivo opens the WebSocket when the call reaches the `<Stream>` of its XML,
163
+ * which {@link plivoStreamXml} writes. The caller comes in μ-law at 8 kHz, and
164
+ * the assistant goes back the same way. The extra headers of the stream are
165
+ * the parameters of the call.
166
+ *
167
+ * @see https://www.plivo.com/docs/voice-agents/audio-streaming/concepts/audio-streaming-reference
168
+ */
169
+ declare class PlivoTransport extends TelephonyTransport {
170
+ private options;
171
+ /**
172
+ * @param socket - The socket Plivo opened
173
+ * @param options - Credentials to hang up with
174
+ */
175
+ constructor(socket: ConstructorParameters<typeof TelephonyTransport>[0], options?: PlivoTransportOptions);
176
+ protected get lineRate(): number;
177
+ protected onProviderMessage(data: Buffer): void;
178
+ protected writeAudio(pcm: Buffer): void;
179
+ protected writeClear(): void;
180
+ protected writeMark(name: string): void;
181
+ protected hangUp(): Promise<void>;
182
+ private sendJson;
183
+ }
184
+ interface PlivoStreamOptions {
185
+ /** Address of the WebSocket that runs the call */
186
+ url: string;
187
+ /**
188
+ * Parameters of the call, which `waitForParams` hands back. Plivo only
189
+ * takes letters and digits in them, 512 bytes at most.
190
+ */
191
+ parameters?: Record<string, string | number>;
192
+ }
193
+ /**
194
+ * Writes the XML that connects a call to a Micdrop server, to answer the
195
+ * answer URL of a Plivo application with
196
+ * @returns The XML document
197
+ */
198
+ declare function plivoStreamXml({ url, parameters }: PlivoStreamOptions): string;
199
+
200
+ type TelnyxCodec = 'PCMU' | 'PCMA';
201
+ interface TelnyxTransportOptions {
202
+ /**
203
+ * Codec of the stream, both ways, `PCMU` by default. It has to match the
204
+ * `stream_codec` and `stream_bidirectional_codec` of the call.
205
+ */
206
+ codec?: TelnyxCodec;
207
+ /**
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.
211
+ */
212
+ apiKey?: string;
213
+ }
214
+ /**
215
+ * A call from Telnyx, streamed with bidirectional RTP media streaming.
216
+ *
217
+ * The call is answered with Call Control, with the stream options that
218
+ * {@link telnyxStreamOptions} writes, and Telnyx opens the WebSocket. The
219
+ * caller comes in G.711 at 8 kHz and the assistant goes back the same way.
220
+ * The parameters of the call travel in its `client_state`.
221
+ *
222
+ * @see https://developers.telnyx.com/docs/voice/programmable-voice/media-streaming
223
+ */
224
+ declare class TelnyxTransport extends TelephonyTransport {
225
+ private options;
226
+ private codec;
227
+ /**
228
+ * @param socket - The socket Telnyx opened
229
+ * @param options - Codec of the stream and key to hang up with
230
+ */
231
+ constructor(socket: ConstructorParameters<typeof TelephonyTransport>[0], options?: TelnyxTransportOptions);
232
+ protected get lineRate(): number;
233
+ protected onProviderMessage(data: Buffer): void;
234
+ protected writeAudio(pcm: Buffer): void;
235
+ protected writeClear(): void;
236
+ protected writeMark(name: string): void;
237
+ protected hangUp(): Promise<void>;
238
+ private sendJson;
239
+ }
240
+ interface TelnyxStreamOptions {
241
+ /** Address of the WebSocket that runs the call */
242
+ url: string;
243
+ /** Parameters of the call, which `waitForParams` hands back */
244
+ parameters?: Record<string, unknown>;
245
+ /** Codec of the stream, both ways, `PCMU` by default */
246
+ codec?: TelnyxCodec;
247
+ }
248
+ /**
249
+ * Writes the stream options of a Call Control `answer`, `dial` or
250
+ * `streaming_start` command, to merge into its body
251
+ * @returns The fields to send to Telnyx
252
+ */
253
+ declare function telnyxStreamOptions({ url, parameters, codec, }: TelnyxStreamOptions): {
254
+ client_state?: string | undefined;
255
+ stream_url: string;
256
+ stream_track: string;
257
+ stream_codec: TelnyxCodec;
258
+ stream_bidirectional_mode: string;
259
+ stream_bidirectional_codec: TelnyxCodec;
260
+ };
261
+
262
+ /**
263
+ * A call from Twilio, over a bidirectional Media Stream.
264
+ *
265
+ * Twilio opens the WebSocket when the call reaches the `<Connect><Stream>`
266
+ * of its TwiML, which {@link twilioStreamTwiml} writes. The caller comes in
267
+ * μ-law at 8 kHz, and the assistant goes back the same way. Closing the
268
+ * socket ends the `<Connect>`, and the call with it when nothing follows.
269
+ *
270
+ * SignalWire speaks the same protocol, with its default `PCMU` codec.
271
+ *
272
+ * @see https://www.twilio.com/docs/voice/media-streams/websocket-messages
273
+ */
274
+ declare class TwilioTransport extends TelephonyTransport {
275
+ protected frameDuration: number;
276
+ protected get lineRate(): number;
277
+ protected onProviderMessage(data: Buffer): void;
278
+ protected writeAudio(pcm: Buffer): void;
279
+ protected writeClear(): void;
280
+ protected writeMark(name: string): void;
281
+ private sendJson;
282
+ }
283
+ interface TwilioStreamOptions {
284
+ /** Address of the WebSocket that runs the call, `wss://` only */
285
+ url: string;
286
+ /**
287
+ * Parameters of the call, which `waitForParams` hands back. Twilio takes no
288
+ * query string in the address, so this is how a call carries its context.
289
+ */
290
+ parameters?: Record<string, string | number | boolean>;
291
+ /** TwiML to say before the stream, for instance a recording notice */
292
+ before?: string;
293
+ }
294
+ /**
295
+ * Writes the TwiML that connects a call to a Micdrop server, to answer the
296
+ * voice webhook of a Twilio number with
297
+ * @returns The TwiML document
298
+ */
299
+ declare function twilioStreamTwiml({ url, parameters, before, }: TwilioStreamOptions): string;
300
+
301
+ /**
302
+ * A call from the Vonage Voice API, connected to a WebSocket by the
303
+ * `connect` action of its NCCO, which {@link vonageConnectNcco} writes.
304
+ *
305
+ * Audio travels both ways as binary frames of 16 bits linear PCM, little
306
+ * endian, at the rate of the `content-type` of the NCCO: 16 kHz by default,
307
+ * twice the quality of a regular phone line. The NCCO headers are the
308
+ * parameters of the call.
309
+ *
310
+ * @see https://developer.vonage.com/en/voice/voice-api/concepts/websockets
311
+ */
312
+ declare class VonageTransport extends TelephonyTransport {
313
+ private rate;
314
+ /**
315
+ * @param socket - The socket Vonage opened
316
+ * @param options - The rate of the NCCO, read again from the first message
317
+ */
318
+ constructor(socket: ConstructorParameters<typeof TelephonyTransport>[0], options?: {
319
+ sampleRate?: number;
320
+ });
321
+ protected get lineRate(): number;
322
+ protected onProviderMessage(data: Buffer, isBinary: boolean): void;
323
+ protected writeAudio(pcm: Buffer): void;
324
+ protected writeClear(): void;
325
+ protected writeMark(name: string): void;
326
+ private sendJson;
327
+ }
328
+ interface VonageConnectOptions {
329
+ /** Address of the WebSocket that runs the call */
330
+ url: string;
331
+ /** Parameters of the call, which `waitForParams` hands back */
332
+ parameters?: Record<string, string | number | boolean>;
333
+ /**
334
+ * The call, as the answer webhook describes it (`uuid`, `from`, `to`), so
335
+ * the transport knows which call it carries
336
+ */
337
+ call?: {
338
+ uuid?: string;
339
+ from?: string;
340
+ to?: string;
341
+ };
342
+ /** Rate of the audio, 16000 by default */
343
+ sampleRate?: 8000 | 16000 | 24000;
344
+ /** Where Vonage sends the events of the WebSocket leg */
345
+ eventUrl?: string;
346
+ }
347
+ /**
348
+ * Writes the NCCO that connects a call to a Micdrop server, to answer the
349
+ * answer webhook of a Vonage application with
350
+ * @returns The NCCO, to send as JSON
351
+ */
352
+ declare function vonageConnectNcco({ url, parameters, call, sampleRate, eventUrl, }: VonageConnectOptions): object[];
353
+
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 };