@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.
@@ -1,11 +1,262 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
- import { commands, createClient, Client, CommandBuilder } from '../index.js';
3
- import type { Command, Flow, WebhookRequest, Call, HandlerResult, CallHandlers } from '../index.js';
2
+ import { commands, createClient, Client, CommandBuilder, onCall, voiceRelay, realtimeAgent, tool } from '../index.js';
3
+ import type { Command, Flow, WebhookRequest, Call, HandlerResult, CallHandlers, VoiceCallHandler, VoiceCallHandlers, VoiceRelayOptions, VoiceRelayHandle, RelayCall, RelaySendOptions, RealtimeAgentOptions, RealtimeTool } from '../index.js';
4
4
 
5
- export { commands, createClient, Client, CommandBuilder };
6
- export type { Command, Flow, WebhookRequest, Call, HandlerResult, CallHandlers };
5
+ export { commands, createClient, Client, CommandBuilder, onCall, voiceRelay, realtimeAgent, tool };
6
+ export type { Command, Flow, WebhookRequest, Call, HandlerResult, CallHandlers, VoiceCallHandler, VoiceCallHandlers, VoiceRelayOptions, VoiceRelayHandle, RelayCall, RelaySendOptions, RealtimeAgentOptions, RealtimeTool };
7
7
 
8
8
 
