@sinch/functions-runtime 0.5.21 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +442 -26
- package/dist/bin/sinch-runtime.js +10 -2
- package/dist/bin/sinch-runtime.js.map +1 -1
- package/dist/{chunk-GHTTRPRF.js → chunk-TOTJB6SW.js} +4240 -353
- package/dist/chunk-TOTJB6SW.js.map +1 -0
- package/dist/index.d.ts +1219 -129
- package/dist/index.js +53 -3
- package/dist/voice/v2.d.ts +956 -70
- package/dist/voice/v2.js +33 -5
- package/package.json +6 -1
- package/dist/chunk-GHTTRPRF.js.map +0 -1
package/README.md
CHANGED
|
@@ -23,20 +23,56 @@ Requires Node.js 24 or later. See the [quickstart](https://developers.sinch.com/
|
|
|
23
23
|
Voice API v2 is what `context.voice` is and what a new function should be written against.
|
|
24
24
|
|
|
25
25
|
```ts
|
|
26
|
-
import { onCall
|
|
26
|
+
import { onCall } from '@sinch/functions-runtime/voice';
|
|
27
27
|
|
|
28
28
|
export const voiceWebhook = onCall({
|
|
29
|
-
incoming: () =>
|
|
30
|
-
|
|
31
|
-
|
|
29
|
+
incoming: (call, builder) =>
|
|
30
|
+
builder.answer().say('Thanks for calling.').dialPhone('+15550001111'),
|
|
31
|
+
completed: (call) => {
|
|
32
|
+
console.log('call ended', call.callId);
|
|
32
33
|
},
|
|
33
34
|
});
|
|
34
35
|
```
|
|
35
36
|
|
|
36
37
|
`onCall` takes handlers keyed by call lifecycle stage — `incoming`, `answered`, `manage`,
|
|
37
38
|
`completed`, a `webhooks` map for named `webhook` commands, and `fallback` — and returns the
|
|
38
|
-
`voiceWebhook` export.
|
|
39
|
-
|
|
39
|
+
`voiceWebhook` export. Each handler is called as `(call, builder, context, request)`: the call,
|
|
40
|
+
a command builder already primed with it, the function context, and the raw request. `call` is
|
|
41
|
+
flat — `call.from`, `call.callId`, with `call.event` beside them, and `call.menu` on a menu —
|
|
42
|
+
and typed per slot: `incoming` gets an `IncomingCall`, `manage` a `MenuCall` whose `menu` is
|
|
43
|
+
guaranteed once `call.event === 'call.menu'`, `completed` a `CompletedCall`. Return the builder
|
|
44
|
+
(`.build()` is optional) and the runtime emits the wire body; return nothing and it answers `204`.
|
|
45
|
+
`call.call` — how the call was read before this flatten — is **deprecated**, not gone: it still
|
|
46
|
+
compiles and still returns `call` itself (`call.call.callId === call.callId`), so code written
|
|
47
|
+
against the old nested shape keeps working. It never appears on the wire (not present on
|
|
48
|
+
`JSON.stringify(call)` or in a body built from `call`). Read the field directly off `call`
|
|
49
|
+
instead — new code should not use `call.call`.
|
|
50
|
+
|
|
51
|
+
The builder's `dialPhone`, `dialSip`, `dialStream` and `dialRelay` put another party on the
|
|
52
|
+
call: they bridge the caller to the new leg and end each leg when the other goes. Because the
|
|
53
|
+
builder knows the call, they fill in what used to be written by hand — the leg names, the
|
|
54
|
+
bridge, the teardown, and `from` (the Sinch number for a phone, the caller's number for SIP).
|
|
55
|
+
They never answer the call: `answer()` stays explicit. `onNoAnswer` covers busy, rejected,
|
|
56
|
+
timed-out and failed at once, and takes a whole flow, so a fallback is another dial:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { dialPhone, say } from '@sinch/functions-runtime/voice';
|
|
60
|
+
|
|
61
|
+
incoming: (call, builder) =>
|
|
62
|
+
builder.answer().dialPhone(agent, {
|
|
63
|
+
onNoAnswer: dialPhone(fallback, { onNoAnswer: say('Nobody is free.').hangup() }),
|
|
64
|
+
}),
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`say`, `dialPhone` and the rest also exist as standalone functions that start a new flow, for
|
|
68
|
+
the places that take one — a menu `option('1', say('Connecting.').dialPhone(sales))`,
|
|
69
|
+
`onNoAnswer`, `onFail`. In a menu, `option` takes keypresses literally (`*` and `#` included);
|
|
70
|
+
`match` takes a regular expression. A menu of keypresses can also be written as one object —
|
|
71
|
+
`menu('main', { prompt, options: { '1': dialPhone(sales), '2': dialPhone(support) }, onFail })`
|
|
72
|
+
— whose `options` keys go through `option`; a `match` needs the callback form. `bridgeTo(destination, options)` is the mechanism under the
|
|
73
|
+
dial verbs, for a hand-built destination or a named bridge or leg. `commands()` still starts a
|
|
74
|
+
free flow for batch bodies and tests; a dial verb there needs `{ liveLeg }`, since no call is
|
|
75
|
+
known.
|
|
40
76
|
|
|
41
77
|
### Routing calls to the function
|
|
42
78
|
|
|
@@ -73,13 +109,389 @@ await context.voice.call('+15559876543', {
|
|
|
73
109
|
await context.voice.callWithStream('+15559876543', '/media', { from: '+15551234567' });
|
|
74
110
|
```
|
|
75
111
|
|
|
112
|
+
`transferToPhone`, `transferToSip`, `transferToStream`, `transferToRelay` and `transferToAgent`
|
|
113
|
+
move a live leg: out of the bridge it is on and into a new one with the destination, whoever it
|
|
114
|
+
was talking to staying behind. They ring for 30 seconds; if nobody answers, or the new party
|
|
115
|
+
hangs up later, the moved leg is dropped. The moved leg is taken to be `caller` (`origin` for an
|
|
116
|
+
outbound call, when `call` is passed); name it with `liveLeg` otherwise:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
await context.voice.transferToPhone(callId, '+15550001111');
|
|
120
|
+
await context.voice.transferToAgent(callId, 'grok', grokNumber);
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`transfer` is the other operation: it dials a third party into the bridge the call is already on.
|
|
124
|
+
|
|
76
125
|
v2 authenticates with the project Access Key pair (`PROJECT_ID_API_KEY` /
|
|
77
126
|
`PROJECT_ID_API_SECRET`), not the v1 application key.
|
|
78
127
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
128
|
+
Everything a voice function needs imports from `@sinch/functions-runtime/voice`: `onCall`, the
|
|
129
|
+
builder and its standalone factories, `voiceRelay`, `realtimeAgent`, `connectAgent`, the client,
|
|
130
|
+
and their types. The package root keeps context, config and Voice v1. `./voice/v2` is the same
|
|
131
|
+
entry under its older name, and `onCall`, `commands`, `createClient`, `Client` and the core v2
|
|
132
|
+
types are also on the root — every path resolves the same declarations, so they mix freely.
|
|
133
|
+
|
|
134
|
+
### Connecting a call to an AI agent
|
|
135
|
+
|
|
136
|
+
`connectAgent` bridges an inbound call to a SIP-based AI voice agent — ElevenLabs or xAI Grok —
|
|
137
|
+
in one call, instead of hand-writing the answer/bridge/dial/teardown commands it takes:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
import { AgentProvider } from '@sinch/functions-runtime';
|
|
141
|
+
import { onCall, connectAgent } from '@sinch/functions-runtime/voice';
|
|
142
|
+
|
|
143
|
+
export const voiceWebhook = onCall({
|
|
144
|
+
incoming: (call) => connectAgent(AgentProvider.ElevenLabs, '+15551234567', { call }),
|
|
145
|
+
});
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The second argument is the number in the SIP URI's user part — for Grok the Direct SIP phone
|
|
149
|
+
number registered in the xAI console, for ElevenLabs the number attached to the agent's phone
|
|
150
|
+
integration. Neither provider routes by agent id, and it must be an E.164 number you configured,
|
|
151
|
+
never a value taken from a caller-controlled webhook field. Passing `call` (the incoming event)
|
|
152
|
+
defaults `from` to the caller's number and adds the `X-Sinch-Call-Id` / `X-Caller-Number` /
|
|
153
|
+
`X-Dialed-Number` SIP headers the agent sees as per-call context. Stream-based providers —
|
|
154
|
+
`AgentProvider.Sinch`, or a future OpenAI/Deepgram provider — are a different call shape and
|
|
155
|
+
throw; use `@sinch/agents` for those.
|
|
156
|
+
|
|
157
|
+
Return the result directly from `incoming`, as above — `callName` and the agent-leg teardown on
|
|
158
|
+
hangup are only honoured on a response to `call.incoming`, so forwarding just its `.commands`
|
|
159
|
+
elsewhere silently drops the teardown and leaves the SIP leg billing until `maxDuration`.
|
|
160
|
+
|
|
161
|
+
The builder's `dialAgent` does the same without that restriction, because it knows which webhook
|
|
162
|
+
it answers: it names the caller leg and adds the teardown only on `call.incoming`, and it never
|
|
163
|
+
answers the call itself. So an agent can be one option of a menu, and a `realtimeAgent` handle
|
|
164
|
+
dials the same way. Every agent leg dialled through `dialAgent` — SIP or a `realtimeAgent`
|
|
165
|
+
handle's own stream — is capped by the `MAX_CALL_DURATION` function variable (seconds), defaulting
|
|
166
|
+
to 1800 when it is unset; an explicit `maxDuration` on the dial itself still wins:
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { dialAgent, dialPhone } from '@sinch/functions-runtime/voice';
|
|
170
|
+
|
|
171
|
+
incoming: (call, builder) =>
|
|
172
|
+
builder.answer().menu('main', (m) =>
|
|
173
|
+
m.prompt('Press 1 for sales, 2 for our assistant.')
|
|
174
|
+
.option('1', dialPhone(sales))
|
|
175
|
+
.option('2', dialAgent('grok', grokNumber))),
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Talking to a caller in text
|
|
179
|
+
|
|
180
|
+
`voiceRelay` puts a Voice Relay leg on the call: Sinch runs speech-to-text and text-to-speech,
|
|
181
|
+
and the function only exchanges text. It owns the `/relay` socket, the handshake, the greeting
|
|
182
|
+
and the one-time token that proves a connecting socket is a leg this function dialled; the
|
|
183
|
+
author writes the conversation:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
import { onCall, voiceRelay } from '@sinch/functions-runtime/voice';
|
|
187
|
+
|
|
188
|
+
const relay = voiceRelay({
|
|
189
|
+
greeting: 'Hi, how can I help?',
|
|
190
|
+
onConnected(call) {
|
|
191
|
+
call.onSpeech(async (text) => call.send(await answer(text)));
|
|
192
|
+
call.onDigits((digits) => call.send(`You pressed ${digits}.`));
|
|
193
|
+
call.onEnded(() => console.log('relay closed', call.id));
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
export default {
|
|
198
|
+
setup: relay.setup,
|
|
199
|
+
voiceWebhook: onCall({ incoming: (call, builder) => builder.answer().dialRelay(relay) }),
|
|
200
|
+
};
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
`voice`, `language`, `interruptions` and `path` (default `/relay`) are the other options.
|
|
204
|
+
`voice`, `language` and `greeting` also take `(call, context) => value`, resolved once per call
|
|
205
|
+
as `realtimeAgent` does; `greeting` may be async, while `voice` and `language` go into the dial
|
|
206
|
+
itself and must return a string. `RELAY_URL` overrides the socket address for local development. `call.hangup()` ends the call,
|
|
207
|
+
and `call.transferToPhone(...)` and the rest of the `transferTo*` family move the caller on.
|
|
208
|
+
|
|
209
|
+
### Hooking a call into a realtime voice agent
|
|
210
|
+
|
|
211
|
+
`connectAgent` hands the call away — the vendor's own agent runtime takes it from there.
|
|
212
|
+
`realtimeAgent` is the opposite: this function stays on the line for the whole call, relaying
|
|
213
|
+
audio to a vendor's realtime voice API and dispatching its tool calls in-process.
|
|
214
|
+
|
|
215
|
+
All four adapters are raw `ws` — no vendor SDK, and no optional peer dependency to install.
|
|
216
|
+
ElevenLabs is not among them — its wire protocol has no way to take a tool schema (or, without an
|
|
217
|
+
opt-in dashboard setting, a prompt) at connect time, so it cannot honor `realtimeAgent`'s "switch
|
|
218
|
+
provider with no code change" promise; it stays a `connectAgent`-only vendor (see above).
|
|
219
|
+
|
|
220
|
+
| `provider` | Transport | Verified | Notes |
|
|
221
|
+
| ------------ | ------------------------------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
222
|
+
| `'deepgram'` | Raw `ws` | Against the shipped `realtime-deepgram` template | No resampling — Deepgram accepts the platform's own negotiated rate. Every declared tool defaults to `defer_until_eot: true`, so a handler waits for the caller to actually finish speaking rather than running speculatively. `UserStartedSpeaking` is gated against an estimated playout window (generation still active, or already-sent audio not yet finished playing) rather than treated as barge-in unconditionally — Deepgram's own docs say it fires for every new utterance, not only a genuine interruption; see `adapters/deepgram.ts`'s file header. |
|
|
223
|
+
| `'openai'` | Raw `ws` (not `@openai/agents`) | Against GPT-Live's current docs and a live probe session — see below | GPT-Live (`gpt-live-1`), Responses delegation, 8kHz `audio/pcmu` both ways. No barge-in signal. |
|
|
224
|
+
| `'grok'` | Raw `ws`, shares the (previous) OpenAI Realtime-shaped adapter's implementation | Against xAI's docs describing the endpoint as OpenAI-compatible | 8kHz `audio/pcmu` both ways. `greeting` is paraphrased, not verbatim — it is sent as `response.create` instructions, not a dedicated field. |
|
|
225
|
+
| `'gemini'` | Raw `ws` (not `@google/genai`) | Against a live Gemini Live session | Fixed 16kHz in / 24kHz out, resampled through a stateful anti-aliasing resampler. Reconnects transparently (capped retries) on a session-window close, using Live's own resumption handle. **Known vendor-side issue:** Gemini can go silent for the rest of a call after a barge-in — see below. |
|
|
226
|
+
| `'voice-relay'` | Voice Relay (Sinch STT/TTS), not a vendor realtime session | Against the adapter's own test suite, not yet a live call | Runs any model behind an OpenAI Responses-compatible API — OpenAI, Azure OpenAI, or a gateway such as OpenRouter or LiteLLM — as a text loop on top of `voiceRelay`. See "Talking to an LLM over Voice Relay" below. |
|
|
227
|
+
|
|
228
|
+
`'openai'` targets OpenAI's GPT-Live API (`wss://api.openai.com/v1/live/sessions`, model
|
|
229
|
+
`gpt-live-1`), not the Realtime API `'grok'` still shares an implementation with
|
|
230
|
+
(`openai-compatible.ts`) — the two vendors no longer share adapter code. GPT-Live delegates tool
|
|
231
|
+
selection to a separate backend model (`delegation: { type: 'responses', responses: { model,
|
|
232
|
+
tools } }` — default `gpt-5.6-luna`, override via `providerOptions.openai.backendModel`); this
|
|
233
|
+
function's own `RealtimeTool.handler` still runs the call in-process exactly like every other
|
|
234
|
+
adapter, Responses delegation just gets GPT-Live to ask for it in a shape this adapter can
|
|
235
|
+
dispatch. GPT-Live is genuinely full-duplex and sends no barge-in event of any kind — this
|
|
236
|
+
adapter never calls `onBargeIn`, and the cross-vendor contract test has an explicit,
|
|
237
|
+
documented allowance for it being the one provider whose normalised hook sequence has no
|
|
238
|
+
`bargeIn` step. Turn boundaries are synthesised (GPT-Live's transcript-delta events are
|
|
239
|
+
explicitly documented as not marking turn boundaries): the agent side flushes on the
|
|
240
|
+
`response.completed` Responses event, the caller side flushes after a short silence gap — see
|
|
241
|
+
`adapters/openai.ts`'s file header for both heuristics.
|
|
242
|
+
|
|
243
|
+
`'openai'` and `'gemini'` have both been confirmed on live calls; `'deepgram'` and `'grok'` have
|
|
244
|
+
not — "verified" above otherwise means checked against the vendor's current documentation or a
|
|
245
|
+
previously-working template, not a real session. `'openai'` was run twice against a real GPT-Live
|
|
246
|
+
session — once probing the raw protocol, once driving the actual adapter through
|
|
247
|
+
`RealtimeAdapter`'s own interface (see its file header for the observed sequence, timings, and what
|
|
248
|
+
those runs left unverified). `'gemini'` was probed live against a real Gemini Live session, driving
|
|
249
|
+
the actual adapter through the same `RealtimeAdapter` interface; a greeting, a tool call, a barge-in
|
|
250
|
+
mid-response, and a forced reconnect all worked. Each adapter's own file header
|
|
251
|
+
(`packages/runtime-shared/src/ai/realtime/adapters/*.ts`) has the specific list of what to check
|
|
252
|
+
live. A cross-vendor contract test (`packages/runtime-shared/src/ai/realtime/contract.test.ts`)
|
|
253
|
+
drives one agent through all four adapters' own scripted fake vendor sockets and asserts the
|
|
254
|
+
normalised author-hook sequence (barge-in aside, for `'openai'`), the tool-result wire format, and
|
|
255
|
+
the 20ms/8kHz audio frame size are identical across providers — the one place this repo checks
|
|
256
|
+
vendor-to-vendor consistency directly, rather than only each adapter's own behavior in isolation.
|
|
257
|
+
|
|
258
|
+
`/stream` requires a one-time token `connect()` mints per call — nothing an author does, but worth
|
|
259
|
+
knowing when reading logs: a connection that never answers and logs "missing, unknown, expired, or
|
|
260
|
+
already-consumed session token" reached `/stream` without going through this agent's own
|
|
261
|
+
`call.incoming` plan (a stale worker, a health-check probe, or a caller-controlled URL). The token
|
|
262
|
+
is checked from the WebSocket upgrade headers immediately when present — the normal case for a
|
|
263
|
+
STREAM leg this agent dialled itself — rather than waiting on the first frame to arrive; a socket
|
|
264
|
+
with no token on its upgrade gets 2 seconds to supply one in its connect frame before it is closed,
|
|
265
|
+
and no more than 32 such token-less sockets may be waiting at once, so the public endpoint cannot be
|
|
266
|
+
used to hold an unbounded number of unauthenticated sockets open. The platform is also told `answer`
|
|
267
|
+
only once the vendor session actually acks ready (Deepgram `SettingsApplied`, GPT-Live
|
|
268
|
+
`session.started`, Grok `session.updated`, Gemini `setupComplete`) — a vendor outage or a bad API
|
|
269
|
+
key rejects the call outright instead of answering into silence.
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import { realtimeAgent, tool } from '@sinch/functions-runtime';
|
|
273
|
+
|
|
274
|
+
const checkAvailability = tool<{ date: string; partySize: number }>({
|
|
275
|
+
name: 'check_availability',
|
|
276
|
+
description: 'Check table availability for a given date and party size.',
|
|
277
|
+
parameters: {
|
|
278
|
+
type: 'object',
|
|
279
|
+
properties: { date: { type: 'string' }, partySize: { type: 'number' } },
|
|
280
|
+
required: ['date', 'partySize'],
|
|
281
|
+
},
|
|
282
|
+
handler: async ({ date, partySize }) => {
|
|
283
|
+
// ... look up availability ...
|
|
284
|
+
return { available: true, times: ['18:00', '19:30'] };
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
const bookTable = tool<{ date: string; time: string; partySize: number; name: string }>({
|
|
289
|
+
name: 'book_table',
|
|
290
|
+
description: 'Book a table once the caller has confirmed a date, time and party size.',
|
|
291
|
+
parameters: {
|
|
292
|
+
type: 'object',
|
|
293
|
+
properties: {
|
|
294
|
+
date: { type: 'string' },
|
|
295
|
+
time: { type: 'string' },
|
|
296
|
+
partySize: { type: 'number' },
|
|
297
|
+
name: { type: 'string' },
|
|
298
|
+
},
|
|
299
|
+
required: ['date', 'time', 'partySize', 'name'],
|
|
300
|
+
},
|
|
301
|
+
handler: async ({ date, time, partySize, name }, ctx) => {
|
|
302
|
+
const confirmationId = `BK-${Date.now().toString(36).toUpperCase()}`;
|
|
303
|
+
await ctx.storage.write(
|
|
304
|
+
`bookings/${confirmationId}.json`,
|
|
305
|
+
JSON.stringify({ date, time, partySize, name })
|
|
306
|
+
);
|
|
307
|
+
return { confirmationId, message: `Booked for ${name}, ${partySize} guests, ${date} ${time}.` };
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
export default realtimeAgent({
|
|
312
|
+
provider: 'deepgram',
|
|
313
|
+
// voice: 'aura-2-thalia-en', // vendor specific, omit for the vendor default
|
|
314
|
+
prompt: 'You are a reservations agent for Acme Cafe. Be brief and friendly.',
|
|
315
|
+
// A longer prompt usually belongs in a file, not inlined:
|
|
316
|
+
// prompt: (call, ctx) => ctx.assets('prompt.md'),
|
|
317
|
+
greeting: async (call, ctx) => {
|
|
318
|
+
const name = await lookupCallerName(call.from, ctx);
|
|
319
|
+
return name
|
|
320
|
+
? `Hello, ${name}! Thanks for calling Acme Cafe.`
|
|
321
|
+
: 'Hello! Thanks for calling Acme Cafe.';
|
|
322
|
+
},
|
|
323
|
+
tools: [checkAvailability, bookTable],
|
|
324
|
+
// Transfer to the host stand for anything this agent cannot resolve — injects a
|
|
325
|
+
// `transfer_to_human` tool the model can call; `hangup: true` (the default) injects
|
|
326
|
+
// `hangup_call` the same way. Both are ordinary PerCallValue options, so this can be a
|
|
327
|
+
// (call, context) => number lookup instead of a fixed string.
|
|
328
|
+
transferTo: '+15550001234',
|
|
329
|
+
providerOptions: {
|
|
330
|
+
deepgram: { sttModel: 'nova-3', llmProvider: 'open_ai', llmModel: 'gpt-5.4-nano' },
|
|
331
|
+
},
|
|
332
|
+
onTranscript: (entry, ctx) => {
|
|
333
|
+
console.log(`[${ctx.callId}] ${entry.role}: ${entry.text}`);
|
|
334
|
+
},
|
|
335
|
+
onEnd: async (ctx) => {
|
|
336
|
+
await ctx.storage.write(
|
|
337
|
+
`calls/${ctx.callId}.json`,
|
|
338
|
+
JSON.stringify({ endedAt: new Date().toISOString(), transcript: ctx.transcript })
|
|
339
|
+
);
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
`provider` is `'openai' | 'gemini' | 'deepgram' | 'grok' | 'voice-relay'`, so a typo is caught at
|
|
345
|
+
compile time rather than only on the first call. `providerOptions` is keyed by provider and only
|
|
346
|
+
reaches the matching adapter — `providerOptions.deepgram` above does nothing if `provider` is ever
|
|
347
|
+
changed to `'openai'`. The STREAM leg `realtimeAgent` dials itself is capped by the same
|
|
348
|
+
`MAX_CALL_DURATION` function variable `dialAgent` reads (default 1800 seconds).
|
|
349
|
+
|
|
350
|
+
**Per-call overrides.** `prompt`, `greeting`, `voice` and `transferTo` each take either a plain
|
|
351
|
+
value or a `(call, context) => value | Promise<value>` function, resolved once per call — before
|
|
352
|
+
the vendor session opens, so the greeting above can say "Hello, Maria" instead of a generic line.
|
|
353
|
+
`model` (in `providerOptions`) is not per-call; only these four are. `prompt: (call, ctx) =>
|
|
354
|
+
ctx.assets(...)` is how a longer prompt comes from a file in `assets/` instead of being inlined —
|
|
355
|
+
`ctx.assets` reads it as plain text, so any `{{placeholder}}` substitution the prompt needs is
|
|
356
|
+
ordinary string work in that same function, not a templating feature this helper provides.
|
|
357
|
+
|
|
358
|
+
**Voice.** Unset means no voice is sent to the vendor at all — every adapter omits the field and
|
|
359
|
+
lets the vendor apply its own default, rather than this repo picking one. Setting `voice` (a
|
|
360
|
+
portable id beyond a small mapped set — it otherwise falls through to the adapter unchanged) is
|
|
361
|
+
the only way a specific voice is used.
|
|
362
|
+
|
|
363
|
+
**Built-in tools.** `hangup` (default `true`) injects a `hangup_call` tool; `transferTo` — a
|
|
364
|
+
number or a `(call, context) => number | undefined` — injects `transfer_to_human` (args: `reason`,
|
|
365
|
+
`summary`). A per-call resolver that returns `undefined` (say, only some callers should be able to
|
|
366
|
+
reach a human) omits the tool for that call, same as leaving `transferTo` unset entirely. Neither
|
|
367
|
+
built-in is declared in `tools` above; both call the same `ctx.hangup()`/`ctx.transfer(number)`
|
|
368
|
+
primitives a custom tool would, and an author tool of the same name wins over the injected one.
|
|
369
|
+
Set `hangup: false` to drop the standard one — a template with its own goodbye-and-hang-up tool
|
|
370
|
+
does not want both.
|
|
371
|
+
|
|
372
|
+
Whenever a `hangup_call` tool is offered (built-in, or an author override of the same name), the
|
|
373
|
+
prompt gets an explicit CALL TERMINATION instruction appended — `tool_choice` stays `'auto'`
|
|
374
|
+
everywhere, so a directive tool description alone does not reliably make a model call it; a live
|
|
375
|
+
probe found GPT-Live saying goodbye and then never ending the call without this. GPT-Live's own
|
|
376
|
+
frontend voice model never calls a tool itself, only delegates to the backend that does, so it
|
|
377
|
+
gets a differently-worded variant telling it to delegate instead — its backend
|
|
378
|
+
(`delegation.responses.instructions`) gets its own short rule, since that's the model that
|
|
379
|
+
actually calls `hangup_call` once delegation happens. Nothing to configure; this only ever adds
|
|
380
|
+
to the prompt, never replaces it.
|
|
381
|
+
|
|
382
|
+
**GPT-Live backend tuning**, via `providerOptions.openai` — `backendServiceTier` (`service_tier`,
|
|
383
|
+
default `'priority'`), `backendReasoningEffort` (`reasoning.effort`, default `'none'`),
|
|
384
|
+
`backendVerbosity` (`text.verbosity`, default `'low'`), `backendParallelToolCalls`
|
|
385
|
+
(`parallel_tool_calls`, default `true`), `backendMaxOutputTokens` (`max_output_tokens`, default
|
|
386
|
+
`300`) — alongside the existing `backendModel`/`backendInstructions`. Defaults favor a spoken
|
|
387
|
+
conversation; no `temperature` field is ever sent to the backend, so it never conflicts with
|
|
388
|
+
`reasoning` per OpenAI's own delegation guide.
|
|
389
|
+
|
|
390
|
+
**What's normalised:** the tool contract, `ctx.transcript` and `onTranscript` (every turn from
|
|
391
|
+
either party, and every completed tool call, in order — see `onEnd` above), `onBargeIn`/
|
|
392
|
+
`onError`/`onEnd`, call control from inside a tool handler (`ctx.hangup()`, `ctx.transfer(number)`
|
|
393
|
+
— the same move-the-leg mechanism as the voice builder's `transferTo*`/`voiceRelay`'s
|
|
394
|
+
`call.transferToPhone`: busy, unanswered or failed drops the caller rather than returning them
|
|
395
|
+
here), audio format and barge-in clearing, and prompt/greeting delivery. **What isn't:** voice and
|
|
396
|
+
model ids beyond a small portable set, a vendor's own split STT/LLM/TTS choices (Deepgram's
|
|
397
|
+
`sttModel`/`llmProvider`/`llmModel` above, for instance), and turn-detection/latency feel — tune
|
|
398
|
+
those per vendor through `providerOptions`. Audio defaults to 8kHz telephony, matching the Voice
|
|
399
|
+
v2 platform's own default for calls that traverse the PSTN; pass `audio: 'wideband'` for a media
|
|
400
|
+
path that never does.
|
|
401
|
+
|
|
402
|
+
Secrets — `DEEPGRAM_API_KEY` for the example above — are read through `context.config`, the same
|
|
403
|
+
way every other function reads a secret, never inlined in `providerOptions`.
|
|
404
|
+
|
|
405
|
+
`realtimeAgent` returns a `VoiceFunction`, the same export shape a plain `voiceWebhook`/`setup`
|
|
406
|
+
function has: it answers the caller, bridges them, and dials a STREAM leg at this function's own
|
|
407
|
+
`/stream` — no `dial.stream` or raw `ws.WebSocket` to write by hand.
|
|
408
|
+
|
|
409
|
+
The one-liner `export default realtimeAgent({...})` above owns `incoming` itself. When a function
|
|
410
|
+
needs its own `incoming` logic first — a business-hours check, a lookup that decides whether to
|
|
411
|
+
answer at all — the same object also exposes `connect`, the plan-building half `voiceWebhook`
|
|
412
|
+
uses internally, so an author can fall through to it instead of reimplementing the answer →
|
|
413
|
+
bridge → dial STREAM-leg plan:
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
import { onCall, realtimeAgent } from '@sinch/functions-runtime/voice';
|
|
417
|
+
|
|
418
|
+
const agent = realtimeAgent({ provider: 'deepgram', prompt: '...' /* tools, hooks, etc. */ });
|
|
419
|
+
|
|
420
|
+
export const voiceWebhook = onCall({
|
|
421
|
+
incoming: async (call, builder, context) => {
|
|
422
|
+
if (isAfterHours()) {
|
|
423
|
+
return builder.say('Sorry, we are closed. Please call back during business hours.').hangup();
|
|
424
|
+
}
|
|
425
|
+
return agent.connect(call, builder, context);
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
### Talking to an LLM over Voice Relay
|
|
431
|
+
|
|
432
|
+
`provider: 'voice-relay'` runs `realtimeAgent` on top of `voiceRelay` instead of a vendor's own
|
|
433
|
+
realtime audio session: Sinch does the speech (STT/TTS), and this function runs the model as a
|
|
434
|
+
text loop over that same connection. From the author's side it behaves like every other
|
|
435
|
+
provider — the same options, `ctx`, `onTranscript`, injected `hangup_call`/`transfer_to_human`
|
|
436
|
+
tools, tool calling and barge-in:
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
export default realtimeAgent({
|
|
440
|
+
provider: 'voice-relay',
|
|
441
|
+
model: 'gpt-4o-mini',
|
|
442
|
+
prompt: 'You are a reservations agent for Acme Cafe. Be brief and friendly.',
|
|
443
|
+
tools: [checkAvailability, bookTable],
|
|
444
|
+
transferTo: '+15550001234',
|
|
445
|
+
});
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
`model` works with any model behind an OpenAI Responses-compatible API — OpenAI, Azure OpenAI, or
|
|
449
|
+
a gateway such as OpenRouter or LiteLLM — sent straight through with no prefix or registry lookup.
|
|
450
|
+
`baseUrl` (or the `OPENAI_BASE_URL` function variable, when `baseUrl` is unset) points it at a
|
|
451
|
+
server other than `https://api.openai.com/v1`. The credential is always the caller's own
|
|
452
|
+
`OPENAI_API_KEY` function secret, read fresh per call rather than cached globally.
|
|
453
|
+
|
|
454
|
+
**Low-latency options**, for a model and account that support them:
|
|
455
|
+
|
|
456
|
+
```ts
|
|
457
|
+
export default realtimeAgent({
|
|
458
|
+
provider: 'voice-relay',
|
|
459
|
+
model: 'gpt-5.4-nano',
|
|
460
|
+
serviceTier: 'priority',
|
|
461
|
+
reasoningEffort: 'none',
|
|
462
|
+
prompt: '...',
|
|
463
|
+
});
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
`serviceTier` (`'auto'` / `'default'` / `'flex'` / `'priority'` / `'fast'`) maps to
|
|
467
|
+
`service_tier`, `reasoningEffort` (`'none'` / `'minimal'` / `'low'` / `'medium'` / `'high'`) to
|
|
468
|
+
`reasoning.effort`, `verbosity` (`'low'` / `'medium'` / `'high'`) to `text.verbosity` — all
|
|
469
|
+
omitted from the request when unset. `LLM_SERVICE_TIER`/`LLM_REASONING_EFFORT`/`LLM_VERBOSITY`
|
|
470
|
+
function variables set them without a code change; an explicit option here wins over the
|
|
471
|
+
variable, which wins over the built-in default.
|
|
472
|
+
|
|
473
|
+
**What the default depends on, and why**: with no `baseUrl` (or `api.openai.com` explicitly),
|
|
474
|
+
`serviceTier` defaults to `'fast'` and every turn uses `store: true` with `previous_response_id`
|
|
475
|
+
chaining — only the new turn is sent, not the whole conversation. Azure OpenAI
|
|
476
|
+
(`*.openai.azure.com`) gets the same chaining but no `serviceTier` default — that setting is
|
|
477
|
+
calibrated against OpenAI's own account tiers. Any other `baseUrl` (a gateway — OpenRouter,
|
|
478
|
+
LiteLLM, a customer's own proxy) is not assumed to support `store`/chaining at all: every turn
|
|
479
|
+
resends the full conversation as `input`, `store: false`, no `previous_response_id`, no
|
|
480
|
+
`serviceTier` unless set explicitly. `reasoningEffort`/`verbosity` default to `'none'`/`'low'`
|
|
481
|
+
only for a `gpt-5*`/o-series model (`gpt-4o-mini` confirmed to reject them outright with a 400) —
|
|
482
|
+
that default applies the same way regardless of `baseUrl`. An o-series model is the one
|
|
483
|
+
exception: it rejects `reasoning.effort: 'none'` outright, so the defaulted value is withheld for
|
|
484
|
+
one (reasoning is omitted entirely) — an explicit option or variable is still sent, on any host
|
|
485
|
+
and for any model.
|
|
486
|
+
|
|
487
|
+
A persistent WebSocket (plain `ws`, not the `openai` package) is opened for the call on every
|
|
488
|
+
host — OpenAI, Azure OpenAI and a gateway alike — instead of a new HTTP/SSE connection per turn.
|
|
489
|
+
What a live WS failure does next depends on the host: OpenAI and Azure OpenAI never fall back to
|
|
490
|
+
HTTP — a failure opens a fresh WebSocket and retries the same turn once, and chaining state
|
|
491
|
+
(`previous_response_id`) survives the reconnect untouched. A gateway is not assumed to speak this
|
|
492
|
+
protocol at all: its first failure (the upgrade itself, or the first request being rejected)
|
|
493
|
+
latches, and every turn for the rest of that call goes over HTTP/SSE instead. A barge-in is never
|
|
494
|
+
treated as a failure on either path.
|
|
83
495
|
|
|
84
496
|
## Voice v1 (legacy)
|
|
85
497
|
|
|
@@ -206,12 +618,16 @@ Helpers such as `getText`, `getChannel`, `getContactId`, `isTextMessage` and `Co
|
|
|
206
618
|
|
|
207
619
|
### Protecting endpoints
|
|
208
620
|
|
|
209
|
-
Export `auth` to
|
|
621
|
+
Export `auth` to gate handlers behind your project API key/secret, and optionally `ADMIN_USER`/`ADMIN_PASSWORD` (a second variable/secret pair you set) as an alternative credential. `'*'` protects every endpoint; an array names the ones to protect, including `'default'` for the root handler (or the static `public/index.html`, if that's what's served there) and a static file's path, e.g. `'public/admin.html'`, for anything else under `public/`. Unlisted static assets (CSS, JS, images) stay public.
|
|
210
622
|
|
|
211
623
|
```ts
|
|
212
|
-
export const auth = ['notes', 'config'];
|
|
624
|
+
export const auth = ['notes', 'config', 'default'];
|
|
213
625
|
```
|
|
214
626
|
|
|
627
|
+
A rejected request gets one of two things: a browser navigating there (an `Accept: text/html` GET) is redirected to a branded `/login` page; anything else (curl, a script, a `fetch()` call) gets a `401` JSON body with no `WWW-Authenticate` header, so a browser never pops its own Basic Auth dialog. `curl -u user:pass` still works unchanged — Basic credentials are sent pre-emptively regardless of the challenge header.
|
|
628
|
+
|
|
629
|
+
Signing in via `/login` sets an HttpOnly session cookie (HMAC of the password, no session store) as an alternative to sending Basic on every request; it's cleared by `POST /logout`. Both routes, and the login page itself, are built in — export your own `login` and/or `logout` handler to replace either one.
|
|
630
|
+
|
|
215
631
|
## Startup and WebSockets
|
|
216
632
|
|
|
217
633
|
Export `setup` to run code once before the server accepts requests, or to accept WebSocket connections (for example a `connectStream` media stream).
|
|
@@ -235,19 +651,19 @@ export function setup(runtime: SinchRuntime) {
|
|
|
235
651
|
|
|
236
652
|
Every handler receives a `FunctionContext`.
|
|
237
653
|
|
|
238
|
-
| Member | What it is
|
|
239
|
-
| ---------------------- |
|
|
240
|
-
| `context.config` | `projectId`, `functionName`, `environment` and
|
|
241
|
-
| `context.env` | Environment variables, including secrets
|
|
242
|
-
| `context.cache` | Key-value store with TTLs: `get`, `set`, `has`, `delete`, `extend`, `keys`, `getMany`. In memory locally, shared in production
|
|
243
|
-
| `context.storage` | Durable files: `write`, `read`, `list`, `exists`, `delete`. Local filesystem in dev, object storage in production
|
|
244
|
-
| `context.database` | Path to a per-function SQLite file, replicated in production. Open it with `node:sqlite` or any SQLite driver
|
|
245
|
-
| `context.assets(name)` | Reads a file from the function's `assets/` directory
|
|
246
|
-
| `context.voice` | Voice API v2 client: `call`, `callWithStream`, `bridge`, `transfer`, `patch`, `onCall`. Always present
|
|
247
|
-
| `context.voice.v1` | Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set
|
|
248
|
-
| `context.conversation` | Conversation API client, when `CONVERSATION_APP_ID` is set
|
|
249
|
-
| `context.sms` | SMS API client, when `SMS_SERVICE_PLAN_ID` is set
|
|
250
|
-
| `context.numbers` | Numbers API client, when `ENABLE_NUMBERS_API=true`
|
|
654
|
+
| Member | What it is |
|
|
655
|
+
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
|
656
|
+
| `context.config` | `projectId`, `functionName`, `environment`, `variables`, and `getVariable`/`requireVariable`/`getSecret`/`requireSecret`/`hasVariable`… |
|
|
657
|
+
| `context.env` | Environment variables, including secrets |
|
|
658
|
+
| `context.cache` | Key-value store with TTLs: `get`, `set`, `has`, `delete`, `extend`, `keys`, `getMany`. In memory locally, shared in production |
|
|
659
|
+
| `context.storage` | Durable files: `write`, `read`, `list`, `exists`, `delete`. Local filesystem in dev, object storage in production |
|
|
660
|
+
| `context.database` | Path to a per-function SQLite file, replicated in production. Open it with `node:sqlite` or any SQLite driver |
|
|
661
|
+
| `context.assets(name)` | Reads a file from the function's `assets/` directory |
|
|
662
|
+
| `context.voice` | Voice API v2 client: `call`, `callWithStream`, `bridge`, `transfer`, `patch`, `onCall`. Always present |
|
|
663
|
+
| `context.voice.v1` | Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set |
|
|
664
|
+
| `context.conversation` | Conversation API client, when `CONVERSATION_APP_ID` is set |
|
|
665
|
+
| `context.sms` | SMS API client, when `SMS_SERVICE_PLAN_ID` is set |
|
|
666
|
+
| `context.numbers` | Numbers API client, when `ENABLE_NUMBERS_API=true` |
|
|
251
667
|
|
|
252
668
|
The API clients also need `PROJECT_ID`, `PROJECT_ID_API_KEY` and `PROJECT_ID_API_SECRET`, which `sinch auth login` provides. A client whose variables are missing is `undefined` — except `context.voice`, which is always there and reports missing credentials when a request is actually sent. Full list: [SDK environment variables](https://developers.sinch.com/docs/functions/reference/sdk-env-vars).
|
|
253
669
|
|
|
@@ -258,7 +674,7 @@ const db = new DatabaseSync(context.database);
|
|
|
258
674
|
db.exec('CREATE TABLE IF NOT EXISTS visits (day TEXT PRIMARY KEY, n INTEGER NOT NULL DEFAULT 0)');
|
|
259
675
|
```
|
|
260
676
|
|
|
261
|
-
`
|
|
677
|
+
`context.config` carries `getVariable`, `requireVariable`, `getSecret`, `requireSecret`, `hasVariable`, `hasSecret`, `isDevelopment`, `isProduction` and `getApplicationCredentials` directly: `context.config.getVariable('COMPANY_NAME', 'Acme')` returns a string, and without a default it returns `null` when unset. `createConfig(context)` and `createUniversalConfig(context)` still return the same methods on a wrapper.
|
|
262
678
|
|
|
263
679
|
## Local development and production
|
|
264
680
|
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
__toESM,
|
|
9
9
|
attachVoiceClient,
|
|
10
10
|
buildBaseContext,
|
|
11
|
+
collectCredentials,
|
|
11
12
|
createApp,
|
|
12
13
|
createCacheClient,
|
|
13
14
|
createSinchRuntime,
|
|
@@ -17,7 +18,7 @@ import {
|
|
|
17
18
|
isVoiceV1Callback,
|
|
18
19
|
secretsLoader,
|
|
19
20
|
setupRequestHandler
|
|
20
|
-
} from "../chunk-
|
|
21
|
+
} from "../chunk-TOTJB6SW.js";
|
|
21
22
|
|
|
22
23
|
// ../../node_modules/dotenv/package.json
|
|
23
24
|
var require_package = __commonJS({
|
|
@@ -585,9 +586,12 @@ async function main() {
|
|
|
585
586
|
const config = loadRuntimeConfig();
|
|
586
587
|
const staticDir = process.env.STATIC_DIR;
|
|
587
588
|
const landingPageEnabled = process.env.LANDING_PAGE_ENABLED !== "false";
|
|
588
|
-
const
|
|
589
|
+
const staticAuthRef = { credentials: [] };
|
|
590
|
+
const app = createApp({ staticDir, landingPageEnabled, staticAuthRef });
|
|
589
591
|
const authKey = process.env.PROJECT_ID_API_KEY;
|
|
590
592
|
const authSecret = process.env.PROJECT_ID_API_SECRET;
|
|
593
|
+
const adminUser = process.env.ADMIN_USER;
|
|
594
|
+
const adminPassword = process.env.ADMIN_PASSWORD;
|
|
591
595
|
let userAuthConfig;
|
|
592
596
|
const loadUserFunction = async () => {
|
|
593
597
|
const functionPath = findFunctionPath();
|
|
@@ -602,6 +606,8 @@ async function main() {
|
|
|
602
606
|
return module.default || module;
|
|
603
607
|
};
|
|
604
608
|
await loadUserFunction();
|
|
609
|
+
staticAuthRef.authConfig = userAuthConfig;
|
|
610
|
+
staticAuthRef.credentials = collectCredentials({ authKey, authSecret, adminUser, adminPassword });
|
|
605
611
|
let setupResult;
|
|
606
612
|
const rawModule = await import(pathToFileURL(findFunctionPath()).href);
|
|
607
613
|
const setupFn = rawModule.setup || rawModule.default?.setup;
|
|
@@ -619,6 +625,8 @@ async function main() {
|
|
|
619
625
|
authConfig: userAuthConfig,
|
|
620
626
|
authKey,
|
|
621
627
|
authSecret,
|
|
628
|
+
adminUser,
|
|
629
|
+
adminPassword,
|
|
622
630
|
loadUserFunction,
|
|
623
631
|
buildContext: (req) => buildLocalContext(req, config),
|
|
624
632
|
logger: console.log,
|