@jambonz/sdk 0.1.0 → 0.1.2

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.
Files changed (122) hide show
  1. package/dist/client/index.cjs +60 -13
  2. package/dist/client/index.cjs.map +1 -1
  3. package/dist/client/index.d.cts +36 -7
  4. package/dist/client/index.d.ts +36 -7
  5. package/dist/client/index.js +59 -13
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/common-BSJZX7WO.d.cts +34 -0
  8. package/dist/common-BSJZX7WO.d.ts +34 -0
  9. package/dist/index.cjs +364 -32
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +8 -7
  12. package/dist/index.d.ts +8 -7
  13. package/dist/index.js +360 -32
  14. package/dist/index.js.map +1 -1
  15. package/dist/rest-BF9HKZrA.d.ts +136 -0
  16. package/dist/rest-v8weIueZ.d.cts +136 -0
  17. package/dist/session-DHc6G_9y.d.cts +112 -0
  18. package/dist/session-DHc6G_9y.d.ts +112 -0
  19. package/dist/types/index.d.cts +4 -3
  20. package/dist/types/index.d.ts +4 -3
  21. package/dist/{verb-builder-But-DJle.d.cts → verb-builder-Dg_IPC4I.d.ts} +35 -2
  22. package/dist/{verb-builder-CO_qoYxC.d.ts → verb-builder-DkHAJrk4.d.cts} +35 -2
  23. package/dist/{verbs-B_afNNUM.d.cts → verbs-fjJjfGEt.d.cts} +40 -14
  24. package/dist/{verbs-B_afNNUM.d.ts → verbs-fjJjfGEt.d.ts} +40 -14
  25. package/dist/webhook/index.cjs +68 -8
  26. package/dist/webhook/index.cjs.map +1 -1
  27. package/dist/webhook/index.d.cts +45 -3
  28. package/dist/webhook/index.d.ts +45 -3
  29. package/dist/webhook/index.js +68 -9
  30. package/dist/webhook/index.js.map +1 -1
  31. package/dist/websocket/index.cjs +291 -19
  32. package/dist/websocket/index.cjs.map +1 -1
  33. package/dist/websocket/index.d.cts +198 -4
  34. package/dist/websocket/index.d.ts +198 -4
  35. package/dist/websocket/index.js +290 -20
  36. package/dist/websocket/index.js.map +1 -1
  37. package/package.json +19 -6
  38. package/schema/callbacks/base.schema.json +29 -0
  39. package/schema/callbacks/call-status.schema.json +22 -0
  40. package/schema/callbacks/conference-status.schema.json +24 -0
  41. package/schema/callbacks/conference-wait.schema.json +11 -0
  42. package/schema/callbacks/conference.schema.json +11 -0
  43. package/schema/callbacks/dequeue.schema.json +19 -0
  44. package/schema/callbacks/dial-dtmf.schema.json +18 -0
  45. package/schema/callbacks/dial-hold.schema.json +22 -0
  46. package/schema/callbacks/dial-refer.schema.json +28 -0
  47. package/schema/callbacks/dial.schema.json +31 -0
  48. package/schema/callbacks/enqueue-wait.schema.json +17 -0
  49. package/schema/callbacks/enqueue.schema.json +27 -0
  50. package/schema/callbacks/gather-partial.schema.json +54 -0
  51. package/schema/callbacks/gather.schema.json +60 -0
  52. package/schema/callbacks/listen.schema.json +21 -0
  53. package/schema/callbacks/llm.schema.json +30 -0
  54. package/schema/callbacks/message.schema.json +35 -0
  55. package/schema/callbacks/play.schema.json +36 -0
  56. package/schema/callbacks/session-new.schema.json +143 -0
  57. package/schema/callbacks/session-reconnect.schema.json +9 -0
  58. package/schema/callbacks/session-redirect.schema.json +38 -0
  59. package/schema/callbacks/sip-refer-event.schema.json +20 -0
  60. package/schema/callbacks/sip-refer.schema.json +22 -0
  61. package/schema/callbacks/sip-request.schema.json +27 -0
  62. package/schema/callbacks/transcribe-translation.schema.json +24 -0
  63. package/schema/callbacks/transcribe.schema.json +46 -0
  64. package/schema/callbacks/verb-status.schema.json +57 -0
  65. package/schema/components/actionHook.schema.json +36 -0
  66. package/schema/components/actionHookDelayAction.schema.json +37 -0
  67. package/schema/components/amd.schema.json +68 -0
  68. package/schema/components/auth.schema.json +18 -0
  69. package/schema/components/bidirectionalAudio.schema.json +22 -0
  70. package/schema/components/fillerNoise.schema.json +25 -0
  71. package/schema/components/recognizer-assemblyAiOptions.schema.json +35 -0
  72. package/schema/components/recognizer-awsOptions.schema.json +52 -0
  73. package/schema/components/recognizer-azureOptions.schema.json +32 -0
  74. package/schema/components/recognizer-cobaltOptions.schema.json +34 -0
  75. package/schema/components/recognizer-customOptions.schema.json +27 -0
  76. package/schema/components/recognizer-deepgramOptions.schema.json +147 -0
  77. package/schema/components/recognizer-elevenlabsOptions.schema.json +39 -0
  78. package/schema/components/recognizer-gladiaOptions.schema.json +8 -0
  79. package/schema/components/recognizer-googleOptions.schema.json +35 -0
  80. package/schema/components/recognizer-houndifyOptions.schema.json +53 -0
  81. package/schema/components/recognizer-ibmOptions.schema.json +54 -0
  82. package/schema/components/recognizer-nuanceOptions.schema.json +150 -0
  83. package/schema/components/recognizer-nvidiaOptions.schema.json +39 -0
  84. package/schema/components/recognizer-openaiOptions.schema.json +59 -0
  85. package/schema/components/recognizer-sonioxOptions.schema.json +46 -0
  86. package/schema/components/recognizer-speechmaticsOptions.schema.json +91 -0
  87. package/schema/components/recognizer-verbioOptions.schema.json +46 -0
  88. package/schema/components/recognizer.schema.json +212 -0
  89. package/schema/components/synthesizer.schema.json +82 -0
  90. package/schema/components/target.schema.json +105 -0
  91. package/schema/components/vad.schema.json +48 -0
  92. package/schema/jambonz-app.schema.json +106 -0
  93. package/schema/verbs/alert.schema.json +20 -0
  94. package/schema/verbs/answer.schema.json +12 -0
  95. package/schema/verbs/conference.schema.json +43 -0
  96. package/schema/verbs/config.schema.json +170 -0
  97. package/schema/verbs/dequeue.schema.json +36 -0
  98. package/schema/verbs/dial.schema.json +153 -0
  99. package/schema/verbs/dtmf.schema.json +27 -0
  100. package/schema/verbs/dub.schema.json +52 -0
  101. package/schema/verbs/enqueue.schema.json +38 -0
  102. package/schema/verbs/gather.schema.json +145 -0
  103. package/schema/verbs/hangup.schema.json +29 -0
  104. package/schema/verbs/leave.schema.json +12 -0
  105. package/schema/verbs/listen.schema.json +109 -0
  106. package/schema/verbs/llm.schema.json +131 -0
  107. package/schema/verbs/message.schema.json +30 -0
  108. package/schema/verbs/pause.schema.json +26 -0
  109. package/schema/verbs/pipeline.schema.json +61 -0
  110. package/schema/verbs/play.schema.json +69 -0
  111. package/schema/verbs/redirect.schema.json +23 -0
  112. package/schema/verbs/say.schema.json +84 -0
  113. package/schema/verbs/sip-decline.schema.json +31 -0
  114. package/schema/verbs/sip-refer.schema.json +41 -0
  115. package/schema/verbs/sip-request.schema.json +33 -0
  116. package/schema/verbs/stream.schema.json +30 -0
  117. package/schema/verbs/tag.schema.json +21 -0
  118. package/schema/verbs/transcribe.schema.json +48 -0
  119. package/dist/common-Bsqv1Brz.d.cts +0 -69
  120. package/dist/common-Bsqv1Brz.d.ts +0 -69
  121. package/dist/rest-BV_FsqnH.d.cts +0 -97
  122. package/dist/rest-CthGXHnw.d.ts +0 -97