9
+ import { ConversationService } from '@sinch/conversation';
10
+ import { NumbersService } from '@sinch/numbers';
11
+ import { SmsService } from '@sinch/sms';
12
+ import { Voice, VoiceService } from '@sinch/voice';
13
+
14
+ interface SayInstruction {
15
+ name: "say";
16
+ text: string;
17
+ locale?: string;
18
+ }
19
+ interface PlayInstruction {
20
+ name: "play";
21
+ url: string;
22
+ }
23
+ interface PlayFilesInstruction {
24
+ name: "playFiles";
25
+ ids: string[];
26
+ locale?: string;
27
+ }
28
+ interface StartRecordingInstruction {
29
+ name: "startRecording";
30
+ options?: {
31
+ destinationUrl?: string;
32
+ credentials?: string;
33
+ format?: string;
34
+ notificationEvents?: boolean;
35
+ transcriptionEnabled?: boolean;
36
+ transcriptionLocale?: string;
37
+ };
38
+ }
39
+ interface StopRecordingInstruction {
40
+ name: "stopRecording";
41
+ }
42
+ interface SetCookieInstruction {
43
+ name: "setCookie";
44
+ key: string;
45
+ value: string;
46
+ }
47
+ interface AnswerInstruction {
48
+ name: "answer";
49
+ }
50
+ interface SendDtmfInstruction {
51
+ name: "sendDtmf";
52
+ value: string;
53
+ }
54
+ type SvamletInstruction = SayInstruction | PlayInstruction | PlayFilesInstruction | StartRecordingInstruction | StopRecordingInstruction | SetCookieInstruction | AnswerInstruction | SendDtmfInstruction;
55
+ interface BaseAction {
56
+ name: string;
57
+ }
58
+ interface HangupAction extends BaseAction {
59
+ name: "hangup";
60
+ }
61
+ interface ContinueAction extends BaseAction {
62
+ name: "continue";
63
+ }
64
+ interface ConnectPstnAction extends BaseAction {
65
+ name: "connectPstn";
66
+ number: string;
67
+ cli?: string;
68
+ maxDuration?: number;
69
+ timeout?: number;
70
+ enableAce?: boolean;
71
+ enableDice?: boolean;
72
+ enablePie?: boolean;
73
+ dtmf?: string;
74
+ custom?: string;
75
+ indications?: string;
76
+ amd?: {
77
+ enabled: boolean;
78
+ };
79
+ }
80
+ interface ConnectSipAction extends BaseAction {
81
+ name: "connectSip";
82
+ /** SVAML `destinationSip` — a discriminated object; both fields are required. */
83
+ destination: {
84
+ type: "sip";
85
+ endpoint: string;
86
+ };
87
+ cli?: string;
88
+ headers?: Record<string, string>;
89
+ custom?: string;
90
+ }
91
+ interface ConnectMxpAction extends BaseAction {
92
+ name: "connectMxp";
93
+ /** SVAML `destinationMxp` — a discriminated object; both fields are required. */
94
+ destination: {
95
+ type: "username" | "Username";
96
+ endpoint: string;
97
+ };
98
+ cli?: string;
99
+ custom?: string;
100
+ }
101
+ interface ConnectConfAction extends BaseAction {
102
+ name: "connectConf";
103
+ conferenceId: string;
104
+ moh?: string;
105
+ enableDice?: boolean;
106
+ custom?: string;
107
+ }
108
+ interface ParkAction extends BaseAction {
109
+ name: "park";
110
+ holdPrompt?: string;
111
+ maxDuration?: number;
112
+ custom?: string;
113
+ }
114
+ interface RunMenuAction extends BaseAction {
115
+ name: "runMenu";
116
+ menus: Menu[];
117
+ barge?: boolean;
118
+ enableDice?: boolean;
119
+ custom?: string;
120
+ }
121
+ interface ConnectStreamAction extends BaseAction {
122
+ name: "connectStream";
123
+ destination: {
124
+ type: "websocket";
125
+ endpoint: string;
126
+ };
127
+ streamingOptions?: {
128
+ version?: number;
129
+ sampleRate?: 8000 | 16000;
130
+ maxFrameSizeMs?: 20 | 40;
131
+ };
132
+ custom?: string;
133
+ }
134
+ interface ConnectAgentAction extends BaseAction {
135
+ name: "connectSip";
136
+ destination: {
137
+ type: "sip";
138
+ endpoint: string;
139
+ };
140
+ /** SIP transport. Grok's endpoint is TLS-only; most others accept TCP. */
141
+ transport?: "UDP" | "TCP" | "TLS";
142
+ cli?: string;
143
+ maxDuration?: number;
144
+ suppressCallbacks?: boolean;
145
+ /** Private SIP headers the far end sees — xAI surfaces these to the agent as `sip_headers`. */
146
+ callHeaders?: {
147
+ key: string;
148
+ value: string;
149
+ }[];
150
+ custom?: string;
151
+ }
152
+ type SvamletAction = HangupAction | ContinueAction | ConnectPstnAction | ConnectSipAction | ConnectMxpAction | ConnectConfAction | ParkAction | RunMenuAction | ConnectStreamAction | ConnectAgentAction;
153
+ interface MenuOption {
154
+ dtmf: string;
155
+ action: string;
156
+ }
157
+ interface Menu {
158
+ id: string;
159
+ mainPrompt: string;
160
+ repeatPrompt?: string;
161
+ options: MenuOption[];
162
+ repeats?: number;
163
+ maxDigits?: number;
164
+ timeoutMills?: number;
165
+ locale?: string;
166
+ }
167
+ interface SvamletResponse {
168
+ /** Instructions to execute before the action */
169
+ instructions?: SvamletInstruction[];
170
+ /** Action to take after instructions complete */
171
+ action: SvamletAction;
172
+ }
173
+ interface IFunctionCache {
174
+ /**
175
+ * Store a value with optional TTL
176
+ *
177
+ * @param key - Cache key
178
+ * @param value - Value to store (will be JSON serialized)
179
+ * @param ttlSeconds - Time to live in seconds (default: 3600)
180
+ *
181
+ * @example
182
+ * ```typescript
183
+ * await context.cache.set('user:123', { name: 'Alice' }, 3600);
184
+ * ```
185
+ */
186
+ set<T = unknown>(key: string, value: T, ttlSeconds?: number): Promise<void>;
187
+ /**
188
+ * Retrieve a value from cache
189
+ *
190
+ * @param key - Cache key
191
+ * @returns The stored value or null if not found/expired
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * const user = await context.cache.get<{ name: string }>('user:123');
196
+ * if (user) console.log(user.name);
197
+ * ```
198
+ */
199
+ get<T = unknown>(key: string): Promise<T | null>;
200
+ /**
201
+ * Check if a key exists in the cache
202
+ *
203
+ * @param key - Cache key
204
+ */
205
+ has(key: string): Promise<boolean>;
206
+ /**
207
+ * Delete a value from cache
208
+ *
209
+ * @param key - Cache key
210
+ * @returns true if the key existed and was deleted
211
+ */
212
+ delete(key: string): Promise<boolean>;
213
+ /**
214
+ * Extend TTL for a key
215
+ *
216
+ * @param key - Cache key
217
+ * @param additionalSeconds - Additional seconds to add to TTL
218
+ * @returns true if the key exists and TTL was extended
219
+ *
220
+ * @example
221
+ * ```typescript
222
+ * // Keep session alive for another 10 minutes
223
+ * await context.cache.extend('session:abc', 600);
224
+ * ```
225
+ */
226
+ extend(key: string, additionalSeconds: number): Promise<boolean>;
227
+ /**
228
+ * Get all keys matching a pattern
229
+ *
230
+ * @param pattern - Pattern with * wildcard (default: '*')
231
+ * @returns Array of matching keys
232
+ *
233
+ * @example
234
+ * ```typescript
235
+ * const sessionKeys = await context.cache.keys('session:*');
236
+ * ```
237
+ */
238
+ keys(pattern?: string): Promise<string[]>;
239
+ /**
240
+ * Get multiple values at once
241
+ *
242
+ * @param keys - Array of keys to retrieve
243
+ * @returns Object with keys and their values (or null if not found)
244
+ *
245
+ * @example
246
+ * ```typescript
247
+ * const keys = await context.cache.keys('user:*');
248
+ * const users = await context.cache.getMany<User>(keys);
249
+ * ```
250
+ */
251
+ getMany<T = unknown>(keys: string[]): Promise<Record<string, T | null>>;
252
+ }
253
+ interface IFunctionStorage {
254
+ write(key: string, data: string | Buffer): Promise<void>;
255
+ read(key: string): Promise<Buffer>;
256
+ list(prefix?: string): Promise<string[]>;
257
+ exists(key: string): Promise<boolean>;
258
+ delete(key: string): Promise<void>;
259
+ }
9
260
  interface ClientContext {
10
261
  /** Function configuration. Only `projectId` is read. */
11
262
  config?: {
@@ -416,7 +667,7 @@ export type EventType = "call.incoming" | "call.answered" | "call.busy" | "call.
416
667
  * @remarks
417
668
  * This is an object with a `commands` array, not a bare array.
418
669
  */
419
- export interface WebhookResponse {
670
+ export interface WebhookBody {
420
671
  /** Ordered command list. At least one command. */
421
672
  commands: Command[];
422
673
  /** Names the inbound leg. Ignored on responses to anything but `call.incoming`. */
@@ -433,7 +684,7 @@ interface CallTransport {
433
684
  *
434
685
  * The body is deliberately permissive rather than `CallRequest`: {@link Client.raw} is an
435
686
  * escape hatch for bodies this module does not model, and validation belongs to
436
- * `toCallRequest`, not to the transport.
687
+ * `toCallBody`, not to the transport.
437
688
  *
438
689
  * @param body - A `callRequest` body, or any object the API accepts
439
690
  * @throws If the API rejects the request
@@ -463,67 +714,92 @@ export type Destination = string | To;
463
714
  export type Origin = string | From;
464
715
  /** Custom call headers, as a plain map or as the wire array */
465
716
  type Headers$1 = Record<string, string> | CallHeader[];
466
- /**
467
- * Build a PHONE destination.
468
- *
469
- * @param number - E.164 phone number. Spaces and dashes are stripped.
470
- *
471
- * @example
472
- * ```typescript
473
- * dialPhone('+15551234567'); // { type: 'PHONE', phone: { number: '+15551234567' } }
474
- * ```
475
- */
476
- export declare function dialPhone(number: string): PhoneEndpoint;
477
- /**
478
- * Build a SIP destination.
479
- *
480
- * @param address - SIP URI (`sip:` or `sips:`)
481
- * @param options - Transport protocol and custom SIP headers
482
- *
483
- * @example
484
- * ```typescript
485
- * dialSip('sip:agent@pbx.example.com', { transport: 'TLS' });
486
- * ```
487
- */
488
- export declare function dialSip(address: string, options?: {
717
+ declare function phone(number: string): PhoneEndpoint;
718
+ declare function sip(address: string, options?: {
489
719
  transport?: "UDP" | "TCP" | "TLS";
490
720
  headers?: Headers$1;
491
721
  }): SipEndpoint;
722
+ declare function stream(endpoint: string, options?: {
723
+ sampleRate?: SampleRate;
724
+ headers?: Headers$1;
725
+ }): StreamEndpoint;
726
+ declare function relay(endpoint: string, options?: {
727
+ ttsVoice?: string;
728
+ sttLanguage?: string;
729
+ enableInterruptions?: boolean;
730
+ headers?: Headers$1;
731
+ }): VoiceRelayEndpoint;
492
732
  /**
493
- * Build a STREAM destination — a WebSocket leg carrying real-time audio.
494
- *
495
- * `streamOptions` is always sent in full, never partially and never omitted: the schema's
496
- * per-field default is 8 kHz (spec line 2904), which is not what any consumer of a stream
497
- * this library builds expects.
498
- *
499
- * @param endpoint - WebSocket URL (`ws://` or `wss://`) reachable from the public internet
500
- * @param options - Sample rate, and headers delivered on the WebSocket upgrade and in the `connect` message
733
+ * Destination builders, one per endpoint type. Nouns: each builds the `to` of a `dial` and
734
+ * nothing more. The verbs that put one on a call are the builder's `.dialPhone()`,
735
+ * `.dialSip()`, `.dialStream()` and `.dialRelay()`.
501
736
  *
502
737
  * @example
503
738
  * ```typescript
504
- * dialStream('wss://example.com/audio', { headers: { 'x-contact-id': 'abc123' } });
739
+ * commands().dial(dial.sip('sip:agent@pbx.example.com', { transport: 'TLS' }), { timeout: 20 });
505
740
  * ```
506
741
  */
507
- export declare function dialStream(endpoint: string, options?: {
508
- sampleRate?: SampleRate;
509
- headers?: Headers$1;
510
- }): StreamEndpoint;
742
+ export declare const dial: {
743
+ readonly phone: typeof phone;
744
+ readonly sip: typeof sip;
745
+ readonly stream: typeof stream;
746
+ readonly relay: typeof relay;
747
+ };
748
+ /** An endpoint on the v2 `call` payload is a discriminated union, not the bare string v1 sent. */
749
+ export declare function endpointNumber(value: From | To | undefined): string;
750
+ /** SIP-based agent providers `dialAgent` and `connectAgent` can bridge to. */
751
+ export type SipAgentProvider = "elevenlabs" | "grok";
511
752
  /**
512
- * Build a VOICE_RELAY destination — platform-side STT and TTS, text over the socket.
513
- *
514
- * The opposite trade to {@link dialStream}: Sinch owns the audio pipeline and the
515
- * application never sees a sample. That also means the application never owns the TTS
516
- * stream, which is why `@sinch/agents` uses STREAM rather than this.
517
- *
518
- * @param endpoint - WebSocket URL that accepts the relay connection. Required by the schema.
519
- * @param options - Platform voice, transcription language, barge-in and headers
753
+ * An agent that is not a SIP provider — a `realtimeAgent` handle — that `dialAgent` can put
754
+ * on a call.
520
755
  */
521
- export declare function dialRelay(endpoint: string, options?: {
522
- ttsVoice?: string;
523
- sttLanguage?: string;
524
- enableInterruptions?: boolean;
756
+ export interface DialableAgent {
757
+ /**
758
+ * Build this call's agent-leg destination. Called once per dial, when the flow is built.
759
+ *
760
+ * @param call - The webhook the handler's builder is answering
761
+ * @param context - The context the voice client was created with, when it had one
762
+ */
763
+ endpointFor(call: WebhookRequest, context: ClientContext | undefined): To;
764
+ }
765
+ /** SIP settings for an agent leg; each defaults to what the provider requires. */
766
+ export interface SipAgentOptions {
767
+ /** Extra SIP headers, merged over the per-call ones (these win on conflict). */
525
768
  headers?: Headers$1;
526
- }): VoiceRelayEndpoint;
769
+ /** SIP transport. Defaults to what the provider requires — TLS for Grok, TCP for ElevenLabs. */
770
+ transport?: "UDP" | "TCP" | "TLS";
771
+ /** SIP host. Defaults to the provider's fixed endpoint — override only for a sandbox or proxy. */
772
+ host?: string;
773
+ /** SIP port. Defaults to the provider's fixed endpoint. */
774
+ port?: number;
775
+ }
776
+ interface FlowScope {
777
+ /** The webhook being answered. Absent when only an explicit `liveLeg` is known. */
778
+ readonly event?: WebhookRequest;
779
+ /** The client's context, handed on to an agent that `dialAgent` builds a leg for */
780
+ readonly context?: ClientContext;
781
+ /** Name the live leg has, or gets from this response */
782
+ readonly liveLeg: string;
783
+ /**
784
+ * `call.incoming` only: this response may name the live leg, and the call-level `onHangup`
785
+ * it carries is the only place a dialled leg's teardown can live. The API ignores both on
786
+ * every other webhook response.
787
+ */
788
+ readonly namesLiveLeg: boolean;
789
+ /** Bridge the live leg is already on — set inside a dial's never-connected outcomes */
790
+ readonly joined?: string;
791
+ /** Legs dialled under this scope that the call-level `onHangup` must end. Shared by copies. */
792
+ readonly dialled: Set<string>;
793
+ /**
794
+ * Every leg name used anywhere in this response's command tree so far, including a dial's
795
+ * own leg before its nested outcome flows (`onBusy`, `onNoAnswer`, ...) are resolved — that
796
+ * is what lets a fallback dial nested inside one of them see the outer leg's name and step
797
+ * past it. Shared by copies, unlike {@link dialled} this is never gated on {@link namesLiveLeg}:
798
+ * a repeat default has to be caught in a `call.answered` or `call.menu` response too, even
799
+ * though neither carries a call-level `onHangup`.
800
+ */
801
+ readonly usedNames: Set<string>;
802
+ }
527
803
  /** Options for a single TTS message */
528
804
  export interface SayOptions {
529
805
  /** Voice name. Defaults to {@link DEFAULT_VOICE}. */
@@ -582,6 +858,79 @@ export interface DialOptions extends DialEvents {
582
858
  */
583
859
  endOnFailure?: string;
584
860
  }
861
+ /** The bridge every call this package builds joins unless told otherwise. */
862
+ export declare const DEFAULT_BRIDGE_NAME = "bridge";
863
+ /**
864
+ * Options for {@link CommandBuilder.bridgeTo} and the `dial*` verbs built on it.
865
+ *
866
+ * On a handler's builder none of these is needed: the leg names, the bridge, `from` and the
867
+ * teardown all come from the call being answered.
868
+ */
869
+ export interface BridgeToOptions {
870
+ /**
871
+ * Caller identity presented to the callee. Defaults by destination: a phone number sees the
872
+ * Sinch number the call is on, so the far party never sees the caller's; a SIP endpoint or
873
+ * agent sees the caller's own E.164 number, because for them it is identity. Streams carry none.
874
+ */
875
+ from?: Origin;
876
+ /** Seconds to wait for an answer. Maximum 60. */
877
+ timeout?: number;
878
+ /** Maximum call duration in seconds. Maximum 14400. */
879
+ maxDuration?: number;
880
+ /**
881
+ * Name for the dialled leg. Defaults by destination: `destination`, `stream` or `relay`. A
882
+ * second dial with no `legName` that lands on the same default within one call flow — a
883
+ * nested fallback in `onBusy`/`onTimeout`, or a sibling `dial*` call — gets `-2`, `-3`, and
884
+ * so on instead of colliding.
885
+ *
886
+ * Voice v2 requires `callName` to stay unique over the call's *whole lifetime*, not just
887
+ * within the commands built here — dialling again on a call that already has a leg by this
888
+ * default name, such as from a later `PATCH`, needs an explicit `legName` to avoid a 500
889
+ * with the leg stuck `QUEUED`.
890
+ */
891
+ legName?: string;
892
+ /** Bridge both legs join. Defaults to `bridge`; name another for a hold room or a whisper. */
893
+ bridgeName?: string;
894
+ /**
895
+ * Name the live leg already has. Only for a flow no handler's builder answers — a batch body,
896
+ * a `PATCH` — since a handler's builder knows it. When set, the flow never names the live leg.
897
+ */
898
+ liveLeg?: string;
899
+ /**
900
+ * Runs when the leg never connects: busy, rejected, timed out or failed. Naming any one outcome
901
+ * detaches the service webhook from all six, so this names all four at once. Defaults to ending
902
+ * the live leg.
903
+ */
904
+ onNoAnswer?: Flow;
905
+ /** Runs when the callee is busy. Overrides `onNoAnswer` for this outcome. */
906
+ onBusy?: Flow;
907
+ /** Runs when the callee rejects. Overrides `onNoAnswer` for this outcome. */
908
+ onReject?: Flow;
909
+ /** Runs when nobody answers within `timeout`. Overrides `onNoAnswer` for this outcome. */
910
+ onTimeout?: Flow;
911
+ /** Runs when the leg could not be set up. Overrides `onNoAnswer` for this outcome. */
912
+ onFailure?: Flow;
913
+ }
914
+ /** SIP settings {@link CommandBuilder.dialSip} passes to `dial.sip` */
915
+ export interface DialSipOptions extends BridgeToOptions {
916
+ transport?: "UDP" | "TCP" | "TLS";
917
+ headers?: Headers$1;
918
+ }
919
+ /** Stream settings {@link CommandBuilder.dialStream} passes to `dial.stream` */
920
+ export interface DialStreamOptions extends BridgeToOptions {
921
+ sampleRate?: SampleRate;
922
+ headers?: Headers$1;
923
+ }
924
+ /** Relay settings {@link CommandBuilder.dialRelay} passes to `dial.relay` */
925
+ export interface DialRelayOptions extends BridgeToOptions {
926
+ ttsVoice?: string;
927
+ sttLanguage?: string;
928
+ enableInterruptions?: boolean;
929
+ headers?: Headers$1;
930
+ }
931
+ /** SIP settings and a leg cap for {@link CommandBuilder.dialAgent} with a SIP provider */
932
+ export interface DialAgentOptions extends BridgeToOptions, SipAgentOptions {
933
+ }
585
934
  /**
586
935
  * The four answering-machine-detection outcomes.
587
936
  *
@@ -729,9 +1078,12 @@ export declare class PromptBuilder {
729
1078
  * with the collected input, arriving as `call.menu`.
730
1079
  */
731
1080
  export declare class MenuItemBuilder {
1081
+ private readonly scope?;
732
1082
  private readonly item;
733
1083
  private readonly matchOrder;
734
1084
  private readonly matches;
1085
+ /** @param scope - The call the enclosing builder answers, handed to every option's flow */
1086
+ constructor(scope?: FlowScope | undefined);
735
1087
  /**
736
1088
  * Prompt played when the menu is entered.
737
1089
  *
@@ -798,6 +1150,18 @@ export declare class MenuItemBuilder {
798
1150
  * @throws If `pattern` does not compile as a regular expression
799
1151
  */
800
1152
  match(pattern: string, flow: Flow): this;
1153
+ /**
1154
+ * What one keypress sequence does — "press 1 for sales".
1155
+ *
1156
+ * `option` takes the tones literally and escapes `*` and `#` for you; {@link match} takes a
1157
+ * regular expression. Both feed the same ordered `matches` list, first match wins.
1158
+ *
1159
+ * @param digits - DTMF tones only: `0`-`9`, `*` and `#`
1160
+ * @param flow - Commands to run when the caller enters exactly these tones
1161
+ * @throws If `digits` contains anything but DTMF tones
1162
+ */
1163
+ option(digits: string, flow: Flow): this;
1164
+ private addMatch;
801
1165
  /**
802
1166
  * Commands to run once the caller is out of attempts.
803
1167
  *
@@ -807,13 +1171,62 @@ export declare class MenuItemBuilder {
807
1171
  /** Emit the menu. */
808
1172
  build(): MenuItem;
809
1173
  }
1174
+ /**
1175
+ * A menu written as one object — the settings {@link MenuItemBuilder} exposes, with `options`
1176
+ * standing in for a run of `option()` calls. No regular expressions here: a `match()` needs the
1177
+ * callback form.
1178
+ */
1179
+ export interface MenuDefinition {
1180
+ /** Prompt played when the menu is entered */
1181
+ prompt?: PromptFlow;
1182
+ /** Prompt played on each retry */
1183
+ repeatPrompt?: PromptFlow;
1184
+ /** Seconds of silence that count as no input */
1185
+ inputTimeout?: number;
1186
+ /** How many times the prompt repeats before `onFail` runs */
1187
+ repeatCount?: number;
1188
+ /** Fewest input characters collected before evaluating */
1189
+ minLength?: number;
1190
+ /** Input length that triggers evaluation */
1191
+ maxLength?: number;
1192
+ /** Sequence that ends input early, e.g. `#` */
1193
+ terminatedBy?: string;
1194
+ /**
1195
+ * What each keypress does, keyed by DTMF tones and escaped exactly as `option()` escapes them.
1196
+ * A plain object is safe here although JavaScript moves integer-like keys first: each key is
1197
+ * an anchored literal, so no two can match the same input and their order changes nothing.
1198
+ */
1199
+ options?: Record<string, Flow>;
1200
+ /** Commands to run once the caller is out of attempts */
1201
+ onFail?: Flow;
1202
+ }
1203
+ /** Start a flow that speaks. See {@link CommandBuilder.say}. */
1204
+ export declare function say(text: string, options?: SayOptions): CommandBuilder;
1205
+ /** Start a flow that plays audio. See {@link CommandBuilder.play}. */
1206
+ export declare function play(url: string): CommandBuilder;
1207
+ /** Start a flow with a menu. See {@link CommandBuilder.menu}. */
1208
+ export declare function menu(name: string, define: MenuDefinition | ((menu: MenuItemBuilder) => MenuItemBuilder | void)): CommandBuilder;
1209
+ /** Start a flow that bridges the caller to a destination. See {@link CommandBuilder.bridgeTo}. */
1210
+ export declare function bridgeTo(destination: Destination, options?: BridgeToOptions): CommandBuilder;
1211
+ /** Start a flow that connects the caller to a phone number. See {@link CommandBuilder.dialPhone}. */
1212
+ export declare function dialPhone(number: string, options?: BridgeToOptions): CommandBuilder;
1213
+ /** Start a flow that connects the caller to a SIP endpoint. See {@link CommandBuilder.dialSip}. */
1214
+ export declare function dialSip(address: string, options?: DialSipOptions): CommandBuilder;
1215
+ /** Start a flow that connects the caller to a media stream. See {@link CommandBuilder.dialStream}. */
1216
+ export declare function dialStream(endpoint: string, options?: DialStreamOptions): CommandBuilder;
1217
+ /** Start a flow that connects the caller to Voice Relay. See {@link CommandBuilder.dialRelay}. */
1218
+ export declare function dialRelay(endpoint: string, options?: DialRelayOptions): CommandBuilder;
1219
+ export declare function dialRelay(relay: DialableAgent, options?: BridgeToOptions): CommandBuilder;
1220
+ /** Start a flow that connects the caller to an AI voice agent. See {@link CommandBuilder.dialAgent}. */
1221
+ export declare function dialAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: DialAgentOptions): CommandBuilder;
1222
+ export declare function dialAgent(agent: DialableAgent, options?: BridgeToOptions): CommandBuilder;
810
1223
  /**
811
1224
  * Emit-target-agnostic description of a call flow.
812
1225
  *
813
- * Build one of these with the client's planning methods, then hand it to
814
- * {@link toCallRequest} or {@link toWebhookResponse}.
1226
+ * Build one of these with a builder or with `client.flows`, then hand it to
1227
+ * {@link toCallBody} or {@link toWebhookBody}.
815
1228
  */
816
- export interface Plan {
1229
+ export interface CallFlow {
817
1230
  /** Ordered command list. Must contain at least one command. */
818
1231
  commands: Command[];
819
1232
  /**
@@ -828,7 +1241,7 @@ export interface Plan {
828
1241
  onHangup?: Command[];
829
1242
  }
830
1243
  /**
831
- * Emit a plan as a `POST /v2/projects/{projectId}/calls` body.
1244
+ * Emit a flow as a `POST /v2/projects/{projectId}/calls` body.
832
1245
  *
833
1246
  * Drops `callName` and `onHangup`: the `callRequest` schema forbids them and the
834
1247
  * API rejects unknown keys with a 400.
@@ -838,13 +1251,13 @@ export interface Plan {
838
1251
  *
839
1252
  * @example
840
1253
  * ```typescript
841
- * const body = toCallRequest({ commands: [{ command: 'hangup' }] });
1254
+ * const body = toCallBody({ commands: [{ command: 'hangup' }] });
842
1255
  * // { commands: [{ command: 'hangup' }] }
843
1256
  * ```
844
1257
  */
845
- export declare function toCallRequest(plan: Plan): CallRequest;
1258
+ export declare function toCallBody(plan: CallFlow): CallRequest;
846
1259
  /**
847
- * Emit a plan as a webhook-response body.
1260
+ * Emit a flow as a webhook-response body.
848
1261
  *
849
1262
  * The response is an object wrapping a `commands` array, not a bare array.
850
1263
  *
@@ -853,7 +1266,7 @@ export declare function toCallRequest(plan: Plan): CallRequest;
853
1266
  *
854
1267
  * @example
855
1268
  * ```typescript
856
- * const body = toWebhookResponse({
1269
+ * const body = toWebhookBody({
857
1270
  * commands: [{ command: 'answer' }],
858
1271
  * callName: 'incoming',
859
1272
  * onHangup: [{ command: 'hangup' }],
@@ -861,16 +1274,65 @@ export declare function toCallRequest(plan: Plan): CallRequest;
861
1274
  * // { commands: [...], callName: 'incoming', events: { onHangup: [...] } }
862
1275
  * ```
863
1276
  */
864
- export declare function toWebhookResponse(plan: Plan): WebhookResponse;
1277
+ export declare function toWebhookBody(plan: CallFlow): WebhookBody;
1278
+ /** The menu that fired and what the caller entered */
1279
+ export interface MenuInput {
1280
+ /** Name of the menu that fired */
1281
+ menuName: string;
1282
+ /** The input sequence collected from the caller */
1283
+ input: string;
1284
+ }
1285
+ interface DeprecatedCallField {
1286
+ /**
1287
+ * @deprecated The call is already flattened onto this object — read the field directly (e.g.
1288
+ * `call.callId`, not `call.call.callId`). This getter returns the object itself, kept only so
1289
+ * code written before the flatten still compiles and runs; it is not present on the wire —
1290
+ * non-enumerable, so it's absent from `JSON.stringify`, `toWebhookRequest`, and any other
1291
+ * spread of this object.
1292
+ */
1293
+ readonly call: Call;
1294
+ }
1295
+ type Flattened<T> = Call & DeprecatedCallField & T;
1296
+ /** Any event, flattened — what `fallback` receives */
1297
+ export type CallEvent = Flattened<{
1298
+ /** Event that triggered this webhook */
1299
+ event: EventType;
1300
+ /** Present for `call.menu`, and for a `webhook` command run inside a menu */
1301
+ menu?: MenuInput;
1302
+ }>;
1303
+ /** `call.incoming` — an inbound call arrived */
1304
+ export type IncomingCall = Flattened<{
1305
+ event: "call.incoming";
1306
+ }>;
1307
+ /** `call.answered` — an outbound call was answered */
1308
+ export type AnsweredCall = Flattened<{
1309
+ event: "call.answered";
1310
+ }>;
1311
+ /** `call.webhook.<name>` — a `webhook` command asked what to do next */
1312
+ export type WebhookCall = Flattened<{
1313
+ event: `call.webhook.${string}`;
1314
+ menu?: MenuInput;
1315
+ }>;
1316
+ /** `call.menu` with what the caller entered, or a `webhook` command's event */
1317
+ export type MenuCall = Flattened<{
1318
+ event: "call.menu";
1319
+ menu: MenuInput;
1320
+ }> | WebhookCall;
1321
+ /** `call.hangup` or `call.failed` — the call ended */
1322
+ export type CompletedCall = Flattened<{
1323
+ event: "call.hangup" | "call.failed";
1324
+ }>;
865
1325
  /**
866
- * The bridge every call this package builds joins unless told otherwise.
1326
+ * Flatten a webhook body into what a handler receives.
867
1327
  *
868
- * Lives here rather than in `client.ts` because both the transfer builder and the client
869
- * need it, and the client is the one that imports — the other direction would be a cycle.
1328
+ * @param request - The webhook body as the platform sent it
870
1329
  */
871
- export declare const DEFAULT_BRIDGE_NAME = "bridge";
872
- /** Name given to the leg a transfer dials, when the caller does not name it. */
873
- export declare const DEFAULT_TRANSFER_LEG = "transfer";
1330
+ export declare function toCallEvent(request: WebhookRequest): CallEvent;
1331
+ /**
1332
+ * The webhook body again, from whichever of the two shapes a caller has — the options that take
1333
+ * "the call" (`connectAgent`, `transferTo*`) accept a handler's flattened call or a raw body.
1334
+ */
1335
+ export declare function toWebhookRequest(call: CallEvent | WebhookRequest): WebhookRequest;
874
1336
  /** Options for {@link buildTransferCommands} and {@link Client.transfer}. */
875
1337
  export interface TransferOptions {
876
1338
  /**
@@ -893,10 +1355,14 @@ export interface TransferOptions {
893
1355
  /** Seconds to wait for an answer. Defaults to 30; the platform maximum is 60. */
894
1356
  timeout?: number;
895
1357
  /**
896
- * Name for the new leg. Defaults to {@link DEFAULT_TRANSFER_LEG}.
1358
+ * Name for the new leg. Left unnamed by default — the platform accepts a `dial` with no
1359
+ * `callName` — since a fixed default would collide with itself on a second transfer of the
1360
+ * same call (Voice v2 requires `callName` to be unique for the session's whole lifetime,
1361
+ * ended legs included) and this package will not invent a random suffix for something
1362
+ * author-facing and potentially read off a later webhook.
897
1363
  *
898
- * Must be unique among the session's live legs. Name it when something downstream reads
899
- * leg names off the webhook payload and has to tell this leg apart from the rest.
1364
+ * Pass one when something downstream needs to address this leg by name afterwards — a later
1365
+ * `PATCH`, a `hangup`, or reading leg names off the webhook payload.
900
1366
  */
901
1367
  callName?: string;
902
1368
  /**
@@ -943,6 +1409,36 @@ export interface TransferOptions {
943
1409
  * ```
944
1410
  */
945
1411
  export declare function buildTransferCommands(to: Destination, options?: TransferOptions): Command[];
1412
+ /** Options for the client's `transferTo*` methods. */
1413
+ export interface TransferToOptions {
1414
+ /** Bridge the leg is moved into. Defaults to `transferBridge`. */
1415
+ bridgeName?: string;
1416
+ /**
1417
+ * Name of the leg being moved — the one ended if the transfer fails or the new party hangs
1418
+ * up. Defaults to the `callName` of a `{ sessionId, callName }` target, else `origin` when
1419
+ * `call` says the call is outbound, else `caller`: the names a handler's builder and
1420
+ * `flows.call` give the live leg.
1421
+ */
1422
+ liveLeg?: string;
1423
+ /**
1424
+ * Name for the dialled leg. Left unnamed by default, for the same reason as
1425
+ * {@link TransferOptions.callName}: no fixed default is safe against a second transfer on
1426
+ * the same call, and this package does not invent a random one. Pass it when something
1427
+ * downstream needs to address this leg afterwards.
1428
+ */
1429
+ legName?: string;
1430
+ /** Seconds to wait for an answer. Defaults to 30. */
1431
+ timeout?: number;
1432
+ /** Maximum duration of the new leg, in seconds */
1433
+ maxDuration?: number;
1434
+ /** Caller identity presented to the destination. Defaults from `call`, as `dial*` does. */
1435
+ from?: Origin;
1436
+ /**
1437
+ * The call's latest webhook, when the caller has it. Gives `from` and `liveLeg` the same
1438
+ * defaults as the builder's `dial*` helpers, and is required to transfer to a realtime agent.
1439
+ */
1440
+ call?: CallEvent | WebhookRequest;
1441
+ }
946
1442
  /** Construction options for {@link Client} */
947
1443
  export interface Options {
948
1444
  /** Sinch project id. Defaults to `PROJECT_ID`, then `context.config.projectId`. */
@@ -1015,8 +1511,30 @@ export interface BridgeOptions extends CallOptions {
1015
1511
  /** Bridge name joining the two legs. Defaults to `bridge`. */
1016
1512
  bridgeName?: string;
1017
1513
  }
1018
- /** A single webhook handler */
1019
- export type WebhookHandler = (event: WebhookRequest) => HandlerResult | Promise<HandlerResult>;
1514
+ /** {@link Client.flows}: each call-placing method's flow, built without sending it. */
1515
+ export interface ClientFlows {
1516
+ /** The {@link Client.call} flow */
1517
+ call(to: Destination, options?: PlaceCallOptions): CallFlow;
1518
+ /** The {@link Client.callWithStream} flow. @throws If the stream path cannot be resolved */
1519
+ streamCall(to: Destination, stream: string, options?: StreamCallOptions): CallFlow;
1520
+ /** The {@link Client.callWithRelay} flow */
1521
+ relayCall(to: Destination, relay: string, options?: RelayCallOptions): CallFlow;
1522
+ /** The {@link Client.bridge} flow */
1523
+ bridge(a: Destination, b: Destination, options?: BridgeOptions): CallFlow;
1524
+ /** The {@link Client.hangup} command list. Ends the addressed leg when no leg is named. */
1525
+ hangup(...callNames: string[]): Command[];
1526
+ }
1527
+ /**
1528
+ * A single webhook handler.
1529
+ *
1530
+ * @param call - The call, flattened, with the `event` that fired (and `menu`, for a menu)
1531
+ * beside its fields — `call.from`, `call.event`. Typed per handler slot; see {@link CallHandlers}.
1532
+ * @param builder - A command builder already primed with this call, one per request. Return
1533
+ * it (`.build()` is optional); its `dial*` helpers default `from`, the leg names and the
1534
+ * teardown from the call it answers.
1535
+ * @param request - The webhook body as the platform sent it. Omitted in every normal handler.
1536
+ */
1537
+ export type WebhookHandler<C extends CallEvent = CallEvent> = (call: C, builder: CommandBuilder, request?: WebhookRequest) => HandlerResult | Promise<HandlerResult>;
1020
1538
  /**
1021
1539
  * A lifecycle handler slot — every key of {@link CallHandlers} except `webhooks`, which is a
1022
1540
  * map of handlers rather than one.
@@ -1086,27 +1604,17 @@ export declare const REDACTED = "[redacted]";
1086
1604
  export declare function redactCredentials<T>(body: T): T;
1087
1605
  /** `JSON.stringify`, but honouring any {@link tagOrder} tag found on nested objects. */
1088
1606
  declare function stringify(value: unknown): string;
1089
- /** SIP-based agent providers {@link connectAgent} can bridge to. */
1090
- export type SipAgentProvider = "elevenlabs" | "grok";
1091
1607
  /** Options for {@link connectAgent}. */
1092
- export interface ConnectAgentOptions {
1608
+ export interface ConnectAgentOptions extends SipAgentOptions {
1093
1609
  /**
1094
1610
  * The `call.incoming` event, when available. Used to default `from` to the caller's E.164
1095
1611
  * number and to add the `X-Sinch-Call-Id` / `X-Caller-Number` / `X-Dialed-Number` SIP
1096
1612
  * headers the grok-voice template sends — how per-call context reaches the agent without an
1097
1613
  * API round trip. Omit it and none of that context rides along.
1098
1614
  */
1099
- call?: WebhookRequest;
1100
- /** Extra SIP headers, merged with the ones derived from `call` (these win on conflict). */
1101
- headers?: Headers$1;
1615
+ call?: CallEvent | WebhookRequest;
1102
1616
  /** Hard cap on call length, in seconds. Both providers bill per minute of audio. Default 1800. */
1103
1617
  maxDuration?: number;
1104
- /** SIP transport. Defaults to what the provider requires — TLS for Grok, TCP for ElevenLabs. */
1105
- transport?: "UDP" | "TCP" | "TLS";
1106
- /** SIP host. Defaults to the provider's fixed endpoint — override only for a sandbox or proxy. */
1107
- host?: string;
1108
- /** SIP port. Defaults to the provider's fixed endpoint. */
1109
- port?: number;
1110
1618
  /** Bridge both legs join. Defaults to {@link DEFAULT_BRIDGE_NAME}. */
1111
1619
  bridgeName?: string;
1112
1620
  /** Name for the inbound leg. Defaults to `'caller'`. */
@@ -1131,10 +1639,11 @@ export interface ConnectAgentOptions {
1131
1639
  * @throws If `provider` is not a SIP-based provider this helper supports, if `number` is not
1132
1640
  * E.164, or if `options.host` contains a character a SIP host cannot
1133
1641
  *
1134
- * Return the {@link Plan} directly from `incoming` — `callName` and `onHangup` are only
1642
+ * Return the {@link CallFlow} directly from `incoming` — `callName` and `onHangup` are only
1135
1643
  * honoured on a response to `call.incoming`. Handing `.commands` on to something else and
1136
1644
  * dropping the rest of the plan silently loses the agent-leg teardown, and the SIP leg bills
1137
- * until `maxDuration`.
1645
+ * until `maxDuration`. For the same reason it cannot be a menu option or answer `call.menu`:
1646
+ * use the handler builder's `dialAgent`, which knows which webhook it answers.
1138
1647
  *
1139
1648
  * @example
1140
1649
  * ```typescript
@@ -1143,7 +1652,415 @@ export interface ConnectAgentOptions {
1143
1652
  * });
1144
1653
  * ```
1145
1654
  */
1146
- export declare function connectAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: ConnectAgentOptions): Plan;
1655
+ export declare function connectAgent(provider: SipAgentProvider | (string & Record<never, never>), number: string, options?: ConnectAgentOptions): CallFlow;
1656
+ type VoiceClient = Client & {
1657
+ /** Voice API v1 client, when `VOICE_APPLICATION_KEY` and `VOICE_APPLICATION_SECRET` are set */
1658
+ v1?: VoiceService;
1659
+ };
1660
+ interface FunctionConfigData {
1661
+ /** Project ID */
1662
+ projectId: string;
1663
+ /** Function name */
1664
+ functionName: string;
1665
+ /** Environment (development, production) */
1666
+ environment: "development" | "production";
1667
+ /** Custom environment variables */
1668
+ variables?: Record<string, string>;
1669
+ }
1670
+ type FunctionConfig = FunctionConfigData & ConfigAccessors;
1671
+ interface FunctionContext {
1672
+ /** Configuration including environment variables */
1673
+ config: FunctionConfig;
1674
+ /**
1675
+ * Key-value cache with TTL support.
1676
+ * In-memory during development, persistent and shared in production.
1677
+ * @see {@link IFunctionCache} for available methods
1678
+ */
1679
+ cache: IFunctionCache;
1680
+ /** Request ID for tracing */
1681
+ requestId?: string;
1682
+ /** Timestamp of the request */
1683
+ timestamp?: string;
1684
+ /** Hostname from the incoming HTTP request (e.g. `my-fn.fn-dev.sinch.com`). Present in production; absent in local dev. */
1685
+ host?: string;
1686
+ /** Environment variables */
1687
+ env?: Record<string, string | undefined>;
1688
+ /**
1689
+ * Voice API v2 client — place calls, bridge legs, attach media streams, dispatch webhooks.
1690
+ * Always present; the credentials are only checked when a request is actually sent.
1691
+ * The v1 SDK client is on `context.voice.v1`.
1692
+ * @see {@link VoiceClient}
1693
+ */
1694
+ voice: VoiceClient;
1695
+ /**
1696
+ * Sinch Conversation SDK client.
1697
+ * Available when `CONVERSATION_APP_ID` is set.
1698
+ */
1699
+ conversation?: ConversationService;
1700
+ /**
1701
+ * Sinch SMS SDK client.
1702
+ * Available when `SMS_SERVICE_PLAN_ID` is set.
1703
+ */
1704
+ sms?: SmsService;
1705
+ /**
1706
+ * Sinch Numbers SDK client.
1707
+ * Available when `ENABLE_NUMBERS_API=true` is set.
1708
+ */
1709
+ numbers?: NumbersService;
1710
+ /**
1711
+ * Persistent file/blob storage.
1712
+ * Local filesystem during development, S3-backed in production.
1713
+ * @see {@link IFunctionStorage} for available methods
1714
+ */
1715
+ storage: IFunctionStorage;
1716
+ /**
1717
+ * File path to a SQLite database for persistent structured data.
1718
+ * The database file is managed by a Litestream sidecar in production
1719
+ * (continuous WAL replication to S3). In development, it's a local file.
1720
+ *
1721
+ * Use any SQLite library — `sql.js` (pure WASM, no native deps) or
1722
+ * `better-sqlite3` (native C++, fastest but requires build tooling).
1723
+ *
1724
+ * @example
1725
+ * ```typescript
1726
+ * // sql.js (recommended — works everywhere)
1727
+ * import initSqlJs from 'sql.js';
1728
+ * const SQL = await initSqlJs();
1729
+ * const buf = existsSync(context.database) ? readFileSync(context.database) : undefined;
1730
+ * const db = new SQL.Database(buf);
1731
+ * db.run('CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT)');
1732
+ * writeFileSync(context.database, Buffer.from(db.export()));
1733
+ *
1734
+ * // better-sqlite3 (fastest — needs python3/make/g++)
1735
+ * import Database from 'better-sqlite3';
1736
+ * const db = new Database(context.database);
1737
+ * db.exec('CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT)');
1738
+ * ```
1739
+ */
1740
+ database: string;
1741
+ /** Read a file from the assets/ directory (private, not served over HTTP) */
1742
+ assets(filename: string): Promise<string>;
1743
+ }
1744
+ type WebSocketHandler = (ws: import("ws").WebSocket, req: import("http").IncomingMessage) => void;
1745
+ interface SinchRuntime {
1746
+ /** Register a callback to run once at startup, before the server accepts requests. */
1747
+ onStartup(handler: (context: FunctionContext) => Promise<void> | void): void;
1748
+ /** Register a WebSocket upgrade handler at the given path. */
1749
+ onWebSocket(path: string, handler: WebSocketHandler): void;
1750
+ }
1751
+ interface ApplicationCredentials {
1752
+ applicationKey: string;
1753
+ applicationSecret: string;
1754
+ }
1755
+ interface ConfigSummary {
1756
+ environment: "production" | "development";
1757
+ variables: Record<string, string | undefined>;
1758
+ secrets: Record<string, string>;
1759
+ hasApplicationCredentials: boolean;
1760
+ }
1761
+ declare class UniversalConfig {
1762
+ private context;
1763
+ private env;
1764
+ /**
1765
+ * Create a new UniversalConfig instance
1766
+ *
1767
+ * @param context - Function execution context
1768
+ */
1769
+ constructor(context: FunctionContext);
1770
+ /**
1771
+ * Get a secret value (e.g., API keys, passwords, tokens)
1772
+ *
1773
+ * @param name - Secret name (e.g., 'PROJECT_ID_API_SECRET')
1774
+ * @param defaultValue - Optional default value if secret not found
1775
+ */
1776
+ getSecret(name: string): string | null;
1777
+ getSecret(name: string, defaultValue: string): string;
1778
+ getSecret(name: string, defaultValue: string | null): string | null;
1779
+ /**
1780
+ * Get an environment variable (non-secret configuration)
1781
+ *
1782
+ * @param name - Variable name (e.g., 'COMPANY_NAME', 'API_URL')
1783
+ * @param defaultValue - Optional default value
1784
+ */
1785
+ getVariable(name: string): string | null;
1786
+ getVariable(name: string, defaultValue: string): string;
1787
+ getVariable(name: string, defaultValue: string | null): string | null;
1788
+ /**
1789
+ * Check if a secret exists (has a value)
1790
+ *
1791
+ * @param name - Secret name
1792
+ */
1793
+ hasSecret(name: string): boolean;
1794
+ /**
1795
+ * Check if a variable exists (has a value)
1796
+ *
1797
+ * @param name - Variable name
1798
+ */
1799
+ hasVariable(name: string): boolean;
1800
+ /**
1801
+ * Get required secret (throws error if not found)
1802
+ *
1803
+ * @param name - Secret name
1804
+ * @throws Error if secret is not found
1805
+ */
1806
+ requireSecret(name: string): string;
1807
+ /**
1808
+ * Get required variable (throws error if not found)
1809
+ *
1810
+ * @param name - Variable name
1811
+ * @throws Error if variable is not found
1812
+ */
1813
+ requireVariable(name: string): string;
1814
+ /**
1815
+ * Get Sinch application credentials
1816
+ */
1817
+ getApplicationCredentials(): ApplicationCredentials | null;
1818
+ /**
1819
+ * Check if running in development mode
1820
+ */
1821
+ isDevelopment(): boolean;
1822
+ /**
1823
+ * Check if running in production mode
1824
+ */
1825
+ isProduction(): boolean;
1826
+ /**
1827
+ * Get cache client instance
1828
+ */
1829
+ getCache(): IFunctionCache | undefined;
1830
+ /**
1831
+ * Get comprehensive configuration summary (useful for debugging)
1832
+ * Excludes actual secret values for security
1833
+ */
1834
+ getConfigSummary(): ConfigSummary;
1835
+ }
1836
+ declare const CONFIG_ACCESSORS: readonly [
1837
+ "getSecret",
1838
+ "getVariable",
1839
+ "hasSecret",
1840
+ "hasVariable",
1841
+ "requireSecret",
1842
+ "requireVariable",
1843
+ "getApplicationCredentials",
1844
+ "isDevelopment",
1845
+ "isProduction",
1846
+ "getCache",
1847
+ "getConfigSummary"
1848
+ ];
1849
+ type ConfigAccessors = Pick<UniversalConfig, (typeof CONFIG_ACCESSORS)[number]>;
1850
+ type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
1851
+ interface FunctionRequest {
1852
+ /** HTTP method */
1853
+ method: HttpMethod;
1854
+ /** Request path */
1855
+ path: string;
1856
+ /** Query parameters */
1857
+ query?: Record<string, string | string[]>;
1858
+ /** Request headers (lowercase keys) */
1859
+ headers?: Record<string, string>;
1860
+ /** Request body (parsed JSON) */
1861
+ body?: unknown;
1862
+ /** Route parameters (e.g., /users/:id) */
1863
+ params?: Record<string, string>;
1864
+ }
1865
+ interface FunctionResponse {
1866
+ /** HTTP status code (default: 200) */
1867
+ statusCode: number;
1868
+ /** Response headers */
1869
+ headers?: Record<string, string>;
1870
+ /** Response body (will be JSON serialized) */
1871
+ body?: unknown;
1872
+ }
1873
+ type IceCallback = Omit<Voice.IceRequest, "callid" | "event"> & {
1874
+ callId?: string;
1875
+ event: "ice";
1876
+ };
1877
+ type AceCallback = Omit<Voice.AceRequest, "callid" | "event"> & {
1878
+ callId?: string;
1879
+ event: "ace";
1880
+ };
1881
+ type PieCallback = Omit<Voice.PieRequest, "callid" | "event"> & {
1882
+ callId?: string;
1883
+ event: "pie";
1884
+ };
1885
+ type DiceCallback = Omit<Voice.DiceRequest, "callid" | "event"> & {
1886
+ callId?: string;
1887
+ event: "dice";
1888
+ };
1889
+ type NotifyCallback = Omit<Voice.NotifyRequest, "callid" | "event"> & {
1890
+ callId?: string;
1891
+ event: "notify";
1892
+ };
1893
+ type ApiHandler = (context: FunctionContext, request: FunctionRequest) => Promise<FunctionResponse | unknown>;
1894
+ type IceHandler = (context: FunctionContext, callbackData: IceCallback) => Promise<SvamletResponse>;
1895
+ type AceHandler = (context: FunctionContext, callbackData: AceCallback) => Promise<SvamletResponse>;
1896
+ type PieHandler = (context: FunctionContext, callbackData: PieCallback) => Promise<SvamletResponse>;
1897
+ type DiceHandler = (context: FunctionContext, callbackData: DiceCallback) => Promise<void>;
1898
+ type NotifyHandler = (context: FunctionContext, callbackData: NotifyCallback) => Promise<void>;
1899
+ type VoiceWebhookHandler = (context: FunctionContext, event: WebhookRequest, request?: FunctionRequest) => HandlerResult | Promise<HandlerResult>;
1900
+ interface VoiceFunction {
1901
+ /** Handle ICE (Incoming Call Event) */
1902
+ ice?: IceHandler;
1903
+ /** Handle ACE (Answered Call Event) */
1904
+ ace?: AceHandler;
1905
+ /** Handle PIE (Prompt Input Event) */
1906
+ pie?: PieHandler;
1907
+ /** Handle DICE (Disconnect Call Event) */
1908
+ dice?: DiceHandler;
1909
+ /** Handle notify events */
1910
+ notify?: NotifyHandler;
1911
+ /**
1912
+ * Handle the Voice API v2 call lifecycle — every `call.*` event this function's service
1913
+ * posts, whatever URL it posts to. Build one with `onCall()`.
1914
+ *
1915
+ * The `ApiHandler` arm is the host's other accepted shape: a handler that returns a full
1916
+ * `{ statusCode, body }` response gets it emitted untouched, which is what
1917
+ * `@sinch/agents` returns from its own `voiceWebhook`.
1918
+ */
1919
+ voiceWebhook?: VoiceWebhookHandler | ApiHandler;
1920
+ /** Default handler for GET / */
1921
+ default?: ApiHandler;
1922
+ /** Root route handler — TypeScript-friendly alias for 'default' */
1923
+ home?: ApiHandler;
1924
+ /** Custom API endpoints (any other exported function) */
1925
+ [key: string]: unknown;
1926
+ }
1927
+ type PerCallValue<T> = T | ((call: Call, context: FunctionContext) => T | Promise<T>);
1928
+ type JsonSchema = Record<string, unknown>;
1929
+ interface TranscriptEntry {
1930
+ /** `'tool'` is a completed tool call, not spoken turn. */
1931
+ role: "user" | "agent" | "tool";
1932
+ /** Spoken/written text for `'user'`/`'agent'`; the tool's name for `'tool'`. */
1933
+ text: string;
1934
+ /** ISO 8601 */
1935
+ timestamp: string;
1936
+ /** Present only when `role` is `'tool'`. */
1937
+ tool?: string;
1938
+ args?: unknown;
1939
+ /** The handler's resolved value. Absent when the handler threw. */
1940
+ result?: unknown;
1941
+ /** The handler's thrown value, if it threw. */
1942
+ error?: unknown;
1943
+ /**
1944
+ * Present when `role` is `'tool'` (the handler's own run time), or `'agent'` (time from the
1945
+ * caller's turn finishing to this reply's first spoken sentence — voice-relay's `converse` and
1946
+ * the STREAM path's `onTurn` both set it; see each adapter for what "first" means there).
1947
+ */
1948
+ latencyMs?: number;
1949
+ /**
1950
+ * `'agent'` only: time from the caller's turn finishing to this whole reply completing,
1951
+ * including any tool rounds in between. Absent when the turn was abandoned by a barge-in.
1952
+ */
1953
+ totalMs?: number;
1954
+ /**
1955
+ * `'agent'` only, GPT-Live-specific — see `RealtimeTurn.delegationMs`'s own doc comment for
1956
+ * exactly what this measures and its one-delegation-per-turn simplification. `undefined` for
1957
+ * every other provider.
1958
+ */
1959
+ delegationMs?: number;
1960
+ /**
1961
+ * `'user'` only: ISO timestamps of the caller's speech. Where a provider reports a
1962
+ * speech-boundary event directly, that wins — GPT-Live from `session.input_transcript.delta`'s
1963
+ * own `start_ms`/`end_ms`, Grok from `input_audio_buffer.speech_started`/`speech_stopped`,
1964
+ * Deepgram `speechStartAt` only from `UserStartedSpeaking` (it has no `speechEndAt` event at
1965
+ * all), Gemini `speechStartAt` only from `interimInputTranscription` (no `speechEndAt` signal —
1966
+ * `VoiceActivity`, which Google's own docs say replaces the deprecated `speechState`, has no
1967
+ * published schema anywhere reachable). Every STREAM provider's real gap — Deepgram/Gemini's
1968
+ * missing `speechEndAt`, and any provider's missing `speechStartAt` — is filled by `agent.ts`'s
1969
+ * own energy-VAD fallback (`vad.ts`) on the caller's raw inbound audio, so in practice neither
1970
+ * field is ever actually unset for a STREAM call. voice-relay is the one exception: no VAD runs
1971
+ * there (Sinch does the STT itself, over the relay socket, not raw audio through this runtime),
1972
+ * and no wire field is documented for caller speech boundaries either — both stay unset, never
1973
+ * guessed at.
1974
+ */
1975
+ speechStartAt?: string;
1976
+ speechEndAt?: string;
1977
+ /**
1978
+ * `'agent'` only: ISO timestamps bracketing when this reply's audio actually played to the
1979
+ * caller, from whatever playback/response-audio event the provider reports — voice-relay's
1980
+ * `textPlaybackStart`/`Stop`/`Cancel`, OpenAI/Grok's first response audio delta and
1981
+ * `response.done`, Deepgram's `AgentStartedSpeaking`/`AgentAudioDone`. Gemini not wired (no
1982
+ * playback signal in what its adapter exposes). Left unset — never guessed — when a provider
1983
+ * doesn't report it.
1984
+ */
1985
+ playbackStartAt?: string;
1986
+ playbackEndAt?: string;
1987
+ /** `'agent'` only: set when `playbackEndAt` was a cancellation (barge-in, or a newer reply
1988
+ * superseding this one) rather than the audio finishing on its own. */
1989
+ interrupted?: boolean;
1990
+ }
1991
+ interface RealtimeUsage {
1992
+ inputTokens?: number;
1993
+ outputTokens?: number;
1994
+ /**
1995
+ * GPT-Live: `session.usage.updated`'s `usage.seconds` directly (vendor-reported, replaces).
1996
+ * Deepgram: never vendor-reported (nothing in its stream carries usage) — `agent.ts` falls back
1997
+ * to its own wall-clock call duration instead, so this is never left unset for Deepgram either.
1998
+ */
1999
+ audioSeconds?: number;
2000
+ }
2001
+ interface RealtimeError {
2002
+ message: string;
2003
+ /** A machine-readable error code, when the vendor or transport provides one (e.g. `ECONNRESET`). */
2004
+ code?: string;
2005
+ /**
2006
+ * The vendor's own error payload, if any, for logging. For a connection-level `ws` error this is
2007
+ * always the sanitised `{ message, code? }` from `sanitizeVendorError` — never the raw `Error`
2008
+ * instance, which can carry the connection URL or headers (an API key, for a vendor that puts one
2009
+ * there). A vendor-sent JSON error frame is passed through as-is; that payload is the vendor's own
2010
+ * message body, not connection metadata.
2011
+ */
2012
+ raw?: unknown;
2013
+ }
2014
+ interface RealtimeSessionContext {
2015
+ /** The caller's leg's callId — the one `call.hangup` will report. */
2016
+ callId: string;
2017
+ storage: IFunctionStorage;
2018
+ config: UniversalConfig;
2019
+ /**
2020
+ * Aborted the moment this call's session ends, from whichever side (hangup, Sinch closing the
2021
+ * STREAM leg, a fatal vendor error). A tool `handler` that supports cancellation can watch this
2022
+ * to stop early instead of running a side effect for a call that is already over — see the
2023
+ * Deepgram adapter's `FunctionCallCancelled` handling.
2024
+ */
2025
+ signal: AbortSignal;
2026
+ /**
2027
+ * This call's transcript so far, in order — every entry `onTranscript` has already fired
2028
+ * with. Read from `onEnd` or a tool `handler`; appended to by the relay, never by an author.
2029
+ */
2030
+ readonly transcript: readonly TranscriptEntry[];
2031
+ /**
2032
+ * This call's running usage total, as of whatever the vendor (or, for Deepgram, our own
2033
+ * wall-clock measurement — see `RealtimeUsage.audioSeconds`'s own doc comment) has reported so
2034
+ * far. Read from `onEnd` to save it; the relay itself logs one summary line at call end too.
2035
+ * Tokens and seconds only — no dollar amounts computed or stored anywhere in this runtime.
2036
+ */
2037
+ readonly usage: RealtimeUsage;
2038
+ /**
2039
+ * End the call. Closes the vendor session and the STREAM leg; `endOnFailure` on the caller's
2040
+ * leg (set by `realtimeAgent`'s own call plan) ends the caller's leg in turn.
2041
+ */
2042
+ hangup(): void;
2043
+ /**
2044
+ * Move the caller to a human number. Same move-the-live-leg mechanism as the voice builder's
2045
+ * `transferTo*`/`voiceRelay`'s `call.transferToPhone`: the caller's leg leaves this call's
2046
+ * bridge for a new one with `number`, and if that dial is busy, unanswered, or fails, the
2047
+ * caller's leg is dropped rather than returned here — this is a cold transfer, not a warm
2048
+ * one. This agent's own STREAM leg has nobody left to relay to once the caller moves, so it
2049
+ * ends right after the move, whether or not the destination ever answers.
2050
+ */
2051
+ transfer(number: string): Promise<void>;
2052
+ }
2053
+ type RealtimeAudioProvider = "openai" | "gemini" | "deepgram" | "grok";
2054
+ type RealtimeAgentProvider = RealtimeAudioProvider | "voice-relay";
2055
+ type RealtimeAgentHandle = VoiceFunction & {
2056
+ connect: VoiceCallHandler;
2057
+ } & v2.DialableAgent;
2058
+ type PerCallSetting = string | ((call: v2.Call, context: FunctionContext) => string);
2059
+ type RelayTransferOptions = Omit<v2.TransferToOptions, "call">;
2060
+
2061
+ declare namespace v2 {
2062
+ export { AmdEventOptions, AnsweredCall, BridgeOptions, BridgeToOptions, Call, CallDirection, CallEvent, CallFlow, CallHandlers, CallOptions, CallReason, CallResponse, CallResult, CallType, Client, ClientFlows, Command, CommandBuilder, CompletedCall, ConnectAgentOptions, DEFAULT_BRIDGE_NAME, DEFAULT_HOST, DEFAULT_SAMPLE_RATE, DEFAULT_STT_LANGUAGE, DEFAULT_VOICE, Destination, DialAgentOptions, DialEvents, DialOptions, DialRelayOptions, DialSipOptions, DialStreamOptions, DialableAgent, EventType, Flow, HandlerKey, HandlerResult, Headers$1 as Headers, IncomingCall, MenuCall, MenuDefinition, MenuInput, MenuItemBuilder, Money, Options, Origin, OriginationType, PatchTarget, PlaceCallOptions, PromptBuilder, PromptFlow, REDACTED, RecordingCredentials, RecordingDestination, RecordingFormat, RecordingType, RelayCallOptions, SampleRate, SayOptions, SipAgentOptions, SipAgentProvider, StartRecordingOptions, StopMessagesFlags, StreamCallOptions, TransferOptions, TransferToOptions, WebhookBody, WebhookCall, WebhookHandler, WebhookOptions, WebhookRequest, bridgeTo, buildTransferCommands, commands, connectAgent, createClient, dial, dialAgent, dialPhone, dialRelay, dialSip, dialStream, endpointNumber, menu, play, redactCredentials, resolveHandlerKey, resolveWebhookName, say, stringify as stringifyOrdered, toCallBody, toCallEvent, toWebhookBody, toWebhookRequest };
2063
+ }
1147
2064
 
1148
2065
  export {
1149
2066
  Headers$1 as Headers,