@jambonz/sdk 0.3.0 → 0.3.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 (40) hide show
  1. package/AGENTS.md +721 -0
  2. package/examples/agent/ws-app.ts +138 -0
  3. package/examples/assemblyai-autogenerate-prompt/app.js +92 -0
  4. package/examples/assemblyai-autogenerate-prompt/package.json +14 -0
  5. package/examples/bedrock-agent.ts +267 -0
  6. package/examples/call-recording/README.md +24 -0
  7. package/examples/call-recording/app.ts +70 -0
  8. package/examples/call-recording/ws-app.ts +47 -0
  9. package/examples/deepgram-voice-agent/ws-app.ts +118 -0
  10. package/examples/dial/app.ts +22 -0
  11. package/examples/echo/app.ts +65 -0
  12. package/examples/echo/ws-app.ts +67 -0
  13. package/examples/elevenlabs-voice-agent/ws-app.ts +81 -0
  14. package/examples/hello-world/README.md +15 -0
  15. package/examples/hello-world/app.js +20 -0
  16. package/examples/hello-world/app.ts +19 -0
  17. package/examples/hello-world/ws-app.ts +18 -0
  18. package/examples/ivr-menu/README.md +15 -0
  19. package/examples/ivr-menu/app.js +85 -0
  20. package/examples/ivr-menu/app.ts +70 -0
  21. package/examples/listen-record/app.ts +22 -0
  22. package/examples/llm-streaming/ws-app.ts +96 -0
  23. package/examples/openai-realtime/ws-app.ts +131 -0
  24. package/examples/queue-with-hold/README.md +19 -0
  25. package/examples/queue-with-hold/app.ts +68 -0
  26. package/examples/queue-with-hold/ws-app.ts +41 -0
  27. package/examples/realtime-translator/src/app.ts +21 -0
  28. package/examples/realtime-translator/src/routes/translator.ts +108 -0
  29. package/examples/realtime-translator/src/utils/config.ts +21 -0
  30. package/examples/realtime-translator/src/utils/translate.ts +23 -0
  31. package/examples/retell-hosted/src/app.ts +22 -0
  32. package/examples/retell-hosted/src/config.ts +53 -0
  33. package/examples/retell-hosted/src/retell.ts +166 -0
  34. package/examples/two-stage-dialer/app.ts +96 -0
  35. package/examples/ultravox-voice-agent/ws-app.ts +116 -0
  36. package/examples/voice-agent/README.md +19 -0
  37. package/examples/voice-agent/app.js +133 -0
  38. package/examples/voice-agent/app.ts +132 -0
  39. package/examples/voice-agent/ws-app.ts +137 -0
  40. package/package.json +9 -4