@@ -18,13 +18,31 @@ var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
18
18
  var COMPONENT_SCHEMAS = [
19
19
  "auth",
20
20
  "actionHook",
21
- "synthesizer",
22
- "recognizer",
23
- "target",
24
- "vad",
21
+ "actionHookDelayAction",
22
+ "amd",
25
23
  "bidirectionalAudio",
26
24
  "fillerNoise",
27
- "actionHookDelayAction"
25
+ "recognizer",
26
+ "recognizer-assemblyAiOptions",
27
+ "recognizer-awsOptions",
28
+ "recognizer-azureOptions",
29
+ "recognizer-cobaltOptions",
30
+ "recognizer-customOptions",
31
+ "recognizer-deepgramOptions",
32
+ "recognizer-elevenlabsOptions",
33
+ "recognizer-gladiaOptions",
34
+ "recognizer-googleOptions",
35
+ "recognizer-houndifyOptions",
36
+ "recognizer-ibmOptions",
37
+ "recognizer-nuanceOptions",
38
+ "recognizer-nvidiaOptions",
39
+ "recognizer-openaiOptions",
40
+ "recognizer-sonioxOptions",
41
+ "recognizer-speechmaticsOptions",
42
+ "recognizer-verbioOptions",
43
+ "synthesizer",
44
+ "target",
45
+ "vad"
28
46
  ];
