@jambonz/sdk 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.
Files changed (39) hide show
  1. package/dist/client/index.cjs +119 -0
  2. package/dist/client/index.cjs.map +1 -0
  3. package/dist/client/index.d.cts +58 -0
  4. package/dist/client/index.d.ts +58 -0
  5. package/dist/client/index.js +115 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/common-Bsqv1Brz.d.cts +69 -0
  8. package/dist/common-Bsqv1Brz.d.ts +69 -0
  9. package/dist/index.cjs +1014 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.cts +10 -0
  12. package/dist/index.d.ts +10 -0
  13. package/dist/index.js +996 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/rest-BV_FsqnH.d.cts +97 -0
  16. package/dist/rest-CthGXHnw.d.ts +97 -0
  17. package/dist/types/index.cjs +4 -0
  18. package/dist/types/index.cjs.map +1 -0
  19. package/dist/types/index.d.cts +3 -0
  20. package/dist/types/index.d.ts +3 -0
  21. package/dist/types/index.js +3 -0
  22. package/dist/types/index.js.map +1 -0
  23. package/dist/verb-builder-But-DJle.d.cts +82 -0
  24. package/dist/verb-builder-CO_qoYxC.d.ts +82 -0
  25. package/dist/verbs-B_afNNUM.d.cts +770 -0
  26. package/dist/verbs-B_afNNUM.d.ts +770 -0
  27. package/dist/webhook/index.cjs +320 -0
  28. package/dist/webhook/index.cjs.map +1 -0
  29. package/dist/webhook/index.d.cts +26 -0
  30. package/dist/webhook/index.d.ts +26 -0
  31. package/dist/webhook/index.js +313 -0
  32. package/dist/webhook/index.js.map +1 -0
  33. package/dist/websocket/index.cjs +833 -0
  34. package/dist/websocket/index.cjs.map +1 -0
  35. package/dist/websocket/index.d.cts +179 -0
  36. package/dist/websocket/index.d.ts +179 -0
  37. package/dist/websocket/index.js +822 -0
  38. package/dist/websocket/index.js.map +1 -0
  39. package/package.json +96 -0