package/AGENTS.md ADDED
@@ -0,0 +1,721 @@
1
+ # @jambonz/sdk — Node.js SDK Guide
2
+
3
+ This guide covers the @jambonz/sdk TypeScript/JavaScript SDK. For the language-agnostic jambonz verb model and protocol reference, see the AGENTS.md in the @jambonz/schema package or use the jambonz MCP server:
4
+
5
+ - **Remote**: `https://mcp-server.jambonz.app/mcp`
6
+ - **Tools**: `jambonz_developer_toolkit` (full guide + schema index), `get_jambonz_schema` (individual verb/component schemas)
7
+
8
+ ## Before You Start — Ask the User
9
+
10
+ Before generating any jambonz application code, ask the user: **"Do you prefer TypeScript or JavaScript?"** Then generate all code examples in their chosen language. If they don't have a preference, default to TypeScript.
11
+
12
+ ## Using the @jambonz/sdk
13
+
14
+ **IMPORTANT**: Always use the `@jambonz/sdk` package (version 0.1.x+) to build jambonz applications. The older packages `@jambonz/node-client-ws` and `@jambonz/node-client` are **deprecated and replaced** by `@jambonz/sdk`. Do NOT use those old packages. Do NOT build apps with raw JSON verb arrays and plain Express/WS — use `@jambonz/sdk`.
15
+
16
+ **IMPORTANT — App Environment Variables vs process.env**: jambonz applications should NEVER use `process.env` for application-configurable values (phone numbers, API keys, language preferences, greeting text, etc.). Instead, use **jambonz application environment variables** — a two-step pattern:
17
+ 1. **Declare** the variables so the jambonz portal can discover them (via `envVars` option for WebSocket, or `envVarsMiddleware` for webhook).
18
+ 2. **Read** the values at runtime from the call payload (`session.data.env_vars` for WebSocket, `req.body.env_vars` for webhook).
19
+
20
+ Both steps are required. Declaring without reading means values are ignored. Reading without declaring means the portal won't know about them and won't send them. See the [Application Environment Variables](#application-environment-variables) section for full details.
21
+
22
+ Install: `npm install @jambonz/sdk`
23
+
24
+ **Dependencies**: Webhook apps also require `express` (`npm install express`). WebSocket apps have no additional dependencies — the SDK includes `ws` internally. When generating a `package.json`, always include all required dependencies.
25
+
26
+ ### Webhook Application (HTTP)
27
+
28
+ Import `WebhookResponse` from `@jambonz/sdk/webhook`. Create an Express server, construct a `WebhookResponse` for each request, chain verb methods, and return it via `res.json()`.
29
+
30
+ **Best practice**: Always include a `POST /call-status` handler. jambonz sends call status change notifications (ringing, in-progress, completed, etc.) to this endpoint. The handler should log the event and return 200. The path `/call-status` is conventional but the user may choose a different path:
31
+
32
+ ```typescript
33
+ app.post('/call-status', (req, res) => {
34
+ console.log(`Call ${req.body.call_sid} status: ${req.body.call_status}`);
35
+ res.sendStatus(200);
36
+ });
37
+ ```
38
+
39
+ ```typescript
40
+ import express from 'express';
41
+ import { WebhookResponse } from '@jambonz/sdk/webhook';
42
+
43
+ const app = express();
44
+ app.use(express.json());
45
+
46
+ app.post('/incoming', (req, res) => {
47
+ const jambonz = new WebhookResponse();
48
+ jambonz
49
+ .say({ text: 'Hello! Welcome to our service.' })
50
+ .gather({
51
+ input: ['speech', 'digits'],
52
+ actionHook: '/handle-input',
53
+ numDigits: 1,
54
+ timeout: 10,
55
+ say: { text: 'Press 1 for sales or 2 for support.' },
56
+ })
57
+ .say({ text: 'We did not receive any input. Goodbye.' })
58
+ .hangup();
59
+
60
+ res.json(jambonz);
61
+ });
62
+
63
+ app.post('/handle-input', (req, res) => {
64
+ const { digits, speech } = req.body;
65
+ const jambonz = new WebhookResponse();
66
+ jambonz.say({ text: `You pressed ${digits || 'nothing'}. Goodbye.` }).hangup();
67
+ res.json(jambonz);
68
+ });
69
+
70
+ // Every webhook app must handle call status events
71
+ app.post('/call-status', (req, res) => {
72
+ console.log(`Call ${req.body.call_sid} status: ${req.body.call_status}`);
73
+ res.sendStatus(200);
74
+ });
75
+
76
+ app.listen(3000, () => console.log('Listening on port 3000'));
77
+ ```
78
+
79
+ ### WebSocket Application
80
+
81
+ Import `createEndpoint` from `@jambonz/sdk/websocket`. Create an HTTP server, call `createEndpoint` to set up WebSocket handling, then register path-based services that receive `session` objects.
82
+
83
+ ```typescript
84
+ import http from 'http';
85
+ import { createEndpoint } from '@jambonz/sdk/websocket';
86
+
87
+ const server = http.createServer();
88
+ const makeService = createEndpoint({ server, port: 3000 });
89
+
90
+ const svc = makeService({ path: '/' });
91
+
92
+ svc.on('session:new', (session) => {
93
+ console.log(`Incoming call: ${session.callSid}`);
94
+
95
+ session
96
+ .say({ text: 'Hello from jambonz over WebSocket!' })
97
+ .hangup()
98
+ .send();
99
+ });
100
+
101
+ console.log('jambonz ws app listening on port 3000');
102
+ ```
103
+
104
+ **Key differences from webhook**: Use `session` instead of `WebhookResponse`. Chain verbs the same way, but call `.send()` at the end to transmit the initial verb array over the WebSocket.
105
+
106
+ ### WebSocket actionHook Events (CRITICAL)
107
+
108
+ In webhook mode, an `actionHook` is just a URL that jambonz POSTs to. In WebSocket mode, the `actionHook` value becomes an **event name** emitted on the session. You MUST bind a handler for it and respond with `.reply()`.
109
+
110
+ **Key rules for WebSocket actionHook handling:**
111
+ 1. Use `session.on('/hookName', (evt) => {...})` to listen for the actionHook event.
112
+ 2. The `evt` object contains the actionHook payload (same fields as the webhook POST body: `reason`, `speech`, `digits`, etc.).
113
+ 3. Respond with `.reply()` — NOT `.send()`. `.send()` is only for the initial verb array (the first response to `session:new`). `.reply()` acknowledges the actionHook and provides the next verb array.
114
+ 4. If no listener is bound for an actionHook, the SDK auto-replies with an empty verb array.
115
+
116
+ ### WebSocket with Gather (speech echo example)
117
+
118
+ ```typescript
119
+ import http from 'http';
120
+ import { createEndpoint } from '@jambonz/sdk/websocket';
121
+
122
+ const server = http.createServer();
123
+ const makeService = createEndpoint({ server, port: 3000 });
124
+
125
+ const svc = makeService({ path: '/' });
126
+
127
+ svc.on('session:new', (session) => {
128
+ // Bind actionHook handler BEFORE sending verbs
129
+ session
130
+ .on('close', (code: number, _reason: Buffer) => {
131
+ console.log(`Session ${session.callSid} closed: ${code}`);
132
+ })
133
+ .on('error', (err: Error) => {
134
+ console.error(`Session ${session.callSid} error:`, err);
135
+ })
136
+ .on('/echo', (evt: Record<string, any>) => {
137
+ // This fires when the gather verb completes (actionHook: '/echo')
138
+ switch (evt.reason) {
139
+ case 'speechDetected': {
140
+ const transcript = evt.speech?.alternatives?.[0]?.transcript || 'nothing';
141
+ session
142
+ .say({ text: `You said: ${transcript}.` })
143
+ .gather({
144
+ input: ['speech'],
145
+ actionHook: '/echo',
146
+ timeout: 10,
147
+ say: { text: 'Please say something else.' },
148
+ })
149
+ .reply(); // reply() — NOT send()
150
+ break;
151
+ }
152
+ case 'timeout':
153
+ session
154
+ .gather({
155
+ input: ['speech'],
156
+ actionHook: '/echo',
157
+ timeout: 10,
158
+ say: { text: 'Are you still there? I didn\'t hear anything.' },
159
+ })
160
+ .reply();
161
+ break;
162
+ default:
163
+ session.reply();
164
+ break;
165
+ }
166
+ });
167
+
168
+ // Send initial verbs to jambonz
169
+ session
170
+ .pause({ length: 1 })
171
+ .gather({
172
+ input: ['speech'],
173
+ actionHook: '/echo',
174
+ timeout: 10,
175
+ say: { text: 'Please say something and I will echo it back to you.' },
176
+ })
177
+ .send(); // send() — first response only
178
+ });
179
+
180
+ console.log('Speech echo WebSocket app listening on port 3000');
181
+ ```
182
+
183
+ **`.send()` vs `.reply()`:**
184
+ - `.send()` — Use ONCE for the initial verb array in response to `session:new`. This acknowledges the session.
185
+ - `.reply()` — Use for ALL subsequent responses (actionHook events, session:redirect). This acknowledges the hook message and provides the next verb array.
186
+
187
+ ### SDK Verb Method Reference
188
+
189
+ Both `WebhookResponse` and `Session` support the same chainable verb methods:
190
+
191
+ `.say(opts)` `.play(opts)` `.gather(opts)` `.dial(opts)` `.llm(opts)` `.s2s(opts)` `.openai_s2s(opts)` `.google_s2s(opts)` `.elevenlabs_s2s(opts)` `.deepgram_s2s(opts)` `.ultravox_s2s(opts)` `.dialogflow(opts)` `.conference(opts)` `.enqueue(opts)` `.dequeue(opts)` `.hangup()` `.pause(opts)` `.redirect(opts)` `.config(opts)` `.tag(opts)` `.dtmf(opts)` `.listen(opts)` `.transcribe(opts)` `.message(opts)` `.stream(opts)` `.agent(opts)` `.dub(opts)` `.alert(opts)` `.answer(opts)` `.leave()` `.sipDecline(opts)` `.sipRefer(opts)` `.sipRequest(opts)`
192
+
193
+ All methods accept the same options as the corresponding verb JSON Schema. Methods are chainable — they return `this`.
194
+
195
+ ### REST API Client
196
+
197
+ ```typescript
198
+ import { JambonzClient } from '@jambonz/sdk/client';
199
+
200
+ const client = new JambonzClient({ baseUrl: 'https://api.jambonz.us', accountSid, apiKey });
201
+
202
+ // Create an outbound call
203
+ await client.calls.create({ from: '+15085551212', to: { type: 'phone', number: '+15085551213' }, call_hook: '/incoming' });
204
+
205
+ // Mid-call control
206
+ await client.calls.whisper(callSid, { verb: 'say', text: 'Supervisor listening.' });
207
+ await client.calls.mute(callSid, 'mute');
208
+ await client.calls.redirect(callSid, 'https://example.com/new-flow');
209
+ await client.calls.update(callSid, { call_status: 'completed' });
210
+ ```
211
+
212
+ ## Application Environment Variables
213
+
214
+ jambonz has a built-in mechanism for application configuration that is **always preferred over `process.env`**. It works in two required steps:
215
+
216
+ 1. **Declare** — Your app declares its configurable parameters with a schema. The jambonz portal discovers these via an HTTP `OPTIONS` request and renders a configuration form for administrators.
217
+ 2. **Receive** — When a call arrives, jambonz delivers the configured values in the call payload as `env_vars`. Your app reads them from there.
218
+
219
+ **IMPORTANT**: Both steps are required. If you only declare without reading, the values are ignored. If you only read without declaring, the portal won't discover the parameters and won't send them. NEVER use `process.env` for values that should be configurable per-application in the jambonz portal.
220
+
221
+ **When to use env vars**: Phone numbers to dial, API keys, language/voice preferences, greeting text, queue names, timeout values, feature flags, or any value that might change between deployments or users. If in doubt, make it an env var.
222
+
223
+ ### Step 1: Define the Schema
224
+
225
+ Define a schema object where each key is a parameter name and the value describes its type and UI behavior:
226
+
227
+ ```typescript
228
+ const envVars = {
229
+ API_KEY: { type: 'string', description: 'Your API key', required: true, obscure: true },
230
+ LANGUAGE: { type: 'string', description: 'TTS language', default: 'en-US', enum: ['en-US', 'es-ES', 'fr-FR'] },
231
+ MAX_RETRIES: { type: 'number', description: 'Max retry attempts', default: 3 },
232
+ CARRIER: { type: 'string', description: 'Outbound carrier', jambonzResource: 'carriers' },
233
+ SYSTEM_PROMPT: { type: 'string', description: 'LLM system prompt', uiHint: 'textarea' },
234
+ TLS_CERT: { type: 'string', description: 'TLS certificate', uiHint: 'filepicker' },
235
+ };
236
+ ```
237
+
238
+ Each parameter supports:
239
+
240
+ | Property | Required | Description |
241
+ |----------|----------|-------------|
242
+ | `type` | Yes | `'string'` \| `'number'` \| `'boolean'` |
243
+ | `description` | Yes | Human-readable label shown in the portal |
244
+ | `required` | No | Whether the user must provide a value |
245
+ | `default` | No | Pre-filled default value |
246
+ | `enum` | No | Array of allowed values — renders as a dropdown |
247
+ | `obscure` | No | Masks the value in the portal UI (for secrets/API keys) |
248
+ | `uiHint` | No | `'input'` (default single-line), `'textarea'` (multi-line), or `'filepicker'` (file upload with textarea) |
249
+ | `jambonzResource` | No | Populate a dropdown from jambonz account data. Currently supports `'carriers'` (lists VoIP carriers on the account) |
250
+
251
+ **Notes on `jambonzResource`**: When set to `'carriers'`, the portal fetches the VoIP carriers configured for the account and renders them as a dropdown. The stored value is the carrier name. This is preferred over hardcoding carrier names or using `enum` with static values.
252
+
253
+ ### Step 2: Register and Read — WebSocket Apps
254
+
255
+ Pass `envVars` to `createEndpoint` to register the declaration (the SDK auto-responds to OPTIONS requests), then read values from `session.data.env_vars`:
256
+
257
+ ```typescript
258
+ import http from 'http';
259
+ import { createEndpoint } from '@jambonz/sdk/websocket';
260
+
261
+ const envVars = {
262
+ GREETING: { type: 'string', description: 'Greeting message', default: 'Hello!' },
263
+ LANGUAGE: { type: 'string', description: 'TTS language', default: 'en-US' },
264
+ };
265
+
266
+ const server = http.createServer();
267
+ const makeService = createEndpoint({ server, port: 3000, envVars }); // Step 1: declare
268
+
269
+ const svc = makeService({ path: '/' });
270
+
271
+ svc.on('session:new', (session) => {
272
+ const greeting = session.data.env_vars?.GREETING || 'Hello!'; // Step 2: read
273
+ const language = session.data.env_vars?.LANGUAGE || 'en-US';
274
+
275
+ session.say({ text: greeting, language }).hangup().send();
276
+ });
277
+ ```
278
+
279
+ ### Step 2: Register and Read — Webhook Apps
280
+
281
+ Use `envVarsMiddleware` to register the declaration (auto-responds to OPTIONS requests), then read values from `req.body.env_vars`:
282
+
283
+ ```typescript
284
+ import express from 'express';
285
+ import { WebhookResponse, envVarsMiddleware } from '@jambonz/sdk/webhook';
286
+
287
+ const envVars = {
288
+ GREETING: { type: 'string', description: 'Greeting message', default: 'Hello!' },
289
+ LANGUAGE: { type: 'string', description: 'TTS language', default: 'en-US' },
290
+ };
291
+
292
+ const app = express();
293
+ app.use(express.json());
294
+ app.use(envVarsMiddleware(envVars)); // Step 1: declare
295
+
296
+ app.post('/incoming', (req, res) => {
297
+ const greeting = req.body.env_vars?.GREETING || 'Hello!'; // Step 2: read
298
+ const language = req.body.env_vars?.LANGUAGE || 'en-US';
299
+
300
+ const jambonz = new WebhookResponse();
301
+ jambonz.say({ text: greeting, language }).hangup();
302
+ res.json(jambonz);
303
+ });
304
+ ```
305
+
306
+ **Note**: `env_vars` is only present in the initial call webhook (or `session:new` for WebSocket), not in subsequent actionHook callbacks. If you need env var values in actionHook handlers, store them in a variable during the initial call.
307
+
308
+ ## Mid-Call Control
309
+
310
+ Active calls can be modified asynchronously — inject verbs, mute, redirect, or start recording while the call is in progress.
311
+
312
+ ### REST API (Webhook Apps)
313
+
314
+ Use `PUT /v1/Accounts/{accountSid}/Calls/{callSid}` to modify an active call:
315
+
316
+ ```json
317
+ { "whisper": { "verb": "say", "text": "Supervisor is listening." } }
318
+ { "mute_status": "mute" }
319
+ { "call_hook": "https://example.com/new-flow" }
320
+ { "call_status": "completed" }
321
+ { "listen_status": "pause" }
322
+ ```
323
+
324
+ The SDK provides typed methods:
325
+ ```typescript
326
+ import { JambonzClient } from '@jambonz/sdk/client';
327
+ const client = new JambonzClient({ baseUrl, accountSid, apiKey });
328
+
329
+ await client.calls.whisper(callSid, { verb: 'say', text: 'Hello' });
330
+ await client.calls.mute(callSid, 'mute');
331
+ await client.calls.redirect(callSid, 'https://example.com/new-flow');
332
+ await client.calls.update(callSid, { call_status: 'completed' });
333
+ ```
334
+
335
+ ### Inject Commands (WebSocket Apps)
336
+
337
+ WebSocket sessions can inject commands for immediate execution:
338
+
339
+ ```typescript
340
+ // Recording
341
+ session.injectRecord('startCallRecording', { siprecServerURL: 'sip:recorder@example.com' });
342
+ session.injectRecord('stopCallRecording');
343
+
344
+ // Whisper a verb to one party
345
+ session.injectWhisper({ verb: 'say', text: 'You have 5 minutes remaining.' });
346
+
347
+ // Mute/unmute
348
+ session.injectMute('mute');
349
+ session.injectMute('unmute');
350
+
351
+ // Pause/resume audio streaming
352
+ session.injectListenStatus('pause');
353
+
354
+ // Send DTMF
355
+ session.injectDtmf('1');
356
+
357
+ // Attach metadata
358
+ session.injectTag({ supervisor: 'jane', priority: 'high' });
359
+
360
+ // Generic inject (for any command)
361
+ session.injectCommand('redirect', { call_hook: '/new-flow' });
362
+
363
+ // Target a specific call leg (e.g., B-leg during a bridged call)
364
+ // Pass call_sid as the third argument to route the command to that leg
365
+ session.injectCommand('dub', { action: 'sayOnTrack', track: 'callee-audio', say: 'Hello' }, dialCallSid);
366
+ ```
367
+
368
+ **Targeting specific call legs:** When bridging calls with `dial`, inject commands default to the A-leg. To target the B-leg, pass its `call_sid` as the third argument. Capture the B-leg call_sid from `call:status` events where `direction === 'outbound'`. See `guide:session-commands` for the full pattern.
369
+
370
+ ## Session Commands
371
+
372
+ Beyond verbs, WebSocket apps can perform async operations at any time during a call: TTS token streaming, inject commands (mute, whisper, DTMF, recording), and LLM tool output. These are SDK method calls that execute immediately without affecting the verb stack.
373
+
374
+ **Fetch the full reference with `guide:session-commands`** — covers all commands with SDK methods, events, setup, and complete examples including how to build a cascaded voice AI agent (app-managed LLM with TTS token streaming).
375
+
376
+ Key capabilities:
377
+ - **TTS token streaming** — `sendTtsTokens()`, `flushTtsTokens()`, `clearTtsTokens()` — pipe LLM tokens to jambonz incrementally for lowest-latency TTS playback. **Not the same as `autoStreamTts`** (which is a jambonz-internal audio optimization).
378
+ - **Inject commands** — `injectMute()`, `injectWhisper()`, `injectDtmf()`, `injectRecord()`, `injectTag()`, `injectListenStatus()` — modify the call mid-stream.
379
+ - **LLM tool output** — `toolOutput()` — return tool call results to the agent verb's LLM.
380
+ - **Cascaded voice AI agents** — build your own STT→LLM→TTS loop using `config` (ttsStream + bargeIn) + `sendTtsTokens()`. Full control over LLM interaction and conversation history.
381
+
382
+ ### Session Events (SDK)
383
+
384
+ The SDK `Session` object emits events for common message types:
385
+
386
+ ```typescript
387
+ // ActionHook events — the hook name IS the event name. Respond with .reply()
388
+ session.on('/echo', (data) => { /* gather actionHook fired */ session.say({text: '...'}).reply(); });
389
+ session.on('/dial-result', (data) => { /* dial actionHook */ session.reply(); });
390
+ session.on('/llm-complete', (data) => { /* llm actionHook */ session.hangup().reply(); });
391
+
392
+ // Fallback — fires for any verb:hook without a specific listener
393
+ session.on('verb:hook', (hook, data) => { /* generic actionHook handler */ });
394
+
395
+ // Status events (informational — no reply needed)
396
+ session.on('verb:status', (data) => { /* verb status notification */ });
397
+ session.on('call:status', (data) => { /* call state change */ });
398
+
399
+ // LLM events
400
+ session.on('llm:tool-call', (data) => { /* tool call from LLM */ });
401
+ session.on('llm:event', (data) => { /* LLM event */ });
402
+
403
+ // TTS streaming — specific lifecycle events
404
+ session.on('tts:stream_open', (data) => { /* vendor connection established */ });
405
+ session.on('tts:stream_paused', (data) => { /* backpressure: buffer full */ });
406
+ session.on('tts:stream_resumed', (data) => { /* backpressure released */ });
407
+ session.on('tts:stream_closed', (data) => { /* TTS stream ended */ });
408
+ session.on('tts:user_interruption', (data) => { /* user barge-in (with event data) */ });
409
+ session.on('tts:user_interrupt', () => { /* user barge-in (convenience, no data) */ });
410
+ // Catch-all for any TTS streaming event
411
+ session.on('tts:streaming-event', (data) => { /* data.event_type has the type */ });
412
+
413
+ // Connection lifecycle
414
+ session.on('close', (code, reason) => { /* connection closed */ });
415
+ session.on('error', (err) => { /* error */ });
416
+ ```
417
+
418
+ ## Audio WebSocket (Listen/Stream)
419
+
420
+ The `listen` and `stream` verbs open a separate WebSocket connection from jambonz to your application, carrying raw audio. This is independent of the control WebSocket (`ws.jambonz.org`) — it uses the `audio.drachtio.org` subprotocol.
421
+
422
+ ### Receiving Audio in the Same Application
423
+
424
+ Use `makeService.audio()` to register an audio WebSocket handler on the same server that handles the control pipe:
425
+
426
+ ```typescript
427
+ import http from 'http';
428
+ import { createEndpoint } from '@jambonz/sdk/websocket';
429
+
430
+ const server = http.createServer();
431
+ const makeService = createEndpoint({ server, port: 3000 });
432
+
433
+ // Control pipe — handles call sessions
434
+ const svc = makeService({ path: '/' });
435
+
436
+ // Audio pipe — receives listen/stream audio
437
+ const audioSvc = makeService.audio({ path: '/audio-stream' });
438
+
439
+ svc.on('session:new', (session) => {
440
+ session
441
+ .answer()
442
+ .say({ text: 'Recording your audio.' })
443
+ .listen({
444
+ url: '/audio-stream', // relative path — jambonz connects back to same server
445
+ sampleRate: 16000,
446
+ mixType: 'mono',
447
+ metadata: { purpose: 'recording' },
448
+ })
449
+ .hangup()
450
+ .send();
451
+ });
452
+
453
+ audioSvc.on('connection', (stream) => {
454
+ console.log(`Audio from call ${stream.callSid}, rate=${stream.sampleRate}`);
455
+ console.log('Metadata:', stream.metadata);
456
+
457
+ stream.on('audio', (pcm: Buffer) => {
458
+ // L16 PCM binary frames
459
+ });
460
+
461
+ stream.on('close', () => {
462
+ console.log('Audio stream closed');
463
+ });
464
+ });
465
+ ```
466
+
467
+ ### AudioStream API
468
+
469
+ The `stream` object in the `connection` event is an `AudioStream` instance:
470
+
471
+ **Properties**: `metadata` (initial JSON), `callSid`, `sampleRate`
472
+
473
+ **Events**:
474
+ - `audio` — L16 PCM binary frame (`Buffer`)
475
+ - `dtmf` — `{digit, duration}` (only if `passDtmf: true` on listen verb)
476
+ - `playDone` — `{id}` (after non-streaming playAudio completes)
477
+ - `mark` — `{name, event}` where event is `'playout'` or `'cleared'`
478
+ - `close` — `(code, reason)`
479
+ - `error` — `(err)`
480
+
481
+ ### Sending Audio Back (Bidirectional)
482
+
483
+ The listen verb supports bidirectional audio. There are two modes, controlled by the `bidirectionalAudio.streaming` option on the listen verb.
484
+
485
+ **Non-streaming mode** (`streaming: false`, the default) — send complete audio clips as base64:
486
+
487
+ ```typescript
488
+ stream.playAudio(base64Content, {
489
+ audioContentType: 'raw', // or 'wav'
490
+ sampleRate: 16000,
491
+ id: 'greeting', // optional — returned in playDone event
492
+ queuePlay: true, // true: queue after current; false: interrupt (default)
493
+ });
494
+
495
+ stream.on('playDone', (evt) => {
496
+ console.log(`Finished playing: ${evt.id}`);
497
+ });
498
+ ```
499
+
500
+ Up to 10 playAudio commands can be queued simultaneously.
501
+
502
+ **Streaming mode** (`streaming: true`) — send raw binary PCM frames directly:
503
+
504
+ ```typescript
505
+ // In the listen verb config:
506
+ // bidirectionalAudio: { enabled: true, streaming: true, sampleRate: 16000 }
507
+
508
+ stream.on('audio', (pcm) => {
509
+ // Echo audio back (or send processed/generated audio)
510
+ stream.sendAudio(pcm);
511
+ });
512
+ ```
513
+
514
+ ### Marks (Synchronization Markers)
515
+
516
+ Marks let you track when streamed audio has been played out to the caller. They work **only with bidirectional streaming mode** — you must enable `bidirectionalAudio: { enabled: true, streaming: true }` on the listen verb.
517
+
518
+ The pattern is: stream audio via `sendAudio()`, then send a mark. When all the audio sent before the mark finishes playing out, jambonz sends back a mark event with `event: 'playout'`. This is how you know the caller has heard a specific chunk of audio.
519
+
520
+ ```typescript
521
+ // Listen verb must enable bidirectional streaming for marks to work
522
+ session
523
+ .listen({
524
+ url: '/audio',
525
+ actionHook: '/listen-done',
526
+ bidirectionalAudio: {
527
+ enabled: true,
528
+ streaming: true,
529
+ sampleRate: 8000,
530
+ },
531
+ })
532
+ .send();
533
+
534
+ // In the audio handler:
535
+ audioSvc.on('connection', (stream) => {
536
+ // Stream audio, then mark a sync point
537
+ stream.sendAudio(pcmBuffer);
538
+ stream.sendMark('chunk-1'); // fires 'playout' when audio above finishes playing
539
+
540
+ stream.sendAudio(morePcm);
541
+ stream.sendMark('chunk-2'); // fires 'playout' when this audio finishes
542
+
543
+ // Listen for mark events
544
+ stream.on('mark', (evt) => {
545
+ // evt.name = 'chunk-1' or 'chunk-2'
546
+ // evt.event = 'playout' (audio played) or 'cleared' (mark was cleared)
547
+ });
548
+
549
+ // Clear all pending marks (unplayed marks get event='cleared')
550
+ stream.clearMarks();
551
+ });
552
+ ```
553
+
554
+ **Important**: Without `bidirectionalAudio.streaming: true`, marks are accepted but never fire — there is no playout buffer to sync against. This is the most common mistake when marks appear to silently fail.
555
+
556
+ ### Other Commands
557
+
558
+ ```typescript
559
+ stream.killAudio(); // Stop playback, flush buffer
560
+ stream.disconnect(); // Close connection, end listen verb
561
+ stream.sendMark('sync-pt'); // Insert synchronization marker
562
+ stream.clearMarks(); // Clear all pending markers
563
+ stream.close(); // Close the WebSocket
564
+ ```
565
+
566
+ ## Recording
567
+
568
+ jambonz supports SIPREC-based call recording. Recording is controlled mid-call via inject commands (WebSocket) or future REST API extensions.
569
+
570
+ ### WebSocket Recording
571
+ ```typescript
572
+ // Start recording — sends audio via SIPREC to a recording server
573
+ session.injectRecord('startCallRecording', {
574
+ siprecServerURL: 'sip:recorder@example.com',
575
+ recordingID: 'my-recording-123', // optional
576
+ });
577
+
578
+ // Pause/resume recording
579
+ session.injectRecord('pauseCallRecording');
580
+ session.injectRecord('resumeCallRecording');
581
+
582
+ // Stop recording
583
+ session.injectRecord('stopCallRecording');
584
+ ```
585
+
586
+ **Important**: The `dial` verb must use `anchorMedia: true` for recording to work during bridged calls. Without media anchoring, audio doesn't flow through the jambonz media server.
587
+
588
+ ## Code Structure
589
+
590
+ ### Single File (default)
591
+
592
+ For simple applications with 1-2 routes, put everything in a single file. This is the default for all examples in this repo and is perfectly suitable for production use.
593
+
594
+ ### Multi-File with Routes Directory
595
+
596
+ For applications with 3+ routes or significant per-route logic, split into a `src/` directory with a routes folder:
597
+
598
+ ```
599
+ src/
600
+ app.ts <- entry point: server setup, route registration
601
+ routes/
602
+ incoming.ts <- handler for one endpoint/path
603
+ hold-music.ts
604
+ queue-exit.ts
605
+ ```
606
+
607
+ **Webhook pattern** — each route file exports an Express route handler:
608
+
609
+ ```typescript
610
+ // src/routes/incoming.ts
611
+ import type { Request, Response } from 'express';
612
+ import { WebhookResponse } from '@jambonz/sdk/webhook';
613
+
614
+ export default function incoming(_req: Request, res: Response) {
615
+ const jambonz = new WebhookResponse();
616
+ jambonz
617
+ .say({ text: 'Thank you for calling. Please hold.' })
618
+ .enqueue({ name: 'support', waitHook: '/hold-music', actionHook: '/queue-exit' });
619
+ res.json(jambonz);
620
+ }
621
+ ```
622
+
623
+ ```typescript
624
+ // src/app.ts
625
+ import express from 'express';
626
+ import incoming from './routes/incoming.js';
627
+ import holdMusic from './routes/hold-music.js';
628
+ import queueExit from './routes/queue-exit.js';
629
+
630
+ const app = express();
631
+ app.use(express.json());
632
+
633
+ app.post('/incoming', incoming);
634
+ app.post('/hold-music', holdMusic);
635
+ app.post('/queue-exit', queueExit);
636
+
637
+ app.listen(3000, () => console.log('Listening on port 3000'));
638
+ ```
639
+
640
+ **WebSocket pattern** — there are two cases to consider:
641
+
642
+ 1. **Multiple services** (different `makeService({ path })` calls — each path gets its own `session:new`). Each route file exports a function that takes a session:
643
+
644
+ ```typescript
645
+ // src/routes/caller.ts
646
+ import type { Session } from '@jambonz/sdk/websocket';
647
+
648
+ export default function caller(session: Session) {
649
+ session
650
+ .say({ text: 'Please hold.' })
651
+ .enqueue({ name: 'support', waitHook: '/hold-music', actionHook: '/queue-exit' })
652
+ .send();
653
+ }
654
+ ```
655
+
656
+ ```typescript
657
+ // src/app.ts
658
+ import http from 'http';
659
+ import { createEndpoint } from '@jambonz/sdk/websocket';
660
+ import caller from './routes/caller.js';
661
+ import agent from './routes/agent.js';
662
+
663
+ const server = http.createServer();
664
+ const makeService = createEndpoint({ server, port: 3000 });
665
+
666
+ makeService({ path: '/incoming' }).on('session:new', (session) => caller(session));
667
+ makeService({ path: '/agent' }).on('session:new', (session) => agent(session));
668
+ ```
669
+
670
+ 2. **Multiple actionHook handlers on one session** — extract handler functions, but register them all within `session:new`:
671
+
672
+ ```typescript
673
+ // src/routes/echo-handler.ts
674
+ import type { Session } from '@jambonz/sdk/websocket';
675
+
676
+ export default function echoHandler(session: Session, evt: Record<string, any>) {
677
+ if (evt.reason === 'speechDetected') {
678
+ const text = evt.speech?.alternatives?.[0]?.transcript || 'nothing';
679
+ session.say({ text: `You said: ${text}` })
680
+ .gather({ input: ['speech'], actionHook: '/echo', timeout: 10 })
681
+ .reply();
682
+ } else {
683
+ session.gather({ input: ['speech'], actionHook: '/echo', timeout: 10,
684
+ say: { text: 'I didn\'t hear anything. Try again.' } }).reply();
685
+ }
686
+ }
687
+ ```
688
+
689
+ ```typescript
690
+ // src/app.ts — wire it up
691
+ svc.on('session:new', (session) => {
692
+ session.on('/echo', (evt) => echoHandler(session, evt));
693
+ session.gather({ input: ['speech'], actionHook: '/echo', timeout: 10,
694
+ say: { text: 'Say something.' } }).send();
695
+ });
696
+ ```
697
+
698
+ ### When to Split
699
+
700
+ - **1-2 routes, simple logic** -> single file
701
+ - **3+ routes or substantial per-route logic** -> `src/app.ts` + `src/routes/`
702
+ - **Shared config, prompts, or utilities** -> `src/config.ts`, `src/prompts.ts`, etc.
703
+
704
+ When in doubt, start with a single file. It's easy to split later.
705
+
706
+ ## Examples
707
+
708
+ Complete working examples are in the `examples/` directory:
709
+ - **hello-world** — Minimal greeting (webhook + WebSocket)
710
+ - **echo** — Speech echo using gather with actionHook pattern (webhook + WebSocket). The canonical example for understanding actionHook event handling.
711
+ - **ivr-menu** — Interactive menu with speech and DTMF input (webhook)
712
+ - **dial** — Simple outbound dial to a phone number (webhook)
713
+ - **listen-record** — Record audio using the listen verb to stream to a WebSocket (webhook)
714
+ - **voice-agent** — LLM-powered conversational AI with tool calls (webhook + WebSocket)
715
+ - **openai-realtime** — OpenAI Realtime API voice agent with function calling (WebSocket)
716
+ - **deepgram-voice-agent** — Deepgram Voice Agent API with function calling (WebSocket)
717
+ - **elevenlabs-voice-agent** — ElevenLabs Conversational AI agent (WebSocket). Demonstrates the agent_id auth pattern unique to ElevenLabs.
718
+ - **llm-streaming** — Anthropic LLM with TTS token streaming and barge-in (WebSocket)
719
+ - **queue-with-hold** — Call queue with hold music and agent dequeue (webhook + WebSocket)
720
+ - **call-recording** — Mid-call recording control via REST API and inject commands (webhook + WebSocket)
721
+ - **realtime-translator** — Bridges two parties with real-time speech translation using STT, Google Translate, and TTS dub tracks. Multi-file example with `src/routes/` structure (WebSocket)