@sinch/functions-runtime 0.5.22 → 0.6.1

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 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, commands } from '@sinch/functions-runtime';
26
+ import { onCall } from '@sinch/functions-runtime/voice';
27
27
 
28
28
  export const voiceWebhook = onCall({
29
- incoming: () => commands().answer().say('Thanks for calling.').hangup(),
30
- completed: (event) => {
31
- console.log('call ended', event.call.callId);
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. Return a `commands()` builder and the runtime emits the wire body;
39
- return nothing and it answers `204`.
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,27 @@ 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
- `createClient`, `commands`, `Client` and the core v2 types are importable from the package
80
- root, as above, or from `@sinch/functions-runtime/voice/v2` — both resolve the same
81
- declarations. The rest of the v2 surface (`MenuItemBuilder`, `dialPhone`, `dialSip`, etc.) is
82
- subpath-only, for code that builds a client of its own.
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.
83
133
 
84
134
  ### Connecting a call to an AI agent
85
135
 
@@ -87,7 +137,8 @@ subpath-only, for code that builds a client of its own.
87
137
  in one call, instead of hand-writing the answer/bridge/dial/teardown commands it takes:
88
138
 
89
139
  ```ts
90
- import { onCall, connectAgent, AgentProvider } from '@sinch/functions-runtime';
140
+ import { AgentProvider } from '@sinch/functions-runtime';
141
+ import { onCall, connectAgent } from '@sinch/functions-runtime/voice';
91
142
 
92
143
  export const voiceWebhook = onCall({
93
144
  incoming: (call) => connectAgent(AgentProvider.ElevenLabs, '+15551234567', { call }),
@@ -107,6 +158,358 @@ Return the result directly from `incoming`, as above — `callName` and the agen
107
158
  hangup are only honoured on a response to `call.incoming`, so forwarding just its `.commands`
108
159
  elsewhere silently drops the teardown and leaves the SIP leg billing until `maxDuration`.
109
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`, `transferTo` and `language` each take
351
+ either a plain value or a `(call, context) => value | Promise<value>` function, resolved once per
352
+ call — before the vendor session opens, so the greeting above can say "Hello, Maria" instead of a
353
+ generic line. `language` is a BCP-47 tag (e.g. `'en-US'`, `'es-MX'`) that pins the provider's
354
+ speech recognition instead of letting it auto-detect; defaults to `'en-US'`. `timezone` (plain
355
+ string, not per-call — a property of the deployment, not the caller) defaults to
356
+ `'America/Chicago'` and drives the current date/time line prepended to every provider's resolved
357
+ prompt. `model` (in `providerOptions`) is not per-call; only `prompt`/`greeting`/`voice`/
358
+ `transferTo`/`language` are. `prompt: (call, ctx) =>
359
+ ctx.assets(...)` is how a longer prompt comes from a file in `assets/` instead of being inlined —
360
+ `ctx.assets` reads it as plain text, so any `{{placeholder}}` substitution the prompt needs is
361
+ ordinary string work in that same function, not a templating feature this helper provides.
362
+
363
+ **Voice.** Unset means no voice is sent to the vendor at all — every adapter omits the field and
364
+ lets the vendor apply its own default, rather than this repo picking one. Setting `voice` (a
365
+ portable id beyond a small mapped set — it otherwise falls through to the adapter unchanged) is
366
+ the only way a specific voice is used.
367
+
368
+ **Built-in tools.** `hangup` (default `true`) injects a `hangup_call` tool; `transferTo` — a
369
+ number or a `(call, context) => number | undefined` — injects `transfer_to_human` (args: `reason`,
370
+ `summary`). A per-call resolver that returns `undefined` (say, only some callers should be able to
371
+ reach a human) omits the tool for that call, same as leaving `transferTo` unset entirely. Neither
372
+ built-in is declared in `tools` above; both call the same `ctx.hangup()`/`ctx.transfer(number)`
373
+ primitives a custom tool would, and an author tool of the same name wins over the injected one.
374
+ Set `hangup: false` to drop the standard one — a template with its own goodbye-and-hang-up tool
375
+ does not want both.
376
+
377
+ Whenever a `hangup_call` tool is offered (built-in, or an author override of the same name), the
378
+ prompt gets an explicit CALL TERMINATION instruction appended — `tool_choice` stays `'auto'`
379
+ everywhere, so a directive tool description alone does not reliably make a model call it; a live
380
+ probe found GPT-Live saying goodbye and then never ending the call without this. GPT-Live's own
381
+ frontend voice model never calls a tool itself, only delegates to the backend that does, so it
382
+ gets a differently-worded variant telling it to delegate instead — its backend
383
+ (`delegation.responses.instructions`) gets its own short rule, since that's the model that
384
+ actually calls `hangup_call` once delegation happens. Nothing to configure; this only ever adds
385
+ to the prompt, never replaces it.
386
+
387
+ **GPT-Live backend tuning**, via `providerOptions.openai` — `backendServiceTier` (`service_tier`,
388
+ default `'priority'`), `backendReasoningEffort` (`reasoning.effort`, default `'none'`),
389
+ `backendVerbosity` (`text.verbosity`, default `'low'`), `backendParallelToolCalls`
390
+ (`parallel_tool_calls`, default `true`), `backendMaxOutputTokens` (`max_output_tokens`, default
391
+ `300`) — alongside the existing `backendModel`/`backendInstructions`. Defaults favor a spoken
392
+ conversation; no `temperature` field is ever sent to the backend, so it never conflicts with
393
+ `reasoning` per OpenAI's own delegation guide.
394
+
395
+ **What's normalised:** the tool contract, `ctx.transcript` and `onTranscript` (every turn from
396
+ either party, and every completed tool call, in order — see `onEnd` above), `onBargeIn`/
397
+ `onError`/`onEnd`, call control from inside a tool handler (`ctx.hangup()`, `ctx.transfer(number)`
398
+ — the same move-the-leg mechanism as the voice builder's `transferTo*`/`voiceRelay`'s
399
+ `call.transferToPhone`: busy, unanswered or failed drops the caller rather than returning them
400
+ here), audio format and barge-in clearing, and prompt/greeting delivery.
401
+
402
+ **Usage and turn timing.** `ctx.usage` (`inputTokens`/`outputTokens`/`audioSeconds`) is the call's
403
+ running total so far, updated as the vendor reports it — tokens/seconds only, no dollar prices.
404
+ Each `TranscriptEntry` also carries, where the provider reports it: `latencyMs` (time from the
405
+ caller's turn finishing to this reply's first spoken sentence, or a tool's own run time),
406
+ `totalMs` (agent turns only: time to the whole reply completing, including any tool rounds —
407
+ unset if the turn was abandoned by a barge-in), `speechStartAt`/`speechEndAt` (user turns; filled
408
+ by an energy-VAD fallback on raw caller audio when a provider doesn't report its own boundary),
409
+ and `playbackStartAt`/`playbackEndAt`/`interrupted` (agent turns; left unset when a provider
410
+ reports no playback signal). Fields a provider doesn't support stay unset rather than guessed at.
411
+
412
+ **What isn't normalised:** voice and
413
+ model ids beyond a small portable set, a vendor's own split STT/LLM/TTS choices (Deepgram's
414
+ `sttModel`/`llmProvider`/`llmModel` above, for instance), and turn-detection/latency feel — tune
415
+ those per vendor through `providerOptions`. Audio defaults to 8kHz telephony, matching the Voice
416
+ v2 platform's own default for calls that traverse the PSTN; pass `audio: 'wideband'` for a media
417
+ path that never does.
418
+
419
+ Secrets — `DEEPGRAM_API_KEY` for the example above — are read through `context.config`, the same
420
+ way every other function reads a secret, never inlined in `providerOptions`.
421
+
422
+ `realtimeAgent` returns a `VoiceFunction`, the same export shape a plain `voiceWebhook`/`setup`
423
+ function has: it answers the caller, bridges them, and dials a STREAM leg at this function's own
424
+ `/stream` — no `dial.stream` or raw `ws.WebSocket` to write by hand.
425
+
426
+ The one-liner `export default realtimeAgent({...})` above owns `incoming` itself. When a function
427
+ needs its own `incoming` logic first — a business-hours check, a lookup that decides whether to
428
+ answer at all — the same object also exposes `connect`, the plan-building half `voiceWebhook`
429
+ uses internally, so an author can fall through to it instead of reimplementing the answer →
430
+ bridge → dial STREAM-leg plan:
431
+
432
+ ```ts
433
+ import { onCall, realtimeAgent } from '@sinch/functions-runtime/voice';
434
+
435
+ const agent = realtimeAgent({ provider: 'deepgram', prompt: '...' /* tools, hooks, etc. */ });
436
+
437
+ export const voiceWebhook = onCall({
438
+ incoming: async (call, builder, context) => {
439
+ if (isAfterHours()) {
440
+ return builder.say('Sorry, we are closed. Please call back during business hours.').hangup();
441
+ }
442
+ return agent.connect(call, builder, context);
443
+ },
444
+ });
445
+ ```
446
+
447
+ ### Talking to an LLM over Voice Relay
448
+
449
+ `provider: 'voice-relay'` runs `realtimeAgent` on top of `voiceRelay` instead of a vendor's own
450
+ realtime audio session: Sinch does the speech (STT/TTS), and this function runs the model as a
451
+ text loop over that same connection. From the author's side it behaves like every other
452
+ provider — the same options, `ctx`, `onTranscript`, injected `hangup_call`/`transfer_to_human`
453
+ tools, tool calling and barge-in:
454
+
455
+ ```ts
456
+ export default realtimeAgent({
457
+ provider: 'voice-relay',
458
+ model: 'gpt-4o-mini',
459
+ prompt: 'You are a reservations agent for Acme Cafe. Be brief and friendly.',
460
+ tools: [checkAvailability, bookTable],
461
+ transferTo: '+15550001234',
462
+ });
463
+ ```
464
+
465
+ `model` works with any model behind an OpenAI Responses-compatible API — OpenAI, Azure OpenAI, or
466
+ a gateway such as OpenRouter or LiteLLM — sent straight through with no prefix or registry lookup.
467
+ `baseUrl` (or the `OPENAI_BASE_URL` function variable, when `baseUrl` is unset) points it at a
468
+ server other than `https://api.openai.com/v1`. The credential is always the caller's own
469
+ `OPENAI_API_KEY` function secret, read fresh per call rather than cached globally.
470
+
471
+ **Low-latency options**, for a model and account that support them:
472
+
473
+ ```ts
474
+ export default realtimeAgent({
475
+ provider: 'voice-relay',
476
+ model: 'gpt-5.4-nano',
477
+ serviceTier: 'priority',
478
+ reasoningEffort: 'none',
479
+ prompt: '...',
480
+ });
481
+ ```
482
+
483
+ `serviceTier` (`'auto'` / `'default'` / `'flex'` / `'priority'` / `'fast'`) maps to
484
+ `service_tier`, `reasoningEffort` (`'none'` / `'minimal'` / `'low'` / `'medium'` / `'high'`) to
485
+ `reasoning.effort`, `verbosity` (`'low'` / `'medium'` / `'high'`) to `text.verbosity` — all
486
+ omitted from the request when unset. `LLM_SERVICE_TIER`/`LLM_REASONING_EFFORT`/`LLM_VERBOSITY`
487
+ function variables set them without a code change; an explicit option here wins over the
488
+ variable, which wins over the built-in default.
489
+
490
+ **What the default depends on, and why**: with no `baseUrl` (or `api.openai.com` explicitly),
491
+ `serviceTier` defaults to `'fast'` and every turn uses `store: true` with `previous_response_id`
492
+ chaining — only the new turn is sent, not the whole conversation. Azure OpenAI
493
+ (`*.openai.azure.com`) gets the same chaining but no `serviceTier` default — that setting is
494
+ calibrated against OpenAI's own account tiers. Any other `baseUrl` (a gateway — OpenRouter,
495
+ LiteLLM, a customer's own proxy) is not assumed to support `store`/chaining at all: every turn
496
+ resends the full conversation as `input`, `store: false`, no `previous_response_id`, no
497
+ `serviceTier` unless set explicitly. `reasoningEffort`/`verbosity` default to `'none'`/`'low'`
498
+ only for a `gpt-5*`/o-series model (`gpt-4o-mini` confirmed to reject them outright with a 400) —
499
+ that default applies the same way regardless of `baseUrl`. An o-series model is the one
500
+ exception: it rejects `reasoning.effort: 'none'` outright, so the defaulted value is withheld for
501
+ one (reasoning is omitted entirely) — an explicit option or variable is still sent, on any host
502
+ and for any model.
503
+
504
+ A persistent WebSocket (plain `ws`, not the `openai` package) is opened for the call on every
505
+ host — OpenAI, Azure OpenAI and a gateway alike — instead of a new HTTP/SSE connection per turn.
506
+ What a live WS failure does next depends on the host: OpenAI and Azure OpenAI never fall back to
507
+ HTTP — a failure opens a fresh WebSocket and retries the same turn once, and chaining state
508
+ (`previous_response_id`) survives the reconnect untouched. A gateway is not assumed to speak this
509
+ protocol at all: its first failure (the upgrade itself, or the first request being rejected)
510
+ latches, and every turn for the rest of that call goes over HTTP/SSE instead. A barge-in is never
511
+ treated as a failure on either path.
512
+
110
513
  ## Voice v1 (legacy)
111
514
 
112
515
  v1 still works, and a function already written against it needs no changes beyond the client:
@@ -232,12 +635,16 @@ Helpers such as `getText`, `getChannel`, `getContactId`, `isTextMessage` and `Co
232
635
 
233
636
  ### Protecting endpoints
234
637
 
235
- Export `auth` to require HTTP Basic authentication with your project API key and secret. `'*'` protects every endpoint; an array names the ones to protect.
638
+ 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.
236
639
 
237
640
  ```ts
238
- export const auth = ['notes', 'config'];
641
+ export const auth = ['notes', 'config', 'default'];
239
642
  ```
240
643
 
644
+ 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.
645
+
646
+ 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.
647
+
241
648
  ## Startup and WebSockets
242
649
 
243
650
  Export `setup` to run code once before the server accepts requests, or to accept WebSocket connections (for example a `connectStream` media stream).
@@ -261,19 +668,19 @@ export function setup(runtime: SinchRuntime) {
261
668
 
262
669
  Every handler receives a `FunctionContext`.
263
670
 
264
- | Member | What it is |
265
- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
266
- | `context.config` | `projectId`, `functionName`, `environment` and the `variables` you set at init or deploy |
267
- | `context.env` | Environment variables, including secrets |
268
- | `context.cache` | Key-value store with TTLs: `get`, `set`, `has`, `delete`, `extend`, `keys`, `getMany`. In memory locally, shared in production |
269
- | `context.storage` | Durable files: `write`, `read`, `list`, `exists`, `delete`. Local filesystem in dev, object storage in production |
270
- | `context.database` | Path to a per-function SQLite file, replicated in production. Open it with `node:sqlite` or any SQLite driver |
271
- | `context.assets(name)` | Reads a file from the function's `assets/` directory |
272
- | `context.voice` | Voice API v2 client: `call`, `callWithStream`, `bridge`, `transfer`, `patch`, `onCall`. Always present |
273
- | `context.voice.v1` | Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set |
274
- | `context.conversation` | Conversation API client, when `CONVERSATION_APP_ID` is set |
275
- | `context.sms` | SMS API client, when `SMS_SERVICE_PLAN_ID` is set |
276
- | `context.numbers` | Numbers API client, when `ENABLE_NUMBERS_API=true` |
671
+ | Member | What it is |
672
+ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
673
+ | `context.config` | `projectId`, `functionName`, `environment`, `variables`, and `getVariable`/`requireVariable`/`getSecret`/`requireSecret`/`hasVariable`… |
674
+ | `context.env` | Environment variables, including secrets |
675
+ | `context.cache` | Key-value store with TTLs: `get`, `set`, `has`, `delete`, `extend`, `keys`, `getMany`. In memory locally, shared in production |
676
+ | `context.storage` | Durable files: `write`, `read`, `list`, `exists`, `delete`. Local filesystem in dev, object storage in production |
677
+ | `context.database` | Path to a per-function SQLite file, replicated in production. Open it with `node:sqlite` or any SQLite driver |
678
+ | `context.assets(name)` | Reads a file from the function's `assets/` directory |
679
+ | `context.voice` | Voice API v2 client: `call`, `callWithStream`, `bridge`, `transfer`, `patch`, `onCall`. Always present |
680
+ | `context.voice.v1` | Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set |
681
+ | `context.conversation` | Conversation API client, when `CONVERSATION_APP_ID` is set |
682
+ | `context.sms` | SMS API client, when `SMS_SERVICE_PLAN_ID` is set |
683
+ | `context.numbers` | Numbers API client, when `ENABLE_NUMBERS_API=true` |
277
684
 
278
685
  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).
279
686
 
@@ -284,7 +691,7 @@ const db = new DatabaseSync(context.database);
284
691
  db.exec('CREATE TABLE IF NOT EXISTS visits (day TEXT PRIMARY KEY, n INTEGER NOT NULL DEFAULT 0)');
285
692
  ```
286
693
 
287
- `createConfig(context)` wraps the configuration with `getVariable`, `requireVariable`, `getSecret`, `requireSecret`, `isDevelopment` and `getApplicationCredentials`.
694
+ `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.
288
695
 
289
696
  ## Local development and production
290
697
 
@@ -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-JP6PANB3.js";
21
+ } from "../chunk-DHM4MH2A.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 app = createApp({ staticDir, landingPageEnabled });
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,