29
47
  var VERB_SCHEMAS = [
30
48
  "answer",
@@ -62,9 +80,9 @@ function findSchemaDir() {
62
80
  const currentDir = typeof __dirname !== "undefined" ? __dirname : path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
63
81
  const candidates = [
64
82
  path.resolve(currentDir, "../../schema"),
65
- // from src/
66
- path.resolve(currentDir, "../../../schema")
67
- // from dist/
83
+ // from typescript/src/
84
+ path.resolve(currentDir, "../schema")
85
+ // from dist/ (tsup bundles to package-root/dist/)
68
86
  ];
69
87
  for (const candidate of candidates) {
70
88
  try {
@@ -127,6 +145,9 @@ function formatErrors(errors) {
127
145
  var VerbBuilder = class {
128
146
  verbs = [];
129
147
  validator;
148
+ /**
149
+ * @param opts - Options for validation and schema directory.
150
+ */
130
151
  constructor(opts) {
131
152
  if (opts?.validate === false) {
132
153
  this.validator = null;
@@ -135,85 +156,111 @@ var VerbBuilder = class {
135
156
  }
136
157
  }
137
158
  // --- Audio & Speech ---
159
+ /** Speak text using TTS. Supports SSML, multiple voices, and streaming. */
138
160
  say(opts) {
139
161
  return this.addVerb({ verb: "say", ...opts });
140
162
  }
163
+ /** Play an audio file from a URL. */
141
164
  play(opts) {
142
165
  return this.addVerb({ verb: "play", ...opts });
143
166
  }
167
+ /** Collect speech (STT) and/or DTMF input from the caller. */
144
168
  gather(opts) {
145
169
  return this.addVerb({ verb: "gather", ...opts });
146
170
  }
147
171
  // --- AI & Real-time ---
172
+ /** Connect the caller to an LLM for real-time voice conversation. */
148
173
  llm(opts) {
149
174
  return this.addVerb({ verb: "llm", ...opts });
150
175
  }
176
+ /** Voice AI pipeline with integrated turn detection. */
151
177
  pipeline(opts) {
152
178
  return this.addVerb({ verb: "pipeline", ...opts });
153
179
  }
180
+ /** Stream real-time call audio to a WebSocket endpoint. Supports bidirectional audio. */
154
181
  listen(opts) {
155
182
  return this.addVerb({ verb: "listen", ...opts });
156
183
  }
184
+ /** Stream real-time call audio to a WebSocket endpoint. Synonym for {@link listen}. */
157
185
  stream(opts) {
158
186
  return this.addVerb({ verb: "stream", ...opts });
159
187
  }
188
+ /** Real-time call transcription sent to a webhook. */
160
189
  transcribe(opts) {
161
190
  return this.addVerb({ verb: "transcribe", ...opts });
162
191
  }
163
192
  // --- Call Control ---
193
+ /** Place an outbound call and bridge it to the current caller. */
164
194
  dial(opts) {
165
195
  return this.addVerb({ verb: "dial", ...opts });
166
196
  }
197
+ /** Join or create a multi-party conference room. */
167
198
  conference(opts) {
168
199
  return this.addVerb({ verb: "conference", ...opts });
169
200
  }
201
+ /** Place the caller into a named queue. */
170
202
  enqueue(opts) {
171
203
  return this.addVerb({ verb: "enqueue", ...opts });
172
204
  }
205
+ /** Remove a caller from a queue and bridge them. */
173
206
  dequeue(opts) {
174
207
  return this.addVerb({ verb: "dequeue", ...opts });
175
208
  }
209
+ /** End the call. */
176
210
  hangup(opts) {
177
211
  return this.addVerb({ verb: "hangup", ...opts });
178
212
  }
213
+ /** Transfer control to a different webhook URL. */
179
214
  redirect(opts) {
180
215
  return this.addVerb({ verb: "redirect", ...opts });
181
216
  }
217
+ /** Wait for a specified duration before continuing. */
182
218
  pause(opts) {
183
219
  return this.addVerb({ verb: "pause", ...opts });
184
220
  }
221
+ /** Leave a conference or queue. */
185
222
  leave(opts) {
186
223
  return this.addVerb({ verb: "leave", ...opts });
187
224
  }
188
225
  // --- SIP ---
226
+ /** Reject an incoming call with a SIP error response. */
189
227
  sipDecline(opts) {
190
228
  return this.addVerb({ verb: "sip:decline", ...opts });
191
229
  }
230
+ /** Send a SIP INFO or other request within the dialog. */
192
231
  sipRequest(opts) {
193
232
  return this.addVerb({ verb: "sip:request", ...opts });
194
233
  }
234
+ /** Transfer the call via SIP REFER. */
195
235
  sipRefer(opts) {
196
236
  return this.addVerb({ verb: "sip:refer", ...opts });
197
237
  }
198
238
  // --- Utility ---
239
+ /** Set session-level defaults (TTS vendor/voice, STT vendor, VAD, etc.). */
199
240
  config(opts) {
200
241
  return this.addVerb({ verb: "config", ...opts });
201
242
  }
243
+ /** Explicitly answer the call (sends a 200 OK). */
202
244
  answer(opts) {
203
245
  return this.addVerb({ verb: "answer", ...opts });
204
246
  }
247
+ /** Send a SIP 180 Ringing with optional Alert-Info header. */
205
248
  alert(opts) {
206
249
  return this.addVerb({ verb: "alert", ...opts });
207
250
  }
251
+ /** Attach metadata to the call for tracking or routing. */
208
252
  tag(opts) {
209
253
  return this.addVerb({ verb: "tag", ...opts });
210
254
  }
255
+ /** Send DTMF tones into the call. */
211
256
  dtmf(opts) {
212
257
  return this.addVerb({ verb: "dtmf", ...opts });
213
258
  }
259
+ /** Mix an auxiliary audio track into the call. */
214
260
  dub(opts) {
215
261
  return this.addVerb({ verb: "dub", ...opts });
216
262
  }
263
+ /** Send an SMS or MMS message. */
217
264
  message(opts) {
218
265
  return this.addVerb({ verb: "message", ...opts });
219
266
  }
@@ -262,8 +309,23 @@ var VerbBuilder = class {
262
309
 
263
310
  // src/websocket/session.ts
264
311
  var Session = class extends events.EventEmitter {
312
+ /** Unique call identifier. */
265
313
  callSid;
314
+ /** Caller phone number or SIP URI. */
315
+ from;
316
+ /** Called phone number or SIP URI. */
317
+ to;
318
+ /** Call direction. */
319
+ direction;
320
+ /** Account identifier. */
321
+ accountSid;
322
+ /** Application identifier. */
323
+ applicationSid;
324
+ /** SIP Call-ID. */
325
+ callId;
326
+ /** Distributed trace header (B3 format), if present. */
266
327
  b3;
328
+ /** Full call session data from jambonz (includes env_vars, SIP headers, etc.). */
267
329
  data;
268
330
  /** Application-specific storage that persists for the session. */
269
331
  locals = {};
@@ -275,14 +337,21 @@ var Session = class extends events.EventEmitter {
275
337
  commandQueue = [];
276
338
  ttsCounter = 0;
277
339
  ttsPaused = false;
340
+ /** @internal */
278
341
  constructor(opts) {
279
342
  super();
280
343
  this.ws = opts.ws;
281
344
  this.logger = opts.logger;
282
345
  this.msgid = opts.msg.msgid;
283
- this.callSid = opts.msg.data?.call_sid ?? opts.msg.call_sid ?? "";
284
- this.b3 = opts.msg.b3;
285
346
  this.data = opts.msg.data ?? {};
347
+ this.callSid = this.data.call_sid ?? opts.msg.call_sid ?? "";
348
+ this.from = this.data.from ?? "";
349
+ this.to = this.data.to ?? "";
350
+ this.direction = this.data.direction ?? "inbound";
351
+ this.accountSid = this.data.account_sid ?? "";
352
+ this.applicationSid = this.data.application_sid ?? "";
353
+ this.callId = this.data.call_id ?? "";
354
+ this.b3 = opts.msg.b3;
286
355
  this.builder = new VerbBuilder({
287
356
  validate: opts.validate,
288
357
  schemaDir: opts.schemaDir
@@ -300,106 +369,132 @@ var Session = class extends events.EventEmitter {
300
369
  // ---------------------------------------------------------------------------
301
370
  // Verb builder delegation — same API as VerbBuilder
302
371
  // ---------------------------------------------------------------------------
372
+ /** Speak text using TTS. Supports SSML, multiple voices, and streaming. */
303
373
  say(opts) {
304
374
  this.builder.say(opts);
305
375
  return this;
306
376
  }
377
+ /** Play an audio file from a URL. */
307
378
  play(opts) {
308
379
  this.builder.play(opts);
309
380
  return this;
310
381
  }
382
+ /** Collect speech (STT) and/or DTMF input from the caller. */
311
383
  gather(opts) {
312
384
  this.builder.gather(opts);
313
385
  return this;
314
386
  }
387
+ /** Connect the caller to an LLM for real-time voice conversation. */
315
388
  llm(opts) {
316
389
  this.builder.llm(opts);
317
390
  return this;
318
391
  }
392
+ /** Voice AI pipeline with integrated turn detection. */
319
393
  pipeline(opts) {
320
394
  this.builder.pipeline(opts);
321
395
  return this;
322
396
  }
397
+ /** Stream real-time call audio to a WebSocket endpoint. Supports bidirectional audio. */
323
398
  listen(opts) {
324
399
  this.builder.listen(opts);
325
400
  return this;
326
401
  }
402
+ /** Stream real-time call audio to a WebSocket endpoint. Synonym for {@link listen}. */
327
403
  stream(opts) {
328
404
  this.builder.stream(opts);
329
405
  return this;
330
406
  }
407
+ /** Real-time call transcription sent to a webhook. */
331
408
  transcribe(opts) {
332
409
  this.builder.transcribe(opts);
333
410
  return this;
334
411
  }
412
+ /** Place an outbound call and bridge it to the current caller. */
335
413
  dial(opts) {
336
414
  this.builder.dial(opts);
337
415
  return this;
338
416
  }
417
+ /** Join or create a multi-party conference room. */
339
418
  conference(opts) {
340
419
  this.builder.conference(opts);
341
420
  return this;
342
421
  }
422
+ /** Place the caller into a named queue. */
343
423
  enqueue(opts) {
344
424
  this.builder.enqueue(opts);
345
425
  return this;
346
426
  }
427
+ /** Remove a caller from a queue and bridge them. */
347
428
  dequeue(opts) {
348
429
  this.builder.dequeue(opts);
349
430
  return this;
350
431
  }
432
+ /** End the call. */
351
433
  hangup(opts) {
352
434
  this.builder.hangup(opts);
353
435
  return this;
354
436
  }
437
+ /** Transfer control to a different webhook URL. */
355
438
  redirect(opts) {
356
439
  this.builder.redirect(opts);
357
440
  return this;
358
441
  }
442
+ /** Wait for a specified duration before continuing. */
359
443
  pause(opts) {
360
444
  this.builder.pause(opts);
361
445
  return this;
362
446
  }
447
+ /** Leave a conference or queue. */
363
448
  leave(opts) {
364
449
  this.builder.leave(opts);
365
450
  return this;
366
451
  }
452
+ /** Reject an incoming call with a SIP error response. */
367
453
  sipDecline(opts) {
368
454
  this.builder.sipDecline(opts);
369
455
  return this;
370
456
  }
457
+ /** Send a SIP INFO or other request within the dialog. */
371
458
  sipRequest(opts) {
372
459
  this.builder.sipRequest(opts);
373
460
  return this;
374
461
  }
462
+ /** Transfer the call via SIP REFER. */
375
463
  sipRefer(opts) {
376
464
  this.builder.sipRefer(opts);
377
465
  return this;
378
466
  }
467
+ /** Set session-level defaults (TTS vendor/voice, STT vendor, VAD, etc.). */
379
468
  config(opts) {
380
469
  this.builder.config(opts);
381
470
  return this;
382
471
  }
472
+ /** Explicitly answer the call (sends a 200 OK). */
383
473
  answer(opts) {
384
474
  this.builder.answer(opts);
385
475
  return this;
386
476
  }
477
+ /** Send a SIP 180 Ringing with optional Alert-Info header. */
387
478
  alert(opts) {
388
479
  this.builder.alert(opts);
389
480
  return this;
390
481
  }
482
+ /** Attach metadata to the call for tracking or routing. */
391
483
  tag(opts) {
392
484
  this.builder.tag(opts);
393
485
  return this;
394
486
  }
487
+ /** Send DTMF tones into the call. */
395
488
  dtmf(opts) {
396
489
  this.builder.dtmf(opts);
397
490
  return this;
398
491
  }
492
+ /** Mix an auxiliary audio track into the call. */
399
493
  dub(opts) {
400
494
  this.builder.dub(opts);
401
495
  return this;
402
496
  }
497
+ /** Send an SMS or MMS message. */
403
498
  message(opts) {
404
499
  this.builder.message(opts);
405
500
  return this;
@@ -453,18 +548,30 @@ var Session = class extends events.EventEmitter {
453
548
  this.wsSend(response);
454
549
  }
455
550
  // ---------------------------------------------------------------------------
551
+ // Verb status events
552
+ // ---------------------------------------------------------------------------
553
+ /**
554
+ * Enable real-time verb status events for this session.
555
+ * Once enabled, the session emits 'verb:status' events for verb lifecycle
556
+ * changes (starting, finished, start-playback, stop-playback, etc.).
557
+ *
558
+ * This is a convenience for `.config({ notifyEvents: true })` — it can be
559
+ * chained into the initial verb sequence or called at any time.
560
+ */
561
+ notifyEvents(enabled = true) {
562
+ this.builder.config({ notifyEvents: enabled });
563
+ return this;
564
+ }
565
+ // ---------------------------------------------------------------------------
456
566
  // Inject commands (immediate execution, bypass verb queue)
457
567
  // ---------------------------------------------------------------------------
458
568
  /** Send an inject command for immediate execution. */
459
569
  injectCommand(command, data, callSid) {
460
570
  this.wsSend({
461
571
  type: "command",
462
- command: "inject",
463
- data: {
464
- command,
465
- ...typeof data === "object" && data !== null ? data : {},
466
- ...callSid ? { call_sid: callSid } : {}
467
- }
572
+ command,
573
+ ...callSid ? { callSid } : {},
574
+ data: typeof data === "object" && data !== null ? data : {}
468
575
  });
469
576
  }
470
577
  /** Redirect call execution to a new webhook. */
@@ -473,7 +580,8 @@ var Session = class extends events.EventEmitter {
473
580
  }
474
581
  /** Inject a whisper verb (say/play) to one party on the call. */
475
582
  injectWhisper(verb, callSid) {
476
- this.injectCommand("whisper", Array.isArray(verb) ? verb : [verb], callSid);
583
+ const whisper = Array.isArray(verb) ? verb : [verb];
584
+ this.injectCommand("whisper", { whisper }, callSid);
477
585
  }
478
586
  /** Mute or unmute the call. */
479
587
  injectMute(status, callSid) {
@@ -649,6 +757,9 @@ var Session = class extends events.EventEmitter {
649
757
  } else if (data?.event_type === "user_interruption") {
650
758
  this.handleUserInterruption();
651
759
  }
760
+ if (data?.event_type) {
761
+ this.emit(`tts:${data.event_type}`, data);
762
+ }
652
763
  this.emit("tts:streaming-event", data);
653
764
  break;
654
765
  case "tts:tokens-result":
@@ -724,6 +835,132 @@ var WsClient = class extends events.EventEmitter {
724
835
  }
725
836
  }
726
837
  };
838
+ var AudioStream = class extends events.EventEmitter {
839
+ metadata;
840
+ callSid;
841
+ sampleRate;
842
+ ws;
843
+ logger;
844
+ constructor(ws, metadata, logger) {
845
+ super();
846
+ this.ws = ws;
847
+ this.logger = logger;
848
+ this.metadata = metadata;
849
+ this.callSid = metadata.callSid;
850
+ this.sampleRate = metadata.sampleRate;
851
+ ws.on("message", (data, isBinary) => {
852
+ if (isBinary) {
853
+ this.emit("audio", Buffer.from(data));
854
+ } else {
855
+ this.onTextMessage(data);
856
+ }
857
+ });
858
+ ws.on("close", (code, reason) => {
859
+ this.emit("close", code, reason.toString());
860
+ });
861
+ ws.on("error", (err) => {
862
+ this.emit("error", err);
863
+ });
864
+ }
865
+ /** Send raw L16 PCM audio back to the caller (streaming mode). */
866
+ sendAudio(pcm) {
867
+ if (this.ws.readyState === 1) {
868
+ this.ws.send(pcm);
869
+ }
870
+ }
871
+ /** Send a playAudio command with base64-encoded audio (non-streaming mode). */
872
+ playAudio(audioContent, opts) {
873
+ this.sendJson({
874
+ type: "playAudio",
875
+ data: {
876
+ audioContent,
877
+ audioContentType: opts?.audioContentType ?? "raw",
878
+ sampleRate: opts?.sampleRate ?? this.sampleRate,
879
+ ...opts?.id !== void 0 ? { id: opts.id } : {},
880
+ ...opts?.queuePlay !== void 0 ? { queuePlay: opts.queuePlay } : {}
881
+ }
882
+ });
883
+ }
884
+ /** Stop any currently playing audio and flush the buffer. */
885
+ killAudio() {
886
+ this.sendJson({ type: "killAudio" });
887
+ }
888
+ /** Tell jambonz to close the connection and end the listen verb. */
889
+ disconnect() {
890
+ this.sendJson({ type: "disconnect" });
891
+ }
892
+ /** Insert a synchronization marker. */
893
+ sendMark(name) {
894
+ this.sendJson({ type: "mark", data: { name } });
895
+ }
896
+ /** Clear all pending markers. */
897
+ clearMarks() {
898
+ this.sendJson({ type: "clearMarks" });
899
+ }
900
+ /** Close the WebSocket connection. */
901
+ close() {
902
+ this.ws.close();
903
+ }
904
+ onTextMessage(raw) {
905
+ try {
906
+ const str = typeof raw === "string" ? raw : Buffer.from(raw).toString("utf-8");
907
+ const msg = JSON.parse(str);
908
+ if (msg.event === "dtmf") {
909
+ this.emit("dtmf", { digit: msg.dtmf, duration: msg.duration });
910
+ return;
911
+ }
912
+ switch (msg.type) {
913
+ case "playDone":
914
+ this.emit("playDone", msg.data ?? {});
915
+ break;
916
+ case "mark":
917
+ this.emit("mark", msg.data ?? {});
918
+ break;
919
+ default:
920
+ this.logger.debug({ msg }, "AudioStream: unhandled text message");
921
+ }
922
+ } catch (err) {
923
+ this.logger.info({ err }, "AudioStream: error parsing text message");
924
+ }
925
+ }
926
+ sendJson(msg) {
927
+ if (this.ws.readyState === 1) {
928
+ this.ws.send(JSON.stringify(msg));
929
+ }
930
+ }
931
+ };
932
+
933
+ // src/websocket/audio-client.ts
934
+ var AudioClient = class extends events.EventEmitter {
935
+ logger;
936
+ path;
937
+ constructor(logger, path) {
938
+ super();
939
+ this.logger = logger;
940
+ this.path = path;
941
+ }
942
+ /** Handle a new audio WebSocket connection. */
943
+ handle(ws, req) {
944
+ const onFirstMessage = (data, isBinary) => {
945
+ ws.removeListener("message", onFirstMessage);
946
+ if (isBinary) {
947
+ this.logger.info("AudioClient: expected JSON metadata as first message, got binary");
948
+ ws.close();
949
+ return;
950
+ }
951
+ try {
952
+ const raw = typeof data === "string" ? data : Buffer.from(data).toString("utf-8");
953
+ const metadata = JSON.parse(raw);
954
+ const stream = new AudioStream(ws, metadata, this.logger);
955
+ this.emit("connection", stream, req);
956
+ } catch (err) {
957
+ this.logger.info({ err }, "AudioClient: error parsing initial metadata");
958
+ ws.close();
959
+ }
960
+ };
961
+ ws.on("message", onFirstMessage);
962
+ }
963
+ };
727
964
 
728
965
  // src/websocket/router.ts
729
966
  var WsRouter = class {
@@ -761,6 +998,7 @@ var WsRouter = class {
761
998
 
762
999
  // src/websocket/endpoint.ts
763
1000
  var WS_PROTOCOL = "ws.jambonz.org";
1001
+ var AUDIO_PROTOCOL = "audio.drachtio.org";
764
1002
  var defaultLogger = {
765
1003
  info: () => {
766
1004
  },
@@ -770,7 +1008,7 @@ var defaultLogger = {
770
1008
  }
771
1009
  };
772
1010
  function createEndpoint(opts) {
773
- const { server, port, logger = defaultLogger, middlewares = [] } = opts;
1011
+ const { server, port, logger = defaultLogger, middlewares = [], envVars } = opts;
774
1012
  const router = new WsRouter();
775
1013
  const wss = new ws.WebSocketServer({
776
1014
  noServer: true,
@@ -779,6 +1017,23 @@ function createEndpoint(opts) {
779
1017
  return false;
780
1018
  }
781
1019
  });
1020
+ const audioWss = new ws.WebSocketServer({
1021
+ noServer: true,
1022
+ handleProtocols: (protocols) => {
1023
+ if (protocols.has(AUDIO_PROTOCOL)) return AUDIO_PROTOCOL;
1024
+ return false;
1025
+ }
1026
+ });
1027
+ const audioRoutes = /* @__PURE__ */ new Map();
1028
+ server.on("request", (req, res) => {
1029
+ if (req.method === "OPTIONS" && envVars) {
1030
+ res.writeHead(200, { "Content-Type": "application/json" });
1031
+ res.end(JSON.stringify(envVars));
1032
+ return;
1033
+ }
1034
+ res.writeHead(426, { "Content-Type": "text/plain" });
1035
+ res.end("Upgrade Required");
1036
+ });
782
1037
  server.on("upgrade", (req, socket, head) => {
783
1038
  const fakeRes = new http__default.default.ServerResponse(req);
784
1039
  runMiddlewares(middlewares, req, fakeRes, (err) => {
@@ -787,6 +1042,14 @@ function createEndpoint(opts) {
787
1042
  socket.destroy();
788
1043
  return;
789
1044
  }
1045
+ const pathname = req.url?.split("?")[0] ?? "/";
1046
+ const audioClient = audioRoutes.get(pathname);
1047
+ if (audioClient) {
1048
+ audioWss.handleUpgrade(req, socket, head, (ws) => {
1049
+ audioClient.handle(ws, req);
1050
+ });
1051
+ return;
1052
+ }
790
1053
  const client = router.route(req);
791
1054
  if (!client) {
792
1055
  logger.debug({ url: req.url }, "Endpoint: no route for WebSocket upgrade");
@@ -801,11 +1064,18 @@ function createEndpoint(opts) {
801
1064
  if (port && !server.listening) {
802
1065
  server.listen(port);
803
1066
  }
804
- return function makeService({ path }) {
1067
+ const makeService = function makeService2({ path }) {
805
1068
  const client = new WsClient(logger, path);
806
1069
  router.use(path, client);
807
1070
  return client;
808
1071
  };
1072
+ makeService.audio = function audio({ path }) {
1073
+ const normalized = path.startsWith("/") ? path : `/${path}`;
1074
+ const client = new AudioClient(logger, normalized);
1075
+ audioRoutes.set(normalized, client);
1076
+ return client;
1077
+ };
1078
+ return makeService;
809
1079
  }
810
1080
  function runMiddlewares(middlewares, req, res, done) {
811
1081
  let i = 0;
@@ -825,6 +1095,8 @@ function runMiddlewares(middlewares, req, res, done) {
825
1095
  next();
826
1096
  }
827
1097
 
1098
+ exports.AudioClient = AudioClient;
1099
+ exports.AudioStream = AudioStream;
828
1100
  exports.Session = Session;
829
1101
  exports.WsClient = WsClient;
830
1102
  exports.WsRouter = WsRouter;