@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
@@ -0,0 +1,96 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ import http from 'http';
3
+ import { createEndpoint } from '@jambonz/sdk/websocket';
4
+
5
+ const ANTHROPIC_MODEL = 'claude-3-5-haiku-latest';
6
+ const systemPrompt = `You are a helpful conversational AI voice bot.
7
+ Please keep your answers short and to the point; the user will follow up with more questions if needed.
8
+ Please reply with unadorned text that can be read aloud to the user using a TTS engine`;
9
+
10
+ const server = http.createServer();
11
+ const makeService = createEndpoint({ server, port: 3000 });
12
+
13
+ const svc = makeService({ path: '/llm-streaming' });
14
+
15
+ svc.on('session:new', (session) => {
16
+ console.log(`Incoming call: ${session.callSid}`);
17
+
18
+ const apiKey = process.env.ANTHROPIC_API_KEY;
19
+ if (!apiKey) throw new Error('ANTHROPIC_API_KEY env variable is required');
20
+
21
+ const client = new Anthropic({ apiKey });
22
+ const messages: Array<{ role: 'user' | 'assistant'; content: string }> = [];
23
+ let assistantResponse = '';
24
+ let userInterrupt = false;
25
+
26
+ session
27
+ .on('/speech-detected', async (evt: Record<string, any>) => {
28
+ const { speech } = evt;
29
+
30
+ // Acknowledge the hook immediately so jambonz can continue
31
+ session.reply();
32
+
33
+ if (speech?.is_final) {
34
+ const { transcript } = speech.alternatives[0];
35
+ messages.push({ role: 'user', content: transcript });
36
+ userInterrupt = false;
37
+
38
+ const stream = await client.messages.create({
39
+ model: ANTHROPIC_MODEL,
40
+ max_tokens: 1024,
41
+ system: systemPrompt,
42
+ messages,
43
+ stream: true,
44
+ });
45
+
46
+ for await (const event of stream) {
47
+ if (userInterrupt) {
48
+ messages.push({ role: 'assistant', content: `${assistantResponse}...` });
49
+ assistantResponse = '';
50
+ break;
51
+ }
52
+
53
+ if ((event as any).delta?.text) {
54
+ const tokens = (event as any).delta.text;
55
+ assistantResponse += tokens;
56
+ session.sendTtsTokens(tokens).catch((err: Error) =>
57
+ console.error('Error sending TTS tokens:', err)
58
+ );
59
+ } else if (event.type === 'message_stop') {
60
+ session.flushTtsTokens();
61
+ messages.push({ role: 'assistant', content: assistantResponse });
62
+ assistantResponse = '';
63
+ }
64
+ }
65
+ }
66
+ })
67
+ .on('tts:streaming-event', (_evt: Record<string, any>) => {
68
+ // TTS streaming lifecycle events
69
+ })
70
+ .on('tts:user_interrupt', () => {
71
+ console.log(`Session ${session.callSid}: user interrupted`);
72
+ userInterrupt = true;
73
+ })
74
+ .on('close', (code: number) => {
75
+ console.log(`Session ${session.callSid} closed: ${code}`);
76
+ })
77
+ .on('error', (err: Error) => {
78
+ console.error(`Session ${session.callSid} error:`, err);
79
+ });
80
+
81
+ session
82
+ .config({
83
+ ttsStream: { enable: true },
84
+ bargeIn: {
85
+ enable: true,
86
+ sticky: true,
87
+ minBargeinWordCount: 1,
88
+ actionHook: '/speech-detected',
89
+ input: ['speech'],
90
+ },
91
+ })
92
+ .say({ text: 'Hi there, how can I help you today?' })
93
+ .send();
94
+ });
95
+
96
+ console.log('LLM streaming app listening on port 3000');
@@ -0,0 +1,131 @@
1
+ import http from 'http';
2
+ import { createEndpoint } from '@jambonz/sdk/websocket';
3
+
4
+ const server = http.createServer();
5
+ const makeService = createEndpoint({
6
+ server,
7
+ port: 3000,
8
+ envVars: {
9
+ OPENAI_API_KEY: {
10
+ type: 'string',
11
+ description: 'OpenAI API key for Realtime',
12
+ required: true,
13
+ obscure: true,
14
+ },
15
+ },
16
+ });
17
+
18
+ const svc = makeService({ path: '/openai-s2s' });
19
+
20
+ svc.on('session:new', (session) => {
21
+ console.log(`Incoming call: ${session.callSid}`);
22
+ console.log(' from: %s to: %s', session.data.from, session.data.to);
23
+ console.log(' env_vars:', JSON.stringify(session.data.env_vars || {}));
24
+
25
+ const apiKey = session.data.env_vars?.OPENAI_API_KEY;
26
+ if (!apiKey) {
27
+ console.error('ERROR: OPENAI_API_KEY not found in application environment variables');
28
+ return;
29
+ }
30
+
31
+ session
32
+ .on('/event', (_evt: Record<string, any>) => {
33
+ // OpenAI Realtime events (conversation.item.*, response.audio_transcript.done, etc.)
34
+ })
35
+ .on('/toolCall', async (evt: Record<string, any>) => {
36
+ const { name, args, tool_call_id } = evt;
37
+
38
+ if (name === 'get_weather') {
39
+ try {
40
+ const geoRes = await fetch(
41
+ `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(args.location)}&count=1&language=en&format=json`
42
+ );
43
+ const geoData = await geoRes.json() as any;
44
+ if (!geoData.results?.length) throw new Error('location_not_found');
45
+
46
+ const { latitude: lat, longitude: lng } = geoData.results[0];
47
+ const wxRes = await fetch(
48
+ `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}&current=temperature_2m,wind_speed_10m&temperature_unit=${args.scale}`
49
+ );
50
+ const weather = await wxRes.json();
51
+
52
+ session.sendToolOutput(tool_call_id, {
53
+ type: 'conversation.item.create',
54
+ item: { type: 'function_call_output', call_id: tool_call_id, output: JSON.stringify(weather) },
55
+ });
56
+ } catch (err) {
57
+ session.sendToolOutput(tool_call_id, {
58
+ type: 'conversation.item.create',
59
+ item: { type: 'function_call_output', call_id: tool_call_id, output: JSON.stringify({ error: String(err) }) },
60
+ });
61
+ }
62
+ }
63
+ })
64
+ .on('/final', (evt: Record<string, any>) => {
65
+ if (['server failure', 'server error'].includes(evt.completion_reason)) {
66
+ session.say({ text: 'Sorry, there was an error processing your request.' }).hangup();
67
+ }
68
+ session.reply();
69
+ })
70
+ .on('close', (code: number) => {
71
+ console.log(`Session ${session.callSid} closed: ${code}`);
72
+ })
73
+ .on('error', (err: Error) => {
74
+ console.error(`Session ${session.callSid} error:`, err);
75
+ });
76
+
77
+ session
78
+ .answer()
79
+ .pause({ length: 1 })
80
+ .openai_s2s({
81
+ model: 'gpt-4o-realtime-preview-2024-12-17',
82
+ auth: { apiKey },
83
+ actionHook: '/final',
84
+ eventHook: '/event',
85
+ toolHook: '/toolCall',
86
+ events: [
87
+ 'conversation.item.*',
88
+ 'response.audio_transcript.done',
89
+ 'input_audio_buffer.committed',
90
+ ],
91
+ llmOptions: {
92
+ response_create: {
93
+ modalities: ['text', 'audio'],
94
+ instructions: 'Please assist the user with their request.',
95
+ voice: 'alloy',
96
+ output_audio_format: 'pcm16',
97
+ temperature: 0.8,
98
+ max_output_tokens: 4096,
99
+ },
100
+ session_update: {
101
+ tools: [
102
+ {
103
+ name: 'get_weather',
104
+ type: 'function',
105
+ description: 'Get the weather at a given location',
106
+ parameters: {
107
+ type: 'object',
108
+ properties: {
109
+ location: { type: 'string', description: 'Location to get the weather from' },
110
+ scale: { type: 'string', enum: ['fahrenheit', 'celsius'] },
111
+ },
112
+ required: ['location', 'scale'],
113
+ },
114
+ },
115
+ ],
116
+ tool_choice: 'auto',
117
+ input_audio_transcription: { model: 'whisper-1' },
118
+ turn_detection: {
119
+ type: 'server_vad',
120
+ threshold: 0.8,
121
+ prefix_padding_ms: 300,
122
+ silence_duration_ms: 500,
123
+ },
124
+ },
125
+ },
126
+ })
127
+ .hangup()
128
+ .send();
129
+ });
130
+
131
+ console.log('OpenAI Realtime voice agent listening on port 3000');
@@ -0,0 +1,19 @@
1
+ # Call Queue with Hold Music
2
+
3
+ A support queue application. Callers are placed in a queue with hold music and position announcements. Agents connect separately to dequeue and bridge to the next waiting caller.
4
+
5
+ ## What It Demonstrates
6
+ - The `enqueue` verb to place callers in a named queue
7
+ - The `waitHook` for hold music and queue position announcements
8
+ - The `dequeue` verb to connect agents with waiting callers
9
+ - Two separate endpoints: one for callers, one for agents
10
+
11
+ ## Prerequisites
12
+ - A jambonz account with two applications configured:
13
+ - Caller-facing application pointing to `/incoming`
14
+ - Agent-facing application pointing to `/agent`
15
+ - A hold music audio file URL (replace the example URL in the code)
16
+
17
+ ## Files
18
+ - `app.ts` — Webhook version (TypeScript using `@jambonz/sdk`)
19
+ - `ws-app.ts` — WebSocket version (TypeScript using `@jambonz/sdk`)
@@ -0,0 +1,68 @@
1
+ import express from 'express';
2
+ import { WebhookResponse } from '@jambonz/sdk/webhook';
3
+
4
+ const app = express();
5
+ app.use(express.json());
6
+
7
+ // Caller arrives — greet and place in queue
8
+ app.post('/incoming', (_req, res) => {
9
+ const jambonz = new WebhookResponse();
10
+ jambonz
11
+ .say({ text: 'Thank you for calling. All agents are currently busy. Please hold and we will be with you shortly.' })
12
+ .enqueue({
13
+ name: 'support',
14
+ waitHook: '/hold-music',
15
+ actionHook: '/queue-exit',
16
+ });
17
+
18
+ res.json(jambonz);
19
+ });
20
+
21
+ // Called periodically while the caller waits in the queue.
22
+ // Return verbs to play hold music and announce queue position.
23
+ app.post('/hold-music', (req, res) => {
24
+ const { queuePosition, queueTime } = req.body;
25
+ const minutes = Math.floor((queueTime || 0) / 60);
26
+
27
+ const jambonz = new WebhookResponse();
28
+ jambonz
29
+ .say({ text: `You are number ${queuePosition || 'next'} in the queue. Approximate wait time: ${minutes || 'less than one'} minutes.` })
30
+ .play({ url: 'https://example.com/sounds/hold-music.mp3', loop: 1 });
31
+
32
+ res.json(jambonz);
33
+ });
34
+
35
+ // Called when the caller leaves the queue (dequeued or hung up)
36
+ app.post('/queue-exit', (req, res) => {
37
+ console.log(`Caller left queue: ${JSON.stringify(req.body)}`);
38
+ const jambonz = new WebhookResponse();
39
+ jambonz.hangup();
40
+ res.json(jambonz);
41
+ });
42
+
43
+ // Agent-facing endpoint — agent calls in and dequeues the next caller
44
+ app.post('/agent', (_req, res) => {
45
+ const jambonz = new WebhookResponse();
46
+ jambonz
47
+ .say({ text: 'Connecting you to the next caller in the queue.' })
48
+ .dequeue({
49
+ name: 'support',
50
+ timeout: 30,
51
+ beep: true,
52
+ actionHook: '/agent-call-end',
53
+ })
54
+ .say({ text: 'No callers are waiting in the queue. Goodbye.' })
55
+ .hangup();
56
+
57
+ res.json(jambonz);
58
+ });
59
+
60
+ // Called when the agent's bridged call ends
61
+ app.post('/agent-call-end', (req, res) => {
62
+ console.log(`Agent call ended: ${JSON.stringify(req.body)}`);
63
+ const jambonz = new WebhookResponse();
64
+ jambonz.hangup();
65
+ res.json(jambonz);
66
+ });
67
+
68
+ app.listen(3000, () => console.log('Queue app listening on port 3000'));
@@ -0,0 +1,41 @@
1
+ import http from 'http';
2
+ import { createEndpoint } from '@jambonz/sdk/websocket';
3
+
4
+ const server = http.createServer();
5
+ const makeService = createEndpoint({ server, port: 3000 });
6
+
7
+ // Caller-facing service — place callers in the support queue
8
+ const callerSvc = makeService({ path: '/incoming' });
9
+
10
+ callerSvc.on('session:new', (session) => {
11
+ console.log(`Caller ${session.callSid} entering queue`);
12
+
13
+ session
14
+ .say({ text: 'Thank you for calling. All agents are currently busy. Please hold.' })
15
+ .enqueue({
16
+ name: 'support',
17
+ waitHook: '/hold-music',
18
+ actionHook: '/queue-exit',
19
+ })
20
+ .send();
21
+ });
22
+
23
+ // Agent-facing service — agent connects and dequeues the next caller
24
+ const agentSvc = makeService({ path: '/agent' });
25
+
26
+ agentSvc.on('session:new', (session) => {
27
+ console.log(`Agent ${session.callSid} ready to take a call`);
28
+
29
+ session
30
+ .say({ text: 'Connecting you to the next caller.' })
31
+ .dequeue({
32
+ name: 'support',
33
+ timeout: 30,
34
+ beep: true,
35
+ })
36
+ .say({ text: 'No callers waiting. Goodbye.' })
37
+ .hangup()
38
+ .send();
39
+ });
40
+
41
+ console.log('Queue ws app listening on port 3000');
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Real-time translator — bridges two parties and translates speech
3
+ * in both directions using jambonz STT, Google Translate, and jambonz TTS.
4
+ *
5
+ * Configuration is provided via jambonz application environment variables
6
+ * (configured in the jambonz portal). GOOGLE_APPLICATION_CREDENTIALS must
7
+ * be set in the process environment for the Google Translate API.
8
+ */
9
+ import http from 'http';
10
+ import { createEndpoint } from '@jambonz/sdk/websocket';
11
+ import { envVars } from './utils/config.js';
12
+ import translator from './routes/translator.js';
13
+
14
+ const port = Number(process.env.PORT) || 3000;
15
+ const server = http.createServer();
16
+ const makeService = createEndpoint({ server, port, envVars });
17
+
18
+ const svc = makeService({ path: '/translator' });
19
+ svc.on('session:new', (session) => translator(session));
20
+
21
+ console.log(`Realtime translator listening on port ${port}`);
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Translator route — bridges an inbound call to a remote party and
3
+ * translates speech in both directions using STT → Google Translate → TTS.
4
+ *
5
+ * Audio never leaves jambonz — only transcription text arrives here.
6
+ * Translated text is injected back via dub tracks using injectCommand.
7
+ */
8
+ import type { Session } from '@jambonz/sdk/websocket';
9
+ import { translateText } from '../utils/translate.js';
10
+
11
+ export default function translator(session: Session) {
12
+ const log = (msg: string) => console.log(`[${session.callSid}] ${msg}`);
13
+ log('new call — setting up translation bridge');
14
+
15
+ const env = (session.data.env_vars ?? {}) as Record<string, string>;
16
+
17
+ const recognizer_a = { vendor: env.CALLER_STT_VENDOR, language: env.CALLER_LANGUAGE_CODE };
18
+ const recognizer_b = { vendor: env.CALLED_STT_VENDOR, language: env.CALLED_LANGUAGE_CODE };
19
+ const synthesizer_a = { vendor: env.CALLER_TTS_VENDOR, language: env.CALLER_LANGUAGE_CODE, voice: env.CALLER_TTS_VOICE };
20
+ const synthesizer_b = { vendor: env.CALLED_TTS_VENDOR, language: env.CALLED_LANGUAGE_CODE, voice: env.CALLED_TTS_VOICE };
21
+
22
+ // ---- Event handlers ----
23
+
24
+ session.on('call:status', (evt: Record<string, any>) => {
25
+ // Capture the B-leg call_sid when the outbound leg connects
26
+ if (!session.locals.call_sid_b && evt.direction === 'outbound') {
27
+ session.locals.call_sid_b = evt.call_sid;
28
+ log(`B-leg call_sid: ${evt.call_sid}`);
29
+ }
30
+ });
31
+
32
+ // A-leg transcription → translate → speak on B-leg
33
+ session.on('/transcription-a', (evt: Record<string, any>) => {
34
+ const transcript = evt.speech?.alternatives?.[0]?.transcript;
35
+ session.reply();
36
+
37
+ const callSidB = session.locals.call_sid_b as string | undefined;
38
+ if (!transcript || !callSidB) return;
39
+
40
+ log(`A says: "${transcript}"`);
41
+ translateText(transcript, recognizer_a.language, recognizer_b.language)
42
+ .then((translation) => {
43
+ if (!translation) return;
44
+ log(`→ B hears: "${translation}"`);
45
+ session.injectCommand('dub', {
46
+ action: 'sayOnTrack',
47
+ track: 'b',
48
+ say: { text: translation, synthesizer: synthesizer_b },
49
+ }, callSidB);
50
+ })
51
+ .catch((err) => console.error('Translation error (A→B):', err));
52
+ });
53
+
54
+ // B-leg transcription → translate → speak on A-leg
55
+ session.on('/transcription-b', (evt: Record<string, any>) => {
56
+ const transcript = evt.speech?.alternatives?.[0]?.transcript;
57
+ session.reply();
58
+
59
+ if (!transcript) return;
60
+
61
+ log(`B says: "${transcript}"`);
62
+ translateText(transcript, recognizer_b.language, recognizer_a.language)
63
+ .then((translation) => {
64
+ if (!translation) return;
65
+ log(`→ A hears: "${translation}"`);
66
+ session.injectCommand('dub', {
67
+ action: 'sayOnTrack',
68
+ track: 'a',
69
+ say: { text: translation, synthesizer: synthesizer_a },
70
+ });
71
+ })
72
+ .catch((err) => console.error('Translation error (B→A):', err));
73
+ });
74
+
75
+ session.on('close', (code: number) => log(`closed (${code})`));
76
+ session.on('error', (err: Error) => console.error(`[${session.callSid}] error:`, err));
77
+
78
+ // ---- Verb sequence ----
79
+
80
+ session
81
+ .answer()
82
+
83
+ // A-leg: attenuate remote audio, enable transcription, add dub track
84
+ .config({
85
+ boostAudioSignal: '-20 dB',
86
+ recognizer: recognizer_a,
87
+ transcribe: {
88
+ enable: true,
89
+ transcriptionHook: '/transcription-a',
90
+ },
91
+ })
92
+ .dub({ action: 'addTrack', track: 'a' })
93
+
94
+ // Dial B-leg with matching config
95
+ .dial({
96
+ target: [{ type: 'phone', number: env.DIAL_TARGET }],
97
+ boostAudioSignal: '-20 dB',
98
+ transcribe: {
99
+ transcriptionHook: '/transcription-b',
100
+ channel: 2,
101
+ recognizer: recognizer_b,
102
+ },
103
+ dub: [{ action: 'addTrack', track: 'b' }],
104
+ })
105
+
106
+ .hangup()
107
+ .send();
108
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Environment variable schema for the realtime translator.
3
+ *
4
+ * The schema is passed to createEndpoint() so jambonz can discover
5
+ * the app's configuration via OPTIONS. At call time the values arrive
6
+ * in session.data.env_vars.
7
+ */
8
+ import type { EnvVarSchema } from '@jambonz/sdk/types';
9
+
10
+ /** Schema declared to jambonz — the portal renders a form from this. */
11
+ export const envVars: EnvVarSchema = {
12
+ CALLER_LANGUAGE_CODE: { type: 'string', description: 'Caller language (BCP-47)', required: true },
13
+ CALLER_TTS_VENDOR: { type: 'string', description: 'Caller TTS vendor', required: true },
14
+ CALLER_TTS_VOICE: { type: 'string', description: 'Caller TTS voice', required: true },
15
+ CALLER_STT_VENDOR: { type: 'string', description: 'Caller STT vendor', required: true },
16
+ CALLED_LANGUAGE_CODE: { type: 'string', description: 'Called party language (BCP-47)', required: true },
17
+ CALLED_TTS_VENDOR: { type: 'string', description: 'Called party TTS vendor', required: true },
18
+ CALLED_TTS_VOICE: { type: 'string', description: 'Called party TTS voice', required: true },
19
+ CALLED_STT_VENDOR: { type: 'string', description: 'Called party STT vendor', required: true },
20
+ DIAL_TARGET: { type: 'string', description: 'Phone number to dial in E.164 format (e.g. +15551234567)', required: true },
21
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Thin wrapper around the Google Translate v2 API.
3
+ * Requires GOOGLE_APPLICATION_CREDENTIALS to point at a service account key.
4
+ */
5
+ import { v2 } from '@google-cloud/translate';
6
+
7
+ const client = new v2.Translate();
8
+
9
+ export async function translateText(
10
+ text: string,
11
+ sourceLang: string,
12
+ targetLang: string
13
+ ): Promise<string | null> {
14
+ text = text.replace(/\n(?!\s)/g, ' ').replace(/\n\s/g, ' ');
15
+ if (!text.trim()) return null;
16
+ if (sourceLang === targetLang) return text;
17
+
18
+ const [translation] = await client.translate(text, {
19
+ from: sourceLang,
20
+ to: targetLang,
21
+ });
22
+ return translation;
23
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Retell-hosted — bridges calls between PSTN callers and Retell AI agents.
3
+ *
4
+ * Inbound PSTN calls are forwarded to Retell; calls originated by Retell
5
+ * are forwarded to the PSTN. SIP REFER (cold transfer) is supported.
6
+ *
7
+ * Configuration is provided via jambonz application environment variables
8
+ * (configured in the jambonz portal).
9
+ */
10
+ import http from 'http';
11
+ import { createEndpoint } from '@jambonz/sdk/websocket';
12
+ import { envVars } from './config.js';
13
+ import retell from './retell.js';
14
+
15
+ const port = Number(process.env.PORT) || 3000;
16
+ const server = http.createServer();
17
+ const makeService = createEndpoint({ server, port, envVars });
18
+
19
+ const svc = makeService({ path: '/' });
20
+ svc.on('session:new', (session) => retell(session));
21
+
22
+ console.log(`Retell-hosted listening on port ${port}`);
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Environment variable schema and utilities for the Retell-hosted app.
3
+ *
4
+ * The schema is passed to createEndpoint() so jambonz can discover
5
+ * the app's configuration via OPTIONS. At call time the values arrive
6
+ * in session.data.env_vars.
7
+ */
8
+ import type { EnvVarSchema } from '@jambonz/sdk/types';
9
+ import { PhoneNumberFormat, PhoneNumberUtil } from 'google-libphonenumber';
10
+
11
+ const phoneUtil = PhoneNumberUtil.getInstance();
12
+
13
+ /** Schema declared to jambonz — the portal renders a form from this. */
14
+ export const envVars: EnvVarSchema = {
15
+ RETELL_TRUNK_NAME: {
16
+ type: 'string',
17
+ description: 'The name of the Carrier you configured in jambonz towards Retell',
18
+ required: true,
19
+ },
20
+ PSTN_TRUNK_NAME: {
21
+ type: 'string',
22
+ description: 'The name of the Carrier you configured in jambonz towards your SIP service provider',
23
+ required: true,
24
+ },
25
+ DEFAULT_COUNTRY: {
26
+ type: 'string',
27
+ description: 'ISO 3166-1 alpha-2 country code for phone number formatting (e.g. US, GB)',
28
+ required: false,
29
+ },
30
+ OVERRIDE_FROM_USER: {
31
+ type: 'string',
32
+ description: 'Value to use for From header in outbound calls to PSTN (original caller ID moved to Diversion header)',
33
+ required: false,
34
+ },
35
+ PASS_REFER: {
36
+ type: 'boolean',
37
+ description: 'When Retell sends a cold transfer (SIP REFER), pass the REFER to the originating carrier if true; otherwise dial a new call via jambonz',
38
+ default: true,
39
+ },
40
+ };
41
+
42
+ /** Format a phone number to E.164 using the given country code. */
43
+ export function getE164(number: string, country: string): string {
44
+ try {
45
+ const parsed = phoneUtil.parseAndKeepRawInput(number, country);
46
+ if (phoneUtil.isValidNumber(parsed)) {
47
+ return phoneUtil.format(parsed, PhoneNumberFormat.E164);
48
+ }
49
+ } catch {
50
+ // fall through
51
+ }
52
+ return number;
53
+ }