package/dist/index.js ADDED
@@ -0,0 +1,996 @@
1
+ import Ajv from 'ajv';
2
+ import { readFileSync } from 'fs';
3
+ import { dirname, resolve } from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import { createHmac, timingSafeEqual } from 'crypto';
6
+ import http from 'http';
7
+ import { WebSocketServer } from 'ws';
8
+ import { EventEmitter } from 'events';
9
+
10
+ // src/validator.ts
11
+ var COMPONENT_SCHEMAS = [
12
+ "auth",
13
+ "actionHook",
14
+ "synthesizer",
15
+ "recognizer",
16
+ "target",
17
+ "vad",
18
+ "bidirectionalAudio",
19
+ "fillerNoise",
20
+ "actionHookDelayAction"
21
+ ];
22
+ var VERB_SCHEMAS = [
23
+ "answer",
24
+ "alert",
25
+ "config",
26
+ "say",
27
+ "play",
28
+ "gather",
29
+ "dial",
30
+ "listen",
31
+ "stream",
32
+ "llm",
33
+ "pipeline",
34
+ "conference",
35
+ "transcribe",
36
+ "enqueue",
37
+ "dequeue",
38
+ "dtmf",
39
+ "dub",
40
+ "hangup",
41
+ "leave",
42
+ "message",
43
+ "pause",
44
+ "redirect",
45
+ "tag",
46
+ "sip-decline",
47
+ "sip-request",
48
+ "sip-refer"
49
+ ];
50
+ function loadSchema(schemaDir, relativePath) {
51
+ const fullPath = resolve(schemaDir, relativePath);
52
+ return JSON.parse(readFileSync(fullPath, "utf-8"));
53
+ }
54
+ function findSchemaDir() {
55
+ const currentDir = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
56
+ const candidates = [
57
+ resolve(currentDir, "../../schema"),
58
+ // from src/
59
+ resolve(currentDir, "../../../schema")
60
+ // from dist/
61
+ ];
62
+ for (const candidate of candidates) {
63
+ try {
64
+ readFileSync(resolve(candidate, "jambonz-app.schema.json"), "utf-8");
65
+ return candidate;
66
+ } catch {
67
+ }
68
+ }
69
+ throw new Error(
70
+ "Could not find jambonz schema directory. Ensure the schema/ directory is present alongside the typescript/ directory."
71
+ );
72
+ }
73
+ var JambonzValidator = class {
74
+ validateApp;
75
+ ajv;
76
+ constructor(schemaDir) {
77
+ const dir = schemaDir ?? findSchemaDir();
78
+ this.ajv = new Ajv({
79
+ allErrors: true,
80
+ strict: false,
81
+ validateSchema: false,
82
+ logger: false
83
+ });
84
+ for (const name of COMPONENT_SCHEMAS) {
85
+ const schema = loadSchema(dir, `components/${name}.schema.json`);
86
+ this.ajv.addSchema(schema);
87
+ }
88
+ for (const name of VERB_SCHEMAS) {
89
+ const schema = loadSchema(dir, `verbs/${name}.schema.json`);
90
+ this.ajv.addSchema(schema);
91
+ }
92
+ const appSchema = loadSchema(dir, "jambonz-app.schema.json");
93
+ this.validateApp = this.ajv.compile(appSchema);
94
+ }
95
+ /** Validate a complete verb array (a jambonz application). */
96
+ validate(app) {
97
+ const valid = this.validateApp(app);
98
+ if (valid) {
99
+ return { valid: true, errors: [] };
100
+ }
101
+ return {
102
+ valid: false,
103
+ errors: formatErrors(this.validateApp.errors)
104
+ };
105
+ }
106
+ /** Validate a single verb object. */
107
+ validateVerb(verb) {
108
+ return this.validate([verb]);
109
+ }
110
+ };
111
+ function formatErrors(errors) {
112
+ if (!errors) return [];
113
+ return errors.map((err) => ({
114
+ path: err.instancePath || "/",
115
+ message: err.message || "Unknown validation error"
116
+ }));
117
+ }
118
+ var _defaultValidator = null;
119
+ function getValidator(schemaDir) {
120
+ if (!_defaultValidator) {
121
+ _defaultValidator = new JambonzValidator(schemaDir);
122
+ }
123
+ return _defaultValidator;
124
+ }
125
+
126
+ // src/verb-builder.ts
127
+ var VerbBuilder = class {
128
+ verbs = [];
129
+ validator;
130
+ constructor(opts) {
131
+ if (opts?.validate === false) {
132
+ this.validator = null;
133
+ } else {
134
+ this.validator = new JambonzValidator(opts?.schemaDir);
135
+ }
136
+ }
137
+ // --- Audio & Speech ---
138
+ say(opts) {
139
+ return this.addVerb({ verb: "say", ...opts });
140
+ }
141
+ play(opts) {
142
+ return this.addVerb({ verb: "play", ...opts });
143
+ }
144
+ gather(opts) {
145
+ return this.addVerb({ verb: "gather", ...opts });
146
+ }
147
+ // --- AI & Real-time ---
148
+ llm(opts) {
149
+ return this.addVerb({ verb: "llm", ...opts });
150
+ }
151
+ pipeline(opts) {
152
+ return this.addVerb({ verb: "pipeline", ...opts });
153
+ }
154
+ listen(opts) {
155
+ return this.addVerb({ verb: "listen", ...opts });
156
+ }
157
+ stream(opts) {
158
+ return this.addVerb({ verb: "stream", ...opts });
159
+ }
160
+ transcribe(opts) {
161
+ return this.addVerb({ verb: "transcribe", ...opts });
162
+ }
163
+ // --- Call Control ---
164
+ dial(opts) {
165
+ return this.addVerb({ verb: "dial", ...opts });
166
+ }
167
+ conference(opts) {
168
+ return this.addVerb({ verb: "conference", ...opts });
169
+ }
170
+ enqueue(opts) {
171
+ return this.addVerb({ verb: "enqueue", ...opts });
172
+ }
173
+ dequeue(opts) {
174
+ return this.addVerb({ verb: "dequeue", ...opts });
175
+ }
176
+ hangup(opts) {
177
+ return this.addVerb({ verb: "hangup", ...opts });
178
+ }
179
+ redirect(opts) {
180
+ return this.addVerb({ verb: "redirect", ...opts });
181
+ }
182
+ pause(opts) {
183
+ return this.addVerb({ verb: "pause", ...opts });
184
+ }
185
+ leave(opts) {
186
+ return this.addVerb({ verb: "leave", ...opts });
187
+ }
188
+ // --- SIP ---
189
+ sipDecline(opts) {
190
+ return this.addVerb({ verb: "sip:decline", ...opts });
191
+ }
192
+ sipRequest(opts) {
193
+ return this.addVerb({ verb: "sip:request", ...opts });
194
+ }
195
+ sipRefer(opts) {
196
+ return this.addVerb({ verb: "sip:refer", ...opts });
197
+ }
198
+ // --- Utility ---
199
+ config(opts) {
200
+ return this.addVerb({ verb: "config", ...opts });
201
+ }
202
+ answer(opts) {
203
+ return this.addVerb({ verb: "answer", ...opts });
204
+ }
205
+ alert(opts) {
206
+ return this.addVerb({ verb: "alert", ...opts });
207
+ }
208
+ tag(opts) {
209
+ return this.addVerb({ verb: "tag", ...opts });
210
+ }
211
+ dtmf(opts) {
212
+ return this.addVerb({ verb: "dtmf", ...opts });
213
+ }
214
+ dub(opts) {
215
+ return this.addVerb({ verb: "dub", ...opts });
216
+ }
217
+ message(opts) {
218
+ return this.addVerb({ verb: "message", ...opts });
219
+ }
220
+ // --- Raw JSON input (primary AI agent path) ---
221
+ /**
222
+ * Add one or more verbs from raw JSON.
223
+ * Validates against the JSON schemas at runtime if validation is enabled.
224
+ */
225
+ addVerbs(verbs) {
226
+ if (this.validator) {
227
+ const result = this.validator.validate(verbs);
228
+ if (!result.valid) {
229
+ const messages = result.errors.map((e) => `${e.path}: ${e.message}`).join("; ");
230
+ throw new Error(`Verb validation failed: ${messages}`);
231
+ }
232
+ }
233
+ this.verbs.push(...verbs);
234
+ return this;
235
+ }
236
+ // --- Internal ---
237
+ addVerb(verb) {
238
+ if (this.validator) {
239
+ const result = this.validator.validateVerb(verb);
240
+ if (!result.valid) {
241
+ const messages = result.errors.map((e) => `${e.path}: ${e.message}`).join("; ");
242
+ throw new Error(`Verb '${verb.verb}' validation failed: ${messages}`);
243
+ }
244
+ }
245
+ this.verbs.push(verb);
246
+ return this;
247
+ }
248
+ /** Get the current verb count. */
249
+ get length() {
250
+ return this.verbs.length;
251
+ }
252
+ /** Clear all queued verbs. */
253
+ clear() {
254
+ this.verbs = [];
255
+ return this;
256
+ }
257
+ /** Returns a copy of the current verb array. */
258
+ toJSON() {
259
+ return [...this.verbs];
260
+ }
261
+ };
262
+ var WebhookResponse = class extends VerbBuilder {
263
+ constructor(opts) {
264
+ super(opts);
265
+ }
266
+ /** Returns the verb array for JSON serialization. */
267
+ toJSON() {
268
+ return [...this.verbs];
269
+ }
270
+ /**
271
+ * Express-compatible middleware for verifying jambonz webhook signatures.
272
+ * Uses HMAC-SHA256 with timing-safe comparison.
273
+ */
274
+ static verifySignature(secret, opts) {
275
+ const tolerance = opts?.tolerance ?? 300;
276
+ return (req, _res, next) => {
277
+ try {
278
+ const signature = req.headers["jambonz-signature"];
279
+ if (!signature) {
280
+ throw new Error("Missing Jambonz-Signature header");
281
+ }
282
+ const parts = signature.split(",");
283
+ let timestamp = "";
284
+ const signatures = [];
285
+ for (const part of parts) {
286
+ const [key, value] = part.split("=");
287
+ if (key === "t") timestamp = value;
288
+ else if (key === "v1") signatures.push(value);
289
+ }
290
+ if (!timestamp || signatures.length === 0) {
291
+ throw new Error("Invalid Jambonz-Signature format");
292
+ }
293
+ const ts = parseInt(timestamp, 10);
294
+ const now = Math.floor(Date.now() / 1e3);
295
+ if (Math.abs(now - ts) > tolerance) {
296
+ throw new Error("Webhook signature timestamp outside tolerance");
297
+ }
298
+ const payload = typeof req.body === "string" ? req.body : JSON.stringify(req.body);
299
+ const signedPayload = `${timestamp}.${payload}`;
300
+ const expected = createHmac("sha256", secret).update(signedPayload).digest("hex");
301
+ const matched = signatures.some((sig) => {
302
+ try {
303
+ return timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
304
+ } catch {
305
+ return false;
306
+ }
307
+ });
308
+ if (!matched) {
309
+ throw new Error("Webhook signature verification failed");
310
+ }
311
+ next();
312
+ } catch (err) {
313
+ next(err instanceof Error ? err : new Error(String(err)));
314
+ }
315
+ };
316
+ }
317
+ };
318
+ var Session = class extends EventEmitter {
319
+ callSid;
320
+ b3;
321
+ data;
322
+ /** Application-specific storage that persists for the session. */
323
+ locals = {};
324
+ ws;
325
+ logger;
326
+ msgid;
327
+ acked = false;
328
+ builder;
329
+ commandQueue = [];
330
+ ttsCounter = 0;
331
+ ttsPaused = false;
332
+ constructor(opts) {
333
+ super();
334
+ this.ws = opts.ws;
335
+ this.logger = opts.logger;
336
+ this.msgid = opts.msg.msgid;
337
+ this.callSid = opts.msg.data?.call_sid ?? opts.msg.call_sid ?? "";
338
+ this.b3 = opts.msg.b3;
339
+ this.data = opts.msg.data ?? {};
340
+ this.builder = new VerbBuilder({
341
+ validate: opts.validate,
342
+ schemaDir: opts.schemaDir
343
+ });
344
+ this.ws.on("message", (data) => {
345
+ this.onMessage(data);
346
+ });
347
+ this.ws.on("close", (code, reason) => {
348
+ this.emit("close", code, reason);
349
+ });
350
+ this.ws.on("error", (err) => {
351
+ this.emit("error", err);
352
+ });
353
+ }
354
+ // ---------------------------------------------------------------------------
355
+ // Verb builder delegation — same API as VerbBuilder
356
+ // ---------------------------------------------------------------------------
357
+ say(opts) {
358
+ this.builder.say(opts);
359
+ return this;
360
+ }
361
+ play(opts) {
362
+ this.builder.play(opts);
363
+ return this;
364
+ }
365
+ gather(opts) {
366
+ this.builder.gather(opts);
367
+ return this;
368
+ }
369
+ llm(opts) {
370
+ this.builder.llm(opts);
371
+ return this;
372
+ }
373
+ pipeline(opts) {
374
+ this.builder.pipeline(opts);
375
+ return this;
376
+ }
377
+ listen(opts) {
378
+ this.builder.listen(opts);
379
+ return this;
380
+ }
381
+ stream(opts) {
382
+ this.builder.stream(opts);
383
+ return this;
384
+ }
385
+ transcribe(opts) {
386
+ this.builder.transcribe(opts);
387
+ return this;
388
+ }
389
+ dial(opts) {
390
+ this.builder.dial(opts);
391
+ return this;
392
+ }
393
+ conference(opts) {
394
+ this.builder.conference(opts);
395
+ return this;
396
+ }
397
+ enqueue(opts) {
398
+ this.builder.enqueue(opts);
399
+ return this;
400
+ }
401
+ dequeue(opts) {
402
+ this.builder.dequeue(opts);
403
+ return this;
404
+ }
405
+ hangup(opts) {
406
+ this.builder.hangup(opts);
407
+ return this;
408
+ }
409
+ redirect(opts) {
410
+ this.builder.redirect(opts);
411
+ return this;
412
+ }
413
+ pause(opts) {
414
+ this.builder.pause(opts);
415
+ return this;
416
+ }
417
+ leave(opts) {
418
+ this.builder.leave(opts);
419
+ return this;
420
+ }
421
+ sipDecline(opts) {
422
+ this.builder.sipDecline(opts);
423
+ return this;
424
+ }
425
+ sipRequest(opts) {
426
+ this.builder.sipRequest(opts);
427
+ return this;
428
+ }
429
+ sipRefer(opts) {
430
+ this.builder.sipRefer(opts);
431
+ return this;
432
+ }
433
+ config(opts) {
434
+ this.builder.config(opts);
435
+ return this;
436
+ }
437
+ answer(opts) {
438
+ this.builder.answer(opts);
439
+ return this;
440
+ }
441
+ alert(opts) {
442
+ this.builder.alert(opts);
443
+ return this;
444
+ }
445
+ tag(opts) {
446
+ this.builder.tag(opts);
447
+ return this;
448
+ }
449
+ dtmf(opts) {
450
+ this.builder.dtmf(opts);
451
+ return this;
452
+ }
453
+ dub(opts) {
454
+ this.builder.dub(opts);
455
+ return this;
456
+ }
457
+ message(opts) {
458
+ this.builder.message(opts);
459
+ return this;
460
+ }
461
+ /** Add raw JSON verbs (primary AI agent path). */
462
+ addVerbs(verbs) {
463
+ this.builder.addVerbs(verbs);
464
+ return this;
465
+ }
466
+ // ---------------------------------------------------------------------------
467
+ // Send / Reply
468
+ // ---------------------------------------------------------------------------
469
+ /** Send queued verbs to jambonz. */
470
+ send(opts) {
471
+ const execImmediate = opts?.execImmediate ?? true;
472
+ const data = this.builder.toJSON();
473
+ this.builder.clear();
474
+ if (!this.acked) {
475
+ this.acked = true;
476
+ const response = {
477
+ type: "ack",
478
+ msgid: this.msgid,
479
+ data
480
+ };
481
+ this.wsSend(response);
482
+ } else {
483
+ const response = {
484
+ type: "command",
485
+ command: "redirect",
486
+ queueCommand: !execImmediate,
487
+ data
488
+ };
489
+ this.wsSend(response);
490
+ }
491
+ }
492
+ /** Reply to an actionHook/eventHook with queued verbs. */
493
+ reply(opts) {
494
+ const execImmediate = opts?.execImmediate ?? true;
495
+ const data = this.builder.toJSON();
496
+ this.builder.clear();
497
+ const response = {
498
+ type: "ack",
499
+ msgid: this.msgid,
500
+ data
501
+ };
502
+ if (!execImmediate) {
503
+ response.type = "command";
504
+ response.command = "redirect";
505
+ response.queueCommand = true;
506
+ }
507
+ this.wsSend(response);
508
+ }
509
+ // ---------------------------------------------------------------------------
510
+ // Inject commands (immediate execution, bypass verb queue)
511
+ // ---------------------------------------------------------------------------
512
+ /** Send an inject command for immediate execution. */
513
+ injectCommand(command, data, callSid) {
514
+ this.wsSend({
515
+ type: "command",
516
+ command: "inject",
517
+ data: {
518
+ command,
519
+ ...typeof data === "object" && data !== null ? data : {},
520
+ ...callSid ? { call_sid: callSid } : {}
521
+ }
522
+ });
523
+ }
524
+ /** Redirect call execution to a new webhook. */
525
+ injectRedirect(hook, callSid) {
526
+ this.injectCommand("redirect", { call_hook: hook }, callSid);
527
+ }
528
+ /** Inject a whisper verb (say/play) to one party on the call. */
529
+ injectWhisper(verb, callSid) {
530
+ this.injectCommand("whisper", Array.isArray(verb) ? verb : [verb], callSid);
531
+ }
532
+ /** Mute or unmute the call. */
533
+ injectMute(status, callSid) {
534
+ this.injectCommand("mute:status", { mute_status: status }, callSid);
535
+ }
536
+ /** Pause or resume audio streaming (listen/stream). */
537
+ injectListenStatus(status, callSid) {
538
+ this.injectCommand("listen:status", { listen_status: status }, callSid);
539
+ }
540
+ /** Control call recording. */
541
+ injectRecord(action, opts, callSid) {
542
+ this.injectCommand("record", { action, ...opts }, callSid);
543
+ }
544
+ /** Send DTMF digits into the call. */
545
+ injectDtmf(digit, duration, callSid) {
546
+ this.injectCommand("dtmf", { digit, ...duration !== void 0 ? { duration } : {} }, callSid);
547
+ }
548
+ /** Attach metadata to the call. */
549
+ injectTag(data, callSid) {
550
+ this.injectCommand("tag", data, callSid);
551
+ }
552
+ /** Send a generic command. */
553
+ sendCommand(command, data) {
554
+ this.wsSend({
555
+ type: "command",
556
+ command,
557
+ data
558
+ });
559
+ }
560
+ /** Send tool output to an active LLM conversation. */
561
+ sendToolOutput(toolCallId, data) {
562
+ this.wsSend({
563
+ type: "command",
564
+ command: "llm:tool-result",
565
+ data: { tool_call_id: toolCallId, ...typeof data === "object" && data !== null ? data : { result: data } }
566
+ });
567
+ }
568
+ /** Update an active LLM conversation. */
569
+ updateLlm(data) {
570
+ this.wsSend({
571
+ type: "command",
572
+ command: "llm:update",
573
+ data
574
+ });
575
+ }
576
+ // ---------------------------------------------------------------------------
577
+ // TTS Token Streaming
578
+ // ---------------------------------------------------------------------------
579
+ /** Whether TTS streaming is paused due to backpressure. */
580
+ get isTtsPaused() {
581
+ return this.ttsPaused;
582
+ }
583
+ /**
584
+ * Send a streaming TTS token.
585
+ * Returns a promise that resolves when jambonz acknowledges receipt.
586
+ * Backpressure is applied automatically: if jambonz signals 'full',
587
+ * subsequent tokens queue until a 'stream_resumed' event arrives.
588
+ */
589
+ sendTtsTokens(text) {
590
+ return new Promise((resolve2, reject) => {
591
+ const id = ++this.ttsCounter;
592
+ this.commandQueue.push({ type: "tokens", id, tokens: text, resolve: resolve2, reject });
593
+ if (this.commandQueue.length === 1 && !this.ttsPaused) {
594
+ this.processQueue();
595
+ }
596
+ });
597
+ }
598
+ /** Queue a TTS flush command. Sent immediately if the queue is empty. */
599
+ flushTtsTokens() {
600
+ if (this.commandQueue.length === 0) {
601
+ this.sendCommand("tts:flush");
602
+ } else {
603
+ this.commandQueue.push({
604
+ type: "flush",
605
+ id: ++this.ttsCounter,
606
+ resolve: () => {
607
+ },
608
+ reject: () => {
609
+ }
610
+ });
611
+ }
612
+ }
613
+ /** Clear all pending TTS tokens and send tts:clear. */
614
+ clearTtsTokens() {
615
+ for (const entry of this.commandQueue) {
616
+ if (entry.type === "tokens") {
617
+ entry.resolve();
618
+ }
619
+ }
620
+ this.commandQueue = [];
621
+ this.ttsPaused = false;
622
+ this.sendCommand("tts:clear");
623
+ }
624
+ processQueue() {
625
+ while (this.commandQueue.length > 0 && this.commandQueue[0].type === "flush") {
626
+ const entry = this.commandQueue.shift();
627
+ this.sendCommand("tts:flush");
628
+ entry.resolve();
629
+ }
630
+ if (this.commandQueue.length > 0 && !this.ttsPaused) {
631
+ const entry = this.commandQueue[0];
632
+ this.wsSend({
633
+ type: "command",
634
+ command: "tts:tokens",
635
+ data: { id: entry.id, tokens: entry.tokens }
636
+ });
637
+ }
638
+ }
639
+ handleTtsTokensResult(data) {
640
+ if (this.commandQueue.length === 0) return;
641
+ const entry = this.commandQueue[0];
642
+ if (entry.type !== "tokens") return;
643
+ const { status, reason } = data;
644
+ if (status === "ok") {
645
+ this.commandQueue.shift();
646
+ entry.resolve();
647
+ } else if (reason === "full") {
648
+ this.ttsPaused = true;
649
+ entry.resolve();
650
+ } else {
651
+ this.commandQueue.shift();
652
+ entry.reject(new Error(`tts-token error: ${reason}`));
653
+ }
654
+ if (this.commandQueue.length > 0 && !this.ttsPaused) {
655
+ this.processQueue();
656
+ }
657
+ }
658
+ handleUserInterruption() {
659
+ for (const entry of this.commandQueue) {
660
+ if (entry.type === "tokens") {
661
+ entry.resolve();
662
+ }
663
+ }
664
+ this.commandQueue = [];
665
+ this.ttsPaused = false;
666
+ this.emit("tts:user_interrupt");
667
+ }
668
+ resumeTtsStreaming() {
669
+ this.ttsPaused = false;
670
+ this.processQueue();
671
+ }
672
+ // ---------------------------------------------------------------------------
673
+ // Inbound message handling
674
+ // ---------------------------------------------------------------------------
675
+ onMessage(raw) {
676
+ try {
677
+ const str = typeof raw === "string" ? raw : Buffer.from(raw).toString("utf-8");
678
+ const msg = JSON.parse(str);
679
+ const { type, msgid, data, hook } = msg;
680
+ switch (type) {
681
+ case "verb:hook":
682
+ case "session:redirect":
683
+ case "dial:confirm":
684
+ this.msgid = msgid;
685
+ if (hook && this.listenerCount(hook) > 0) {
686
+ this.emit(hook, data);
687
+ } else if (type === "verb:hook" && this.listenerCount("verb:hook") > 0) {
688
+ this.emit("verb:hook", hook, data);
689
+ } else {
690
+ this.reply();
691
+ }
692
+ break;
693
+ case "llm:event":
694
+ case "llm:tool-call":
695
+ if (hook) {
696
+ this.emit(hook, data);
697
+ }
698
+ this.emit(type, data);
699
+ break;
700
+ case "tts:streaming-event":
701
+ if (data?.event_type === "stream_resumed") {
702
+ this.resumeTtsStreaming();
703
+ } else if (data?.event_type === "user_interruption") {
704
+ this.handleUserInterruption();
705
+ }
706
+ this.emit("tts:streaming-event", data);
707
+ break;
708
+ case "tts:tokens-result":
709
+ this.handleTtsTokensResult(data ?? {});
710
+ break;
711
+ case "call:status":
712
+ case "verb:status":
713
+ case "jambonz:error":
714
+ this.emit(type, data);
715
+ break;
716
+ default:
717
+ this.logger.debug({ type }, "Session: unhandled message type");
718
+ }
719
+ } catch (err) {
720
+ this.logger.info({ err }, "Session: error handling message");
721
+ }
722
+ }
723
+ // ---------------------------------------------------------------------------
724
+ // Utilities
725
+ // ---------------------------------------------------------------------------
726
+ wsSend(msg) {
727
+ if (this.ws.readyState === 1) {
728
+ this.ws.send(JSON.stringify(msg));
729
+ }
730
+ }
731
+ /** Close the WebSocket connection. */
732
+ close() {
733
+ this.ws.close();
734
+ }
735
+ toJSON() {
736
+ return this.data;
737
+ }
738
+ };
739
+
740
+ // src/websocket/client.ts
741
+ var WsClient = class extends EventEmitter {
742
+ logger;
743
+ path;
744
+ constructor(logger, path) {
745
+ super();
746
+ this.logger = logger;
747
+ this.path = path;
748
+ }
749
+ /** Handle a new WebSocket connection. Called by the endpoint on upgrade. */
750
+ handle(ws, req) {
751
+ const onMessage = (data) => {
752
+ try {
753
+ const raw = typeof data === "string" ? data : Buffer.from(data).toString("utf-8");
754
+ const msg = JSON.parse(raw);
755
+ this.onSessionMessage(ws, req, msg, onMessage);
756
+ } catch (err) {
757
+ this.logger.info({ err }, "WsClient: error parsing message");
758
+ }
759
+ };
760
+ ws.on("message", onMessage);
761
+ }
762
+ onSessionMessage(ws, req, msg, onMessage) {
763
+ const { type } = msg;
764
+ if (type === "session:new" || type === "session:adulting" || type === "session:reconnect") {
765
+ ws.removeListener("message", onMessage);
766
+ const session = new Session({ ws, msg, logger: this.logger });
767
+ this.emit("session:new", session, this.path, req);
768
+ } else if (type === "session:redirect") {
769
+ ws.removeListener("message", onMessage);
770
+ const session = new Session({ ws, msg, logger: this.logger });
771
+ if (this.listenerCount("session:redirect") > 0) {
772
+ this.emit("session:redirect", session, this.path, req);
773
+ } else {
774
+ this.emit("session:new", session, this.path, req);
775
+ }
776
+ } else {
777
+ this.logger.debug({ type }, "WsClient: unexpected message type before session");
778
+ }
779
+ }
780
+ };
781
+
782
+ // src/websocket/router.ts
783
+ var WsRouter = class {
784
+ routes = [];
785
+ wildcard = null;
786
+ /** Register a client for a path pattern. Use '*' for wildcard. */
787
+ use(path, client) {
788
+ if (path === "*") {
789
+ this.wildcard = client;
790
+ return;
791
+ }
792
+ const normalized = path.startsWith("/") ? path : `/${path}`;
793
+ const chunks = normalized.split("/").filter(Boolean);
794
+ this.routes.push({ path: normalized, chunks, client });
795
+ this.routes.sort((a, b) => b.chunks.length - a.chunks.length);
796
+ }
797
+ /** Find the matching client for a request. Returns undefined if no match. */
798
+ route(req) {
799
+ const pathname = req.url?.split("?")[0];
800
+ if (!pathname) return this.wildcard ?? void 0;
801
+ const urlChunks = pathname.split("/").filter(Boolean);
802
+ for (const route of this.routes) {
803
+ if (route.chunks.length > urlChunks.length) continue;
804
+ const matched = route.chunks.every((chunk, i) => chunk === urlChunks[i]);
805
+ if (matched) {
806
+ const remaining = "/" + urlChunks.slice(route.chunks.length).join("/");
807
+ req.originalUrl = req.url;
808
+ req.url = remaining;
809
+ return route.client;
810
+ }
811
+ }
812
+ return this.wildcard ?? void 0;
813
+ }
814
+ };
815
+
816
+ // src/websocket/endpoint.ts
817
+ var WS_PROTOCOL = "ws.jambonz.org";
818
+ var defaultLogger = {
819
+ info: () => {
820
+ },
821
+ error: () => {
822
+ },
823
+ debug: () => {
824
+ }
825
+ };
826
+ function createEndpoint(opts) {
827
+ const { server, port, logger = defaultLogger, middlewares = [] } = opts;
828
+ const router = new WsRouter();
829
+ const wss = new WebSocketServer({
830
+ noServer: true,
831
+ handleProtocols: (protocols) => {
832
+ if (protocols.has(WS_PROTOCOL)) return WS_PROTOCOL;
833
+ return false;
834
+ }
835
+ });
836
+ server.on("upgrade", (req, socket, head) => {
837
+ const fakeRes = new http.ServerResponse(req);
838
+ runMiddlewares(middlewares, req, fakeRes, (err) => {
839
+ if (err) {
840
+ logger.info({ err }, "Endpoint: middleware rejected upgrade");
841
+ socket.destroy();
842
+ return;
843
+ }
844
+ const client = router.route(req);
845
+ if (!client) {
846
+ logger.debug({ url: req.url }, "Endpoint: no route for WebSocket upgrade");
847
+ socket.destroy();
848
+ return;
849
+ }
850
+ wss.handleUpgrade(req, socket, head, (ws) => {
851
+ client.handle(ws, req);
852
+ });
853
+ });
854
+ });
855
+ if (port && !server.listening) {
856
+ server.listen(port);
857
+ }
858
+ return function makeService({ path }) {
859
+ const client = new WsClient(logger, path);
860
+ router.use(path, client);
861
+ return client;
862
+ };
863
+ }
864
+ function runMiddlewares(middlewares, req, res, done) {
865
+ let i = 0;
866
+ function next(err) {
867
+ if (err) return done(err);
868
+ if (i >= middlewares.length) return done();
869
+ const mw = middlewares[i++];
870
+ try {
871
+ const result = mw(req, res, next);
872
+ if (result instanceof Promise) {
873
+ result.catch(next);
874
+ }
875
+ } catch (e) {
876
+ next(e instanceof Error ? e : new Error(String(e)));
877
+ }
878
+ }
879
+ next();
880
+ }
881
+
882
+ // src/client/api.ts
883
+ var HttpClient = class {
884
+ baseUrl;
885
+ headers;
886
+ constructor(opts) {
887
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "") + "/v1";
888
+ this.headers = {
889
+ "Authorization": `Bearer ${opts.apiKey}`,
890
+ "Content-Type": "application/json"
891
+ };
892
+ }
893
+ async get(path) {
894
+ const res = await fetch(`${this.baseUrl}${path}`, {
895
+ method: "GET",
896
+ headers: this.headers
897
+ });
898
+ if (!res.ok) throw new Error(`GET ${path} failed: ${res.status} ${res.statusText}`);
899
+ return res.json();
900
+ }
901
+ async post(path, body) {
902
+ const res = await fetch(`${this.baseUrl}${path}`, {
903
+ method: "POST",
904
+ headers: this.headers,
905
+ body: JSON.stringify(body)
906
+ });
907
+ if (!res.ok) throw new Error(`POST ${path} failed: ${res.status} ${res.statusText}`);
908
+ return res.json();
909
+ }
910
+ async put(path, body) {
911
+ const res = await fetch(`${this.baseUrl}${path}`, {
912
+ method: "PUT",
913
+ headers: this.headers,
914
+ body: JSON.stringify(body)
915
+ });
916
+ if (!res.ok) throw new Error(`PUT ${path} failed: ${res.status} ${res.statusText}`);
917
+ }
918
+ async del(path) {
919
+ const res = await fetch(`${this.baseUrl}${path}`, {
920
+ method: "DELETE",
921
+ headers: this.headers
922
+ });
923
+ if (!res.ok) throw new Error(`DELETE ${path} failed: ${res.status} ${res.statusText}`);
924
+ }
925
+ };
926
+ var CallsResource = class {
927
+ constructor(http2, accountSid) {
928
+ this.http = http2;
929
+ this.accountSid = accountSid;
930
+ }
931
+ /** Create a new outbound call. */
932
+ async create(opts) {
933
+ const result = await this.http.post(
934
+ `/Accounts/${this.accountSid}/Calls`,
935
+ opts
936
+ );
937
+ return result.sid;
938
+ }
939
+ /** Get info about an active call. */
940
+ async get(callSid) {
941
+ return this.http.get(
942
+ `/Accounts/${this.accountSid}/Calls/${callSid}`
943
+ );
944
+ }
945
+ /** Update an active call (redirect, mute, hangup, etc). */
946
+ async update(callSid, opts) {
947
+ return this.http.put(
948
+ `/Accounts/${this.accountSid}/Calls/${callSid}`,
949
+ opts
950
+ );
951
+ }
952
+ /** Terminate a call. */
953
+ async delete(callSid) {
954
+ return this.http.del(
955
+ `/Accounts/${this.accountSid}/Calls/${callSid}`
956
+ );
957
+ }
958
+ /** Redirect call execution to a new webhook URL. */
959
+ async redirect(callSid, hook) {
960
+ return this.update(callSid, { call_hook: hook });
961
+ }
962
+ /** Inject a whisper verb (say/play) to one party on the call. */
963
+ async whisper(callSid, verb) {
964
+ return this.update(callSid, { whisper: verb });
965
+ }
966
+ /** Mute or unmute a call. */
967
+ async mute(callSid, status) {
968
+ return this.update(callSid, { mute_status: status });
969
+ }
970
+ };
971
+ var MessagesResource = class {
972
+ constructor(http2, accountSid) {
973
+ this.http = http2;
974
+ this.accountSid = accountSid;
975
+ }
976
+ /** Send an SMS/MMS message. */
977
+ async create(opts) {
978
+ return this.http.post(
979
+ `/Accounts/${this.accountSid}/Messages`,
980
+ opts
981
+ );
982
+ }
983
+ };
984
+ var JambonzClient = class {
985
+ calls;
986
+ messages;
987
+ constructor(opts) {
988
+ const http2 = new HttpClient(opts);
989
+ this.calls = new CallsResource(http2, opts.accountSid);
990
+ this.messages = new MessagesResource(http2, opts.accountSid);
991
+ }
992
+ };
993
+
994
+ export { CallsResource, JambonzClient, JambonzValidator, MessagesResource, Session, VerbBuilder, WebhookResponse, WsClient, WsRouter, createEndpoint, getValidator };
995
+ //# sourceMappingURL=index.js.map
996
+ //# sourceMappingURL=index.js.map